tx_pool.go 57 KB

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