tx_pool.go 58 KB

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