-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathidentity.ts
More file actions
279 lines (251 loc) · 8.45 KB
/
identity.ts
File metadata and controls
279 lines (251 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import {
CallRequest,
Cbor,
HttpAgentRequest,
PublicKey,
ReadRequest,
Signature,
SignIdentity,
} from "@dfinity/agent";
import { Principal } from "@dfinity/principal";
import LedgerApp, { ResponseSign, TokenInfo } from "@zondax/ledger-icp";
import { Secp256k1PublicKey } from "./secp256k1";
// @ts-ignore (no types are available)
import TransportWebHID, { Transport } from "@ledgerhq/hw-transport-webhid";
import TransportNodeHidNoEvents from "@ledgerhq/hw-transport-node-hid-noevents";
// Add polyfill for `window.fetch` for agent-js to work.
// @ts-ignore (no types are available)
import fetch from "node-fetch";
import { isNullish, nonNullish } from "@dfinity/utils";
global.fetch = fetch;
/**
* Convert the HttpAgentRequest body into cbor which can be signed by the Ledger Hardware Wallet.
* @param request - body of the HttpAgentRequest
*/
function _prepareCborForLedger(
request: ReadRequest | CallRequest
): ArrayBuffer {
return Cbor.encode({ content: request });
}
/**
* A Hardware Ledger Internet Computer Agent identity.
*/
export class LedgerIdentity extends SignIdentity {
// A flag to signal that the next transaction to be signed will be
// a "stake neuron" transaction.
private _neuronStakeFlag = false;
/**
* Create a LedgerIdentity using the Web USB transport.
* @param derivePath The derivation path.
*/
public static async create(
derivePath = `m/44'/223'/0'/0/0`
): Promise<LedgerIdentity> {
const [app, transport] = await this._connect();
try {
const publicKey = await this._fetchPublicKeyFromDevice(app, derivePath);
return new this(derivePath, publicKey);
} finally {
// Always close the transport.
transport.close();
}
}
private constructor(
public readonly derivePath: string,
private readonly _publicKey: Secp256k1PublicKey
) {
super();
}
/**
* Connect to a ledger hardware wallet.
*/
private static async _connect(): Promise<[LedgerApp, Transport]> {
async function getTransport() {
if (await TransportWebHID.isSupported()) {
// We're in a web browser.
return TransportWebHID.create();
} else if (await TransportNodeHidNoEvents.isSupported()) {
// Maybe we're in a CLI.
return TransportNodeHidNoEvents.create();
} else {
// Unknown environment.
throw Error();
}
}
try {
const transport = await getTransport();
const app = new LedgerApp(transport);
return [app, transport];
} catch (err) {
// @ts-ignore
if (err.id && err.id == "NoDeviceFound") {
throw "No Ledger device found. Is the wallet connected and unlocked?";
} else if (
// @ts-ignore
err.message &&
// @ts-ignore
err.message.includes("cannot open device with path")
) {
throw "Cannot connect to Ledger device. Please close all other wallet applications (e.g. Ledger Live) and try again.";
} else {
// Unsupported browser. Data on browser compatibility is taken from https://caniuse.com/webhid
throw `Cannot connect to Ledger Wallet. Either you have other wallet applications open (e.g. Ledger Live), or your browser doesn't support WebHID, which is necessary to communicate with your Ledger hardware wallet.\n\nSupported browsers:\n* Chrome (Desktop) v89+\n* Edge v89+\n* Opera v76+\n\nError: ${err}`;
}
}
}
private static async _fetchPublicKeyFromDevice(
app: LedgerApp,
derivePath: string
): Promise<Secp256k1PublicKey> {
const resp = await app.getAddressAndPubKey(derivePath);
// Code references: https://github.com/Zondax/ledger-js/blob/799b056c0ed40af06d375b2b6220c0316f272fe7/src/consts.ts#L31
if (resp.returnCode == 0x6e01) {
throw "Please open the Internet Computer app on your wallet and try again.";
} else if (resp.returnCode == 0x5515) {
throw "Ledger Wallet is locked. Unlock it and try again.";
} else if (resp.returnCode == 0xffff) {
throw "Unable to fetch the public key. Please try again.";
} else if (isNullish(resp.publicKey)) {
throw "Public key not available. Please try again.";
}
// This type doesn't have the right fields in it, so we have to manually type it.
const principal = (resp as unknown as { principalText: string })
.principalText;
const publicKey = Secp256k1PublicKey.fromRaw(
new Uint8Array(resp.publicKey)
);
if (
principal !==
Principal.selfAuthenticating(new Uint8Array(publicKey.toDer())).toText()
) {
throw new Error(
"Principal returned by device does not match public key."
);
}
return publicKey;
}
/**
* Required by Ledger.com that the user should be able to press a Button in UI
* and verify the address/pubkey are the same as on the device screen.
*/
public async showAddressAndPubKeyOnDevice(): Promise<void> {
this._executeWithApp(async (app: LedgerApp) => {
await app.showAddressAndPubKey(this.derivePath);
});
}
/**
* @returns The verion of the `Internet Computer' app installed on the Ledger device.
*/
public async getVersion(): Promise<Version> {
return this._executeWithApp(async (app: LedgerApp) => {
const res = await app.getVersion();
if (
isNullish(res.major) ||
isNullish(res.minor) ||
isNullish(res.patch)
) {
throw new Error(
`A ledger error happened during version fetch:
Code: ${res.returnCode}
Message: ${JSON.stringify(res.errorMessage)}`
);
}
return {
major: res.major,
minor: res.minor,
patch: res.patch,
};
});
}
public async getSupportedTokens(): Promise<TokenInfo[]> {
return this._executeWithApp(async (app: LedgerApp) => {
const res = await app.tokenRegistry();
if (nonNullish(res.tokenRegistry)) {
return res.tokenRegistry;
}
throw new Error(
`A ledger error happened during token registry fetch:
Code: ${res.returnCode}
Message: ${JSON.stringify(res.errorMessage)}`
);
});
}
public getPublicKey(): PublicKey {
return this._publicKey;
}
public async sign(blob: ArrayBuffer): Promise<Signature> {
return await this._executeWithApp(async (app: LedgerApp) => {
const resp: ResponseSign = await app.sign(
this.derivePath,
Buffer.from(blob),
this._neuronStakeFlag ? 1 : 0
);
// Remove the "neuron stake" flag, since we already signed the transaction.
this._neuronStakeFlag = false;
const signatureRS = resp.signatureRS;
if (!signatureRS) {
throw new Error(
`A ledger error happened during signature:\n` +
`Code: ${resp.returnCode}\n` +
`Message: ${JSON.stringify(resp.errorMessage)}\n`
);
}
if (signatureRS?.byteLength !== 64) {
throw new Error(
`Signature must be 64 bytes long (is ${signatureRS.length})`
);
}
return bufferToArrayBuffer(signatureRS) as Signature;
});
}
/**
* Signals that the upcoming transaction to be signed will be a "stake neuron" transaction.
*/
public flagUpcomingStakeNeuron(): void {
this._neuronStakeFlag = true;
}
public async transformRequest(request: HttpAgentRequest): Promise<unknown> {
const { body, ...fields } = request;
const signature = await this.sign(_prepareCborForLedger(body));
return {
...fields,
body: {
content: body,
sender_pubkey: this._publicKey.toDer(),
sender_sig: signature,
},
};
}
private async _executeWithApp<T>(
func: (app: LedgerApp) => Promise<T>
): Promise<T> {
const [app, transport] = await LedgerIdentity._connect();
try {
// Verify that the public key of the device matches the public key of this identity.
const devicePublicKey = await LedgerIdentity._fetchPublicKeyFromDevice(
app,
this.derivePath
);
if (JSON.stringify(devicePublicKey) !== JSON.stringify(this._publicKey)) {
throw new Error(
"Found unexpected public key. Are you sure you're using the right wallet?"
);
}
// Run the provided function.
return await func(app);
} finally {
transport.close();
}
}
}
interface Version {
major: number;
minor: number;
patch: number;
}
function bufferToArrayBuffer(buffer: Buffer): ArrayBuffer {
return buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength
);
}