-
-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathKeyringController.test.ts
More file actions
4384 lines (3947 loc) · 156 KB
/
KeyringController.test.ts
File metadata and controls
4384 lines (3947 loc) · 156 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 { Chain, Common, Hardfork } from '@ethereumjs/common';
import type { TypedTxData } from '@ethereumjs/tx';
import { TransactionFactory } from '@ethereumjs/tx';
import { CryptoHDKey, ETHSignature } from '@keystonehq/bc-ur-registry-eth';
import { MetaMaskKeyring as QRKeyring } from '@keystonehq/metamask-airgapped-keyring';
import { Messenger } from '@metamask/base-controller';
import { HdKeyring } from '@metamask/eth-hd-keyring';
import {
normalize,
recoverPersonalSignature,
recoverTypedSignature,
SignTypedDataVersion,
encrypt,
recoverEIP7702Authorization,
} from '@metamask/eth-sig-util';
import SimpleKeyring from '@metamask/eth-simple-keyring';
import type { EthKeyring } from '@metamask/keyring-internal-api';
import type { KeyringClass } from '@metamask/keyring-utils';
import { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';
import { bytesToHex, isValidHexAddress, type Hex } from '@metamask/utils';
import * as sinon from 'sinon';
import * as uuid from 'uuid';
import { KeyringControllerError } from './constants';
import type {
KeyringControllerEvents,
KeyringControllerMessenger,
KeyringControllerState,
KeyringControllerOptions,
KeyringControllerActions,
} from './KeyringController';
import {
AccountImportStrategy,
KeyringController,
KeyringTypes,
isCustodyKeyring,
keyringBuilderFactory,
} from './KeyringController';
import MockEncryptor, {
MOCK_ENCRYPTION_KEY,
} from '../tests/mocks/mockEncryptor';
import { MockErc4337Keyring } from '../tests/mocks/mockErc4337Keyring';
import { MockKeyring } from '../tests/mocks/mockKeyring';
import MockShallowGetAccountsKeyring from '../tests/mocks/mockShallowGetAccountsKeyring';
import { buildMockTransaction } from '../tests/mocks/mockTransaction';
jest.mock('uuid', () => {
return {
...jest.requireActual('uuid'),
v4: () => '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d',
};
});
const input =
'{"version":3,"id":"534e0199-53f6-41a9-a8fe-d504702ee5e8","address":"b97c80fab7a3793bbe746864db80d236f1345ea7",' +
'"crypto":{"ciphertext":"974fec42023c2d6340d9710863aa82a2961aa03b9d7e5dd19aa77ab4aab1f344",' +
'"cipherparams":{"iv":"eba107752a238d2dd26e543860dccec4"},"cipher":"aes-128-ctr","kdf":"scrypt",' +
'"kdfparams":{"dklen":32,"salt":"2a8894ff056db4cc1851e45390996dd26b075e5ceaf72c13ca4c202f94ca468a",' +
'"n":131072,"r":8,"p":1},"mac":"8bd084028ecb331275a76583d41fe0e1212825a6d155e904d1baf448d33e7150"}}';
const seedWords =
'puzzle seed penalty soldier say clay field arctic metal hen cage runway';
const uint8ArraySeed = new Uint8Array(
new Uint16Array(
seedWords.split(' ').map((word) => wordlist.indexOf(word)),
).buffer,
);
const privateKey =
'1e4e6a4c0c077f4ae8ddfbf372918e61dd0fb4a4cfa592cb16e7546d505e68fc';
const password = 'password123';
const commonConfig = { chain: Chain.Goerli, hardfork: Hardfork.Berlin };
describe('KeyringController', () => {
afterEach(() => {
sinon.restore();
jest.resetAllMocks();
});
describe('constructor', () => {
it('should use the default encryptor if none is provided', async () => {
expect(
() =>
new KeyringController({
messenger: buildKeyringControllerMessenger(),
cacheEncryptionKey: true,
}),
).not.toThrow();
});
it('should throw error if cacheEncryptionKey is true and encryptor does not support key export', () => {
expect(
() =>
// @ts-expect-error testing an invalid encryptor
new KeyringController({
messenger: buildKeyringControllerMessenger(),
cacheEncryptionKey: true,
encryptor: { encrypt: jest.fn(), decrypt: jest.fn() },
}),
).toThrow(KeyringControllerError.UnsupportedEncryptionKeyExport);
});
it('allows overwriting the built-in Simple keyring builder', async () => {
const mockSimpleKeyringBuilder =
// todo: keyring types are mismatched, this should be fixed in they keyrings themselves
// @ts-expect-error keyring types are mismatched
buildKeyringBuilderWithSpy(SimpleKeyring);
await withController(
{ keyringBuilders: [mockSimpleKeyringBuilder] },
async ({ controller }) => {
await controller.addNewKeyring(KeyringTypes.simple);
expect(mockSimpleKeyringBuilder).toHaveBeenCalledTimes(1);
},
);
});
it('allows overwriting the built-in HD keyring builder', async () => {
// todo: keyring types are mismatched, this should be fixed in they keyrings themselves
// @ts-expect-error keyring types are mismatched
const mockHdKeyringBuilder = buildKeyringBuilderWithSpy(HdKeyring);
await withController(
{ keyringBuilders: [mockHdKeyringBuilder] },
async () => {
// This is called as part of initializing the controller
// because the first keyring is assumed to always be an HD keyring
expect(mockHdKeyringBuilder).toHaveBeenCalledTimes(1);
},
);
});
});
describe('addNewAccount', () => {
describe('when accountCount is not provided', () => {
it('should add new account', async () => {
await withController(async ({ controller, initialState }) => {
const addedAccountAddress = await controller.addNewAccount();
expect(initialState.keyrings).toHaveLength(1);
expect(initialState.keyrings[0].accounts).not.toStrictEqual(
controller.state.keyrings[0].accounts,
);
expect(controller.state.keyrings[0].accounts).toHaveLength(2);
expect(initialState.keyrings[0].accounts).not.toContain(
addedAccountAddress,
);
expect(addedAccountAddress).toBe(
controller.state.keyrings[0].accounts[1],
);
});
});
});
describe('when accountCount is provided', () => {
it('should add new account if accountCount is in sequence', async () => {
await withController(async ({ controller, initialState }) => {
const addedAccountAddress = await controller.addNewAccount(
initialState.keyrings[0].accounts.length,
);
expect(initialState.keyrings).toHaveLength(1);
expect(initialState.keyrings[0].accounts).not.toStrictEqual(
controller.state.keyrings[0].accounts,
);
expect(controller.state.keyrings[0].accounts).toHaveLength(2);
expect(initialState.keyrings[0].accounts).not.toContain(
addedAccountAddress,
);
expect(addedAccountAddress).toBe(
controller.state.keyrings[0].accounts[1],
);
});
});
it('should throw an error if passed accountCount param is out of sequence', async () => {
await withController(async ({ controller, initialState }) => {
const accountCount = initialState.keyrings[0].accounts.length;
await expect(
controller.addNewAccount(accountCount + 1),
).rejects.toThrow('Account out of sequence');
});
});
it('should not add a new account if called twice with the same accountCount param', async () => {
await withController(async ({ controller, initialState }) => {
const accountCount = initialState.keyrings[0].accounts.length;
const firstAccountAdded =
await controller.addNewAccount(accountCount);
const secondAccountAdded =
await controller.addNewAccount(accountCount);
expect(firstAccountAdded).toBe(secondAccountAdded);
expect(controller.state.keyrings[0].accounts).toHaveLength(
accountCount + 1,
);
});
});
it('should throw an error if there is no primary keyring', async () => {
await withController(
{ skipVaultCreation: true, state: { vault: 'my vault' } },
async ({ controller, encryptor }) => {
jest
.spyOn(encryptor, 'decrypt')
.mockResolvedValueOnce([{ type: 'Unsupported', data: '' }]);
await controller.submitPassword('123');
await expect(controller.addNewAccount()).rejects.toThrow(
'No HD keyring found',
);
},
);
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller }) => {
await controller.setLocked();
await expect(controller.addNewAccount()).rejects.toThrow(
KeyringControllerError.ControllerLocked,
);
});
});
// Testing fix for bug #4157 {@link https://github.com/MetaMask/core/issues/4157}
it('should return an existing HD account if the accountCount is lower than oldAccounts', async () => {
const mockAddress = '0x123';
stubKeyringClassWithAccount(MockKeyring, mockAddress);
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockKeyring)] },
async ({ controller, initialState }) => {
await controller.addNewKeyring(MockKeyring.type);
// expect there to be two accounts, 1 from HD and 1 from MockKeyring
expect(await controller.getAccounts()).toHaveLength(2);
const accountCount = initialState.keyrings[0].accounts.length;
// We add a new account for "index 1" (not existing yet)
const firstAccountAdded =
await controller.addNewAccount(accountCount);
// Adding an account for an existing index will return the existing account's address
const secondAccountAdded =
await controller.addNewAccount(accountCount);
expect(firstAccountAdded).toBe(secondAccountAdded);
expect(controller.state.keyrings[0].accounts).toHaveLength(
accountCount + 1,
);
expect(await controller.getAccounts()).toHaveLength(3);
},
);
});
it('should throw instead of returning undefined', async () => {
await withController(async ({ controller }) => {
jest.spyOn(controller, 'getKeyringsByType').mockReturnValueOnce([
{
getAccounts: () => [undefined, undefined],
},
]);
await expect(controller.addNewAccount(1)).rejects.toThrow(
"Can't find account at index 1",
);
});
});
});
describe('addNewAccountForKeyring', () => {
describe('when accountCount is not provided', () => {
it('should add new account', async () => {
await withController(async ({ controller, initialState }) => {
const [primaryKeyring] = controller.getKeyringsByType(
KeyringTypes.hd,
) as EthKeyring[];
const addedAccountAddress =
await controller.addNewAccountForKeyring(primaryKeyring);
expect(initialState.keyrings).toHaveLength(1);
expect(initialState.keyrings[0].accounts).not.toStrictEqual(
controller.state.keyrings[0].accounts,
);
expect(controller.state.keyrings[0].accounts).toHaveLength(2);
expect(initialState.keyrings[0].accounts).not.toContain(
addedAccountAddress,
);
expect(addedAccountAddress).toBe(
controller.state.keyrings[0].accounts[1],
);
});
});
it('should not throw when `keyring.getAccounts()` returns a shallow copy', async () => {
await withController(
{
keyringBuilders: [
keyringBuilderFactory(MockShallowGetAccountsKeyring),
],
},
async ({ controller }) => {
await controller.addNewKeyring(MockShallowGetAccountsKeyring.type);
// TODO: This is a temporary workaround while `addNewAccountForKeyring` is not
// removed.
const mockKeyring = controller.getKeyringsByType(
MockShallowGetAccountsKeyring.type,
)[0] as EthKeyring;
const addedAccountAddress =
await controller.addNewAccountForKeyring(mockKeyring);
expect(controller.state.keyrings).toHaveLength(2);
expect(controller.state.keyrings[1].accounts).toHaveLength(1);
expect(addedAccountAddress).toBe(
controller.state.keyrings[1].accounts[0],
);
},
);
});
});
describe('when accountCount is provided', () => {
it('should add new account if accountCount is in sequence', async () => {
await withController(async ({ controller, initialState }) => {
const [primaryKeyring] = controller.getKeyringsByType(
KeyringTypes.hd,
) as EthKeyring[];
const addedAccountAddress =
await controller.addNewAccountForKeyring(primaryKeyring);
expect(initialState.keyrings).toHaveLength(1);
expect(initialState.keyrings[0].accounts).not.toStrictEqual(
controller.state.keyrings[0].accounts,
);
expect(controller.state.keyrings[0].accounts).toHaveLength(2);
expect(initialState.keyrings[0].accounts).not.toContain(
addedAccountAddress,
);
expect(addedAccountAddress).toBe(
controller.state.keyrings[0].accounts[1],
);
});
});
it('should throw an error if passed accountCount param is out of sequence', async () => {
await withController(async ({ controller, initialState }) => {
const [primaryKeyring] = controller.getKeyringsByType(
KeyringTypes.hd,
) as EthKeyring[];
const accountCount = initialState.keyrings[0].accounts.length;
await expect(
controller.addNewAccountForKeyring(
primaryKeyring,
accountCount + 1,
),
).rejects.toThrow('Account out of sequence');
});
});
it('should not add a new account if called twice with the same accountCount param', async () => {
await withController(async ({ controller, initialState }) => {
const accountCount = initialState.keyrings[0].accounts.length;
const [primaryKeyring] = controller.getKeyringsByType(
KeyringTypes.hd,
) as EthKeyring[];
const firstAccountAdded = await controller.addNewAccountForKeyring(
primaryKeyring,
accountCount,
);
const secondAccountAdded = await controller.addNewAccountForKeyring(
primaryKeyring,
accountCount,
);
expect(firstAccountAdded).toBe(secondAccountAdded);
expect(controller.state.keyrings[0].accounts).toHaveLength(
accountCount + 1,
);
});
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller }) => {
const keyring = controller.getKeyringsByType(KeyringTypes.hd)[0];
await controller.setLocked();
await expect(
controller.addNewAccountForKeyring(keyring as EthKeyring),
).rejects.toThrow(KeyringControllerError.ControllerLocked);
});
});
});
describe('addNewKeyring', () => {
describe('when there is a builder for the given type', () => {
it('should add new keyring', async () => {
await withController(async ({ controller, initialState }) => {
const initialKeyrings = initialState.keyrings;
await controller.addNewKeyring(KeyringTypes.simple);
expect(controller.state.keyrings).not.toStrictEqual(initialKeyrings);
expect(controller.state.keyrings).toHaveLength(2);
});
});
it('should return a readonly object as metadata', async () => {
await withController(async ({ controller }) => {
const newMetadata = await controller.addNewKeyring(KeyringTypes.hd);
expect(() => {
newMetadata.name = 'new name';
}).toThrow(/Cannot assign to read only property 'name'/u);
});
});
});
describe('when there is no builder for the given type', () => {
it('should throw error', async () => {
await withController(async ({ controller }) => {
await expect(controller.addNewKeyring('fake')).rejects.toThrow(
'KeyringController - No keyringBuilder found for keyring. Keyring type: fake',
);
});
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller }) => {
await controller.setLocked();
await expect(controller.addNewKeyring(KeyringTypes.hd)).rejects.toThrow(
KeyringControllerError.ControllerLocked,
);
});
});
});
describe('createNewVaultAndRestore', () => {
[false, true].map((cacheEncryptionKey) =>
describe(`when cacheEncryptionKey is ${cacheEncryptionKey}`, () => {
it('should create new vault and restore', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller, initialState }) => {
const initialVault = controller.state.vault;
const initialKeyringsMetadata = controller.state.keyringsMetadata;
await controller.createNewVaultAndRestore(
password,
uint8ArraySeed,
);
expect(controller.state).not.toBe(initialState);
expect(controller.state.vault).toBeDefined();
expect(controller.state.vault).toStrictEqual(initialVault);
expect(controller.state.keyringsMetadata).toHaveLength(
initialKeyringsMetadata.length,
);
// new keyring metadata should be generated
expect(controller.state.keyringsMetadata).not.toStrictEqual(
initialKeyringsMetadata,
);
},
);
});
it('should call encryptor.encrypt with the same keyrings if old seedWord is used', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller, encryptor }) => {
const encryptSpy = jest.spyOn(encryptor, 'encrypt');
const serializedKeyring = await controller.withKeyring(
{ type: 'HD Key Tree' },
async ({ keyring }) => keyring.serialize(),
);
const currentSeedWord =
await controller.exportSeedPhrase(password);
await controller.createNewVaultAndRestore(
password,
currentSeedWord,
);
expect(encryptSpy).toHaveBeenCalledWith(password, [
{
data: serializedKeyring,
type: 'HD Key Tree',
},
]);
},
);
});
it('should throw error if creating new vault and restore without password', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller }) => {
await expect(
controller.createNewVaultAndRestore('', uint8ArraySeed),
).rejects.toThrow(KeyringControllerError.InvalidEmptyPassword);
},
);
});
it('should throw error if creating new vault and restoring without seed phrase', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller }) => {
await expect(
controller.createNewVaultAndRestore(
password,
// @ts-expect-error invalid seed phrase
'',
),
).rejects.toThrow(
'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',
);
},
);
});
cacheEncryptionKey &&
it('should set encryptionKey and encryptionSalt in state', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller }) => {
await controller.createNewVaultAndRestore(
password,
uint8ArraySeed,
);
expect(controller.state.encryptionKey).toBeDefined();
expect(controller.state.encryptionSalt).toBeDefined();
},
);
});
}),
);
});
describe('createNewVaultAndKeychain', () => {
[false, true].map((cacheEncryptionKey) =>
describe(`when cacheEncryptionKey is ${cacheEncryptionKey}`, () => {
describe('when there is no existing vault', () => {
it('should create new vault, mnemonic and keychain', async () => {
await withController(
{ cacheEncryptionKey, skipVaultCreation: true },
async ({ controller }) => {
await controller.createNewVaultAndKeychain(password);
const currentSeedPhrase =
await controller.exportSeedPhrase(password);
expect(currentSeedPhrase.length).toBeGreaterThan(0);
expect(
isValidHexAddress(
controller.state.keyrings[0].accounts[0] as Hex,
),
).toBe(true);
expect(controller.state.vault).toBeDefined();
},
);
});
cacheEncryptionKey &&
it('should set encryptionKey and encryptionSalt in state', async () => {
await withController(
{ cacheEncryptionKey, skipVaultCreation: true },
async ({ controller }) => {
await controller.createNewVaultAndKeychain(password);
expect(controller.state.encryptionKey).toBeDefined();
expect(controller.state.encryptionSalt).toBeDefined();
},
);
});
it('should set default state', async () => {
await withController(
{ cacheEncryptionKey, skipVaultCreation: true },
async ({ controller }) => {
await controller.createNewVaultAndKeychain(password);
expect(controller.state.keyrings).not.toStrictEqual([]);
const keyring = controller.state.keyrings[0];
expect(keyring.accounts).not.toStrictEqual([]);
expect(keyring.type).toBe('HD Key Tree');
expect(controller.state.vault).toBeDefined();
},
);
});
it('should throw error if password is of wrong type', async () => {
await withController(
{ cacheEncryptionKey, skipVaultCreation: true },
async ({ controller }) => {
await expect(
controller.createNewVaultAndKeychain(
// @ts-expect-error invalid password
123,
),
).rejects.toThrow(KeyringControllerError.WrongPasswordType);
},
);
});
it('should throw error if the first account is not found on the keyring', async () => {
jest.spyOn(HdKeyring.prototype, 'getAccounts').mockReturnValue([]);
await withController(
{ cacheEncryptionKey, skipVaultCreation: true },
async ({ controller }) => {
await expect(
controller.createNewVaultAndKeychain(password),
).rejects.toThrow(KeyringControllerError.NoFirstAccount);
},
);
});
!cacheEncryptionKey &&
it('should not set encryptionKey and encryptionSalt in state', async () => {
await withController(
{ skipVaultCreation: true },
async ({ controller }) => {
await controller.createNewVaultAndKeychain(password);
expect(controller.state).not.toHaveProperty('encryptionKey');
expect(controller.state).not.toHaveProperty('encryptionSalt');
},
);
});
});
describe('when there is an existing vault', () => {
it('should not create a new vault or keychain', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller, initialState }) => {
const initialSeedWord =
await controller.exportSeedPhrase(password);
expect(initialSeedWord).toBeDefined();
const initialVault = controller.state.vault;
await controller.createNewVaultAndKeychain(password);
const currentSeedWord =
await controller.exportSeedPhrase(password);
expect(initialState).toStrictEqual(controller.state);
expect(initialSeedWord).toBe(currentSeedWord);
expect(initialVault).toStrictEqual(controller.state.vault);
},
);
});
cacheEncryptionKey &&
it('should set encryptionKey and encryptionSalt in state', async () => {
await withController(
{ cacheEncryptionKey },
async ({ controller }) => {
await controller.setLocked();
expect(controller.state.encryptionKey).toBeUndefined();
expect(controller.state.encryptionSalt).toBeUndefined();
await controller.createNewVaultAndKeychain(password);
expect(controller.state.encryptionKey).toBeDefined();
expect(controller.state.encryptionSalt).toBeDefined();
},
);
});
!cacheEncryptionKey &&
it('should not set encryptionKey and encryptionSalt in state', async () => {
await withController(
{ skipVaultCreation: false, cacheEncryptionKey },
async ({ controller }) => {
await controller.createNewVaultAndKeychain(password);
expect(controller.state).not.toHaveProperty('encryptionKey');
expect(controller.state).not.toHaveProperty('encryptionSalt');
},
);
});
});
}),
);
});
describe('setLocked', () => {
it('should set locked correctly', async () => {
await withController(async ({ controller }) => {
expect(controller.isUnlocked()).toBe(true);
expect(controller.state.isUnlocked).toBe(true);
await controller.setLocked();
expect(controller.isUnlocked()).toBe(false);
expect(controller.state.isUnlocked).toBe(false);
expect(controller.state).not.toHaveProperty('encryptionKey');
expect(controller.state).not.toHaveProperty('encryptionSalt');
});
});
it('should emit KeyringController:lock event', async () => {
await withController(async ({ controller, messenger }) => {
const listener = sinon.spy();
messenger.subscribe('KeyringController:lock', listener);
await controller.setLocked();
expect(listener.called).toBe(true);
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller }) => {
await controller.setLocked();
await expect(controller.setLocked()).rejects.toThrow(
KeyringControllerError.ControllerLocked,
);
});
});
});
describe('exportSeedPhrase', () => {
describe('when mnemonic is not exportable', () => {
it('should throw error', async () => {
await withController(async ({ controller }) => {
const primaryKeyring = controller.getKeyringsByType(
KeyringTypes.hd,
)[0] as EthKeyring & { mnemonic: string };
primaryKeyring.mnemonic = '';
await expect(controller.exportSeedPhrase(password)).rejects.toThrow(
"Can't get mnemonic bytes from keyring",
);
});
});
});
describe('when mnemonic is exportable', () => {
describe('when correct password is provided', () => {
it('should export seed phrase without keyringId', async () => {
await withController(async ({ controller }) => {
const seed = await controller.exportSeedPhrase(password);
expect(seed).not.toBe('');
});
});
it('should export seed phrase with valid keyringId', async () => {
await withController(async ({ controller, initialState }) => {
const keyringId = initialState.keyringsMetadata[0].id;
const seed = await controller.exportSeedPhrase(password, keyringId);
expect(seed).not.toBe('');
});
});
it('should throw error if keyringId is invalid', async () => {
await withController(async ({ controller }) => {
await expect(
controller.exportSeedPhrase(password, 'invalid-id'),
).rejects.toThrow('Keyring not found');
});
});
});
describe('when wrong password is provided', () => {
it('should export seed phrase', async () => {
await withController(async ({ controller, encryptor }) => {
jest
.spyOn(encryptor, 'decrypt')
.mockRejectedValueOnce(new Error('Invalid password'));
await expect(controller.exportSeedPhrase('')).rejects.toThrow(
'Invalid password',
);
});
});
it('should throw invalid password error with valid keyringId', async () => {
await withController(
async ({ controller, encryptor, initialState }) => {
const keyringId = initialState.keyringsMetadata[0].id;
jest
.spyOn(encryptor, 'decrypt')
.mockRejectedValueOnce(new Error('Invalid password'));
await expect(
controller.exportSeedPhrase('', keyringId),
).rejects.toThrow('Invalid password');
},
);
});
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller }) => {
await controller.setLocked();
await expect(controller.exportSeedPhrase(password)).rejects.toThrow(
KeyringControllerError.ControllerLocked,
);
});
});
});
describe('exportAccount', () => {
describe('when the keyring for the given address supports exportAccount', () => {
describe('when correct password is provided', () => {
describe('when correct account is provided', () => {
it('should export account', async () => {
await withController(async ({ controller, initialState }) => {
const account = initialState.keyrings[0].accounts[0];
const newPrivateKey = await controller.exportAccount(
password,
account,
);
expect(newPrivateKey).not.toBe('');
});
});
});
describe('when wrong account is provided', () => {
it('should throw error', async () => {
await withController(async ({ controller }) => {
await expect(
controller.exportAccount(password, ''),
).rejects.toThrow(
'KeyringController - No keyring found. Error info: There are keyrings, but none match the address',
);
});
});
});
});
describe('when wrong password is provided', () => {
it('should throw error', async () => {
await withController(async ({ controller, encryptor }) => {
jest
.spyOn(encryptor, 'decrypt')
.mockRejectedValueOnce(new Error('Invalid password'));
await expect(controller.exportSeedPhrase('')).rejects.toThrow(
'Invalid password',
);
});
});
});
});
describe('when the keyring for the given address does not support exportAccount', () => {
it('should throw error', async () => {
const address = '0x5AC6D462f054690a373FABF8CC28e161003aEB19';
stubKeyringClassWithAccount(MockKeyring, address);
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockKeyring)] },
async ({ controller }) => {
await controller.addNewKeyring(MockKeyring.type);
await expect(
controller.exportAccount(password, address),
).rejects.toThrow(KeyringControllerError.UnsupportedExportAccount);
},
);
});
});
});
describe('getAccounts', () => {
it('should get accounts', async () => {
await withController(async ({ controller, initialState }) => {
const initialAccount = initialState.keyrings[0].accounts;
const accounts = await controller.getAccounts();
expect(accounts).toStrictEqual(initialAccount);
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller }) => {
await controller.setLocked();
await expect(controller.getAccounts()).rejects.toThrow(
KeyringControllerError.ControllerLocked,
);
});
});
});
describe('getEncryptionPublicKey', () => {
describe('when the keyring for the given address supports getEncryptionPublicKey', () => {
it('should return the correct encryption public key', async () => {
await withController(async ({ controller }) => {
const importedAccountAddress =
await controller.importAccountWithStrategy(
AccountImportStrategy.privateKey,
[privateKey],
);
const encryptionPublicKey = await controller.getEncryptionPublicKey(
importedAccountAddress,
);
expect(encryptionPublicKey).toBe(
'ZfKqt4HSy4tt9/WvqP3QrnzbIS04cnV//BhksKbLgVA=',
);
});
});
});
describe('when the keyring for the given address does not support getEncryptionPublicKey', () => {
it('should throw error', async () => {
const address = '0x5AC6D462f054690a373FABF8CC28e161003aEB19';
stubKeyringClassWithAccount(MockKeyring, address);
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockKeyring)] },
async ({ controller }) => {
await controller.addNewKeyring(MockKeyring.type);
await expect(
controller.getEncryptionPublicKey(address),
).rejects.toThrow(
KeyringControllerError.UnsupportedGetEncryptionPublicKey,
);
},
);
});
});
it('should throw error when the controller is locked', async () => {
await withController(async ({ controller, initialState }) => {
await controller.setLocked();
await expect(
controller.getEncryptionPublicKey(
initialState.keyrings[0].accounts[0],
),
).rejects.toThrow(KeyringControllerError.ControllerLocked);
});
});
});
describe('decryptMessage', () => {
describe('when the keyring for the given address supports decryptMessage', () => {
it('should successfully decrypt a message with valid parameters and return the raw decryption result', async () => {
await withController(async ({ controller }) => {
const importedAccountAddress =
await controller.importAccountWithStrategy(
AccountImportStrategy.privateKey,
[privateKey],
);
const message = 'Hello, encrypted world!';
const encryptedMessage = encrypt({
publicKey: await controller.getEncryptionPublicKey(
importedAccountAddress,
),
data: message,
version: 'x25519-xsalsa20-poly1305',
});
const messageParams = {
from: importedAccountAddress,
data: encryptedMessage,
};
const result = await controller.decryptMessage(messageParams);
expect(result).toBe(message);
});
});
it("should throw an error if the 'from' parameter is not a valid account address", async () => {
await withController(async ({ controller }) => {
const messageParams = {
from: 'invalid address',
data: {
version: '1.0',
nonce: '123456',
ephemPublicKey: '0xabcdef1234567890',
ciphertext: '0xabcdef1234567890',
},
};
await expect(
controller.decryptMessage(messageParams),
).rejects.toThrow(
'KeyringController - No keyring found. Error info: There are keyrings, but none match the address',
);
});
});
});
describe('when the keyring for the given address does not support decryptMessage', () => {
it('should throw error', async () => {
const address = '0x5AC6D462f054690a373FABF8CC28e161003aEB19';
stubKeyringClassWithAccount(MockKeyring, address);
await withController(
{ keyringBuilders: [keyringBuilderFactory(MockKeyring)] },
async ({ controller }) => {
await controller.addNewKeyring(MockKeyring.type);
await expect(
controller.decryptMessage({
from: address,
data: {
version: '1.0',
nonce: '123456',
ephemPublicKey: '0xabcdef1234567890',
ciphertext: '0xabcdef1234567890',
},
}),
).rejects.toThrow(KeyringControllerError.UnsupportedDecryptMessage);
},
);
});
});