aboutsummaryrefslogtreecommitdiffstats
path: root/packages/subproviders/src
diff options
context:
space:
mode:
Diffstat (limited to 'packages/subproviders/src')
-rw-r--r--packages/subproviders/src/globals.d.ts11
-rw-r--r--packages/subproviders/src/index.ts4
-rw-r--r--packages/subproviders/src/subproviders/base_wallet_subprovider.ts5
-rw-r--r--packages/subproviders/src/subproviders/ledger.ts144
-rw-r--r--packages/subproviders/src/subproviders/mnemonic_wallet.ts145
-rw-r--r--packages/subproviders/src/subproviders/private_key_wallet.ts (renamed from packages/subproviders/src/subproviders/private_key_wallet_subprovider.ts)39
-rw-r--r--packages/subproviders/src/types.ts33
-rw-r--r--packages/subproviders/src/utils/wallet_utils.ts79
8 files changed, 361 insertions, 99 deletions
diff --git a/packages/subproviders/src/globals.d.ts b/packages/subproviders/src/globals.d.ts
index c5ad26876..4b3ecdf3c 100644
--- a/packages/subproviders/src/globals.d.ts
+++ b/packages/subproviders/src/globals.d.ts
@@ -51,17 +51,6 @@ declare module '@ledgerhq/hw-transport-node-hid' {
}
}
-// hdkey declarations
-declare module 'hdkey' {
- class HDNode {
- public publicKey: Buffer;
- public chainCode: Buffer;
- public constructor();
- public derive(path: string): HDNode;
- }
- export = HDNode;
-}
-
declare module '*.json' {
const json: any;
/* tslint:disable */
diff --git a/packages/subproviders/src/index.ts b/packages/subproviders/src/index.ts
index b84473e45..ff28b8a8d 100644
--- a/packages/subproviders/src/index.ts
+++ b/packages/subproviders/src/index.ts
@@ -12,12 +12,12 @@ export { LedgerSubprovider } from './subproviders/ledger';
export { GanacheSubprovider } from './subproviders/ganache';
export { Subprovider } from './subproviders/subprovider';
export { NonceTrackerSubprovider } from './subproviders/nonce_tracker';
-export { PrivateKeyWalletSubprovider } from './subproviders/private_key_wallet_subprovider';
+export { PrivateKeyWalletSubprovider } from './subproviders/private_key_wallet';
+export { MnemonicWalletSubprovider } from './subproviders/mnemonic_wallet';
export {
Callback,
ErrorCallback,
NextCallback,
- LedgerWalletSubprovider,
LedgerCommunicationClient,
NonceSubproviderErrors,
LedgerSubproviderConfigs,
diff --git a/packages/subproviders/src/subproviders/base_wallet_subprovider.ts b/packages/subproviders/src/subproviders/base_wallet_subprovider.ts
index 034f83e7f..0a9b99ae4 100644
--- a/packages/subproviders/src/subproviders/base_wallet_subprovider.ts
+++ b/packages/subproviders/src/subproviders/base_wallet_subprovider.ts
@@ -21,7 +21,7 @@ export abstract class BaseWalletSubprovider extends Subprovider {
public abstract async getAccountsAsync(): Promise<string[]>;
public abstract async signTransactionAsync(txParams: PartialTxParams): Promise<string>;
- public abstract async signPersonalMessageAsync(data: string): Promise<string>;
+ public abstract async signPersonalMessageAsync(data: string, address: string): Promise<string>;
/**
* This method conforms to the web3-provider-engine interface.
@@ -85,8 +85,9 @@ export abstract class BaseWalletSubprovider extends Subprovider {
case 'eth_sign':
case 'personal_sign':
const data = payload.method === 'eth_sign' ? payload.params[1] : payload.params[0];
+ const address = payload.method === 'eth_sign' ? payload.params[0] : payload.params[1];
try {
- const ecSignatureHex = await this.signPersonalMessageAsync(data);
+ const ecSignatureHex = await this.signPersonalMessageAsync(data, address);
end(null, ecSignatureHex);
} catch (err) {
end(err);
diff --git a/packages/subproviders/src/subproviders/ledger.ts b/packages/subproviders/src/subproviders/ledger.ts
index aa86bf6c0..563e5a56a 100644
--- a/packages/subproviders/src/subproviders/ledger.ts
+++ b/packages/subproviders/src/subproviders/ledger.ts
@@ -1,5 +1,4 @@
import { assert } from '@0xproject/assert';
-import { JSONRPCRequestPayload } from '@0xproject/types';
import { addressUtils } from '@0xproject/utils';
import EthereumTx = require('ethereumjs-tx');
import ethUtil = require('ethereumjs-util');
@@ -9,6 +8,7 @@ import { Lock } from 'semaphore-async-await';
import {
Callback,
+ DerivedHDKeyInfo,
LedgerEthereumClient,
LedgerEthereumClientFactoryAsync,
LedgerSubproviderConfigs,
@@ -17,13 +17,15 @@ import {
ResponseWithTxParams,
WalletSubproviderErrors,
} from '../types';
+import { walletUtils } from '../utils/wallet_utils';
import { BaseWalletSubprovider } from './base_wallet_subprovider';
-const DEFAULT_DERIVATION_PATH = `44'/60'/0'`;
-const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10;
+const DEFAULT_BASE_DERIVATION_PATH = `44'/60'/0'`;
const ASK_FOR_ON_DEVICE_CONFIRMATION = false;
const SHOULD_GET_CHAIN_CODE = true;
+const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10;
+const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
/**
* Subprovider for interfacing with a user's [Ledger Nano S](https://www.ledgerwallet.com/products/ledger-nano-s).
@@ -34,11 +36,11 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
private _nonceLock = new Lock();
private _connectionLock = new Lock();
private _networkId: number;
- private _derivationPath: string;
- private _derivationPathIndex: number;
+ private _baseDerivationPath: string;
private _ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync;
private _ledgerClientIfExists?: LedgerEthereumClient;
private _shouldAlwaysAskForConfirmation: boolean;
+ private _addressSearchLimit: number;
/**
* Instantiates a LedgerSubprovider. Defaults to derivationPath set to `44'/60'/0'`.
* TestRPC/Ganache defaults to `m/44'/60'/0'/0`, so set this in the configs if desired.
@@ -49,40 +51,35 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
super();
this._networkId = config.networkId;
this._ledgerEthereumClientFactoryAsync = config.ledgerEthereumClientFactoryAsync;
- this._derivationPath = config.derivationPath || DEFAULT_DERIVATION_PATH;
+ this._baseDerivationPath = config.baseDerivationPath || DEFAULT_BASE_DERIVATION_PATH;
this._shouldAlwaysAskForConfirmation =
!_.isUndefined(config.accountFetchingConfigs) &&
!_.isUndefined(config.accountFetchingConfigs.shouldAskForOnDeviceConfirmation)
? config.accountFetchingConfigs.shouldAskForOnDeviceConfirmation
: ASK_FOR_ON_DEVICE_CONFIRMATION;
- this._derivationPathIndex = 0;
+ this._addressSearchLimit =
+ !_.isUndefined(config.accountFetchingConfigs) &&
+ !_.isUndefined(config.accountFetchingConfigs.addressSearchLimit)
+ ? config.accountFetchingConfigs.addressSearchLimit
+ : DEFAULT_ADDRESS_SEARCH_LIMIT;
}
/**
* Retrieve the set derivation path
* @returns derivation path
*/
public getPath(): string {
- return this._derivationPath;
+ return this._baseDerivationPath;
}
/**
* Set a desired derivation path when computing the available user addresses
- * @param derivationPath The desired derivation path (e.g `44'/60'/0'`)
- */
- public setPath(derivationPath: string) {
- this._derivationPath = derivationPath;
- }
- /**
- * Set the final derivation path index. If a user wishes to sign a message with the
- * 6th address in a derivation path, before calling `signPersonalMessageAsync`, you must
- * call this method with pathIndex `6`.
- * @param pathIndex Desired derivation path index
+ * @param basDerivationPath The desired derivation path (e.g `44'/60'/0'`)
*/
- public setPathIndex(pathIndex: number) {
- this._derivationPathIndex = pathIndex;
+ public setPath(basDerivationPath: string) {
+ this._baseDerivationPath = basDerivationPath;
}
/**
* Retrieve a users Ledger accounts. The accounts are derived from the derivationPath,
- * master public key and chainCode. Because of this, you can request as many accounts
+ * master public key and chain code. Because of this, you can request as many accounts
* as you wish and it only requires a single request to the Ledger device. This method
* is automatically called when issuing a `eth_accounts` JSON RPC request via your providerEngine
* instance.
@@ -90,46 +87,27 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
* @return An array of accounts
*/
public async getAccountsAsync(numberOfAccounts: number = DEFAULT_NUM_ADDRESSES_TO_FETCH): Promise<string[]> {
- this._ledgerClientIfExists = await this._createLedgerClientAsync();
-
- let ledgerResponse;
- try {
- ledgerResponse = await this._ledgerClientIfExists.getAddress(
- this._derivationPath,
- this._shouldAlwaysAskForConfirmation,
- SHOULD_GET_CHAIN_CODE,
- );
- } finally {
- await this._destroyLedgerClientAsync();
- }
-
- const hdKey = new HDNode();
- hdKey.publicKey = new Buffer(ledgerResponse.publicKey, 'hex');
- hdKey.chainCode = new Buffer(ledgerResponse.chainCode, 'hex');
-
- const accounts: string[] = [];
- for (let i = 0; i < numberOfAccounts; i++) {
- const derivedHDNode = hdKey.derive(`m/${i + this._derivationPathIndex}`);
- const derivedPublicKey = derivedHDNode.publicKey;
- const shouldSanitizePublicKey = true;
- const ethereumAddressUnprefixed = ethUtil
- .publicToAddress(derivedPublicKey, shouldSanitizePublicKey)
- .toString('hex');
- const ethereumAddressPrefixed = ethUtil.addHexPrefix(ethereumAddressUnprefixed);
- accounts.push(ethereumAddressPrefixed.toLowerCase());
- }
+ const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync();
+ const derivedKeyInfos = walletUtils.calculateDerivedHDKeyInfos(initialDerivedKeyInfo, numberOfAccounts);
+ const accounts = _.map(derivedKeyInfos, k => k.address);
return accounts;
}
/**
- * Sign a transaction with the Ledger. If you've added the LedgerSubprovider to your
- * app's provider, you can simply send an `eth_sendTransaction` JSON RPC request, and
- * this method will be called auto-magically. If you are not using this via a ProviderEngine
+ * Signs a transaction on the Ledger with the account specificed by the `from` field in txParams.
+ * If you've added the LedgerSubprovider to your app's provider, you can simply send an `eth_sendTransaction`
+ * JSON RPC request, and this method will be called auto-magically. If you are not using this via a ProviderEngine
* instance, you can call it directly.
* @param txParams Parameters of the transaction to sign
* @return Signed transaction hex string
*/
public async signTransactionAsync(txParams: PartialTxParams): Promise<string> {
LedgerSubprovider._validateTxParams(txParams);
+ if (_.isUndefined(txParams.from) || !addressUtils.isAddress(txParams.from)) {
+ throw new Error(WalletSubproviderErrors.FromAddressMissingOrInvalid);
+ }
+ const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync();
+ const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, txParams.from);
+
this._ledgerClientIfExists = await this._createLedgerClientAsync();
const tx = new EthereumTx(txParams);
@@ -141,8 +119,8 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
const txHex = tx.serialize().toString('hex');
try {
- const derivationPath = this._getDerivationPath();
- const result = await this._ledgerClientIfExists.signTransaction(derivationPath, txHex);
+ const fullDerivationPath = derivedKeyInfo.derivationPath;
+ const result = await this._ledgerClientIfExists.signTransaction(fullDerivationPath, txHex);
// Store signature in transaction
tx.r = Buffer.from(result.r, 'hex');
tx.s = Buffer.from(result.s, 'hex');
@@ -165,25 +143,30 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
}
}
/**
- * Sign a personal Ethereum signed message. The signing address will be the one
- * retrieved given a derivationPath and pathIndex set on the subprovider.
+ * Sign a personal Ethereum signed message. The signing account will be the account
+ * associated with the provided address.
* The Ledger adds the Ethereum signed message prefix on-device. If you've added
* the LedgerSubprovider to your app's provider, you can simply send an `eth_sign`
* or `personal_sign` JSON RPC request, and this method will be called auto-magically.
* If you are not using this via a ProviderEngine instance, you can call it directly.
- * @param data Message to sign
+ * @param data Hex string message to sign
+ * @param address Address of the account to sign with
* @return Signature hex string (order: rsv)
*/
- public async signPersonalMessageAsync(data: string): Promise<string> {
+ public async signPersonalMessageAsync(data: string, address: string): Promise<string> {
if (_.isUndefined(data)) {
throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage);
}
assert.isHexString('data', data);
+ assert.isETHAddressHex('address', address);
+ const initialDerivedKeyInfo = await this._initialDerivedKeyInfoAsync();
+ const derivedKeyInfo = this._findDerivedKeyInfoForAddress(initialDerivedKeyInfo, address);
+
this._ledgerClientIfExists = await this._createLedgerClientAsync();
try {
- const derivationPath = this._getDerivationPath();
+ const fullDerivationPath = derivedKeyInfo.derivationPath;
const result = await this._ledgerClientIfExists.signPersonalMessage(
- derivationPath,
+ fullDerivationPath,
ethUtil.stripHexPrefix(data),
);
const v = result.v - 27;
@@ -199,10 +182,6 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
throw err;
}
}
- private _getDerivationPath() {
- const derivationPath = `${this.getPath()}/${this._derivationPathIndex}`;
- return derivationPath;
- }
private async _createLedgerClientAsync(): Promise<LedgerEthereumClient> {
await this._connectionLock.acquire();
if (!_.isUndefined(this._ledgerClientIfExists)) {
@@ -223,4 +202,41 @@ export class LedgerSubprovider extends BaseWalletSubprovider {
this._ledgerClientIfExists = undefined;
this._connectionLock.release();
}
+ private async _initialDerivedKeyInfoAsync(): Promise<DerivedHDKeyInfo> {
+ this._ledgerClientIfExists = await this._createLedgerClientAsync();
+
+ const parentKeyDerivationPath = `m/${this._baseDerivationPath}`;
+ let ledgerResponse;
+ try {
+ ledgerResponse = await this._ledgerClientIfExists.getAddress(
+ parentKeyDerivationPath,
+ this._shouldAlwaysAskForConfirmation,
+ SHOULD_GET_CHAIN_CODE,
+ );
+ } finally {
+ await this._destroyLedgerClientAsync();
+ }
+ const hdKey = new HDNode();
+ hdKey.publicKey = new Buffer(ledgerResponse.publicKey, 'hex');
+ hdKey.chainCode = new Buffer(ledgerResponse.chainCode, 'hex');
+ const address = walletUtils.addressOfHDKey(hdKey);
+ const initialDerivedKeyInfo = {
+ hdKey,
+ address,
+ derivationPath: parentKeyDerivationPath,
+ baseDerivationPath: this._baseDerivationPath,
+ };
+ return initialDerivedKeyInfo;
+ }
+ private _findDerivedKeyInfoForAddress(initalHDKey: DerivedHDKeyInfo, address: string): DerivedHDKeyInfo {
+ const matchedDerivedKeyInfo = walletUtils.findDerivedKeyInfoForAddressIfExists(
+ address,
+ initalHDKey,
+ this._addressSearchLimit,
+ );
+ if (_.isUndefined(matchedDerivedKeyInfo)) {
+ throw new Error(`${WalletSubproviderErrors.AddressNotFound}: ${address}`);
+ }
+ return matchedDerivedKeyInfo;
+ }
}
diff --git a/packages/subproviders/src/subproviders/mnemonic_wallet.ts b/packages/subproviders/src/subproviders/mnemonic_wallet.ts
new file mode 100644
index 000000000..080bfeb4c
--- /dev/null
+++ b/packages/subproviders/src/subproviders/mnemonic_wallet.ts
@@ -0,0 +1,145 @@
+import { assert } from '@0xproject/assert';
+import { addressUtils } from '@0xproject/utils';
+import * as bip39 from 'bip39';
+import ethUtil = require('ethereumjs-util');
+import HDNode = require('hdkey');
+import * as _ from 'lodash';
+
+import { DerivedHDKeyInfo, MnemonicWalletSubproviderConfigs, PartialTxParams, WalletSubproviderErrors } from '../types';
+import { walletUtils } from '../utils/wallet_utils';
+
+import { BaseWalletSubprovider } from './base_wallet_subprovider';
+import { PrivateKeyWalletSubprovider } from './private_key_wallet';
+
+const DEFAULT_BASE_DERIVATION_PATH = `44'/60'/0'/0`;
+const DEFAULT_NUM_ADDRESSES_TO_FETCH = 10;
+const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
+
+/**
+ * This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface.
+ * This subprovider intercepts all account related RPC requests (e.g message/transaction signing, etc...) and handles
+ * all requests with accounts derived from the supplied mnemonic.
+ */
+export class MnemonicWalletSubprovider extends BaseWalletSubprovider {
+ private _addressSearchLimit: number;
+ private _baseDerivationPath: string;
+ private _derivedKeyInfo: DerivedHDKeyInfo;
+ private _mnemonic: string;
+
+ /**
+ * Instantiates a MnemonicWalletSubprovider. Defaults to baseDerivationPath set to `44'/60'/0'/0`.
+ * This is the default in TestRPC/Ganache, it can be overridden if desired.
+ * @param config Configuration for the mnemonic wallet, must contain the mnemonic
+ * @return MnemonicWalletSubprovider instance
+ */
+ constructor(config: MnemonicWalletSubproviderConfigs) {
+ assert.isString('mnemonic', config.mnemonic);
+ const baseDerivationPath = config.baseDerivationPath || DEFAULT_BASE_DERIVATION_PATH;
+ assert.isString('baseDerivationPath', baseDerivationPath);
+ const addressSearchLimit = config.addressSearchLimit || DEFAULT_ADDRESS_SEARCH_LIMIT;
+ assert.isNumber('addressSearchLimit', addressSearchLimit);
+ super();
+
+ this._mnemonic = config.mnemonic;
+ this._baseDerivationPath = baseDerivationPath;
+ this._addressSearchLimit = addressSearchLimit;
+ this._derivedKeyInfo = this._initialDerivedKeyInfo(this._baseDerivationPath);
+ }
+ /**
+ * Retrieve the set derivation path
+ * @returns derivation path
+ */
+ public getPath(): string {
+ return this._baseDerivationPath;
+ }
+ /**
+ * Set a desired derivation path when computing the available user addresses
+ * @param baseDerivationPath The desired derivation path (e.g `44'/60'/0'`)
+ */
+ public setPath(baseDerivationPath: string) {
+ this._baseDerivationPath = baseDerivationPath;
+ this._derivedKeyInfo = this._initialDerivedKeyInfo(this._baseDerivationPath);
+ }
+ /**
+ * Retrieve the accounts associated with the mnemonic.
+ * This method is implicitly called when issuing a `eth_accounts` JSON RPC request
+ * via your providerEngine instance.
+ * @param numberOfAccounts Number of accounts to retrieve (default: 10)
+ * @return An array of accounts
+ */
+ public async getAccountsAsync(numberOfAccounts: number = DEFAULT_NUM_ADDRESSES_TO_FETCH): Promise<string[]> {
+ const derivedKeys = walletUtils.calculateDerivedHDKeyInfos(this._derivedKeyInfo, numberOfAccounts);
+ const accounts = _.map(derivedKeys, k => k.address);
+ return accounts;
+ }
+
+ /**
+ * Signs a transaction with the account specificed by the `from` field in txParams.
+ * If you've added this Subprovider to your app's provider, you can simply send
+ * an `eth_sendTransaction` JSON RPC request, and this method will be called auto-magically.
+ * If you are not using this via a ProviderEngine instance, you can call it directly.
+ * @param txParams Parameters of the transaction to sign
+ * @return Signed transaction hex string
+ */
+ public async signTransactionAsync(txParams: PartialTxParams): Promise<string> {
+ if (_.isUndefined(txParams.from) || !addressUtils.isAddress(txParams.from)) {
+ throw new Error(WalletSubproviderErrors.FromAddressMissingOrInvalid);
+ }
+ const privateKeyWallet = this._privateKeyWalletForAddress(txParams.from);
+ const signedTx = privateKeyWallet.signTransactionAsync(txParams);
+ return signedTx;
+ }
+ /**
+ * Sign a personal Ethereum signed message. The signing account will be the account
+ * associated with the provided address.
+ * If you've added the MnemonicWalletSubprovider to your app's provider, you can simply send an `eth_sign`
+ * or `personal_sign` JSON RPC request, and this method will be called auto-magically.
+ * If you are not using this via a ProviderEngine instance, you can call it directly.
+ * @param data Hex string message to sign
+ * @param address Address of the account to sign with
+ * @return Signature hex string (order: rsv)
+ */
+ public async signPersonalMessageAsync(data: string, address: string): Promise<string> {
+ if (_.isUndefined(data)) {
+ throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage);
+ }
+ assert.isHexString('data', data);
+ assert.isETHAddressHex('address', address);
+ const privateKeyWallet = this._privateKeyWalletForAddress(address);
+ const sig = await privateKeyWallet.signPersonalMessageAsync(data, address);
+ return sig;
+ }
+ private _privateKeyWalletForAddress(address: string): PrivateKeyWalletSubprovider {
+ const derivedKeyInfo = this._findDerivedKeyInfoForAddress(address);
+ const privateKeyHex = derivedKeyInfo.hdKey.privateKey.toString('hex');
+ const privateKeyWallet = new PrivateKeyWalletSubprovider(privateKeyHex);
+ return privateKeyWallet;
+ }
+ private _findDerivedKeyInfoForAddress(address: string): DerivedHDKeyInfo {
+ const matchedDerivedKeyInfo = walletUtils.findDerivedKeyInfoForAddressIfExists(
+ address,
+ this._derivedKeyInfo,
+ this._addressSearchLimit,
+ );
+ if (_.isUndefined(matchedDerivedKeyInfo)) {
+ throw new Error(`${WalletSubproviderErrors.AddressNotFound}: ${address}`);
+ }
+ return matchedDerivedKeyInfo;
+ }
+ private _initialDerivedKeyInfo(baseDerivationPath: string): DerivedHDKeyInfo {
+ const seed = bip39.mnemonicToSeed(this._mnemonic);
+ const hdKey = HDNode.fromMasterSeed(seed);
+ // Walk down to base derivation level (i.e m/44'/60'/0') and create an initial key at that level
+ // all children will then be walked relative (i.e m/0)
+ const parentKeyDerivationPath = `m/${baseDerivationPath}`;
+ const parentHDKeyAtDerivationPath = hdKey.derive(parentKeyDerivationPath);
+ const address = walletUtils.addressOfHDKey(parentHDKeyAtDerivationPath);
+ const derivedKeyInfo = {
+ address,
+ baseDerivationPath,
+ derivationPath: parentKeyDerivationPath,
+ hdKey: parentHDKeyAtDerivationPath,
+ };
+ return derivedKeyInfo;
+ }
+}
diff --git a/packages/subproviders/src/subproviders/private_key_wallet_subprovider.ts b/packages/subproviders/src/subproviders/private_key_wallet.ts
index c3a53773a..b3f48fd90 100644
--- a/packages/subproviders/src/subproviders/private_key_wallet_subprovider.ts
+++ b/packages/subproviders/src/subproviders/private_key_wallet.ts
@@ -1,13 +1,11 @@
import { assert } from '@0xproject/assert';
-import { JSONRPCRequestPayload } from '@0xproject/types';
import EthereumTx = require('ethereumjs-tx');
import * as ethUtil from 'ethereumjs-util';
import * as _ from 'lodash';
-import { Callback, ErrorCallback, PartialTxParams, ResponseWithTxParams, WalletSubproviderErrors } from '../types';
+import { PartialTxParams, WalletSubproviderErrors } from '../types';
import { BaseWalletSubprovider } from './base_wallet_subprovider';
-import { Subprovider } from './subprovider';
/**
* This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface.
@@ -17,6 +15,11 @@ import { Subprovider } from './subprovider';
export class PrivateKeyWalletSubprovider extends BaseWalletSubprovider {
private _address: string;
private _privateKeyBuffer: Buffer;
+ /**
+ * Instantiates a PrivateKeyWalletSubprovider.
+ * @param privateKey The corresponding private key to an Ethereum address
+ * @return PrivateKeyWalletSubprovider instance
+ */
constructor(privateKey: string) {
assert.isString('privateKey', privateKey);
super();
@@ -42,26 +45,40 @@ export class PrivateKeyWalletSubprovider extends BaseWalletSubprovider {
*/
public async signTransactionAsync(txParams: PartialTxParams): Promise<string> {
PrivateKeyWalletSubprovider._validateTxParams(txParams);
+ if (!_.isUndefined(txParams.from) && txParams.from !== this._address) {
+ throw new Error(
+ `Requested to sign transaction with address: ${txParams.from}, instantiated with address: ${
+ this._address
+ }`,
+ );
+ }
const tx = new EthereumTx(txParams);
tx.sign(this._privateKeyBuffer);
const rawTx = `0x${tx.serialize().toString('hex')}`;
return rawTx;
}
/**
- * Sign a personal Ethereum signed message. The signing address will be
- * calculated from the private key.
- * If you've added the PKWalletSubprovider to your app's provider, you can simply send an `eth_sign`
+ * Sign a personal Ethereum signed message. The signing address will be calculated from the private key.
+ * The address must be provided it must match the address calculated from the private key.
+ * If you've added this Subprovider to your app's provider, you can simply send an `eth_sign`
* or `personal_sign` JSON RPC request, and this method will be called auto-magically.
* If you are not using this via a ProviderEngine instance, you can call it directly.
- * @param data Message to sign
+ * @param data Hex string message to sign
+ * @param address Address of the account to sign with
* @return Signature hex string (order: rsv)
*/
- public async signPersonalMessageAsync(dataIfExists: string): Promise<string> {
- if (_.isUndefined(dataIfExists)) {
+ public async signPersonalMessageAsync(data: string, address: string): Promise<string> {
+ if (_.isUndefined(data)) {
throw new Error(WalletSubproviderErrors.DataMissingForSignPersonalMessage);
}
- assert.isHexString('data', dataIfExists);
- const dataBuff = ethUtil.toBuffer(dataIfExists);
+ assert.isHexString('data', data);
+ assert.isETHAddressHex('address', address);
+ if (address !== this._address) {
+ throw new Error(
+ `Requested to sign message with address: ${address}, instantiated with address: ${this._address}`,
+ );
+ }
+ const dataBuff = ethUtil.toBuffer(data);
const msgHashBuff = ethUtil.hashPersonalMessage(dataBuff);
const sig = ethUtil.ecsign(msgHashBuff, this._privateKeyBuffer);
const rpcSig = ethUtil.toRpcSig(sig.v, sig.r, sig.s);
diff --git a/packages/subproviders/src/types.ts b/packages/subproviders/src/types.ts
index bacb7091b..74ecec23b 100644
--- a/packages/subproviders/src/types.ts
+++ b/packages/subproviders/src/types.ts
@@ -1,4 +1,5 @@
import { ECSignature, JSONRPCRequestPayload } from '@0xproject/types';
+import HDNode = require('hdkey');
import * as _ from 'lodash';
export interface LedgerCommunicationClient {
@@ -40,20 +41,33 @@ export type LedgerEthereumClientFactoryAsync = () => Promise<LedgerEthereumClien
export interface LedgerSubproviderConfigs {
networkId: number;
ledgerEthereumClientFactoryAsync: LedgerEthereumClientFactoryAsync;
- derivationPath?: string;
+ baseDerivationPath?: string;
accountFetchingConfigs?: AccountFetchingConfigs;
}
/*
+ * addressSearchLimit: The maximum number of addresses to search through, defaults to 1000
* numAddressesToReturn: Number of addresses to return from 'eth_accounts' call
* shouldAskForOnDeviceConfirmation: Whether you wish to prompt the user on their Ledger
* before fetching their addresses
*/
export interface AccountFetchingConfigs {
+ addressSearchLimit?: number;
numAddressesToReturn?: number;
shouldAskForOnDeviceConfirmation?: boolean;
}
+/*
+ * mnemonic: The string mnemonic seed
+ * addressSearchLimit: The maximum number of addresses to search through, defaults to 1000
+ * baseDerivationPath: The base derivation path (e.g 44'/60'/0'/0)
+ */
+export interface MnemonicWalletSubproviderConfigs {
+ mnemonic: string;
+ addressSearchLimit?: number;
+ baseDerivationPath?: string;
+}
+
export interface SignatureData {
hash: string;
r: string;
@@ -67,18 +81,12 @@ export interface LedgerGetAddressResult {
chainCode: string;
}
-export interface LedgerWalletSubprovider {
- getPath: () => string;
- setPath: (path: string) => void;
- setPathIndex: (pathIndex: number) => void;
-}
-
export interface PartialTxParams {
nonce: string;
gasPrice?: string;
gas: string;
to: string;
- from?: string;
+ from: string;
value?: string;
data?: string;
chainId: number; // EIP 155 chainId - mainnet: 1, ropsten: 3
@@ -96,12 +104,13 @@ export interface ResponseWithTxParams {
}
export enum WalletSubproviderErrors {
+ AddressNotFound = 'ADDRESS_NOT_FOUND',
DataMissingForSignPersonalMessage = 'DATA_MISSING_FOR_SIGN_PERSONAL_MESSAGE',
SenderInvalidOrNotSupplied = 'SENDER_INVALID_OR_NOT_SUPPLIED',
+ FromAddressMissingOrInvalid = 'FROM_ADDRESS_MISSING_OR_INVALID',
}
export enum LedgerSubproviderErrors {
TooOldLedgerFirmware = 'TOO_OLD_LEDGER_FIRMWARE',
- FromAddressMissingOrInvalid = 'FROM_ADDRESS_MISSING_OR_INVALID',
MultipleOpenConnectionsDisallowed = 'MULTIPLE_OPEN_CONNECTIONS_DISALLOWED',
}
@@ -109,6 +118,12 @@ export enum NonceSubproviderErrors {
EmptyParametersFound = 'EMPTY_PARAMETERS_FOUND',
CannotDetermineAddressFromPayload = 'CANNOT_DETERMINE_ADDRESS_FROM_PAYLOAD',
}
+export interface DerivedHDKeyInfo {
+ address: string;
+ baseDerivationPath: string;
+ derivationPath: string;
+ hdKey: HDNode;
+}
export type ErrorCallback = (err: Error | null, data?: any) => void;
export type Callback = () => void;
diff --git a/packages/subproviders/src/utils/wallet_utils.ts b/packages/subproviders/src/utils/wallet_utils.ts
new file mode 100644
index 000000000..cd5cd9ba0
--- /dev/null
+++ b/packages/subproviders/src/utils/wallet_utils.ts
@@ -0,0 +1,79 @@
+import ethUtil = require('ethereumjs-util');
+import HDNode = require('hdkey');
+import * as _ from 'lodash';
+
+import { DerivedHDKeyInfo, WalletSubproviderErrors } from '../types';
+
+const DEFAULT_ADDRESS_SEARCH_LIMIT = 1000;
+
+class DerivedHDKeyInfoIterator implements IterableIterator<DerivedHDKeyInfo> {
+ private _parentDerivedKeyInfo: DerivedHDKeyInfo;
+ private _searchLimit: number;
+ private _index: number;
+
+ constructor(initialDerivedKey: DerivedHDKeyInfo, searchLimit: number = DEFAULT_ADDRESS_SEARCH_LIMIT) {
+ this._searchLimit = searchLimit;
+ this._parentDerivedKeyInfo = initialDerivedKey;
+ this._index = 0;
+ }
+
+ public next(): IteratorResult<DerivedHDKeyInfo> {
+ const baseDerivationPath = this._parentDerivedKeyInfo.baseDerivationPath;
+ const derivationIndex = this._index;
+ const fullDerivationPath = `m/${baseDerivationPath}/${derivationIndex}`;
+ const path = `m/${derivationIndex}`;
+ const hdKey = this._parentDerivedKeyInfo.hdKey.derive(path);
+ const address = walletUtils.addressOfHDKey(hdKey);
+ const derivedKey: DerivedHDKeyInfo = {
+ address,
+ hdKey,
+ baseDerivationPath,
+ derivationPath: fullDerivationPath,
+ };
+ const done = this._index === this._searchLimit;
+ this._index++;
+ return {
+ done,
+ value: derivedKey,
+ };
+ }
+
+ public [Symbol.iterator](): IterableIterator<DerivedHDKeyInfo> {
+ return this;
+ }
+}
+
+export const walletUtils = {
+ calculateDerivedHDKeyInfos(parentDerivedKeyInfo: DerivedHDKeyInfo, numberOfKeys: number): DerivedHDKeyInfo[] {
+ const derivedKeys: DerivedHDKeyInfo[] = [];
+ const derivedKeyIterator = new DerivedHDKeyInfoIterator(parentDerivedKeyInfo, numberOfKeys);
+ for (const key of derivedKeyIterator) {
+ derivedKeys.push(key);
+ }
+ return derivedKeys;
+ },
+ findDerivedKeyInfoForAddressIfExists(
+ address: string,
+ parentDerivedKeyInfo: DerivedHDKeyInfo,
+ searchLimit: number,
+ ): DerivedHDKeyInfo | undefined {
+ let matchedKey: DerivedHDKeyInfo | undefined;
+ const derivedKeyIterator = new DerivedHDKeyInfoIterator(parentDerivedKeyInfo, searchLimit);
+ for (const key of derivedKeyIterator) {
+ if (key.address === address) {
+ matchedKey = key;
+ break;
+ }
+ }
+ return matchedKey;
+ },
+ addressOfHDKey(hdKey: HDNode): string {
+ const shouldSanitizePublicKey = true;
+ const derivedPublicKey = hdKey.publicKey;
+ const ethereumAddressUnprefixed = ethUtil
+ .publicToAddress(derivedPublicKey, shouldSanitizePublicKey)
+ .toString('hex');
+ const address = ethUtil.addHexPrefix(ethereumAddressUnprefixed).toLowerCase();
+ return address;
+ },
+};