From 62febac87659ddf78a34dd0dac1ee8a38d8c8e77 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 27 Feb 2018 15:14:18 -0800 Subject: refactor retrytx with higher gas price: - create a new tx instead of overwriting the tx hash - add a new state 'dropped' to the txStateManager - mark duplicate txs as dropped when one gets confirmed in a block --- app/scripts/controllers/transactions.js | 43 +++++++++++++++++++++------------ app/scripts/lib/tx-state-manager.js | 38 +++++++++++++++++++++-------- 2 files changed, 55 insertions(+), 26 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index ef5578d5a..aad3f9952 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -6,7 +6,6 @@ const EthQuery = require('ethjs-query') const TransactionStateManger = require('../lib/tx-state-manager') const TxGasUtil = require('../lib/tx-gas-utils') const PendingTransactionTracker = require('../lib/pending-tx-tracker') -const createId = require('../lib/random-id') const NonceTracker = require('../lib/nonce-tracker') /* @@ -92,8 +91,22 @@ module.exports = class TransactionController extends EventEmitter { this.pendingTxTracker.on('tx:warning', (txMeta) => { this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:warning') }) + this.pendingTxTracker.on('tx:confirmed', (txId) => { + this.txStateManager.setTxStatusConfirmed(txId) + // get the confirmed transactions nonce and from address + const txMeta = this.txStateManager.getTx(txId) + const { nonce, from } = txMeta.txParams + const sameNonceTxs = this.txStateManager.getFilteredTxList({nonce, from}) + if (!sameNonceTxs.length) return + // mark all same nonce transactions as dropped and give i a replacedBy hash + sameNonceTxs.forEach((otherTxMeta) => { + if (otherTxMeta === txId) return + otherTxMeta.replacedBy = txMeta.hash + this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:confirmed reference to confirmed txHash with same nonce') + this.txStateManager.setTxStatusDropped(otherTxMeta.id) + }) + }) this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) - this.pendingTxTracker.on('tx:confirmed', this.txStateManager.setTxStatusConfirmed.bind(this.txStateManager)) this.pendingTxTracker.on('tx:block-update', (txMeta, latestBlockNumber) => { if (!txMeta.firstRetryBlockNumber) { txMeta.firstRetryBlockNumber = latestBlockNumber @@ -186,14 +199,7 @@ module.exports = class TransactionController extends EventEmitter { // validate await this.txGasUtil.validateTxParams(txParams) // construct txMeta - const txMeta = { - id: createId(), - time: (new Date()).getTime(), - status: 'unapproved', - metamaskNetworkId: this.getNetwork(), - txParams: txParams, - loadingDefaults: true, - } + const txMeta = this.txStateManager.generateTxMeta({txParams}) this.addTx(txMeta) this.emit('newUnapprovedTx', txMeta) // add default tx params @@ -215,7 +221,6 @@ module.exports = class TransactionController extends EventEmitter { const txParams = txMeta.txParams // ensure value txMeta.gasPriceSpecified = Boolean(txParams.gasPrice) - txMeta.nonceSpecified = Boolean(txParams.nonce) let gasPrice = txParams.gasPrice if (!gasPrice) { gasPrice = this.getGasPrice ? this.getGasPrice() : await this.query.gasPrice() @@ -226,11 +231,17 @@ module.exports = class TransactionController extends EventEmitter { return await this.txGasUtil.analyzeGasUsage(txMeta) } - async retryTransaction (txId) { - this.txStateManager.setTxStatusUnapproved(txId) - const txMeta = this.txStateManager.getTx(txId) - txMeta.lastGasPrice = txMeta.txParams.gasPrice - this.txStateManager.updateTx(txMeta, 'retryTransaction: manual retry') + async retryTransaction (originalTxId) { + const originalTxMeta = this.txStateManager.getTx(originalTxId) + const lastGasPrice = originalTxMeta.txParams.gasPrice + const txMeta = this.txStateManager.generateTxMeta({ + txParams: originalTxMeta.txParams, + lastGasPrice, + loadingDefaults: false, + nonceSpecified: true, + }) + this.addTx(txMeta) + this.emit('newUnapprovedTx', txMeta) } async updateTransaction (txMeta) { diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index 051efd247..25442ce47 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -1,9 +1,21 @@ const extend = require('xtend') const EventEmitter = require('events') const ObservableStore = require('obs-store') +const createId = require('./random-id') const ethUtil = require('ethereumjs-util') const txStateHistoryHelper = require('./tx-state-history-helper') +// STATUS METHODS + // statuses: + // - `'unapproved'` the user has not responded + // - `'rejected'` the user has responded no! + // - `'approved'` the user has approved the tx + // - `'signed'` the tx is signed + // - `'submitted'` the tx is sent to a server + // - `'confirmed'` the tx has been included in a block. + // - `'failed'` the tx failed for some reason, included on tx data. + // - `'dropped'` the tx nonce was already used + module.exports = class TransactionStateManger extends EventEmitter { constructor ({ initState, txHistoryLimit, getNetwork }) { super() @@ -16,6 +28,16 @@ module.exports = class TransactionStateManger extends EventEmitter { this.getNetwork = getNetwork } + generateTxMeta (opts) { + return extend({ + id: createId(), + time: (new Date()).getTime(), + status: 'unapproved', + metamaskNetworkId: this.getNetwork(), + loadingDefaults: true, + }, opts) + } + // Returns the number of txs for the current network. getTxCount () { return this.getTxList().length @@ -164,16 +186,6 @@ module.exports = class TransactionStateManger extends EventEmitter { }) } - // STATUS METHODS - // statuses: - // - `'unapproved'` the user has not responded - // - `'rejected'` the user has responded no! - // - `'approved'` the user has approved the tx - // - `'signed'` the tx is signed - // - `'submitted'` the tx is sent to a server - // - `'confirmed'` the tx has been included in a block. - // - `'failed'` the tx failed for some reason, included on tx data. - // get::set status // should return the status of the tx. @@ -211,6 +223,12 @@ module.exports = class TransactionStateManger extends EventEmitter { this._setTxStatus(txId, 'confirmed') } + // should update the status dropped + setTxStatusDropped (txId) { + this._setTxStatus(txId, 'dropped') + } + + setTxStatusFailed (txId, err) { const txMeta = this.getTx(txId) txMeta.err = { -- cgit From 4a3288fec9ae7bd717b539d9bfcb8d5ba5b1ef8c Mon Sep 17 00:00:00 2001 From: frankiebee Date: Wed, 7 Mar 2018 22:01:14 -0800 Subject: transactions - make _markNonceDuplicatesDropped --- app/scripts/controllers/transactions.js | 41 ++++++++++++++++----------------- 1 file changed, 20 insertions(+), 21 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index aad3f9952..e903c73e8 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -91,21 +91,7 @@ module.exports = class TransactionController extends EventEmitter { this.pendingTxTracker.on('tx:warning', (txMeta) => { this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:warning') }) - this.pendingTxTracker.on('tx:confirmed', (txId) => { - this.txStateManager.setTxStatusConfirmed(txId) - // get the confirmed transactions nonce and from address - const txMeta = this.txStateManager.getTx(txId) - const { nonce, from } = txMeta.txParams - const sameNonceTxs = this.txStateManager.getFilteredTxList({nonce, from}) - if (!sameNonceTxs.length) return - // mark all same nonce transactions as dropped and give i a replacedBy hash - sameNonceTxs.forEach((otherTxMeta) => { - if (otherTxMeta === txId) return - otherTxMeta.replacedBy = txMeta.hash - this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:confirmed reference to confirmed txHash with same nonce') - this.txStateManager.setTxStatusDropped(otherTxMeta.id) - }) - }) + this.pendingTxTracker.on('tx:confirmed', (txId) => this._markNonceDuplicatesDropped(txId)) this.pendingTxTracker.on('tx:failed', this.txStateManager.setTxStatusFailed.bind(this.txStateManager)) this.pendingTxTracker.on('tx:block-update', (txMeta, latestBlockNumber) => { if (!txMeta.firstRetryBlockNumber) { @@ -238,7 +224,6 @@ module.exports = class TransactionController extends EventEmitter { txParams: originalTxMeta.txParams, lastGasPrice, loadingDefaults: false, - nonceSpecified: true, }) this.addTx(txMeta) this.emit('newUnapprovedTx', txMeta) @@ -264,11 +249,9 @@ module.exports = class TransactionController extends EventEmitter { // wait for a nonce nonceLock = await this.nonceTracker.getNonceLock(fromAddress) // add nonce to txParams - const nonce = txMeta.nonceSpecified ? txMeta.txParams.nonce : nonceLock.nextNonce - if (nonce > nonceLock.nextNonce) { - const message = `Specified nonce may not be larger than account's next valid nonce.` - throw new Error(message) - } + // if txMeta has lastGasPrice then it is a retry at same nonce with higher + // gas price transaction and their for the nonce should not be calculated + const nonce = txMeta.lastGasPrice ? txMeta.txParams.nonce : nonceLock.nextNonce txMeta.txParams.nonce = ethUtil.addHexPrefix(nonce.toString(16)) // add nonce debugging information to txMeta txMeta.nonceDetails = nonceLock.nonceDetails @@ -325,6 +308,22 @@ module.exports = class TransactionController extends EventEmitter { // PRIVATE METHODS // + _markNonceDuplicatesDropped (txId) { + this.txStateManager.setTxStatusConfirmed(txId) + // get the confirmed transactions nonce and from address + const txMeta = this.txStateManager.getTx(txId) + const { nonce, from } = txMeta.txParams + const sameNonceTxs = this.txStateManager.getFilteredTxList({nonce, from}) + if (!sameNonceTxs.length) return + // mark all same nonce transactions as dropped and give i a replacedBy hash + sameNonceTxs.forEach((otherTxMeta) => { + if (otherTxMeta === txId) return + otherTxMeta.replacedBy = txMeta.hash + this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:confirmed reference to confirmed txHash with same nonce') + this.txStateManager.setTxStatusDropped(otherTxMeta.id) + }) + } + _updateMemstore () { const unapprovedTxs = this.txStateManager.getUnapprovedTxList() const selectedAddressTxList = this.txStateManager.getFilteredTxList({ -- cgit From 5572345b781ce68178dd4e72d4e56b2dec26a454 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Thu, 8 Mar 2018 10:36:31 -0800 Subject: fix marking of confirmed transaction as dropped --- app/scripts/controllers/transactions.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index e903c73e8..3dbd424ca 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -317,7 +317,7 @@ module.exports = class TransactionController extends EventEmitter { if (!sameNonceTxs.length) return // mark all same nonce transactions as dropped and give i a replacedBy hash sameNonceTxs.forEach((otherTxMeta) => { - if (otherTxMeta === txId) return + if (otherTxMeta.id === txId) return otherTxMeta.replacedBy = txMeta.hash this.txStateManager.updateTx(txMeta, 'transactions/pending-tx-tracker#event: tx:confirmed reference to confirmed txHash with same nonce') this.txStateManager.setTxStatusDropped(otherTxMeta.id) -- cgit From 9fd349d7407d7c33deb317942f7e2835585767c9 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 13 Mar 2018 09:51:37 -0700 Subject: transactions:state - add a submittedTime stamp so the ui has a better grasp of the time of submission --- app/scripts/lib/tx-state-manager.js | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'app/scripts') diff --git a/app/scripts/lib/tx-state-manager.js b/app/scripts/lib/tx-state-manager.js index e75f733aa..ad07c813f 100644 --- a/app/scripts/lib/tx-state-manager.js +++ b/app/scripts/lib/tx-state-manager.js @@ -214,7 +214,11 @@ module.exports = class TransactionStateManager extends EventEmitter { } // should update the status of the tx to 'submitted'. + // and add a time stamp for when it was called setTxStatusSubmitted (txId) { + const txMeta = this.getTx(txId) + txMeta.submittedTime = (new Date()).getTime() + this.updateTx(txMeta, 'txStateManager - add submitted time stamp') this._setTxStatus(txId, 'submitted') } -- cgit From 9d7640996aa9b63fb6c9271d7e0698e7acdc559e Mon Sep 17 00:00:00 2001 From: frankiebee Date: Tue, 13 Mar 2018 14:42:26 -0700 Subject: transactions - return the txMeta in retryTransaction --- app/scripts/controllers/transactions.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index a3f731b6e..ab07dde62 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -3,7 +3,7 @@ const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') const Transaction = require('ethereumjs-tx') const EthQuery = require('ethjs-query') -const TransactionStateManager = require('../lib/tx-state-manager') +const TransactionStateManger = require('../lib/tx-state-manager') const TxGasUtil = require('../lib/tx-gas-utils') const PendingTransactionTracker = require('../lib/pending-tx-tracker') const NonceTracker = require('../lib/nonce-tracker') @@ -37,7 +37,7 @@ module.exports = class TransactionController extends EventEmitter { this.query = new EthQuery(this.provider) this.txGasUtil = new TxGasUtil(this.provider) - this.txStateManager = new TransactionStateManager({ + this.txStateManager = new TransactionStateManger({ initState: opts.initState, txHistoryLimit: opts.txHistoryLimit, getNetwork: this.getNetwork.bind(this), @@ -227,6 +227,7 @@ module.exports = class TransactionController extends EventEmitter { }) this.addTx(txMeta) this.emit('newUnapprovedTx', txMeta) + return txMeta } async updateTransaction (txMeta) { -- cgit From 2d3763d70927dd1aefbc19f9ab6d463a713f2576 Mon Sep 17 00:00:00 2001 From: Lazaridis Date: Sat, 10 Mar 2018 04:56:39 +0200 Subject: add READMEs to folders, re #3427 --- app/scripts/README.md | 14 ++++++++++++++ app/scripts/controllers/README.md | 4 ++++ app/scripts/migrations/README.md | 5 +++++ 3 files changed, 23 insertions(+) create mode 100644 app/scripts/README.md create mode 100644 app/scripts/controllers/README.md create mode 100644 app/scripts/migrations/README.md (limited to 'app/scripts') diff --git a/app/scripts/README.md b/app/scripts/README.md new file mode 100644 index 000000000..f5a907244 --- /dev/null +++ b/app/scripts/README.md @@ -0,0 +1,14 @@ +# Main MetaMask Code + +This folder contains the core-code. + +Currently, it is organized mostly based on file category, like: + +controllers, migrations, lib + +## Ongoing Task + +Refactor code-structure, thus the subsystems are reflected on the filesystem. + +### Examples + diff --git a/app/scripts/controllers/README.md b/app/scripts/controllers/README.md new file mode 100644 index 000000000..392c0457d --- /dev/null +++ b/app/scripts/controllers/README.md @@ -0,0 +1,4 @@ +# Controllers + +Different controllers (in the sense of *VC *View-Controller). + diff --git a/app/scripts/migrations/README.md b/app/scripts/migrations/README.md new file mode 100644 index 000000000..3a67b08e1 --- /dev/null +++ b/app/scripts/migrations/README.md @@ -0,0 +1,5 @@ +# Migrations + +Data (user data, config files etc.) is migrated from one version to another. + +Migrations are called by {} from {} during {}. \ No newline at end of file -- cgit From 106ce091a9ef9fbd37b90c49bc76f12bd796ebb5 Mon Sep 17 00:00:00 2001 From: Dan Date: Wed, 14 Mar 2018 11:45:04 -0230 Subject: Fix TransactionStateManager spelling. --- app/scripts/controllers/transactions.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js index ab07dde62..3e3909361 100644 --- a/app/scripts/controllers/transactions.js +++ b/app/scripts/controllers/transactions.js @@ -3,7 +3,7 @@ const ObservableStore = require('obs-store') const ethUtil = require('ethereumjs-util') const Transaction = require('ethereumjs-tx') const EthQuery = require('ethjs-query') -const TransactionStateManger = require('../lib/tx-state-manager') +const TransactionStateManager = require('../lib/tx-state-manager') const TxGasUtil = require('../lib/tx-gas-utils') const PendingTransactionTracker = require('../lib/pending-tx-tracker') const NonceTracker = require('../lib/nonce-tracker') @@ -37,7 +37,7 @@ module.exports = class TransactionController extends EventEmitter { this.query = new EthQuery(this.provider) this.txGasUtil = new TxGasUtil(this.provider) - this.txStateManager = new TransactionStateManger({ + this.txStateManager = new TransactionStateManager({ initState: opts.initState, txHistoryLimit: opts.txHistoryLimit, getNetwork: this.getNetwork.bind(this), -- cgit From bc987a1129194c0c79cde9d73557a98a22aa4e40 Mon Sep 17 00:00:00 2001 From: frankiebee Date: Wed, 14 Mar 2018 08:20:54 -0700 Subject: fix destructuring of variables --- app/scripts/lib/local-store.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/lib/local-store.js b/app/scripts/lib/local-store.js index 781aea17e..1cf00dd30 100644 --- a/app/scripts/lib/local-store.js +++ b/app/scripts/lib/local-store.js @@ -3,7 +3,7 @@ // https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage/local const extension = require('extensionizer') -const { promisify } = require('util').promisify +const { promisify } = require('util') module.exports = class ExtensionStore { constructor() { -- cgit From d8f5150aa5bf4b04310f887504428f1caa13cbf4 Mon Sep 17 00:00:00 2001 From: Lazaridis Date: Fri, 16 Mar 2018 00:27:10 +0200 Subject: adds initial documentation, re #3568 --- app/scripts/metamask-controller.js | 178 ++++++++++++++++++++++++++++--------- 1 file changed, 138 insertions(+), 40 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 0a5c1d36f..31c0bed58 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -1,3 +1,9 @@ +/** + * @file The central metamask controller. Aggregates other controllers and exports an api. + * @copyright Copyright (c) 2018 MetaMask + * @license MIT + */ + const EventEmitter = require('events') const extend = require('xtend') const pump = require('pump') @@ -41,7 +47,11 @@ const seedPhraseVerifier = require('./lib/seed-phrase-verifier') module.exports = class MetamaskController extends EventEmitter { - constructor (opts) { + /** + * @constructor + * @param {Object} opts + */ + constructor (opts) { super() this.defaultMaxListeners = 20 @@ -223,10 +233,9 @@ module.exports = class MetamaskController extends EventEmitter { this.infuraController.store.subscribe(sendUpdate) } - // - // Constructor helpers - // - + /** + * Constructor helper: initialize a provider. + */ initializeProvider () { const providerOpts = { static: { @@ -257,6 +266,9 @@ module.exports = class MetamaskController extends EventEmitter { return providerProxy } + /** + * Constructor helper: initialize a public confi store. + */ initPublicConfigStore () { // get init state const publicConfigStore = new ObservableStore() @@ -282,6 +294,9 @@ module.exports = class MetamaskController extends EventEmitter { // State Management // + /** + * ? + */ getState () { const wallet = this.configManager.getWallet() const vault = this.keyringController.store.getState().vault @@ -319,7 +334,10 @@ module.exports = class MetamaskController extends EventEmitter { // // Remote Features // - + + /** + * ? + */ getApi () { const keyringController = this.keyringController const preferencesController = this.preferencesController @@ -517,10 +535,22 @@ module.exports = class MetamaskController extends EventEmitter { return '0x' + percentileNumBn.mul(GWEI_BN).toString(16) } - // - // Vault Management - // - +//============================================================================= +// VAULT / KEYRING RELATED METHODS +//============================================================================= + + /** + * Creates a new Vault(?) and create a new keychain(?) + * + * A vault is ... + * + * A keychain is ... + * + * + * @param {} password + * + * @returns {} vault + */ async createNewVaultAndKeychain (password) { const release = await this.createVaultMutex.acquire() let vault @@ -544,6 +574,11 @@ module.exports = class MetamaskController extends EventEmitter { return vault } + /** + * Create a new Vault and restore an existent keychain + * @param {} password + * @param {} seed + */ async createNewVaultAndRestore (password, seed) { const release = await this.createVaultMutex.acquire() try { @@ -557,16 +592,28 @@ module.exports = class MetamaskController extends EventEmitter { } } + /** + * Retrieves the first Identiy from the passed Vault and selects the related address + * + * An Identity is ... + * + * @param {} vault + */ selectFirstIdentity (vault) { const { identities } = vault const address = Object.keys(identities)[0] this.preferencesController.setSelectedAddress(address) } - // + // ? // Opinionated Keyring Management // + /** + * Adds a new account to ... + * + * @returns {} keyState + */ async addNewAccount () { const primaryKeyring = this.keyringController.getKeyringsByType('HD Key Tree')[0] if (!primaryKeyring) { @@ -588,10 +635,12 @@ module.exports = class MetamaskController extends EventEmitter { return keyState } - // Adds the current vault's seed words to the UI's state tree. - // - // Used when creating a first vault, to allow confirmation. - // Also used when revealing the seed words in the confirmation view. + /** + * Adds the current vault's seed words to the UI's state tree. + * + * Used when creating a first vault, to allow confirmation. + * Also used when revealing the seed words in the confirmation view. + */ placeSeedWords (cb) { this.verifySeedPhrase() @@ -604,10 +653,13 @@ module.exports = class MetamaskController extends EventEmitter { }) } - // Verifies the current vault's seed words if they can restore the - // accounts belonging to the current vault. - // - // Called when the first account is created and on unlocking the vault. + /** + * Verifies the validity of the current vault's seed phrase. + * + * Validity: seed phrase can restore the accounts belonging to the current vault. + * + * Called when the first account is created and on unlocking the vault. + */ async verifySeedPhrase () { const primaryKeyring = this.keyringController.getKeyringsByType('HD Key Tree')[0] @@ -632,22 +684,33 @@ module.exports = class MetamaskController extends EventEmitter { } } - // ClearSeedWordCache - // - // Removes the primary account's seed words from the UI's state tree, - // ensuring they are only ever available in the background process. + /** + * Remove the primary account seed phrase from the UI's state tree. + * + * The seed phrase remains available in the background process. + * + */ clearSeedWordCache (cb) { this.configManager.setSeedWords(null) cb(null, this.preferencesController.getSelectedAddress()) } - + + /** + * ? + */ resetAccount (cb) { const selectedAddress = this.preferencesController.getSelectedAddress() this.txController.wipeTransactions(selectedAddress) cb(null, selectedAddress) } - + /** + * Imports an account ... ? + * + * @param {} strategy + * @param {} args + * @param {} cb + */ importAccountWithStrategy (strategy, args, cb) { accountImporter.importAccount(strategy, args) .then((privateKey) => { @@ -659,11 +722,15 @@ module.exports = class MetamaskController extends EventEmitter { .catch((reason) => { cb(reason) }) } +//============================================================================= +// END (VAULT / KEYRING RELATED METHODS) +//============================================================================= - // - // Identity Management - // - // + + +//============================================================================= +// Identity Management +//============================================================================= async retryTransaction (txId, cb) { await this.txController.retryTransaction(txId) @@ -729,7 +796,11 @@ module.exports = class MetamaskController extends EventEmitter { } }) } - + + /** + * @param {} msgParams + * @param {} cb + */ signMessage (msgParams, cb) { log.info('MetaMaskController - signMessage') const msgId = msgParams.metamaskId @@ -758,6 +829,12 @@ module.exports = class MetamaskController extends EventEmitter { } // Prefixed Style Message Signing Methods: + + /** + * + * @param {} msgParams + * @param {} cb + */ approvePersonalMessage (msgParams, cb) { const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams) this.sendUpdate() @@ -773,7 +850,10 @@ module.exports = class MetamaskController extends EventEmitter { } }) } - + + /** + * @param {} msgParams + */ signPersonalMessage (msgParams) { log.info('MetaMaskController - signPersonalMessage') const msgId = msgParams.metamaskId @@ -791,7 +871,10 @@ module.exports = class MetamaskController extends EventEmitter { return this.getState() }) } - + + /** + * @param {} msgParams + */ signTypedMessage (msgParams) { log.info('MetaMaskController - signTypedMessage') const msgId = msgParams.metamaskId @@ -843,13 +926,23 @@ module.exports = class MetamaskController extends EventEmitter { this.sendUpdate() cb() } - + + /** + * ? + * + * @param {} migratorOutput + */ restoreOldVaultAccounts (migratorOutput) { const { serialized } = migratorOutput return this.keyringController.restoreKeyring(serialized) .then(() => migratorOutput) } + /** + * ? + * + * @param {} migratorOutput + */ restoreOldLostAccounts (migratorOutput) { const { lostAccounts } = migratorOutput if (lostAccounts) { @@ -859,10 +952,15 @@ module.exports = class MetamaskController extends EventEmitter { return Promise.resolve(migratorOutput) } - // IMPORT LOST ACCOUNTS - // @Object with key lostAccounts: @Array accounts <{ address, privateKey }> - // Uses the array's private keys to create a new Simple Key Pair keychain - // and add it to the keyring controller. + + /** + * Import (lost) Accounts + * + * @param {Object} {lostAccounts} @Array accounts <{ address, privateKey }> + * + * Uses the array's private keys to create a new Simple Key Pair keychain + * and add it to the keyring controller. + */ importLostAccounts ({ lostAccounts }) { const privKeys = lostAccounts.map(acct => acct.privateKey) return this.keyringController.restoreKeyring({ @@ -871,9 +969,9 @@ module.exports = class MetamaskController extends EventEmitter { }) } - // - // config - // +//============================================================================= +// CONFIG +//============================================================================= // Log blocks -- cgit From 904f00e8acf40a72d233d1776c8aa760026e1bd3 Mon Sep 17 00:00:00 2001 From: Lazaridis Date: Fri, 16 Mar 2018 02:29:53 +0200 Subject: group all vault/keyring related methods together, re #3568 --- app/scripts/metamask-controller.js | 258 +++++++++++++++++++------------------ 1 file changed, 130 insertions(+), 128 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 31c0bed58..cbdf757c6 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -267,7 +267,7 @@ module.exports = class MetamaskController extends EventEmitter { } /** - * Constructor helper: initialize a public confi store. + * Constructor helper: initialize a public config store. */ initPublicConfigStore () { // get init state @@ -290,12 +290,11 @@ module.exports = class MetamaskController extends EventEmitter { return publicConfigStore } - // - // State Management - // /** - * ? + * The metamask-state of the various controllers, made available to the UI + * + * @returns {Object} status */ getState () { const wallet = this.configManager.getWallet() @@ -331,12 +330,10 @@ module.exports = class MetamaskController extends EventEmitter { ) } - // - // Remote Features - // - /** - * ? + * Returns an api-object which is consumed by the UI + * + * @returns {Object} */ getApi () { const keyringController = this.keyringController @@ -656,7 +653,7 @@ module.exports = class MetamaskController extends EventEmitter { /** * Verifies the validity of the current vault's seed phrase. * - * Validity: seed phrase can restore the accounts belonging to the current vault. + * Validity: seed phrase restores the accounts belonging to the current vault. * * Called when the first account is created and on unlocking the vault. */ @@ -722,81 +719,9 @@ module.exports = class MetamaskController extends EventEmitter { .catch((reason) => { cb(reason) }) } -//============================================================================= -// END (VAULT / KEYRING RELATED METHODS) -//============================================================================= - - - -//============================================================================= -// Identity Management -//============================================================================= - - async retryTransaction (txId, cb) { - await this.txController.retryTransaction(txId) - const state = await this.getState() - return state - } - - - newUnsignedMessage (msgParams, cb) { - const msgId = this.messageManager.addUnapprovedMessage(msgParams) - this.sendUpdate() - this.opts.showUnconfirmedMessage() - this.messageManager.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - return cb(null, data.rawSig) - case 'rejected': - return cb(new Error('MetaMask Message Signature: User denied message signature.')) - default: - return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) - } - }) - } - - newUnsignedPersonalMessage (msgParams, cb) { - if (!msgParams.from) { - return cb(new Error('MetaMask Message Signature: from field is required.')) - } - - const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams) - this.sendUpdate() - this.opts.showUnconfirmedMessage() - this.personalMessageManager.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - return cb(null, data.rawSig) - case 'rejected': - return cb(new Error('MetaMask Message Signature: User denied message signature.')) - default: - return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) - } - }) - } - - newUnsignedTypedMessage (msgParams, cb) { - let msgId - try { - msgId = this.typedMessageManager.addUnapprovedMessage(msgParams) - this.sendUpdate() - this.opts.showUnconfirmedMessage() - } catch (e) { - return cb(e) - } + // --------------------------------------------------------------------------- + // Identity Management (sign) - this.typedMessageManager.once(`${msgId}:finished`, (data) => { - switch (data.status) { - case 'signed': - return cb(null, data.rawSig) - case 'rejected': - return cb(new Error('MetaMask Message Signature: User denied message signature.')) - default: - return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) - } - }) - } - /** * @param {} msgParams * @param {} cb @@ -820,14 +745,6 @@ module.exports = class MetamaskController extends EventEmitter { }) } - cancelMessage (msgId, cb) { - const messageManager = this.messageManager - messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) - } - } - // Prefixed Style Message Signing Methods: /** @@ -892,41 +809,10 @@ module.exports = class MetamaskController extends EventEmitter { return this.getState() }) } - - cancelPersonalMessage (msgId, cb) { - const messageManager = this.personalMessageManager - messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) - } - } - - cancelTypedMessage (msgId, cb) { - const messageManager = this.typedMessageManager - messageManager.rejectMsg(msgId) - if (cb && typeof cb === 'function') { - cb(null, this.getState()) - } - } - - markAccountsFound (cb) { - this.configManager.setLostAccounts([]) - this.sendUpdate() - cb(null, this.getState()) - } - - markPasswordForgotten(cb) { - this.configManager.setPasswordForgotten(true) - this.sendUpdate() - cb() - } - - unMarkPasswordForgotten(cb) { - this.configManager.setPasswordForgotten(false) - this.sendUpdate() - cb() - } + // --------------------------------------------------------------------------- + // Account Restauration + /** * ? * @@ -952,7 +838,6 @@ module.exports = class MetamaskController extends EventEmitter { return Promise.resolve(migratorOutput) } - /** * Import (lost) Accounts * @@ -969,6 +854,123 @@ module.exports = class MetamaskController extends EventEmitter { }) } +//============================================================================= +// END (VAULT / KEYRING RELATED METHODS) +//============================================================================= + + + +//============================================================================= +// MESSAGES +//============================================================================= + + async retryTransaction (txId, cb) { + await this.txController.retryTransaction(txId) + const state = await this.getState() + return state + } + + + newUnsignedMessage (msgParams, cb) { + const msgId = this.messageManager.addUnapprovedMessage(msgParams) + this.sendUpdate() + this.opts.showUnconfirmedMessage() + this.messageManager.once(`${msgId}:finished`, (data) => { + switch (data.status) { + case 'signed': + return cb(null, data.rawSig) + case 'rejected': + return cb(new Error('MetaMask Message Signature: User denied message signature.')) + default: + return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + } + }) + } + + newUnsignedPersonalMessage (msgParams, cb) { + if (!msgParams.from) { + return cb(new Error('MetaMask Message Signature: from field is required.')) + } + + const msgId = this.personalMessageManager.addUnapprovedMessage(msgParams) + this.sendUpdate() + this.opts.showUnconfirmedMessage() + this.personalMessageManager.once(`${msgId}:finished`, (data) => { + switch (data.status) { + case 'signed': + return cb(null, data.rawSig) + case 'rejected': + return cb(new Error('MetaMask Message Signature: User denied message signature.')) + default: + return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + } + }) + } + + newUnsignedTypedMessage (msgParams, cb) { + let msgId + try { + msgId = this.typedMessageManager.addUnapprovedMessage(msgParams) + this.sendUpdate() + this.opts.showUnconfirmedMessage() + } catch (e) { + return cb(e) + } + + this.typedMessageManager.once(`${msgId}:finished`, (data) => { + switch (data.status) { + case 'signed': + return cb(null, data.rawSig) + case 'rejected': + return cb(new Error('MetaMask Message Signature: User denied message signature.')) + default: + return cb(new Error(`MetaMask Message Signature: Unknown problem: ${JSON.stringify(msgParams)}`)) + } + }) + } + + cancelMessage (msgId, cb) { + const messageManager = this.messageManager + messageManager.rejectMsg(msgId) + if (cb && typeof cb === 'function') { + cb(null, this.getState()) + } + } + + cancelPersonalMessage (msgId, cb) { + const messageManager = this.personalMessageManager + messageManager.rejectMsg(msgId) + if (cb && typeof cb === 'function') { + cb(null, this.getState()) + } + } + + cancelTypedMessage (msgId, cb) { + const messageManager = this.typedMessageManager + messageManager.rejectMsg(msgId) + if (cb && typeof cb === 'function') { + cb(null, this.getState()) + } + } + + markAccountsFound (cb) { + this.configManager.setLostAccounts([]) + this.sendUpdate() + cb(null, this.getState()) + } + + markPasswordForgotten(cb) { + this.configManager.setPasswordForgotten(true) + this.sendUpdate() + cb() + } + + unMarkPasswordForgotten(cb) { + this.configManager.setPasswordForgotten(false) + this.sendUpdate() + cb() + } + //============================================================================= // CONFIG //============================================================================= -- cgit From bb6af25e20f723942a2b5770a8763bff3b6d6032 Mon Sep 17 00:00:00 2001 From: Lazaridis Date: Fri, 16 Mar 2018 03:22:10 +0200 Subject: add ESLint exceptions for //= and //-, re #3568 --- app/scripts/metamask-controller.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index cbdf757c6..953e22fc7 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -858,11 +858,11 @@ module.exports = class MetamaskController extends EventEmitter { // END (VAULT / KEYRING RELATED METHODS) //============================================================================= +// - -//============================================================================= +//============================================================================= // MESSAGES -//============================================================================= +//============================================================================= async retryTransaction (txId, cb) { await this.txController.retryTransaction(txId) -- cgit From e1d6398b0fed39e579c0383e34236b30d3154295 Mon Sep 17 00:00:00 2001 From: Lazaridis Date: Fri, 16 Mar 2018 18:37:56 +0200 Subject: moves setup-related code towads end of file, re #3568 --- app/scripts/metamask-controller.js | 239 +++++++++++++++++++------------------ 1 file changed, 124 insertions(+), 115 deletions(-) (limited to 'app/scripts') diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js index 953e22fc7..18d71874a 100644 --- a/app/scripts/metamask-controller.js +++ b/app/scripts/metamask-controller.js @@ -290,6 +290,9 @@ module.exports = class MetamaskController extends EventEmitter { return publicConfigStore } +//============================================================================= +// EXPOSED TO THE UI SUBSYSTEM +//============================================================================= /** * The metamask-state of the various controllers, made available to the UI @@ -415,122 +418,7 @@ module.exports = class MetamaskController extends EventEmitter { } } - setupUntrustedCommunication (connectionStream, originDomain) { - // Check if new connection is blacklisted - if (this.blacklistController.checkForPhishing(originDomain)) { - log.debug('MetaMask - sending phishing warning for', originDomain) - this.sendPhishingWarning(connectionStream, originDomain) - return - } - - // setup multiplexing - const mux = setupMultiplex(connectionStream) - // connect features - this.setupProviderConnection(mux.createStream('provider'), originDomain) - this.setupPublicConfig(mux.createStream('publicConfig')) - } - - setupTrustedCommunication (connectionStream, originDomain) { - // setup multiplexing - const mux = setupMultiplex(connectionStream) - // connect features - this.setupControllerConnection(mux.createStream('controller')) - this.setupProviderConnection(mux.createStream('provider'), originDomain) - } - - sendPhishingWarning (connectionStream, hostname) { - const mux = setupMultiplex(connectionStream) - const phishingStream = mux.createStream('phishing') - phishingStream.write({ hostname }) - } - - setupControllerConnection (outStream) { - const api = this.getApi() - const dnode = Dnode(api) - pump( - outStream, - dnode, - outStream, - (err) => { - if (err) log.error(err) - } - ) - dnode.on('remote', (remote) => { - // push updates to popup - const sendUpdate = remote.sendUpdate.bind(remote) - this.on('update', sendUpdate) - }) - } - - setupProviderConnection (outStream, origin) { - // setup json rpc engine stack - const engine = new RpcEngine() - // create filter polyfill middleware - const filterMiddleware = createFilterMiddleware({ - provider: this.provider, - blockTracker: this.provider._blockTracker, - }) - - engine.push(createOriginMiddleware({ origin })) - engine.push(createLoggerMiddleware({ origin })) - engine.push(filterMiddleware) - engine.push(createProviderMiddleware({ provider: this.provider })) - - // setup connection - const providerStream = createEngineStream({ engine }) - pump( - outStream, - providerStream, - outStream, - (err) => { - // cleanup filter polyfill middleware - filterMiddleware.destroy() - if (err) log.error(err) - } - ) - } - - setupPublicConfig (outStream) { - pump( - asStream(this.publicConfigStore), - outStream, - (err) => { - if (err) log.error(err) - } - ) - } - - privateSendUpdate () { - this.emit('update', this.getState()) - } - - getGasPrice () { - const { recentBlocksController } = this - const { recentBlocks } = recentBlocksController.store.getState() - - // Return 1 gwei if no blocks have been observed: - if (recentBlocks.length === 0) { - return '0x' + GWEI_BN.toString(16) - } - - const lowestPrices = recentBlocks.map((block) => { - if (!block.gasPrices || block.gasPrices.length < 1) { - return GWEI_BN - } - return block.gasPrices - .map(hexPrefix => hexPrefix.substr(2)) - .map(hex => new BN(hex, 16)) - .sort((a, b) => { - return a.gt(b) ? 1 : -1 - })[0] - }) - .map(number => number.div(GWEI_BN).toNumber()) - - const percentileNum = percentile(50, lowestPrices) - const percentileNumBn = new BN(percentileNum) - return '0x' + percentileNumBn.mul(GWEI_BN).toString(16) - } //============================================================================= // VAULT / KEYRING RELATED METHODS @@ -971,6 +859,127 @@ module.exports = class MetamaskController extends EventEmitter { cb() } +//============================================================================= +// SETUP +//============================================================================= + + setupUntrustedCommunication (connectionStream, originDomain) { + // Check if new connection is blacklisted + if (this.blacklistController.checkForPhishing(originDomain)) { + log.debug('MetaMask - sending phishing warning for', originDomain) + this.sendPhishingWarning(connectionStream, originDomain) + return + } + + // setup multiplexing + const mux = setupMultiplex(connectionStream) + // connect features + this.setupProviderConnection(mux.createStream('provider'), originDomain) + this.setupPublicConfig(mux.createStream('publicConfig')) + } + + setupTrustedCommunication (connectionStream, originDomain) { + // setup multiplexing + const mux = setupMultiplex(connectionStream) + // connect features + this.setupControllerConnection(mux.createStream('controller')) + this.setupProviderConnection(mux.createStream('provider'), originDomain) + } + + sendPhishingWarning (connectionStream, hostname) { + const mux = setupMultiplex(connectionStream) + const phishingStream = mux.createStream('phishing') + phishingStream.write({ hostname }) + } + + setupControllerConnection (outStream) { + const api = this.getApi() + const dnode = Dnode(api) + pump( + outStream, + dnode, + outStream, + (err) => { + if (err) log.error(err) + } + ) + dnode.on('remote', (remote) => { + // push updates to popup + const sendUpdate = remote.sendUpdate.bind(remote) + this.on('update', sendUpdate) + }) + } + + setupProviderConnection (outStream, origin) { + // setup json rpc engine stack + const engine = new RpcEngine() + + // create filter polyfill middleware + const filterMiddleware = createFilterMiddleware({ + provider: this.provider, + blockTracker: this.provider._blockTracker, + }) + + engine.push(createOriginMiddleware({ origin })) + engine.push(createLoggerMiddleware({ origin })) + engine.push(filterMiddleware) + engine.push(createProviderMiddleware({ provider: this.provider })) + + // setup connection + const providerStream = createEngineStream({ engine }) + pump( + outStream, + providerStream, + outStream, + (err) => { + // cleanup filter polyfill middleware + filterMiddleware.destroy() + if (err) log.error(err) + } + ) + } + + setupPublicConfig (outStream) { + pump( + asStream(this.publicConfigStore), + outStream, + (err) => { + if (err) log.error(err) + } + ) + } + + privateSendUpdate () { + this.emit('update', this.getState()) + } + + getGasPrice () { + const { recentBlocksController } = this + const { recentBlocks } = recentBlocksController.store.getState() + + // Return 1 gwei if no blocks have been observed: + if (recentBlocks.length === 0) { + return '0x' + GWEI_BN.toString(16) + } + + const lowestPrices = recentBlocks.map((block) => { + if (!block.gasPrices || block.gasPrices.length < 1) { + return GWEI_BN + } + return block.gasPrices + .map(hexPrefix => hexPrefix.substr(2)) + .map(hex => new BN(hex, 16)) + .sort((a, b) => { + return a.gt(b) ? 1 : -1 + })[0] + }) + .map(number => number.div(GWEI_BN).toNumber()) + + const percentileNum = percentile(50, lowestPrices) + const percentileNumBn = new BN(percentileNum) + return '0x' + percentileNumBn.mul(GWEI_BN).toString(16) + } + //============================================================================= // CONFIG //============================================================================= -- cgit From 6174c00c1036e77e1dc2ec39f20cf3a2a8518a21 Mon Sep 17 00:00:00 2001 From: Saptak Sengupta Date: Fri, 16 Mar 2018 11:20:34 +0530 Subject: Inject Script: Blacklist domains where not to inject script Put a blacklist domain check where if the page url is in the list of blacklisted domains, we shouldn't inject script in that web page. --- app/scripts/contentscript.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'app/scripts') diff --git a/app/scripts/contentscript.js b/app/scripts/contentscript.js index 2ed7c87b6..7abbc60e7 100644 --- a/app/scripts/contentscript.js +++ b/app/scripts/contentscript.js @@ -96,7 +96,8 @@ function logStreamDisconnectWarning (remoteLabel, err) { } function shouldInjectWeb3 () { - return doctypeCheck() && suffixCheck() && documentElementCheck() + return doctypeCheck() && suffixCheck() + && documentElementCheck() && !blacklistedDomainCheck() } function doctypeCheck () { @@ -129,6 +130,20 @@ function documentElementCheck () { return true } +function blacklistedDomainCheck () { + var blacklistedDomains = ['uscourts.gov', 'dropbox.com'] + var currentUrl = window.location.href + var currentRegex + for (let i = 0; i < blacklistedDomains.length; i++) { + const blacklistedDomain = blacklistedDomains[i].replace('.', '\\.') + currentRegex = new RegExp(`(?:https?:\\/\\/)(?:(?!${blacklistedDomain}).)*$`) + if (!currentRegex.test(currentUrl)) { + return true + } + } + return false +} + function redirectToPhishingWarning () { console.log('MetaMask - redirecting to phishing warning') window.location.href = 'https://metamask.io/phishing.html' -- cgit