forked from MetaMask/eth-trezor-keyring
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
524 lines (472 loc) · 15.6 KB
/
index.js
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
const { EventEmitter } = require('events');
const ethUtil = require('@ethereumjs/util');
const HDKey = require('hdkey');
const TrezorConnect = require('@trezor/connect-web').default;
const { TransactionFactory } = require('@ethereumjs/tx');
const { transformTypedData } = require('@trezor/connect-plugin-ethereum');
const hdPathString = `m/44'/60'/0'/0`;
const SLIP0044TestnetPath = `m/44'/1'/0'/0`;
const ALLOWED_HD_PATHS = {
[hdPathString]: true,
[SLIP0044TestnetPath]: true,
};
const keyringType = 'Trezor Hardware';
const pathBase = 'm';
const MAX_INDEX = 1000;
const DELAY_BETWEEN_POPUPS = 1000;
const TREZOR_CONNECT_MANIFEST = {
email: 'support@metamask.io',
appUrl: 'https://metamask.io',
};
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* @typedef {import('@ethereumjs/tx').TypedTransaction} TypedTransaction
* @typedef {InstanceType<import("ethereumjs-tx")>} OldEthJsTransaction
*/
/**
* Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx
*
* Transactions built with older versions of ethereumjs-tx have a
* getChainId method that newer versions do not.
* Older versions are mutable
* while newer versions default to being immutable.
* Expected shape and type
* of data for v, r and s differ (Buffer (old) vs BN (new)).
*
* @param {TypedTransaction | OldEthJsTransaction} tx
* @returns {tx is OldEthJsTransaction} Returns `true` if tx is an old-style ethereumjs-tx transaction.
*/
function isOldStyleEthereumjsTx(tx) {
return typeof tx.getChainId === 'function';
}
class TrezorKeyring extends EventEmitter {
constructor(opts = {}) {
super();
this.type = keyringType;
this.accounts = [];
this.hdk = new HDKey();
this.page = 0;
this.perPage = 5;
this.unlockedAccount = 0;
this.paths = {};
this.deserialize(opts);
this.trezorConnectInitiated = false;
TrezorConnect.on('DEVICE_EVENT', (event) => {
if (event && event.payload && event.payload.features) {
this.model = event.payload.features.model;
}
});
if (!this.trezorConnectInitiated) {
TrezorConnect.init({ manifest: TREZOR_CONNECT_MANIFEST, lazyLoad: true });
this.trezorConnectInitiated = true;
}
}
/**
* Gets the model, if known.
* This may be `undefined` if the model hasn't been loaded yet.
*
* @returns {"T" | "1" | undefined}
*/
getModel() {
return this.model;
}
dispose() {
// This removes the Trezor Connect iframe from the DOM
// This method is not well documented, but the code it calls can be seen
// here: https://github.com/trezor/connect/blob/dec4a56af8a65a6059fb5f63fa3c6690d2c37e00/src/js/iframe/builder.js#L181
TrezorConnect.dispose();
}
serialize() {
return Promise.resolve({
hdPath: this.hdPath,
accounts: this.accounts,
page: this.page,
paths: this.paths,
perPage: this.perPage,
unlockedAccount: this.unlockedAccount,
});
}
deserialize(opts = {}) {
this.hdPath = opts.hdPath || hdPathString;
this.accounts = opts.accounts || [];
this.page = opts.page || 0;
this.perPage = opts.perPage || 5;
return Promise.resolve();
}
isUnlocked() {
return Boolean(this.hdk && this.hdk.publicKey);
}
unlock() {
if (this.isUnlocked()) {
return Promise.resolve('already unlocked');
}
return new Promise((resolve, reject) => {
TrezorConnect.getPublicKey({
path: this.hdPath,
coin: 'ETH',
})
.then((response) => {
if (response.success) {
this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');
this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');
resolve('just unlocked');
} else {
reject(
new Error(
(response.payload && response.payload.error) || 'Unknown error',
),
);
}
})
.catch((e) => {
reject(new Error((e && e.toString()) || 'Unknown error'));
});
});
}
setAccountToUnlock(index) {
this.unlockedAccount = parseInt(index, 10);
}
addAccounts(n = 1) {
return new Promise((resolve, reject) => {
this.unlock()
.then((_) => {
const from = this.unlockedAccount;
const to = from + n;
for (let i = from; i < to; i++) {
const address = this._addressFromIndex(pathBase, i);
if (!this.accounts.includes(address)) {
this.accounts.push(address);
}
this.page = 0;
}
resolve(this.accounts);
})
.catch((e) => {
reject(e);
});
});
}
getFirstPage() {
this.page = 0;
return this.__getPage(1);
}
getNextPage() {
return this.__getPage(1);
}
getPreviousPage() {
return this.__getPage(-1);
}
__getPage(increment) {
this.page += increment;
if (this.page <= 0) {
this.page = 1;
}
return new Promise((resolve, reject) => {
this.unlock()
.then((_) => {
const from = (this.page - 1) * this.perPage;
const to = from + this.perPage;
const accounts = [];
for (let i = from; i < to; i++) {
const address = this._addressFromIndex(pathBase, i);
accounts.push({
address,
balance: null,
index: i,
});
this.paths[ethUtil.toChecksumAddress(address)] = i;
}
resolve(accounts);
})
.catch((e) => {
reject(e);
});
});
}
getAccounts() {
return Promise.resolve(this.accounts.slice());
}
removeAccount(address) {
if (
!this.accounts.map((a) => a.toLowerCase()).includes(address.toLowerCase())
) {
throw new Error(`Address ${address} not found in this keyring`);
}
this.accounts = this.accounts.filter(
(a) => a.toLowerCase() !== address.toLowerCase(),
);
}
/**
* Signs a transaction using Trezor.
*
* Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns
* the same type.
*
* @template {TypedTransaction | OldEthJsTransaction} Transaction
* @param {string} address - Hex string address.
* @param {Transaction} tx - Instance of either new-style or old-style ethereumjs transaction.
* @returns {Promise<Transaction>} The signed transaction, an instance of either new-style or old-style
* ethereumjs transaction.
*/
signTransaction(address, tx) {
if (isOldStyleEthereumjsTx(tx)) {
// In this version of ethereumjs-tx we must add the chainId in hex format
// to the initial v value. The chainId must be included in the serialized
// transaction which is only communicated to ethereumjs-tx in this
// value. In newer versions the chainId is communicated via the 'Common'
// object.
return this._signTransaction(address, tx.getChainId(), tx, (payload) => {
tx.v = Buffer.from(payload.v, 'hex');
tx.r = Buffer.from(payload.r, 'hex');
tx.s = Buffer.from(payload.s, 'hex');
return tx;
});
}
return this._signTransaction(
address,
Number(tx.common.chainId()),
tx,
(payload) => {
// Because tx will be immutable, first get a plain javascript object that
// represents the transaction. Using txData here as it aligns with the
// nomenclature of ethereumjs/tx.
const txData = tx.toJSON();
// The fromTxData utility expects a type to support transactions with a type other than 0
txData.type = tx.type;
// The fromTxData utility expects v,r and s to be hex prefixed
txData.v = ethUtil.addHexPrefix(payload.v);
txData.r = ethUtil.addHexPrefix(payload.r);
txData.s = ethUtil.addHexPrefix(payload.s);
// Adopt the 'common' option from the original transaction and set the
// returned object to be frozen if the original is frozen.
return TransactionFactory.fromTxData(txData, {
common: tx.common,
freeze: Object.isFrozen(tx),
});
},
);
}
/**
*
* @template {TypedTransaction | OldEthJsTransaction} Transaction
* @param {string} address - Hex string address.
* @param {number} chainId - Chain ID
* @param {Transaction} tx - Instance of either new-style or old-style ethereumjs transaction.
* @param {(import('trezor-connect').EthereumSignedTx) => Transaction} handleSigning - Converts signed transaction
* to the same new-style or old-style ethereumjs-tx.
* @returns {Promise<Transaction>} The signed transaction, an instance of either new-style or old-style
* ethereumjs transaction.
*/
async _signTransaction(address, chainId, tx, handleSigning) {
let transaction;
if (isOldStyleEthereumjsTx(tx)) {
// legacy transaction from ethereumjs-tx package has no .toJSON() function,
// so we need to convert to hex-strings manually manually
transaction = {
to: this._normalize(tx.to),
value: this._normalize(tx.value),
data: this._normalize(tx.data),
chainId,
nonce: this._normalize(tx.nonce),
gasLimit: this._normalize(tx.gasLimit),
gasPrice: this._normalize(tx.gasPrice),
};
} else {
// new-style transaction from @ethereumjs/tx package
// we can just copy tx.toJSON() for everything except chainId, which must be a number
transaction = {
...tx.toJSON(),
chainId,
to: this._normalize(tx.to),
};
}
try {
const status = await this.unlock();
await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);
const response = await TrezorConnect.ethereumSignTransaction({
path: this._pathFromAddress(address),
transaction,
});
if (response.success) {
const newOrMutatedTx = handleSigning(response.payload);
const addressSignedWith = ethUtil.toChecksumAddress(
ethUtil.addHexPrefix(
newOrMutatedTx.getSenderAddress().toString('hex'),
),
);
const correctAddress = ethUtil.toChecksumAddress(address);
if (addressSignedWith !== correctAddress) {
throw new Error("signature doesn't match the right address");
}
return newOrMutatedTx;
}
throw new Error(
(response.payload && response.payload.error) || 'Unknown error',
);
} catch (e) {
throw new Error((e && e.toString()) || 'Unknown error');
}
}
signMessage(withAccount, data) {
return this.signPersonalMessage(withAccount, data);
}
// For personal_sign, we need to prefix the message:
signPersonalMessage(withAccount, message) {
return new Promise((resolve, reject) => {
this.unlock()
.then((status) => {
setTimeout(
(_) => {
TrezorConnect.ethereumSignMessage({
path: this._pathFromAddress(withAccount),
message: ethUtil.stripHexPrefix(message),
hex: true,
})
.then((response) => {
if (response.success) {
if (
response.payload.address !==
ethUtil.toChecksumAddress(withAccount)
) {
reject(
new Error('signature doesnt match the right address'),
);
}
const signature = `0x${response.payload.signature}`;
resolve(signature);
} else {
reject(
new Error(
(response.payload && response.payload.error) ||
'Unknown error',
),
);
}
})
.catch((e) => {
reject(new Error((e && e.toString()) || 'Unknown error'));
});
// This is necessary to avoid popup collision
// between the unlock & sign trezor popups
},
status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0,
);
})
.catch((e) => {
reject(new Error((e && e.toString()) || 'Unknown error'));
});
});
}
/**
* EIP-712 Sign Typed Data
*/
async signTypedData(address, data, { version }) {
const dataWithHashes = transformTypedData(data, version === 'V4');
// set default values for signTypedData
// Trezor is stricter than @metamask/eth-sig-util in what it accepts
const {
types: { EIP712Domain = [], ...otherTypes } = {},
message = {},
domain = {},
primaryType,
// snake_case since Trezor uses Protobuf naming conventions here
domain_separator_hash, // eslint-disable-line camelcase
message_hash, // eslint-disable-line camelcase
} = dataWithHashes;
// This is necessary to avoid popup collision
// between the unlock & sign trezor popups
const status = await this.unlock();
await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);
const response = await TrezorConnect.ethereumSignTypedData({
path: this._pathFromAddress(address),
data: {
types: { EIP712Domain, ...otherTypes },
message,
domain,
primaryType,
},
metamask_v4_compat: true,
// Trezor 1 only supports blindly signing hashes
domain_separator_hash,
message_hash,
});
if (response.success) {
if (ethUtil.toChecksumAddress(address) !== response.payload.address) {
throw new Error('signature doesnt match the right address');
}
return response.payload.signature;
}
throw new Error(
(response.payload && response.payload.error) || 'Unknown error',
);
}
exportAccount() {
return Promise.reject(new Error('Not supported on this device'));
}
forgetDevice() {
this.accounts = [];
this.hdk = new HDKey();
this.page = 0;
this.unlockedAccount = 0;
this.paths = {};
}
/**
* Set the HD path to be used by the keyring. Only known supported HD paths are allowed.
*
* If the given HD path is already the current HD path, nothing happens. Otherwise the new HD
* path is set, and the wallet state is completely reset.
*
* @throws {Error] Throws if the HD path is not supported.
*
* @param {string} hdPath - The HD path to set.
*/
setHdPath(hdPath) {
if (!ALLOWED_HD_PATHS[hdPath]) {
throw new Error(
`The setHdPath method does not support setting HD Path to ${hdPath}`,
);
}
// Reset HDKey if the path changes
if (this.hdPath !== hdPath) {
this.hdk = new HDKey();
this.accounts = [];
this.page = 0;
this.perPage = 5;
this.unlockedAccount = 0;
this.paths = {};
}
this.hdPath = hdPath;
}
/* PRIVATE METHODS */
_normalize(buf) {
return ethUtil.bufferToHex(buf).toString();
}
// eslint-disable-next-line no-shadow
_addressFromIndex(pathBase, i) {
const dkey = this.hdk.derive(`${pathBase}/${i}`);
const address = ethUtil
.publicToAddress(dkey.publicKey, true)
.toString('hex');
return ethUtil.toChecksumAddress(`0x${address}`);
}
_pathFromAddress(address) {
const checksummedAddress = ethUtil.toChecksumAddress(address);
let index = this.paths[checksummedAddress];
if (typeof index === 'undefined') {
for (let i = 0; i < MAX_INDEX; i++) {
if (checksummedAddress === this._addressFromIndex(pathBase, i)) {
index = i;
break;
}
}
}
if (typeof index === 'undefined') {
throw new Error('Unknown address');
}
return `${this.hdPath}/${index}`;
}
}
TrezorKeyring.type = keyringType;
module.exports = TrezorKeyring;