This repository was archived by the owner on Oct 7, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathKeyringController.test.ts
More file actions
2065 lines (1836 loc) · 72.3 KB
/
KeyringController.test.ts
File metadata and controls
2065 lines (1836 loc) · 72.3 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 { Wallet } from '@ethereumjs/wallet';
import HdKeyring from '@metamask/eth-hd-keyring';
import { normalize as normalizeAddress } from '@metamask/eth-sig-util';
import type { Hex, Json, KeyringClass } from '@metamask/utils';
import { bytesToHex } from '@metamask/utils';
import { strict as assert } from 'assert';
import * as sinon from 'sinon';
import { KeyringController, keyringBuilderFactory } from '.';
import { KeyringType, KeyringControllerError } from './constants';
import {
MockEncryptor,
KeyringMockWithInit,
PASSWORD,
MOCK_HARDCODED_KEY,
MOCK_ENCRYPTION_SALT,
BaseKeyringMock,
KeyringMockWithDestroy,
buildMockTransaction,
KeyringMockWithSignTransaction,
KeyringMockWithUserOp,
} from './test';
import type { KeyringControllerArgs } from './types';
const MOCK_ENCRYPTION_KEY =
'{"alg":"A256GCM","ext":true,"k":"wYmxkxOOFBDP6F6VuuYFcRt_Po-tSLFHCWVolsHs4VI","key_ops":["encrypt","decrypt"],"kty":"oct"}';
const MOCK_ENCRYPTION_DATA = `{"data":"2fOOPRKClNrisB+tmqIcETyZvDuL2iIR1Hr1nO7XZHyMqVY1cDBetw2gY5C+cIo1qkpyv3bPp+4buUjp38VBsjbijM0F/FLOqWbcuKM9h9X0uwxsgsZ96uwcIf5I46NiMgoFlhppTTMZT0Nkocz+SnvHM0IgLsFan7JqBU++vSJvx2M1PDljZSunOsqyyL+DKmbYmM4umbouKV42dipUwrCvrQJmpiUZrSkpMJrPJk9ufDQO4CyIVo0qry3aNRdYFJ6rgSyq/k6rXMwGExCMHn8UlhNnAMuMKWPWR/ymK1bzNcNs4VU14iVjEXOZGPvD9cvqVe/VtcnIba6axNEEB4HWDOCdrDh5YNWwMlQVL7vSB2yOhPZByGhnEOloYsj2E5KEb9jFGskt7EKDEYNofr6t83G0c+B72VGYZeCvgtzXzgPwzIbhTtKkP+gdBmt2JNSYrTjLypT0q+v4C9BN1xWTxPmX6TTt0NzkI9pJxgN1VQAfSU9CyWTVpd4CBkgom2cSBsxZ2MNbdKF+qSWz3fQcmJ55hxM0EGJSt9+8eQOTuoJlBapRk4wdZKHR2jdKzPjSF2MAmyVD2kU51IKa/cVsckRFEes+m7dKyHRvlNwgT78W9tBDdZb5PSlfbZXnv8z5q1KtAj2lM2ogJ7brHBdevl4FISdTkObpwcUMcvACOOO0dj6CSYjSKr0ZJ2RLChVruZyPDxEhKGb/8Kv8trLOR3mck/et6d050/NugezycNk4nnzu5iP90gPbSzaqdZI=","iv":"qTGO1afGv3waHN9KoW34Eg==","salt":"${MOCK_ENCRYPTION_SALT}"}`;
const walletOneSeedWords =
'puzzle seed penalty soldier say clay field arctic metal hen cage runway';
const mockAddress = '0xef35ca8ebb9669a35c31b5f6f249a9941a812ac1';
const walletOneAddresses = ['0xef35ca8ebb9669a35c31b5f6f249a9941a812ac1'];
const walletOnePrivateKey = [
'ace918800411c0b96b915f76efbbd4d50e6c997180fee58e01f60d3a412d2f7e',
];
const walletTwoSeedWords =
'urge letter protect palace city barely security section midnight wealth south deer';
const walletTwoAddresses = [
'0xbbafcf3d00fb625b65bb1497c94bf42c1f4b3e78',
'0x49dd2653f38f75d40fdbd51e83b9c9724c87f7eb',
];
/**
* Create a keyring controller that has been initialized with the given options.
*
* @param options - Initialization options.
* @param options.constructorOptions - Constructor options, merged with test defaults.
* @param options.password - The vault password. If provided, creates a new vault (if necessary)
* and unlocks the vault.
* @param options.seedPhrase - A seed phrase. If provided, this is used to restore the vault.
* @returns A keyring controller.
*/
async function initializeKeyringController({
constructorOptions,
password,
seedPhrase,
}: {
constructorOptions?: Partial<KeyringControllerArgs>;
password?: string;
seedPhrase?: string;
} = {}) {
const keyringController = new KeyringController({
encryptor: new MockEncryptor(),
cacheEncryptionKey: false,
keyringBuilders: [keyringBuilderFactory(BaseKeyringMock)],
...constructorOptions,
});
if (seedPhrase && !password) {
throw new Error('Password required to restore vault');
} else if (seedPhrase && password) {
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic: walletOneSeedWords,
numberOfAccounts: 1,
},
});
} else if (password) {
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
});
}
return keyringController;
}
/**
* Delete the encryption key and salt from the `memStore` of the given keyring controller.
*
* @param keyringController - The keyring controller to delete the encryption key and salt from.
*/
function deleteEncryptionKeyAndSalt(keyringController: KeyringController) {
const keyringControllerState = keyringController.memStore.getState();
delete keyringControllerState.encryptionKey;
delete keyringControllerState.encryptionSalt;
keyringController.memStore.updateState(keyringControllerState);
}
/**
* Stub the `getAccounts` and `addAccounts` methods of the given keyring class to return the given
* account.
*
* @param keyringClass - The keyring class to stub.
* @param account - The account to return.
*/
function stubKeyringClassWithAccount(
keyringClass: KeyringClass<Json>,
account: string,
) {
sinon
.stub(keyringClass.prototype, 'getAccounts')
.returns(Promise.resolve([account]));
sinon
.stub(keyringClass.prototype, 'addAccounts')
.returns(Promise.resolve([account]));
}
describe('KeyringController', () => {
afterEach(() => {
sinon.restore();
});
describe('constructor', () => {
describe('with cacheEncryptionKey = true', () => {
it('should throw error if provided encryptor does not support key export', async () => {
expect(
() =>
// @ts-expect-error we want to bypass typechecks here.
new KeyringController({
cacheEncryptionKey: true,
encryptor: {
decrypt: async (_pass: string, _text: string) =>
Promise.resolve('encrypted'),
encrypt: async (_pass: string, _obj: any) => 'decrypted',
},
}),
).toThrow(KeyringControllerError.UnsupportedEncryptionKeyExport);
});
});
});
describe('setLocked', () => {
it('setLocked correctly sets lock state', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
assert.notDeepEqual(
keyringController.keyrings,
[],
'keyrings should not be empty',
);
await keyringController.setLocked();
expect(keyringController.password).toBeUndefined();
expect(keyringController.memStore.getState().isUnlocked).toBe(false);
expect(keyringController.keyrings).toHaveLength(0);
});
it('emits "lock" event', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const lockSpy = sinon.spy();
keyringController.on('lock', lockSpy);
await keyringController.setLocked();
expect(lockSpy.calledOnce).toBe(true);
});
it('calls keyring optional destroy function', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
keyringBuilders: [keyringBuilderFactory(KeyringMockWithDestroy)],
},
});
const destroy = sinon.spy(KeyringMockWithDestroy.prototype, 'destroy');
await keyringController.addNewKeyring('Keyring Mock With Destroy');
await keyringController.setLocked();
expect(destroy.calledOnce).toBe(true);
});
});
describe('submitPassword', () => {
it('should not load keyrings when incorrect password', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
});
await keyringController.persistAllKeyrings();
expect(keyringController.keyrings).toHaveLength(1);
await keyringController.setLocked();
await expect(
keyringController.submitPassword('Wrong password'),
).rejects.toThrow('Incorrect password.');
expect(keyringController.password).toBeUndefined();
expect(keyringController.keyrings).toHaveLength(0);
});
it('emits "unlock" event', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
await keyringController.setLocked();
const unlockSpy = sinon.spy();
keyringController.on('unlock', unlockSpy);
await keyringController.submitPassword(PASSWORD);
expect(unlockSpy.calledOnce).toBe(true);
});
});
describe('persistAllKeyrings', () => {
it('should persist keyrings in _unsupportedKeyrings array', async () => {
const mockEncryptor = new MockEncryptor();
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
encryptor: mockEncryptor,
},
});
const encryptSpy = sinon.spy(mockEncryptor, 'encrypt');
const unsupportedKeyring = { type: 'DUMMY_KEYRING', data: {} };
keyringController.unsupportedKeyrings = [unsupportedKeyring];
await keyringController.persistAllKeyrings();
assert(keyringController.store.getState().vault, 'Vault is not set');
expect(encryptSpy.calledOnce).toBe(true);
expect(encryptSpy.getCalls()[0]?.args[1]).toHaveLength(2);
expect(encryptSpy.getCalls()[0]?.args[1]).toContain(unsupportedKeyring);
});
describe('when `cacheEncryptionKey` is enabled', () => {
describe('when `encryptionKey` is set', () => {
it('should save an up to date encryption salt to the `memStore`', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
cacheEncryptionKey: true,
},
});
const vaultEncryptionKey = '🔑';
const vaultEncryptionSalt = '🧂';
const vault = JSON.stringify({ salt: vaultEncryptionSalt });
keyringController.store.updateState({ vault });
await keyringController.unlockKeyrings(
undefined,
vaultEncryptionKey,
vaultEncryptionSalt,
);
expect(keyringController.memStore.getState().encryptionKey).toBe(
vaultEncryptionKey,
);
expect(keyringController.memStore.getState().encryptionSalt).toBe(
vaultEncryptionSalt,
);
const response = await keyringController.persistAllKeyrings();
expect(response).toBe(true);
expect(keyringController.memStore.getState().encryptionKey).toBe(
vaultEncryptionKey,
);
expect(keyringController.memStore.getState().encryptionSalt).toBe(
vaultEncryptionSalt,
);
});
});
describe('when `encryptionKey` is not set and `password` is set', () => {
it('should save an up to date encryption salt to the `memStore` when `password` is set through `createNewVaultAndKeychain`', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
cacheEncryptionKey: true,
},
});
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
});
deleteEncryptionKeyAndSalt(keyringController);
const response = await keyringController.persistAllKeyrings();
expect(response).toBe(true);
expect(keyringController.memStore.getState().encryptionKey).toBe(
MOCK_HARDCODED_KEY,
);
expect(keyringController.memStore.getState().encryptionSalt).toBe(
MOCK_ENCRYPTION_SALT,
);
});
it('should save an up to date encryption salt to the `memStore` when `password` is set through `submitPassword`', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
cacheEncryptionKey: true,
},
});
await keyringController.submitPassword(PASSWORD);
deleteEncryptionKeyAndSalt(keyringController);
const response = await keyringController.persistAllKeyrings();
expect(response).toBe(true);
expect(keyringController.memStore.getState().encryptionKey).toBe(
MOCK_HARDCODED_KEY,
);
expect(keyringController.memStore.getState().encryptionSalt).toBe(
MOCK_ENCRYPTION_SALT,
);
});
});
});
it('should add an `encryptionSalt` to the `memStore` when a vault is restored', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
cacheEncryptionKey: true,
},
});
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic: walletOneSeedWords,
numberOfAccounts: 1,
},
});
const finalMemStore = keyringController.memStore.getState();
expect(finalMemStore.encryptionKey).toBe(MOCK_HARDCODED_KEY);
expect(finalMemStore.encryptionSalt).toBe(MOCK_ENCRYPTION_SALT);
});
});
describe('createNewVaultWithKeyring', () => {
it('should create a new vault with a HD keyring', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
keyringController.store.putState({});
assert(!keyringController.store.getState().vault, 'no previous vault');
const newVault = await keyringController.createNewVaultWithKeyring(
PASSWORD,
{
type: KeyringType.HD,
},
);
const { vault } = keyringController.store.getState();
expect(vault).toStrictEqual(expect.stringMatching('.+'));
expect(typeof newVault).toBe('object');
});
it('should create a new vault with a simple keyring', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
keyringController.store.putState({});
assert(!keyringController.store.getState().vault, 'no previous vault');
const newVault = await keyringController.createNewVaultWithKeyring(
PASSWORD,
{
type: KeyringType.Simple,
opts: walletOnePrivateKey,
},
);
const { vault } = keyringController.store.getState();
expect(vault).toStrictEqual(expect.stringMatching('.+'));
expect(typeof newVault).toBe('object');
const accounts = await keyringController.getAccounts();
expect(accounts).toHaveLength(1);
expect(accounts[0]).toBe(walletOneAddresses[0]);
});
it('should unlock the vault', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
keyringController.store.putState({});
assert(!keyringController.store.getState().vault, 'no previous vault');
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
});
const { isUnlocked } = keyringController.memStore.getState();
expect(isUnlocked).toBe(true);
});
it('should encrypt keyrings with the correct password each time they are persisted', async () => {
const mockEncryptor = new MockEncryptor();
const encryptSpy = sinon.spy(mockEncryptor, 'encrypt');
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
encryptor: mockEncryptor,
},
});
keyringController.store.putState({});
assert(!keyringController.store.getState().vault, 'no previous vault');
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
});
const { vault } = keyringController.store.getState();
// eslint-disable-next-line jest/no-restricted-matchers
expect(vault).toBeTruthy();
encryptSpy.args.forEach(([actualPassword]) => {
expect(actualPassword).toBe(PASSWORD);
});
});
it('should throw error if accounts are not generated correctly', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
jest
.spyOn(HdKeyring.prototype, 'getAccounts')
.mockImplementation(async () => Promise.resolve([]));
await expect(async () =>
keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
}),
).rejects.toThrow(KeyringControllerError.NoFirstAccount);
});
describe('when `cacheEncryptionKey` is enabled', () => {
it('should add an `encryptionSalt` to the `memStore` when a new vault is created', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
cacheEncryptionKey: true,
},
});
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
});
const finalMemStore = keyringController.memStore.getState();
expect(finalMemStore.encryptionKey).toBe(MOCK_HARDCODED_KEY);
expect(finalMemStore.encryptionSalt).toBe(MOCK_ENCRYPTION_SALT);
});
});
it('clears old keyrings and creates a one', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const initialAccounts = await keyringController.getAccounts();
expect(initialAccounts).toHaveLength(1);
await keyringController.addNewKeyring(KeyringType.HD);
const allAccounts = await keyringController.getAccounts();
expect(allAccounts).toHaveLength(2);
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic: walletOneSeedWords,
numberOfAccounts: 1,
},
});
const allAccountsAfter = await keyringController.getAccounts();
expect(allAccountsAfter).toHaveLength(1);
expect(allAccountsAfter[0]).toBe(walletOneAddresses[0]);
});
it('throws error if argument password is not a string', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
await expect(async () =>
// @ts-expect-error Missing other required permission types.
keyringController.createNewVaultWithKeyring(12, {
type: KeyringType.HD,
opts: {
mnemonic: walletTwoSeedWords,
numberOfAccounts: 1,
},
}),
).rejects.toThrow('KeyringController - Password must be of type string.');
});
it('throws error if mnemonic passed is invalid', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
await expect(async () =>
keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic:
'test test test palace city barely security section midnight wealth south deer',
numberOfAccounts: 1,
},
}),
).rejects.toThrow(
'Eth-Hd-Keyring: Invalid secret recovery phrase provided',
);
await expect(async () =>
keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic: '1234',
numberOfAccounts: 1,
},
}),
).rejects.toThrow(
'Eth-Hd-Keyring: Invalid secret recovery phrase provided',
);
});
it('accepts mnemonic passed as type array of numbers', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const allAccountsBefore = await keyringController.getAccounts();
expect(allAccountsBefore[0]).not.toBe(walletTwoAddresses[0]);
const mnemonicAsArrayOfNumbers = Array.from(
Buffer.from(walletTwoSeedWords).values(),
);
await keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic: mnemonicAsArrayOfNumbers,
numberOfAccounts: 1,
},
});
const allAccountsAfter = await keyringController.getAccounts();
expect(allAccountsAfter).toHaveLength(1);
expect(allAccountsAfter[0]).toBe(walletTwoAddresses[0]);
});
it('throws error if accounts are not created properly', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
jest
.spyOn(HdKeyring.prototype, 'getAccounts')
.mockImplementation(async () => Promise.resolve([]));
await expect(async () =>
keyringController.createNewVaultWithKeyring(PASSWORD, {
type: KeyringType.HD,
opts: {
mnemonic: walletTwoSeedWords,
numberOfAccounts: 1,
},
}),
).rejects.toThrow('KeyringController - First Account not found.');
});
});
describe('addNewKeyring', () => {
it('should add simple key pair', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const privateKey =
'c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3';
const previousAccounts = await keyringController.getAccounts();
const keyring = await keyringController.addNewKeyring(
KeyringType.Simple,
[privateKey],
);
const keyringAccounts = await keyring?.getAccounts();
const expectedKeyringAccounts = [
'0x627306090abab3a6e1400e9345bc60c78a8bef57',
];
expect(keyringAccounts).toStrictEqual(expectedKeyringAccounts);
const allAccounts = await keyringController.getAccounts();
const expectedAllAccounts = previousAccounts.concat(
expectedKeyringAccounts,
);
expect(allAccounts).toStrictEqual(expectedAllAccounts);
});
it('should add HD Key Tree without mnemonic passed as an argument', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const previousAllAccounts = await keyringController.getAccounts();
expect(previousAllAccounts).toHaveLength(1);
const keyring = await keyringController.addNewKeyring(KeyringType.HD);
const keyringAccounts = await keyring?.getAccounts();
expect(keyringAccounts).toHaveLength(1);
const allAccounts = await keyringController.getAccounts();
expect(allAccounts).toHaveLength(2);
});
it('should add HD Key Tree with mnemonic passed as an argument', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const previousAllAccounts = await keyringController.getAccounts();
expect(previousAllAccounts).toHaveLength(1);
const keyring = await keyringController.addNewKeyring(KeyringType.HD, {
numberOfAccounts: 2,
mnemonic: walletTwoSeedWords,
});
const keyringAccounts = await keyring?.getAccounts();
expect(keyringAccounts).toHaveLength(2);
expect(keyringAccounts?.[0]).toStrictEqual(walletTwoAddresses[0]);
expect(keyringAccounts?.[1]).toStrictEqual(walletTwoAddresses[1]);
const allAccounts = await keyringController.getAccounts();
expect(allAccounts).toHaveLength(3);
});
it('should add keyring that expects undefined serialized state', async () => {
let deserializedSpy = sinon.spy();
const mockKeyringBuilder = () => {
const keyring = new KeyringMockWithInit();
deserializedSpy = sinon.spy(keyring, 'deserialize');
return keyring;
};
mockKeyringBuilder.type = 'Mock Keyring';
const keyringController = await initializeKeyringController({
constructorOptions: {
keyringBuilders: [mockKeyringBuilder],
},
password: PASSWORD,
});
await keyringController.addNewKeyring('Mock Keyring');
expect(deserializedSpy.callCount).toBe(1);
expect(deserializedSpy.calledWith(undefined)).toBe(true);
});
it('should call init method if available', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
keyringBuilders: [keyringBuilderFactory(KeyringMockWithInit)],
},
});
const initSpy = sinon.spy(KeyringMockWithInit.prototype, 'init');
const keyring = await keyringController.addNewKeyring(
'Keyring Mock With Init',
);
expect(keyring).toBeInstanceOf(KeyringMockWithInit);
sinon.assert.calledOnce(initSpy);
});
it('should add HD Key Tree when addAccounts is asynchronous', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const originalAccAccounts = HdKeyring.prototype.addAccounts;
sinon.stub(HdKeyring.prototype, 'addAccounts').callsFake(async () => {
return new Promise((resolve) => {
setImmediate(() => {
resolve(originalAccAccounts.bind(this)());
});
});
});
sinon.stub(HdKeyring.prototype, 'deserialize').callsFake(async () => {
return new Promise<void>((resolve) => {
setImmediate(() => {
resolve();
});
});
});
sinon
.stub(HdKeyring.prototype, 'getAccounts')
.callsFake(() => ['mock account']);
const keyring = await keyringController.addNewKeyring(KeyringType.HD, {
mnemonic: 'mock mnemonic',
});
const keyringAccounts = await keyring?.getAccounts();
expect(keyringAccounts).toHaveLength(1);
});
});
describe('restoreKeyring', () => {
it(`should pass a keyring's serialized data back to the correct type.`, async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const mockSerialized = {
type: 'HD Key Tree',
data: {
mnemonic: walletOneSeedWords,
numberOfAccounts: 1,
},
};
const keyring = await keyringController.restoreKeyring(mockSerialized);
// eslint-disable-next-line no-unsafe-optional-chaining
// @ts-expect-error this value should never be undefined in this specific context.
const { numberOfAccounts } = await keyring.serialize();
expect(numberOfAccounts).toBe(1);
const accounts = await keyring?.getAccounts();
expect(accounts?.[0]).toBe(walletOneAddresses[0]);
});
it('should return undefined if keyring type is not supported.', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const unsupportedKeyring = { type: 'Ledger Keyring', data: 'DUMMY' };
const keyring = await keyringController.restoreKeyring(
unsupportedKeyring,
);
expect(keyring).toBeUndefined();
});
});
describe('getAccounts', () => {
it('returns the result of getAccounts for each keyring', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
keyringController.keyrings = [
{
// @ts-expect-error there's only a need to mock the getAccounts method for this test.
async getAccounts() {
return Promise.resolve([1, 2, 3]);
},
},
{
// @ts-expect-error there's only a need to mock the getAccounts method for this test.
async getAccounts() {
return Promise.resolve([4, 5, 6]);
},
},
];
const result = await keyringController.getAccounts();
expect(result).toStrictEqual([
'0x01',
'0x02',
'0x03',
'0x04',
'0x05',
'0x06',
]);
});
});
describe('removeAccount', () => {
it('removes an account from the corresponding keyring', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const account: { privateKey: string; publicKey: Hex } = {
privateKey:
'c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3',
publicKey: '0x627306090abab3a6e1400e9345bc60c78a8bef57',
};
const accountsBeforeAdding = await keyringController.getAccounts();
// Add a new keyring with one account
await keyringController.addNewKeyring(KeyringType.Simple, [
account.privateKey,
]);
expect(keyringController.keyrings).toHaveLength(2);
// remove that account that we just added
await keyringController.removeAccount(account.publicKey);
expect(keyringController.keyrings).toHaveLength(1);
// fetch accounts after removal
const result = await keyringController.getAccounts();
expect(result).toStrictEqual(accountsBeforeAdding);
});
it('removes the keyring if there are no accounts after removal', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
const account: { privateKey: string; publicKey: Hex } = {
privateKey:
'c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3',
publicKey: '0x627306090abab3a6e1400e9345bc60c78a8bef57',
};
// Add a new keyring with one account
await keyringController.addNewKeyring(KeyringType.Simple, [
account.privateKey,
]);
// We should have 2 keyrings
expect(keyringController.keyrings).toHaveLength(2);
// remove that account that we just added
await keyringController.removeAccount(account.publicKey);
// Check that the previous keyring with only one account
// was also removed after removing the account
expect(keyringController.keyrings).toHaveLength(1);
});
it('calls keyring optional destroy function', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
keyringBuilders: [keyringBuilderFactory(KeyringMockWithDestroy)],
},
});
const destroy = sinon.spy(KeyringMockWithDestroy.prototype, 'destroy');
const keyring = await keyringController.addNewKeyring(
'Keyring Mock With Destroy',
);
sinon.stub(keyringController, 'getKeyringForAccount').resolves(keyring);
await keyringController.removeAccount('0x0');
expect(destroy.calledOnce).toBe(true);
});
it('does not remove the keyring if there are accounts remaining after removing one from the keyring', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
// Add a new keyring with two accounts
await keyringController.addNewKeyring(KeyringType.HD, {
mnemonic: walletTwoSeedWords,
numberOfAccounts: 2,
});
// We should have 2 keyrings
expect(keyringController.keyrings).toHaveLength(2);
// remove one account from the keyring we just added
// @ts-expect-error this value should never be undefied
await keyringController.removeAccount(walletTwoAddresses[0]);
// Check that the newly added keyring was not removed after
// removing the account since it still has an account left
expect(keyringController.keyrings).toHaveLength(2);
});
it('throws an error if the keyring for the given account does not support account removal', async () => {
const mockAccount = '0x5aC6d462f054690A373Fabf8cc28E161003aEB19';
stubKeyringClassWithAccount(BaseKeyringMock, mockAccount);
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
keyringBuilders: [keyringBuilderFactory(BaseKeyringMock)],
},
});
await keyringController.addNewKeyring(BaseKeyringMock.type);
await expect(
keyringController.removeAccount(mockAccount),
).rejects.toThrow(KeyringControllerError.UnsupportedRemoveAccount);
});
});
describe('unlockKeyrings', () => {
it('returns the list of keyrings', async () => {
const keyringController = await initializeKeyringController({
password: PASSWORD,
});
await keyringController.setLocked();
const keyrings = await keyringController.unlockKeyrings(PASSWORD);
expect(keyrings).toHaveLength(1);
await Promise.all(
keyrings.map(async (keyring) => {
// @ts-expect-error numberOfAccounts mising in Json specification.
const { numberOfAccounts } = await keyring.serialize();
expect(numberOfAccounts).toBe(1);
}),
);
});
it('add serialized keyring to unsupportedKeyrings array if keyring type is not known', async () => {
const mockEncryptor = new MockEncryptor();
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
encryptor: mockEncryptor,
},
});
const unsupportedKeyrings = [{ type: 'Ledger Keyring', data: 'DUMMY' }];
await mockEncryptor.encrypt(PASSWORD, unsupportedKeyrings);
await keyringController.setLocked();
const keyrings = await keyringController.unlockKeyrings(PASSWORD);
expect(keyrings).toHaveLength(0);
expect(keyringController.unsupportedKeyrings).toStrictEqual(
unsupportedKeyrings,
);
});
it('should throw error if there is no vault', async () => {
const keyringController = new KeyringController({
cacheEncryptionKey: false,
});
await expect(async () =>
keyringController.unlockKeyrings(PASSWORD),
).rejects.toThrow(KeyringControllerError.VaultError);
});
it('should throw error if decrypted vault is not an array of serialized keyrings', async () => {
const mockEncryptor = new MockEncryptor();
sinon
.stub(mockEncryptor, 'decrypt')
.resolves('[{"foo": "not a valid keyring}]');
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
encryptor: mockEncryptor,
},
});
await expect(async () =>
keyringController.unlockKeyrings(PASSWORD),
).rejects.toThrow(KeyringControllerError.VaultDataError);
});
it('should throw error if decrypted vault includes an invalid keyring', async () => {
const mockEncryptor = new MockEncryptor();
sinon
.stub(mockEncryptor, 'decrypt')
.resolves([{ foo: 'not a valid keyring' }]);
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
encryptor: mockEncryptor,
},
});
await expect(async () =>
keyringController.unlockKeyrings(PASSWORD),
).rejects.toThrow(KeyringControllerError.VaultDataError);
});
describe('with old vault format', () => {
describe(`with cacheEncryptionKey = true and encryptionKey is unset`, () => {
it('should update the vault', async () => {
const mockEncryptor = new MockEncryptor();
const keyringController = await initializeKeyringController({
password: PASSWORD,
constructorOptions: {
cacheEncryptionKey: true,
encryptor: mockEncryptor,
},
});
deleteEncryptionKeyAndSalt(keyringController);
const initialVault = keyringController.store.getState().vault;
const mockEncryptionResult = {
data: '0x1234',
iv: 'an iv',
};
sinon.stub(mockEncryptor, 'isVaultUpdated').returns(false);
sinon
.stub(mockEncryptor, 'encryptWithKey')
.resolves(mockEncryptionResult);
await keyringController.unlockKeyrings(PASSWORD);
const updatedVault = keyringController.store.getState().vault;
expect(initialVault).not.toBe(updatedVault);
expect(updatedVault).toBe(
JSON.stringify({
...mockEncryptionResult,
salt: MOCK_ENCRYPTION_SALT,
}),
);