tx_pool.go 60 KB

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