@metamask/eth-hd-keyring 9.0.1 → 10.0.1
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 +23 -1
- package/dist/index.cjs +286 -131
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +157 -44
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +157 -44
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +288 -133
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -8
package/dist/index.mjs
CHANGED
|
@@ -1,70 +1,83 @@
|
|
|
1
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
2
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
4
|
+
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");
|
|
5
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
6
|
+
};
|
|
7
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
8
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
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
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
|
+
};
|
|
12
|
+
var _HdKeyring_instances, _HdKeyring_wallets, _HdKeyring_cryptographicFunctions, _HdKeyring_uint8ArrayToString, _HdKeyring_stringToUint8Array, _HdKeyring_mnemonicToUint8Array, _HdKeyring_getPrivateKeyFor, _HdKeyring_getWalletForAccount, _HdKeyring_initFromMnemonic, _HdKeyring_addressfromPublicKey, _HdKeyring_normalizeAddress;
|
|
1
13
|
import { privateToPublic, publicToAddress, ecsign, arrToBufArr, bufferToHex } from "@ethereumjs/util";
|
|
2
|
-
import { concatSig, decrypt, getEncryptionPublicKey, normalize, personalSign, signTypedData, SignTypedDataVersion } from "@metamask/eth-sig-util";
|
|
14
|
+
import { concatSig, decrypt, getEncryptionPublicKey, normalize, personalSign, signEIP7702Authorization, signTypedData, SignTypedDataVersion } from "@metamask/eth-sig-util";
|
|
3
15
|
import { mnemonicToSeed } from "@metamask/key-tree";
|
|
4
16
|
import { generateMnemonic } from "@metamask/scure-bip39";
|
|
5
17
|
import { wordlist } from "@metamask/scure-bip39/dist/wordlists/english.js";
|
|
6
|
-
import { assertIsHexString, remove0x } from "@metamask/utils";
|
|
18
|
+
import { add0x, assert, assertIsHexString, remove0x } from "@metamask/utils";
|
|
7
19
|
import { HDKey } from "ethereum-cryptography/hdkey";
|
|
8
20
|
import { keccak256 } from "ethereum-cryptography/keccak";
|
|
9
21
|
import { bytesToHex } from "ethereum-cryptography/utils";
|
|
10
22
|
// Options:
|
|
11
23
|
const hdPathString = `m/44'/60'/0'/0`;
|
|
12
24
|
const type = 'HD Key Tree';
|
|
25
|
+
/**
|
|
26
|
+
* Checks if the given value is a valid serialized Buffer compatible with
|
|
27
|
+
* the return type of `Buffer.toJSON`.
|
|
28
|
+
*
|
|
29
|
+
* @param value - The value to check.
|
|
30
|
+
* @returns `true` if the value is a valid serialized buffer, `false` otherwise.
|
|
31
|
+
*/
|
|
32
|
+
function isSerializedBuffer(value) {
|
|
33
|
+
return (typeof value === 'object' &&
|
|
34
|
+
value !== null &&
|
|
35
|
+
'type' in value &&
|
|
36
|
+
value.type === 'Buffer' &&
|
|
37
|
+
'data' in value &&
|
|
38
|
+
Array.isArray(value.data));
|
|
39
|
+
}
|
|
13
40
|
class HdKeyring {
|
|
14
|
-
/* PUBLIC METHODS */
|
|
15
41
|
constructor(opts = {}) {
|
|
42
|
+
_HdKeyring_instances.add(this);
|
|
16
43
|
this.type = type;
|
|
17
|
-
this.
|
|
44
|
+
this.hdPath = hdPathString;
|
|
45
|
+
_HdKeyring_wallets.set(this, []);
|
|
46
|
+
_HdKeyring_cryptographicFunctions.set(this, void 0);
|
|
18
47
|
// Cryptographic functions to be used by `@metamask/key-tree`. It will use built-in implementations if not provided here.
|
|
19
|
-
this
|
|
48
|
+
__classPrivateFieldSet(this, _HdKeyring_cryptographicFunctions, opts.cryptographicFunctions, "f");
|
|
20
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Initialize the keyring with a random mnemonic.
|
|
52
|
+
*
|
|
53
|
+
* @returns A promise that resolves when the process is complete.
|
|
54
|
+
*/
|
|
21
55
|
async generateRandomMnemonic() {
|
|
22
|
-
await this.
|
|
23
|
-
}
|
|
24
|
-
_uint8ArrayToString(mnemonic) {
|
|
25
|
-
const recoveredIndices = Array.from(new Uint16Array(new Uint8Array(mnemonic).buffer));
|
|
26
|
-
return recoveredIndices.map((i) => wordlist[i]).join(' ');
|
|
27
|
-
}
|
|
28
|
-
_stringToUint8Array(mnemonic) {
|
|
29
|
-
const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));
|
|
30
|
-
return new Uint8Array(new Uint16Array(indices).buffer);
|
|
31
|
-
}
|
|
32
|
-
_mnemonicToUint8Array(mnemonic) {
|
|
33
|
-
let mnemonicData = mnemonic;
|
|
34
|
-
// when encrypted/decrypted, buffers get cast into js object with a property type set to buffer
|
|
35
|
-
if (mnemonic && mnemonic.type && mnemonic.type === 'Buffer') {
|
|
36
|
-
mnemonicData = mnemonic.data;
|
|
37
|
-
}
|
|
38
|
-
if (
|
|
39
|
-
// this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings
|
|
40
|
-
typeof mnemonicData === 'string' ||
|
|
41
|
-
Buffer.isBuffer(mnemonicData) ||
|
|
42
|
-
Array.isArray(mnemonicData)) {
|
|
43
|
-
let mnemonicAsString = mnemonicData;
|
|
44
|
-
if (Array.isArray(mnemonicData)) {
|
|
45
|
-
mnemonicAsString = Buffer.from(mnemonicData).toString();
|
|
46
|
-
}
|
|
47
|
-
else if (Buffer.isBuffer(mnemonicData)) {
|
|
48
|
-
mnemonicAsString = mnemonicData.toString();
|
|
49
|
-
}
|
|
50
|
-
return this._stringToUint8Array(mnemonicAsString);
|
|
51
|
-
}
|
|
52
|
-
else if (mnemonicData instanceof Object &&
|
|
53
|
-
!(mnemonicData instanceof Uint8Array)) {
|
|
54
|
-
// when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array
|
|
55
|
-
return Uint8Array.from(Object.values(mnemonicData));
|
|
56
|
-
}
|
|
57
|
-
return mnemonicData;
|
|
56
|
+
await __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_initFromMnemonic).call(this, generateMnemonic(wordlist));
|
|
58
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Return the serialized state of the keyring.
|
|
60
|
+
*
|
|
61
|
+
* @returns The serialized state of the keyring.
|
|
62
|
+
*/
|
|
59
63
|
async serialize() {
|
|
60
|
-
|
|
61
|
-
|
|
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
|
+
}
|
|
62
69
|
return {
|
|
63
|
-
mnemonic
|
|
64
|
-
numberOfAccounts: this.
|
|
70
|
+
mnemonic,
|
|
71
|
+
numberOfAccounts: __classPrivateFieldGet(this, _HdKeyring_wallets, "f").length,
|
|
65
72
|
hdPath: this.hdPath,
|
|
66
73
|
};
|
|
67
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
|
+
*/
|
|
68
81
|
async deserialize(opts = {}) {
|
|
69
82
|
if (opts.numberOfAccounts && !opts.mnemonic) {
|
|
70
83
|
throw new Error('Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic');
|
|
@@ -72,159 +85,301 @@ class HdKeyring {
|
|
|
72
85
|
if (this.root) {
|
|
73
86
|
throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
|
|
74
87
|
}
|
|
75
|
-
this
|
|
76
|
-
this._wallets = [];
|
|
88
|
+
__classPrivateFieldSet(this, _HdKeyring_wallets, [], "f");
|
|
77
89
|
this.mnemonic = null;
|
|
78
90
|
this.root = null;
|
|
79
|
-
this.hdPath = opts.hdPath
|
|
91
|
+
this.hdPath = opts.hdPath ?? hdPathString;
|
|
80
92
|
if (opts.mnemonic) {
|
|
81
|
-
await this.
|
|
93
|
+
await __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_initFromMnemonic).call(this, opts.mnemonic);
|
|
82
94
|
}
|
|
83
95
|
if (opts.numberOfAccounts) {
|
|
84
96
|
return this.addAccounts(opts.numberOfAccounts);
|
|
85
97
|
}
|
|
86
98
|
return [];
|
|
87
99
|
}
|
|
88
|
-
|
|
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) {
|
|
89
108
|
if (!this.root) {
|
|
90
109
|
throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');
|
|
91
110
|
}
|
|
92
|
-
const oldLen = this.
|
|
111
|
+
const oldLen = __classPrivateFieldGet(this, _HdKeyring_wallets, "f").length;
|
|
93
112
|
const newWallets = [];
|
|
94
113
|
for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {
|
|
95
114
|
const wallet = this.root.deriveChild(i);
|
|
96
115
|
newWallets.push(wallet);
|
|
97
|
-
this.
|
|
116
|
+
__classPrivateFieldGet(this, _HdKeyring_wallets, "f").push(wallet);
|
|
98
117
|
}
|
|
99
|
-
const hexWallets = newWallets.map((
|
|
100
|
-
|
|
118
|
+
const hexWallets = newWallets.map((wallet) => {
|
|
119
|
+
assert(wallet.publicKey, 'Expected public key to be set');
|
|
120
|
+
return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, wallet.publicKey);
|
|
101
121
|
});
|
|
102
122
|
return Promise.resolve(hexWallets);
|
|
103
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* Get the addresses of all accounts in the keyring.
|
|
126
|
+
*
|
|
127
|
+
* @returns The addresses of all accounts in the keyring.
|
|
128
|
+
*/
|
|
104
129
|
getAccounts() {
|
|
105
|
-
return this.
|
|
130
|
+
return __classPrivateFieldGet(this, _HdKeyring_wallets, "f").map((wallet) => {
|
|
131
|
+
assert(wallet.publicKey, 'Expected public key to be set');
|
|
132
|
+
return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, wallet.publicKey);
|
|
133
|
+
});
|
|
106
134
|
}
|
|
107
|
-
|
|
108
|
-
|
|
135
|
+
/**
|
|
136
|
+
* Get the public address of the account for the given app key origin.
|
|
137
|
+
*
|
|
138
|
+
* @param address - The address of the account.
|
|
139
|
+
* @param origin - The origin of the app requesting the account.
|
|
140
|
+
* @returns The public address of the account.
|
|
141
|
+
*/
|
|
109
142
|
async getAppKeyAddress(address, origin) {
|
|
110
143
|
if (!origin || typeof origin !== 'string') {
|
|
111
144
|
throw new Error(`'origin' must be a non-empty string`);
|
|
112
145
|
}
|
|
113
|
-
const wallet = this.
|
|
146
|
+
const wallet = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address, {
|
|
114
147
|
withAppKeyOrigin: origin,
|
|
115
148
|
});
|
|
116
|
-
|
|
149
|
+
assert(wallet.publicKey, 'Expected public key to be set');
|
|
150
|
+
const appKeyAddress = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_normalizeAddress).call(this, publicToAddress(wallet.publicKey).toString('hex'));
|
|
117
151
|
return appKeyAddress;
|
|
118
152
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
153
|
+
/**
|
|
154
|
+
* Export the private key for a specific account.
|
|
155
|
+
*
|
|
156
|
+
* @param address - The address of the account.
|
|
157
|
+
* @param opts - The options for exporting the account.
|
|
158
|
+
* @param opts.withAppKeyOrigin - An optional string to export the account
|
|
159
|
+
* for a specific app origin.
|
|
160
|
+
* @returns The private key of the account.
|
|
161
|
+
*/
|
|
162
|
+
async exportAccount(address, opts) {
|
|
163
|
+
const wallet = opts
|
|
164
|
+
? __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address, opts)
|
|
165
|
+
: __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address);
|
|
166
|
+
const { privateKey } = wallet;
|
|
167
|
+
assert(privateKey instanceof Uint8Array, 'Expected private key to be of type Uint8Array');
|
|
168
|
+
return bytesToHex(privateKey);
|
|
123
169
|
}
|
|
124
|
-
|
|
170
|
+
/**
|
|
171
|
+
* Sign a transaction using the private key of the specified account.
|
|
172
|
+
*
|
|
173
|
+
* @param address - The address of the account.
|
|
174
|
+
* @param tx - The transaction to sign.
|
|
175
|
+
* @param opts - The options for signing the transaction.
|
|
176
|
+
* @returns The signed transaction.
|
|
177
|
+
*/
|
|
125
178
|
async signTransaction(address, tx, opts = {}) {
|
|
126
|
-
const privKey = this.
|
|
127
|
-
const signedTx = tx.sign(privKey);
|
|
179
|
+
const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, opts);
|
|
180
|
+
const signedTx = tx.sign(Buffer.from(privKey));
|
|
128
181
|
// Newer versions of Ethereumjs-tx are immutable and return a new tx object
|
|
129
|
-
return signedTx
|
|
182
|
+
return signedTx ?? tx;
|
|
130
183
|
}
|
|
131
|
-
|
|
184
|
+
/**
|
|
185
|
+
* Sign a message using the private key of the specified account.
|
|
186
|
+
*
|
|
187
|
+
* @param address - The address of the account.
|
|
188
|
+
* @param data - The data to sign.
|
|
189
|
+
* @param opts - The options for signing the message.
|
|
190
|
+
* @returns The signature of the message.
|
|
191
|
+
*/
|
|
132
192
|
async signMessage(address, data, opts = {}) {
|
|
133
193
|
assertIsHexString(data);
|
|
134
194
|
const message = remove0x(data);
|
|
135
|
-
const privKey = this.
|
|
136
|
-
const msgSig = ecsign(Buffer.from(message, 'hex'), privKey);
|
|
137
|
-
const rawMsgSig = concatSig(
|
|
195
|
+
const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, opts);
|
|
196
|
+
const msgSig = ecsign(Buffer.from(message, 'hex'), Buffer.from(privKey));
|
|
197
|
+
const rawMsgSig = concatSig(
|
|
198
|
+
// WARN: verify this cast to Buffer
|
|
199
|
+
msgSig.v, msgSig.r, msgSig.s);
|
|
138
200
|
return rawMsgSig;
|
|
139
201
|
}
|
|
140
|
-
|
|
202
|
+
/**
|
|
203
|
+
* Sign a personal message using the private key of the specified account.
|
|
204
|
+
* This method is compatible with the `personal_sign` RPC method.
|
|
205
|
+
*
|
|
206
|
+
* @param address - The address of the account.
|
|
207
|
+
* @param msgHex - The message to sign.
|
|
208
|
+
* @param opts - The options for signing the message.
|
|
209
|
+
* @returns The signature of the message.
|
|
210
|
+
*/
|
|
141
211
|
async signPersonalMessage(address, msgHex, opts = {}) {
|
|
142
|
-
const privKey = this.
|
|
143
|
-
const privateKey = Buffer.from(privKey
|
|
144
|
-
|
|
145
|
-
return sig;
|
|
212
|
+
const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, address, opts);
|
|
213
|
+
const privateKey = Buffer.from(privKey);
|
|
214
|
+
return personalSign({ privateKey, data: msgHex });
|
|
146
215
|
}
|
|
147
|
-
|
|
216
|
+
/**
|
|
217
|
+
* Decrypt an encrypted message using the private key of the specified account.
|
|
218
|
+
* The message must be encrypted using the public key of the account.
|
|
219
|
+
* This method is compatible with the `eth_decryptMessage` RPC method
|
|
220
|
+
*
|
|
221
|
+
* @param withAccount - The address of the account.
|
|
222
|
+
* @param encryptedData - The encrypted data.
|
|
223
|
+
* @returns The decrypted message.
|
|
224
|
+
*/
|
|
148
225
|
async decryptMessage(withAccount, encryptedData) {
|
|
149
|
-
const wallet = this.
|
|
226
|
+
const wallet = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, withAccount);
|
|
150
227
|
const { privateKey: privateKeyAsUint8Array } = wallet;
|
|
228
|
+
assert(privateKeyAsUint8Array, 'Expected private key to be set');
|
|
151
229
|
const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');
|
|
152
|
-
|
|
153
|
-
return sig;
|
|
230
|
+
return decrypt({ privateKey: privateKeyAsHex, encryptedData });
|
|
154
231
|
}
|
|
155
|
-
|
|
232
|
+
/**
|
|
233
|
+
* Sign a typed message using the private key of the specified account.
|
|
234
|
+
* This method is compatible with the `eth_signTypedData` RPC method.
|
|
235
|
+
*
|
|
236
|
+
* @param withAccount - The address of the account.
|
|
237
|
+
* @param typedData - The typed data to sign.
|
|
238
|
+
* @param opts - The options for signing the message.
|
|
239
|
+
* @returns The signature of the message.
|
|
240
|
+
*/
|
|
156
241
|
async signTypedData(withAccount, typedData, opts = { version: SignTypedDataVersion.V1 }) {
|
|
157
242
|
// Treat invalid versions as "V1"
|
|
158
243
|
const version = Object.keys(SignTypedDataVersion).includes(opts.version)
|
|
159
244
|
? opts.version
|
|
160
245
|
: SignTypedDataVersion.V1;
|
|
161
|
-
const privateKey = this.
|
|
162
|
-
return signTypedData({
|
|
246
|
+
const privateKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, withAccount, opts);
|
|
247
|
+
return signTypedData({
|
|
248
|
+
privateKey: Buffer.from(privateKey),
|
|
249
|
+
data: typedData,
|
|
250
|
+
version,
|
|
251
|
+
});
|
|
163
252
|
}
|
|
253
|
+
/**
|
|
254
|
+
* Sign an EIP-7702 authorization using the private key of the specified account.
|
|
255
|
+
* This method is compatible with the EIP-7702 standard for enabling smart contract code for EOAs.
|
|
256
|
+
*
|
|
257
|
+
* @param withAccount - The address of the account.
|
|
258
|
+
* @param authorization - The EIP-7702 authorization to sign.
|
|
259
|
+
* @param opts - The options for selecting the account.
|
|
260
|
+
* @returns The signature of the authorization.
|
|
261
|
+
*/
|
|
262
|
+
async signEip7702Authorization(withAccount, authorization, opts) {
|
|
263
|
+
const privateKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, withAccount, opts);
|
|
264
|
+
return signEIP7702Authorization({
|
|
265
|
+
privateKey: Buffer.from(privateKey),
|
|
266
|
+
authorization,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Remove an account from the keyring.
|
|
271
|
+
*
|
|
272
|
+
* @param account - The address of the account to remove.
|
|
273
|
+
*/
|
|
164
274
|
removeAccount(account) {
|
|
165
|
-
const address =
|
|
166
|
-
if (!this
|
|
167
|
-
.map(({ publicKey }) => this.
|
|
275
|
+
const address = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_normalizeAddress).call(this, account);
|
|
276
|
+
if (!__classPrivateFieldGet(this, _HdKeyring_wallets, "f")
|
|
277
|
+
.map(({ publicKey }) => publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey))
|
|
168
278
|
.includes(address)) {
|
|
169
279
|
throw new Error(`Address ${address} not found in this keyring`);
|
|
170
280
|
}
|
|
171
|
-
this
|
|
281
|
+
__classPrivateFieldSet(this, _HdKeyring_wallets, __classPrivateFieldGet(this, _HdKeyring_wallets, "f").filter(({ publicKey }) => publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey) !== address), "f");
|
|
172
282
|
}
|
|
173
|
-
|
|
283
|
+
/**
|
|
284
|
+
* Get the public key of the account to be used for encryption.
|
|
285
|
+
*
|
|
286
|
+
* @param withAccount - The address of the account.
|
|
287
|
+
* @param opts - The options for selecting the account.
|
|
288
|
+
* @returns The public key of the account.
|
|
289
|
+
*/
|
|
174
290
|
async getEncryptionPublicKey(withAccount, opts = {}) {
|
|
175
|
-
const privKey = this.
|
|
176
|
-
const publicKey = getEncryptionPublicKey(privKey);
|
|
291
|
+
const privKey = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getPrivateKeyFor).call(this, withAccount, opts);
|
|
292
|
+
const publicKey = getEncryptionPublicKey(bytesToHex(privKey));
|
|
177
293
|
return publicKey;
|
|
178
294
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
295
|
+
}
|
|
296
|
+
_HdKeyring_wallets = new WeakMap(), _HdKeyring_cryptographicFunctions = new WeakMap(), _HdKeyring_instances = new WeakSet(), _HdKeyring_uint8ArrayToString = function _HdKeyring_uint8ArrayToString(mnemonic) {
|
|
297
|
+
const recoveredIndices = Array.from(new Uint16Array(new Uint8Array(mnemonic).buffer));
|
|
298
|
+
return recoveredIndices.map((i) => wordlist[i]).join(' ');
|
|
299
|
+
}, _HdKeyring_stringToUint8Array = function _HdKeyring_stringToUint8Array(mnemonic) {
|
|
300
|
+
const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));
|
|
301
|
+
return new Uint8Array(new Uint16Array(indices).buffer);
|
|
302
|
+
}, _HdKeyring_mnemonicToUint8Array = function _HdKeyring_mnemonicToUint8Array(mnemonic) {
|
|
303
|
+
let mnemonicData = mnemonic;
|
|
304
|
+
// When using `Buffer.toJSON()`, the Buffer is serialized into an object
|
|
305
|
+
// with the structure `{ type: 'Buffer', data: [...] }`
|
|
306
|
+
if (isSerializedBuffer(mnemonic)) {
|
|
307
|
+
mnemonicData = mnemonic.data;
|
|
185
308
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
309
|
+
if (
|
|
310
|
+
// this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings
|
|
311
|
+
typeof mnemonicData === 'string' ||
|
|
312
|
+
Buffer.isBuffer(mnemonicData) ||
|
|
313
|
+
Array.isArray(mnemonicData)) {
|
|
314
|
+
let mnemonicAsString;
|
|
315
|
+
if (Array.isArray(mnemonicData)) {
|
|
316
|
+
mnemonicAsString = Buffer.from(mnemonicData).toString();
|
|
193
317
|
}
|
|
194
|
-
if (
|
|
195
|
-
|
|
196
|
-
const appKeyOriginBuffer = Buffer.from(opts.withAppKeyOrigin, 'utf8');
|
|
197
|
-
const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
|
|
198
|
-
const appKeyPrivateKey = arrToBufArr(keccak256(appKeyBuffer, 256));
|
|
199
|
-
const appKeyPublicKey = privateToPublic(appKeyPrivateKey);
|
|
200
|
-
wallet = { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
|
|
318
|
+
else if (Buffer.isBuffer(mnemonicData)) {
|
|
319
|
+
mnemonicAsString = mnemonicData.toString();
|
|
201
320
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
/* PRIVATE / UTILITY METHODS */
|
|
205
|
-
/**
|
|
206
|
-
* Sets appropriate properties for the keyring based on the given
|
|
207
|
-
* BIP39-compliant mnemonic.
|
|
208
|
-
*
|
|
209
|
-
* @param {string|Array<number>|Buffer} mnemonic - A seed phrase represented
|
|
210
|
-
* as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input
|
|
211
|
-
* passed as type buffer or array of UTF-8 bytes must be NFKD normalized.
|
|
212
|
-
*/
|
|
213
|
-
async _initFromMnemonic(mnemonic) {
|
|
214
|
-
if (this.root) {
|
|
215
|
-
throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
|
|
321
|
+
else {
|
|
322
|
+
mnemonicAsString = mnemonicData;
|
|
216
323
|
}
|
|
217
|
-
this
|
|
218
|
-
const seed = await mnemonicToSeed(this.mnemonic, '', // No passphrase
|
|
219
|
-
this._cryptographicFunctions);
|
|
220
|
-
this.hdWallet = HDKey.fromMasterSeed(seed);
|
|
221
|
-
this.root = this.hdWallet.derive(this.hdPath);
|
|
324
|
+
return __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_stringToUint8Array).call(this, mnemonicAsString);
|
|
222
325
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
326
|
+
else if (mnemonicData instanceof Object &&
|
|
327
|
+
!(mnemonicData instanceof Uint8Array)) {
|
|
328
|
+
// when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array
|
|
329
|
+
return Uint8Array.from(Object.values(mnemonicData));
|
|
226
330
|
}
|
|
227
|
-
|
|
331
|
+
assert(mnemonicData instanceof Uint8Array, 'Expected Uint8Array mnemonic');
|
|
332
|
+
return mnemonicData;
|
|
333
|
+
}, _HdKeyring_getPrivateKeyFor = function _HdKeyring_getPrivateKeyFor(address, opts) {
|
|
334
|
+
if (!address) {
|
|
335
|
+
throw new Error('Must specify address.');
|
|
336
|
+
}
|
|
337
|
+
const wallet = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_getWalletForAccount).call(this, address, opts);
|
|
338
|
+
assert(wallet.privateKey, 'Missing private key');
|
|
339
|
+
return wallet.privateKey;
|
|
340
|
+
}, _HdKeyring_getWalletForAccount = function _HdKeyring_getWalletForAccount(account, { withAppKeyOrigin } = {}) {
|
|
341
|
+
const address = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_normalizeAddress).call(this, account);
|
|
342
|
+
const wallet = __classPrivateFieldGet(this, _HdKeyring_wallets, "f").find(({ publicKey }) => {
|
|
343
|
+
return publicKey && __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_addressfromPublicKey).call(this, publicKey) === address;
|
|
344
|
+
});
|
|
345
|
+
if (!wallet) {
|
|
346
|
+
throw new Error('HD Keyring - Unable to find matching address.');
|
|
347
|
+
}
|
|
348
|
+
if (withAppKeyOrigin) {
|
|
349
|
+
const { privateKey } = wallet;
|
|
350
|
+
assert(privateKey, 'Expected private key to be set');
|
|
351
|
+
const appKeyOriginBuffer = Buffer.from(withAppKeyOrigin, 'utf8');
|
|
352
|
+
const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
|
|
353
|
+
const appKeyPrivateKey = arrToBufArr(keccak256(appKeyBuffer));
|
|
354
|
+
const appKeyPublicKey = privateToPublic(appKeyPrivateKey);
|
|
355
|
+
return { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
|
|
356
|
+
}
|
|
357
|
+
return wallet;
|
|
358
|
+
}, _HdKeyring_initFromMnemonic =
|
|
359
|
+
/**
|
|
360
|
+
* Sets appropriate properties for the keyring based on the given
|
|
361
|
+
* BIP39-compliant mnemonic.
|
|
362
|
+
*
|
|
363
|
+
* @param mnemonic - A seed phrase represented
|
|
364
|
+
* as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input
|
|
365
|
+
* passed as type buffer or array of UTF-8 bytes must be NFKD normalized.
|
|
366
|
+
*/
|
|
367
|
+
async function _HdKeyring_initFromMnemonic(mnemonic) {
|
|
368
|
+
if (this.root) {
|
|
369
|
+
throw new Error('Eth-Hd-Keyring: Secret recovery phrase already provided');
|
|
370
|
+
}
|
|
371
|
+
this.mnemonic = __classPrivateFieldGet(this, _HdKeyring_instances, "m", _HdKeyring_mnemonicToUint8Array).call(this, mnemonic);
|
|
372
|
+
const seed = await mnemonicToSeed(this.mnemonic, '', // No passphrase
|
|
373
|
+
__classPrivateFieldGet(this, _HdKeyring_cryptographicFunctions, "f"));
|
|
374
|
+
this.hdWallet = HDKey.fromMasterSeed(seed);
|
|
375
|
+
this.root = this.hdWallet.derive(this.hdPath);
|
|
376
|
+
}, _HdKeyring_addressfromPublicKey = function _HdKeyring_addressfromPublicKey(publicKey) {
|
|
377
|
+
return add0x(bufferToHex(publicToAddress(Buffer.from(publicKey), true)).toLowerCase());
|
|
378
|
+
}, _HdKeyring_normalizeAddress = function _HdKeyring_normalizeAddress(address) {
|
|
379
|
+
const normalized = normalize(address);
|
|
380
|
+
assert(normalized, 'Expected address to be set');
|
|
381
|
+
return add0x(normalized);
|
|
382
|
+
};
|
|
228
383
|
HdKeyring.type = type;
|
|
229
384
|
export default HdKeyring;
|
|
230
385
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,eAAe,EACf,MAAM,EACN,WAAW,EACX,WAAW,EACZ,yBAAyB;AAC1B,OAAO,EACL,SAAS,EACT,OAAO,EACP,sBAAsB,EACtB,SAAS,EACT,YAAY,EACZ,aAAa,EACb,oBAAoB,EACrB,+BAA+B;AAChC,OAAO,EAAE,cAAc,EAAE,2BAA2B;AACpD,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AACzD,OAAO,EAAE,QAAQ,EAAE,wDAAqD;AACxE,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,wBAAwB;AAC9D,OAAO,EAAE,KAAK,EAAE,oCAAoC;AACpD,OAAO,EAAE,SAAS,EAAE,qCAAqC;AACzD,OAAO,EAAE,UAAU,EAAE,oCAAoC;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,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EAAE,GAAG,CAAC,CAAC,CAAC;YACnE,MAAM,eAAe,GAAG,eAAe,CAAC,gBAAgB,CAAC,CAAC;YAC1D,MAAM,GAAG,EAAE,UAAU,EAAE,gBAAgB,EAAE,SAAS,EAAE,eAAe,EAAE,CAAC;QACxE,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,+BAA+B;IAE/B;;;;;;;OAOG;IACH,KAAK,CAAC,iBAAiB,CAAC,QAAQ;QAC9B,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACd,MAAM,IAAI,KAAK,CACb,yDAAyD,CAC1D,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,qBAAqB,CAAC,QAAQ,CAAC,CAAC;QAErD,MAAM,IAAI,GAAG,MAAM,cAAc,CAC/B,IAAI,CAAC,QAAQ,EACb,EAAE,EAAE,gBAAgB;QACpB,IAAI,CAAC,uBAAuB,CAC7B,CAAC;QACF,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;QAC3C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAChD,CAAC;IAED,4FAA4F;IAC5F,qBAAqB,CAAC,SAAS;QAC7B,OAAO,WAAW,CAChB,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAC9C,CAAC,WAAW,EAAE,CAAC;IAClB,CAAC;CACF;AAED,SAAS,CAAC,IAAI,GAAG,IAAI,CAAC;AACtB,eAAe,SAAS,CAAC","sourcesContent":["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 _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.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EACL,eAAe,EACf,eAAe,EACf,MAAM,EACN,WAAW,EACX,WAAW,EACZ,yBAAyB;AAC1B,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,EAEjB,QAAQ,EACT,wBAAwB;AACzB,OAAO,EAAE,KAAK,EAAE,oCAAoC;AACpD,OAAO,EAAE,SAAS,EAAE,qCAAqC;AACzD,OAAO,EAAE,UAAU,EAAE,oCAAoC;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,SAAS;IAiBb,YAAY,OAAyB,EAAE;;QAdvC,SAAI,GAAW,IAAI,CAAC;QAQpB,WAAM,GAAW,YAAY,CAAC;QAE9B,6BAAoB,EAAE,EAAC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,AAAf,CAAgB;AA2hB7B,eAAe,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 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 type Hex,\n remove0x,\n} 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\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\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<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 publicToAddress(wallet.publicKey).toString('hex'),\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 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 // 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: 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(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 = 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): Hex {\n return add0x(\n bufferToHex(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\nexport default HdKeyring;\n"]}
|