-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathledger-keyring.test.ts
More file actions
1481 lines (1277 loc) · 52.4 KB
/
Copy pathledger-keyring.test.ts
File metadata and controls
1481 lines (1277 loc) · 52.4 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
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Common, Chain, Hardfork } from '@ethereumjs/common';
import { RLP } from '@ethereumjs/rlp';
import { TransactionFactory } from '@ethereumjs/tx';
import * as ethUtil from '@ethereumjs/util';
import { TransportStatusError } from '@ledgerhq/hw-transport';
import * as sigUtil from '@metamask/eth-sig-util';
import { bytesToHex, Hex, remove0x } from '@metamask/utils';
import EthereumTx from 'ethereumjs-tx';
import HDKey from 'hdkey';
import { LedgerBridge, LedgerBridgeOptions } from './ledger-bridge';
import { LedgerIframeBridge } from './ledger-iframe-bridge';
import { AccountDetails, LedgerKeyring } from './ledger-keyring';
jest.mock('@metamask/eth-sig-util', () => {
return {
// eslint-disable-next-line @typescript-eslint/naming-convention
__esModule: true,
...jest.requireActual('@metamask/eth-sig-util'),
};
});
const fakeAccounts = [
'0xF30952A1c534CDE7bC471380065726fa8686dfB3',
'0x44fe3Cf56CaF651C4bD34Ae6dbcffa34e9e3b84B',
'0x8Ee3374Fa705C1F939715871faf91d4348D5b906',
'0xEF69e24dE9CdEe93C4736FE29791E45d5D4CFd6A',
'0xC668a5116A045e9162902795021907Cb15aa2620',
'0xbF519F7a6D8E72266825D770C60dbac55a3baeb9',
'0x0258632Fe2F91011e06375eB0E6f8673C0463204',
'0x4fC1700C0C61980aef0Fb9bDBA67D8a25B5d4335',
'0xeEC5D417152aE295c047FB0B0eBd7c7090dDedEb',
'0xd3f978B9eEEdB68A38CF252B3779afbeb3623fDf',
'0xd819fE2beD53f44825F66873a159B687736d3092',
'0xE761dA62f053ad9eE221d325657535991Ab659bD',
'0xd4F1686961642340a80334b5171d85Bbd390c691',
'0x6772C4B1E841b295960Bb4662dceD9bb71726357',
'0x41bEAD6585eCA6c79B553Ca136f0DFA78A006899',
'0xf37559520757223264ee707d4e3fdfaa118db9bd',
] as const;
const fakeXPubKey =
'xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt';
const fakeHdKey = HDKey.fromExtendedKey(fakeXPubKey);
const fakeTx = new EthereumTx({
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
// EIP 155 chainId - mainnet: 1, ropsten: 3
chainId: '0x1',
});
const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Berlin });
const commonEIP1559 = new Common({
chain: Chain.Mainnet,
hardfork: Hardfork.London,
});
const newFakeTx = TransactionFactory.fromTxData(
{
nonce: '0x00',
gasPrice: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
},
{ common, freeze: false },
);
const fakeTypeTwoTx = TransactionFactory.fromTxData(
{
nonce: '0x00',
maxFeePerGas: '0x19184e72a000',
maxPriorityFeePerGas: '0x09184e72a000',
gasLimit: '0x2710',
to: '0x0000000000000000000000000000000000000000',
value: '0x00',
data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
type: 2,
v: '0x01',
},
{ common: commonEIP1559, freeze: false },
);
describe('LedgerKeyring', function () {
let keyring: LedgerKeyring;
let bridge: LedgerBridge<LedgerBridgeOptions>;
/**
* Sets up the keyring to unlock one account.
*
* @param accountIndex - The index of the account to unlock.
* @returns Returns a promise that resolves when the keyring is unlocked.
*/
async function basicSetupToUnlockOneAccount(accountIndex = 0): Promise<void> {
keyring.setAccountToUnlock(accountIndex);
await keyring.addAccounts(1);
jest
.spyOn(keyring, 'unlock')
.mockResolvedValue(fakeAccounts[accountIndex] as Hex);
}
beforeEach(async function () {
bridge = new LedgerIframeBridge();
keyring = new LedgerKeyring({ bridge });
keyring.hdk = fakeHdKey;
await keyring.deserialize({});
});
afterEach(function () {
jest.clearAllMocks();
});
describe('Keyring.type', function () {
it('is a class property that returns the type string.', function () {
const { type } = LedgerKeyring;
expect(typeof type).toBe('string');
});
it('returns the correct value', function () {
const { type } = keyring;
const correct = LedgerKeyring.type;
expect(type).toBe(correct);
});
});
describe('constructor', function () {
it('constructs', async function () {
const ledgerKeyring = new LedgerKeyring({
bridge: new LedgerIframeBridge(),
});
expect(typeof ledgerKeyring).toBe('object');
const accounts = await ledgerKeyring.getAccounts();
expect(Array.isArray(accounts)).toBe(true);
});
it('throws if a bridge is not provided', function () {
expect(
() =>
new LedgerKeyring({
bridge: undefined as unknown as LedgerBridge<LedgerBridgeOptions>,
}),
).toThrow('Bridge is a required dependency for the keyring');
});
});
describe('init', function () {
it('calls bridge init', async function () {
jest.spyOn(bridge, 'init').mockResolvedValue(undefined);
await keyring.init();
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(bridge.init).toHaveBeenCalledTimes(1);
});
});
describe('serialize', function () {
it('serializes an instance', async function () {
const output = await keyring.serialize();
expect(output.hdPath).toBe(`m/44'/60'/0'`);
expect(Array.isArray(output.accounts)).toBe(true);
expect(output.accounts).toHaveLength(0);
});
});
describe('deserialize', function () {
it('serializes what it deserializes', async function () {
const account = fakeAccounts[0];
const checksum = ethUtil.toChecksumAddress(account);
const someHdPath = `m/44'/60'/0'/1`;
const accountDetails: Record<string, AccountDetails> = {};
accountDetails[checksum] = {
index: 0,
hdPath: someHdPath,
};
await keyring.deserialize({
hdPath: someHdPath,
accounts: [account],
accountDetails,
deviceId: 'some-device',
});
const serialized = await keyring.serialize();
expect(serialized.accounts).toHaveLength(1);
expect(serialized.hdPath).toBe(someHdPath);
expect(serialized.accountDetails).toStrictEqual(accountDetails);
expect(serialized.deviceId).toBe('some-device');
});
it('migrates accountIndexes to accountDetails', async function () {
const someHdPath = `m/44'/60'/0'/0/0`;
const account = fakeAccounts[1];
const checksum = ethUtil.toChecksumAddress(account);
const accountIndexes: Record<string, number> = {};
accountIndexes[checksum] = 1;
await keyring.deserialize({
accounts: [account],
accountIndexes,
hdPath: someHdPath,
});
expect(keyring.hdPath).toBe(someHdPath);
expect(keyring.accounts[0]).toBe(account);
expect(keyring.accountDetails[checksum]).toStrictEqual({
bip44: true,
hdPath: `m/44'/60'/1'/0/0`,
});
});
it('migrates non-bip44 accounts to accountDetails', async function () {
const someHdPath = `m/44'/60'/0'`;
const account = fakeAccounts[1];
const checksum = ethUtil.toChecksumAddress(account);
await keyring.deserialize({
accounts: [account],
hdPath: someHdPath,
deviceId: 'some-device',
implementFullBIP44: true,
});
expect(keyring.hdPath).toStrictEqual(someHdPath);
expect(keyring.accounts[0]).toBe(account);
expect(keyring.accountDetails[checksum]).toStrictEqual({
bip44: false,
hdPath: `m/44'/60'/0'/1`,
});
});
it('throws an error when the address is not found', async function () {
const hdPath = `m/44'/60'/0'`;
const account = '0x90A5b70d94418d6c25C19071e5b8170607f6302D';
const accountIndexes: Record<string, number> = {};
accountIndexes['0x90a'] = 1;
await expect(
keyring.deserialize({
hdPath,
accounts: [account],
deviceId: 'some-device',
implementFullBIP44: true,
accountIndexes,
}),
).rejects.toThrow('Unknown address');
});
describe('setDeviceId', function () {
it('sets the deviceId', function () {
keyring.setDeviceId('some-device');
expect(keyring.getDeviceId()).toBe('some-device');
});
});
describe('getDeviceId', function () {
it('returns the deviceId', function () {
keyring.setDeviceId('some-device');
expect(keyring.getDeviceId()).toBe('some-device');
});
});
describe('isConnected', function () {
it('returns true if bridge is connected', function () {
bridge.isDeviceConnected = true;
expect(keyring.isConnected()).toBe(true);
});
it('returns false if bridge is not connected', function () {
bridge.isDeviceConnected = false;
expect(keyring.isConnected()).toBe(false);
});
});
describe('getName', function () {
it('returns the keyring name', function () {
expect(keyring.getName()).toBe('Ledger Hardware');
});
});
describe('isUnlocked', function () {
it('returns true if there is a public key', function () {
expect(keyring.isUnlocked()).toBe(true);
});
});
describe('setAccountToUnlock', function () {
it('sets unlockedAccount to new value', function () {
keyring.setAccountToUnlock(3);
expect(keyring.unlockedAccount).toBe(3);
});
});
describe('setHdPath', function () {
it('sets the hdPath', function () {
const someHDPath = `m/44'/99'/0`;
keyring.setHdPath(someHDPath);
expect(keyring.hdPath).toBe(someHDPath);
});
it('resets the HDKey if the path changes', function () {
const someHDPath = `m/44'/99'/0`;
keyring.setHdPath(someHDPath);
expect(keyring.hdk.publicKey).toBeNull();
});
});
describe('unlock', function () {
it('resolves to a public key if it exists', async function () {
expect(async () => {
await keyring.unlock();
}).not.toThrow();
});
it('updates hdk.publicKey if updateHdk is true', async function () {
// @ts-expect-error we want to bypass the set publicKey property set method
keyring.hdk = { publicKey: 'ABC' };
jest.spyOn(bridge, 'getPublicKey').mockResolvedValue({
publicKey:
'04197ced33b63059074b90ddecb9400c45cbc86210a20317b539b8cae84e573342149c3384ae45f27db68e75823323e97e03504b73ecbc47f5922b9b8144345e5a',
chainCode:
'ba0fb16e01c463d1635ec36f5adeb93a838adcd1526656c55f828f1e34002a8b',
address: fakeAccounts[1],
});
await keyring.unlock(`m/44'/60'/0'/1`);
expect(keyring.hdk.publicKey).not.toBe('ABC');
});
it('throws an error when the bridge getPublicKey method throws an error and it is not an error type', async function () {
keyring.setHdPath(`m/44'/60'/0'/0`);
jest.spyOn(bridge, 'getPublicKey').mockRejectedValue('Some error');
await expect(keyring.unlock()).rejects.toThrow(
'Ledger: Unknown error while unlocking account',
);
});
it('does not update hdk.publicKey if updateHdk is false', async function () {
// @ts-expect-error we want to bypass the publicKey property set method
keyring.hdk = { publicKey: 'ABC' };
jest.spyOn(bridge, 'getPublicKey').mockResolvedValue({
publicKey:
'04197ced33b63059074b90ddecb9400c45cbc86210a20317b539b8cae84e573342149c3384ae45f27db68e75823323e97e03504b73ecbc47f5922b9b8144345e5a',
chainCode:
'ba0fb16e01c463d1635ec36f5adeb93a838adcd1526656c55f828f1e34002a8b',
address: fakeAccounts[1],
});
await keyring.unlock(`m/44'/60'/0'/1`, false);
expect(keyring.hdk.publicKey).toBe('ABC');
});
it('unlocks with the set hdPath if a new one is not provided', async function () {
keyring.setHdPath(`m/44'/60'/0'/0`);
jest.spyOn(bridge, 'getPublicKey').mockResolvedValue(
Promise.resolve({
publicKey: '0x1234',
chainCode: '0x1234',
address: fakeAccounts[0],
}),
);
const account = await keyring.unlock(undefined, false);
expect(account).toBe(fakeAccounts[0]);
});
it('throws an error if the bridge getPublicKey method throws an error', async function () {
keyring.setHdPath(`m/44'/60'/0'/0`);
jest
.spyOn(bridge, 'getPublicKey')
.mockRejectedValue(new Error('Some error'));
await expect(keyring.unlock()).rejects.toThrow('Some error');
});
});
describe('addAccounts', function () {
describe('with no arguments', function () {
it('returns a single account', async function () {
keyring.setAccountToUnlock(0);
const accounts = await keyring.addAccounts(1);
expect(accounts).toHaveLength(1);
});
});
describe('with a numeric argument', function () {
it('returns that number of accounts', async function () {
keyring.setAccountToUnlock(0);
const firstBatch = await keyring.addAccounts(3);
keyring.setAccountToUnlock(3);
const secondBatch = await keyring.addAccounts(2);
expect(firstBatch).toHaveLength(3);
expect(secondBatch).toHaveLength(2);
});
it('returns the expected accounts', async function () {
keyring.setAccountToUnlock(0);
const firstBatch = await keyring.addAccounts(3);
keyring.setAccountToUnlock(3);
const secondBatch = await keyring.addAccounts(2);
expect(firstBatch).toStrictEqual([
fakeAccounts[0],
fakeAccounts[1],
fakeAccounts[2],
]);
expect(secondBatch).toStrictEqual([fakeAccounts[3], fakeAccounts[4]]);
});
});
it('stores account details for bip44 accounts', async function () {
keyring.setHdPath(`m/44'/60'/0'/0/0`);
keyring.setAccountToUnlock(1);
jest.spyOn(keyring, 'unlock').mockResolvedValue(fakeAccounts[0]);
const accounts = await keyring.addAccounts(1);
expect(keyring.accountDetails[accounts[0] as string]).toStrictEqual({
bip44: true,
hdPath: `m/44'/60'/1'/0/0`,
});
});
it('stores account details for non-bip44 accounts', async function () {
keyring.setHdPath(`m/44'/60'/0'`);
keyring.setAccountToUnlock(2);
const accounts = await keyring.addAccounts(1);
expect(keyring.accountDetails[accounts[0] as string]).toStrictEqual({
bip44: false,
hdPath: `m/44'/60'/0'/2`,
});
});
describe('when called multiple times', function () {
it('does not remove existing accounts', async function () {
keyring.setAccountToUnlock(0);
const firstBatch = await keyring.addAccounts(1);
keyring.setAccountToUnlock(1);
const secondBatch = await keyring.addAccounts(1);
expect(await keyring.getAccounts()).toHaveLength(2);
expect(firstBatch).toStrictEqual([fakeAccounts[0]]);
expect(secondBatch).toStrictEqual([fakeAccounts[1]]);
});
});
});
describe('removeAccount', function () {
describe('if the account exists', function () {
it('removes that account', async function () {
keyring.setAccountToUnlock(0);
const accounts = await keyring.addAccounts(1);
expect(accounts).toHaveLength(1);
keyring.removeAccount(fakeAccounts[0]);
const accountsAfterRemoval = await keyring.getAccounts();
expect(accountsAfterRemoval).toHaveLength(0);
});
});
describe('if the account does not exist', function () {
it('throws an error', function () {
const unexistingAccount =
'0x0000000000000000000000000000000000000000';
expect(() => {
keyring.removeAccount(unexistingAccount);
}).toThrow(`Address ${unexistingAccount} not found in this keyring`);
});
});
});
describe('getFirstPage', function () {
it('sets the currentPage to 1', async function () {
await keyring.getFirstPage();
expect(keyring.page).toBe(1);
});
it('returns the list of accounts for current page', async function () {
const accounts = await keyring.getFirstPage();
expect(accounts).toHaveLength(keyring.perPage);
expect(accounts[0]?.address).toBe(fakeAccounts[0]);
expect(accounts[1]?.address).toBe(fakeAccounts[1]);
expect(accounts[2]?.address).toBe(fakeAccounts[2]);
expect(accounts[3]?.address).toBe(fakeAccounts[3]);
expect(accounts[4]?.address).toBe(fakeAccounts[4]);
});
it('returns the list of accounts when isLedgerLiveHdPath is true', async function () {
keyring.setHdPath(`m/44'/60'/0'/0/0`);
jest.spyOn(keyring, 'unlock').mockResolvedValue(fakeAccounts[0]);
const accounts = await keyring.getFirstPage();
expect(accounts).toHaveLength(keyring.perPage);
expect(accounts[0]?.address).toBe(
'0xF30952A1c534CDE7bC471380065726fa8686dfB3',
);
});
});
describe('getNextPage', function () {
it('returns the list of accounts for current page', async function () {
const accounts = await keyring.getNextPage();
expect(accounts).toHaveLength(keyring.perPage);
expect(accounts[0]?.address).toBe(fakeAccounts[0]);
expect(accounts[1]?.address).toBe(fakeAccounts[1]);
expect(accounts[2]?.address).toBe(fakeAccounts[2]);
expect(accounts[3]?.address).toBe(fakeAccounts[3]);
expect(accounts[4]?.address).toBe(fakeAccounts[4]);
});
});
describe('getPreviousPage', function () {
it('returns the list of accounts for current page', async function () {
// manually advance 1 page
await keyring.getNextPage();
const accounts = await keyring.getPreviousPage();
expect(accounts).toHaveLength(keyring.perPage);
expect(accounts[0]?.address).toBe(fakeAccounts[0]);
expect(accounts[1]?.address).toBe(fakeAccounts[1]);
expect(accounts[2]?.address).toBe(fakeAccounts[2]);
expect(accounts[3]?.address).toBe(fakeAccounts[3]);
expect(accounts[4]?.address).toBe(fakeAccounts[4]);
});
it('is able to go back to the previous page', async function () {
// manually advance 1 page
await keyring.getNextPage();
const accounts = await keyring.getPreviousPage();
expect(accounts).toHaveLength(keyring.perPage);
expect(accounts[0]?.address).toBe(fakeAccounts[0]);
expect(accounts[1]?.address).toBe(fakeAccounts[1]);
expect(accounts[2]?.address).toBe(fakeAccounts[2]);
expect(accounts[3]?.address).toBe(fakeAccounts[3]);
expect(accounts[4]?.address).toBe(fakeAccounts[4]);
});
});
describe('getAccounts', function () {
const accountIndex = 5;
let accounts: string[] = [];
beforeEach(async function () {
keyring.setAccountToUnlock(accountIndex);
await keyring.addAccounts(1);
accounts = await keyring.getAccounts();
});
it('returns an array of accounts', function () {
expect(Array.isArray(accounts)).toBe(true);
expect(accounts).toHaveLength(1);
});
it('returns the expected', function () {
const expectedAccount = fakeAccounts[accountIndex];
expect(accounts[0]).toStrictEqual(expectedAccount);
});
});
describe('forgetDevice', function () {
it('clears the content of the keyring', async function () {
// Add an account
keyring.setAccountToUnlock(0);
await keyring.addAccounts(1);
// Wipe the keyring
keyring.forgetDevice();
const accounts = await keyring.getAccounts();
expect(keyring.isUnlocked()).toBe(false);
expect(accounts).toHaveLength(0);
});
it('deviceId should be cleared after forgetting the device', async function () {
// Add an account
keyring.setAccountToUnlock(0);
await keyring.addAccounts(1);
keyring.setDeviceId('device-id');
// Wipe the keyring
keyring.forgetDevice();
expect(keyring.getDeviceId()).toBe('');
});
});
describe('attemptMakeApp', function () {
it('calls the bridge attemptMakeApp method', async function () {
jest.spyOn(bridge, 'attemptMakeApp').mockResolvedValue(true);
await keyring.attemptMakeApp();
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(bridge.attemptMakeApp).toHaveBeenCalledTimes(1);
});
});
describe('updateTransportMethod', function () {
describe('when bridge is connected', function () {
it('calls the bridge updateTransportMethod method', async function () {
jest.spyOn(bridge, 'updateTransportMethod').mockResolvedValue(true);
await keyring.updateTransportMethod('some-transport');
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(bridge.updateTransportMethod).toHaveBeenCalledTimes(1);
});
});
});
describe('signTransaction', function () {
describe('using old versions of ethereumjs/tx', function () {
it('passes serialized transaction to ledger and return signed tx', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockImplementation(async (params) => {
expect(params).toStrictEqual({
hdPath: "m/44'/60'/0'/0",
tx: fakeTx.serialize().toString('hex'),
});
return { v: '0x1', r: '0x0', s: '0x0' };
});
jest.spyOn(fakeTx, 'verifySignature').mockReturnValue(true);
const returnedTx = await keyring.signTransaction(
fakeAccounts[0],
fakeTx,
);
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(keyring.bridge.deviceSignTransaction).toHaveBeenCalled();
expect(returnedTx).toHaveProperty('v');
expect(returnedTx).toHaveProperty('r');
expect(returnedTx).toHaveProperty('s');
});
});
describe('using new versions of ethereumjs/tx', function () {
it('passes correctly encoded legacy transaction to ledger and return signed tx', async function () {
// Generated by signing newFakeTx with private key eee0290acfa88cf7f97be7525437db1624293f829b8a2cba380390618d62662b
const expectedRSV = {
v: '0x26',
r: '0xf3a7718999d1b87beda810b25cc025153e74df0745279826b9b2f3d1d1b6318',
s: '0x7e33bdfbf5272dc4f55649e9ba729849670171a68ef8c0fbeed3b879b90b8954',
} as const;
await basicSetupToUnlockOneAccount();
const signedNewFakeTx = TransactionFactory.fromTxData(
{
...newFakeTx.toJSON(),
...expectedRSV,
},
{ freeze: false },
);
jest
.spyOn(TransactionFactory, 'fromTxData')
.mockReturnValue(signedNewFakeTx);
jest
.spyOn(signedNewFakeTx, 'verifySignature')
.mockImplementation(() => true);
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockImplementation(async (params) => {
expect(params).toStrictEqual({
hdPath: "m/44'/60'/0'/0",
tx: Buffer.from(
RLP.encode(newFakeTx.getMessageToSign()),
).toString('hex'),
});
return expectedRSV;
});
const returnedTx = await keyring.signTransaction(
fakeAccounts[0],
newFakeTx,
);
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(keyring.bridge.deviceSignTransaction).toHaveBeenCalled();
expect(returnedTx.toJSON()).toStrictEqual(signedNewFakeTx.toJSON());
});
it('passes correctly encoded EIP1559 transaction to ledger and return signed tx', async function () {
// Generated by signing fakeTypeTwoTx with private key eee0290acfa88cf7f97be7525437db1624293f829b8a2cba380390618d62662b
const expectedRSV = {
v: '0x0',
r: '0x5ffb3adeaec80e430e7a7b02d95c5108b6f09a0bdf3cf69869dc1b38d0fb8d3a',
s: '0x28b234a5403d31564e18258df84c51a62683e3f54fa2b106fdc1a9058006a112',
} as const;
await basicSetupToUnlockOneAccount();
const signedFakeTypeTwoTx = TransactionFactory.fromTxData(
{
...fakeTypeTwoTx.toJSON(),
type: fakeTypeTwoTx.type,
...expectedRSV,
},
{ common: commonEIP1559, freeze: false },
);
jest
.spyOn(TransactionFactory, 'fromTxData')
.mockReturnValue(signedFakeTypeTwoTx);
jest
.spyOn(signedFakeTypeTwoTx, 'verifySignature')
.mockReturnValue(true);
jest.spyOn(fakeTypeTwoTx, 'verifySignature').mockReturnValue(true);
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockImplementation(async (params) => {
expect(params).toStrictEqual({
hdPath: "m/44'/60'/0'/0",
tx: remove0x(
bytesToHex(fakeTypeTwoTx.getMessageToSign() as Uint8Array),
),
});
return expectedRSV;
});
const returnedTx = await keyring.signTransaction(
fakeAccounts[0],
fakeTypeTwoTx,
);
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(keyring.bridge.deviceSignTransaction).toHaveBeenCalled();
expect(returnedTx.toJSON()).toStrictEqual(
signedFakeTypeTwoTx.toJSON(),
);
});
});
it('throws default error in signTransaction when unlockAccountByAddress returns undefined hdPath', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring, 'unlockAccountByAddress')
.mockResolvedValue(undefined);
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow('Ledger: hdPath is empty while signing transaction');
});
it('throws different error to the default one if the bridge error is an instance of the Error object', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockRejectedValue(new Error('some error'));
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow('some error');
});
it('throws the default error if the bridge error is not an instance of the Error object', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockRejectedValue('some error');
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow('Ledger: Unknown error while signing transaction');
});
it('throws an error if the signature is invalid', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockResolvedValue({ v: '0x1', r: '0x0', s: '0x0' });
jest.spyOn(fakeTx, 'verifySignature').mockReturnValue(false);
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow('Ledger: The transaction signature is not valid');
});
it('throws user rejection error when TransportStatusError with code 27013 is thrown', async function () {
await basicSetupToUnlockOneAccount();
const transportError = {
statusCode: 27013,
message: 'Ledger device: (denied by the user?) (0x6985)',
name: 'TransportStatusError',
};
Object.setPrototypeOf(transportError, TransportStatusError.prototype);
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockRejectedValue(transportError);
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow('Ledger: User rejected the transaction');
});
it('throws blind signing error when TransportStatusError with code 27264 is thrown', async function () {
await basicSetupToUnlockOneAccount();
const transportError = {
statusCode: 27264,
message: 'Ledger device: Invalid data received (0x6a80)',
name: 'TransportStatusError',
};
Object.setPrototypeOf(transportError, TransportStatusError.prototype);
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockRejectedValue(transportError);
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow('Ledger: Blind signing must be enabled');
});
it('re-throws TransportStatusError with unknown status code', async function () {
await basicSetupToUnlockOneAccount();
const transportError = {
statusCode: 12345,
message: 'Some other transport error',
name: 'TransportStatusError',
};
Object.setPrototypeOf(transportError, TransportStatusError.prototype);
jest
.spyOn(keyring.bridge, 'deviceSignTransaction')
.mockRejectedValue(transportError);
await expect(
keyring.signTransaction(fakeAccounts[0], fakeTx),
).rejects.toThrow(transportError);
});
});
describe('signPersonalMessage', function () {
it('calls create a listener waiting for the iframe response', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockImplementation(async (params) => {
expect(params).toStrictEqual({
hdPath: "m/44'/60'/0'/0",
message: 'some message',
});
return { v: 1, r: '0x0', s: '0x0' };
});
jest
.spyOn(sigUtil, 'recoverPersonalSignature')
.mockReturnValue(fakeAccounts[0]);
await keyring.signPersonalMessage(fakeAccounts[0], 'some message');
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(keyring.bridge.deviceSignMessage).toHaveBeenCalled();
});
it('throws the default error in personal sign if the unlockAccountByAddress method returns an undefined hdPath', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring, 'unlockAccountByAddress')
.mockResolvedValue(undefined);
await expect(
keyring.signPersonalMessage(fakeAccounts[0], 'fakeTx'),
).rejects.toThrow('Ledger: Unknown error while signing message');
});
it('throws an error in personal sign if the deviceSignTransaction rejects with an error', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockRejectedValue(new Error('some error'));
await expect(
keyring.signPersonalMessage(fakeAccounts[0], 'fakeTx'),
).rejects.toThrow('some error');
});
it('throws default error in personal sign when deviceSignTransaction rejects with an error that is not an instance of Error object', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockRejectedValue('some error');
await expect(
keyring.signPersonalMessage(fakeAccounts[0], 'fakeTx'),
).rejects.toThrow('Ledger: Unknown error while signing message');
});
it('throws an error if the signature does not match the address', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockResolvedValue({ v: 1, r: '0x0', s: '0x0' });
jest
.spyOn(sigUtil, 'recoverPersonalSignature')
.mockReturnValue('0x0000000000000000000000000000000000000000');
await expect(
keyring.signPersonalMessage(fakeAccounts[0], 'some message'),
).rejects.toThrow(
'Ledger: The signature doesnt match the right address',
);
});
it('throws user rejection error when TransportStatusError with code 27013 is thrown in signPersonalMessage', async function () {
await basicSetupToUnlockOneAccount();
const transportError = {
statusCode: 27013,
message: 'Ledger device: (denied by the user?) (0x6985)',
name: 'TransportStatusError',
};
Object.setPrototypeOf(transportError, TransportStatusError.prototype);
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockRejectedValue(transportError);
await expect(
keyring.signPersonalMessage(fakeAccounts[0], 'some message'),
).rejects.toThrow('Ledger: User rejected the transaction');
});
it('re-throws TransportStatusError with unknown status code in signPersonalMessage', async function () {
await basicSetupToUnlockOneAccount();
const transportError = {
statusCode: 12345,
message: 'Some other transport error',
name: 'TransportStatusError',
};
Object.setPrototypeOf(transportError, TransportStatusError.prototype);
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockRejectedValue(transportError);
await expect(
keyring.signPersonalMessage(fakeAccounts[0], 'some message'),
).rejects.toThrow(transportError);
});
it('normalizes v=0 to v=27 for proper signature recovery', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockResolvedValue({ v: 0, r: 'aabbccdd', s: '11223344' });
jest
.spyOn(sigUtil, 'recoverPersonalSignature')
.mockReturnValue(fakeAccounts[0]);
const result = await keyring.signPersonalMessage(
fakeAccounts[0],
'some message',
);
// v=0 should be normalized to v=27 (0x1b)
expect(result).toBe('0xaabbccdd112233441b');
});
it('normalizes v=1 to v=28 for proper signature recovery', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockResolvedValue({ v: 1, r: 'aabbccdd', s: '11223344' });
jest
.spyOn(sigUtil, 'recoverPersonalSignature')
.mockReturnValue(fakeAccounts[0]);
const result = await keyring.signPersonalMessage(
fakeAccounts[0],
'some message',
);
// v=1 should be normalized to v=28 (0x1c)
expect(result).toBe('0xaabbccdd112233441c');
});
it('preserves v=27 unchanged', async function () {
await basicSetupToUnlockOneAccount();
jest
.spyOn(keyring.bridge, 'deviceSignMessage')
.mockResolvedValue({ v: 27, r: 'aabbccdd', s: '11223344' });
jest
.spyOn(sigUtil, 'recoverPersonalSignature')
.mockReturnValue(fakeAccounts[0]);
const result = await keyring.signPersonalMessage(
fakeAccounts[0],