Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding ability to signMessage with Ledger adapter #712

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chilled-badgers-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@solana/wallet-adapter-ledger': minor
---

Adding ability to signMessage with Ledger adapter
1 change: 1 addition & 0 deletions packages/wallets/ledger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@ledgerhq/hw-transport": "6.27.1",
"@ledgerhq/hw-transport-webhid": "6.27.1",
"@solana/wallet-adapter-base": "workspace:^",
"bip32-path": "^0.4.2",
"buffer": "^6.0.3"
},
"devDependencies": {
Expand Down
24 changes: 21 additions & 3 deletions packages/wallets/ledger/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import {
WalletPublicKeyError,
WalletReadyState,
WalletSignTransactionError,
WalletSignMessageError,
} from '@solana/wallet-adapter-base';
import type { PublicKey, Transaction } from '@solana/web3.js';
import './polyfills/index.js';
import { getDerivationPath, getPublicKey, signTransaction } from './util.js';
import { pathToBuffer, getPublicKey, signTransaction, signMessage } from './util.js';

export interface LedgerWalletAdapterConfig {
derivationPath?: Buffer;
derivationPath?: string;
}

export const LedgerWalletName = 'Ledger' as WalletName<'Ledger'>;
Expand All @@ -29,6 +30,7 @@ export class LedgerWalletAdapter extends BaseSignerWalletAdapter {
icon =
'data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMzUgMzUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGcgZmlsbD0iI2ZmZiI+PHBhdGggZD0ibTIzLjU4OCAwaC0xNnYyMS41ODNoMjEuNnYtMTZhNS41ODUgNS41ODUgMCAwIDAgLTUuNi01LjU4M3oiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDUuNzM5KSIvPjxwYXRoIGQ9Im04LjM0MiAwaC0yLjc1N2E1LjU4NSA1LjU4NSAwIDAgMCAtNS41ODUgNS41ODV2Mi43NTdoOC4zNDJ6Ii8+PHBhdGggZD0ibTAgNy41OWg4LjM0MnY4LjM0MmgtOC4zNDJ6IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwIDUuNzM5KSIvPjxwYXRoIGQ9Im0xNS4xOCAyMy40NTFoMi43NTdhNS41ODUgNS41ODUgMCAwIDAgNS41ODUtNS42di0yLjY3MWgtOC4zNDJ6IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMS40NzggMTEuNDc4KSIvPjxwYXRoIGQ9Im03LjU5IDE1LjE4aDguMzQydjguMzQyaC04LjM0MnoiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDUuNzM5IDExLjQ3OCkiLz48cGF0aCBkPSJtMCAxNS4xOHYyLjc1N2E1LjU4NSA1LjU4NSAwIDAgMCA1LjU4NSA1LjU4NWgyLjc1N3YtOC4zNDJ6IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgwIDExLjQ3OCkiLz48L2c+PC9zdmc+';
readonly supportedTransactionVersions = null;
readonly DEFAULT_DERIVATION_PATH = "44'/501'/0'";

private _derivationPath: Buffer;
private _connecting: boolean;
Expand All @@ -44,7 +46,7 @@ export class LedgerWalletAdapter extends BaseSignerWalletAdapter {

constructor(config: LedgerWalletAdapterConfig = {}) {
super();
this._derivationPath = config.derivationPath || getDerivationPath(0, 0);
this._derivationPath = pathToBuffer(config.derivationPath || this.DEFAULT_DERIVATION_PATH);
this._connecting = false;
this._transport = null;
this._publicKey = null;
Expand Down Expand Up @@ -142,6 +144,22 @@ export class LedgerWalletAdapter extends BaseSignerWalletAdapter {
}
}

async signMessage(message: Uint8Array): Promise<Uint8Array> {
try {
try {
const transport = this._transport;
if (!transport) throw new WalletNotConnectedError();

return new Uint8Array(await signMessage(transport, Buffer.from(message.buffer), this._derivationPath));
} catch (error: any) {
throw new WalletSignMessageError(error?.message, error);
}
} catch (error: any) {
this.emit('error', error);
throw error;
}
}

private _disconnected = () => {
const transport = this._transport;
if (transport) {
Expand Down
2 changes: 1 addition & 1 deletion packages/wallets/ledger/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './adapter.js';
export { getDerivationPath } from './util.js';
export { pathToBuffer } from './util.js';
54 changes: 30 additions & 24 deletions packages/wallets/ledger/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,12 @@ import type { default as Transport } from '@ledgerhq/hw-transport';
import { StatusCodes, TransportStatusError } from '@ledgerhq/hw-transport';
import type { Transaction } from '@solana/web3.js';
import { PublicKey } from '@solana/web3.js';
import BIPPath from 'bip32-path';
import './polyfills/index.js';

export function getDerivationPath(account?: number, change?: number): Buffer {
const length = account !== undefined ? (change === undefined ? 3 : 4) : 2;
const derivationPath = Buffer.alloc(1 + length * 4);

let offset = derivationPath.writeUInt8(length, 0);
offset = derivationPath.writeUInt32BE(harden(44), offset); // Using BIP44
offset = derivationPath.writeUInt32BE(harden(501), offset); // Solana's BIP44 path

if (account !== undefined) {
offset = derivationPath.writeUInt32BE(harden(account), offset);
if (change !== undefined) {
derivationPath.writeUInt32BE(harden(change), offset);
}
}

return derivationPath;
}

const BIP32_HARDENED_BIT = (1 << 31) >>> 0;

function harden(n: number): number {
return (n | BIP32_HARDENED_BIT) >>> 0;
}

const INS_GET_PUBKEY = 0x05;
const INS_SIGN_MESSAGE = 0x06;
const INS_SIGN_MESSAGE_OFFCHAIN = 0x07;

const P1_NON_CONFIRM = 0x00;
const P1_CONFIRM = 0x01;
Expand Down Expand Up @@ -62,6 +40,34 @@ export async function signTransaction(
return await send(transport, INS_SIGN_MESSAGE, P1_CONFIRM, data);
}

/** @internal */
export async function signMessage(transport: Transport, message: Buffer, derivationPath: Buffer): Promise<Buffer> {
const paths = Buffer.alloc(1);
paths.writeUInt8(1, 0);

const data = Buffer.concat([paths, derivationPath, message]);

return await send(transport, INS_SIGN_MESSAGE_OFFCHAIN, P1_CONFIRM, data);
}
Comment on lines +66 to +74
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this looks great. I think we'll need to add some things to the adapter/utils to help apps prepare the right message format to sign, but this is a good start.


export function pathToBuffer(originalPath: string) {
const path = originalPath
.split('/')
.map((value) => (value.endsWith("'") || value.endsWith('h') ? value : `${value}'`))
.join('/');
const pathNums: number[] = BIPPath.fromString(path).toPathArray();
return serializePath(pathNums);
}

function serializePath(path: number[]) {
const buf = Buffer.alloc(1 + path.length * 4);
buf.writeUInt8(path.length, 0);
for (const [i, num] of path.entries()) {
buf.writeUInt32BE(num, 1 + i * 4);
}
return buf;
}

async function send(transport: Transport, instruction: number, p1: number, data: Buffer): Promise<Buffer> {
let p2 = 0;
let offset = 0;
Expand Down
1 change: 1 addition & 0 deletions packages/wallets/ledger/src/utils.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
declare module 'bip32-path';
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.