@metamask/eth-hd-keyring 12.1.0 → 13.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +41 -1
- package/dist/hd-keyring-v2.cjs +180 -0
- package/dist/hd-keyring-v2.cjs.map +1 -0
- package/dist/hd-keyring-v2.d.cts +38 -0
- package/dist/hd-keyring-v2.d.cts.map +1 -0
- package/dist/hd-keyring-v2.d.mts +38 -0
- package/dist/hd-keyring-v2.d.mts.map +1 -0
- package/dist/hd-keyring-v2.mjs +176 -0
- package/dist/hd-keyring-v2.mjs.map +1 -0
- package/dist/hd-keyring.cjs +48 -44
- package/dist/hd-keyring.cjs.map +1 -1
- package/dist/hd-keyring.d.cts +26 -12
- package/dist/hd-keyring.d.cts.map +1 -1
- package/dist/hd-keyring.d.mts +26 -12
- package/dist/hd-keyring.d.mts.map +1 -1
- package/dist/hd-keyring.mjs +49 -45
- package/dist/hd-keyring.mjs.map +1 -1
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -2
package/dist/hd-keyring.mjs
CHANGED
|
@@ -9,11 +9,11 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _HdKeyring_instances,
|
|
12
|
+
var _HdKeyring_instances, _HdKeyring_walletMap, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressFromPublicKey, _HdKeyring_normalizeAddress, _HdKeyring_assertValidMnemonic;
|
|
13
13
|
import { privateToPublic, publicToAddress, ecsign } from "@ethereumjs/util";
|
|
14
14
|
import { concatSig, decrypt, getEncryptionPublicKey, normalize, personalSign, signEIP7702Authorization, signTypedData, SignTypedDataVersion } from "@metamask/eth-sig-util";
|
|
15
15
|
import { mnemonicToSeed } from "@metamask/key-tree";
|
|
16
|
-
import { generateMnemonic } from "@metamask/scure-bip39";
|
|
16
|
+
import { generateMnemonic, validateMnemonic } from "@metamask/scure-bip39";
|
|
17
17
|
import { wordlist } from "@metamask/scure-bip39/dist/wordlists/english.js";
|
|
18
18
|
import { add0x, assert, assertIsHexString, bigIntToBytes, bytesToHex, remove0x } from "@metamask/utils";
|
|
19
19
|
import { HDKey } from "ethereum-cryptography/hdkey";
|
|
@@ -41,7 +41,7 @@ export class HdKeyring {
|
|
|
41
41
|
_HdKeyring_instances.add(this);
|
|
42
42
|
this.type = type;
|
|
43
43
|
this.hdPath = hdPathString;
|
|
44
|
-
|
|
44
|
+
_HdKeyring_walletMap.set(this, new Map());
|
|
45
45
|
_HdKeyring_cryptographicFunctions.set(this, void 0);
|
|
46
46
|
// Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.
|
|
47
47
|
__classPrivateFieldSet(this, _HdKeyring_cryptographicFunctions, opts.cryptographicFunctions, "f");
|
|
@@ -67,7 +67,7 @@ export class HdKeyring {
|
|
|
67
67
|
}
|
|
68
68
|
return {
|
|
69
69
|
mnemonic,
|
|
70
|
-
numberOfAccounts: __classPrivateFieldGet(this,
|
|
70
|
+
numberOfAccounts: __classPrivateFieldGet(this, _HdKeyring_walletMap, "f").size,
|
|
71
71
|
hdPath: this.hdPath,
|
|
72
72
|
};
|
|
73
73
|
}
|
|
@@ -77,14 +77,14 @@ export class HdKeyring {
|
|
|
77
77
|
* @param opts - The serialized state of the keyring.
|
|
78
78
|
* @returns An empty array.
|
|
79
79
|
*/
|
|
80
|
-
async deserialize(opts
|
|
80
|
+
async deserialize(opts) {
|
|
81
81
|
if (opts.numberOfAccounts && !opts.mnemonic) {
|
|
82
82
|
throw new Error('Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic');
|
|
83
83
|
}
|
|
84
84
|
if (this.root) {
|
|
85
85
|
throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
|
|
86
86
|
}
|
|
87
|
-
|
|
87
|
+
__classPrivateFieldGet(this, _HdKeyring_walletMap, "f").clear();
|
|
88
88
|
this.mnemonic = null;
|
|
89
89
|
this.seed = null;
|
|
90
90
|
this.root = null;
|
|
@@ -93,9 +93,8 @@ export class HdKeyring {
|
|
|
93
93
|
await __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_initFromMnemonic).call(this, opts.mnemonic);
|
|
94
94
|
}
|
|
95
95
|
if (opts.numberOfAccounts) {
|
|
96
|
-
|
|
96
|
+
await this.addAccounts(opts.numberOfAccounts);
|
|
97
97
|
}
|
|
98
|
-
return [];
|
|
99
98
|
}
|
|
100
99
|
/**
|
|
101
100
|
* Add new accounts to the keyring. The accounts will be derived
|
|
@@ -108,29 +107,28 @@ export class HdKeyring {
|
|
|
108
107
|
if (!this.root) {
|
|
109
108
|
throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');
|
|
110
109
|
}
|
|
111
|
-
const oldLen = __classPrivateFieldGet(this,
|
|
112
|
-
const
|
|
110
|
+
const oldLen = __classPrivateFieldGet(this, _HdKeyring_walletMap, "f").size;
|
|
111
|
+
const newAddresses = [];
|
|
113
112
|
for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
__classPrivateFieldGet(this,
|
|
113
|
+
const hdKey = this.root.deriveChild(i);
|
|
114
|
+
assert(hdKey.publicKey, 'Expected public key to be set');
|
|
115
|
+
const address = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressFromPublicKey).call(this, hdKey.publicKey);
|
|
116
|
+
const walletData = {
|
|
117
|
+
hdKey,
|
|
118
|
+
address,
|
|
119
|
+
};
|
|
120
|
+
__classPrivateFieldGet(this, _HdKeyring_walletMap, "f").set(address, walletData);
|
|
121
|
+
newAddresses.push(address);
|
|
117
122
|
}
|
|
118
|
-
|
|
119
|
-
assert(wallet.publicKey, 'Expected public key to be set');
|
|
120
|
-
return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, wallet.publicKey);
|
|
121
|
-
});
|
|
122
|
-
return Promise.resolve(hexWallets);
|
|
123
|
+
return Promise.resolve(newAddresses);
|
|
123
124
|
}
|
|
124
125
|
/**
|
|
125
126
|
* Get the addresses of all accounts in the keyring.
|
|
126
127
|
*
|
|
127
128
|
* @returns The addresses of all accounts in the keyring.
|
|
128
129
|
*/
|
|
129
|
-
getAccounts() {
|
|
130
|
-
return __classPrivateFieldGet(this,
|
|
131
|
-
assert(wallet.publicKey, 'Expected public key to be set');
|
|
132
|
-
return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, wallet.publicKey);
|
|
133
|
-
});
|
|
130
|
+
async getAccounts() {
|
|
131
|
+
return Array.from(__classPrivateFieldGet(this, _HdKeyring_walletMap, "f").keys());
|
|
134
132
|
}
|
|
135
133
|
/**
|
|
136
134
|
* Get the public address of the account for the given app key origin.
|
|
@@ -231,20 +229,21 @@ export class HdKeyring {
|
|
|
231
229
|
* Sign a typed message using the private key of the specified account.
|
|
232
230
|
* This method is compatible with the `eth_signTypedData` RPC method.
|
|
233
231
|
*
|
|
234
|
-
* @param
|
|
235
|
-
* @param
|
|
236
|
-
* @param
|
|
232
|
+
* @param address - The address of the account.
|
|
233
|
+
* @param data - The typed data to sign.
|
|
234
|
+
* @param options - The options for signing the message.
|
|
237
235
|
* @returns The signature of the message.
|
|
238
236
|
*/
|
|
239
|
-
async signTypedData(
|
|
237
|
+
async signTypedData(address, data, options) {
|
|
238
|
+
let { version } = options ?? { version: SignTypedDataVersion.V1 };
|
|
240
239
|
// Treat invalid versions as "V1"
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
const privateKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this,
|
|
240
|
+
if (!version || !Object.keys(SignTypedDataVersion).includes(version)) {
|
|
241
|
+
version = SignTypedDataVersion.V1;
|
|
242
|
+
}
|
|
243
|
+
const privateKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, options);
|
|
245
244
|
return signTypedData({
|
|
246
245
|
privateKey: Buffer.from(privateKey),
|
|
247
|
-
data
|
|
246
|
+
data,
|
|
248
247
|
version,
|
|
249
248
|
});
|
|
250
249
|
}
|
|
@@ -271,12 +270,10 @@ export class HdKeyring {
|
|
|
271
270
|
*/
|
|
272
271
|
removeAccount(account) {
|
|
273
272
|
const address = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_normalizeAddress).call(this, account);
|
|
274
|
-
if (!__classPrivateFieldGet(this,
|
|
275
|
-
.map(({ publicKey }) => publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey))
|
|
276
|
-
.includes(address)) {
|
|
273
|
+
if (!__classPrivateFieldGet(this, _HdKeyring_walletMap, "f").has(address)) {
|
|
277
274
|
throw new Error(`Address ${address} not found in this keyring`);
|
|
278
275
|
}
|
|
279
|
-
|
|
276
|
+
__classPrivateFieldGet(this, _HdKeyring_walletMap, "f").delete(address);
|
|
280
277
|
}
|
|
281
278
|
/**
|
|
282
279
|
* Get the public key of the account to be used for encryption.
|
|
@@ -291,7 +288,7 @@ export class HdKeyring {
|
|
|
291
288
|
return publicKey;
|
|
292
289
|
}
|
|
293
290
|
}
|
|
294
|
-
|
|
291
|
+
_HdKeyring_walletMap = new WeakMap(), _HdKeyring_cryptographicFunctions = new WeakMap(), _HdKeyring_instances = new WeakSet(), _HdKeyring_uint8ArrayToString = function _HdKeyring_uint8ArrayToString(mnemonic) {
|
|
295
292
|
const recoveredIndices = Array.from(new Uint16Array(new Uint8Array(mnemonic).buffer));
|
|
296
293
|
return recoveredIndices.map((i) => wordlist[i]).join(' ');
|
|
297
294
|
}, _HdKeyring_stringToUint8Array = function _HdKeyring_stringToUint8Array(mnemonic) {
|
|
@@ -337,14 +334,12 @@ _HdKeyring_wallets = new WeakMap(), _HdKeyring_cryptographicFunctions = new Weak
|
|
|
337
334
|
return wallet.privateKey;
|
|
338
335
|
}, _HdKeyring_getWalletForAccount = function _HdKeyring_getWalletForAccount(account, { withAppKeyOrigin } = {}) {
|
|
339
336
|
const address = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_normalizeAddress).call(this, account);
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
});
|
|
343
|
-
if (!wallet) {
|
|
337
|
+
const walletData = __classPrivateFieldGet(this, _HdKeyring_walletMap, "f").get(address);
|
|
338
|
+
if (!walletData) {
|
|
344
339
|
throw new Error('HD Keyring - Unable to find matching address.');
|
|
345
340
|
}
|
|
346
341
|
if (withAppKeyOrigin) {
|
|
347
|
-
const { privateKey } =
|
|
342
|
+
const { privateKey } = walletData.hdKey;
|
|
348
343
|
assert(privateKey, 'Expected private key to be set');
|
|
349
344
|
const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');
|
|
350
345
|
const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
|
|
@@ -352,7 +347,7 @@ _HdKeyring_wallets = new WeakMap(), _HdKeyring_cryptographicFunctions = new Weak
|
|
|
352
347
|
const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));
|
|
353
348
|
return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
|
|
354
349
|
}
|
|
355
|
-
return
|
|
350
|
+
return walletData.hdKey;
|
|
356
351
|
}, _HdKeyring_initFromMnemonic =
|
|
357
352
|
/**
|
|
358
353
|
* Sets appropriate properties for the keyring based on the given
|
|
@@ -366,17 +361,26 @@ async function _HdKeyring_initFromMnemonic(mnemonic) {
|
|
|
366
361
|
if (this.root) {
|
|
367
362
|
throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
|
|
368
363
|
}
|
|
369
|
-
|
|
364
|
+
// Convert and validate before assigning to instance property
|
|
365
|
+
// to avoid inconsistent state if validation fails
|
|
366
|
+
const mnemonicAsUint8Array = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
|
|
367
|
+
__classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_assertValidMnemonic).call(this, mnemonicAsUint8Array);
|
|
368
|
+
this.mnemonic = mnemonicAsUint8Array;
|
|
370
369
|
this.seed = await mnemonicToSeed(this.mnemonic, '', // No passphrase
|
|
371
370
|
__classPrivateFieldGet(this, _HdKeyring_cryptographicFunctions, "f"));
|
|
372
371
|
this.hdWallet = HDKey.fromMasterSeed(this.seed);
|
|
373
372
|
this.root = this.hdWallet.derive(this.hdPath);
|
|
374
|
-
},
|
|
373
|
+
}, _HdKeyring_addressFromPublicKey = function _HdKeyring_addressFromPublicKey(publicKey) {
|
|
375
374
|
return add0x(bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase());
|
|
376
375
|
}, _HdKeyring_normalizeAddress = function _HdKeyring_normalizeAddress(address) {
|
|
377
376
|
const normalized = normalize(address);
|
|
378
377
|
assert(normalized, 'Expected address to be set');
|
|
379
378
|
return add0x(normalized);
|
|
379
|
+
}, _HdKeyring_assertValidMnemonic = function _HdKeyring_assertValidMnemonic(mnemonic) {
|
|
380
|
+
const mnemonicString = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_uint8ArrayToString).call(this, mnemonic);
|
|
381
|
+
if (!validateMnemonic(mnemonicString, wordlist)) {
|
|
382
|
+
throw new Error('Eth-Hd-Keyring: Invalid secret recovery phrase provided');
|
|
383
|
+
}
|
|
380
384
|
};
|
|
381
385
|
HdKeyring.type = type;
|
|
382
386
|
//# sourceMappingURL=hd-keyring.mjs.map
|
package/dist/hd-keyring.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hd-keyring.mjs","sourceRoot":"","sources":["../src/hd-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,EAAE,yBAAyB;AAC5E,OAAO,EACL,SAAS,EACT,OAAO,EAGP,sBAAsB,EAEtB,SAAS,EACT,YAAY,EACZ,wBAAwB,EACxB,aAAa,EACb,oBAAoB,EAGrB,+BAA+B;AAChC,OAAO,EAEL,cAAc,EACf,2BAA2B;AAC5B,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AACzD,OAAO,EAAE,QAAQ,EAAE,wDAAqD;AACxE,OAAO,EACL,KAAK,EACL,MAAM,EACN,iBAAiB,EACjB,aAAa,EACb,UAAU,EAEV,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oCAAoC;AACpD,OAAO,EAAE,SAAS,EAAE,qCAAqC;AAEzD,WAAW;AACX,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,IAAI,GAAG,aAAa,CAAC;AA8B3B;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,IAAI,KAAK,QAAQ;QACvB,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAC1B,CAAC;AACJ,CAAC;AAED,MAAM,OAAO,SAAS;IAmBpB,YAAY,OAAyB,EAAE;;QAhBvC,SAAI,GAAW,IAAI,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AAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,WAAW,EAAE,CACxE,CAAC;AACJ,CAAC,qEAQiB,OAAe;IAC/B,MAAM,UAAU,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;IACtC,MAAM,CAAC,UAAU,EAAE,4BAA4B,CAAC,CAAC;IACjD,OAAO,KAAK,CAAC,UAAU,CAAC,CAAC;AAC3B,CAAC;AA1hBM,cAAI,GAAW,IAAI,AAAf,CAAgB","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { privateToPublic, publicToAddress, ecsign } from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EIP7702Authorization,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\n signEIP7702Authorization,\n signTypedData,\n SignTypedDataVersion,\n type TypedDataV1,\n type TypedMessage,\n} from '@metamask/eth-sig-util';\nimport {\n type CryptographicFunctions,\n mnemonicToSeed,\n} from '@metamask/key-tree';\nimport { generateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport {\n add0x,\n assert,\n assertIsHexString,\n bigIntToBytes,\n bytesToHex,\n type Hex,\n remove0x,\n} from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\nexport type HDKeyringOptions = {\n cryptographicFunctions?: CryptographicFunctions;\n};\n\n/**\n * The serialized state of an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type HDKeyringState = {\n mnemonic: number[] | Uint8Array | Buffer | string;\n numberOfAccounts: number;\n hdPath: string;\n};\n\n/**\n * Options for selecting an account from an `HDKeyring` instance.\n *\n * @property withAppKeyOrigin - The origin of the app requesting the account.\n */\nexport type HDKeyringAccountSelectionOptions = {\n withAppKeyOrigin?: string;\n};\n\ntype SerializedBuffer = ReturnType<Buffer['toJSON']>;\n\n/**\n * Checks if the given value is a valid serialized Buffer compatible with\n * the return type of `Buffer.toJSON`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid serialized buffer, `false` otherwise.\n */\nfunction isSerializedBuffer(value: unknown): value is SerializedBuffer {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n value.type === 'Buffer' &&\n 'data' in value &&\n Array.isArray(value.data)\n );\n}\n\nexport class HdKeyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: Uint8Array | null;\n\n seed?: Uint8Array | null;\n\n root?: HDKey | null;\n\n hdWallet?: HDKey;\n\n hdPath: string = hdPathString;\n\n #wallets: HDKey[] = [];\n\n readonly #cryptographicFunctions?: CryptographicFunctions;\n\n constructor(opts: HDKeyringOptions = {}) {\n // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.\n this.#cryptographicFunctions = opts.cryptographicFunctions;\n }\n\n /**\n * Initialize the keyring with a random mnemonic.\n *\n * @returns A promise that resolves when the process is complete.\n */\n async generateRandomMnemonic(): Promise<void> {\n await this.#initFromMnemonic(generateMnemonic(wordlist));\n }\n\n /**\n * Return the serialized state of the keyring.\n *\n * @returns The serialized state of the keyring.\n */\n async serialize(): Promise<HDKeyringState> {\n let mnemonic: number[] = [];\n\n if (this.mnemonic) {\n const mnemonicAsString = this.#uint8ArrayToString(this.mnemonic);\n mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));\n }\n\n return {\n mnemonic,\n numberOfAccounts: this.#wallets.length,\n hdPath: this.hdPath,\n };\n }\n\n /**\n * Initialize the keyring with the given serialized state.\n *\n * @param opts - The serialized state of the keyring.\n * @returns An empty array.\n */\n async deserialize(opts: Partial<HDKeyringState> = {}): Promise<string[]> {\n if (opts.numberOfAccounts && !opts.mnemonic) {\n throw new Error(\n 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',\n );\n }\n\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n this.#wallets = [];\n this.mnemonic = null;\n this.seed = null;\n this.root = null;\n this.hdPath = opts.hdPath ?? hdPathString;\n\n if (opts.mnemonic) {\n await this.#initFromMnemonic(opts.mnemonic);\n }\n\n if (opts.numberOfAccounts) {\n return this.addAccounts(opts.numberOfAccounts);\n }\n\n return [];\n }\n\n /**\n * Add new accounts to the keyring. The accounts will be derived\n * sequentially from the root HD wallet, using increasing indices.\n *\n * @param numberOfAccounts - The number of accounts to add.\n * @returns The addresses of the new accounts.\n */\n async addAccounts(numberOfAccounts = 1): Promise<Hex[]> {\n if (!this.root) {\n throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');\n }\n\n const oldLen = this.#wallets.length;\n const newWallets: HDKey[] = [];\n for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {\n const wallet = this.root.deriveChild(i);\n newWallets.push(wallet);\n this.#wallets.push(wallet);\n }\n const hexWallets = newWallets.map((wallet) => {\n assert(wallet.publicKey, 'Expected public key to be set');\n return this.#addressfromPublicKey(wallet.publicKey);\n });\n return Promise.resolve(hexWallets);\n }\n\n /**\n * Get the addresses of all accounts in the keyring.\n *\n * @returns The addresses of all accounts in the keyring.\n */\n getAccounts(): Hex[] {\n return this.#wallets.map((wallet) => {\n assert(wallet.publicKey, 'Expected public key to be set');\n return this.#addressfromPublicKey(wallet.publicKey);\n });\n }\n\n /**\n * Get the public address of the account for the given app key origin.\n *\n * @param address - The address of the account.\n * @param origin - The origin of the app requesting the account.\n * @returns The public address of the account.\n */\n async getAppKeyAddress(address: Hex, origin: string): Promise<Hex> {\n if (!origin || typeof origin !== 'string') {\n throw new Error(`'origin' must be a non-empty string`);\n }\n const wallet = this.#getWalletForAccount(address, {\n withAppKeyOrigin: origin,\n });\n assert(wallet.publicKey, 'Expected public key to be set');\n const appKeyAddress = this.#normalizeAddress(\n bytesToHex(publicToAddress(wallet.publicKey)),\n );\n return appKeyAddress;\n }\n\n /**\n * Export the private key for a specific account.\n *\n * @param address - The address of the account.\n * @param opts - The options for exporting the account.\n * @param opts.withAppKeyOrigin - An optional string to export the account\n * for a specific app origin.\n * @returns The private key of the account.\n */\n async exportAccount(\n address: Hex,\n opts?: { withAppKeyOrigin: string },\n ): Promise<string> {\n const wallet = opts\n ? this.#getWalletForAccount(address, opts)\n : this.#getWalletForAccount(address);\n const { privateKey } = wallet;\n assert(\n privateKey instanceof Uint8Array,\n 'Expected private key to be of type Uint8Array',\n );\n return remove0x(bytesToHex(privateKey));\n }\n\n /**\n * Sign a transaction using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param tx - The transaction to sign.\n * @param opts - The options for signing the transaction.\n * @returns The signed transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction,\n opts = {},\n ): Promise<TypedTransaction> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(Buffer.from(privKey));\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx ?? tx;\n }\n\n /**\n * Sign a message using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param data - The data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signMessage(\n address: Hex,\n data: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this.#getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));\n const rawMsgSig = concatSig(\n Buffer.from(bigIntToBytes(msgSig.v)),\n Buffer.from(msgSig.r),\n Buffer.from(msgSig.s),\n );\n return rawMsgSig;\n }\n\n /**\n * Sign a personal message using the private key of the specified account.\n * This method is compatible with the `personal_sign` RPC method.\n *\n * @param address - The address of the account.\n * @param msgHex - The message to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signPersonalMessage(\n address: Hex,\n msgHex: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey);\n return personalSign({ privateKey, data: msgHex });\n }\n\n /**\n * Decrypt an encrypted message using the private key of the specified account.\n * The message must be encrypted using the public key of the account.\n * This method is compatible with the `eth_decryptMessage` RPC method\n *\n * @param withAccount - The address of the account.\n * @param encryptedData - The encrypted data.\n * @returns The decrypted message.\n */\n async decryptMessage(\n withAccount: Hex,\n encryptedData: EthEncryptedData,\n ): Promise<string> {\n const wallet = this.#getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n assert(privateKeyAsUint8Array, 'Expected private key to be set');\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n return decrypt({ privateKey: privateKeyAsHex, encryptedData });\n }\n\n /**\n * Sign a typed message using the private key of the specified account.\n * This method is compatible with the `eth_signTypedData` RPC method.\n *\n * @param withAccount - The address of the account.\n * @param typedData - The typed data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signTypedData<Types extends MessageTypes>(\n withAccount: Hex,\n typedData: TypedDataV1 | TypedMessage<Types>,\n opts: HDKeyringAccountSelectionOptions & {\n version: SignTypedDataVersion;\n } = { version: SignTypedDataVersion.V1 },\n ): Promise<string> {\n // Treat invalid versions as \"V1\"\n const version = Object.keys(SignTypedDataVersion).includes(opts.version)\n ? opts.version\n : SignTypedDataVersion.V1;\n\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signTypedData({\n privateKey: Buffer.from(privateKey),\n data: typedData,\n version,\n });\n }\n\n /**\n * Sign an EIP-7702 authorization using the private key of the specified account.\n * This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.\n *\n * @param withAccount - The address of the account.\n * @param authorization - The EIP-7702 authorization to sign.\n * @param opts - The options for selecting the account.\n * @returns The signature of the authorization.\n */\n async signEip7702Authorization(\n withAccount: Hex,\n authorization: EIP7702Authorization,\n opts?: HDKeyringAccountSelectionOptions,\n ): Promise<string> {\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signEIP7702Authorization({\n privateKey: Buffer.from(privateKey),\n authorization,\n });\n }\n\n /**\n * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: Hex): void {\n const address = this.#normalizeAddress(account);\n if (\n !this.#wallets\n .map(\n ({ publicKey }) => publicKey && this.#addressfromPublicKey(publicKey),\n )\n .includes(address)\n ) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.#wallets = this.#wallets.filter(\n ({ publicKey }) =>\n publicKey && this.#addressfromPublicKey(publicKey) !== address,\n );\n }\n\n /**\n * Get the public key of the account to be used for encryption.\n *\n * @param withAccount - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The public key of the account.\n */\n async getEncryptionPublicKey(\n withAccount: Hex,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(remove0x(bytesToHex(privKey)));\n return publicKey;\n }\n\n /**\n * Convert a Uint8Array mnemonic to a secret recovery phrase,\n * using the english wordlist.\n *\n * @param mnemonic - The Uint8Array mnemonic.\n * @returns The string mnemonic.\n */\n #uint8ArrayToString(mnemonic: Uint8Array): string {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n /**\n * Convert a secret recovery phrase to a Uint8Array mnemonic,\n * using the english wordlist.\n *\n * @param mnemonic - The string mnemonic.\n * @returns The Uint8Array mnemonic.\n */\n #stringToUint8Array(mnemonic: string): Uint8Array {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n /**\n * Convert a mnemonic to a Uint8Array mnemonic.\n *\n * @param mnemonic - The mnemonic seed phrase.\n * @returns The Uint8Array mnemonic.\n */\n #mnemonicToUint8Array(\n mnemonic: Buffer | SerializedBuffer | string | Uint8Array | number[],\n ): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // When using `Buffer.toJSON()`, the Buffer is serialized into an object\n // with the structure `{ type: 'Buffer', data: [...] }`\n if (isSerializedBuffer(mnemonic)) {\n mnemonicData = mnemonic.data;\n }\n\n if (\n // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings\n typeof mnemonicData === 'string' ||\n Buffer.isBuffer(mnemonicData) ||\n Array.isArray(mnemonicData)\n ) {\n let mnemonicAsString: string;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\n } else {\n mnemonicAsString = mnemonicData;\n }\n return this.#stringToUint8Array(mnemonicAsString);\n } else if (\n mnemonicData instanceof Object &&\n !(mnemonicData instanceof Uint8Array)\n ) {\n // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array\n return Uint8Array.from(Object.values(mnemonicData));\n }\n\n assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');\n return mnemonicData;\n }\n\n /**\n * Get the private key for the specified account.\n *\n * @param address - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The private key of the account.\n */\n #getPrivateKeyFor(\n address: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): Uint8Array | Buffer {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this.#getWalletForAccount(address, opts);\n assert(wallet.privateKey, 'Missing private key');\n return wallet.privateKey;\n }\n\n /**\n * Get the wallet for the specified account.\n *\n * @param account - The address of the account.\n * @returns The wallet for the account as HDKey.\n */\n #getWalletForAccount(account: Hex): HDKey;\n\n /**\n * Get the wallet for the specified account and app origin.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n accounts: Hex,\n opts: { withAppKeyOrigin: string },\n ): { privateKey: Buffer; publicKey: Buffer };\n\n /**\n * Get the wallet for the specified account with optional\n * additional options.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n account: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: Hex,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = this.#normalizeAddress(account);\n const wallet = this.#wallets.find(({ publicKey }) => {\n return publicKey && this.#addressfromPublicKey(publicKey) === address;\n });\n if (!wallet) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (withAppKeyOrigin) {\n const { privateKey } = wallet;\n assert(privateKey, 'Expected private key to be set');\n const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = Buffer.from(keccak256(appKeyBuffer));\n const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));\n return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return wallet;\n }\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param mnemonic - A seed phrase represented\n * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input\n * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.\n */\n async #initFromMnemonic(\n mnemonic: string | number[] | Buffer | Uint8Array,\n ): Promise<void> {\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.mnemonic = this.#mnemonicToUint8Array(mnemonic);\n\n this.seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(this.seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n /**\n * Get the address of the account from the public key.\n *\n * @param publicKey - The public key of the account.\n * @returns The address of the account.\n */\n #addressfromPublicKey(publicKey: Uint8Array): Hex {\n return add0x(\n bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase(),\n );\n }\n\n /**\n * Normalize an address to a lower-cased '0x'-prefixed hex string.\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\n #normalizeAddress(address: string): Hex {\n const normalized = normalize(address);\n assert(normalized, 'Expected address to be set');\n return add0x(normalized);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hd-keyring.mjs","sourceRoot":"","sources":["../src/hd-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,EAAE,yBAAyB;AAC5E,OAAO,EACL,SAAS,EACT,OAAO,EAGP,sBAAsB,EAEtB,SAAS,EACT,YAAY,EACZ,wBAAwB,EACxB,aAAa,EACb,oBAAoB,EAGrB,+BAA+B;AAChC,OAAO,EAEL,cAAc,EACf,2BAA2B;AAE5B,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,8BAA8B;AAC3E,OAAO,EAAE,QAAQ,EAAE,wDAAqD;AACxE,OAAO,EACL,KAAK,EACL,MAAM,EACN,iBAAiB,EACjB,aAAa,EACb,UAAU,EAEV,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oCAAoC;AACpD,OAAO,EAAE,SAAS,EAAE,qCAAqC;AAEzD,WAAW;AACX,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,IAAI,GAAG,aAAa,CAAC;AAuD3B;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,IAAI,KAAK,QAAQ;QACvB,MAAM,I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D,OAAO,KAAK,CAAC,UAAU,CAAC,CAAC;AAC3B,CAAC,2EASoB,QAAoB;IACvC,MAAM,cAAc,GAAG,uBAAA,IAAI,2DAAoB,MAAxB,IAAI,EAAqB,QAAQ,CAAC,CAAC;IAC1D,IAAI,CAAC,gBAAgB,CAAC,cAAc,EAAE,QAAQ,CAAC,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;IACJ,CAAC;AACH,CAAC;AAviBM,cAAI,GAAW,IAAI,AAAf,CAAgB","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport { privateToPublic, publicToAddress, ecsign } from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EIP7702Authorization,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\n signEIP7702Authorization,\n signTypedData,\n SignTypedDataVersion,\n type TypedDataV1,\n type TypedMessage,\n} from '@metamask/eth-sig-util';\nimport {\n type CryptographicFunctions,\n mnemonicToSeed,\n} from '@metamask/key-tree';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport { generateMnemonic, validateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport {\n add0x,\n assert,\n assertIsHexString,\n bigIntToBytes,\n bytesToHex,\n type Hex,\n remove0x,\n} from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\ntype Mnemonic = string | number[] | SerializedBuffer | Buffer | Uint8Array;\n\nexport type HDKeyringOptions = {\n cryptographicFunctions?: CryptographicFunctions;\n};\n\n/**\n * The serialized state of an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type SerializedHDKeyringState = {\n mnemonic: number[];\n numberOfAccounts: number;\n hdPath: string;\n};\n\n/**\n * An object that can be passed to the Keyring.deserialize method to initialize\n * an `HDKeyring` instance.\n *\n * @property mnemonic - The mnemonic seed phrase as an array of numbers.\n * @property numberOfAccounts - The number of accounts in the keyring.\n * @property hdPath - The HD path used to derive accounts.\n */\nexport type DeserializableHDKeyringState = Omit<\n SerializedHDKeyringState,\n 'mnemonic'\n> & {\n mnemonic: number[] | SerializedBuffer | string;\n};\n\n/**\n * Options for selecting an account from an `HDKeyring` instance.\n *\n * @property withAppKeyOrigin - The origin of the app requesting the account.\n */\nexport type HDKeyringAccountSelectionOptions = {\n withAppKeyOrigin?: string;\n};\n\ntype SerializedBuffer = ReturnType<Buffer['toJSON']>;\n\n/**\n * Wallet storage object that contains both the HDKey and pre-computed address.\n */\ntype WalletData = {\n hdKey: HDKey;\n address: Hex;\n};\n\n/**\n * Checks if the given value is a valid serialized Buffer compatible with\n * the return type of `Buffer.toJSON`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid serialized buffer, `false` otherwise.\n */\nfunction isSerializedBuffer(value: unknown): value is SerializedBuffer {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'type' in value &&\n value.type === 'Buffer' &&\n 'data' in value &&\n Array.isArray(value.data)\n );\n}\n\nexport class HdKeyring implements Keyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: Uint8Array | null;\n\n seed?: Uint8Array | null;\n\n root?: HDKey | null;\n\n hdWallet?: HDKey;\n\n hdPath: string = hdPathString;\n\n readonly #walletMap = new Map<Hex, WalletData>();\n\n readonly #cryptographicFunctions?: CryptographicFunctions;\n\n constructor(opts: HDKeyringOptions = {}) {\n // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.\n this.#cryptographicFunctions = opts.cryptographicFunctions;\n }\n\n /**\n * Initialize the keyring with a random mnemonic.\n *\n * @returns A promise that resolves when the process is complete.\n */\n async generateRandomMnemonic(): Promise<void> {\n await this.#initFromMnemonic(generateMnemonic(wordlist));\n }\n\n /**\n * Return the serialized state of the keyring.\n *\n * @returns The serialized state of the keyring.\n */\n async serialize(): Promise<SerializedHDKeyringState> {\n let mnemonic: number[] = [];\n\n if (this.mnemonic) {\n const mnemonicAsString = this.#uint8ArrayToString(this.mnemonic);\n mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));\n }\n\n return {\n mnemonic,\n numberOfAccounts: this.#walletMap.size,\n hdPath: this.hdPath,\n };\n }\n\n /**\n * Initialize the keyring with the given serialized state.\n *\n * @param opts - The serialized state of the keyring.\n * @returns An empty array.\n */\n async deserialize(\n opts: Partial<DeserializableHDKeyringState>,\n ): Promise<void> {\n if (opts.numberOfAccounts && !opts.mnemonic) {\n throw new Error(\n 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',\n );\n }\n\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n this.#walletMap.clear();\n this.mnemonic = null;\n this.seed = null;\n this.root = null;\n this.hdPath = opts.hdPath ?? hdPathString;\n\n if (opts.mnemonic) {\n await this.#initFromMnemonic(opts.mnemonic);\n }\n\n if (opts.numberOfAccounts) {\n await this.addAccounts(opts.numberOfAccounts);\n }\n }\n\n /**\n * Add new accounts to the keyring. The accounts will be derived\n * sequentially from the root HD wallet, using increasing indices.\n *\n * @param numberOfAccounts - The number of accounts to add.\n * @returns The addresses of the new accounts.\n */\n async addAccounts(numberOfAccounts = 1): Promise<Hex[]> {\n if (!this.root) {\n throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');\n }\n\n const oldLen = this.#walletMap.size;\n const newAddresses: Hex[] = [];\n for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {\n const hdKey = this.root.deriveChild(i);\n assert(hdKey.publicKey, 'Expected public key to be set');\n\n const address = this.#addressFromPublicKey(hdKey.publicKey);\n const walletData: WalletData = {\n hdKey,\n address,\n };\n\n this.#walletMap.set(address, walletData);\n newAddresses.push(address);\n }\n\n return Promise.resolve(newAddresses);\n }\n\n /**\n * Get the addresses of all accounts in the keyring.\n *\n * @returns The addresses of all accounts in the keyring.\n */\n async getAccounts(): Promise<Hex[]> {\n return Array.from(this.#walletMap.keys());\n }\n\n /**\n * Get the public address of the account for the given app key origin.\n *\n * @param address - The address of the account.\n * @param origin - The origin of the app requesting the account.\n * @returns The public address of the account.\n */\n async getAppKeyAddress(address: Hex, origin: string): Promise<Hex> {\n if (!origin || typeof origin !== 'string') {\n throw new Error(`'origin' must be a non-empty string`);\n }\n const wallet = this.#getWalletForAccount(address, {\n withAppKeyOrigin: origin,\n });\n assert(wallet.publicKey, 'Expected public key to be set');\n const appKeyAddress = this.#normalizeAddress(\n bytesToHex(publicToAddress(wallet.publicKey)),\n );\n return appKeyAddress;\n }\n\n /**\n * Export the private key for a specific account.\n *\n * @param address - The address of the account.\n * @param opts - The options for exporting the account.\n * @param opts.withAppKeyOrigin - An optional string to export the account\n * for a specific app origin.\n * @returns The private key of the account.\n */\n async exportAccount(\n address: Hex,\n opts?: { withAppKeyOrigin: string },\n ): Promise<string> {\n const wallet = opts\n ? this.#getWalletForAccount(address, opts)\n : this.#getWalletForAccount(address);\n const { privateKey } = wallet;\n assert(\n privateKey instanceof Uint8Array,\n 'Expected private key to be of type Uint8Array',\n );\n return remove0x(bytesToHex(privateKey));\n }\n\n /**\n * Sign a transaction using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param tx - The transaction to sign.\n * @param opts - The options for signing the transaction.\n * @returns The signed transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction,\n opts = {},\n ): Promise<TypedTransaction> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(Buffer.from(privKey));\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx ?? tx;\n }\n\n /**\n * Sign a message using the private key of the specified account.\n *\n * @param address - The address of the account.\n * @param data - The data to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signMessage(\n address: Hex,\n data: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this.#getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));\n const rawMsgSig = concatSig(\n Buffer.from(bigIntToBytes(msgSig.v)),\n Buffer.from(msgSig.r),\n Buffer.from(msgSig.s),\n );\n return rawMsgSig;\n }\n\n /**\n * Sign a personal message using the private key of the specified account.\n * This method is compatible with the `personal_sign` RPC method.\n *\n * @param address - The address of the account.\n * @param msgHex - The message to sign.\n * @param opts - The options for signing the message.\n * @returns The signature of the message.\n */\n async signPersonalMessage(\n address: Hex,\n msgHex: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey);\n return personalSign({ privateKey, data: msgHex });\n }\n\n /**\n * Decrypt an encrypted message using the private key of the specified account.\n * The message must be encrypted using the public key of the account.\n * This method is compatible with the `eth_decryptMessage` RPC method\n *\n * @param withAccount - The address of the account.\n * @param encryptedData - The encrypted data.\n * @returns The decrypted message.\n */\n async decryptMessage(\n withAccount: Hex,\n encryptedData: EthEncryptedData,\n ): Promise<string> {\n const wallet = this.#getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n assert(privateKeyAsUint8Array, 'Expected private key to be set');\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n return decrypt({ privateKey: privateKeyAsHex, encryptedData });\n }\n\n /**\n * Sign a typed message using the private key of the specified account.\n * This method is compatible with the `eth_signTypedData` RPC method.\n *\n * @param address - The address of the account.\n * @param data - The typed data to sign.\n * @param options - The options for signing the message.\n * @returns The signature of the message.\n */\n async signTypedData<\n Version extends SignTypedDataVersion,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: Version extends 'V1' ? TypedDataV1 : TypedMessage<Types>,\n options?: HDKeyringAccountSelectionOptions & Options,\n ): Promise<string> {\n let { version } = options ?? { version: SignTypedDataVersion.V1 };\n\n // Treat invalid versions as \"V1\"\n if (!version || !Object.keys(SignTypedDataVersion).includes(version)) {\n version = SignTypedDataVersion.V1;\n }\n\n const privateKey = this.#getPrivateKeyFor(address, options);\n return signTypedData({\n privateKey: Buffer.from(privateKey),\n data,\n version,\n });\n }\n\n /**\n * Sign an EIP-7702 authorization using the private key of the specified account.\n * This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.\n *\n * @param withAccount - The address of the account.\n * @param authorization - The EIP-7702 authorization to sign.\n * @param opts - The options for selecting the account.\n * @returns The signature of the authorization.\n */\n async signEip7702Authorization(\n withAccount: Hex,\n authorization: EIP7702Authorization,\n opts?: HDKeyringAccountSelectionOptions,\n ): Promise<string> {\n const privateKey = this.#getPrivateKeyFor(withAccount, opts);\n return signEIP7702Authorization({\n privateKey: Buffer.from(privateKey),\n authorization,\n });\n }\n\n /**\n * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: Hex): void {\n const address = this.#normalizeAddress(account);\n\n if (!this.#walletMap.has(address)) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.#walletMap.delete(address);\n }\n\n /**\n * Get the public key of the account to be used for encryption.\n *\n * @param withAccount - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The public key of the account.\n */\n async getEncryptionPublicKey(\n withAccount: Hex,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(remove0x(bytesToHex(privKey)));\n return publicKey;\n }\n\n /**\n * Convert a Uint8Array mnemonic to a secret recovery phrase,\n * using the english wordlist.\n *\n * @param mnemonic - The Uint8Array mnemonic.\n * @returns The string mnemonic.\n */\n #uint8ArrayToString(mnemonic: Uint8Array): string {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n /**\n * Convert a secret recovery phrase to a Uint8Array mnemonic,\n * using the english wordlist.\n *\n * @param mnemonic - The string mnemonic.\n * @returns The Uint8Array mnemonic.\n */\n #stringToUint8Array(mnemonic: string): Uint8Array {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n /**\n * Convert a mnemonic to a Uint8Array mnemonic.\n *\n * @param mnemonic - The mnemonic seed phrase.\n * @returns The Uint8Array mnemonic.\n */\n #mnemonicToUint8Array(mnemonic: Mnemonic): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // When using `Buffer.toJSON()`, the Buffer is serialized into an object\n // with the structure `{ type: 'Buffer', data: [...] }`\n if (isSerializedBuffer(mnemonic)) {\n mnemonicData = mnemonic.data;\n }\n\n if (\n // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings\n typeof mnemonicData === 'string' ||\n Buffer.isBuffer(mnemonicData) ||\n Array.isArray(mnemonicData)\n ) {\n let mnemonicAsString: string;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\n } else {\n mnemonicAsString = mnemonicData;\n }\n return this.#stringToUint8Array(mnemonicAsString);\n } else if (\n mnemonicData instanceof Object &&\n !(mnemonicData instanceof Uint8Array)\n ) {\n // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array\n return Uint8Array.from(Object.values(mnemonicData));\n }\n\n assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');\n return mnemonicData;\n }\n\n /**\n * Get the private key for the specified account.\n *\n * @param address - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns The private key of the account.\n */\n #getPrivateKeyFor(\n address: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): Uint8Array | Buffer {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this.#getWalletForAccount(address, opts);\n assert(wallet.privateKey, 'Missing private key');\n return wallet.privateKey;\n }\n\n /**\n * Get the wallet for the specified account.\n *\n * @param account - The address of the account.\n * @returns The wallet for the account as HDKey.\n */\n #getWalletForAccount(account: Hex): HDKey;\n\n /**\n * Get the wallet for the specified account and app origin.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n accounts: Hex,\n opts: { withAppKeyOrigin: string },\n ): { privateKey: Buffer; publicKey: Buffer };\n\n /**\n * Get the wallet for the specified account with optional\n * additional options.\n *\n * @param account - The address of the account.\n * @param opts - The options for selecting the account.\n * @returns A key pair representing the wallet.\n */\n #getWalletForAccount(\n account: Hex,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: Hex,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = this.#normalizeAddress(account);\n const walletData = this.#walletMap.get(address);\n if (!walletData) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (withAppKeyOrigin) {\n const { privateKey } = walletData.hdKey;\n assert(privateKey, 'Expected private key to be set');\n const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = Buffer.from(keccak256(appKeyBuffer));\n const appKeyPublicKey = Buffer.from(privateToPublic(appKeyPrivateKey));\n return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return walletData.hdKey;\n }\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param mnemonic - A seed phrase represented\n * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input\n * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.\n */\n async #initFromMnemonic(mnemonic: Mnemonic): Promise<void> {\n if (this.root) {\n throw new Error(\n 'Eth-Hd-Keyring: Secret recovery phrase already provided',\n );\n }\n\n // Convert and validate before assigning to instance property\n // to avoid inconsistent state if validation fails\n const mnemonicAsUint8Array = this.#mnemonicToUint8Array(mnemonic);\n this.#assertValidMnemonic(mnemonicAsUint8Array);\n this.mnemonic = mnemonicAsUint8Array;\n\n this.seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(this.seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n /**\n * Get the address of the account from the public key.\n *\n * @param publicKey - The public key of the account.\n * @returns The address of the account.\n */\n #addressFromPublicKey(publicKey: Uint8Array): Hex {\n return add0x(\n bytesToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase(),\n );\n }\n\n /**\n * Normalize an address to a lower-cased '0x'-prefixed hex string.\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\n #normalizeAddress(address: string): Hex {\n const normalized = normalize(address);\n assert(normalized, 'Expected address to be set');\n return add0x(normalized);\n }\n\n /**\n * Assert that the mnemonic seed phrase is valid.\n * Throws an error if the mnemonic is not a valid BIP39 phrase.\n *\n * @param mnemonic - The mnemonic seed phrase to validate (as Uint8Array).\n * @throws If the mnemonic is not a valid BIP39 secret recovery phrase.\n */\n #assertValidMnemonic(mnemonic: Uint8Array): void {\n const mnemonicString = this.#uint8ArrayToString(mnemonic);\n if (!validateMnemonic(mnemonicString, wordlist)) {\n throw new Error(\n 'Eth-Hd-Keyring: Invalid secret recovery phrase provided',\n );\n }\n }\n}\n"]}
|
package/dist/index.cjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.HdKeyring = void 0;
|
|
3
|
+
exports.HdKeyringV2 = exports.HdKeyring = void 0;
|
|
4
4
|
var hd_keyring_1 = require("./hd-keyring.cjs");
|
|
5
5
|
Object.defineProperty(exports, "HdKeyring", { enumerable: true, get: function () { return hd_keyring_1.HdKeyring; } });
|
|
6
|
+
var hd_keyring_v2_1 = require("./hd-keyring-v2.cjs");
|
|
7
|
+
Object.defineProperty(exports, "HdKeyringV2", { enumerable: true, get: function () { return hd_keyring_v2_1.HdKeyringV2; } });
|
|
6
8
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,+CAAyC;AAAhC,uGAAA,SAAS,OAAA","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n
|
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,+CAAyC;AAAhC,uGAAA,SAAS,OAAA;AAOlB,qDAAuE;AAA9D,4GAAA,WAAW,OAAA","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n SerializedHDKeyringState,\n DeserializableHDKeyringState,\n HDKeyringOptions,\n HDKeyringAccountSelectionOptions,\n} from './hd-keyring';\nexport { HdKeyringV2, type HdKeyringV2Options } from './hd-keyring-v2';\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { HdKeyring } from "./hd-keyring.cjs";
|
|
2
|
-
export type {
|
|
2
|
+
export type { SerializedHDKeyringState, DeserializableHDKeyringState, HDKeyringOptions, HDKeyringAccountSelectionOptions, } from "./hd-keyring.cjs";
|
|
3
|
+
export { HdKeyringV2, type HdKeyringV2Options } from "./hd-keyring-v2.cjs";
|
|
3
4
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,
|
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,gCAAgC,GACjC,yBAAqB;AACtB,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,4BAAwB"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { HdKeyring } from "./hd-keyring.mjs";
|
|
2
|
-
export type {
|
|
2
|
+
export type { SerializedHDKeyringState, DeserializableHDKeyringState, HDKeyringOptions, HDKeyringAccountSelectionOptions, } from "./hd-keyring.mjs";
|
|
3
|
+
export { HdKeyringV2, type HdKeyringV2Options } from "./hd-keyring-v2.mjs";
|
|
3
4
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,YAAY,EACV,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,gCAAgC,GACjC,yBAAqB;AACtB,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,4BAAwB"}
|
package/dist/index.mjs
CHANGED
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n
|
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,yBAAqB;AAOzC,OAAO,EAAE,WAAW,EAA2B,4BAAwB","sourcesContent":["export { HdKeyring } from './hd-keyring';\nexport type {\n SerializedHDKeyringState,\n DeserializableHDKeyringState,\n HDKeyringOptions,\n HDKeyringAccountSelectionOptions,\n} from './hd-keyring';\nexport { HdKeyringV2, type HdKeyringV2Options } from './hd-keyring-v2';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/eth-hd-keyring",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "13.1.0",
|
|
4
4
|
"description": "A simple standard interface for a seed phrase generated set of Ethereum accounts.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ethereum",
|
|
@@ -43,17 +43,21 @@
|
|
|
43
43
|
"test:clean": "jest --clearCache"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
|
+
"@ethereumjs/tx": "^5.4.0",
|
|
46
47
|
"@ethereumjs/util": "^9.1.0",
|
|
47
48
|
"@metamask/eth-sig-util": "^8.2.0",
|
|
48
49
|
"@metamask/key-tree": "^10.0.2",
|
|
50
|
+
"@metamask/keyring-api": "^21.3.0",
|
|
51
|
+
"@metamask/keyring-utils": "^3.1.0",
|
|
49
52
|
"@metamask/scure-bip39": "^2.1.1",
|
|
53
|
+
"@metamask/superstruct": "^3.1.0",
|
|
50
54
|
"@metamask/utils": "^11.1.0",
|
|
51
55
|
"ethereum-cryptography": "^2.1.2"
|
|
52
56
|
},
|
|
53
57
|
"devDependencies": {
|
|
54
|
-
"@ethereumjs/tx": "^5.4.0",
|
|
55
58
|
"@lavamoat/allow-scripts": "^3.2.1",
|
|
56
59
|
"@lavamoat/preinstall-always-fail": "^2.1.0",
|
|
60
|
+
"@metamask/account-api": "^0.12.0",
|
|
57
61
|
"@metamask/auto-changelog": "^3.4.4",
|
|
58
62
|
"@metamask/bip39": "^4.0.0",
|
|
59
63
|
"@ts-bridge/cli": "^0.6.3",
|