tx_pool.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "errors"
  19. "math"
  20. "math/big"
  21. "sort"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/common/prque"
  26. "github.com/ethereum/go-ethereum/core/mps"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/metrics"
  32. "github.com/ethereum/go-ethereum/params"
  33. pcore "github.com/ethereum/go-ethereum/permission/core"
  34. "github.com/ethereum/go-ethereum/private"
  35. )
  36. const (
  37. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  38. chainHeadChanSize = 10
  39. // txSlotSize is used to calculate how many data slots a single transaction
  40. // takes up based on its size. The slots are used as DoS protection, ensuring
  41. // that validating a new transaction remains a constant operation (in reality
  42. // O(maxslots), where max slots are 4 currently).
  43. txSlotSize = 32 * 1024
  44. // txMaxSize is the maximum size a single transaction can have. This field has
  45. // non-trivial consequences: larger transactions are significantly harder and
  46. // more expensive to propagate; larger transactions also take more resources
  47. // to validate whether they fit into the pool or not.
  48. // txMaxSize = 4 * txSlotSize // 128KB
  49. // Quorum - value above is not used. instead, ChainConfig.TransactionSizeLimit is used
  50. )
  51. var (
  52. // ErrAlreadyKnown is returned if the transactions is already contained
  53. // within the pool.
  54. ErrAlreadyKnown = errors.New("already known")
  55. // ErrInvalidSender is returned if the transaction contains an invalid signature.
  56. ErrInvalidSender = errors.New("invalid sender")
  57. // ErrUnderpriced is returned if a transaction's gas price is below the minimum
  58. // configured for the transaction pool.
  59. ErrUnderpriced = errors.New("transaction underpriced")
  60. // ErrTxPoolOverflow is returned if the transaction pool is full and can't accpet
  61. // another remote transaction.
  62. ErrTxPoolOverflow = errors.New("txpool is full")
  63. // ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
  64. // with a different one without the required price bump.
  65. ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")
  66. // ErrGasLimit is returned if a transaction's requested gas limit exceeds the
  67. // maximum allowance of the current block.
  68. ErrGasLimit = errors.New("exceeds block gas limit")
  69. // ErrNegativeValue is a sanity error to ensure no one is able to specify a
  70. // transaction with a negative value.
  71. ErrNegativeValue = errors.New("negative value")
  72. // ErrOversizedData is returned if the input data of a transaction is greater
  73. // than some meaningful limit a user might use. This is not a consensus error
  74. // making the transaction invalid, rather a DOS protection.
  75. ErrOversizedData = errors.New("oversized data")
  76. // ErrInvalidGasPrice is returned if gas price is disabled, but a gas price
  77. // is specified in the transaction
  78. ErrInvalidGasPrice = errors.New("Gas price not 0")
  79. // ErrEtherValueUnsupported is returned if a transaction specifies an Ether Value
  80. // for a private Quorum transaction.
  81. ErrEtherValueUnsupported = errors.New("ether value is not supported for private transactions")
  82. )
  83. var (
  84. evictionInterval = time.Minute // Time interval to check for evictable transactions
  85. statsReportInterval = 8 * time.Second // Time interval to report transaction pool stats
  86. )
  87. var (
  88. // Metrics for the pending pool
  89. pendingDiscardMeter = metrics.NewRegisteredMeter("txpool/pending/discard", nil)
  90. pendingReplaceMeter = metrics.NewRegisteredMeter("txpool/pending/replace", nil)
  91. pendingRateLimitMeter = metrics.NewRegisteredMeter("txpool/pending/ratelimit", nil) // Dropped due to rate limiting
  92. pendingNofundsMeter = metrics.NewRegisteredMeter("txpool/pending/nofunds", nil) // Dropped due to out-of-funds
  93. // Metrics for the queued pool
  94. queuedDiscardMeter = metrics.NewRegisteredMeter("txpool/queued/discard", nil)
  95. queuedReplaceMeter = metrics.NewRegisteredMeter("txpool/queued/replace", nil)
  96. queuedRateLimitMeter = metrics.NewRegisteredMeter("txpool/queued/ratelimit", nil) // Dropped due to rate limiting
  97. queuedNofundsMeter = metrics.NewRegisteredMeter("txpool/queued/nofunds", nil) // Dropped due to out-of-funds
  98. queuedEvictionMeter = metrics.NewRegisteredMeter("txpool/queued/eviction", nil) // Dropped due to lifetime
  99. // General tx metrics
  100. knownTxMeter = metrics.NewRegisteredMeter("txpool/known", nil)
  101. validTxMeter = metrics.NewRegisteredMeter("txpool/valid", nil)
  102. invalidTxMeter = metrics.NewRegisteredMeter("txpool/invalid", nil)
  103. underpricedTxMeter = metrics.NewRegisteredMeter("txpool/underpriced", nil)
  104. overflowedTxMeter = metrics.NewRegisteredMeter("txpool/overflowed", nil)
  105. pendingGauge = metrics.NewRegisteredGauge("txpool/pending", nil)
  106. queuedGauge = metrics.NewRegisteredGauge("txpool/queued", nil)
  107. localGauge = metrics.NewRegisteredGauge("txpool/local", nil)
  108. slotsGauge = metrics.NewRegisteredGauge("txpool/slots", nil)
  109. )
  110. // TxStatus is the current status of a transaction as seen by the pool.
  111. type TxStatus uint
  112. const (
  113. TxStatusUnknown TxStatus = iota
  114. TxStatusQueued
  115. TxStatusPending
  116. TxStatusIncluded
  117. )
  118. // blockChain provides the state of blockchain and current gas limit to do
  119. // some pre checks in tx pool and event subscribers.
  120. type blockChain interface {
  121. CurrentBlock() *types.Block
  122. GetBlock(hash common.Hash, number uint64) *types.Block
  123. StateAt(root common.Hash) (*state.StateDB, mps.PrivateStateRepository, error)
  124. SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
  125. }
  126. // TxPoolConfig are the configuration parameters of the transaction pool.
  127. type TxPoolConfig struct {
  128. Locals []common.Address // Addresses that should be treated by default as local
  129. NoLocals bool // Whether local transaction handling should be disabled
  130. Journal string // Journal of local transactions to survive node restarts
  131. Rejournal time.Duration // Time interval to regenerate the local transaction journal
  132. PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
  133. PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)
  134. AccountSlots uint64 // Number of executable transaction slots guaranteed per account
  135. GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts
  136. AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
  137. GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts
  138. Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
  139. }
  140. // DefaultTxPoolConfig contains the default configurations for the transaction
  141. // pool.
  142. var DefaultTxPoolConfig = TxPoolConfig{
  143. Journal: "transactions.rlp",
  144. Rejournal: time.Hour,
  145. PriceLimit: 1,
  146. PriceBump: 10,
  147. AccountSlots: 16,
  148. GlobalSlots: 4096,
  149. AccountQueue: 64,
  150. GlobalQueue: 1024,
  151. Lifetime: 3 * time.Hour,
  152. }
  153. // sanitize checks the provided user configurations and changes anything that's
  154. // unreasonable or unworkable.
  155. func (config *TxPoolConfig) sanitize() TxPoolConfig {
  156. conf := *config
  157. if conf.Rejournal < time.Second {
  158. log.Warn("Sanitizing invalid txpool journal time", "provided", conf.Rejournal, "updated", time.Second)
  159. conf.Rejournal = time.Second
  160. }
  161. if conf.PriceLimit < 1 {
  162. log.Warn("Sanitizing invalid txpool price limit", "provided", conf.PriceLimit, "updated", DefaultTxPoolConfig.PriceLimit)
  163. conf.PriceLimit = DefaultTxPoolConfig.PriceLimit
  164. }
  165. if conf.PriceBump < 1 {
  166. log.Warn("Sanitizing invalid txpool price bump", "provided", conf.PriceBump, "updated", DefaultTxPoolConfig.PriceBump)
  167. conf.PriceBump = DefaultTxPoolConfig.PriceBump
  168. }
  169. if conf.AccountSlots < 1 {
  170. log.Warn("Sanitizing invalid txpool account slots", "provided", conf.AccountSlots, "updated", DefaultTxPoolConfig.AccountSlots)
  171. conf.AccountSlots = DefaultTxPoolConfig.AccountSlots
  172. }
  173. if conf.GlobalSlots < 1 {
  174. log.Warn("Sanitizing invalid txpool global slots", "provided", conf.GlobalSlots, "updated", DefaultTxPoolConfig.GlobalSlots)
  175. conf.GlobalSlots = DefaultTxPoolConfig.GlobalSlots
  176. }
  177. if conf.AccountQueue < 1 {
  178. log.Warn("Sanitizing invalid txpool account queue", "provided", conf.AccountQueue, "updated", DefaultTxPoolConfig.AccountQueue)
  179. conf.AccountQueue = DefaultTxPoolConfig.AccountQueue
  180. }
  181. if conf.GlobalQueue < 1 {
  182. log.Warn("Sanitizing invalid txpool global queue", "provided", conf.GlobalQueue, "updated", DefaultTxPoolConfig.GlobalQueue)
  183. conf.GlobalQueue = DefaultTxPoolConfig.GlobalQueue
  184. }
  185. if conf.Lifetime < 1 {
  186. log.Warn("Sanitizing invalid txpool lifetime", "provided", conf.Lifetime, "updated", DefaultTxPoolConfig.Lifetime)
  187. conf.Lifetime = DefaultTxPoolConfig.Lifetime
  188. }
  189. return conf
  190. }
  191. // TxPool contains all currently known transactions. Transactions
  192. // enter the pool when they are received from the network or submitted
  193. // locally. They exit the pool when they are included in the blockchain.
  194. //
  195. // The pool separates processable transactions (which can be applied to the
  196. // current state) and future transactions. Transactions move between those
  197. // two states over time as they are received and processed.
  198. type TxPool struct {
  199. config TxPoolConfig
  200. chainconfig *params.ChainConfig
  201. chain blockChain
  202. gasPrice *big.Int
  203. txFeed event.Feed
  204. scope event.SubscriptionScope
  205. signer types.Signer
  206. mu sync.RWMutex
  207. istanbul bool // Fork indicator whether we are in the istanbul stage.
  208. eip2718 bool // Fork indicator whether we are using EIP-2718 type transactions.
  209. currentState *state.StateDB // Current state in the blockchain head
  210. pendingNonces *txNoncer // Pending state tracking virtual nonces
  211. currentMaxGas uint64 // Current gas limit for transaction caps
  212. locals *accountSet // Set of local transaction to exempt from eviction rules
  213. journal *txJournal // Journal of local transaction to back up to disk
  214. pending map[common.Address]*txList // All currently processable transactions
  215. queue map[common.Address]*txList // Queued but non-processable transactions
  216. beats map[common.Address]time.Time // Last heartbeat from each known account
  217. all *txLookup // All transactions to allow lookups
  218. priced *txPricedList // All transactions sorted by price
  219. chainHeadCh chan ChainHeadEvent
  220. chainHeadSub event.Subscription
  221. reqResetCh chan *txpoolResetRequest
  222. reqPromoteCh chan *accountSet
  223. queueTxEventCh chan *types.Transaction
  224. reorgDoneCh chan chan struct{}
  225. reorgShutdownCh chan struct{} // requests shutdown of scheduleReorgLoop
  226. wg sync.WaitGroup // tracks loop, scheduleReorgLoop
  227. }
  228. type txpoolResetRequest struct {
  229. oldHead, newHead *types.Header
  230. }
  231. // NewTxPool creates a new transaction pool to gather, sort and filter inbound
  232. // transactions from the network.
  233. func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool {
  234. // Sanitize the input to ensure no vulnerable gas prices are set
  235. config = (&config).sanitize()
  236. // Create the transaction pool with its initial settings
  237. pool := &TxPool{
  238. config: config,
  239. chainconfig: chainconfig,
  240. chain: chain,
  241. signer: types.LatestSigner(chainconfig),
  242. pending: make(map[common.Address]*txList),
  243. queue: make(map[common.Address]*txList),
  244. beats: make(map[common.Address]time.Time),
  245. all: newTxLookup(),
  246. chainHeadCh: make(chan ChainHeadEvent, chainHeadChanSize),
  247. reqResetCh: make(chan *txpoolResetRequest),
  248. reqPromoteCh: make(chan *accountSet),
  249. queueTxEventCh: make(chan *types.Transaction),
  250. reorgDoneCh: make(chan chan struct{}),
  251. reorgShutdownCh: make(chan struct{}),
  252. gasPrice: new(big.Int).SetUint64(config.PriceLimit),
  253. }
  254. pool.locals = newAccountSet(pool.signer)
  255. for _, addr := range config.Locals {
  256. log.Info("Setting new local account", "address", addr)
  257. pool.locals.add(addr)
  258. }
  259. pool.priced = newTxPricedList(pool.all)
  260. pool.reset(nil, chain.CurrentBlock().Header())
  261. // Start the reorg loop early so it can handle requests generated during journal loading.
  262. pool.wg.Add(1)
  263. go pool.scheduleReorgLoop()
  264. // If local transactions and journaling is enabled, load from disk
  265. if !config.NoLocals && config.Journal != "" {
  266. pool.journal = newTxJournal(config.Journal)
  267. if err := pool.journal.load(pool.AddLocals); err != nil {
  268. log.Warn("Failed to load transaction journal", "err", err)
  269. }
  270. if err := pool.journal.rotate(pool.local()); err != nil {
  271. log.Warn("Failed to rotate transaction journal", "err", err)
  272. }
  273. }
  274. // Subscribe events from blockchain and start the main event loop.
  275. pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh)
  276. pool.wg.Add(1)
  277. go pool.loop()
  278. return pool
  279. }
  280. // loop is the transaction pool's main event loop, waiting for and reacting to
  281. // outside blockchain events as well as for various reporting and transaction
  282. // eviction events.
  283. func (pool *TxPool) loop() {
  284. defer pool.wg.Done()
  285. var (
  286. prevPending, prevQueued, prevStales int
  287. // Start the stats reporting and transaction eviction tickers
  288. report = time.NewTicker(statsReportInterval)
  289. evict = time.NewTicker(evictionInterval)
  290. journal = time.NewTicker(pool.config.Rejournal)
  291. // Track the previous head headers for transaction reorgs
  292. head = pool.chain.CurrentBlock()
  293. )
  294. defer report.Stop()
  295. defer evict.Stop()
  296. defer journal.Stop()
  297. for {
  298. select {
  299. // Handle ChainHeadEvent
  300. case ev := <-pool.chainHeadCh:
  301. if ev.Block != nil {
  302. pool.requestReset(head.Header(), ev.Block.Header())
  303. head = ev.Block
  304. }
  305. // System shutdown.
  306. case <-pool.chainHeadSub.Err():
  307. close(pool.reorgShutdownCh)
  308. return
  309. // Handle stats reporting ticks
  310. case <-report.C:
  311. pool.mu.RLock()
  312. pending, queued := pool.stats()
  313. stales := pool.priced.stales
  314. pool.mu.RUnlock()
  315. if pending != prevPending || queued != prevQueued || stales != prevStales {
  316. log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales)
  317. prevPending, prevQueued, prevStales = pending, queued, stales
  318. }
  319. // Handle inactive account transaction eviction
  320. case <-evict.C:
  321. pool.mu.Lock()
  322. for addr := range pool.queue {
  323. // Skip local transactions from the eviction mechanism
  324. if pool.locals.contains(addr) {
  325. continue
  326. }
  327. // Any non-locals old enough should be removed
  328. if time.Since(pool.beats[addr]) > pool.config.Lifetime {
  329. list := pool.queue[addr].Flatten()
  330. for _, tx := range list {
  331. pool.removeTx(tx.Hash(), true)
  332. }
  333. queuedEvictionMeter.Mark(int64(len(list)))
  334. }
  335. }
  336. pool.mu.Unlock()
  337. // Handle local transaction journal rotation
  338. case <-journal.C:
  339. if pool.journal != nil {
  340. pool.mu.Lock()
  341. if err := pool.journal.rotate(pool.local()); err != nil {
  342. log.Warn("Failed to rotate local tx journal", "err", err)
  343. }
  344. pool.mu.Unlock()
  345. }
  346. }
  347. }
  348. }
  349. // Stop terminates the transaction pool.
  350. func (pool *TxPool) Stop() {
  351. // Unsubscribe all subscriptions registered from txpool
  352. pool.scope.Close()
  353. // Unsubscribe subscriptions registered from blockchain
  354. pool.chainHeadSub.Unsubscribe()
  355. pool.wg.Wait()
  356. if pool.journal != nil {
  357. pool.journal.close()
  358. }
  359. log.Info("Transaction pool stopped")
  360. }
  361. // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
  362. // starts sending event to the given channel.
  363. func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
  364. return pool.scope.Track(pool.txFeed.Subscribe(ch))
  365. }
  366. // GasPrice returns the current gas price enforced by the transaction pool.
  367. func (pool *TxPool) GasPrice() *big.Int {
  368. pool.mu.RLock()
  369. defer pool.mu.RUnlock()
  370. return new(big.Int).Set(pool.gasPrice)
  371. }
  372. // SetGasPrice updates the minimum price required by the transaction pool for a
  373. // new transaction, and drops all transactions below this threshold.
  374. func (pool *TxPool) SetGasPrice(price *big.Int) {
  375. //Quorum
  376. if pool.chainconfig.IsQuorum && !pool.chainconfig.IsGasPriceEnabled(pool.chain.CurrentBlock().Header().Number) {
  377. log.Info("Transaction pool price threshold not updated as gasPrice is not enabled")
  378. return
  379. }
  380. //End-Quorum
  381. pool.mu.Lock()
  382. defer pool.mu.Unlock()
  383. pool.gasPrice = price
  384. for _, tx := range pool.priced.Cap(price) {
  385. pool.removeTx(tx.Hash(), false)
  386. }
  387. log.Info("Transaction pool price threshold updated", "price", price)
  388. }
  389. // Nonce returns the next nonce of an account, with all transactions executable
  390. // by the pool already applied on top.
  391. func (pool *TxPool) Nonce(addr common.Address) uint64 {
  392. pool.mu.RLock()
  393. defer pool.mu.RUnlock()
  394. return pool.pendingNonces.get(addr)
  395. }
  396. // Stats retrieves the current pool stats, namely the number of pending and the
  397. // number of queued (non-executable) transactions.
  398. func (pool *TxPool) Stats() (int, int) {
  399. pool.mu.RLock()
  400. defer pool.mu.RUnlock()
  401. return pool.stats()
  402. }
  403. // stats retrieves the current pool stats, namely the number of pending and the
  404. // number of queued (non-executable) transactions.
  405. func (pool *TxPool) stats() (int, int) {
  406. pending := 0
  407. for _, list := range pool.pending {
  408. pending += list.Len()
  409. }
  410. queued := 0
  411. for _, list := range pool.queue {
  412. queued += list.Len()
  413. }
  414. return pending, queued
  415. }
  416. // Content retrieves the data content of the transaction pool, returning all the
  417. // pending as well as queued transactions, grouped by account and sorted by nonce.
  418. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  419. pool.mu.Lock()
  420. defer pool.mu.Unlock()
  421. pending := make(map[common.Address]types.Transactions)
  422. for addr, list := range pool.pending {
  423. pending[addr] = list.Flatten()
  424. }
  425. queued := make(map[common.Address]types.Transactions)
  426. for addr, list := range pool.queue {
  427. queued[addr] = list.Flatten()
  428. }
  429. return pending, queued
  430. }
  431. // Pending retrieves all currently processable transactions, grouped by origin
  432. // account and sorted by nonce. The returned transaction set is a copy and can be
  433. // freely modified by calling code.
  434. func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
  435. pool.mu.Lock()
  436. defer pool.mu.Unlock()
  437. pending := make(map[common.Address]types.Transactions)
  438. for addr, list := range pool.pending {
  439. pending[addr] = list.Flatten()
  440. }
  441. return pending, nil
  442. }
  443. // Locals retrieves the accounts currently considered local by the pool.
  444. func (pool *TxPool) Locals() []common.Address {
  445. pool.mu.Lock()
  446. defer pool.mu.Unlock()
  447. return pool.locals.flatten()
  448. }
  449. // local retrieves all currently known local transactions, grouped by origin
  450. // account and sorted by nonce. The returned transaction set is a copy and can be
  451. // freely modified by calling code.
  452. func (pool *TxPool) local() map[common.Address]types.Transactions {
  453. txs := make(map[common.Address]types.Transactions)
  454. for addr := range pool.locals.accounts {
  455. if pending := pool.pending[addr]; pending != nil {
  456. txs[addr] = append(txs[addr], pending.Flatten()...)
  457. }
  458. if queued := pool.queue[addr]; queued != nil {
  459. txs[addr] = append(txs[addr], queued.Flatten()...)
  460. }
  461. }
  462. return txs
  463. }
  464. // validateTx checks whether a transaction is valid according to the consensus
  465. // rules and adheres to some heuristic limits of the local node (price and size).
  466. func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
  467. // Accept only legacy transactions until EIP-2718/2930 activates.
  468. if !pool.eip2718 && tx.Type() != types.LegacyTxType {
  469. return ErrTxTypeNotSupported
  470. }
  471. // Quorum
  472. sizeLimit := pool.chainconfig.GetTransactionSizeLimit(pool.chain.CurrentBlock().Number())
  473. // Reject transactions over defined size to prevent DOS attacks
  474. if float64(tx.Size()) > float64(sizeLimit*1024) {
  475. return ErrOversizedData
  476. }
  477. // End Quorum
  478. // Transactions can't be negative. This may never happen using RLP decoded
  479. // transactions but may occur if you create a transaction using the RPC.
  480. if tx.Value().Sign() < 0 {
  481. return ErrNegativeValue
  482. }
  483. // Ensure the transaction doesn't exceed the current block limit gas.
  484. if pool.currentMaxGas < tx.Gas() {
  485. return ErrGasLimit
  486. }
  487. // Make sure the transaction is signed properly.
  488. from, err := types.Sender(pool.signer, tx)
  489. if err != nil {
  490. return ErrInvalidSender
  491. }
  492. if pool.chainconfig.IsQuorum {
  493. // Quorum
  494. if tx.IsPrivacyMarker() {
  495. innerTx, _, _, _ := private.FetchPrivateTransaction(tx.Data())
  496. if innerTx != nil {
  497. if err := pool.validateTx(innerTx, local); err != nil {
  498. return err
  499. }
  500. }
  501. }
  502. // Quorum
  503. // Reject transaction if gas price is disabled, but gas price is specified
  504. if (!pool.chainconfig.IsGasPriceEnabled(pool.chain.CurrentBlock().Header().Number)) && tx.GasPriceIntCmp(common.Big0) != 0 {
  505. return ErrInvalidGasPrice
  506. }
  507. // Ether value is not currently supported on private transactions
  508. if tx.IsPrivate() && (len(tx.Data()) == 0 || tx.Value().Sign() != 0) {
  509. return ErrEtherValueUnsupported
  510. }
  511. // Quorum - check if the sender account is authorized to perform the transaction
  512. if err := pcore.CheckAccountPermission(tx.From(), tx.To(), tx.Value(), tx.Data(), tx.Gas(), tx.GasPrice()); err != nil {
  513. return err
  514. }
  515. }
  516. if !pool.chainconfig.IsQuorum || pool.chainconfig.IsGasPriceEnabled(pool.chain.CurrentBlock().Header().Number) {
  517. // Drop non-local transactions under our own minimal accepted gas price
  518. local = local || pool.locals.contains(from)
  519. if !local && tx.GasPriceIntCmp(pool.gasPrice) < 0 {
  520. return ErrUnderpriced
  521. }
  522. }
  523. // Ensure the transaction adheres to nonce ordering
  524. if pool.currentState.GetNonce(from) > tx.Nonce() {
  525. return ErrNonceTooLow
  526. }
  527. // Transactor should have enough funds to cover the costs
  528. // cost == V + GP * GL
  529. if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  530. return ErrInsufficientFunds
  531. }
  532. // Ensure the transaction has more gas than the basic tx fee.
  533. intrGas, err := IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, pool.istanbul)
  534. if err != nil {
  535. return err
  536. }
  537. if tx.Gas() < intrGas {
  538. return ErrIntrinsicGas
  539. }
  540. return nil
  541. }
  542. // add validates a transaction and inserts it into the non-executable queue for later
  543. // pending promotion and execution. If the transaction is a replacement for an already
  544. // pending or queued one, it overwrites the previous transaction if its price is higher.
  545. //
  546. // If a newly added transaction is marked as local, its sending account will be
  547. // whitelisted, preventing any associated transaction from being dropped out of the pool
  548. // due to pricing constraints.
  549. func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err error) {
  550. // If the transaction is already known, discard it
  551. hash := tx.Hash()
  552. if pool.all.Get(hash) != nil {
  553. log.Trace("Discarding already known transaction", "hash", hash)
  554. knownTxMeter.Mark(1)
  555. return false, ErrAlreadyKnown
  556. }
  557. // Make the local flag. If it's from local source or it's from the network but
  558. // the sender is marked as local previously, treat it as the local transaction.
  559. isLocal := local || pool.locals.containsTx(tx)
  560. // If the transaction fails basic validation, discard it
  561. if err := pool.validateTx(tx, isLocal); err != nil {
  562. log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
  563. invalidTxMeter.Mark(1)
  564. return false, err
  565. }
  566. // If the transaction pool is full, discard underpriced transactions
  567. if uint64(pool.all.Count()+numSlots(tx)) > pool.config.GlobalSlots+pool.config.GlobalQueue {
  568. // If the new transaction is underpriced, don't accept it
  569. if (!pool.chainconfig.IsQuorum || pool.chainconfig.IsGasPriceEnabled(pool.chain.CurrentBlock().Header().Number)) && !isLocal && pool.priced.Underpriced(tx) {
  570. log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
  571. underpricedTxMeter.Mark(1)
  572. return false, ErrUnderpriced
  573. }
  574. // New transaction is better than our worse ones, make room for it.
  575. // If it's a local transaction, forcibly discard all available transactions.
  576. // Otherwise if we can't make enough room for new one, abort the operation.
  577. drop, success := pool.priced.Discard(pool.all.Slots()-int(pool.config.GlobalSlots+pool.config.GlobalQueue)+numSlots(tx), isLocal)
  578. // Special case, we still can't make the room for the new remote one.
  579. if !isLocal && !success {
  580. log.Trace("Discarding overflown transaction", "hash", hash)
  581. overflowedTxMeter.Mark(1)
  582. return false, ErrTxPoolOverflow
  583. }
  584. // Kick out the underpriced remote transactions.
  585. for _, tx := range drop {
  586. log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
  587. underpricedTxMeter.Mark(1)
  588. pool.removeTx(tx.Hash(), false)
  589. }
  590. }
  591. // Try to replace an existing transaction in the pending pool
  592. from, _ := types.Sender(pool.signer, tx) // already validated
  593. if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
  594. // Nonce already pending, check if required price bump is met
  595. inserted, old := list.Add(tx, pool.config.PriceBump)
  596. if !inserted {
  597. pendingDiscardMeter.Mark(1)
  598. return false, ErrReplaceUnderpriced
  599. }
  600. // New transaction is better, replace old one
  601. if old != nil {
  602. pool.all.Remove(old.Hash())
  603. pool.priced.Removed(1)
  604. pendingReplaceMeter.Mark(1)
  605. }
  606. pool.all.Add(tx, isLocal)
  607. pool.priced.Put(tx, isLocal)
  608. pool.journalTx(from, tx)
  609. pool.queueTxEvent(tx)
  610. log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
  611. // Successful promotion, bump the heartbeat
  612. pool.beats[from] = time.Now()
  613. return old != nil, nil
  614. }
  615. // New transaction isn't replacing a pending one, push into queue
  616. replaced, err = pool.enqueueTx(hash, tx, isLocal, true)
  617. if err != nil {
  618. return false, err
  619. }
  620. // Mark local addresses and journal local transactions
  621. if local && !pool.locals.contains(from) {
  622. log.Info("Setting new local account", "address", from)
  623. pool.locals.add(from)
  624. pool.priced.Removed(pool.all.RemoteToLocals(pool.locals)) // Migrate the remotes if it's marked as local first time.
  625. }
  626. if isLocal {
  627. localGauge.Inc(1)
  628. }
  629. pool.journalTx(from, tx)
  630. log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
  631. return replaced, nil
  632. }
  633. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  634. //
  635. // Note, this method assumes the pool lock is held!
  636. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction, local bool, addAll bool) (bool, error) {
  637. // Try to insert the transaction into the future queue
  638. from, _ := types.Sender(pool.signer, tx) // already validated
  639. if pool.queue[from] == nil {
  640. pool.queue[from] = newTxList(false)
  641. }
  642. inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
  643. if !inserted {
  644. // An older transaction was better, discard this
  645. queuedDiscardMeter.Mark(1)
  646. return false, ErrReplaceUnderpriced
  647. }
  648. // Discard any previous transaction and mark this
  649. if old != nil {
  650. pool.all.Remove(old.Hash())
  651. pool.priced.Removed(1)
  652. queuedReplaceMeter.Mark(1)
  653. } else {
  654. // Nothing was replaced, bump the queued counter
  655. queuedGauge.Inc(1)
  656. }
  657. // If the transaction isn't in lookup set but it's expected to be there,
  658. // show the error log.
  659. if pool.all.Get(hash) == nil && !addAll {
  660. log.Error("Missing transaction in lookup set, please report the issue", "hash", hash)
  661. }
  662. if addAll {
  663. pool.all.Add(tx, local)
  664. pool.priced.Put(tx, local)
  665. }
  666. // If we never record the heartbeat, do it right now.
  667. if _, exist := pool.beats[from]; !exist {
  668. pool.beats[from] = time.Now()
  669. }
  670. return old != nil, nil
  671. }
  672. // journalTx adds the specified transaction to the local disk journal if it is
  673. // deemed to have been sent from a local account.
  674. func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
  675. // Only journal if it's enabled and the transaction is local
  676. if pool.journal == nil || !pool.locals.contains(from) {
  677. return
  678. }
  679. if err := pool.journal.insert(tx); err != nil {
  680. log.Warn("Failed to journal local transaction", "err", err)
  681. }
  682. }
  683. // promoteTx adds a transaction to the pending (processable) list of transactions
  684. // and returns whether it was inserted or an older was better.
  685. //
  686. // Note, this method assumes the pool lock is held!
  687. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool {
  688. // Try to insert the transaction into the pending queue
  689. if pool.pending[addr] == nil {
  690. pool.pending[addr] = newTxList(true)
  691. }
  692. list := pool.pending[addr]
  693. inserted, old := list.Add(tx, pool.config.PriceBump)
  694. if !inserted {
  695. // An older transaction was better, discard this
  696. pool.all.Remove(hash)
  697. pool.priced.Removed(1)
  698. pendingDiscardMeter.Mark(1)
  699. return false
  700. }
  701. // Otherwise discard any previous transaction and mark this
  702. if old != nil {
  703. pool.all.Remove(old.Hash())
  704. pool.priced.Removed(1)
  705. pendingReplaceMeter.Mark(1)
  706. } else {
  707. // Nothing was replaced, bump the pending counter
  708. pendingGauge.Inc(1)
  709. }
  710. // Set the potentially new pending nonce and notify any subsystems of the new tx
  711. pool.pendingNonces.set(addr, tx.Nonce()+1)
  712. // Successful promotion, bump the heartbeat
  713. pool.beats[addr] = time.Now()
  714. return true
  715. }
  716. // AddLocals enqueues a batch of transactions into the pool if they are valid, marking the
  717. // senders as a local ones, ensuring they go around the local pricing constraints.
  718. //
  719. // This method is used to add transactions from the RPC API and performs synchronous pool
  720. // reorganization and event propagation.
  721. func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
  722. return pool.addTxs(txs, !pool.config.NoLocals, true)
  723. }
  724. // AddLocal enqueues a single local transaction into the pool if it is valid. This is
  725. // a convenience wrapper aroundd AddLocals.
  726. func (pool *TxPool) AddLocal(tx *types.Transaction) error {
  727. errs := pool.AddLocals([]*types.Transaction{tx})
  728. return errs[0]
  729. }
  730. // AddRemotes enqueues a batch of transactions into the pool if they are valid. If the
  731. // senders are not among the locally tracked ones, full pricing constraints will apply.
  732. //
  733. // This method is used to add transactions from the p2p network and does not wait for pool
  734. // reorganization and internal event propagation.
  735. func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
  736. return pool.addTxs(txs, false, false)
  737. }
  738. // This is like AddRemotes, but waits for pool reorganization. Tests use this method.
  739. func (pool *TxPool) AddRemotesSync(txs []*types.Transaction) []error {
  740. return pool.addTxs(txs, false, true)
  741. }
  742. // This is like AddRemotes with a single transaction, but waits for pool reorganization. Tests use this method.
  743. func (pool *TxPool) addRemoteSync(tx *types.Transaction) error {
  744. errs := pool.AddRemotesSync([]*types.Transaction{tx})
  745. return errs[0]
  746. }
  747. // AddRemote enqueues a single transaction into the pool if it is valid. This is a convenience
  748. // wrapper around AddRemotes.
  749. //
  750. // Deprecated: use AddRemotes
  751. func (pool *TxPool) AddRemote(tx *types.Transaction) error {
  752. errs := pool.AddRemotes([]*types.Transaction{tx})
  753. return errs[0]
  754. }
  755. // addTxs attempts to queue a batch of transactions if they are valid.
  756. func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error {
  757. // Filter out known ones without obtaining the pool lock or recovering signatures
  758. var (
  759. errs = make([]error, len(txs))
  760. news = make([]*types.Transaction, 0, len(txs))
  761. )
  762. for i, tx := range txs {
  763. // If the transaction is known, pre-set the error slot
  764. if pool.all.Get(tx.Hash()) != nil {
  765. errs[i] = ErrAlreadyKnown
  766. knownTxMeter.Mark(1)
  767. continue
  768. }
  769. // Exclude transactions with invalid signatures as soon as
  770. // possible and cache senders in transactions before
  771. // obtaining lock
  772. _, err := types.Sender(pool.signer, tx)
  773. if err != nil {
  774. errs[i] = ErrInvalidSender
  775. invalidTxMeter.Mark(1)
  776. continue
  777. }
  778. // Accumulate all unknown transactions for deeper processing
  779. news = append(news, tx)
  780. }
  781. if len(news) == 0 {
  782. return errs
  783. }
  784. // Process all the new transaction and merge any errors into the original slice
  785. pool.mu.Lock()
  786. newErrs, dirtyAddrs := pool.addTxsLocked(news, local)
  787. pool.mu.Unlock()
  788. var nilSlot = 0
  789. for _, err := range newErrs {
  790. for errs[nilSlot] != nil {
  791. nilSlot++
  792. }
  793. errs[nilSlot] = err
  794. nilSlot++
  795. }
  796. // Reorg the pool internals if needed and return
  797. done := pool.requestPromoteExecutables(dirtyAddrs)
  798. if sync {
  799. <-done
  800. }
  801. return errs
  802. }
  803. // addTxsLocked attempts to queue a batch of transactions if they are valid.
  804. // The transaction pool lock must be held.
  805. func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) ([]error, *accountSet) {
  806. dirty := newAccountSet(pool.signer)
  807. errs := make([]error, len(txs))
  808. for i, tx := range txs {
  809. replaced, err := pool.add(tx, local)
  810. errs[i] = err
  811. if err == nil && !replaced {
  812. dirty.addTx(tx)
  813. }
  814. }
  815. validTxMeter.Mark(int64(len(dirty.accounts)))
  816. return errs, dirty
  817. }
  818. // Status returns the status (unknown/pending/queued) of a batch of transactions
  819. // identified by their hashes.
  820. func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
  821. status := make([]TxStatus, len(hashes))
  822. for i, hash := range hashes {
  823. tx := pool.Get(hash)
  824. if tx == nil {
  825. continue
  826. }
  827. from, _ := types.Sender(pool.signer, tx) // already validated
  828. pool.mu.RLock()
  829. if txList := pool.pending[from]; txList != nil && txList.txs.items[tx.Nonce()] != nil {
  830. status[i] = TxStatusPending
  831. } else if txList := pool.queue[from]; txList != nil && txList.txs.items[tx.Nonce()] != nil {
  832. status[i] = TxStatusQueued
  833. }
  834. // implicit else: the tx may have been included into a block between
  835. // checking pool.Get and obtaining the lock. In that case, TxStatusUnknown is correct
  836. pool.mu.RUnlock()
  837. }
  838. return status
  839. }
  840. // Get returns a transaction if it is contained in the pool and nil otherwise.
  841. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  842. return pool.all.Get(hash)
  843. }
  844. // Has returns an indicator whether txpool has a transaction cached with the
  845. // given hash.
  846. func (pool *TxPool) Has(hash common.Hash) bool {
  847. return pool.all.Get(hash) != nil
  848. }
  849. // removeTx removes a single transaction from the queue, moving all subsequent
  850. // transactions back to the future queue.
  851. func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {
  852. // Fetch the transaction we wish to delete
  853. tx := pool.all.Get(hash)
  854. if tx == nil {
  855. return
  856. }
  857. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  858. // Remove it from the list of known transactions
  859. pool.all.Remove(hash)
  860. if outofbound {
  861. pool.priced.Removed(1)
  862. }
  863. if pool.locals.contains(addr) {
  864. localGauge.Dec(1)
  865. }
  866. // Remove the transaction from the pending lists and reset the account nonce
  867. if pending := pool.pending[addr]; pending != nil {
  868. if removed, invalids := pending.Remove(tx); removed {
  869. // If no more pending transactions are left, remove the list
  870. if pending.Empty() {
  871. delete(pool.pending, addr)
  872. }
  873. // Postpone any invalidated transactions
  874. for _, tx := range invalids {
  875. // Internal shuffle shouldn't touch the lookup set.
  876. pool.enqueueTx(tx.Hash(), tx, false, false)
  877. }
  878. // Update the account nonce if needed
  879. pool.pendingNonces.setIfLower(addr, tx.Nonce())
  880. // Reduce the pending counter
  881. pendingGauge.Dec(int64(1 + len(invalids)))
  882. return
  883. }
  884. }
  885. // Transaction is in the future queue
  886. if future := pool.queue[addr]; future != nil {
  887. if removed, _ := future.Remove(tx); removed {
  888. // Reduce the queued counter
  889. queuedGauge.Dec(1)
  890. }
  891. if future.Empty() {
  892. delete(pool.queue, addr)
  893. delete(pool.beats, addr)
  894. }
  895. }
  896. }
  897. // requestReset requests a pool reset to the new head block.
  898. // The returned channel is closed when the reset has occurred.
  899. func (pool *TxPool) requestReset(oldHead *types.Header, newHead *types.Header) chan struct{} {
  900. select {
  901. case pool.reqResetCh <- &txpoolResetRequest{oldHead, newHead}:
  902. return <-pool.reorgDoneCh
  903. case <-pool.reorgShutdownCh:
  904. return pool.reorgShutdownCh
  905. }
  906. }
  907. // requestPromoteExecutables requests transaction promotion checks for the given addresses.
  908. // The returned channel is closed when the promotion checks have occurred.
  909. func (pool *TxPool) requestPromoteExecutables(set *accountSet) chan struct{} {
  910. select {
  911. case pool.reqPromoteCh <- set:
  912. return <-pool.reorgDoneCh
  913. case <-pool.reorgShutdownCh:
  914. return pool.reorgShutdownCh
  915. }
  916. }
  917. // queueTxEvent enqueues a transaction event to be sent in the next reorg run.
  918. func (pool *TxPool) queueTxEvent(tx *types.Transaction) {
  919. select {
  920. case pool.queueTxEventCh <- tx:
  921. case <-pool.reorgShutdownCh:
  922. }
  923. }
  924. // scheduleReorgLoop schedules runs of reset and promoteExecutables. Code above should not
  925. // call those methods directly, but request them being run using requestReset and
  926. // requestPromoteExecutables instead.
  927. func (pool *TxPool) scheduleReorgLoop() {
  928. defer pool.wg.Done()
  929. var (
  930. curDone chan struct{} // non-nil while runReorg is active
  931. nextDone = make(chan struct{})
  932. launchNextRun bool
  933. reset *txpoolResetRequest
  934. dirtyAccounts *accountSet
  935. queuedEvents = make(map[common.Address]*txSortedMap)
  936. )
  937. for {
  938. // Launch next background reorg if needed
  939. if curDone == nil && launchNextRun {
  940. // Run the background reorg and announcements
  941. go pool.runReorg(nextDone, reset, dirtyAccounts, queuedEvents)
  942. // Prepare everything for the next round of reorg
  943. curDone, nextDone = nextDone, make(chan struct{})
  944. launchNextRun = false
  945. reset, dirtyAccounts = nil, nil
  946. queuedEvents = make(map[common.Address]*txSortedMap)
  947. }
  948. select {
  949. case req := <-pool.reqResetCh:
  950. // Reset request: update head if request is already pending.
  951. if reset == nil {
  952. reset = req
  953. } else {
  954. reset.newHead = req.newHead
  955. }
  956. launchNextRun = true
  957. pool.reorgDoneCh <- nextDone
  958. case req := <-pool.reqPromoteCh:
  959. // Promote request: update address set if request is already pending.
  960. if dirtyAccounts == nil {
  961. dirtyAccounts = req
  962. } else {
  963. dirtyAccounts.merge(req)
  964. }
  965. launchNextRun = true
  966. pool.reorgDoneCh <- nextDone
  967. case tx := <-pool.queueTxEventCh:
  968. // Queue up the event, but don't schedule a reorg. It's up to the caller to
  969. // request one later if they want the events sent.
  970. addr, _ := types.Sender(pool.signer, tx)
  971. if _, ok := queuedEvents[addr]; !ok {
  972. queuedEvents[addr] = newTxSortedMap()
  973. }
  974. queuedEvents[addr].Put(tx)
  975. case <-curDone:
  976. curDone = nil
  977. case <-pool.reorgShutdownCh:
  978. // Wait for current run to finish.
  979. if curDone != nil {
  980. <-curDone
  981. }
  982. close(nextDone)
  983. return
  984. }
  985. }
  986. }
  987. // runReorg runs reset and promoteExecutables on behalf of scheduleReorgLoop.
  988. func (pool *TxPool) runReorg(done chan struct{}, reset *txpoolResetRequest, dirtyAccounts *accountSet, events map[common.Address]*txSortedMap) {
  989. defer close(done)
  990. var promoteAddrs []common.Address
  991. if dirtyAccounts != nil && reset == nil {
  992. // Only dirty accounts need to be promoted, unless we're resetting.
  993. // For resets, all addresses in the tx queue will be promoted and
  994. // the flatten operation can be avoided.
  995. promoteAddrs = dirtyAccounts.flatten()
  996. }
  997. pool.mu.Lock()
  998. if reset != nil {
  999. // Reset from the old head to the new, rescheduling any reorged transactions
  1000. pool.reset(reset.oldHead, reset.newHead)
  1001. // Nonces were reset, discard any events that became stale
  1002. for addr := range events {
  1003. events[addr].Forward(pool.pendingNonces.get(addr))
  1004. if events[addr].Len() == 0 {
  1005. delete(events, addr)
  1006. }
  1007. }
  1008. // Reset needs promote for all addresses
  1009. promoteAddrs = make([]common.Address, 0, len(pool.queue))
  1010. for addr := range pool.queue {
  1011. promoteAddrs = append(promoteAddrs, addr)
  1012. }
  1013. }
  1014. // Check for pending transactions for every account that sent new ones
  1015. promoted := pool.promoteExecutables(promoteAddrs)
  1016. // If a new block appeared, validate the pool of pending transactions. This will
  1017. // remove any transaction that has been included in the block or was invalidated
  1018. // because of another transaction (e.g. higher gas price).
  1019. if reset != nil {
  1020. pool.demoteUnexecutables()
  1021. }
  1022. // Ensure pool.queue and pool.pending sizes stay within the configured limits.
  1023. pool.truncatePending()
  1024. pool.truncateQueue()
  1025. // Update all accounts to the latest known pending nonce
  1026. for addr, list := range pool.pending {
  1027. highestPending := list.LastElement()
  1028. pool.pendingNonces.set(addr, highestPending.Nonce()+1)
  1029. }
  1030. pool.mu.Unlock()
  1031. // Notify subsystems for newly added transactions
  1032. for _, tx := range promoted {
  1033. addr, _ := types.Sender(pool.signer, tx)
  1034. if _, ok := events[addr]; !ok {
  1035. events[addr] = newTxSortedMap()
  1036. }
  1037. events[addr].Put(tx)
  1038. }
  1039. if len(events) > 0 {
  1040. var txs []*types.Transaction
  1041. for _, set := range events {
  1042. txs = append(txs, set.Flatten()...)
  1043. }
  1044. pool.txFeed.Send(NewTxsEvent{txs})
  1045. }
  1046. }
  1047. // reset retrieves the current state of the blockchain and ensures the content
  1048. // of the transaction pool is valid with regard to the chain state.
  1049. func (pool *TxPool) reset(oldHead, newHead *types.Header) {
  1050. // If we're reorging an old state, reinject all dropped transactions
  1051. var reinject types.Transactions
  1052. if oldHead != nil && oldHead.Hash() != newHead.ParentHash {
  1053. // If the reorg is too deep, avoid doing it (will happen during fast sync)
  1054. oldNum := oldHead.Number.Uint64()
  1055. newNum := newHead.Number.Uint64()
  1056. if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 {
  1057. log.Debug("Skipping deep transaction reorg", "depth", depth)
  1058. } else {
  1059. // Reorg seems shallow enough to pull in all transactions into memory
  1060. var discarded, included types.Transactions
  1061. var (
  1062. rem = pool.chain.GetBlock(oldHead.Hash(), oldHead.Number.Uint64())
  1063. add = pool.chain.GetBlock(newHead.Hash(), newHead.Number.Uint64())
  1064. )
  1065. if rem == nil {
  1066. // This can happen if a setHead is performed, where we simply discard the old
  1067. // head from the chain.
  1068. // If that is the case, we don't have the lost transactions any more, and
  1069. // there's nothing to add
  1070. if newNum >= oldNum {
  1071. // If we reorged to a same or higher number, then it's not a case of setHead
  1072. log.Warn("Transaction pool reset with missing oldhead",
  1073. "old", oldHead.Hash(), "oldnum", oldNum, "new", newHead.Hash(), "newnum", newNum)
  1074. return
  1075. }
  1076. // If the reorg ended up on a lower number, it's indicative of setHead being the cause
  1077. log.Debug("Skipping transaction reset caused by setHead",
  1078. "old", oldHead.Hash(), "oldnum", oldNum, "new", newHead.Hash(), "newnum", newNum)
  1079. // We still need to update the current state s.th. the lost transactions can be readded by the user
  1080. } else {
  1081. for rem.NumberU64() > add.NumberU64() {
  1082. discarded = append(discarded, rem.Transactions()...)
  1083. if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  1084. log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  1085. return
  1086. }
  1087. }
  1088. for add.NumberU64() > rem.NumberU64() {
  1089. included = append(included, add.Transactions()...)
  1090. if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  1091. log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  1092. return
  1093. }
  1094. }
  1095. for rem.Hash() != add.Hash() {
  1096. discarded = append(discarded, rem.Transactions()...)
  1097. if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  1098. log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  1099. return
  1100. }
  1101. included = append(included, add.Transactions()...)
  1102. if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  1103. log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  1104. return
  1105. }
  1106. }
  1107. reinject = types.TxDifference(discarded, included)
  1108. }
  1109. }
  1110. }
  1111. // Initialize the internal state to the current head
  1112. if newHead == nil {
  1113. newHead = pool.chain.CurrentBlock().Header() // Special case during testing
  1114. }
  1115. statedb, _, err := pool.chain.StateAt(newHead.Root)
  1116. if err != nil {
  1117. log.Error("Failed to reset txpool state", "err", err)
  1118. return
  1119. }
  1120. pool.currentState = statedb
  1121. pool.pendingNonces = newTxNoncer(statedb)
  1122. pool.currentMaxGas = newHead.GasLimit
  1123. // Inject any transactions discarded due to reorgs
  1124. log.Debug("Reinjecting stale transactions", "count", len(reinject))
  1125. senderCacher.recover(pool.signer, reinject)
  1126. pool.addTxsLocked(reinject, false)
  1127. // Update all fork indicator by next pending block number.
  1128. next := new(big.Int).Add(newHead.Number, big.NewInt(1))
  1129. pool.istanbul = pool.chainconfig.IsIstanbul(next)
  1130. pool.eip2718 = pool.chainconfig.IsBerlin(next)
  1131. }
  1132. // promoteExecutables moves transactions that have become processable from the
  1133. // future queue to the set of pending transactions. During this process, all
  1134. // invalidated transactions (low nonce, low balance) are deleted.
  1135. func (pool *TxPool) promoteExecutables(accounts []common.Address) []*types.Transaction {
  1136. isQuorum := pool.chainconfig.IsQuorum
  1137. // Init delayed since tx pool could have been started before any state sync
  1138. if isQuorum && pool.pendingNonces == nil {
  1139. pool.reset(nil, nil)
  1140. }
  1141. // Track the promoted transactions to broadcast them at once
  1142. var promoted []*types.Transaction
  1143. // Iterate over all accounts and promote any executable transactions
  1144. for _, addr := range accounts {
  1145. list := pool.queue[addr]
  1146. if list == nil {
  1147. continue // Just in case someone calls with a non existing account
  1148. }
  1149. // Drop all transactions that are deemed too old (low nonce)
  1150. forwards := list.Forward(pool.currentState.GetNonce(addr))
  1151. for _, tx := range forwards {
  1152. hash := tx.Hash()
  1153. pool.all.Remove(hash)
  1154. }
  1155. log.Trace("Removed old queued transactions", "count", len(forwards))
  1156. var drops types.Transactions
  1157. if !isQuorum || pool.chainconfig.IsGasPriceEnabled(pool.chain.CurrentBlock().Header().Number) {
  1158. // Drop all transactions that are too costly (low balance or out of gas)
  1159. drops, _ = list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  1160. for _, tx := range drops {
  1161. hash := tx.Hash()
  1162. pool.all.Remove(hash)
  1163. }
  1164. log.Trace("Removed unpayable queued transactions", "count", len(drops))
  1165. queuedNofundsMeter.Mark(int64(len(drops)))
  1166. }
  1167. // Gather all executable transactions and promote them
  1168. readies := list.Ready(pool.pendingNonces.get(addr))
  1169. for _, tx := range readies {
  1170. hash := tx.Hash()
  1171. log.Trace("Promoting queued transaction", "hash", hash)
  1172. if pool.promoteTx(addr, hash, tx) {
  1173. promoted = append(promoted, tx)
  1174. }
  1175. }
  1176. log.Trace("Promoted queued transactions", "count", len(promoted))
  1177. queuedGauge.Dec(int64(len(readies)))
  1178. // Drop all transactions over the allowed limit
  1179. var caps types.Transactions
  1180. if !pool.locals.contains(addr) {
  1181. caps = list.Cap(int(pool.config.AccountQueue))
  1182. for _, tx := range caps {
  1183. hash := tx.Hash()
  1184. pool.all.Remove(hash)
  1185. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  1186. }
  1187. queuedRateLimitMeter.Mark(int64(len(caps)))
  1188. }
  1189. // Mark all the items dropped as removed
  1190. pool.priced.Removed(len(forwards) + len(drops) + len(caps))
  1191. queuedGauge.Dec(int64(len(forwards) + len(drops) + len(caps)))
  1192. if pool.locals.contains(addr) {
  1193. localGauge.Dec(int64(len(forwards) + len(drops) + len(caps)))
  1194. }
  1195. // Delete the entire queue entry if it became empty.
  1196. if list.Empty() {
  1197. delete(pool.queue, addr)
  1198. delete(pool.beats, addr)
  1199. }
  1200. }
  1201. return promoted
  1202. }
  1203. // truncatePending removes transactions from the pending queue if the pool is above the
  1204. // pending limit. The algorithm tries to reduce transaction counts by an approximately
  1205. // equal number for all for accounts with many pending transactions.
  1206. func (pool *TxPool) truncatePending() {
  1207. pending := uint64(0)
  1208. for _, list := range pool.pending {
  1209. pending += uint64(list.Len())
  1210. }
  1211. if pending <= pool.config.GlobalSlots {
  1212. return
  1213. }
  1214. pendingBeforeCap := pending
  1215. // Assemble a spam order to penalize large transactors first
  1216. spammers := prque.New(nil)
  1217. for addr, list := range pool.pending {
  1218. // Only evict transactions from high rollers
  1219. if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  1220. spammers.Push(addr, int64(list.Len()))
  1221. }
  1222. }
  1223. // Gradually drop transactions from offenders
  1224. offenders := []common.Address{}
  1225. for pending > pool.config.GlobalSlots && !spammers.Empty() {
  1226. // Retrieve the next offender if not local address
  1227. offender, _ := spammers.Pop()
  1228. offenders = append(offenders, offender.(common.Address))
  1229. // Equalize balances until all the same or below threshold
  1230. if len(offenders) > 1 {
  1231. // Calculate the equalization threshold for all current offenders
  1232. threshold := pool.pending[offender.(common.Address)].Len()
  1233. // Iteratively reduce all offenders until below limit or threshold reached
  1234. for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  1235. for i := 0; i < len(offenders)-1; i++ {
  1236. list := pool.pending[offenders[i]]
  1237. caps := list.Cap(list.Len() - 1)
  1238. for _, tx := range caps {
  1239. // Drop the transaction from the global pools too
  1240. hash := tx.Hash()
  1241. pool.all.Remove(hash)
  1242. // Update the account nonce to the dropped transaction
  1243. pool.pendingNonces.setIfLower(offenders[i], tx.Nonce())
  1244. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  1245. }
  1246. pool.priced.Removed(len(caps))
  1247. pendingGauge.Dec(int64(len(caps)))
  1248. if pool.locals.contains(offenders[i]) {
  1249. localGauge.Dec(int64(len(caps)))
  1250. }
  1251. pending--
  1252. }
  1253. }
  1254. }
  1255. }
  1256. // If still above threshold, reduce to limit or min allowance
  1257. if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  1258. for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  1259. for _, addr := range offenders {
  1260. list := pool.pending[addr]
  1261. caps := list.Cap(list.Len() - 1)
  1262. for _, tx := range caps {
  1263. // Drop the transaction from the global pools too
  1264. hash := tx.Hash()
  1265. pool.all.Remove(hash)
  1266. // Update the account nonce to the dropped transaction
  1267. pool.pendingNonces.setIfLower(addr, tx.Nonce())
  1268. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  1269. }
  1270. pool.priced.Removed(len(caps))
  1271. pendingGauge.Dec(int64(len(caps)))
  1272. if pool.locals.contains(addr) {
  1273. localGauge.Dec(int64(len(caps)))
  1274. }
  1275. pending--
  1276. }
  1277. }
  1278. }
  1279. pendingRateLimitMeter.Mark(int64(pendingBeforeCap - pending))
  1280. }
  1281. // truncateQueue drops the oldes transactions in the queue if the pool is above the global queue limit.
  1282. func (pool *TxPool) truncateQueue() {
  1283. queued := uint64(0)
  1284. for _, list := range pool.queue {
  1285. queued += uint64(list.Len())
  1286. }
  1287. if queued <= pool.config.GlobalQueue {
  1288. return
  1289. }
  1290. // Sort all accounts with queued transactions by heartbeat
  1291. addresses := make(addressesByHeartbeat, 0, len(pool.queue))
  1292. for addr := range pool.queue {
  1293. if !pool.locals.contains(addr) { // don't drop locals
  1294. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  1295. }
  1296. }
  1297. sort.Sort(addresses)
  1298. // Drop transactions until the total is below the limit or only locals remain
  1299. for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  1300. addr := addresses[len(addresses)-1]
  1301. list := pool.queue[addr.address]
  1302. addresses = addresses[:len(addresses)-1]
  1303. // Drop all transactions if they are less than the overflow
  1304. if size := uint64(list.Len()); size <= drop {
  1305. for _, tx := range list.Flatten() {
  1306. pool.removeTx(tx.Hash(), true)
  1307. }
  1308. drop -= size
  1309. queuedRateLimitMeter.Mark(int64(size))
  1310. continue
  1311. }
  1312. // Otherwise drop only last few transactions
  1313. txs := list.Flatten()
  1314. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  1315. pool.removeTx(txs[i].Hash(), true)
  1316. drop--
  1317. queuedRateLimitMeter.Mark(1)
  1318. }
  1319. }
  1320. }
  1321. // demoteUnexecutables removes invalid and processed transactions from the pools
  1322. // executable/pending queue and any subsequent transactions that become unexecutable
  1323. // are moved back into the future queue.
  1324. func (pool *TxPool) demoteUnexecutables() {
  1325. // Iterate over all accounts and demote any non-executable transactions
  1326. for addr, list := range pool.pending {
  1327. nonce := pool.currentState.GetNonce(addr)
  1328. // Drop all transactions that are deemed too old (low nonce)
  1329. olds := list.Forward(nonce)
  1330. for _, tx := range olds {
  1331. hash := tx.Hash()
  1332. pool.all.Remove(hash)
  1333. log.Trace("Removed old pending transaction", "hash", hash)
  1334. }
  1335. // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  1336. drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  1337. for _, tx := range drops {
  1338. hash := tx.Hash()
  1339. log.Trace("Removed unpayable pending transaction", "hash", hash)
  1340. pool.all.Remove(hash)
  1341. }
  1342. pool.priced.Removed(len(olds) + len(drops))
  1343. pendingNofundsMeter.Mark(int64(len(drops)))
  1344. for _, tx := range invalids {
  1345. hash := tx.Hash()
  1346. log.Trace("Demoting pending transaction", "hash", hash)
  1347. // Internal shuffle shouldn't touch the lookup set.
  1348. pool.enqueueTx(hash, tx, false, false)
  1349. }
  1350. pendingGauge.Dec(int64(len(olds) + len(drops) + len(invalids)))
  1351. if pool.locals.contains(addr) {
  1352. localGauge.Dec(int64(len(olds) + len(drops) + len(invalids)))
  1353. }
  1354. // If there's a gap in front, alert (should never happen) and postpone all transactions
  1355. if list.Len() > 0 && list.txs.Get(nonce) == nil {
  1356. gapped := list.Cap(0)
  1357. for _, tx := range gapped {
  1358. hash := tx.Hash()
  1359. log.Error("Demoting invalidated transaction", "hash", hash)
  1360. // Internal shuffle shouldn't touch the lookup set.
  1361. pool.enqueueTx(hash, tx, false, false)
  1362. }
  1363. pendingGauge.Dec(int64(len(gapped)))
  1364. // This might happen in a reorg, so log it to the metering
  1365. blockReorgInvalidatedTx.Mark(int64(len(gapped)))
  1366. }
  1367. // Delete the entire pending entry if it became empty.
  1368. if list.Empty() {
  1369. delete(pool.pending, addr)
  1370. }
  1371. }
  1372. }
  1373. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  1374. type addressByHeartbeat struct {
  1375. address common.Address
  1376. heartbeat time.Time
  1377. }
  1378. type addressesByHeartbeat []addressByHeartbeat
  1379. func (a addressesByHeartbeat) Len() int { return len(a) }
  1380. func (a addressesByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  1381. func (a addressesByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1382. // accountSet is simply a set of addresses to check for existence, and a signer
  1383. // capable of deriving addresses from transactions.
  1384. type accountSet struct {
  1385. accounts map[common.Address]struct{}
  1386. signer types.Signer
  1387. cache *[]common.Address
  1388. }
  1389. // newAccountSet creates a new address set with an associated signer for sender
  1390. // derivations.
  1391. func newAccountSet(signer types.Signer, addrs ...common.Address) *accountSet {
  1392. as := &accountSet{
  1393. accounts: make(map[common.Address]struct{}),
  1394. signer: signer,
  1395. }
  1396. for _, addr := range addrs {
  1397. as.add(addr)
  1398. }
  1399. return as
  1400. }
  1401. // contains checks if a given address is contained within the set.
  1402. func (as *accountSet) contains(addr common.Address) bool {
  1403. _, exist := as.accounts[addr]
  1404. return exist
  1405. }
  1406. func (as *accountSet) empty() bool {
  1407. return len(as.accounts) == 0
  1408. }
  1409. // containsTx checks if the sender of a given tx is within the set. If the sender
  1410. // cannot be derived, this method returns false.
  1411. func (as *accountSet) containsTx(tx *types.Transaction) bool {
  1412. if addr, err := types.Sender(as.signer, tx); err == nil {
  1413. return as.contains(addr)
  1414. }
  1415. return false
  1416. }
  1417. // add inserts a new address into the set to track.
  1418. func (as *accountSet) add(addr common.Address) {
  1419. as.accounts[addr] = struct{}{}
  1420. as.cache = nil
  1421. }
  1422. // addTx adds the sender of tx into the set.
  1423. func (as *accountSet) addTx(tx *types.Transaction) {
  1424. if addr, err := types.Sender(as.signer, tx); err == nil {
  1425. as.add(addr)
  1426. }
  1427. }
  1428. // flatten returns the list of addresses within this set, also caching it for later
  1429. // reuse. The returned slice should not be changed!
  1430. func (as *accountSet) flatten() []common.Address {
  1431. if as.cache == nil {
  1432. accounts := make([]common.Address, 0, len(as.accounts))
  1433. for account := range as.accounts {
  1434. accounts = append(accounts, account)
  1435. }
  1436. as.cache = &accounts
  1437. }
  1438. return *as.cache
  1439. }
  1440. // merge adds all addresses from the 'other' set into 'as'.
  1441. func (as *accountSet) merge(other *accountSet) {
  1442. for addr := range other.accounts {
  1443. as.accounts[addr] = struct{}{}
  1444. }
  1445. as.cache = nil
  1446. }
  1447. // txLookup is used internally by TxPool to track transactions while allowing
  1448. // lookup without mutex contention.
  1449. //
  1450. // Note, although this type is properly protected against concurrent access, it
  1451. // is **not** a type that should ever be mutated or even exposed outside of the
  1452. // transaction pool, since its internal state is tightly coupled with the pools
  1453. // internal mechanisms. The sole purpose of the type is to permit out-of-bound
  1454. // peeking into the pool in TxPool.Get without having to acquire the widely scoped
  1455. // TxPool.mu mutex.
  1456. //
  1457. // This lookup set combines the notion of "local transactions", which is useful
  1458. // to build upper-level structure.
  1459. type txLookup struct {
  1460. slots int
  1461. lock sync.RWMutex
  1462. locals map[common.Hash]*types.Transaction
  1463. remotes map[common.Hash]*types.Transaction
  1464. }
  1465. // newTxLookup returns a new txLookup structure.
  1466. func newTxLookup() *txLookup {
  1467. return &txLookup{
  1468. locals: make(map[common.Hash]*types.Transaction),
  1469. remotes: make(map[common.Hash]*types.Transaction),
  1470. }
  1471. }
  1472. // Range calls f on each key and value present in the map. The callback passed
  1473. // should return the indicator whether the iteration needs to be continued.
  1474. // Callers need to specify which set (or both) to be iterated.
  1475. func (t *txLookup) Range(f func(hash common.Hash, tx *types.Transaction, local bool) bool, local bool, remote bool) {
  1476. t.lock.RLock()
  1477. defer t.lock.RUnlock()
  1478. if local {
  1479. for key, value := range t.locals {
  1480. if !f(key, value, true) {
  1481. return
  1482. }
  1483. }
  1484. }
  1485. if remote {
  1486. for key, value := range t.remotes {
  1487. if !f(key, value, false) {
  1488. return
  1489. }
  1490. }
  1491. }
  1492. }
  1493. // Get returns a transaction if it exists in the lookup, or nil if not found.
  1494. func (t *txLookup) Get(hash common.Hash) *types.Transaction {
  1495. t.lock.RLock()
  1496. defer t.lock.RUnlock()
  1497. if tx := t.locals[hash]; tx != nil {
  1498. return tx
  1499. }
  1500. return t.remotes[hash]
  1501. }
  1502. // GetLocal returns a transaction if it exists in the lookup, or nil if not found.
  1503. func (t *txLookup) GetLocal(hash common.Hash) *types.Transaction {
  1504. t.lock.RLock()
  1505. defer t.lock.RUnlock()
  1506. return t.locals[hash]
  1507. }
  1508. // GetRemote returns a transaction if it exists in the lookup, or nil if not found.
  1509. func (t *txLookup) GetRemote(hash common.Hash) *types.Transaction {
  1510. t.lock.RLock()
  1511. defer t.lock.RUnlock()
  1512. return t.remotes[hash]
  1513. }
  1514. // Count returns the current number of transactions in the lookup.
  1515. func (t *txLookup) Count() int {
  1516. t.lock.RLock()
  1517. defer t.lock.RUnlock()
  1518. return len(t.locals) + len(t.remotes)
  1519. }
  1520. // LocalCount returns the current number of local transactions in the lookup.
  1521. func (t *txLookup) LocalCount() int {
  1522. t.lock.RLock()
  1523. defer t.lock.RUnlock()
  1524. return len(t.locals)
  1525. }
  1526. // RemoteCount returns the current number of remote transactions in the lookup.
  1527. func (t *txLookup) RemoteCount() int {
  1528. t.lock.RLock()
  1529. defer t.lock.RUnlock()
  1530. return len(t.remotes)
  1531. }
  1532. // Slots returns the current number of slots used in the lookup.
  1533. func (t *txLookup) Slots() int {
  1534. t.lock.RLock()
  1535. defer t.lock.RUnlock()
  1536. return t.slots
  1537. }
  1538. // Add adds a transaction to the lookup.
  1539. func (t *txLookup) Add(tx *types.Transaction, local bool) {
  1540. t.lock.Lock()
  1541. defer t.lock.Unlock()
  1542. t.slots += numSlots(tx)
  1543. slotsGauge.Update(int64(t.slots))
  1544. if local {
  1545. t.locals[tx.Hash()] = tx
  1546. } else {
  1547. t.remotes[tx.Hash()] = tx
  1548. }
  1549. }
  1550. // Remove removes a transaction from the lookup.
  1551. func (t *txLookup) Remove(hash common.Hash) {
  1552. t.lock.Lock()
  1553. defer t.lock.Unlock()
  1554. tx, ok := t.locals[hash]
  1555. if !ok {
  1556. tx, ok = t.remotes[hash]
  1557. }
  1558. if !ok {
  1559. log.Error("No transaction found to be deleted", "hash", hash)
  1560. return
  1561. }
  1562. t.slots -= numSlots(tx)
  1563. slotsGauge.Update(int64(t.slots))
  1564. delete(t.locals, hash)
  1565. delete(t.remotes, hash)
  1566. }
  1567. // RemoteToLocals migrates the transactions belongs to the given locals to locals
  1568. // set. The assumption is held the locals set is thread-safe to be used.
  1569. func (t *txLookup) RemoteToLocals(locals *accountSet) int {
  1570. t.lock.Lock()
  1571. defer t.lock.Unlock()
  1572. var migrated int
  1573. for hash, tx := range t.remotes {
  1574. if locals.containsTx(tx) {
  1575. t.locals[hash] = tx
  1576. delete(t.remotes, hash)
  1577. migrated += 1
  1578. }
  1579. }
  1580. return migrated
  1581. }
  1582. // numSlots calculates the number of slots needed for a single transaction.
  1583. func numSlots(tx *types.Transaction) int {
  1584. return int((tx.Size() + txSlotSize - 1) / txSlotSize)
  1585. }
  1586. // Quorum
  1587. // helper function to return chainHeadChannel size
  1588. func GetChainHeadChannleSize() int {
  1589. return chainHeadChanSize
  1590. }