mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-28 07:36:44 +00:00
* Adding in Mumbai/Mainnet precursor deb packaging for tests to use during upgrade(iterations to come) * Added changes per discussion in PR, more changes may be necessary * Adding prerelease true * Disabling goreleaser * Removing README swap file * change bor_dir and add bor user for v0.3.0 release * rollback bor user and use root * metrics: handle equal to separated config flag (#596) * metrics: handle based config path * internal/cli/server: add more context to logs * use space separated flag and value in bor.service * fixed static-nodes related buf (os independent) (#598) * fixed static-nodes related buf (os independent) * taking static-nodes as input if default not present * Update default flags (#600) * internal/cli/server: use geth's default for txpool.pricelimit and add comments * builder/files: update config.toml for mainnet * packaging/templates: update defaults for mainnet and mumbai * internal/cli/server: skip overriding cache * packaging/templates: update cache value for mainnet * packaging/templates: update gcmode for archive mumbai node * metrics: handle nil telemetry config (#601) * resolve merge conflicts * update go version in release.yml * update goversion in makefile * update Docker login for goreleaser-cross v1.19 * Cleanup for the packager to use git tag in the package profile naming. Added conditional check for directory structure, this is in prep for v0.3.1, as this will create a failure on upgrade path in package due to file exist * added a toml configuration file with comments describing each flag (#607) * added a toml configuration file with comments describing each flag * internal/cli/server: update flag description * docs/cli: update example config and description of flags * docs: update new-cli docs Co-authored-by: Manav Darji <manavdarji.india@gmail.com> * Adding of 0.3.0 package changes, control file updates, postinst changes, and packager update * added ancient datadir flag and toml field, need to decide on default value and update the conversion script * updated toml files with ancient field * Add support for new flags in new config.toml, which were present in old config.toml (#612) * added HTTPTimeouts, and TrieTimeout flag in new tol, from old toml * added RAW fields for these time.Duration flags * updated the conversion script to support these extra 4 flags * removed hcl and json config tests as we are only supporting toml config files * updated toml files with cache.timeout field * updated toml files with jsonrpc.timeouts field * tests/bor: expect a call for latest checkpoint * tests/bor: expect a call for latest checkpoint * packaging/templates: update cache values for archive nodes Co-authored-by: Manav Darji <manavdarji.india@gmail.com> * remove unwanted code * Fix docker publish authentication issue In gorelease-cross 1.19+, dockerhub authentication will require docker logion action followed by mounting docker config file. See https://github.com/goreleaser/goreleaser-cross#github-actions. * Revert "update Docker login for goreleaser-cross v1.19" This reverts commit4d19cf5342. * Bump version to stable * Revert "Merge pull request #435 from maticnetwork/POS-553" This reverts commit657d262def, reversing changes made to88dbfa1c13. * revert change for release for go1.19 * Add default values to CLI helper and docs This commit adds default values to CLI helper and docs. When the default value of a string flag, slice string flag, or map string flag is empty, its helper message won't show any default value. * Add a summary of new CLI in docs * Updating packager as binutils changed version so that apt-get installs current versions * Add state pruning to new CLI * Minor wording fix in prune state description * Bumping control file versions * Mainnet Delhi fork * Set version to stable * change delhi hardfork block number * handle future chain import and skip peer drop (#650) * handle future chain import and skip peer drop * add block import metric * params: bump version to v0.3.3-stable * Bump bor version in control files for v0.3.3 mainnet release * Added checks to RPC requests and introduced new flags to customise the parameters (#657) * added a check to reject rpc requests with batch size > the one set using a newly added flag (rpcbatchlimit) * added a check to reject rpc requests whose result size > the one set using a newly added flag (rpcreturndatalimit) * updated the config files and docs * chg : trieTimeout from 60 to 10 mins (#692) * chg : trieTimeout from 60 to 10 mins * chg : cache.timout to 10m from 1h in configs * internal/cli/server : fix : added triesInMemory in config (#691) * changed version from 0.3.0 to 0.3.4-beta (#693) * fix nil state-sync issue, increase grpc limit (#695) * Increase grpc message size limit in pprof * consensus/bor/bor.go : stateSyncs init fixed [Fix #686] * eth/filters: handle nil state-sync before notify * eth/filters: update check Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> * core, tests/bor: add more tests for state-sync validation (#710) * core: add get state sync function for tests * tests/bor: add validation for state sync events post consensus * Arpit/temp bor sync (#701) * Increase grpc message size limit in pprof * ReadBorReceipts improvements * use internal function * fix tests * fetch geth upstread for ReadBorReceiptRLP * Only query bor receipt when the query index is equal to # tx in block body This change reduces the frequency of calling ReadBorReceipt and ReadBorTransaction, which are CPU and db intensive. * Revert "fetch geth upstread for ReadBorReceiptRLP" This reverts commit 2e838a6b1313d26674f3a8df4b044e35dcbf35a0. * Restore ReadBorReceiptRLP * fix bor receipts * remove unused * fix lints --------- Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> * Revert "chg : trieTimeout from 60 to 10 mins (#692)" (#720) This reverts commit241843c7e7. * Arpit/add execution pool 2 (#719) * initial * linters * linters * remove timeout * update pool * change pool size function * check nil * check nil * fix tests * Use execution pool from server in all handlers * simplify things * test fix * add support for cli, config * add to cli and config * merge base branch * debug statements * fix bug * atomic pointer timeout * add apis * update workerpool * fix issues * change params * fix issues * fix ipc issue * remove execution pool from IPC * revert * fix tests * mutex * refactor flag and value names * ordering fix * refactor flag and value names * update default ep size to 40 * fix bor start issues * revert file changes * debug statements * fix bug * update workerpool * atomic pointer timeout * add apis * Merge branch 'add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * fix issues * change params * fix issues * fix ipc issue * remove execution pool from IPC * revert * merge base branch * Merge branch 'add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * mutex * fix tests * Merge branch 'arpit/add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * Change default size of execution pool to 40 * refactor flag and value names * fix merge conflicts * ordering fix * refactor flag and value names * update default ep size to 40 * fix bor start issues * revert file changes * fix linters * fix go.mod * change sec to ms * change default value for ep timeout * fix node api calls * comment setter for ep timeout --------- Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> * version change (#721) * Event based pprof (#732) * feature * Save pprof to /tmp --------- Co-authored-by: Jerry <jerrycgh@gmail.com> * Cherry-pick changes from develop (#738) * Check if block is nil to prevent panic (#736) * miner: use env for tracing instead of block object (#728) --------- Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> * add max code init size check in txpool (#739) * Revert "Event based pprof" and update version (#742) * Revert "Event based pprof (#732)" This reverts commit22fa4033e8. * params: update version to 0.3.4-beta3 * packaging/templates: update bor version * internal/ethapi :: Fix : newRPCTransactionFromBlockIndex * Merge master to qa (#813) * Merge qa to master (#750) * Added checks to RPC requests and introduced new flags to customise the parameters (#657) * added a check to reject rpc requests with batch size > the one set using a newly added flag (rpcbatchlimit) * added a check to reject rpc requests whose result size > the one set using a newly added flag (rpcreturndatalimit) * updated the config files and docs * chg : trieTimeout from 60 to 10 mins (#692) * chg : trieTimeout from 60 to 10 mins * chg : cache.timout to 10m from 1h in configs * internal/cli/server : fix : added triesInMemory in config (#691) * changed version from 0.3.0 to 0.3.4-beta (#693) * fix nil state-sync issue, increase grpc limit (#695) * Increase grpc message size limit in pprof * consensus/bor/bor.go : stateSyncs init fixed [Fix #686] * eth/filters: handle nil state-sync before notify * eth/filters: update check Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> * core, tests/bor: add more tests for state-sync validation (#710) * core: add get state sync function for tests * tests/bor: add validation for state sync events post consensus * Arpit/temp bor sync (#701) * Increase grpc message size limit in pprof * ReadBorReceipts improvements * use internal function * fix tests * fetch geth upstread for ReadBorReceiptRLP * Only query bor receipt when the query index is equal to # tx in block body This change reduces the frequency of calling ReadBorReceipt and ReadBorTransaction, which are CPU and db intensive. * Revert "fetch geth upstread for ReadBorReceiptRLP" This reverts commit 2e838a6b1313d26674f3a8df4b044e35dcbf35a0. * Restore ReadBorReceiptRLP * fix bor receipts * remove unused * fix lints --------- Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> * Revert "chg : trieTimeout from 60 to 10 mins (#692)" (#720) This reverts commit241843c7e7. * Arpit/add execution pool 2 (#719) * initial * linters * linters * remove timeout * update pool * change pool size function * check nil * check nil * fix tests * Use execution pool from server in all handlers * simplify things * test fix * add support for cli, config * add to cli and config * merge base branch * debug statements * fix bug * atomic pointer timeout * add apis * update workerpool * fix issues * change params * fix issues * fix ipc issue * remove execution pool from IPC * revert * fix tests * mutex * refactor flag and value names * ordering fix * refactor flag and value names * update default ep size to 40 * fix bor start issues * revert file changes * debug statements * fix bug * update workerpool * atomic pointer timeout * add apis * Merge branch 'add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * fix issues * change params * fix issues * fix ipc issue * remove execution pool from IPC * revert * merge base branch * Merge branch 'add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * mutex * fix tests * Merge branch 'arpit/add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * Change default size of execution pool to 40 * refactor flag and value names * fix merge conflicts * ordering fix * refactor flag and value names * update default ep size to 40 * fix bor start issues * revert file changes * fix linters * fix go.mod * change sec to ms * change default value for ep timeout * fix node api calls * comment setter for ep timeout --------- Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> * version change (#721) * Event based pprof (#732) * feature * Save pprof to /tmp --------- Co-authored-by: Jerry <jerrycgh@gmail.com> * Cherry-pick changes from develop (#738) * Check if block is nil to prevent panic (#736) * miner: use env for tracing instead of block object (#728) --------- Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> * add max code init size check in txpool (#739) * Revert "Event based pprof" and update version (#742) * Revert "Event based pprof (#732)" This reverts commit22fa4033e8. * params: update version to 0.3.4-beta3 * packaging/templates: update bor version * params, packaging/templates: update bor version --------- Co-authored-by: SHIVAM SHARMA <shivam691999@gmail.com> Co-authored-by: Pratik Patil <pratikspatil024@gmail.com> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> Co-authored-by: Arpit Temani <temaniarpit27@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> * core, miner: add sub-spans for tracing (#753) * core, miner: add sub-spans for tracing * fix linters * core: add logs for debugging * core: add more logs to print tdd while reorg * fix linters * core: minor fix * core: remove debug logs * core: use different span for write block and set head * core: use internal context for sending traces (#755) * core: add : impossible reorg block dump (#754) * add : impossible reorg block dump * chg : 3 seperate files for impossoble reorg dump * add : use exportBlocks method and RLP blocks before writing * chg : small changes * bump : go version from 1.19 to 1.20.1 (#761) * Revert "bump : go version from 1.19 to 1.20.1 (#761)" This reverts commit4561012af9. * core/vm: use optimized bigint (#26021) * Add holiman/big * Fix linter * Bump version to v0.3.5 * fix lints from develop (few lints decided to appear from code that was untouched, weird) * upgrade crypto lib version (#770) * bump dep : github.com/Masterminds/goutils to v1.1.1 (#769) * mardizzone/pos-1313: bump crypto dependency (#772) * dev: chg: bumd net dependency * dev: chg: bump crypto dependency * dev: chg: bump crypto dependency * bump dep : golang.org/x/net to v0.8.0 (#771) * Verify validator set against local contract on receiving an end-of-sprint block (#768) * Verify validator set against local contract on receiving an end-of-sprint block * Fix tests * Respect error returned by ParseValidators * Keep going back until a parent block presents * core/txpool: implement DoS defenses from geth (#778) * Hotfixes and deps bump (#776) * dev: chg: bump deps * internal/cli/server, rpc: lower down http readtimeout to 10s * dev: chg: get p2p adapter * dev: chg: lower down jsonrpc readtimeout to 10s * cherry-pick txpool optimisation changes * add check for empty lists in txpool (#704) * add check * linters * core, miner: add empty instrumentation name for tracing --------- Co-authored-by: Raneet Debnath <raneetdebnath10@gmail.com> Co-authored-by: SHIVAM SHARMA <shivam691999@gmail.com> Co-authored-by: Evgeny Danilenko <6655321@bk.ru> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> * packaging,params: bump to v0.3.6 (#782) * v0.3.6 fix (#787) * Fix get validator set in header verifier * chg : commit tx logs from info to debug (#673) * chg : commit tx logs from info to debug * fix : minor changes * chg : miner : commitTransactions-stats moved from info to debug * lint : fix linters * refactor logging * miner : chg : UnauthorizedSignerError to debug * lint : fix lint * fix : log.Logger interface compatibility --------- Co-authored-by: Evgeny Danienko <6655321@bk.ru> * Remove unnecessary sorting of valset from header in verification * dev: chg: version bump --------- Co-authored-by: SHIVAM SHARMA <shivam691999@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: marcello33 <marcelloardizzone@hotmail.it> * core: improve locks in txpool (#807) * added a write lock to the txs.filter method and a read lock to the txs.reheap method - both of which are called by Filter during reorg adjustments to txpool * txpool reorg locks * more locks * locks * linters * params, packaging: update version for v0.3.8-beta release * core: add logs in reheap --------- Co-authored-by: Alex <dalexwatts@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> * Merge qa to master (#808) * Added checks to RPC requests and introduced new flags to customise the parameters (#657) * added a check to reject rpc requests with batch size > the one set using a newly added flag (rpcbatchlimit) * added a check to reject rpc requests whose result size > the one set using a newly added flag (rpcreturndatalimit) * updated the config files and docs * chg : trieTimeout from 60 to 10 mins (#692) * chg : trieTimeout from 60 to 10 mins * chg : cache.timout to 10m from 1h in configs * internal/cli/server : fix : added triesInMemory in config (#691) * changed version from 0.3.0 to 0.3.4-beta (#693) * fix nil state-sync issue, increase grpc limit (#695) * Increase grpc message size limit in pprof * consensus/bor/bor.go : stateSyncs init fixed [Fix #686] * eth/filters: handle nil state-sync before notify * eth/filters: update check Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> * core, tests/bor: add more tests for state-sync validation (#710) * core: add get state sync function for tests * tests/bor: add validation for state sync events post consensus * Arpit/temp bor sync (#701) * Increase grpc message size limit in pprof * ReadBorReceipts improvements * use internal function * fix tests * fetch geth upstread for ReadBorReceiptRLP * Only query bor receipt when the query index is equal to # tx in block body This change reduces the frequency of calling ReadBorReceipt and ReadBorTransaction, which are CPU and db intensive. * Revert "fetch geth upstread for ReadBorReceiptRLP" This reverts commit 2e838a6b1313d26674f3a8df4b044e35dcbf35a0. * Restore ReadBorReceiptRLP * fix bor receipts * remove unused * fix lints --------- Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> * Revert "chg : trieTimeout from 60 to 10 mins (#692)" (#720) This reverts commit241843c7e7. * Arpit/add execution pool 2 (#719) * initial * linters * linters * remove timeout * update pool * change pool size function * check nil * check nil * fix tests * Use execution pool from server in all handlers * simplify things * test fix * add support for cli, config * add to cli and config * merge base branch * debug statements * fix bug * atomic pointer timeout * add apis * update workerpool * fix issues * change params * fix issues * fix ipc issue * remove execution pool from IPC * revert * fix tests * mutex * refactor flag and value names * ordering fix * refactor flag and value names * update default ep size to 40 * fix bor start issues * revert file changes * debug statements * fix bug * update workerpool * atomic pointer timeout * add apis * Merge branch 'add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * fix issues * change params * fix issues * fix ipc issue * remove execution pool from IPC * revert * merge base branch * Merge branch 'add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * mutex * fix tests * Merge branch 'arpit/add-execution-pool' of github.com:maticnetwork/bor into arpit/add-execution-pool * Change default size of execution pool to 40 * refactor flag and value names * fix merge conflicts * ordering fix * refactor flag and value names * update default ep size to 40 * fix bor start issues * revert file changes * fix linters * fix go.mod * change sec to ms * change default value for ep timeout * fix node api calls * comment setter for ep timeout --------- Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Manav Darji <manavdarji.india@gmail.com> * version change (#721) * Event based pprof (#732) * feature * Save pprof to /tmp --------- Co-authored-by: Jerry <jerrycgh@gmail.com> * Cherry-pick changes from develop (#738) * Check if block is nil to prevent panic (#736) * miner: use env for tracing instead of block object (#728) --------- Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> * add max code init size check in txpool (#739) * Revert "Event based pprof" and update version (#742) * Revert "Event based pprof (#732)" This reverts commit22fa4033e8. * params: update version to 0.3.4-beta3 * packaging/templates: update bor version * internal/ethapi :: Fix : newRPCTransactionFromBlockIndex * fix: remove assignment for bor receipt --------- Co-authored-by: SHIVAM SHARMA <shivam691999@gmail.com> Co-authored-by: Pratik Patil <pratikspatil024@gmail.com> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> Co-authored-by: Arpit Temani <temaniarpit27@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> * Setting up bor to use hosted 18.04 runner as ubuntu provided 18.04 runner is end of life --------- Co-authored-by: SHIVAM SHARMA <shivam691999@gmail.com> Co-authored-by: Pratik Patil <pratikspatil024@gmail.com> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> Co-authored-by: Arpit Temani <temaniarpit27@gmail.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: marcello33 <marcelloardizzone@hotmail.it> Co-authored-by: Raneet Debnath <raneetdebnath10@gmail.com> Co-authored-by: Raneet Debnath <35629432+Raneet10@users.noreply.github.com> Co-authored-by: Alex <dalexwatts@gmail.com> Co-authored-by: Daniel Jones <djones@polygon.technology> * core: remove duplicate tests * miner: use get validators by hash in tests --------- Co-authored-by: Daniel Jones <djones@polygon.technology> Co-authored-by: Will Button <wbutton@polygon.technology> Co-authored-by: Will Button <will@willbutton.com> Co-authored-by: Daniel Jones <105369507+djpolygon@users.noreply.github.com> Co-authored-by: Pratik Patil <pratikspatil024@gmail.com> Co-authored-by: Arpit Temani <temaniarpit27@gmail.com> Co-authored-by: Jerry <jerrycgh@gmail.com> Co-authored-by: SHIVAM SHARMA <shivam691999@gmail.com> Co-authored-by: Daniil <daniil.melnik@chainstack.com> Co-authored-by: Evgeny Danienko <6655321@bk.ru> Co-authored-by: Dmitry <46797839+dkeysil@users.noreply.github.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: marcello33 <marcelloardizzone@hotmail.it> Co-authored-by: Raneet Debnath <raneetdebnath10@gmail.com> Co-authored-by: Raneet Debnath <35629432+Raneet10@users.noreply.github.com> Co-authored-by: Alex <dalexwatts@gmail.com>
865 lines
25 KiB
Go
865 lines
25 KiB
Go
// Copyright 2016 The go-ethereum Authors
|
|
// This file is part of the go-ethereum library.
|
|
//
|
|
// The go-ethereum library is free software: you can redistribute it and/or modify
|
|
// it under the terms of the GNU Lesser General Public License as published by
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
// (at your option) any later version.
|
|
//
|
|
// The go-ethereum library is distributed in the hope that it will be useful,
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
// GNU Lesser General Public License for more details.
|
|
//
|
|
// You should have received a copy of the GNU Lesser General Public License
|
|
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
package core
|
|
|
|
import (
|
|
"container/heap"
|
|
"math"
|
|
"math/big"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/holiman/uint256"
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
cmath "github.com/ethereum/go-ethereum/common/math"
|
|
"github.com/ethereum/go-ethereum/core/types"
|
|
"github.com/ethereum/go-ethereum/log"
|
|
)
|
|
|
|
// nonceHeap is a heap.Interface implementation over 64bit unsigned integers for
|
|
// retrieving sorted transactions from the possibly gapped future queue.
|
|
type nonceHeap []uint64
|
|
|
|
func (h nonceHeap) Len() int { return len(h) }
|
|
func (h nonceHeap) Less(i, j int) bool { return h[i] < h[j] }
|
|
func (h nonceHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
|
|
|
func (h *nonceHeap) Push(x interface{}) {
|
|
*h = append(*h, x.(uint64))
|
|
}
|
|
|
|
func (h *nonceHeap) Pop() interface{} {
|
|
old := *h
|
|
n := len(old)
|
|
x := old[n-1]
|
|
*h = old[0 : n-1]
|
|
return x
|
|
}
|
|
|
|
// txSortedMap is a nonce->transaction hash map with a heap based index to allow
|
|
// iterating over the contents in a nonce-incrementing way.
|
|
type txSortedMap struct {
|
|
items map[uint64]*types.Transaction // Hash map storing the transaction data
|
|
index *nonceHeap // Heap of nonces of all the stored transactions (non-strict mode)
|
|
m sync.RWMutex
|
|
|
|
cache types.Transactions // Cache of the transactions already sorted
|
|
isEmpty bool
|
|
cacheMu sync.RWMutex
|
|
}
|
|
|
|
// newTxSortedMap creates a new nonce-sorted transaction map.
|
|
func newTxSortedMap() *txSortedMap {
|
|
return &txSortedMap{
|
|
items: make(map[uint64]*types.Transaction),
|
|
index: new(nonceHeap),
|
|
isEmpty: true,
|
|
}
|
|
}
|
|
|
|
// Get retrieves the current transactions associated with the given nonce.
|
|
func (m *txSortedMap) Get(nonce uint64) *types.Transaction {
|
|
m.m.RLock()
|
|
defer m.m.RUnlock()
|
|
|
|
return m.items[nonce]
|
|
}
|
|
|
|
func (m *txSortedMap) Has(nonce uint64) bool {
|
|
if m == nil {
|
|
return false
|
|
}
|
|
|
|
m.m.RLock()
|
|
defer m.m.RUnlock()
|
|
|
|
return m.items[nonce] != nil
|
|
}
|
|
|
|
// Put inserts a new transaction into the map, also updating the map's nonce
|
|
// index. If a transaction already exists with the same nonce, it's overwritten.
|
|
func (m *txSortedMap) Put(tx *types.Transaction) {
|
|
m.m.Lock()
|
|
defer m.m.Unlock()
|
|
|
|
nonce := tx.Nonce()
|
|
if m.items[nonce] == nil {
|
|
heap.Push(m.index, nonce)
|
|
}
|
|
|
|
m.items[nonce] = tx
|
|
|
|
m.cacheMu.Lock()
|
|
m.isEmpty = true
|
|
m.cache = nil
|
|
m.cacheMu.Unlock()
|
|
}
|
|
|
|
// Forward removes all transactions from the map with a nonce lower than the
|
|
// provided threshold. Every removed transaction is returned for any post-removal
|
|
// maintenance.
|
|
func (m *txSortedMap) Forward(threshold uint64) types.Transactions {
|
|
m.m.Lock()
|
|
defer m.m.Unlock()
|
|
|
|
var removed types.Transactions
|
|
|
|
// Pop off heap items until the threshold is reached
|
|
for m.index.Len() > 0 && (*m.index)[0] < threshold {
|
|
nonce := heap.Pop(m.index).(uint64)
|
|
removed = append(removed, m.items[nonce])
|
|
delete(m.items, nonce)
|
|
}
|
|
|
|
// If we had a cached order, shift the front
|
|
m.cacheMu.Lock()
|
|
if m.cache != nil {
|
|
hitCacheCounter.Inc(1)
|
|
m.cache = m.cache[len(removed):]
|
|
}
|
|
m.cacheMu.Unlock()
|
|
|
|
return removed
|
|
}
|
|
|
|
// Filter iterates over the list of transactions and removes all of them for which
|
|
// the specified function evaluates to true.
|
|
// Filter, as opposed to 'filter', re-initialises the heap after the operation is done.
|
|
// If you want to do several consecutive filterings, it's therefore better to first
|
|
// do a .filter(func1) followed by .Filter(func2) or reheap()
|
|
func (m *txSortedMap) Filter(filter func(*types.Transaction) bool) types.Transactions {
|
|
m.m.Lock()
|
|
defer m.m.Unlock()
|
|
|
|
removed := m.filter(filter)
|
|
// If transactions were removed, the heap and cache are ruined
|
|
if len(removed) > 0 {
|
|
m.reheap(false)
|
|
}
|
|
return removed
|
|
}
|
|
|
|
func (m *txSortedMap) reheap(withRlock bool) {
|
|
index := make(nonceHeap, 0, len(m.items))
|
|
|
|
if withRlock {
|
|
m.m.RLock()
|
|
log.Info("[DEBUG] Acquired lock over txpool map while performing reheap")
|
|
}
|
|
|
|
for nonce := range m.items {
|
|
index = append(index, nonce)
|
|
}
|
|
|
|
if withRlock {
|
|
m.m.RUnlock()
|
|
}
|
|
|
|
heap.Init(&index)
|
|
|
|
if withRlock {
|
|
m.m.Lock()
|
|
}
|
|
|
|
m.index = &index
|
|
|
|
if withRlock {
|
|
m.m.Unlock()
|
|
}
|
|
|
|
m.cacheMu.Lock()
|
|
m.cache = nil
|
|
m.isEmpty = true
|
|
m.cacheMu.Unlock()
|
|
|
|
resetCacheGauge.Inc(1)
|
|
}
|
|
|
|
// filter is identical to Filter, but **does not** regenerate the heap. This method
|
|
// should only be used if followed immediately by a call to Filter or reheap()
|
|
func (m *txSortedMap) filter(filter func(*types.Transaction) bool) types.Transactions {
|
|
var removed types.Transactions
|
|
|
|
// Collect all the transactions to filter out
|
|
for nonce, tx := range m.items {
|
|
if filter(tx) {
|
|
removed = append(removed, tx)
|
|
delete(m.items, nonce)
|
|
}
|
|
}
|
|
if len(removed) > 0 {
|
|
m.cacheMu.Lock()
|
|
m.cache = nil
|
|
m.isEmpty = true
|
|
m.cacheMu.Unlock()
|
|
|
|
resetCacheGauge.Inc(1)
|
|
}
|
|
return removed
|
|
}
|
|
|
|
// Cap places a hard limit on the number of items, returning all transactions
|
|
// exceeding that limit.
|
|
func (m *txSortedMap) Cap(threshold int) types.Transactions {
|
|
m.m.Lock()
|
|
defer m.m.Unlock()
|
|
|
|
// Short circuit if the number of items is under the limit
|
|
if len(m.items) <= threshold {
|
|
return nil
|
|
}
|
|
|
|
// Otherwise gather and drop the highest nonce'd transactions
|
|
var drops types.Transactions
|
|
|
|
sort.Sort(*m.index)
|
|
|
|
for size := len(m.items); size > threshold; size-- {
|
|
drops = append(drops, m.items[(*m.index)[size-1]])
|
|
delete(m.items, (*m.index)[size-1])
|
|
}
|
|
|
|
*m.index = (*m.index)[:threshold]
|
|
heap.Init(m.index)
|
|
|
|
// If we had a cache, shift the back
|
|
m.cacheMu.Lock()
|
|
if m.cache != nil {
|
|
m.cache = m.cache[:len(m.cache)-len(drops)]
|
|
}
|
|
m.cacheMu.Unlock()
|
|
|
|
return drops
|
|
}
|
|
|
|
// Remove deletes a transaction from the maintained map, returning whether the
|
|
// transaction was found.
|
|
func (m *txSortedMap) Remove(nonce uint64) bool {
|
|
m.m.Lock()
|
|
defer m.m.Unlock()
|
|
|
|
// Short circuit if no transaction is present
|
|
_, ok := m.items[nonce]
|
|
if !ok {
|
|
return false
|
|
}
|
|
|
|
// Otherwise delete the transaction and fix the heap index
|
|
for i := 0; i < m.index.Len(); i++ {
|
|
if (*m.index)[i] == nonce {
|
|
heap.Remove(m.index, i)
|
|
|
|
break
|
|
}
|
|
}
|
|
|
|
delete(m.items, nonce)
|
|
|
|
m.cacheMu.Lock()
|
|
m.cache = nil
|
|
m.isEmpty = true
|
|
m.cacheMu.Unlock()
|
|
|
|
resetCacheGauge.Inc(1)
|
|
|
|
return true
|
|
}
|
|
|
|
// Ready retrieves a sequentially increasing list of transactions starting at the
|
|
// provided nonce that is ready for processing. The returned transactions will be
|
|
// removed from the list.
|
|
//
|
|
// Note, all transactions with nonces lower than start will also be returned to
|
|
// prevent getting into and invalid state. This is not something that should ever
|
|
// happen but better to be self correcting than failing!
|
|
func (m *txSortedMap) Ready(start uint64) types.Transactions {
|
|
m.m.Lock()
|
|
defer m.m.Unlock()
|
|
|
|
// Short circuit if no transactions are available
|
|
if m.index.Len() == 0 || (*m.index)[0] > start {
|
|
return nil
|
|
}
|
|
|
|
// Otherwise start accumulating incremental transactions
|
|
var ready types.Transactions
|
|
|
|
for next := (*m.index)[0]; m.index.Len() > 0 && (*m.index)[0] == next; next++ {
|
|
ready = append(ready, m.items[next])
|
|
delete(m.items, next)
|
|
heap.Pop(m.index)
|
|
}
|
|
|
|
m.cacheMu.Lock()
|
|
m.cache = nil
|
|
m.isEmpty = true
|
|
m.cacheMu.Unlock()
|
|
|
|
resetCacheGauge.Inc(1)
|
|
|
|
return ready
|
|
}
|
|
|
|
// Len returns the length of the transaction map.
|
|
func (m *txSortedMap) Len() int {
|
|
m.m.RLock()
|
|
defer m.m.RUnlock()
|
|
|
|
return len(m.items)
|
|
}
|
|
|
|
func (m *txSortedMap) flatten() types.Transactions {
|
|
// If the sorting was not cached yet, create and cache it
|
|
m.cacheMu.Lock()
|
|
defer m.cacheMu.Unlock()
|
|
|
|
if m.isEmpty {
|
|
m.isEmpty = false // to simulate sync.Once
|
|
|
|
m.cacheMu.Unlock()
|
|
|
|
m.m.RLock()
|
|
|
|
cache := make(types.Transactions, 0, len(m.items))
|
|
|
|
for _, tx := range m.items {
|
|
cache = append(cache, tx)
|
|
}
|
|
|
|
m.m.RUnlock()
|
|
|
|
// exclude sorting from locks
|
|
sort.Sort(types.TxByNonce(cache))
|
|
|
|
m.cacheMu.Lock()
|
|
m.cache = cache
|
|
|
|
reinitCacheGauge.Inc(1)
|
|
missCacheCounter.Inc(1)
|
|
} else {
|
|
hitCacheCounter.Inc(1)
|
|
}
|
|
|
|
return m.cache
|
|
}
|
|
|
|
func (m *txSortedMap) lastElement() *types.Transaction {
|
|
// If the sorting was not cached yet, create and cache it
|
|
m.cacheMu.Lock()
|
|
defer m.cacheMu.Unlock()
|
|
|
|
cache := m.cache
|
|
|
|
if m.isEmpty {
|
|
m.isEmpty = false // to simulate sync.Once
|
|
|
|
m.cacheMu.Unlock()
|
|
|
|
m.m.RLock()
|
|
cache = make(types.Transactions, 0, len(m.items))
|
|
|
|
for _, tx := range m.items {
|
|
cache = append(cache, tx)
|
|
}
|
|
|
|
m.m.RUnlock()
|
|
|
|
// exclude sorting from locks
|
|
sort.Sort(types.TxByNonce(cache))
|
|
|
|
m.cacheMu.Lock()
|
|
m.cache = cache
|
|
|
|
reinitCacheGauge.Inc(1)
|
|
missCacheCounter.Inc(1)
|
|
} else {
|
|
hitCacheCounter.Inc(1)
|
|
}
|
|
|
|
ln := len(cache)
|
|
if ln == 0 {
|
|
return nil
|
|
}
|
|
|
|
return cache[len(cache)-1]
|
|
}
|
|
|
|
// Flatten creates a nonce-sorted slice of transactions based on the loosely
|
|
// sorted internal representation. The result of the sorting is cached in case
|
|
// it's requested again before any modifications are made to the contents.
|
|
func (m *txSortedMap) Flatten() types.Transactions {
|
|
// Copy the cache to prevent accidental modifications
|
|
return m.flatten()
|
|
}
|
|
|
|
// LastElement returns the last element of a flattened list, thus, the
|
|
// transaction with the highest nonce
|
|
func (m *txSortedMap) LastElement() *types.Transaction {
|
|
return m.lastElement()
|
|
}
|
|
|
|
// txList is a "list" of transactions belonging to an account, sorted by account
|
|
// nonce. The same type can be used both for storing contiguous transactions for
|
|
// the executable/pending queue; and for storing gapped transactions for the non-
|
|
// executable/future queue, with minor behavioral changes.
|
|
type txList struct {
|
|
strict bool // Whether nonces are strictly continuous or not
|
|
txs *txSortedMap // Heap indexed sorted hash map of the transactions
|
|
|
|
costcap *uint256.Int // Price of the highest costing transaction (reset only if exceeds balance)
|
|
gascap uint64 // Gas limit of the highest spending transaction (reset only if exceeds block limit)
|
|
totalcost *big.Int // Total cost of all transactions in the list
|
|
}
|
|
|
|
// newTxList create a new transaction list for maintaining nonce-indexable fast,
|
|
// gapped, sortable transaction lists.
|
|
func newTxList(strict bool) *txList {
|
|
return &txList{
|
|
strict: strict,
|
|
txs: newTxSortedMap(),
|
|
totalcost: new(big.Int),
|
|
}
|
|
}
|
|
|
|
// Overlaps returns whether the transaction specified has the same nonce as one
|
|
// already contained within the list.
|
|
func (l *txList) Overlaps(tx *types.Transaction) bool {
|
|
return l.txs.Get(tx.Nonce()) != nil
|
|
}
|
|
|
|
// Add tries to insert a new transaction into the list, returning whether the
|
|
// transaction was accepted, and if yes, any previous transaction it replaced.
|
|
//
|
|
// If the new transaction is accepted into the list, the lists' cost and gas
|
|
// thresholds are also potentially updated.
|
|
func (l *txList) Add(tx *types.Transaction, priceBump uint64) (bool, *types.Transaction) {
|
|
// If there's an older better transaction, abort
|
|
old := l.txs.Get(tx.Nonce())
|
|
if old != nil {
|
|
if old.GasFeeCapCmp(tx) >= 0 || old.GasTipCapCmp(tx) >= 0 {
|
|
return false, nil
|
|
}
|
|
|
|
// thresholdFeeCap = oldFC * (100 + priceBump) / 100
|
|
a := uint256.NewInt(100 + priceBump)
|
|
aFeeCap := uint256.NewInt(0).Mul(a, old.GasFeeCapUint())
|
|
aTip := a.Mul(a, old.GasTipCapUint())
|
|
|
|
// thresholdTip = oldTip * (100 + priceBump) / 100
|
|
b := cmath.U100
|
|
thresholdFeeCap := aFeeCap.Div(aFeeCap, b)
|
|
thresholdTip := aTip.Div(aTip, b)
|
|
|
|
// We have to ensure that both the new fee cap and tip are higher than the
|
|
// old ones as well as checking the percentage threshold to ensure that
|
|
// this is accurate for low (Wei-level) gas price replacements.
|
|
if tx.GasFeeCapUIntLt(thresholdFeeCap) || tx.GasTipCapUIntLt(thresholdTip) {
|
|
return false, nil
|
|
}
|
|
// Old is being replaced, subtract old cost
|
|
l.subTotalCost([]*types.Transaction{old})
|
|
}
|
|
|
|
// Add new tx cost to totalcost
|
|
l.totalcost.Add(l.totalcost, tx.Cost())
|
|
|
|
// Otherwise overwrite the old transaction with the current one
|
|
l.txs.Put(tx)
|
|
|
|
if cost := tx.CostUint(); l.costcap == nil || l.costcap.Lt(cost) {
|
|
l.costcap = cost
|
|
}
|
|
|
|
if gas := tx.Gas(); l.gascap < gas {
|
|
l.gascap = gas
|
|
}
|
|
|
|
return true, old
|
|
}
|
|
|
|
// Forward removes all transactions from the list with a nonce lower than the
|
|
// provided threshold. Every removed transaction is returned for any post-removal
|
|
// maintenance.
|
|
func (l *txList) Forward(threshold uint64) types.Transactions {
|
|
txs := l.txs.Forward(threshold)
|
|
l.subTotalCost(txs)
|
|
|
|
return txs
|
|
}
|
|
|
|
// Filter removes all transactions from the list with a cost or gas limit higher
|
|
// than the provided thresholds. Every removed transaction is returned for any
|
|
// post-removal maintenance. Strict-mode invalidated transactions are also
|
|
// returned.
|
|
//
|
|
// This method uses the cached costcap and gascap to quickly decide if there's even
|
|
// a point in calculating all the costs or if the balance covers all. If the threshold
|
|
// is lower than the costgas cap, the caps will be reset to a new high after removing
|
|
// the newly invalidated transactions.
|
|
func (l *txList) Filter(costLimit *uint256.Int, gasLimit uint64) (types.Transactions, types.Transactions) {
|
|
// If all transactions are below the threshold, short circuit
|
|
if cmath.U256LTE(l.costcap, costLimit) && l.gascap <= gasLimit {
|
|
return nil, nil
|
|
}
|
|
|
|
l.costcap = costLimit.Clone() // Lower the caps to the thresholds
|
|
l.gascap = gasLimit
|
|
|
|
// Filter out all the transactions above the account's funds
|
|
cost := uint256.NewInt(0)
|
|
removed := l.txs.Filter(func(tx *types.Transaction) bool {
|
|
cost.SetFromBig(tx.Cost())
|
|
return tx.Gas() > gasLimit || cost.Gt(costLimit)
|
|
})
|
|
|
|
if len(removed) == 0 {
|
|
return nil, nil
|
|
}
|
|
var invalids types.Transactions
|
|
// If the list was strict, filter anything above the lowest nonce
|
|
if l.strict {
|
|
lowest := uint64(math.MaxUint64)
|
|
for _, tx := range removed {
|
|
if nonce := tx.Nonce(); lowest > nonce {
|
|
lowest = nonce
|
|
}
|
|
}
|
|
|
|
l.txs.m.Lock()
|
|
invalids = l.txs.filter(func(tx *types.Transaction) bool { return tx.Nonce() > lowest })
|
|
l.txs.m.Unlock()
|
|
}
|
|
// Reset total cost
|
|
l.subTotalCost(removed)
|
|
l.subTotalCost(invalids)
|
|
|
|
l.txs.reheap(true)
|
|
|
|
return removed, invalids
|
|
}
|
|
|
|
// Cap places a hard limit on the number of items, returning all transactions
|
|
// exceeding that limit.
|
|
func (l *txList) Cap(threshold int) types.Transactions {
|
|
txs := l.txs.Cap(threshold)
|
|
l.subTotalCost(txs)
|
|
|
|
return txs
|
|
}
|
|
|
|
// Remove deletes a transaction from the maintained list, returning whether the
|
|
// transaction was found, and also returning any transaction invalidated due to
|
|
// the deletion (strict mode only).
|
|
func (l *txList) Remove(tx *types.Transaction) (bool, types.Transactions) {
|
|
// Remove the transaction from the set
|
|
nonce := tx.Nonce()
|
|
if removed := l.txs.Remove(nonce); !removed {
|
|
return false, nil
|
|
}
|
|
|
|
l.subTotalCost([]*types.Transaction{tx})
|
|
// In strict mode, filter out non-executable transactions
|
|
if l.strict {
|
|
txs := l.txs.Filter(func(tx *types.Transaction) bool { return tx.Nonce() > nonce })
|
|
l.subTotalCost(txs)
|
|
|
|
return true, txs
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
// Ready retrieves a sequentially increasing list of transactions starting at the
|
|
// provided nonce that is ready for processing. The returned transactions will be
|
|
// removed from the list.
|
|
//
|
|
// Note, all transactions with nonces lower than start will also be returned to
|
|
// prevent getting into and invalid state. This is not something that should ever
|
|
// happen but better to be self correcting than failing!
|
|
func (l *txList) Ready(start uint64) types.Transactions {
|
|
txs := l.txs.Ready(start)
|
|
l.subTotalCost(txs)
|
|
|
|
return txs
|
|
}
|
|
|
|
// Len returns the length of the transaction list.
|
|
func (l *txList) Len() int {
|
|
return l.txs.Len()
|
|
}
|
|
|
|
// Empty returns whether the list of transactions is empty or not.
|
|
func (l *txList) Empty() bool {
|
|
return l.Len() == 0
|
|
}
|
|
|
|
// Flatten creates a nonce-sorted slice of transactions based on the loosely
|
|
// sorted internal representation. The result of the sorting is cached in case
|
|
// it's requested again before any modifications are made to the contents.
|
|
func (l *txList) Flatten() types.Transactions {
|
|
return l.txs.Flatten()
|
|
}
|
|
|
|
// LastElement returns the last element of a flattened list, thus, the
|
|
// transaction with the highest nonce
|
|
func (l *txList) LastElement() *types.Transaction {
|
|
return l.txs.LastElement()
|
|
}
|
|
|
|
func (l *txList) Has(nonce uint64) bool {
|
|
return l != nil && l.txs.items[nonce] != nil
|
|
}
|
|
|
|
// subTotalCost subtracts the cost of the given transactions from the
|
|
// total cost of all transactions.
|
|
func (l *txList) subTotalCost(txs []*types.Transaction) {
|
|
for _, tx := range txs {
|
|
l.totalcost.Sub(l.totalcost, tx.Cost())
|
|
}
|
|
}
|
|
|
|
// priceHeap is a heap.Interface implementation over transactions for retrieving
|
|
// price-sorted transactions to discard when the pool fills up. If baseFee is set
|
|
// then the heap is sorted based on the effective tip based on the given base fee.
|
|
// If baseFee is nil then the sorting is based on gasFeeCap.
|
|
type priceHeap struct {
|
|
baseFee *uint256.Int // heap should always be re-sorted after baseFee is changed
|
|
list []*types.Transaction
|
|
baseFeeMu sync.RWMutex
|
|
}
|
|
|
|
func (h *priceHeap) Len() int { return len(h.list) }
|
|
func (h *priceHeap) Swap(i, j int) { h.list[i], h.list[j] = h.list[j], h.list[i] }
|
|
|
|
func (h *priceHeap) Less(i, j int) bool {
|
|
switch h.cmp(h.list[i], h.list[j]) {
|
|
case -1:
|
|
return true
|
|
case 1:
|
|
return false
|
|
default:
|
|
return h.list[i].Nonce() > h.list[j].Nonce()
|
|
}
|
|
}
|
|
|
|
func (h *priceHeap) cmp(a, b *types.Transaction) int {
|
|
h.baseFeeMu.RLock()
|
|
|
|
if h.baseFee != nil {
|
|
// Compare effective tips if baseFee is specified
|
|
if c := a.EffectiveGasTipTxUintCmp(b, h.baseFee); c != 0 {
|
|
h.baseFeeMu.RUnlock()
|
|
|
|
return c
|
|
}
|
|
}
|
|
|
|
h.baseFeeMu.RUnlock()
|
|
|
|
// Compare fee caps if baseFee is not specified or effective tips are equal
|
|
if c := a.GasFeeCapCmp(b); c != 0 {
|
|
return c
|
|
}
|
|
|
|
// Compare tips if effective tips and fee caps are equal
|
|
return a.GasTipCapCmp(b)
|
|
}
|
|
|
|
func (h *priceHeap) Push(x interface{}) {
|
|
tx := x.(*types.Transaction)
|
|
h.list = append(h.list, tx)
|
|
}
|
|
|
|
func (h *priceHeap) Pop() interface{} {
|
|
old := h.list
|
|
n := len(old)
|
|
x := old[n-1]
|
|
old[n-1] = nil
|
|
h.list = old[0 : n-1]
|
|
return x
|
|
}
|
|
|
|
// txPricedList is a price-sorted heap to allow operating on transactions pool
|
|
// contents in a price-incrementing way. It's built opon the all transactions
|
|
// in txpool but only interested in the remote part. It means only remote transactions
|
|
// will be considered for tracking, sorting, eviction, etc.
|
|
//
|
|
// Two heaps are used for sorting: the urgent heap (based on effective tip in the next
|
|
// block) and the floating heap (based on gasFeeCap). Always the bigger heap is chosen for
|
|
// eviction. Transactions evicted from the urgent heap are first demoted into the floating heap.
|
|
// In some cases (during a congestion, when blocks are full) the urgent heap can provide
|
|
// better candidates for inclusion while in other cases (at the top of the baseFee peak)
|
|
// the floating heap is better. When baseFee is decreasing they behave similarly.
|
|
type txPricedList struct {
|
|
// Number of stale price points to (re-heap trigger).
|
|
// This field is accessed atomically, and must be the first field
|
|
// to ensure it has correct alignment for atomic.AddInt64.
|
|
// See https://golang.org/pkg/sync/atomic/#pkg-note-BUG.
|
|
stales int64
|
|
|
|
all *txLookup // Pointer to the map of all transactions
|
|
urgent, floating priceHeap // Heaps of prices of all the stored **remote** transactions
|
|
reheapMu sync.Mutex // Mutex asserts that only one routine is reheaping the list
|
|
}
|
|
|
|
const (
|
|
// urgentRatio : floatingRatio is the capacity ratio of the two queues
|
|
urgentRatio = 4
|
|
floatingRatio = 1
|
|
)
|
|
|
|
// newTxPricedList creates a new price-sorted transaction heap.
|
|
func newTxPricedList(all *txLookup) *txPricedList {
|
|
return &txPricedList{
|
|
all: all,
|
|
}
|
|
}
|
|
|
|
// Put inserts a new transaction into the heap.
|
|
func (l *txPricedList) Put(tx *types.Transaction, local bool) {
|
|
if local {
|
|
return
|
|
}
|
|
// Insert every new transaction to the urgent heap first; Discard will balance the heaps
|
|
heap.Push(&l.urgent, tx)
|
|
}
|
|
|
|
// Removed notifies the prices transaction list that an old transaction dropped
|
|
// from the pool. The list will just keep a counter of stale objects and update
|
|
// the heap if a large enough ratio of transactions go stale.
|
|
func (l *txPricedList) Removed(count int) {
|
|
// Bump the stale counter, but exit if still too low (< 25%)
|
|
stales := atomic.AddInt64(&l.stales, int64(count))
|
|
if int(stales) <= (len(l.urgent.list)+len(l.floating.list))/4 {
|
|
return
|
|
}
|
|
// Seems we've reached a critical number of stale transactions, reheap
|
|
l.Reheap()
|
|
}
|
|
|
|
// Underpriced checks whether a transaction is cheaper than (or as cheap as) the
|
|
// lowest priced (remote) transaction currently being tracked.
|
|
func (l *txPricedList) Underpriced(tx *types.Transaction) bool {
|
|
// Note: with two queues, being underpriced is defined as being worse than the worst item
|
|
// in all non-empty queues if there is any. If both queues are empty then nothing is underpriced.
|
|
return (l.underpricedFor(&l.urgent, tx) || len(l.urgent.list) == 0) &&
|
|
(l.underpricedFor(&l.floating, tx) || len(l.floating.list) == 0) &&
|
|
(len(l.urgent.list) != 0 || len(l.floating.list) != 0)
|
|
}
|
|
|
|
// underpricedFor checks whether a transaction is cheaper than (or as cheap as) the
|
|
// lowest priced (remote) transaction in the given heap.
|
|
func (l *txPricedList) underpricedFor(h *priceHeap, tx *types.Transaction) bool {
|
|
// Discard stale price points if found at the heap start
|
|
for len(h.list) > 0 {
|
|
head := h.list[0]
|
|
if l.all.GetRemote(head.Hash()) == nil { // Removed or migrated
|
|
atomic.AddInt64(&l.stales, -1)
|
|
heap.Pop(h)
|
|
continue
|
|
}
|
|
break
|
|
}
|
|
// Check if the transaction is underpriced or not
|
|
if len(h.list) == 0 {
|
|
return false // There is no remote transaction at all.
|
|
}
|
|
// If the remote transaction is even cheaper than the
|
|
// cheapest one tracked locally, reject it.
|
|
return h.cmp(h.list[0], tx) >= 0
|
|
}
|
|
|
|
// Discard finds a number of most underpriced transactions, removes them from the
|
|
// priced list and returns them for further removal from the entire pool.
|
|
//
|
|
// Note local transaction won't be considered for eviction.
|
|
func (l *txPricedList) Discard(slots int, force bool) (types.Transactions, bool) {
|
|
drop := make(types.Transactions, 0, slots) // Remote underpriced transactions to drop
|
|
for slots > 0 {
|
|
if len(l.urgent.list)*floatingRatio > len(l.floating.list)*urgentRatio || floatingRatio == 0 {
|
|
// Discard stale transactions if found during cleanup
|
|
tx := heap.Pop(&l.urgent).(*types.Transaction)
|
|
if l.all.GetRemote(tx.Hash()) == nil { // Removed or migrated
|
|
atomic.AddInt64(&l.stales, -1)
|
|
continue
|
|
}
|
|
// Non stale transaction found, move to floating heap
|
|
heap.Push(&l.floating, tx)
|
|
} else {
|
|
if len(l.floating.list) == 0 {
|
|
// Stop if both heaps are empty
|
|
break
|
|
}
|
|
// Discard stale transactions if found during cleanup
|
|
tx := heap.Pop(&l.floating).(*types.Transaction)
|
|
if l.all.GetRemote(tx.Hash()) == nil { // Removed or migrated
|
|
atomic.AddInt64(&l.stales, -1)
|
|
continue
|
|
}
|
|
// Non stale transaction found, discard it
|
|
drop = append(drop, tx)
|
|
slots -= numSlots(tx)
|
|
}
|
|
}
|
|
// If we still can't make enough room for the new transaction
|
|
if slots > 0 && !force {
|
|
for _, tx := range drop {
|
|
heap.Push(&l.urgent, tx)
|
|
}
|
|
return nil, false
|
|
}
|
|
return drop, true
|
|
}
|
|
|
|
// Reheap forcibly rebuilds the heap based on the current remote transaction set.
|
|
func (l *txPricedList) Reheap() {
|
|
l.reheapMu.Lock()
|
|
defer l.reheapMu.Unlock()
|
|
start := time.Now()
|
|
atomic.StoreInt64(&l.stales, 0)
|
|
l.urgent.list = make([]*types.Transaction, 0, l.all.RemoteCount())
|
|
l.all.Range(func(hash common.Hash, tx *types.Transaction, local bool) bool {
|
|
l.urgent.list = append(l.urgent.list, tx)
|
|
return true
|
|
}, false, true) // Only iterate remotes
|
|
heap.Init(&l.urgent)
|
|
|
|
// balance out the two heaps by moving the worse half of transactions into the
|
|
// floating heap
|
|
// Note: Discard would also do this before the first eviction but Reheap can do
|
|
// is more efficiently. Also, Underpriced would work suboptimally the first time
|
|
// if the floating queue was empty.
|
|
floatingCount := len(l.urgent.list) * floatingRatio / (urgentRatio + floatingRatio)
|
|
l.floating.list = make([]*types.Transaction, floatingCount)
|
|
for i := 0; i < floatingCount; i++ {
|
|
l.floating.list[i] = heap.Pop(&l.urgent).(*types.Transaction)
|
|
}
|
|
heap.Init(&l.floating)
|
|
reheapTimer.Update(time.Since(start))
|
|
}
|
|
|
|
// SetBaseFee updates the base fee and triggers a re-heap. Note that Removed is not
|
|
// necessary to call right before SetBaseFee when processing a new block.
|
|
func (l *txPricedList) SetBaseFee(baseFee *uint256.Int) {
|
|
l.urgent.baseFeeMu.Lock()
|
|
l.urgent.baseFee = baseFee
|
|
l.urgent.baseFeeMu.Unlock()
|
|
|
|
l.Reheap()
|
|
}
|