aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--app/scripts/controllers/transactions.js80
-rw-r--r--app/scripts/lib/nonce-tracker.js57
-rw-r--r--app/scripts/metamask-controller.js2
-rw-r--r--package.json1
-rw-r--r--test/unit/nonce-tracker-test.js40
-rw-r--r--test/unit/tx-controller-test.js24
6 files changed, 150 insertions, 54 deletions
diff --git a/app/scripts/controllers/transactions.js b/app/scripts/controllers/transactions.js
index f6dea34e7..651565519 100644
--- a/app/scripts/controllers/transactions.js
+++ b/app/scripts/controllers/transactions.js
@@ -4,9 +4,10 @@ const extend = require('xtend')
const Semaphore = require('semaphore')
const ObservableStore = require('obs-store')
const ethUtil = require('ethereumjs-util')
+const denodeify = require('denodeify')
const TxProviderUtil = require('../lib/tx-utils')
const createId = require('../lib/random-id')
-const denodeify = require('denodeify')
+const NonceTracker = require('../lib/nonce-tracker')
const RETRY_LIMIT = 200
@@ -22,6 +23,11 @@ module.exports = class TransactionController extends EventEmitter {
this.txHistoryLimit = opts.txHistoryLimit
this.provider = opts.provider
this.blockTracker = opts.blockTracker
+ this.nonceTracker = new NonceTracker({
+ provider: this.provider,
+ blockTracker: this.provider._blockTracker,
+ getPendingTransactions: (address) => this.getFilteredTxList({ from: address, status: 'submitted' }),
+ })
this.query = opts.ethQuery
this.txProviderUtils = new TxProviderUtil(this.query)
this.blockTracker.on('rawBlock', this.checkForTxInBlock.bind(this))
@@ -170,29 +176,33 @@ module.exports = class TransactionController extends EventEmitter {
}, {})
}
- approveTransaction (txId, cb = warn) {
- const self = this
- // approve
- self.setTxStatusApproved(txId)
- // only allow one tx at a time for atomic nonce usage
- self.nonceLock.take(() => {
- // begin signature process
- async.waterfall([
- (cb) => self.fillInTxParams(txId, cb),
- (cb) => self.signTransaction(txId, cb),
- (rawTx, cb) => self.publishTransaction(txId, rawTx, cb),
- ], (err) => {
- self.nonceLock.leave()
- if (err) {
- this.setTxStatusFailed(txId, {
- errCode: err.errCode || err,
- message: err.message || 'Transaction failed during approval',
- })
- return cb(err)
- }
- cb()
+ async approveTransaction (txId, cb = warn) {
+ let nonceLock
+ try {
+ // approve
+ this.setTxStatusApproved(txId)
+ // get next nonce
+ const txMeta = this.getTx(txId)
+ const fromAddress = txMeta.txParams.from
+ nonceLock = await this.nonceTracker.getNonceLock(fromAddress)
+ txMeta.txParams.nonce = nonceLock.nextNonce
+ this.updateTx(txMeta)
+ // sign transaction
+ const rawTx = await denodeify(this.signTransaction.bind(this))(txId)
+ await this.publishTransaction(txId, rawTx)
+ // must set transaction to submitted/failed before releasing lock
+ nonceLock.releaseLock()
+ cb()
+ } catch (err) {
+ this.setTxStatusFailed(txId, {
+ errCode: err.errCode || err,
+ message: err.message || 'Transaction failed during approval',
})
- })
+ // must set transaction to submitted/failed before releasing lock
+ if (nonceLock) nonceLock.releaseLock()
+ // continue with error chain
+ cb(err)
+ }
}
cancelTransaction (txId, cb = warn) {
@@ -200,15 +210,6 @@ module.exports = class TransactionController extends EventEmitter {
cb()
}
- fillInTxParams (txId, cb) {
- const txMeta = this.getTx(txId)
- this.txProviderUtils.fillInTxParams(txMeta.txParams, (err) => {
- if (err) return cb(err)
- this.updateTx(txMeta)
- cb()
- })
- }
-
getChainId () {
const networkState = this.networkStore.getState()
const getChainId = parseInt(networkState)
@@ -234,16 +235,17 @@ module.exports = class TransactionController extends EventEmitter {
})
}
- publishTransaction (txId, rawTx, cb = warn) {
+ publishTransaction (txId, rawTx) {
const txMeta = this.getTx(txId)
txMeta.rawTx = rawTx
this.updateTx(txMeta)
-
- this.txProviderUtils.publishTransaction(rawTx, (err, txHash) => {
- if (err) return cb(err)
- this.setTxHash(txId, txHash)
- this.setTxStatusSubmitted(txId)
- cb()
+ return new Promise((resolve, reject) => {
+ this.txProviderUtils.publishTransaction(rawTx, (err, txHash) => {
+ if (err) reject(err)
+ this.setTxHash(txId, txHash)
+ this.setTxStatusSubmitted(txId)
+ resolve()
+ })
})
}
diff --git a/app/scripts/lib/nonce-tracker.js b/app/scripts/lib/nonce-tracker.js
new file mode 100644
index 000000000..4ea511dec
--- /dev/null
+++ b/app/scripts/lib/nonce-tracker.js
@@ -0,0 +1,57 @@
+const EthQuery = require('eth-query')
+
+class NonceTracker {
+
+ constructor ({ blockTracker, provider, getPendingTransactions }) {
+ this.blockTracker = blockTracker
+ this.ethQuery = new EthQuery(provider)
+ this.getPendingTransactions = getPendingTransactions
+ this.lockMap = {}
+ }
+
+ // releaseLock must be called
+ // releaseLock must be called after adding signed tx to pending transactions (or discarding)
+ async getNonceLock (address) {
+ // await lock free
+ await this.lockMap[address]
+ // take lock
+ const releaseLock = this._takeLock(address)
+ // calculate next nonce
+ const currentBlock = await this._getCurrentBlock()
+ const blockNumber = currentBlock.number
+ const pendingTransactions = this.getPendingTransactions(address)
+ const baseCount = await this._getTxCount(address, blockNumber)
+ const nextNonce = parseInt(baseCount) + pendingTransactions.length
+ // return next nonce and release cb
+ return { nextNonce: nextNonce.toString(16), releaseLock }
+ }
+
+ async _getCurrentBlock () {
+ const currentBlock = this.blockTracker.getCurrentBlock()
+ if (currentBlock) return currentBlock
+ return await Promise((reject, resolve) => {
+ this.blockTracker.once('latest', resolve)
+ })
+ }
+
+ _takeLock (lockId) {
+ let releaseLock = null
+ // create and store lock
+ const lock = new Promise((resolve, reject) => { releaseLock = resolve })
+ this.lockMap[lockId] = lock
+ // setup lock teardown
+ lock.then(() => delete this.lockMap[lockId])
+ return releaseLock
+ }
+
+ _getTxCount (address, blockNumber) {
+ return new Promise((resolve, reject) => {
+ this.ethQuery.getTransactionCount(address, blockNumber, (err, result) => {
+ err ? reject(err) : resolve(result)
+ })
+ })
+ }
+
+}
+
+module.exports = NonceTracker
diff --git a/app/scripts/metamask-controller.js b/app/scripts/metamask-controller.js
index 1a83c70f5..be64a45c7 100644
--- a/app/scripts/metamask-controller.js
+++ b/app/scripts/metamask-controller.js
@@ -309,7 +309,7 @@ module.exports = class MetamaskController extends EventEmitter {
exportAccount: nodeify(keyringController.exportAccount).bind(keyringController),
// txController
- approveTransaction: txController.approveTransaction.bind(txController),
+ approveTransaction: nodeify(txController.approveTransaction).bind(txController),
cancelTransaction: txController.cancelTransaction.bind(txController),
updateAndApproveTransaction: this.updateAndApproveTx.bind(this),
diff --git a/package.json b/package.json
index 3f62923f8..82792351d 100644
--- a/package.json
+++ b/package.json
@@ -10,6 +10,7 @@
"dist": "npm install && gulp dist",
"test": "npm run lint && npm run test-unit && npm run test-integration",
"test-unit": "METAMASK_ENV=test mocha --require test/helper.js --recursive \"test/unit/**/*.js\"",
+ "single-test": "METAMASK_ENV=test mocha --require test/helper.js",
"test-integration": "npm run buildMock && npm run buildCiUnits && testem ci -P 2",
"lint": "gulp lint",
"buildCiUnits": "node test/integration/index.js",
diff --git a/test/unit/nonce-tracker-test.js b/test/unit/nonce-tracker-test.js
new file mode 100644
index 000000000..16cd6d008
--- /dev/null
+++ b/test/unit/nonce-tracker-test.js
@@ -0,0 +1,40 @@
+const assert = require('assert')
+const NonceTracker = require('../../app/scripts/lib/nonce-tracker')
+
+describe('Nonce Tracker', function () {
+ let nonceTracker, provider, getPendingTransactions, pendingTxs
+
+
+ beforeEach(function () {
+ pendingTxs = [{
+ 'status': 'submitted',
+ 'txParams': {
+ 'from': '0x7d3517b0d011698406d6e0aed8453f0be2697926',
+ 'gas': '0x30d40',
+ 'value': '0x0',
+ 'nonce': '0x0',
+ },
+ }]
+
+
+ getPendingTransactions = () => pendingTxs
+ provider = { sendAsync: (_, cb) => { cb(undefined, {result: '0x0'}) } }
+ nonceTracker = new NonceTracker({
+ blockTracker: {
+ getCurrentBlock: () => '0x11b568',
+ },
+ provider,
+ getPendingTransactions,
+ })
+ })
+
+ describe('#getNonceLock', function () {
+ it('should work', async function (done) {
+ this.timeout(15000)
+ const nonceLock = await nonceTracker.getNonceLock('0x7d3517b0d011698406d6e0aed8453f0be2697926')
+ assert.equal(nonceLock.nextNonce, '1', 'nonce should be 1')
+ await nonceLock.releaseLock()
+ done()
+ })
+ })
+})
diff --git a/test/unit/tx-controller-test.js b/test/unit/tx-controller-test.js
index 0d35cd62c..8ce6a5a65 100644
--- a/test/unit/tx-controller-test.js
+++ b/test/unit/tx-controller-test.js
@@ -1,5 +1,4 @@
const assert = require('assert')
-const EventEmitter = require('events')
const ethUtil = require('ethereumjs-util')
const EthTx = require('ethereumjs-tx')
const EthQuery = require('eth-query')
@@ -19,14 +18,15 @@ describe('Transaction Controller', function () {
txController = new TransactionController({
networkStore: new ObservableStore(currentNetworkId),
txHistoryLimit: 10,
- provider: { _blockTracker: new EventEmitter()},
- blockTracker: new EventEmitter(),
- ethQuery: new EthQuery(new EventEmitter()),
+ blockTracker: { getCurrentBlock: noop, on: noop },
+ provider: { sendAsync: noop },
+ ethQuery: new EthQuery({ sendAsync: noop }),
signTransaction: (ethTx) => new Promise((resolve) => {
ethTx.sign(privKey)
resolve()
}),
})
+ txController.nonceTracker.getNonceLock = () => Promise.resolve({ nextNonce: 0, releaseLock: noop })
})
describe('#validateTxParams', function () {
@@ -270,26 +270,25 @@ describe('Transaction Controller', function () {
it('does not overwrite set values', function (done) {
+ this.timeout(15000)
const wrongValue = '0x05'
txController.addTx(txMeta)
const estimateStub = sinon.stub(txController.txProviderUtils.query, 'estimateGas')
- .callsArgWith(1, null, wrongValue)
+ .callsArgWithAsync(1, null, wrongValue)
const priceStub = sinon.stub(txController.txProviderUtils.query, 'gasPrice')
- .callsArgWith(0, null, wrongValue)
+ .callsArgWithAsync(0, null, wrongValue)
- const nonceStub = sinon.stub(txController.txProviderUtils.query, 'getTransactionCount')
- .callsArgWith(2, null, wrongValue)
const signStub = sinon.stub(txController, 'signTransaction')
- .callsArgWith(1, null, noop)
+ .callsArgWithAsync(1, null, noop)
const pubStub = sinon.stub(txController.txProviderUtils, 'publishTransaction')
- .callsArgWith(1, null, originalValue)
+ .callsArgWithAsync(1, null, originalValue)
- txController.approveTransaction(txMeta.id, (err) => {
+ txController.approveTransaction(txMeta.id).then((err) => {
assert.ifError(err, 'should not error')
const result = txController.getTx(txMeta.id)
@@ -297,15 +296,12 @@ describe('Transaction Controller', function () {
assert.equal(params.gas, originalValue, 'gas unmodified')
assert.equal(params.gasPrice, originalValue, 'gas price unmodified')
- assert.equal(params.nonce, originalValue, 'nonce unmodified')
assert.equal(result.hash, originalValue, 'hash was set')
estimateStub.restore()
priceStub.restore()
signStub.restore()
- nonceStub.restore()
pubStub.restore()
-
done()
})
})