1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-04 23:14:56 +01:00
metamask-extension/app/scripts/controllers/transactions/nonce-tracker.js

187 lines
6.4 KiB
JavaScript
Raw Normal View History

2017-08-22 23:33:54 +02:00
const EthQuery = require('ethjs-query')
const assert = require('assert')
const Mutex = require('await-semaphore').Mutex
2018-04-19 20:29:26 +02:00
/**
2018-04-25 20:13:51 +02:00
@param opts {Object}
@param {Object} opts.provider a ethereum provider
@param {Function} opts.getPendingTransactions a function that returns an array of txMeta
whosee status is `submitted`
2018-04-25 20:13:51 +02:00
@param {Function} opts.getConfirmedTransactions a function that returns an array of txMeta
whose status is `confirmed`
2018-04-19 20:29:26 +02:00
@class
*/
2017-06-15 07:16:14 +02:00
class NonceTracker {
constructor ({ provider, getPendingTransactions, getConfirmedTransactions }) {
this.provider = provider
2017-06-15 07:16:14 +02:00
this.ethQuery = new EthQuery(provider)
this.getPendingTransactions = getPendingTransactions
this.getConfirmedTransactions = getConfirmedTransactions
2017-06-15 07:16:14 +02:00
this.lockMap = {}
}
2018-04-19 20:29:26 +02:00
/**
@returns {Promise<Object>} with the key releaseLock (the gloabl mutex)
2018-04-19 20:29:26 +02:00
*/
async getGlobalLock () {
const globalMutex = this._lookupMutex('global')
// await global mutex free
const releaseLock = await globalMutex.acquire()
return { releaseLock }
}
2018-04-19 20:29:26 +02:00
/**
* @typedef NonceDetails
* @property {number} highestLocallyConfirmed - A hex string of the highest nonce on a confirmed transaction.
* @property {number} nextNetworkNonce - The next nonce suggested by the eth_getTransactionCount method.
* @property {number} highetSuggested - The maximum between the other two, the number returned.
*/
2018-04-19 20:29:26 +02:00
/**
this will return an object with the `nextNonce` `nonceDetails` of type NonceDetails, and the releaseLock
Note: releaseLock must be called after adding a signed tx to pending transactions (or discarding).
@param address {string} the hex string for the address whose nonce we are calculating
2018-04-25 20:13:51 +02:00
@returns {Promise<NonceDetails>}
2018-04-19 20:29:26 +02:00
*/
2017-06-22 04:51:00 +02:00
async getNonceLock (address) {
// await global mutex free
await this._globalMutexFree()
// await lock free, then take lock
const releaseLock = await this._takeMutex(address)
// evaluate multiple nextNonce strategies
const nonceDetails = {}
const networkNonceResult = await this._getNetworkNextNonce(address)
const highestLocallyConfirmed = this._getHighestLocallyConfirmed(address)
2017-08-24 05:31:03 +02:00
const nextNetworkNonce = networkNonceResult.nonce
const highestSuggested = Math.max(nextNetworkNonce, highestLocallyConfirmed)
2017-08-24 05:11:37 +02:00
const pendingTxs = this.getPendingTransactions(address)
2017-08-24 05:31:03 +02:00
const localNonceResult = this._getHighestContinuousFrom(pendingTxs, highestSuggested) || 0
2017-08-24 06:14:46 +02:00
nonceDetails.params = {
highestLocallyConfirmed,
2017-08-24 06:14:46 +02:00
highestSuggested,
nextNetworkNonce,
}
nonceDetails.local = localNonceResult
nonceDetails.network = networkNonceResult
const nextNonce = Math.max(networkNonceResult.nonce, localNonceResult.nonce)
assert(Number.isInteger(nextNonce), `nonce-tracker - nextNonce is not an integer - got: (${typeof nextNonce}) "${nextNonce}"`)
// return nonce and release cb
return { nextNonce, nonceDetails, releaseLock }
2017-06-15 07:16:14 +02:00
}
2017-06-22 04:51:00 +02:00
async _getCurrentBlock () {
const blockTracker = this._getBlockTracker()
const currentBlock = blockTracker.getCurrentBlock()
2017-06-15 07:16:14 +02:00
if (currentBlock) return currentBlock
2018-02-16 00:32:48 +01:00
return await new Promise((reject, resolve) => {
blockTracker.once('latest', resolve)
2017-06-15 07:16:14 +02:00
})
}
async _globalMutexFree () {
const globalMutex = this._lookupMutex('global')
const release = await globalMutex.acquire()
release()
}
async _takeMutex (lockId) {
const mutex = this._lookupMutex(lockId)
const releaseLock = await mutex.acquire()
2017-06-15 07:16:14 +02:00
return releaseLock
}
_lookupMutex (lockId) {
let mutex = this.lockMap[lockId]
if (!mutex) {
mutex = new Mutex()
this.lockMap[lockId] = mutex
}
return mutex
2017-06-22 02:28:19 +02:00
}
async _getNetworkNextNonce (address) {
2017-08-19 01:05:21 +02:00
// calculate next nonce
// we need to make sure our base count
// and pending count are from the same block
const currentBlock = await this._getCurrentBlock()
const blockNumber = currentBlock.blockNumber
const baseCountBN = await this.ethQuery.getTransactionCount(address, blockNumber || 'latest')
2017-08-24 06:37:07 +02:00
const baseCount = baseCountBN.toNumber()
2017-08-19 01:05:21 +02:00
assert(Number.isInteger(baseCount), `nonce-tracker - baseCount is not an integer - got: (${typeof baseCount}) "${baseCount}"`)
const nonceDetails = { blockNumber, baseCount }
return { name: 'network', nonce: baseCount, details: nonceDetails }
2017-08-19 01:05:21 +02:00
}
2017-08-19 00:44:32 +02:00
_getHighestLocallyConfirmed (address) {
const confirmedTransactions = this.getConfirmedTransactions(address)
const highest = this._getHighestNonce(confirmedTransactions)
2017-08-24 05:31:03 +02:00
return Number.isInteger(highest) ? highest + 1 : 0
2017-08-22 02:04:47 +02:00
}
_reduceTxListToUniqueNonces (txList) {
const reducedTxList = txList.reduce((reducedList, txMeta, index) => {
if (!index) return [txMeta]
const nonceMatches = txList.filter((txData) => {
return txMeta.txParams.nonce === txData.txParams.nonce
})
if (nonceMatches.length > 1) return reducedList
reducedList.push(txMeta)
return reducedList
}, [])
return reducedTxList
}
_getHighestNonce (txList) {
2017-08-24 06:50:28 +02:00
const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce
assert(typeof nonce, 'string', 'nonces should be hex strings')
return parseInt(nonce, 16)
})
const highestNonce = Math.max.apply(null, nonces)
return highestNonce
2017-08-22 02:04:47 +02:00
}
2018-04-25 20:13:51 +02:00
/**
@typedef {object} highestContinuousFrom
@property {string} - name the name for how the nonce was calculated based on the data used
@property {number} - nonce the next suggested nonce
@property {object} - details the provided starting nonce that was used (for debugging)
*/
/**
@param txList {array} - list of txMeta's
@param startPoint {number} - the highest known locally confirmed nonce
@returns {highestContinuousFrom}
*/
_getHighestContinuousFrom (txList, startPoint) {
2017-08-24 06:50:28 +02:00
const nonces = txList.map((txMeta) => {
const nonce = txMeta.txParams.nonce
assert(typeof nonce, 'string', 'nonces should be hex strings')
return parseInt(nonce, 16)
})
let highest = startPoint
2017-08-24 05:31:03 +02:00
while (nonces.includes(highest)) {
highest++
}
2017-08-24 05:31:03 +02:00
return { name: 'local', nonce: highest, details: { startPoint, highest } }
}
// this is a hotfix for the fact that the blockTracker will
// change when the network changes
2018-04-25 20:13:51 +02:00
/**
@returns {Object} the current blockTracker
*/
_getBlockTracker () {
return this.provider._blockTracker
}
2017-06-15 07:16:14 +02:00
}
module.exports = NonceTracker