@metamask-previews/eth-hd-keyring 7.0.1-38c4bd5

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 ADDED
@@ -0,0 +1,121 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [7.0.1]
11
+
12
+ ### Changed
13
+
14
+ - **BREAKING:** Update minimum Node.js version from v14 to v16 ([#98](https://github.com/MetaMask/eth-hd-keyring/pull/98))
15
+ - Bump dependencies ([#99](https://github.com/MetaMask/eth-hd-keyring/pull/99))
16
+ - **BREAKING:** `@metamask/eth-sig-util` from `^6.0.0` to `^7.0.0`
17
+ - **BREAKING:** `@metamask/utils` from `^5.0.2` to `^8.1.0`
18
+ - `@ethereumjs/tx` from `^4.1.1` to `^4.2.0`
19
+ - `@ethereumjs/util` from `8.0.5` to `^8.1.0`
20
+ - `ethereum-cryptography` from `^1.2.0` to `^2.1.2`
21
+
22
+ ## [7.0.0] [RETRACTED]
23
+
24
+ ### Changed
25
+
26
+ - This version was retracted due to a bug causing code to be missing from published package.
27
+
28
+ ## [6.0.2]
29
+
30
+ ### Fixed
31
+
32
+ - Bump dependencies ([#94](https://github.com/MetaMask/eth-hd-keyring/pull/94))
33
+ - `@ethereumjs/util` from `^8.0.2` to `^8.1.0`
34
+ - `@metamask/eth-sig-util` from `^5.0.2` to `^6.0.0`
35
+ - `@metamask/scure-bip39` from `^2.0.3` to `^2.1.0`
36
+ - `@metamask/utils` from `^5.0.0` to `^5.0.2`
37
+ - `ethereum-cryptography` from `^1.1.2` to `^1.2.0`
38
+
39
+ ## [6.0.1] [RETRACTED]
40
+
41
+ ### Changed
42
+
43
+ - This version was retracted due to a bug causing code to be missing from published package.
44
+
45
+ ## [6.0.0]
46
+
47
+ ### Changed
48
+
49
+ - Revert mnemonic serialization format from `Record<number, number>` (i.e. a stringified `Uint8Array`) which was introduced in v5.0.0 back to an untyped array of utf8 encoded bytes, which was the format prior to v5.0.0 ([#81](https://github.com/MetaMask/eth-hd-keyring/pull/81))
50
+
51
+ ## [5.0.1] [DEPRECATED]
52
+
53
+ ### Removed
54
+
55
+ - Remove prepack script and references in order to fix publish release flow ([#77](https://github.com/MetaMask/eth-hd-keyring/pull/77))
56
+
57
+ ## [5.0.0] [DEPRECATED]
58
+
59
+ ### Changed
60
+
61
+ - **BREAKING**: Update minimum Node.js version from v12 to v14 ([#67](https://github.com/MetaMask/eth-hd-keyring/pull/67))
62
+ - **BREAKING:** Makes version-specific `signTypedData` methods private ([#71](https://github.com/MetaMask/eth-hd-keyring/pull/71))
63
+ - Consumers should use the generic `signTypedData` method and pass the version they'd like as a property in the options argument.
64
+ - **BREAKING:** Makes the `wallets` property private ([#71](https://github.com/MetaMask/eth-hd-keyring/pull/71))
65
+ - Consumers should not use this property as it is intended for internal use only.
66
+ - **BREAKING:** Makes `getPrivateKeyFor` a private method ([#71](https://github.com/MetaMask/eth-hd-keyring/pull/71))
67
+ - Consumers who wish to get the private key for a given account should use the `exportAccount` method.
68
+ - **BREAKING:** Bumps browser requirements to those with ES2020 support or greater ([#70](https://github.com/MetaMask/eth-hd-keyring/pull/70))
69
+ - This change is introduced in update of `@metamask/eth-sig-util` to v5 and new direct dependency on `ethereumjs/util` v8.0.2
70
+ - Replaces use of `ethereumjs-wallet` implementation of hdkey with one from `ethereum-cryptography` and adapts accordingly. ([#69](https://github.com/MetaMask/eth-hd-keyring/pull/69))
71
+ - Replaces `@metamask/bip39` with `@metamask/scure-bip39` ([#67](https://github.com/MetaMask/eth-hd-keyring/pull/67))
72
+
73
+ ### Removed
74
+
75
+ - **BREAKING:** Remove redundant `newGethSignMessage` method ([#71](https://github.com/MetaMask/eth-hd-keyring/pull/71))
76
+ - Consumers can use `signPersonalMessage` method as a replacement for newGethSignMessage.
77
+ - **BREAKING:** `HDKeyring` no longer extends `EventEmitter`, so no `EventEmitter` methods are available on this class ([#70](https://github.com/MetaMask/eth-hd-keyring/pull/70))
78
+ - Removes `ethereumjs-util` dependency. ([#67](https://github.com/MetaMask/eth-hd-keyring/pull/67))
79
+
80
+ ## [4.0.2]
81
+
82
+ ### Added
83
+
84
+ - Add parameter validation for constructor / `deserialize` method ([#65](https://github.com/MetaMask/eth-hd-keyring/pull/65))
85
+ - As of v4.0.0, the `deserialize` method (which is also called by the constructor) can no longer generate accounts with the `numberOfAccounts` option without a `mnemonic`. Prior to v4.0.0, a mnemonic was generated automatically if it was missing, but we now want to ensure a mnemonic is never implicitly generated without the caller knowing.
86
+
87
+ ## [4.0.1]
88
+
89
+ ### Added
90
+
91
+ - Add tests to get coverage to 100% ([#62](https://github.com/MetaMask/eth-hd-keyring/pull/62))
92
+
93
+ ### Fixed
94
+
95
+ - Fix bug where an unexpected error would occur if the mnemonic passed to `_initFromMnemonic` was a buffer array ([#62](https://github.com/MetaMask/eth-hd-keyring/pull/62))
96
+
97
+ ## [4.0.0]
98
+
99
+ ### Changed
100
+
101
+ - **BREAKING**: Do not allow re-initialization of keyring instance ([#55](https://github.com/MetaMask/eth-hd-keyring/pull/55))
102
+ - Consumers are now required to call generateRandomMnemonic() after initialization for creating new SRPs.
103
+ - **BREAKING**: Update minimum Node.js version from v10 to v12 ([#45](https://github.com/MetaMask/eth-hd-keyring/pull/45))
104
+ - Add `@lavamoat/allow-scripts` ([#47](https://github.com/MetaMask/eth-hd-keyring/pull/47))
105
+ - We now have an allowlist for all post-install scripts. The standard setup script has been added, along with new contributor documentation in the README to explain this script.
106
+ - Obfuscate serialized mnemonic ([#59](https://github.com/MetaMask/eth-hd-keyring/pull/59))
107
+ - Class variable `mnemonic` on `HdKeyring` can now be either type `Buffer` or type `string`.
108
+ - Deserialize method (and `HdKeyring` constructor by extension) can no longer be passed an options object containing a value for `numberOfAccounts` if it is not also containing a value for `mnemonic`.
109
+ - Package name changed from `eth-hd-keyring` to `@metamask/eth-hd-keyring`.
110
+
111
+ [Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@7.0.1...HEAD
112
+ [7.0.1]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@7.0.0...@metamask/eth-hd-keyring@7.0.1
113
+ [7.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@6.0.2...@metamask/eth-hd-keyring@7.0.0
114
+ [6.0.2]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@6.0.1...@metamask/eth-hd-keyring@6.0.2
115
+ [6.0.1]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@6.0.0...@metamask/eth-hd-keyring@6.0.1
116
+ [6.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@5.0.1...@metamask/eth-hd-keyring@6.0.0
117
+ [5.0.1]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@5.0.0...@metamask/eth-hd-keyring@5.0.1
118
+ [5.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@4.0.2...@metamask/eth-hd-keyring@5.0.0
119
+ [4.0.2]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@4.0.1...@metamask/eth-hd-keyring@4.0.2
120
+ [4.0.1]: https://github.com/MetaMask/accounts/compare/@metamask/eth-hd-keyring@4.0.0...@metamask/eth-hd-keyring@4.0.1
121
+ [4.0.0]: https://github.com/MetaMask/accounts/releases/tag/@metamask/eth-hd-keyring@4.0.0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2020 MetaMask
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,127 @@
1
+ # HD Keyring
2
+
3
+ A simple JS class wrapped around [ethereumjs-wallet](https://github.com/ethereumjs/ethereumjs-wallet) designed to expose an interface common to many different signing strategies, to be used in a `KeyringController`, like is being used in [MetaMask](https://metamask.io/)
4
+
5
+ ## Installation
6
+
7
+ `yarn add @metamask/eth-hd-keyring`
8
+
9
+ or
10
+
11
+ `npm install @metamask/eth-hd-keyring`
12
+
13
+ ## The Keyring Class Protocol
14
+
15
+ One of the goals of this class is to allow developers to easily add new signing strategies to MetaMask. We call these signing strategies Keyrings, because they can manage multiple keys.
16
+
17
+ ### Keyring.type
18
+
19
+ A class property that returns a unique string describing the Keyring.
20
+ This is the only class property or method, the remaining methods are instance methods.
21
+
22
+ ### constructor( options )
23
+
24
+ As a Javascript class, your Keyring object will be used to instantiate new Keyring instances using the new keyword. For example:
25
+
26
+ ```
27
+ const keyring = new YourKeyringClass(options);
28
+ ```
29
+
30
+ The constructor currently receives an options object that will be defined by your keyring-building UI, once the user has gone through the steps required for you to fully instantiate a new keyring. For example, choosing a pattern for a vanity account, or entering a seed phrase.
31
+
32
+ We haven't defined the protocol for this account-generating UI yet, so for now please ensure your Keyring behaves nicely when not passed any options object.
33
+
34
+ ## Keyring Instance Methods
35
+
36
+ All below instance methods must return Promises to allow asynchronous resolution.
37
+
38
+ ### serialize()
39
+
40
+ In this method, you must return any JSON-serializable JavaScript object that you like. It will be encoded to a string, encrypted with the user's password, and stored to disk. This is the same object you will receive in the deserialize() method, so it should capture all the information you need to restore the Keyring's state.
41
+
42
+ ### deserialize( object )
43
+
44
+ As discussed above, the deserialize() method will be passed the JavaScript object that you returned when the serialize() method was called.
45
+
46
+ ### addAccounts( n = 1 )
47
+
48
+ The addAccounts(n) method is used to inform your keyring that the user wishes to create a new account. You should perform whatever internal steps are needed so that a call to serialize() will persist the new account, and then return an array of the new account addresses.
49
+
50
+ The method may be called with or without an argument, specifying the number of accounts to create. You should generally default to 1 per call.
51
+
52
+ ### getAccounts()
53
+
54
+ When this method is called, you must return an array of hex-string addresses for the accounts that your Keyring is able to sign for.
55
+
56
+ ### signTransaction(address, transaction)
57
+
58
+ This method will receive a hex-prefixed, all-lowercase address string for the account you should sign the incoming transaction with.
59
+
60
+ For your convenience, the transaction is an instance of ethereumjs-tx, (https://github.com/ethereumjs/ethereumjs-tx) so signing can be as simple as:
61
+
62
+ ```
63
+ transaction.sign(privateKey)
64
+ ```
65
+
66
+ You must return a valid signed ethereumjs-tx (https://github.com/ethereumjs/ethereumjs-tx) object when complete, it can be the same transaction you received.
67
+
68
+ ### signMessage(address, data)
69
+
70
+ The `eth_sign` method will receive the incoming data, alread hashed, and must sign that hash, and then return the raw signed hash.
71
+
72
+ ### exportAccount(address)
73
+
74
+ Exports the specified account as a private key hex string.
75
+
76
+ ## Contributing
77
+
78
+ ### Setup
79
+
80
+ - Install [Node.js](https://nodejs.org) version 18
81
+ - If you are using [nvm](https://github.com/creationix/nvm#installation) (recommended) running `nvm use` will automatically choose the right node version for you.
82
+ - Install [Yarn v3](https://yarnpkg.com/getting-started/install)
83
+ - Run `yarn install` to install dependencies and run any required post-install scripts
84
+
85
+ ### Testing and Linting
86
+
87
+ Run `yarn test` to run the tests once. To run tests on file changes, run `yarn test:watch`.
88
+
89
+ Run `yarn lint` to run the linter, or run `yarn lint:fix` to run the linter and fix any automatically fixable issues.
90
+
91
+ ### Release & Publishing
92
+
93
+ The project follows the same release process as the other libraries in the MetaMask organization. The GitHub Actions [`action-create-release-pr`](https://github.com/MetaMask/action-create-release-pr) and [`action-publish-release`](https://github.com/MetaMask/action-publish-release) are used to automate the release process; see those repositories for more information about how they work.
94
+
95
+ 1. Choose a release version.
96
+
97
+ - The release version should be chosen according to SemVer. Analyze the changes to see whether they include any breaking changes, new features, or deprecations, then choose the appropriate SemVer version. See [the SemVer specification](https://semver.org/) for more information.
98
+
99
+ 2. If this release is backporting changes onto a previous release, then ensure there is a major version branch for that version (e.g. `1.x` for a `v1` backport release).
100
+
101
+ - The major version branch should be set to the most recent release with that major version. For example, when backporting a `v1.0.2` release, you'd want to ensure there was a `1.x` branch that was set to the `v1.0.1` tag.
102
+
103
+ 3. Trigger the [`workflow_dispatch`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#workflow_dispatch) event [manually](https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow) for the `Create Release Pull Request` action to create the release PR.
104
+
105
+ - For a backport release, the base branch should be the major version branch that you ensured existed in step 2. For a normal release, the base branch should be the main branch for that repository (which should be the default value).
106
+ - This should trigger the [`action-create-release-pr`](https://github.com/MetaMask/action-create-release-pr) workflow to create the release PR.
107
+
108
+ 4. Update the changelog to move each change entry into the appropriate change category ([See here](https://keepachangelog.com/en/1.0.0/#types) for the full list of change categories, and the correct ordering), and edit them to be more easily understood by users of the package.
109
+
110
+ - Generally any changes that don't affect consumers of the package (e.g. lockfile changes or development environment changes) are omitted. Exceptions may be made for changes that might be of interest despite not having an effect upon the published package (e.g. major test improvements, security improvements, improved documentation, etc.).
111
+ - Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
112
+ - Consolidate related changes into one change entry if it makes it easier to explain.
113
+ - Run `yarn auto-changelog validate --rc` to check that the changelog is correctly formatted.
114
+
115
+ 5. Review and QA the release.
116
+
117
+ - If changes are made to the base branch, the release branch will need to be updated with these changes and review/QA will need to restart again. As such, it's probably best to avoid merging other PRs into the base branch while review is underway.
118
+
119
+ 6. Squash & Merge the release.
120
+
121
+ - This should trigger the [`action-publish-release`](https://github.com/MetaMask/action-publish-release) workflow to tag the final release commit and publish the release on GitHub.
122
+
123
+ 7. Publish the release on npm.
124
+
125
+ - Be very careful to use a clean local environment to publish the release, and follow exactly the same steps used during CI.
126
+ - Use `npm publish --dry-run` to examine the release contents to ensure the correct files are included. Compare to previous releases if necessary (e.g. using `https://unpkg.com/browse/[package name]@[package version]/`).
127
+ - Once you are confident the release contents are correct, publish the release using `npm publish`.
package/index.js ADDED
@@ -0,0 +1,312 @@
1
+ const { HDKey } = require('ethereum-cryptography/hdkey');
2
+ const { keccak256 } = require('ethereum-cryptography/keccak');
3
+ const { bytesToHex } = require('ethereum-cryptography/utils');
4
+ const {
5
+ privateToPublic,
6
+ publicToAddress,
7
+ ecsign,
8
+ arrToBufArr,
9
+ bufferToHex,
10
+ } = require('@ethereumjs/util');
11
+ const bip39 = require('@metamask/scure-bip39');
12
+ const { wordlist } = require('@metamask/scure-bip39/dist/wordlists/english');
13
+ const {
14
+ concatSig,
15
+ decrypt,
16
+ getEncryptionPublicKey,
17
+ normalize,
18
+ personalSign,
19
+ signTypedData,
20
+ SignTypedDataVersion,
21
+ } = require('@metamask/eth-sig-util');
22
+ const { assertIsHexString, remove0x } = require('@metamask/utils');
23
+
24
+ // Options:
25
+ const hdPathString = `m/44'/60'/0'/0`;
26
+ const type = 'HD Key Tree';
27
+
28
+ class HdKeyring {
29
+ /* PUBLIC METHODS */
30
+ constructor(opts = {}) {
31
+ this.type = type;
32
+ this._wallets = [];
33
+ this.deserialize(opts);
34
+ }
35
+
36
+ generateRandomMnemonic() {
37
+ this._initFromMnemonic(bip39.generateMnemonic(wordlist));
38
+ }
39
+
40
+ _uint8ArrayToString(mnemonic) {
41
+ const recoveredIndices = Array.from(
42
+ new Uint16Array(new Uint8Array(mnemonic).buffer),
43
+ );
44
+ return recoveredIndices.map((i) => wordlist[i]).join(' ');
45
+ }
46
+
47
+ _stringToUint8Array(mnemonic) {
48
+ const indices = mnemonic.split(' ').map((word) => wordlist.indexOf(word));
49
+ return new Uint8Array(new Uint16Array(indices).buffer);
50
+ }
51
+
52
+ _mnemonicToUint8Array(mnemonic) {
53
+ let mnemonicData = mnemonic;
54
+ // when encrypted/decrypted, buffers get cast into js object with a property type set to buffer
55
+ if (mnemonic && mnemonic.type && mnemonic.type === 'Buffer') {
56
+ mnemonicData = mnemonic.data;
57
+ }
58
+
59
+ if (
60
+ // this block is for backwards compatibility with vaults that were previously stored as buffers, number arrays or plain text strings
61
+ typeof mnemonicData === 'string' ||
62
+ Buffer.isBuffer(mnemonicData) ||
63
+ Array.isArray(mnemonicData)
64
+ ) {
65
+ let mnemonicAsString = mnemonicData;
66
+ if (Array.isArray(mnemonicData)) {
67
+ mnemonicAsString = Buffer.from(mnemonicData).toString();
68
+ } else if (Buffer.isBuffer(mnemonicData)) {
69
+ mnemonicAsString = mnemonicData.toString();
70
+ }
71
+ return this._stringToUint8Array(mnemonicAsString);
72
+ } else if (
73
+ mnemonicData instanceof Object &&
74
+ !(mnemonicData instanceof Uint8Array)
75
+ ) {
76
+ // when encrypted/decrypted the Uint8Array becomes a js object we need to cast back to a Uint8Array
77
+ return Uint8Array.from(Object.values(mnemonicData));
78
+ }
79
+ return mnemonicData;
80
+ }
81
+
82
+ serialize() {
83
+ const mnemonicAsString = this._uint8ArrayToString(this.mnemonic);
84
+ const uint8ArrayMnemonic = new TextEncoder('utf-8').encode(
85
+ mnemonicAsString,
86
+ );
87
+
88
+ return Promise.resolve({
89
+ mnemonic: Array.from(uint8ArrayMnemonic),
90
+ numberOfAccounts: this._wallets.length,
91
+ hdPath: this.hdPath,
92
+ });
93
+ }
94
+
95
+ deserialize(opts = {}) {
96
+ if (opts.numberOfAccounts && !opts.mnemonic) {
97
+ throw new Error(
98
+ 'Eth-Hd-Keyring: Deserialize method cannot be called with an opts value for numberOfAccounts and no menmonic',
99
+ );
100
+ }
101
+
102
+ if (this.root) {
103
+ throw new Error(
104
+ 'Eth-Hd-Keyring: Secret recovery phrase already provided',
105
+ );
106
+ }
107
+ this.opts = opts;
108
+ this._wallets = [];
109
+ this.mnemonic = null;
110
+ this.root = null;
111
+ this.hdPath = opts.hdPath || hdPathString;
112
+
113
+ if (opts.mnemonic) {
114
+ this._initFromMnemonic(opts.mnemonic);
115
+ }
116
+
117
+ if (opts.numberOfAccounts) {
118
+ return this.addAccounts(opts.numberOfAccounts);
119
+ }
120
+
121
+ return Promise.resolve([]);
122
+ }
123
+
124
+ addAccounts(numberOfAccounts = 1) {
125
+ if (!this.root) {
126
+ throw new Error('Eth-Hd-Keyring: No secret recovery phrase provided');
127
+ }
128
+
129
+ const oldLen = this._wallets.length;
130
+ const newWallets = [];
131
+ for (let i = oldLen; i < numberOfAccounts + oldLen; i++) {
132
+ const wallet = this.root.deriveChild(i);
133
+ newWallets.push(wallet);
134
+ this._wallets.push(wallet);
135
+ }
136
+ const hexWallets = newWallets.map((w) => {
137
+ return this._addressfromPublicKey(w.publicKey);
138
+ });
139
+ return Promise.resolve(hexWallets);
140
+ }
141
+
142
+ getAccounts() {
143
+ return this._wallets.map((w) => this._addressfromPublicKey(w.publicKey));
144
+ }
145
+
146
+ /* BASE KEYRING METHODS */
147
+
148
+ // returns an address specific to an app
149
+ async getAppKeyAddress(address, origin) {
150
+ if (!origin || typeof origin !== 'string') {
151
+ throw new Error(`'origin' must be a non-empty string`);
152
+ }
153
+ const wallet = this._getWalletForAccount(address, {
154
+ withAppKeyOrigin: origin,
155
+ });
156
+ const appKeyAddress = normalize(
157
+ publicToAddress(wallet.publicKey).toString('hex'),
158
+ );
159
+
160
+ return appKeyAddress;
161
+ }
162
+
163
+ // exportAccount should return a hex-encoded private key:
164
+ async exportAccount(address, opts = {}) {
165
+ const wallet = this._getWalletForAccount(address, opts);
166
+ return bytesToHex(wallet.privateKey);
167
+ }
168
+
169
+ // tx is an instance of the ethereumjs-transaction class.
170
+ async signTransaction(address, tx, opts = {}) {
171
+ const privKey = this._getPrivateKeyFor(address, opts);
172
+ const signedTx = tx.sign(privKey);
173
+ // Newer versions of Ethereumjs-tx are immutable and return a new tx object
174
+ return signedTx === undefined ? tx : signedTx;
175
+ }
176
+
177
+ // For eth_sign, we need to sign arbitrary data:
178
+ async signMessage(address, data, opts = {}) {
179
+ assertIsHexString(data);
180
+ const message = remove0x(data);
181
+ const privKey = this._getPrivateKeyFor(address, opts);
182
+ const msgSig = ecsign(Buffer.from(message, 'hex'), privKey);
183
+ const rawMsgSig = concatSig(msgSig.v, msgSig.r, msgSig.s);
184
+ return rawMsgSig;
185
+ }
186
+
187
+ // For personal_sign, we need to prefix the message:
188
+ async signPersonalMessage(address, msgHex, opts = {}) {
189
+ const privKey = this._getPrivateKeyFor(address, opts);
190
+ const privateKey = Buffer.from(privKey, 'hex');
191
+ const sig = personalSign({ privateKey, data: msgHex });
192
+ return sig;
193
+ }
194
+
195
+ // For eth_decryptMessage:
196
+ async decryptMessage(withAccount, encryptedData) {
197
+ const wallet = this._getWalletForAccount(withAccount);
198
+ const { privateKey: privateKeyAsUint8Array } = wallet;
199
+ const privateKeyAsHex = Buffer.from(privateKeyAsUint8Array).toString('hex');
200
+ const sig = decrypt({ privateKey: privateKeyAsHex, encryptedData });
201
+ return sig;
202
+ }
203
+
204
+ // personal_signTypedData, signs data along with the schema
205
+ async signTypedData(
206
+ withAccount,
207
+ typedData,
208
+ opts = { version: SignTypedDataVersion.V1 },
209
+ ) {
210
+ // Treat invalid versions as "V1"
211
+ const version = Object.keys(SignTypedDataVersion).includes(opts.version)
212
+ ? opts.version
213
+ : SignTypedDataVersion.V1;
214
+
215
+ const privateKey = this._getPrivateKeyFor(withAccount, opts);
216
+ return signTypedData({ privateKey, data: typedData, version });
217
+ }
218
+
219
+ removeAccount(account) {
220
+ const address = normalize(account);
221
+ if (
222
+ !this._wallets
223
+ .map(({ publicKey }) => this._addressfromPublicKey(publicKey))
224
+ .includes(address)
225
+ ) {
226
+ throw new Error(`Address ${address} not found in this keyring`);
227
+ }
228
+
229
+ this._wallets = this._wallets.filter(
230
+ ({ publicKey }) => this._addressfromPublicKey(publicKey) !== address,
231
+ );
232
+ }
233
+
234
+ // get public key for nacl
235
+ async getEncryptionPublicKey(withAccount, opts = {}) {
236
+ const privKey = this._getPrivateKeyFor(withAccount, opts);
237
+ const publicKey = getEncryptionPublicKey(privKey);
238
+ return publicKey;
239
+ }
240
+
241
+ _getPrivateKeyFor(address, opts = {}) {
242
+ if (!address) {
243
+ throw new Error('Must specify address.');
244
+ }
245
+ const wallet = this._getWalletForAccount(address, opts);
246
+ return wallet.privateKey;
247
+ }
248
+
249
+ _getWalletForAccount(account, opts = {}) {
250
+ const address = normalize(account);
251
+ let wallet = this._wallets.find(({ publicKey }) => {
252
+ return this._addressfromPublicKey(publicKey) === address;
253
+ });
254
+ if (!wallet) {
255
+ throw new Error('HD Keyring - Unable to find matching address.');
256
+ }
257
+
258
+ if (opts.withAppKeyOrigin) {
259
+ const { privateKey } = wallet;
260
+ const appKeyOriginBuffer = Buffer.from(opts.withAppKeyOrigin, 'utf8');
261
+ const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
262
+ const appKeyPrivateKey = arrToBufArr(keccak256(appKeyBuffer, 256));
263
+ const appKeyPublicKey = privateToPublic(appKeyPrivateKey);
264
+ wallet = { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
265
+ }
266
+
267
+ return wallet;
268
+ }
269
+
270
+ /* PRIVATE / UTILITY METHODS */
271
+
272
+ /**
273
+ * Sets appropriate properties for the keyring based on the given
274
+ * BIP39-compliant mnemonic.
275
+ *
276
+ * @param {string|Array<number>|Buffer} mnemonic - A seed phrase represented
277
+ * as a string, an array of UTF-8 bytes, or a Buffer. Mnemonic input
278
+ * passed as type buffer or array of UTF-8 bytes must be NFKD normalized.
279
+ */
280
+ _initFromMnemonic(mnemonic) {
281
+ if (this.root) {
282
+ throw new Error(
283
+ 'Eth-Hd-Keyring: Secret recovery phrase already provided',
284
+ );
285
+ }
286
+
287
+ this.mnemonic = this._mnemonicToUint8Array(mnemonic);
288
+
289
+ // validate before initializing
290
+ const isValid = bip39.validateMnemonic(this.mnemonic, wordlist);
291
+ if (!isValid) {
292
+ throw new Error(
293
+ 'Eth-Hd-Keyring: Invalid secret recovery phrase provided',
294
+ );
295
+ }
296
+
297
+ // eslint-disable-next-line n/no-sync
298
+ const seed = bip39.mnemonicToSeedSync(this.mnemonic, wordlist);
299
+ this.hdWallet = HDKey.fromMasterSeed(seed);
300
+ this.root = this.hdWallet.derive(this.hdPath);
301
+ }
302
+
303
+ // small helper function to convert publicKey in Uint8Array form to a publicAddress as a hex
304
+ _addressfromPublicKey(publicKey) {
305
+ return bufferToHex(
306
+ publicToAddress(Buffer.from(publicKey), true),
307
+ ).toLowerCase();
308
+ }
309
+ }
310
+
311
+ HdKeyring.type = type;
312
+ module.exports = HdKeyring;
package/jest.config.js ADDED
@@ -0,0 +1,32 @@
1
+ /*
2
+ * For a detailed explanation regarding each configuration property and type check, visit:
3
+ * https://jestjs.io/docs/configuration
4
+ */
5
+
6
+ const merge = require('deepmerge');
7
+ const path = require('path');
8
+
9
+ const baseConfig = require('../../jest.config.packages');
10
+
11
+ const displayName = path.basename(__dirname);
12
+
13
+ module.exports = merge(baseConfig, {
14
+ // The display name when running multiple projects
15
+ displayName,
16
+
17
+ // An array of regexp pattern strings used to skip coverage collection
18
+ coveragePathIgnorePatterns: ['./test'],
19
+
20
+ // The glob patterns Jest uses to detect test files
21
+ testMatch: ['**/test/**/*.[jt]s?(x)'],
22
+
23
+ // An object that configures minimum threshold enforcement for coverage results
24
+ coverageThreshold: {
25
+ global: {
26
+ branches: 84,
27
+ functions: 100,
28
+ lines: 95,
29
+ statements: 95,
30
+ },
31
+ },
32
+ });
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@metamask-previews/eth-hd-keyring",
3
+ "version": "7.0.1-38c4bd5",
4
+ "description": "A simple standard interface for a seed phrase generated set of Ethereum accounts.",
5
+ "keywords": [
6
+ "ethereum",
7
+ "keyring"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/eth-hd-keyring#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/eth-hd-keyring/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/MetaMask/eth-hd-keyring.git"
16
+ },
17
+ "license": "ISC",
18
+ "author": "Dan Finlay",
19
+ "main": "index.js",
20
+ "scripts": {
21
+ "build": "",
22
+ "build:clean": "",
23
+ "build:force": "",
24
+ "changelog:update": "../../scripts/update-changelog.sh @metamask/eth-hd-keyring",
25
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/eth-hd-keyring",
26
+ "publish:preview": "yarn npm publish --tag preview",
27
+ "test": "jest",
28
+ "test:clean": "jest --clearCache",
29
+ "test:verbose": "jest --verbose"
30
+ },
31
+ "dependencies": {
32
+ "@ethereumjs/util": "^8.1.0",
33
+ "@metamask/eth-sig-util": "^7.0.0",
34
+ "@metamask/scure-bip39": "^2.1.0",
35
+ "@metamask/utils": "^8.1.0",
36
+ "deepmerge": "^4.2.2",
37
+ "ethereum-cryptography": "^2.1.2"
38
+ },
39
+ "devDependencies": {
40
+ "@ethereumjs/tx": "^4.0.1",
41
+ "@lavamoat/allow-scripts": "^3.0.4",
42
+ "@lavamoat/preinstall-always-fail": "^1.0.0",
43
+ "@metamask/auto-changelog": "^3.4.4",
44
+ "@metamask/bip39": "^4.0.0",
45
+ "@metamask/eth-hd-keyring": "4.0.1",
46
+ "@types/jest": "^29.4.0",
47
+ "jest": "^29.4.3"
48
+ },
49
+ "engines": {
50
+ "node": "^18.18 || >=20"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public",
54
+ "registry": "https://registry.npmjs.org/"
55
+ },
56
+ "lavamoat": {
57
+ "allowScripts": {
58
+ "@lavamoat/preinstall-always-fail": false,
59
+ "@metamask/eth-hd-keyring>ethereumjs-util>ethereum-cryptography>keccak": false,
60
+ "@metamask/eth-hd-keyring>ethereumjs-util>ethereum-cryptography>secp256k1": false
61
+ }
62
+ }
63
+ }