@rabby-wallet/eth-simple-keyring 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ [Unreleased]: https://github.com/MetaMask/eth-simple-keyring/
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,132 @@
1
+ # Simple 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`; such as the one used in [MetaMask](https://metamask.io/)
4
+
5
+ ## The Keyring Class Protocol
6
+
7
+ 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.
8
+
9
+ ### Keyring.type
10
+
11
+ A class property that returns a unique string describing the Keyring.
12
+ This is the only class property or method, the remaining methods are instance methods.
13
+
14
+ ### constructor( options )
15
+
16
+ As a Javascript class, your Keyring object will be used to instantiate new Keyring instances using the new keyword. For example:
17
+
18
+ ```
19
+ const keyring = new YourKeyringClass(options);
20
+ ```
21
+
22
+ 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.
23
+
24
+ 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.
25
+
26
+ ## Keyring Instance Methods
27
+
28
+ All below instance methods must return Promises to allow asynchronous resolution.
29
+
30
+ ### serialize()
31
+
32
+ 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.
33
+
34
+ ### deserialize( object )
35
+
36
+ As discussed above, the deserialize() method will be passed the JavaScript object that you returned when the serialize() method was called.
37
+
38
+ ### addAccounts( n = 1 )
39
+
40
+ 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.
41
+
42
+ 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.
43
+
44
+ ### getAccounts()
45
+
46
+ 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.
47
+
48
+ ### signTransaction(address, transaction)
49
+
50
+ This method will receive a hex-prefixed, all-lowercase address string for the account you should sign the incoming transaction with.
51
+
52
+ For your convenience, the transaction is an instance of ethereumjs-tx, (https://github.com/ethereumjs/ethereumjs-tx) so signing can be as simple as:
53
+
54
+ ```
55
+ transaction.sign(privateKey)
56
+ ```
57
+
58
+ 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.
59
+
60
+ ### signMessage(address, data)
61
+
62
+ The `eth_sign` method will receive the incoming data, already hashed, and must sign that hash, and then return the raw signed hash.
63
+
64
+ ### getEncryptionPublicKey(address)
65
+
66
+ This provides the public key for encryption function.
67
+
68
+ ### decryptMessage(address, data)
69
+
70
+ The `eth_decryptMessage` method will receive the incoming data in array format that returns `encrypt` function in `eth-sig-util` and must decrypt message, and then return the raw message.
71
+
72
+ ### exportAccount(address)
73
+
74
+ Exports the specified account as a private key hex string.
75
+
76
+ ### removeAccount(address)
77
+
78
+ removes the specified account from the list of accounts.
79
+
80
+ ## Contributing
81
+
82
+ ### Setup
83
+
84
+ - Install [Node.js](https://nodejs.org) version 12
85
+ - If you are using [nvm](https://github.com/creationix/nvm#installation) (recommended) running `nvm use` will automatically choose the right node version for you.
86
+ - Install [Yarn v1](https://yarnpkg.com/en/docs/install)
87
+ - Run `yarn setup` to install dependencies and run any requried post-install scripts
88
+ - **Warning:** Do not use the `yarn` / `yarn install` command directly. Use `yarn setup` instead. The normal install command will skip required post-install scripts, leaving your development environment in an invalid state.
89
+
90
+ ### Testing and Linting
91
+
92
+ Run `yarn test` to run the tests once. To run tests on file changes, run `yarn test:watch`.
93
+
94
+ Run `yarn lint` to run the linter, or run `yarn lint:fix` to run the linter and fix any automatically fixable issues.
95
+
96
+ ### Release & Publishing
97
+
98
+ 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.
99
+
100
+ 1. Choose a release version.
101
+
102
+ - 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.
103
+
104
+ 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).
105
+
106
+ - 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.
107
+
108
+ 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.
109
+
110
+ - 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).
111
+ - This should trigger the [`action-create-release-pr`](https://github.com/MetaMask/action-create-release-pr) workflow to create the release PR.
112
+
113
+ 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.
114
+
115
+ - 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.).
116
+ - Try to explain each change in terms that users of the package would understand (e.g. avoid referencing internal variables/concepts).
117
+ - Consolidate related changes into one change entry if it makes it easier to explain.
118
+ - Run `yarn auto-changelog validate --rc` to check that the changelog is correctly formatted.
119
+
120
+ 5. Review and QA the release.
121
+
122
+ - 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.
123
+
124
+ 6. Squash & Merge the release.
125
+
126
+ - 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.
127
+
128
+ 7. Publish the release on npm.
129
+
130
+ - Be very careful to use a clean local environment to publish the release, and follow exactly the same steps used during CI.
131
+ - 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]/`).
132
+ - Once you are confident the release contents are correct, publish the release using `npm publish`.
package/index.js ADDED
@@ -0,0 +1,199 @@
1
+ const { EventEmitter } = require('events');
2
+ const ethUtil = require('ethereumjs-util');
3
+ const randomBytes = require('randombytes');
4
+
5
+ const type = 'Simple Key Pair';
6
+ const {
7
+ concatSig,
8
+ decrypt,
9
+ getEncryptionPublicKey,
10
+ normalize,
11
+ personalSign,
12
+ signTypedData,
13
+ SignTypedDataVersion,
14
+ } = require('@metamask/eth-sig-util');
15
+
16
+ function generateKey() {
17
+ const privateKey = randomBytes(32);
18
+ // I don't think this is possible, but this validation was here previously,
19
+ // so it has been preserved just in case.
20
+ // istanbul ignore next
21
+ if (!ethUtil.isValidPrivate(privateKey)) {
22
+ throw new Error(
23
+ 'Private key does not satisfy the curve requirements (ie. it is invalid)',
24
+ );
25
+ }
26
+ return privateKey;
27
+ }
28
+
29
+ class SimpleKeyring extends EventEmitter {
30
+ constructor(opts) {
31
+ super();
32
+ this.type = type;
33
+ this._wallets = [];
34
+ this.deserialize(opts);
35
+ }
36
+
37
+ async serialize() {
38
+ return this._wallets.map(({ privateKey }) => privateKey.toString('hex'));
39
+ }
40
+
41
+ async deserialize(privateKeys = []) {
42
+ this._wallets = privateKeys.map((hexPrivateKey) => {
43
+ const strippedHexPrivateKey = ethUtil.stripHexPrefix(hexPrivateKey);
44
+ const privateKey = Buffer.from(strippedHexPrivateKey, 'hex');
45
+ const publicKey = ethUtil.privateToPublic(privateKey);
46
+ return { privateKey, publicKey };
47
+ });
48
+ }
49
+
50
+ async addAccounts(n = 1) {
51
+ const newWallets = [];
52
+ for (let i = 0; i < n; i++) {
53
+ const privateKey = generateKey();
54
+ const publicKey = ethUtil.privateToPublic(privateKey);
55
+ newWallets.push({ privateKey, publicKey });
56
+ }
57
+ this._wallets = this._wallets.concat(newWallets);
58
+ const hexWallets = newWallets.map(({ publicKey }) =>
59
+ ethUtil.bufferToHex(ethUtil.publicToAddress(publicKey)),
60
+ );
61
+ return hexWallets;
62
+ }
63
+
64
+ async getAccounts() {
65
+ return this._wallets.map(({ publicKey }) =>
66
+ ethUtil.bufferToHex(ethUtil.publicToAddress(publicKey)),
67
+ );
68
+ }
69
+
70
+ // tx is an instance of the ethereumjs-transaction class.
71
+ async signTransaction(address, tx, opts = {}) {
72
+ const privKey = this._getPrivateKeyFor(address, opts);
73
+ const signedTx = tx.sign(privKey);
74
+ // Newer versions of Ethereumjs-tx are immutable and return a new tx object
75
+ return signedTx === undefined ? tx : signedTx;
76
+ }
77
+
78
+ // For eth_sign, we need to sign arbitrary data:
79
+ async signMessage(address, data, opts = {}) {
80
+ const message = ethUtil.stripHexPrefix(data);
81
+ const privKey = this._getPrivateKeyFor(address, opts);
82
+ const msgSig = ethUtil.ecsign(Buffer.from(message, 'hex'), privKey);
83
+ const rawMsgSig = concatSig(msgSig.v, msgSig.r, msgSig.s);
84
+ return rawMsgSig;
85
+ }
86
+
87
+ // For personal_sign, we need to prefix the message:
88
+ async signPersonalMessage(address, msgHex, opts = {}) {
89
+ const privKey = this._getPrivateKeyFor(address, opts);
90
+ const privateKey = Buffer.from(privKey, 'hex');
91
+ const sig = personalSign({ privateKey, data: msgHex });
92
+ return sig;
93
+ }
94
+
95
+ // For eth_decryptMessage:
96
+ async decryptMessage(withAccount, encryptedData) {
97
+ const wallet = this._getWalletForAccount(withAccount);
98
+ const privateKey = ethUtil.stripHexPrefix(wallet.privateKey);
99
+ const sig = decrypt({ privateKey, encryptedData });
100
+ return sig;
101
+ }
102
+
103
+ // personal_signTypedData, signs data along with the schema
104
+ async signTypedData(
105
+ withAccount,
106
+ typedData,
107
+ opts = { version: SignTypedDataVersion.V1 },
108
+ ) {
109
+ // Treat invalid versions as "V1"
110
+ const version = Object.keys(SignTypedDataVersion).includes(opts.version)
111
+ ? opts.version
112
+ : SignTypedDataVersion.V1;
113
+
114
+ const privateKey = this._getPrivateKeyFor(withAccount, opts);
115
+ return signTypedData({ privateKey, data: typedData, version });
116
+ }
117
+
118
+ // get public key for nacl
119
+ async getEncryptionPublicKey(withAccount, opts = {}) {
120
+ const privKey = this._getPrivateKeyFor(withAccount, opts);
121
+ const publicKey = getEncryptionPublicKey(privKey);
122
+ return publicKey;
123
+ }
124
+
125
+ _getPrivateKeyFor(address, opts = {}) {
126
+ if (!address) {
127
+ throw new Error('Must specify address.');
128
+ }
129
+ const wallet = this._getWalletForAccount(address, opts);
130
+ return wallet.privateKey;
131
+ }
132
+
133
+ // returns an address specific to an app
134
+ async getAppKeyAddress(address, origin) {
135
+ if (!origin || typeof origin !== 'string') {
136
+ throw new Error(`'origin' must be a non-empty string`);
137
+ }
138
+ const wallet = this._getWalletForAccount(address, {
139
+ withAppKeyOrigin: origin,
140
+ });
141
+ const appKeyAddress = normalize(
142
+ ethUtil.publicToAddress(wallet.publicKey).toString('hex'),
143
+ );
144
+ return appKeyAddress;
145
+ }
146
+
147
+ // exportAccount should return a hex-encoded private key:
148
+ async exportAccount(address, opts = {}) {
149
+ const wallet = this._getWalletForAccount(address, opts);
150
+ return wallet.privateKey.toString('hex');
151
+ }
152
+
153
+ removeAccount(address) {
154
+ if (
155
+ !this._wallets
156
+ .map(({ publicKey }) =>
157
+ ethUtil.bufferToHex(ethUtil.publicToAddress(publicKey)).toLowerCase(),
158
+ )
159
+ .includes(address.toLowerCase())
160
+ ) {
161
+ throw new Error(`Address ${address} not found in this keyring`);
162
+ }
163
+
164
+ this._wallets = this._wallets.filter(
165
+ ({ publicKey }) =>
166
+ ethUtil
167
+ .bufferToHex(ethUtil.publicToAddress(publicKey))
168
+ .toLowerCase() !== address.toLowerCase(),
169
+ );
170
+ }
171
+
172
+ /**
173
+ * @private
174
+ */
175
+ _getWalletForAccount(account, opts = {}) {
176
+ const address = normalize(account);
177
+ let wallet = this._wallets.find(
178
+ ({ publicKey }) =>
179
+ ethUtil.bufferToHex(ethUtil.publicToAddress(publicKey)) === address,
180
+ );
181
+ if (!wallet) {
182
+ throw new Error('Simple Keyring - Unable to find matching address.');
183
+ }
184
+
185
+ if (opts.withAppKeyOrigin) {
186
+ const { privateKey } = wallet;
187
+ const appKeyOriginBuffer = Buffer.from(opts.withAppKeyOrigin, 'utf8');
188
+ const appKeyBuffer = Buffer.concat([privateKey, appKeyOriginBuffer]);
189
+ const appKeyPrivateKey = ethUtil.keccak(appKeyBuffer, 256);
190
+ const appKeyPublicKey = ethUtil.privateToPublic(appKeyPrivateKey);
191
+ wallet = { privateKey: appKeyPrivateKey, publicKey: appKeyPublicKey };
192
+ }
193
+
194
+ return wallet;
195
+ }
196
+ }
197
+
198
+ SimpleKeyring.type = type;
199
+ module.exports = SimpleKeyring;
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@rabby-wallet/eth-simple-keyring",
3
+ "version": "4.2.0",
4
+ "description": "A simple standard interface for a series of Ethereum private keys.",
5
+ "keywords": [
6
+ "ethereum",
7
+ "keyring"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/eth-simple-keyring#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/eth-simple-keyring/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/MetaMask/eth-simple-keyring.git"
16
+ },
17
+ "license": "ISC",
18
+ "author": "Dan Finlay",
19
+ "main": "index.js",
20
+ "files": [
21
+ "index.js"
22
+ ],
23
+ "scripts": {
24
+ "setup": "yarn install && yarn allow-scripts",
25
+ "test": "jest",
26
+ "test:watch": "jest --watch",
27
+ "lint:eslint": "eslint . --cache --ext js,ts",
28
+ "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore",
29
+ "lint": "yarn lint:eslint && yarn lint:misc --check",
30
+ "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write"
31
+ },
32
+ "dependencies": {
33
+ "@metamask/eth-sig-util": "^4.0.0",
34
+ "ethereumjs-util": "^7.0.9",
35
+ "randombytes": "^2.1.0"
36
+ },
37
+ "devDependencies": {
38
+ "@ethereumjs/tx": "^3.1.1",
39
+ "@lavamoat/allow-scripts": "^1.0.6",
40
+ "@metamask/auto-changelog": "^2.5.0",
41
+ "@metamask/eslint-config": "^8.0.0",
42
+ "@metamask/eslint-config-jest": "^8.0.0",
43
+ "@metamask/eslint-config-nodejs": "^8.0.0",
44
+ "@types/jest": "^26.0.24",
45
+ "eslint": "^7.30.0",
46
+ "eslint-config-prettier": "^8.3.0",
47
+ "eslint-plugin-import": "^2.23.4",
48
+ "eslint-plugin-jest": "^24.3.6",
49
+ "eslint-plugin-node": "^11.1.0",
50
+ "eslint-plugin-prettier": "^3.4.0",
51
+ "jest": "^27.0.6",
52
+ "prettier": "^2.3.2",
53
+ "prettier-plugin-packagejson": "^2.2.11"
54
+ },
55
+ "engines": {
56
+ "node": ">=12.0.0"
57
+ },
58
+ "lavamoat": {
59
+ "allowScripts": {
60
+ "keccak": true,
61
+ "secp256k1": true,
62
+ "@lavamoat/preinstall-always-fail": false
63
+ }
64
+ }
65
+ }