@metamask-previews/eth-hd-keyring 9.0.1-15a8cd2 → 9.0.1-15c90e6

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 CHANGED
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Changed
11
+
12
+ - **BREAKING**: Added types to `HdKeyring` ([#166](https://github.com/MetaMask/accounts/pull/166))
13
+ - All methods on `HdKeyring` retain their existing signatures, but now have types.
14
+
10
15
  ## [9.0.1]
11
16
 
12
17
  ### Changed
package/dist/index.cjs CHANGED
@@ -1,4 +1,16 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ 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");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _HdKeyring_instances, _HdKeyring_wallets, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressfromPublicKey;
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  const util_1 = require("@ethereumjs/util");
4
16
  const eth_sig_util_1 = require("@metamask/eth-sig-util");
@@ -12,61 +24,60 @@ const utils_2 = require("ethereum-cryptography/utils");
12
24
  // Options:
13
25
  const hdPathString = `m/44'/60'/0'/0`;
14
26
  const type = 'HD Key Tree';
27
+ /**
28
+ * Checks if the given value is a JsCastedBuffer.
29
+ *
30
+ * @param maybeJsCastedBuffer - The value to check.
31
+ * @returns `true` if the value is a JsCastedBuffer, `false` otherwise.
32
+ */
33
+ function isJsCastedBuffer(maybeJsCastedBuffer) {
34
+ return (typeof maybeJsCastedBuffer === 'object' &&
35
+ maybeJsCastedBuffer !== null &&
36
+ 'type' in maybeJsCastedBuffer &&
37
+ maybeJsCastedBuffer.type === 'Buffer' &&
38
+ 'data' in maybeJsCastedBuffer);
39
+ }
15
40
  class HdKeyring {
16
- /* PUBLIC METHODS */
17
41
  constructor(opts = {}) {
42
+ _HdKeyring_instances.add(this);
18
43
  this.type = type;
19
- this._wallets = [];
44
+ this.hdPath = hdPathString;
45
+ _HdKeyring_wallets.set(this, []);
46
+ _HdKeyring_cryptographicFunctions.set(this, void 0);
20
47
  // Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.
21
- this._cryptographicFunctions = opts.cryptographicFunctions;
48
+ __classPrivateFieldSet(this, _HdKeyring_cryptographicFunctions, opts.cryptographicFunctions, "f");
22
49
  }
50
+ /**
51
+ * Initialize the keyring with a random mnemonic.
52
+ *
53
+ * @returns A promise that resolves when the process is complete.
54
+ */
23
55
  async generateRandomMnemonic() {
24
- await this._initFromMnemonic((0, scure_bip39_1.generateMnemonic)(english_1.wordlist));
25
- }
26
- _uint8ArrayToString(mnemonic) {
27
- const recoveredIndices = Array.from(new Uint16Array(new Uint8Array(mnemonic).buffer));
28
- return recoveredIndices.map((i) => english_1.wordlist[i]).join(' ');
29
- }
30
- _stringToUint8Array(mnemonic) {
31
- const indices = mnemonic.split(' ').map((word) => english_1.wordlist.indexOf(word));
32
- return new Uint8Array(new Uint16Array(indices).buffer);
33
- }
34
- _mnemonicToUint8Array(mnemonic) {
35
- let mnemonicData = mnemonic;
36
- // when encrypted/decrypted, buffers get cast into js object with a property type set to buffer
37
- if (mnemonic && mnemonic.type && mnemonic.type === 'Buffer') {
38
- mnemonicData = mnemonic.data;
39
- }
40
- if (
41
- // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings
42
- typeof mnemonicData === 'string' ||
43
- Buffer.isBuffer(mnemonicData) ||
44
- Array.isArray(mnemonicData)) {
45
- let mnemonicAsString = mnemonicData;
46
- if (Array.isArray(mnemonicData)) {
47
- mnemonicAsString = Buffer.from(mnemonicData).toString();
48
- }
49
- else if (Buffer.isBuffer(mnemonicData)) {
50
- mnemonicAsString = mnemonicData.toString();
51
- }
52
- return this._stringToUint8Array(mnemonicAsString);
53
- }
54
- else if (mnemonicData instanceof Object &&
55
- !(mnemonicData instanceof Uint8Array)) {
56
- // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array
57
- return Uint8Array.from(Object.values(mnemonicData));
58
- }
59
- return mnemonicData;
56
+ await __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_initFromMnemonic).call(this, (0, scure_bip39_1.generateMnemonic)(english_1.wordlist));
60
57
  }
58
+ /**
59
+ * Return the serialized state of the keyring.
60
+ *
61
+ * @returns The serialized state of the keyring.
62
+ */
61
63
  async serialize() {
62
- const mnemonicAsString = this._uint8ArrayToString(this.mnemonic);
63
- const uint8ArrayMnemonic = new TextEncoder('utf-8').encode(mnemonicAsString);
64
+ let mnemonic = [];
65
+ if (this.mnemonic) {
66
+ const mnemonicAsString = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_uint8ArrayToString).call(this, this.mnemonic);
67
+ mnemonic = Array.from(new TextEncoder().encode(mnemonicAsString));
68
+ }
64
69
  return {
65
- mnemonic: Array.from(uint8ArrayMnemonic),
66
- numberOfAccounts: this._wallets.length,
70
+ mnemonic,
71
+ numberOfAccounts: __classPrivateFieldGet(this, _HdKeyring_wallets, "f").length,
67
72
  hdPath: this.hdPath,
68
73
  };
69
74
  }
75
+ /**
76
+ * Initialize the keyring with the given serialized state.
77
+ *
78
+ * @param opts - The serialized state of the keyring.
79
+ * @returns An empty array.
80
+ */
70
81
  async deserialize(opts = {}) {
71
82
  if (opts.numberOfAccounts && !opts.mnemonic) {
72
83
  throw new Error('Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic');
@@ -74,168 +85,278 @@ class HdKeyring {
74
85
  if (this.root) {
75
86
  throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
76
87
  }
77
- this.opts = opts;
78
- this._wallets = [];
88
+ __classPrivateFieldSet(this, _HdKeyring_wallets, [], "f");
79
89
  this.mnemonic = null;
80
90
  this.root = null;
81
- this.hdPath = opts.hdPath || hdPathString;
91
+ this.hdPath = opts.hdPath ?? hdPathString;
82
92
  if (opts.mnemonic) {
83
- await this._initFromMnemonic(opts.mnemonic);
93
+ await __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_initFromMnemonic).call(this, opts.mnemonic);
84
94
  }
85
95
  if (opts.numberOfAccounts) {
86
96
  return this.addAccounts(opts.numberOfAccounts);
87
97
  }
88
98
  return [];
89
99
  }
90
- addAccounts(numberOfAccounts = 1) {
100
+ /**
101
+ * Add new accounts to the keyring. The accounts will be derived
102
+ * sequentially from the root HD wallet, using increasing indices.
103
+ *
104
+ * @param numberOfAccounts - The number of accounts to add.
105
+ * @returns The addresses of the new accounts.
106
+ */
107
+ async addAccounts(numberOfAccounts = 1) {
91
108
  if (!this.root) {
92
109
  throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');
93
110
  }
94
- const oldLen = this._wallets.length;
111
+ const oldLen = __classPrivateFieldGet(this, _HdKeyring_wallets, "f").length;
95
112
  const newWallets = [];
96
113
  for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {
97
114
  const wallet = this.root.deriveChild(i);
98
115
  newWallets.push(wallet);
99
- this._wallets.push(wallet);
116
+ __classPrivateFieldGet(this, _HdKeyring_wallets, "f").push(wallet);
100
117
  }
101
- const hexWallets = newWallets.map((w) => {
102
- return this._addressfromPublicKey(w.publicKey);
118
+ const hexWallets = newWallets.map((wallet) => {
119
+ return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, wallet.publicKey);
103
120
  });
104
121
  return Promise.resolve(hexWallets);
105
122
  }
106
- getAccounts() {
107
- return this._wallets.map((w) => this._addressfromPublicKey(w.publicKey));
123
+ /**
124
+ * Get the addresses of all accounts in the keyring.
125
+ *
126
+ * @returns The addresses of all accounts in the keyring.
127
+ */
128
+ async getAccounts() {
129
+ return __classPrivateFieldGet(this, _HdKeyring_wallets, "f").map((wallet) => __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, wallet.publicKey));
108
130
  }
109
- /* BASE KEYRING METHODS */
110
- // returns an address specific to an app
131
+ /**
132
+ * Get the public address of the account for the given app key origin.
133
+ *
134
+ * @param address - The address of the account.
135
+ * @param origin - The origin of the app requesting the account.
136
+ * @returns The public address of the account.
137
+ */
111
138
  async getAppKeyAddress(address, origin) {
112
139
  if (!origin || typeof origin !== 'string') {
113
140
  throw new Error(`'origin' must be a non-empty string`);
114
141
  }
115
- const wallet = this._getWalletForAccount(address, {
142
+ const wallet = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address, {
116
143
  withAppKeyOrigin: origin,
117
144
  });
145
+ (0, utils_1.assert)(wallet.publicKey, 'Expected public key to be set');
118
146
  const appKeyAddress = (0, eth_sig_util_1.normalize)((0, util_1.publicToAddress)(wallet.publicKey).toString('hex'));
147
+ (0, utils_1.assert)(appKeyAddress, 'Expected app key address to be set');
119
148
  return appKeyAddress;
120
149
  }
121
- // exportAccount should return a hex-encoded private key:
122
- async exportAccount(address, opts = {}) {
123
- const wallet = this._getWalletForAccount(address, opts);
124
- return (0, utils_2.bytesToHex)(wallet.privateKey);
150
+ /**
151
+ * Export the private key for a specific account.
152
+ *
153
+ * @param address - The address of the account.
154
+ * @param opts - The options for exporting the account.
155
+ * @param opts.withAppKeyOrigin - An optional string to export the account
156
+ * for a specific app origin.
157
+ * @returns The private key of the account.
158
+ */
159
+ async exportAccount(address, opts) {
160
+ const wallet = opts
161
+ ? __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address, opts)
162
+ : __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address);
163
+ const { privateKey } = wallet;
164
+ (0, utils_1.assert)(privateKey instanceof Uint8Array, 'Expected private key to be of type Uint8Array');
165
+ return (0, utils_2.bytesToHex)(privateKey);
125
166
  }
126
- // tx is an instance of the ethereumjs-transaction class.
167
+ /**
168
+ * Sign a transaction using the private key of the specified account.
169
+ *
170
+ * @param address - The address of the account.
171
+ * @param tx - The transaction to sign.
172
+ * @param opts - The options for signing the transaction.
173
+ * @returns The signed transaction.
174
+ */
127
175
  async signTransaction(address, tx, opts = {}) {
128
- const privKey = this._getPrivateKeyFor(address, opts);
129
- const signedTx = tx.sign(privKey);
176
+ const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, opts);
177
+ const signedTx = tx.sign(Buffer.from(privKey));
130
178
  // Newer versions of Ethereumjs-tx are immutable and return a new tx object
131
- return signedTx === undefined ? tx : signedTx;
179
+ return signedTx ?? tx;
132
180
  }
133
- // For eth_sign, we need to sign arbitrary data:
181
+ /**
182
+ * Sign a message using the private key of the specified account.
183
+ *
184
+ * @param address - The address of the account.
185
+ * @param data - The data to sign.
186
+ * @param opts - The options for signing the message.
187
+ * @returns The signature of the message.
188
+ */
134
189
  async signMessage(address, data, opts = {}) {
135
190
  (0, utils_1.assertIsHexString)(data);
136
191
  const message = (0, utils_1.remove0x)(data);
137
- const privKey = this._getPrivateKeyFor(address, opts);
138
- const msgSig = (0, util_1.ecsign)(Buffer.from(message, 'hex'), privKey);
139
- const rawMsgSig = (0, eth_sig_util_1.concatSig)(msgSig.v, msgSig.r, msgSig.s);
192
+ const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, opts);
193
+ const msgSig = (0, util_1.ecsign)(Buffer.from(message, 'hex'), Buffer.from(privKey));
194
+ const rawMsgSig = (0, eth_sig_util_1.concatSig)(
195
+ // WARN: verify this cast to Buffer
196
+ msgSig.v, msgSig.r, msgSig.s);
140
197
  return rawMsgSig;
141
198
  }
142
- // For personal_sign, we need to prefix the message:
199
+ /**
200
+ * Sign a personal message using the private key of the specified account.
201
+ * This method is compatible with the `personal_sign` RPC method.
202
+ *
203
+ * @param address - The address of the account.
204
+ * @param msgHex - The message to sign.
205
+ * @param opts - The options for signing the message.
206
+ * @returns The signature of the message.
207
+ */
143
208
  async signPersonalMessage(address, msgHex, opts = {}) {
144
- const privKey = this._getPrivateKeyFor(address, opts);
145
- const privateKey = Buffer.from(privKey, 'hex');
146
- const sig = (0, eth_sig_util_1.personalSign)({ privateKey, data: msgHex });
147
- return sig;
209
+ const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, opts);
210
+ const privateKey = Buffer.from(privKey);
211
+ return (0, eth_sig_util_1.personalSign)({ privateKey, data: msgHex });
148
212
  }
149
- // For eth_decryptMessage:
213
+ /**
214
+ * Decrypt an encrypted message using the private key of the specified account.
215
+ * The message must be encrypted using the public key of the account.
216
+ * This method is compatible with the `eth_decryptMessage` RPC method
217
+ *
218
+ * @param withAccount - The address of the account.
219
+ * @param encryptedData - The encrypted data.
220
+ * @returns The decrypted message.
221
+ */
150
222
  async decryptMessage(withAccount, encryptedData) {
151
- const wallet = this._getWalletForAccount(withAccount);
223
+ const wallet = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, withAccount);
152
224
  const { privateKey: privateKeyAsUint8Array } = wallet;
225
+ (0, utils_1.assert)(privateKeyAsUint8Array, 'Expected private key to be set');
153
226
  const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');
154
- const sig = (0, eth_sig_util_1.decrypt)({ privateKey: privateKeyAsHex, encryptedData });
155
- return sig;
227
+ return (0, eth_sig_util_1.decrypt)({ privateKey: privateKeyAsHex, encryptedData });
156
228
  }
157
- // personal_signTypedData, signs data along with the schema
229
+ /**
230
+ * Sign a typed message using the private key of the specified account.
231
+ * This method is compatible with the `eth_signTypedData` RPC method.
232
+ *
233
+ * @param withAccount - The address of the account.
234
+ * @param typedData - The typed data to sign.
235
+ * @param opts - The options for signing the message.
236
+ * @returns The signature of the message.
237
+ */
158
238
  async signTypedData(withAccount, typedData, opts = { version: eth_sig_util_1.SignTypedDataVersion.V1 }) {
159
239
  // Treat invalid versions as "V1"
160
240
  const version = Object.keys(eth_sig_util_1.SignTypedDataVersion).includes(opts.version)
161
241
  ? opts.version
162
242
  : eth_sig_util_1.SignTypedDataVersion.V1;
163
- const privateKey = this._getPrivateKeyFor(withAccount, opts);
164
- return (0, eth_sig_util_1.signTypedData)({ privateKey, data: typedData, version });
243
+ const privateKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, withAccount, opts);
244
+ return (0, eth_sig_util_1.signTypedData)({
245
+ privateKey: Buffer.from(privateKey),
246
+ data: typedData,
247
+ version,
248
+ });
165
249
  }
250
+ /**
251
+ * Remove an account from the keyring.
252
+ *
253
+ * @param account - The address of the account to remove.
254
+ */
166
255
  removeAccount(account) {
167
256
  const address = (0, eth_sig_util_1.normalize)(account);
168
- if (!this._wallets
169
- .map(({ publicKey }) => this._addressfromPublicKey(publicKey))
257
+ (0, utils_1.assert)(address, 'Must specify a valid address.');
258
+ if (!__classPrivateFieldGet(this, _HdKeyring_wallets, "f")
259
+ .map(({ publicKey }) => publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey))
170
260
  .includes(address)) {
171
261
  throw new Error(`Address ${address} not found in this keyring`);
172
262
  }
173
- this._wallets = this._wallets.filter(({ publicKey }) => this._addressfromPublicKey(publicKey) !== address);
263
+ __classPrivateFieldSet(this, _HdKeyring_wallets, __classPrivateFieldGet(this, _HdKeyring_wallets, "f").filter(({ publicKey }) => publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey) !== address), "f");
174
264
  }
175
- // get public key for nacl
265
+ /**
266
+ * Get the public key of the account to be used for encryption.
267
+ *
268
+ * @param withAccount - The address of the account.
269
+ * @param opts - The options for selecting the account.
270
+ * @returns The public key of the account.
271
+ */
176
272
  async getEncryptionPublicKey(withAccount, opts = {}) {
177
- const privKey = this._getPrivateKeyFor(withAccount, opts);
178
- const publicKey = (0, eth_sig_util_1.getEncryptionPublicKey)(privKey);
273
+ const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, withAccount, opts);
274
+ const publicKey = (0, eth_sig_util_1.getEncryptionPublicKey)((0, utils_2.bytesToHex)(privKey));
179
275
  return publicKey;
180
276
  }
181
- getFingerprint() {
182
- const firstIndexFingerprint = this.root.deriveChild(0).fingerprint;
183
- console.log('firstIndexFingerprint', firstIndexFingerprint);
184
- const fingerprint = (0, keccak_1.keccak256)(Buffer.from(this.root.deriveChild(0).fingerprint.toString()));
185
- console.log('fingerPrint', fingerprint);
186
- const result = Buffer.from(fingerprint).toString('hex');
187
- console.log('result', result);
188
- return result;
189
- }
190
- _getPrivateKeyFor(address, opts = {}) {
191
- if (!address) {
192
- throw new Error('Must specify address.');
193
- }
194
- const wallet = this._getWalletForAccount(address, opts);
195
- return wallet.privateKey;
277
+ }
278
+ _HdKeyring_wallets = new WeakMap(), _HdKeyring_cryptographicFunctions = new WeakMap(), _HdKeyring_instances = new WeakSet(), _HdKeyring_uint8ArrayToString = function _HdKeyring_uint8ArrayToString(mnemonic) {
279
+ const recoveredIndices = Array.from(new Uint16Array(new Uint8Array(mnemonic).buffer));
280
+ return recoveredIndices.map((i) => english_1.wordlist[i]).join(' ');
281
+ }, _HdKeyring_stringToUint8Array = function _HdKeyring_stringToUint8Array(mnemonic) {
282
+ const indices = mnemonic.split(' ').map((word) => english_1.wordlist.indexOf(word));
283
+ return new Uint8Array(new Uint16Array(indices).buffer);
284
+ }, _HdKeyring_mnemonicToUint8Array = function _HdKeyring_mnemonicToUint8Array(mnemonic) {
285
+ let mnemonicData = mnemonic;
286
+ // when encrypted/decrypted, buffers get cast into js object with a property type set to buffer
287
+ if (isJsCastedBuffer(mnemonic)) {
288
+ mnemonicData = mnemonic.data;
196
289
  }
197
- _getWalletForAccount(account, opts = {}) {
198
- const address = (0, eth_sig_util_1.normalize)(account);
199
- let wallet = this._wallets.find(({ publicKey }) => {
200
- return this._addressfromPublicKey(publicKey) === address;
201
- });
202
- if (!wallet) {
203
- throw new Error('HD Keyring - Unable to find matching address.');
290
+ if (
291
+ // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings
292
+ typeof mnemonicData === 'string' ||
293
+ Buffer.isBuffer(mnemonicData) ||
294
+ Array.isArray(mnemonicData)) {
295
+ let mnemonicAsString;
296
+ if (Array.isArray(mnemonicData)) {
297
+ mnemonicAsString = Buffer.from(mnemonicData).toString();
204
298
  }
205
- if (opts.withAppKeyOrigin) {
206
- const { privateKey } = wallet;
207
- const appKeyOriginBuffer = Buffer.from(opts.withAppKeyOrigin, 'utf8');
208
- const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
209
- const appKeyPrivateKey = (0, util_1.arrToBufArr)((0, keccak_1.keccak256)(appKeyBuffer, 256));
210
- const appKeyPublicKey = (0, util_1.privateToPublic)(appKeyPrivateKey);
211
- wallet = { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
299
+ else if (Buffer.isBuffer(mnemonicData)) {
300
+ mnemonicAsString = mnemonicData.toString();
212
301
  }
213
- return wallet;
214
- }
215
- /* PRIVATE / UTILITY METHODS */
216
- /**
217
- * Sets appropriate properties for the keyring based on the given
218
- * BIP39-compliant mnemonic.
219
- *
220
- * @param {string|Array<number>|Buffer} mnemonic - A seed phrase represented
221
- * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input
222
- * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.
223
- */
224
- async _initFromMnemonic(mnemonic) {
225
- if (this.root) {
226
- throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
302
+ else {
303
+ mnemonicAsString = mnemonicData;
227
304
  }
228
- this.mnemonic = this._mnemonicToUint8Array(mnemonic);
229
- const seed = await (0, key_tree_1.mnemonicToSeed)(this.mnemonic, '', // No passphrase
230
- this._cryptographicFunctions);
231
- this.hdWallet = hdkey_1.HDKey.fromMasterSeed(seed);
232
- this.root = this.hdWallet.derive(this.hdPath);
305
+ return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_stringToUint8Array).call(this, mnemonicAsString);
233
306
  }
234
- // small helper function to convert publicKey in Uint8Array form to a publicAddress as a hex
235
- _addressfromPublicKey(publicKey) {
236
- return (0, util_1.bufferToHex)((0, util_1.publicToAddress)(Buffer.from(publicKey), true)).toLowerCase();
307
+ else if (mnemonicData instanceof Object &&
308
+ !(mnemonicData instanceof Uint8Array)) {
309
+ // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array
310
+ return Uint8Array.from(Object.values(mnemonicData));
237
311
  }
238
- }
312
+ (0, utils_1.assert)(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');
313
+ return mnemonicData;
314
+ }, _HdKeyring_getPrivateKeyFor = function _HdKeyring_getPrivateKeyFor(address, opts) {
315
+ if (!address) {
316
+ throw new Error('Must specify address.');
317
+ }
318
+ const wallet = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address, opts);
319
+ (0, utils_1.assert)(wallet.privateKey, 'Missing private key');
320
+ return wallet.privateKey;
321
+ }, _HdKeyring_getWalletForAccount = function _HdKeyring_getWalletForAccount(account, { withAppKeyOrigin } = {}) {
322
+ const address = (0, eth_sig_util_1.normalize)(account);
323
+ const wallet = __classPrivateFieldGet(this, _HdKeyring_wallets, "f").find(({ publicKey }) => {
324
+ return publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey) === address;
325
+ });
326
+ if (!wallet) {
327
+ throw new Error('HD Keyring - Unable to find matching address.');
328
+ }
329
+ if (withAppKeyOrigin) {
330
+ const { privateKey } = wallet;
331
+ (0, utils_1.assert)(privateKey, 'Expected private key to be set');
332
+ const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');
333
+ const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
334
+ const appKeyPrivateKey = (0, util_1.arrToBufArr)((0, keccak_1.keccak256)(appKeyBuffer));
335
+ const appKeyPublicKey = (0, util_1.privateToPublic)(appKeyPrivateKey);
336
+ return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
337
+ }
338
+ return wallet;
339
+ }, _HdKeyring_initFromMnemonic =
340
+ /**
341
+ * Sets appropriate properties for the keyring based on the given
342
+ * BIP39-compliant mnemonic.
343
+ *
344
+ * @param mnemonic - A seed phrase represented
345
+ * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input
346
+ * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.
347
+ */
348
+ async function _HdKeyring_initFromMnemonic(mnemonic) {
349
+ if (this.root) {
350
+ throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
351
+ }
352
+ this.mnemonic = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
353
+ const seed = await (0, key_tree_1.mnemonicToSeed)(this.mnemonic, '', // No passphrase
354
+ __classPrivateFieldGet(this, _HdKeyring_cryptographicFunctions, "f"));
355
+ this.hdWallet = hdkey_1.HDKey.fromMasterSeed(seed);
356
+ this.root = this.hdWallet.derive(this.hdPath);
357
+ }, _HdKeyring_addressfromPublicKey = function _HdKeyring_addressfromPublicKey(publicKey) {
358
+ return (0, util_1.bufferToHex)((0, util_1.publicToAddress)(Buffer.from(publicKey), true)).toLowerCase();
359
+ };
239
360
  HdKeyring.type = type;
240
361
  exports.default = HdKeyring;
241
362
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":";;AAAA,2CAM0B;AAC1B,yDAQgC;AAChC,iDAAoD;AACpD,uDAAyD;AACzD,6EAAwE;AACxE,2CAA8D;AAC9D,uDAAoD;AACpD,yDAAyD;AACzD,uDAAyD;AAEzD,WAAW;AACX,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,IAAI,GAAG,aAAa,CAAC;AAE3B,MAAM,SAAS;IACb,oBAAoB;IACpB,YAAY,IAAI,GAAG,EAAE;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,yHAAyH;QACzH,IAAI,CAAC,uBAAuB,GAAG,IAAI,CAAC,sBAAsB,CAAC;IAC7D,CAAC;IAED,KAAK,CAAC,sBAAsB;QAC1B,MAAM,IAAI,CAAC,iBAAiB,CAAC,IAAA,8BAAgB,EAAC,kBAAQ,CAAC,CAAC,CAAC;IAC3D,CAAC;IAED,mBAAmB,CAAC,QAAQ;QAC1B,MAAM,gBAAgB,GAAG,KAAK,CAAC,IAAI,CACjC,IAAI,WAAW,CAAC,IAAI,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CACjD,CAAC;QACF,OAAO,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,kBAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI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ourcesContent":["import {\n privateToPublic,\n publicToAddress,\n ecsign,\n arrToBufArr,\n bufferToHex,\n} from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n getEncryptionPublicKey,\n normalize,\n personalSign,\n signTypedData,\n SignTypedDataVersion,\n} from '@metamask/eth-sig-util';\nimport { mnemonicToSeed } from '@metamask/key-tree';\nimport { generateMnemonic } from '@metamask/scure-bip39';\nimport { wordlist } from '@metamask/scure-bip39/dist/wordlists/english';\nimport { assertIsHexString, remove0x } from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\nimport { bytesToHex } from 'ethereum-cryptography/utils';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\nclass HdKeyring {\n /* PUBLIC METHODS */\n constructor(opts = {}) {\n this.type = type;\n this._wallets = [];\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 async generateRandomMnemonic() {\n await this._initFromMnemonic(generateMnemonic(wordlist));\n }\n\n _uint8ArrayToString(mnemonic) {\n const recoveredIndices = Array.from(\n new Uint16Array(new Uint8Array(mnemonic).buffer),\n );\n return recoveredIndices.map((i) => wordlist[i]).join(' ');\n }\n\n _stringToUint8Array(mnemonic) {\n const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));\n return new Uint8Array(new Uint16Array(indices).buffer);\n }\n\n _mnemonicToUint8Array(mnemonic) {\n let mnemonicData = mnemonic;\n // when encrypted/decrypted, buffers get cast into js object with a property type set to buffer\n if (mnemonic && mnemonic.type && mnemonic.type === 'Buffer') {\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 = mnemonicData;\n if (Array.isArray(mnemonicData)) {\n mnemonicAsString = Buffer.from(mnemonicData).toString();\n } else if (Buffer.isBuffer(mnemonicData)) {\n mnemonicAsString = mnemonicData.toString();\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 return mnemonicData;\n }\n\n async serialize() {\n const mnemonicAsString = this._uint8ArrayToString(this.mnemonic);\n const uint8ArrayMnemonic = new TextEncoder('utf-8').encode(\n mnemonicAsString,\n );\n\n return {\n mnemonic: Array.from(uint8ArrayMnemonic),\n numberOfAccounts: this._wallets.length,\n hdPath: this.hdPath,\n };\n }\n\n async deserialize(opts = {}) {\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.opts = opts;\n this._wallets = [];\n this.mnemonic = 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 addAccounts(numberOfAccounts = 1) {\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 = [];\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((w) => {\n return this._addressfromPublicKey(w.publicKey);\n });\n return Promise.resolve(hexWallets);\n }\n\n getAccounts() {\n return this._wallets.map((w) => this._addressfromPublicKey(w.publicKey));\n }\n\n /* BASE KEYRING METHODS */\n\n // returns an address specific to an app\n async getAppKeyAddress(address, origin) {\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 const appKeyAddress = normalize(\n publicToAddress(wallet.publicKey).toString('hex'),\n );\n\n return appKeyAddress;\n }\n\n // exportAccount should return a hex-encoded private key:\n async exportAccount(address, opts = {}) {\n const wallet = this._getWalletForAccount(address, opts);\n return bytesToHex(wallet.privateKey);\n }\n\n // tx is an instance of the ethereumjs-transaction class.\n async signTransaction(address, tx, opts = {}) {\n const privKey = this._getPrivateKeyFor(address, opts);\n const signedTx = tx.sign(privKey);\n // Newer versions of Ethereumjs-tx are immutable and return a new tx object\n return signedTx === undefined ? tx : signedTx;\n }\n\n // For eth_sign, we need to sign arbitrary data:\n async signMessage(address, data, opts = {}) {\n assertIsHexString(data);\n const message = remove0x(data);\n const privKey = this._getPrivateKeyFor(address, opts);\n const msgSig = ecsign(Buffer.from(message, 'hex'), privKey);\n const rawMsgSig = concatSig(msgSig.v, msgSig.r, msgSig.s);\n return rawMsgSig;\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(address, msgHex, opts = {}) {\n const privKey = this._getPrivateKeyFor(address, opts);\n const privateKey = Buffer.from(privKey, 'hex');\n const sig = personalSign({ privateKey, data: msgHex });\n return sig;\n }\n\n // For eth_decryptMessage:\n async decryptMessage(withAccount, encryptedData) {\n const wallet = this._getWalletForAccount(withAccount);\n const { privateKey: privateKeyAsUint8Array } = wallet;\n const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');\n const sig = decrypt({ privateKey: privateKeyAsHex, encryptedData });\n return sig;\n }\n\n // personal_signTypedData, signs data along with the schema\n async signTypedData(\n withAccount,\n typedData,\n opts = { version: SignTypedDataVersion.V1 },\n ) {\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({ privateKey, data: typedData, version });\n }\n\n removeAccount(account) {\n const address = normalize(account);\n if (\n !this._wallets\n .map(({ publicKey }) => this._addressfromPublicKey(publicKey))\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 }) => this._addressfromPublicKey(publicKey) !== address,\n );\n }\n\n // get public key for nacl\n async getEncryptionPublicKey(withAccount, opts = {}) {\n const privKey = this._getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(privKey);\n return publicKey;\n }\n\n getFingerprint() {\n const firstIndexFingerprint = this.root.deriveChild(0).fingerprint;\n console.log('firstIndexFingerprint', firstIndexFingerprint);\n const fingerprint = keccak256(\n Buffer.from(this.root.deriveChild(0).fingerprint.toString()),\n );\n console.log('fingerPrint', fingerprint);\n const result = Buffer.from(fingerprint).toString('hex');\n console.log('result', result);\n return result;\n }\n\n _getPrivateKeyFor(address, opts = {}) {\n if (!address) {\n throw new Error('Must specify address.');\n }\n const wallet = this._getWalletForAccount(address, opts);\n return wallet.privateKey;\n }\n\n _getWalletForAccount(account, opts = {}) {\n const address = normalize(account);\n let wallet = this._wallets.find(({ publicKey }) => {\n return this._addressfromPublicKey(publicKey) === address;\n });\n if (!wallet) {\n throw new Error('HD Keyring - Unable to find matching address.');\n }\n\n if (opts.withAppKeyOrigin) {\n const { privateKey } = wallet;\n const appKeyOriginBuffer = Buffer.from(opts.withAppKeyOrigin, 'utf8');\n const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);\n const appKeyPrivateKey = arrToBufArr(keccak256(appKeyBuffer, 256));\n const appKeyPublicKey = privateToPublic(appKeyPrivateKey);\n wallet = { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };\n }\n\n return wallet;\n }\n\n /* PRIVATE / UTILITY METHODS */\n\n /**\n * Sets appropriate properties for the keyring based on the given\n * BIP39-compliant mnemonic.\n *\n * @param {string|Array<number>|Buffer} 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) {\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 const seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this._cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(seed);\n this.root = this.hdWallet.derive(this.hdPath);\n }\n\n // small helper function to convert publicKey in Uint8Array form to a publicAddress as a hex\n _addressfromPublicKey(publicKey) {\n return bufferToHex(\n publicToAddress(Buffer.from(publicKey), true),\n ).toLowerCase();\n }\n}\n\nHdKeyring.type = type;\nexport default HdKeyring;\n"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AACA,2CAM0B;AAC1B,yDAYgC;AAChC,iDAG4B;AAC5B,uDAAyD;AACzD,6EAAwE;AACxE,2CAAsE;AACtE,uDAAoD;AACpD,yDAAyD;AACzD,uDAAyD;AAEzD,WAAW;AACX,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,IAAI,GAAG,aAAa,CAAC;AAiC3B;;;;;GAKG;AACH,SAAS,gBAAgB,CACvB,mBAA4B;IAE5B,OAAO,CACL,OAAO,mBAAmB,KAAK,QAAQ;QACvC,mBAAmB,KAAK,IAAI;QAC5B,MAAM,IAAI,mBAAmB;QAC7B,mBAAmB,CAAC,IAAI,KAAK,QAAQ;QACrC,MAAM,IAAI,mBAAmB,CAC9B,CAAC;AACJ,CAAC;AAED,MAAM,SAAS;IAiBb,YAAY,OAAyB,EAAE;;QAdvC,SAAI,GAAW,IAAI,CAAC;QAQpB,WAAM,GAAW,YAAY,CAAC;QAE9B,6BAAoB,EAAE,EAAC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IACtE,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,sCACH,QAAiD;IAEjD,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,QAAQ,GAAG,uBAAA,IAAI,6DAAsB,MAA1B,IAAI,EAAuB,QAAQ,CAAC,CAAC;IAErD,MAAM,IAAI,GAAG,MAAM,IAAA,yBAAc,EAC/B,IAAI,CAAC,QAAQ,EACb,EAAE,EAAE,gBAAgB;IACpB,uBAAA,IAAI,yCAAwB,CAC7B,CAAC;IACF,IAAI,CAAC,QAAQ,GAAG,aAAK,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;IAC3C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAChD,CAAC,6EAQqB,SAAqB;IACzC,OAAO,IAAA,kBAAW,EAChB,IAAA,sBAAe,EAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAC9C,CAAC,WAAW,EAAE,CAAC;AAClB,CAAC;AAtfM,cAAI,GAAW,IAAI,AAAf,CAAgB;AAyf7B,kBAAe,SAAS,CAAC","sourcesContent":["import type { TypedTransaction } from '@ethereumjs/tx';\nimport {\n privateToPublic,\n publicToAddress,\n ecsign,\n arrToBufArr,\n bufferToHex,\n} from '@ethereumjs/util';\nimport {\n concatSig,\n decrypt,\n type EthEncryptedData,\n getEncryptionPublicKey,\n type MessageTypes,\n normalize,\n personalSign,\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 { assert, assertIsHexString, remove0x } from '@metamask/utils';\nimport { HDKey } from 'ethereum-cryptography/hdkey';\nimport { keccak256 } from 'ethereum-cryptography/keccak';\nimport { bytesToHex } from 'ethereum-cryptography/utils';\n\n// Options:\nconst hdPathString = `m/44'/60'/0'/0`;\nconst type = 'HD Key Tree';\n\ntype JsCastedBuffer = {\n type: 'Buffer';\n data: unknown;\n};\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\n/**\n * Checks if the given value is a JsCastedBuffer.\n *\n * @param maybeJsCastedBuffer - The value to check.\n * @returns `true` if the value is a JsCastedBuffer, `false` otherwise.\n */\nfunction isJsCastedBuffer(\n maybeJsCastedBuffer: unknown,\n): maybeJsCastedBuffer is JsCastedBuffer {\n return (\n typeof maybeJsCastedBuffer === 'object' &&\n maybeJsCastedBuffer !== null &&\n 'type' in maybeJsCastedBuffer &&\n maybeJsCastedBuffer.type === 'Buffer' &&\n 'data' in maybeJsCastedBuffer\n );\n}\n\nclass HdKeyring {\n static type: string = type;\n\n type: string = type;\n\n mnemonic?: 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.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<string[]> {\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 = [];\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 return this.#addressfromPublicKey(wallet.publicKey as Uint8Array);\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 async getAccounts(): Promise<string[]> {\n return this.#wallets.map((wallet) =>\n this.#addressfromPublicKey(wallet.publicKey as Uint8Array),\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: string, origin: string): Promise<string> {\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 = normalize(\n publicToAddress(wallet.publicKey).toString('hex'),\n );\n assert(appKeyAddress, 'Expected app key address to be set');\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: string,\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 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: string,\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: string,\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 // WARN: verify this cast to Buffer\n msgSig.v as unknown as Buffer,\n msgSig.r,\n 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: string,\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: string,\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: string,\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 * Remove an account from the keyring.\n *\n * @param account - The address of the account to remove.\n */\n removeAccount(account: string): void {\n const address = normalize(account);\n assert(address, 'Must specify a valid address.');\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: string,\n opts: HDKeyringAccountSelectionOptions = {},\n ): Promise<string> {\n const privKey = this.#getPrivateKeyFor(withAccount, opts);\n const publicKey = getEncryptionPublicKey(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 | JsCastedBuffer | string | Uint8Array | number[],\n ): Uint8Array {\n let mnemonicData: unknown = mnemonic;\n // when encrypted/decrypted, buffers get cast into js object with a property type set to buffer\n if (isJsCastedBuffer(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: string,\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: string): 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: string,\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: string,\n opts?: HDKeyringAccountSelectionOptions,\n ): HDKey | { privateKey: Buffer; publicKey: Buffer };\n\n #getWalletForAccount(\n account: string,\n { withAppKeyOrigin }: HDKeyringAccountSelectionOptions = {},\n ): HDKey | { privateKey: Buffer; publicKey: Buffer } {\n const address = normalize(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 = arrToBufArr(keccak256(appKeyBuffer));\n const appKeyPublicKey = 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 const seed = await mnemonicToSeed(\n this.mnemonic,\n '', // No passphrase\n this.#cryptographicFunctions,\n );\n this.hdWallet = HDKey.fromMasterSeed(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): string {\n return bufferToHex(\n publicToAddress(Buffer.from(publicKey), true),\n ).toLowerCase();\n }\n}\n\nexport default HdKeyring;\n"]}