-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathKeyringController.ts
2470 lines (2194 loc) · 76.4 KB
/
KeyringController.ts
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 type { TxData, TypedTransaction } from '@ethereumjs/tx';
import { isValidPrivate, toBuffer, getBinarySize } from '@ethereumjs/util';
import type {
MetaMaskKeyring as QRKeyring,
IKeyringState as IQRKeyringState,
} from '@keystonehq/metamask-airgapped-keyring';
import type { RestrictedControllerMessenger } from '@metamask/base-controller';
import { BaseController } from '@metamask/base-controller';
import * as encryptorUtils from '@metamask/browser-passworder';
import HDKeyring from '@metamask/eth-hd-keyring';
import { normalize as ethNormalize } from '@metamask/eth-sig-util';
import SimpleKeyring from '@metamask/eth-simple-keyring';
import type {
KeyringExecutionContext,
EthBaseTransaction,
EthBaseUserOperation,
EthUserOperation,
EthUserOperationPatch,
} from '@metamask/keyring-api';
import type { EthKeyring } from '@metamask/keyring-internal-api';
import type {
PersonalMessageParams,
TypedMessageParams,
} from '@metamask/message-manager';
import type {
Eip1024EncryptedData,
Hex,
Json,
KeyringClass,
} from '@metamask/utils';
import {
add0x,
assertIsStrictHexString,
bytesToHex,
hasProperty,
isObject,
isStrictHexString,
isValidHexAddress,
isValidJson,
remove0x,
} from '@metamask/utils';
import { Mutex } from 'async-mutex';
import type { MutexInterface } from 'async-mutex';
import Wallet, { thirdparty as importers } from 'ethereumjs-wallet';
import type { Patch } from 'immer';
import { KeyringControllerError } from './constants';
const name = 'KeyringController';
/**
* Available keyring types
*/
export enum KeyringTypes {
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
simple = 'Simple Key Pair',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
hd = 'HD Key Tree',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
qr = 'QR Hardware Wallet Device',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
trezor = 'Trezor Hardware',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
ledger = 'Ledger Hardware',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
lattice = 'Lattice Hardware',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
snap = 'Snap Keyring',
}
/**
* Custody keyring types are a special case, as they are not a single type
* but they all start with the prefix "Custody".
* @param keyringType - The type of the keyring.
* @returns Whether the keyring type is a custody keyring.
*/
export const isCustodyKeyring = (keyringType: string): boolean => {
return keyringType.startsWith('Custody');
};
/**
* @type KeyringControllerState
*
* Keyring controller state
* @property vault - Encrypted string representing keyring data
* @property isUnlocked - Whether vault is unlocked
* @property keyringTypes - Account types
* @property keyrings - Group of accounts
* @property encryptionKey - Keyring encryption key
* @property encryptionSalt - Keyring encryption salt
*/
export type KeyringControllerState = {
vault?: string;
isUnlocked: boolean;
keyrings: KeyringObject[];
encryptionKey?: string;
encryptionSalt?: string;
};
export type KeyringControllerMemState = Omit<
KeyringControllerState,
'vault' | 'encryptionKey' | 'encryptionSalt'
>;
export type KeyringControllerGetStateAction = {
type: `${typeof name}:getState`;
handler: () => KeyringControllerState;
};
export type KeyringControllerSignMessageAction = {
type: `${typeof name}:signMessage`;
handler: KeyringController['signMessage'];
};
export type KeyringControllerSignPersonalMessageAction = {
type: `${typeof name}:signPersonalMessage`;
handler: KeyringController['signPersonalMessage'];
};
export type KeyringControllerSignTypedMessageAction = {
type: `${typeof name}:signTypedMessage`;
handler: KeyringController['signTypedMessage'];
};
export type KeyringControllerDecryptMessageAction = {
type: `${typeof name}:decryptMessage`;
handler: KeyringController['decryptMessage'];
};
export type KeyringControllerGetEncryptionPublicKeyAction = {
type: `${typeof name}:getEncryptionPublicKey`;
handler: KeyringController['getEncryptionPublicKey'];
};
export type KeyringControllerGetKeyringsByTypeAction = {
type: `${typeof name}:getKeyringsByType`;
handler: KeyringController['getKeyringsByType'];
};
export type KeyringControllerGetKeyringForAccountAction = {
type: `${typeof name}:getKeyringForAccount`;
handler: KeyringController['getKeyringForAccount'];
};
export type KeyringControllerGetAccountsAction = {
type: `${typeof name}:getAccounts`;
handler: KeyringController['getAccounts'];
};
export type KeyringControllerPersistAllKeyringsAction = {
type: `${typeof name}:persistAllKeyrings`;
handler: KeyringController['persistAllKeyrings'];
};
export type KeyringControllerPrepareUserOperationAction = {
type: `${typeof name}:prepareUserOperation`;
handler: KeyringController['prepareUserOperation'];
};
export type KeyringControllerPatchUserOperationAction = {
type: `${typeof name}:patchUserOperation`;
handler: KeyringController['patchUserOperation'];
};
export type KeyringControllerSignUserOperationAction = {
type: `${typeof name}:signUserOperation`;
handler: KeyringController['signUserOperation'];
};
export type KeyringControllerAddNewAccountAction = {
type: `${typeof name}:addNewAccount`;
handler: KeyringController['addNewAccount'];
};
export type KeyringControllerStateChangeEvent = {
type: `${typeof name}:stateChange`;
payload: [KeyringControllerState, Patch[]];
};
export type KeyringControllerAccountRemovedEvent = {
type: `${typeof name}:accountRemoved`;
payload: [string];
};
export type KeyringControllerLockEvent = {
type: `${typeof name}:lock`;
payload: [];
};
export type KeyringControllerUnlockEvent = {
type: `${typeof name}:unlock`;
payload: [];
};
export type KeyringControllerQRKeyringStateChangeEvent = {
type: `${typeof name}:qrKeyringStateChange`;
payload: [ReturnType<IQRKeyringState['getState']>];
};
export type KeyringControllerActions =
| KeyringControllerGetStateAction
| KeyringControllerSignMessageAction
| KeyringControllerSignPersonalMessageAction
| KeyringControllerSignTypedMessageAction
| KeyringControllerDecryptMessageAction
| KeyringControllerGetEncryptionPublicKeyAction
| KeyringControllerGetAccountsAction
| KeyringControllerGetKeyringsByTypeAction
| KeyringControllerGetKeyringForAccountAction
| KeyringControllerPersistAllKeyringsAction
| KeyringControllerPrepareUserOperationAction
| KeyringControllerPatchUserOperationAction
| KeyringControllerSignUserOperationAction
| KeyringControllerAddNewAccountAction;
export type KeyringControllerEvents =
| KeyringControllerStateChangeEvent
| KeyringControllerLockEvent
| KeyringControllerUnlockEvent
| KeyringControllerAccountRemovedEvent
| KeyringControllerQRKeyringStateChangeEvent;
export type KeyringControllerMessenger = RestrictedControllerMessenger<
typeof name,
KeyringControllerActions,
KeyringControllerEvents,
never,
never
>;
export type KeyringControllerOptions = {
keyringBuilders?: { (): EthKeyring<Json>; type: string }[];
messenger: KeyringControllerMessenger;
state?: { vault?: string };
} & (
| {
cacheEncryptionKey: true;
encryptor?: ExportableKeyEncryptor;
}
| {
cacheEncryptionKey?: false;
encryptor?: GenericEncryptor | ExportableKeyEncryptor;
}
);
/**
* @type KeyringObject
*
* Keyring object to return in fullUpdate
* @property type - Keyring type
* @property accounts - Associated accounts
*/
export type KeyringObject = {
accounts: string[];
type: string;
};
/**
* A strategy for importing an account
*/
export enum AccountImportStrategy {
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
privateKey = 'privateKey',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
json = 'json',
}
/**
* The `signTypedMessage` version
*
* @see https://docs.metamask.io/guide/signing-data.html
*/
export enum SignTypedDataVersion {
V1 = 'V1',
V3 = 'V3',
V4 = 'V4',
}
/**
* A serialized keyring object.
*/
export type SerializedKeyring = {
type: string;
data: Json;
};
/**
* A generic encryptor interface that supports encrypting and decrypting
* serializable data with a password.
*/
export type GenericEncryptor = {
/**
* Encrypts the given object with the given password.
*
* @param password - The password to encrypt with.
* @param object - The object to encrypt.
* @returns The encrypted string.
*/
encrypt: (password: string, object: Json) => Promise<string>;
/**
* Decrypts the given encrypted string with the given password.
*
* @param password - The password to decrypt with.
* @param encryptedString - The encrypted string to decrypt.
* @returns The decrypted object.
*/
decrypt: (password: string, encryptedString: string) => Promise<unknown>;
/**
* Optional vault migration helper. Checks if the provided vault is up to date
* with the desired encryption algorithm.
*
* @param vault - The encrypted string to check.
* @param targetDerivationParams - The desired target derivation params.
* @returns The updated encrypted string.
*/
isVaultUpdated?: (
vault: string,
targetDerivationParams?: encryptorUtils.KeyDerivationOptions,
) => boolean;
};
/**
* An encryptor interface that supports encrypting and decrypting
* serializable data with a password, and exporting and importing keys.
*/
export type ExportableKeyEncryptor = GenericEncryptor & {
/**
* Encrypts the given object with the given encryption key.
*
* @param key - The encryption key to encrypt with.
* @param object - The object to encrypt.
* @returns The encryption result.
*/
encryptWithKey: (
key: unknown,
object: Json,
) => Promise<encryptorUtils.EncryptionResult>;
/**
* Encrypts the given object with the given password, and returns the
* encryption result and the exported key string.
*
* @param password - The password to encrypt with.
* @param object - The object to encrypt.
* @param salt - The optional salt to use for encryption.
* @returns The encrypted string and the exported key string.
*/
encryptWithDetail: (
password: string,
object: Json,
salt?: string,
) => Promise<encryptorUtils.DetailedEncryptionResult>;
/**
* Decrypts the given encrypted string with the given encryption key.
*
* @param key - The encryption key to decrypt with.
* @param encryptedString - The encrypted string to decrypt.
* @returns The decrypted object.
*/
decryptWithKey: (key: unknown, encryptedString: string) => Promise<unknown>;
/**
* Decrypts the given encrypted string with the given password, and returns
* the decrypted object and the salt and exported key string used for
* encryption.
*
* @param password - The password to decrypt with.
* @param encryptedString - The encrypted string to decrypt.
* @returns The decrypted object and the salt and exported key string used for
* encryption.
*/
decryptWithDetail: (
password: string,
encryptedString: string,
) => Promise<encryptorUtils.DetailedDecryptResult>;
/**
* Generates an encryption key from exported key string.
*
* @param key - The exported key string.
* @returns The encryption key.
*/
importKey: (key: string) => Promise<unknown>;
};
export type KeyringSelector =
| {
type: string;
index?: number;
}
| {
address: Hex;
};
/**
* A function executed within a mutually exclusive lock, with
* a mutex releaser in its option bag.
*
* @param releaseLock - A function to release the lock.
*/
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/naming-convention
type MutuallyExclusiveCallback<T> = ({
releaseLock,
}: {
releaseLock: MutexInterface.Releaser;
}) => Promise<T>;
/**
* Get builder function for `Keyring`
*
* Returns a builder function for `Keyring` with a `type` property.
*
* @param KeyringConstructor - The Keyring class for the builder.
* @returns A builder function for the given Keyring.
*/
export function keyringBuilderFactory(KeyringConstructor: KeyringClass<Json>) {
const builder = () => new KeyringConstructor();
builder.type = KeyringConstructor.type;
return builder;
}
const defaultKeyringBuilders = [
keyringBuilderFactory(SimpleKeyring),
keyringBuilderFactory(HDKeyring),
];
export const getDefaultKeyringState = (): KeyringControllerState => {
return {
isUnlocked: false,
keyrings: [],
};
};
/**
* Assert that the given keyring has an exportable
* mnemonic.
*
* @param keyring - The keyring to check
* @throws When the keyring does not have a mnemonic
*/
function assertHasUint8ArrayMnemonic(
keyring: EthKeyring<Json>,
): asserts keyring is EthKeyring<Json> & { mnemonic: Uint8Array } {
if (
!(
hasProperty(keyring, 'mnemonic') && keyring.mnemonic instanceof Uint8Array
)
) {
throw new Error("Can't get mnemonic bytes from keyring");
}
}
/**
* Assert that the provided encryptor supports
* encryption and encryption key export.
*
* @param encryptor - The encryptor to check.
* @throws If the encryptor does not support key encryption.
*/
function assertIsExportableKeyEncryptor(
encryptor: GenericEncryptor | ExportableKeyEncryptor,
): asserts encryptor is ExportableKeyEncryptor {
if (
!(
'importKey' in encryptor &&
typeof encryptor.importKey === 'function' &&
'decryptWithKey' in encryptor &&
typeof encryptor.decryptWithKey === 'function' &&
'encryptWithKey' in encryptor &&
typeof encryptor.encryptWithKey === 'function'
)
) {
throw new Error(KeyringControllerError.UnsupportedEncryptionKeyExport);
}
}
/**
* Assert that the provided password is a valid non-empty string.
*
* @param password - The password to check.
* @throws If the password is not a valid string.
*/
function assertIsValidPassword(password: unknown): asserts password is string {
if (typeof password !== 'string') {
throw new Error(KeyringControllerError.WrongPasswordType);
}
if (!password || !password.length) {
throw new Error(KeyringControllerError.InvalidEmptyPassword);
}
}
/**
* Checks if the provided value is a serialized keyrings array.
*
* @param array - The value to check.
* @returns True if the value is a serialized keyrings array.
*/
function isSerializedKeyringsArray(
array: unknown,
): array is SerializedKeyring[] {
return (
typeof array === 'object' &&
Array.isArray(array) &&
array.every((value) => value.type && isValidJson(value.data))
);
}
/**
* Display For Keyring
*
* Is used for adding the current keyrings to the state object.
*
* @param keyring - The keyring to display.
* @returns A keyring display object, with type and accounts properties.
*/
async function displayForKeyring(
keyring: EthKeyring<Json>,
): Promise<{ type: string; accounts: string[] }> {
const accounts = await keyring.getAccounts();
return {
type: keyring.type,
// Cast to `string[]` here is safe here because `accounts` has no nullish
// values, and `normalize` returns `string` unless given a nullish value
accounts: accounts.map(normalize) as string[],
};
}
/**
* Check if address is an ethereum address
*
* @param address - An address.
* @returns Returns true if the address is an ethereum one, false otherwise.
*/
function isEthAddress(address: string): boolean {
// We first check if it's a matching `Hex` string, so that is narrows down
// `address` as an `Hex` type, allowing us to use `isValidHexAddress`
return (
// NOTE: This function only checks for lowercased strings
isStrictHexString(address.toLowerCase()) &&
// This checks for lowercased addresses and checksum addresses too
isValidHexAddress(address as Hex)
);
}
/**
* Normalize ethereum or non-EVM address.
*
* @param address - Ethereum or non-EVM address.
* @returns The normalized address.
*/
function normalize(address: string): string | undefined {
// Since the `KeyringController` is only dealing with address, we have
// no other way to get the associated account type with this address. So we
// are down to check the actual address format for now
// TODO: Find a better way to not have those runtime checks based on the
// address value!
return isEthAddress(address) ? ethNormalize(address) : address;
}
/**
* Controller responsible for establishing and managing user identity.
*
* This class is a wrapper around the `eth-keyring-controller` package. The
* `eth-keyring-controller` manages the "vault", which is an encrypted store of private keys, and
* it manages the wallet "lock" state. This wrapper class has convenience methods for interacting
* with the internal keyring controller and handling certain complex operations that involve the
* keyrings.
*/
export class KeyringController extends BaseController<
typeof name,
KeyringControllerState,
KeyringControllerMessenger
> {
readonly #controllerOperationMutex = new Mutex();
readonly #vaultOperationMutex = new Mutex();
#keyringBuilders: { (): EthKeyring<Json>; type: string }[];
#keyrings: EthKeyring<Json>[];
#unsupportedKeyrings: SerializedKeyring[];
#password?: string;
#encryptor: GenericEncryptor | ExportableKeyEncryptor;
#cacheEncryptionKey: boolean;
#qrKeyringStateListener?: (
state: ReturnType<IQRKeyringState['getState']>,
) => void;
/**
* Creates a KeyringController instance.
*
* @param options - Initial options used to configure this controller
* @param options.encryptor - An optional object for defining encryption schemes.
* @param options.keyringBuilders - Set a new name for account.
* @param options.cacheEncryptionKey - Whether to cache or not encryption key.
* @param options.messenger - A restricted controller messenger.
* @param options.state - Initial state to set on this controller.
*/
constructor(options: KeyringControllerOptions) {
const {
encryptor = encryptorUtils,
keyringBuilders,
messenger,
state,
} = options;
super({
name,
metadata: {
vault: { persist: true, anonymous: false },
isUnlocked: { persist: false, anonymous: true },
keyrings: { persist: false, anonymous: false },
encryptionKey: { persist: false, anonymous: false },
encryptionSalt: { persist: false, anonymous: false },
},
messenger,
state: {
...getDefaultKeyringState(),
...state,
},
});
this.#keyringBuilders = keyringBuilders
? keyringBuilders.concat(defaultKeyringBuilders)
: defaultKeyringBuilders;
this.#encryptor = encryptor;
this.#keyrings = [];
this.#unsupportedKeyrings = [];
// This option allows the controller to cache an exported key
// for use in decrypting and encrypting data without password
this.#cacheEncryptionKey = Boolean(options.cacheEncryptionKey);
if (this.#cacheEncryptionKey) {
assertIsExportableKeyEncryptor(encryptor);
}
this.#registerMessageHandlers();
}
/**
* Adds a new account to the default (first) HD seed phrase keyring.
*
* @param accountCount - Number of accounts before adding a new one, used to
* make the method idempotent.
* @returns Promise resolving to the added account address.
*/
async addNewAccount(accountCount?: number): Promise<string> {
return this.#persistOrRollback(async () => {
const primaryKeyring = this.getKeyringsByType('HD Key Tree')[0] as
| EthKeyring<Json>
| undefined;
if (!primaryKeyring) {
throw new Error('No HD keyring found');
}
const oldAccounts = await primaryKeyring.getAccounts();
if (accountCount && oldAccounts.length !== accountCount) {
if (accountCount > oldAccounts.length) {
throw new Error('Account out of sequence');
}
// we return the account already existing at index `accountCount`
const existingAccount = oldAccounts[accountCount];
if (!existingAccount) {
throw new Error(`Can't find account at index ${accountCount}`);
}
return existingAccount;
}
const [addedAccountAddress] = await primaryKeyring.addAccounts(1);
await this.#verifySeedPhrase();
return addedAccountAddress;
});
}
/**
* Adds a new account to the specified keyring.
*
* @param keyring - Keyring to add the account to.
* @param accountCount - Number of accounts before adding a new one, used to make the method idempotent.
* @returns Promise resolving to the added account address
*/
async addNewAccountForKeyring(
keyring: EthKeyring<Json>,
accountCount?: number,
): Promise<Hex> {
// READ THIS CAREFULLY:
// We still uses `Hex` here, since we are not using this method when creating
// and account using a "Snap Keyring". This function assume the `keyring` is
// ethereum compatible, but "Snap Keyring" might not be.
return this.#persistOrRollback(async () => {
const oldAccounts = await this.#getAccountsFromKeyrings();
if (accountCount && oldAccounts.length !== accountCount) {
if (accountCount > oldAccounts.length) {
throw new Error('Account out of sequence');
}
const existingAccount = oldAccounts[accountCount];
assertIsStrictHexString(existingAccount);
return existingAccount;
}
await keyring.addAccounts(1);
const addedAccountAddress = (await this.#getAccountsFromKeyrings()).find(
(selectedAddress) => !oldAccounts.includes(selectedAddress),
);
assertIsStrictHexString(addedAccountAddress);
return addedAccountAddress;
});
}
/**
* Effectively the same as creating a new keychain then populating it
* using the given seed phrase.
*
* @param password - Password to unlock keychain.
* @param seed - A BIP39-compliant seed phrase as Uint8Array,
* either as a string or an array of UTF-8 bytes that represent the string.
* @returns Promise resolving when the operation ends successfully.
*/
async createNewVaultAndRestore(
password: string,
seed: Uint8Array,
): Promise<void> {
return this.#persistOrRollback(async () => {
assertIsValidPassword(password);
await this.#createNewVaultWithKeyring(password, {
type: KeyringTypes.hd,
opts: {
mnemonic: seed,
numberOfAccounts: 1,
},
});
});
}
/**
* Create a new vault and primary keyring.
*
* This only works if keyrings are empty. If there is a pre-existing unlocked vault, calling this will have no effect.
* If there is a pre-existing locked vault, it will be replaced.
*
* @param password - Password to unlock the new vault.
*/
async createNewVaultAndKeychain(password: string) {
return this.#persistOrRollback(async () => {
const accounts = await this.#getAccountsFromKeyrings();
if (!accounts.length) {
await this.#createNewVaultWithKeyring(password, {
type: KeyringTypes.hd,
});
}
});
}
/**
* Adds a new keyring of the given `type`.
*
* @param type - Keyring type name.
* @param opts - Keyring options.
* @throws If a builder for the given `type` does not exist.
* @returns Promise resolving to the added keyring.
*/
async addNewKeyring(
type: KeyringTypes | string,
opts?: unknown,
): Promise<unknown> {
if (type === KeyringTypes.qr) {
return this.getOrAddQRKeyring();
}
return this.#persistOrRollback(async () => this.#newKeyring(type, opts));
}
/**
* Method to verify a given password validity. Throws an
* error if the password is invalid.
*
* @param password - Password of the keyring.
*/
async verifyPassword(password: string) {
if (!this.state.vault) {
throw new Error(KeyringControllerError.VaultError);
}
await this.#encryptor.decrypt(password, this.state.vault);
}
/**
* Returns the status of the vault.
*
* @returns Boolean returning true if the vault is unlocked.
*/
isUnlocked(): boolean {
return this.state.isUnlocked;
}
/**
* Gets the seed phrase of the HD keyring.
*
* @param password - Password of the keyring.
* @returns Promise resolving to the seed phrase.
*/
async exportSeedPhrase(password: string): Promise<Uint8Array> {
await this.verifyPassword(password);
assertHasUint8ArrayMnemonic(this.#keyrings[0]);
return this.#keyrings[0].mnemonic;
}
/**
* Gets the private key from the keyring controlling an address.
*
* @param password - Password of the keyring.
* @param address - Address to export.
* @returns Promise resolving to the private key for an address.
*/
async exportAccount(password: string, address: string): Promise<string> {
await this.verifyPassword(password);
const keyring = (await this.getKeyringForAccount(
address,
)) as EthKeyring<Json>;
if (!keyring.exportAccount) {
throw new Error(KeyringControllerError.UnsupportedExportAccount);
}
return await keyring.exportAccount(normalize(address) as Hex);
}
/**
* Returns the public addresses of all accounts from every keyring.
*
* @returns A promise resolving to an array of addresses.
*/
async getAccounts(): Promise<string[]> {
return this.state.keyrings.reduce<string[]>(
(accounts, keyring) => accounts.concat(keyring.accounts),
[],
);
}
/**
* Get encryption public key.
*
* @param account - An account address.
* @param opts - Additional encryption options.
* @throws If the `account` does not exist or does not support the `getEncryptionPublicKey` method
* @returns Promise resolving to encyption public key of the `account` if one exists.
*/
async getEncryptionPublicKey(
account: string,
opts?: Record<string, unknown>,
): Promise<string> {
const address = ethNormalize(account) as Hex;
const keyring = (await this.getKeyringForAccount(
account,
)) as EthKeyring<Json>;
if (!keyring.getEncryptionPublicKey) {
throw new Error(KeyringControllerError.UnsupportedGetEncryptionPublicKey);
}
return await keyring.getEncryptionPublicKey(address, opts);
}
/**
* Attempts to decrypt the provided message parameters.
*
* @param messageParams - The decryption message parameters.
* @param messageParams.from - The address of the account you want to use to decrypt the message.
* @param messageParams.data - The encrypted data that you want to decrypt.
* @returns The raw decryption result.
*/
async decryptMessage(messageParams: {
from: string;
data: Eip1024EncryptedData;
}): Promise<string> {
const address = ethNormalize(messageParams.from) as Hex;
const keyring = (await this.getKeyringForAccount(
address,
)) as EthKeyring<Json>;
if (!keyring.decryptMessage) {
throw new Error(KeyringControllerError.UnsupportedDecryptMessage);
}
return keyring.decryptMessage(address, messageParams.data);
}
/**
* Returns the currently initialized keyring that manages
* the specified `address` if one exists.
*
* @deprecated Use of this method is discouraged as actions executed directly on
* keyrings are not being reflected in the KeyringController state and not
* persisted in the vault. Use `withKeyring` instead.
* @param account - An account address.
* @returns Promise resolving to keyring of the `account` if one exists.
*/
async getKeyringForAccount(account: string): Promise<unknown> {
const address = normalize(account);
const candidates = await Promise.all(
this.#keyrings.map(async (keyring) => {
return Promise.all([keyring, keyring.getAccounts()]);
}),
);
const winners = candidates.filter((candidate) => {
const accounts = candidate[1].map(normalize);
return accounts.includes(address);
});
if (winners.length && winners[0]?.length) {
return winners[0][0];
}
// Adding more info to the error
let errorInfo = '';
if (!candidates.length) {
errorInfo = 'There are no keyrings';
} else if (!winners.length) {
errorInfo = 'There are keyrings, but none match the address';
}
throw new Error(
`${KeyringControllerError.NoKeyring}. Error info: ${errorInfo}`,
);
}
/**
* Returns all keyrings of the given type.
*
* @deprecated Use of this method is discouraged as actions executed directly on
* keyrings are not being reflected in the KeyringController state and not
* persisted in the vault. Use `withKeyring` instead.
* @param type - Keyring type name.
* @returns An array of keyrings of the given type.
*/
getKeyringsByType(type: KeyringTypes | string): unknown[] {
return this.#keyrings.filter((keyring) => keyring.type === type);
}
/**
* Persist all serialized keyrings in the vault.
*
* @deprecated This method is being phased out in favor of `withKeyring`.
* @returns Promise resolving with `true` value when the
* operation completes.
*/
async persistAllKeyrings(): Promise<boolean> {
return this.#persistOrRollback(async () => true);
}
/**
* Imports an account with the specified import strategy.
*
* @param strategy - Import strategy name.
* @param args - Array of arguments to pass to the underlying stategy.
* @throws Will throw when passed an unrecognized strategy.
* @returns Promise resolving to the imported account address.
*/
async importAccountWithStrategy(
strategy: AccountImportStrategy,
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: any[],
): Promise<string> {
return this.#persistOrRollback(async () => {
let privateKey;
switch (strategy) {
case 'privateKey':
const [importedKey] = args;
if (!importedKey) {
throw new Error('Cannot import an empty key.');
}
const prefixed = add0x(importedKey);
let bufferedPrivateKey;
try {