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

162 lines
5.6 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, blockTracker, getPendingTransactions, getConfirmedTransactions }) {
this.provider = provider
this.blockTracker = blockTracker
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} highestSuggested - 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)
try {
// evaluate multiple nextNonce strategies
const nonceDetails = {}
const networkNonceResult = await this._getNetworkNextNonce(address)
const highestLocallyConfirmed = this._getHighestLocallyConfirmed(address)
const nextNetworkNonce = networkNonceResult.nonce
const highestSuggested = Math.max(nextNetworkNonce, highestLocallyConfirmed)
2017-08-24 05:11:37 +02:00
const pendingTxs = this.getPendingTransactions(address)
const localNonceResult = this._getHighestContinuousFrom(pendingTxs, highestSuggested) || 0
nonceDetails.params = {
highestLocallyConfirmed,
highestSuggested,
nextNetworkNonce,
}
nonceDetails.local = localNonceResult
nonceDetails.network = networkNonceResult
2017-08-24 06:14:46 +02:00
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 }
} catch (err) {
// release lock if we encounter an error
releaseLock()
throw err
}
2017-06-15 07:16:14 +02:00
}
async _globalMutexFree () {
const globalMutex = this._lookupMutex('global')
const releaseLock = await globalMutex.acquire()
releaseLock()
}
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 blockNumber = await this.blockTracker.getLatestBlock()
const baseCountBN = await this.ethQuery.getTransactionCount(address, blockNumber)
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
}
_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 } }
}
2017-06-15 07:16:14 +02:00
}
module.exports = NonceTracker