tx_pool.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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. "fmt"
  20. "math"
  21. "math/big"
  22. "sort"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/common/prque"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/metrics"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. const (
  35. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  36. chainHeadChanSize = 10
  37. )
  38. var (
  39. // ErrInvalidSender is returned if the transaction contains an invalid signature.
  40. ErrInvalidSender = errors.New("invalid sender")
  41. // ErrNonceTooLow is returned if the nonce of a transaction is lower than the
  42. // one present in the local chain.
  43. ErrNonceTooLow = errors.New("nonce too low")
  44. // ErrUnderpriced is returned if a transaction's gas price is below the minimum
  45. // configured for the transaction pool.
  46. ErrUnderpriced = errors.New("transaction underpriced")
  47. // ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
  48. // with a different one without the required price bump.
  49. ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")
  50. // ErrInsufficientFunds is returned if the total cost of executing a transaction
  51. // is higher than the balance of the user's account.
  52. ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value")
  53. // ErrIntrinsicGas is returned if the transaction is specified to use less gas
  54. // than required to start the invocation.
  55. ErrIntrinsicGas = errors.New("intrinsic gas too low")
  56. // ErrGasLimit is returned if a transaction's requested gas limit exceeds the
  57. // maximum allowance of the current block.
  58. ErrGasLimit = errors.New("exceeds block gas limit")
  59. // ErrNegativeValue is a sanity error to ensure noone is able to specify a
  60. // transaction with a negative value.
  61. ErrNegativeValue = errors.New("negative value")
  62. // ErrOversizedData is returned if the input data of a transaction is greater
  63. // than some meaningful limit a user might use. This is not a consensus error
  64. // making the transaction invalid, rather a DOS protection.
  65. ErrOversizedData = errors.New("oversized data")
  66. )
  67. var (
  68. evictionInterval = time.Minute // Time interval to check for evictable transactions
  69. statsReportInterval = 8 * time.Second // Time interval to report transaction pool stats
  70. )
  71. var (
  72. // Metrics for the pending pool
  73. pendingDiscardCounter = metrics.NewRegisteredCounter("txpool/pending/discard", nil)
  74. pendingReplaceCounter = metrics.NewRegisteredCounter("txpool/pending/replace", nil)
  75. pendingRateLimitCounter = metrics.NewRegisteredCounter("txpool/pending/ratelimit", nil) // Dropped due to rate limiting
  76. pendingNofundsCounter = metrics.NewRegisteredCounter("txpool/pending/nofunds", nil) // Dropped due to out-of-funds
  77. // Metrics for the queued pool
  78. queuedDiscardCounter = metrics.NewRegisteredCounter("txpool/queued/discard", nil)
  79. queuedReplaceCounter = metrics.NewRegisteredCounter("txpool/queued/replace", nil)
  80. queuedRateLimitCounter = metrics.NewRegisteredCounter("txpool/queued/ratelimit", nil) // Dropped due to rate limiting
  81. queuedNofundsCounter = metrics.NewRegisteredCounter("txpool/queued/nofunds", nil) // Dropped due to out-of-funds
  82. // General tx metrics
  83. invalidTxCounter = metrics.NewRegisteredCounter("txpool/invalid", nil)
  84. underpricedTxCounter = metrics.NewRegisteredCounter("txpool/underpriced", nil)
  85. )
  86. // TxStatus is the current status of a transaction as seen by the pool.
  87. type TxStatus uint
  88. const (
  89. TxStatusUnknown TxStatus = iota
  90. TxStatusQueued
  91. TxStatusPending
  92. TxStatusIncluded
  93. )
  94. // blockChain provides the state of blockchain and current gas limit to do
  95. // some pre checks in tx pool and event subscribers.
  96. type blockChain interface {
  97. CurrentBlock() *types.Block
  98. GetBlock(hash common.Hash, number uint64) *types.Block
  99. StateAt(root common.Hash) (*state.StateDB, error)
  100. SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
  101. }
  102. // TxPoolConfig are the configuration parameters of the transaction pool.
  103. type TxPoolConfig struct {
  104. Locals []common.Address // Addresses that should be treated by default as local
  105. NoLocals bool // Whether local transaction handling should be disabled
  106. Journal string // Journal of local transactions to survive node restarts
  107. Rejournal time.Duration // Time interval to regenerate the local transaction journal
  108. PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
  109. PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)
  110. AccountSlots uint64 // Number of executable transaction slots guaranteed per account
  111. GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts
  112. AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
  113. GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts
  114. Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
  115. }
  116. // DefaultTxPoolConfig contains the default configurations for the transaction
  117. // pool.
  118. var DefaultTxPoolConfig = TxPoolConfig{
  119. Journal: "transactions.rlp",
  120. Rejournal: time.Hour,
  121. PriceLimit: 1,
  122. PriceBump: 10,
  123. AccountSlots: 16,
  124. GlobalSlots: 4096,
  125. AccountQueue: 64,
  126. GlobalQueue: 1024,
  127. Lifetime: 3 * time.Hour,
  128. }
  129. // sanitize checks the provided user configurations and changes anything that's
  130. // unreasonable or unworkable.
  131. func (config *TxPoolConfig) sanitize() TxPoolConfig {
  132. conf := *config
  133. if conf.Rejournal < time.Second {
  134. log.Warn("Sanitizing invalid txpool journal time", "provided", conf.Rejournal, "updated", time.Second)
  135. conf.Rejournal = time.Second
  136. }
  137. if conf.PriceLimit < 1 {
  138. log.Warn("Sanitizing invalid txpool price limit", "provided", conf.PriceLimit, "updated", DefaultTxPoolConfig.PriceLimit)
  139. conf.PriceLimit = DefaultTxPoolConfig.PriceLimit
  140. }
  141. if conf.PriceBump < 1 {
  142. log.Warn("Sanitizing invalid txpool price bump", "provided", conf.PriceBump, "updated", DefaultTxPoolConfig.PriceBump)
  143. conf.PriceBump = DefaultTxPoolConfig.PriceBump
  144. }
  145. if conf.AccountSlots < 1 {
  146. log.Warn("Sanitizing invalid txpool account slots", "provided", conf.AccountSlots, "updated", DefaultTxPoolConfig.AccountSlots)
  147. conf.AccountSlots = DefaultTxPoolConfig.AccountSlots
  148. }
  149. if conf.GlobalSlots < 1 {
  150. log.Warn("Sanitizing invalid txpool global slots", "provided", conf.GlobalSlots, "updated", DefaultTxPoolConfig.GlobalSlots)
  151. conf.GlobalSlots = DefaultTxPoolConfig.GlobalSlots
  152. }
  153. if conf.AccountQueue < 1 {
  154. log.Warn("Sanitizing invalid txpool account queue", "provided", conf.AccountQueue, "updated", DefaultTxPoolConfig.AccountQueue)
  155. conf.AccountQueue = DefaultTxPoolConfig.AccountQueue
  156. }
  157. if conf.GlobalQueue < 1 {
  158. log.Warn("Sanitizing invalid txpool global queue", "provided", conf.GlobalQueue, "updated", DefaultTxPoolConfig.GlobalQueue)
  159. conf.GlobalQueue = DefaultTxPoolConfig.GlobalQueue
  160. }
  161. if conf.Lifetime < 1 {
  162. log.Warn("Sanitizing invalid txpool lifetime", "provided", conf.Lifetime, "updated", DefaultTxPoolConfig.Lifetime)
  163. conf.Lifetime = DefaultTxPoolConfig.Lifetime
  164. }
  165. return conf
  166. }
  167. // TxPool contains all currently known transactions. Transactions
  168. // enter the pool when they are received from the network or submitted
  169. // locally. They exit the pool when they are included in the blockchain.
  170. //
  171. // The pool separates processable transactions (which can be applied to the
  172. // current state) and future transactions. Transactions move between those
  173. // two states over time as they are received and processed.
  174. type TxPool struct {
  175. config TxPoolConfig
  176. chainconfig *params.ChainConfig
  177. chain blockChain
  178. gasPrice *big.Int
  179. txFeed event.Feed
  180. scope event.SubscriptionScope
  181. chainHeadCh chan ChainHeadEvent
  182. chainHeadSub event.Subscription
  183. signer types.Signer
  184. mu sync.RWMutex
  185. currentState *state.StateDB // Current state in the blockchain head
  186. pendingState *state.ManagedState // Pending state tracking virtual nonces
  187. currentMaxGas uint64 // Current gas limit for transaction caps
  188. locals *accountSet // Set of local transaction to exempt from eviction rules
  189. journal *txJournal // Journal of local transaction to back up to disk
  190. pending map[common.Address]*txList // All currently processable transactions
  191. queue map[common.Address]*txList // Queued but non-processable transactions
  192. beats map[common.Address]time.Time // Last heartbeat from each known account
  193. all *txLookup // All transactions to allow lookups
  194. priced *txPricedList // All transactions sorted by price
  195. wg sync.WaitGroup // for shutdown sync
  196. homestead bool
  197. }
  198. // NewTxPool creates a new transaction pool to gather, sort and filter inbound
  199. // transactions from the network.
  200. func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool {
  201. // Sanitize the input to ensure no vulnerable gas prices are set
  202. config = (&config).sanitize()
  203. // Create the transaction pool with its initial settings
  204. pool := &TxPool{
  205. config: config,
  206. chainconfig: chainconfig,
  207. chain: chain,
  208. signer: types.NewEIP155Signer(chainconfig.ChainID),
  209. pending: make(map[common.Address]*txList),
  210. queue: make(map[common.Address]*txList),
  211. beats: make(map[common.Address]time.Time),
  212. all: newTxLookup(),
  213. chainHeadCh: make(chan ChainHeadEvent, chainHeadChanSize),
  214. gasPrice: new(big.Int).SetUint64(config.PriceLimit),
  215. }
  216. pool.locals = newAccountSet(pool.signer)
  217. for _, addr := range config.Locals {
  218. log.Info("Setting new local account", "address", addr)
  219. pool.locals.add(addr)
  220. }
  221. pool.priced = newTxPricedList(pool.all)
  222. pool.reset(nil, chain.CurrentBlock().Header())
  223. // If local transactions and journaling is enabled, load from disk
  224. if !config.NoLocals && config.Journal != "" {
  225. pool.journal = newTxJournal(config.Journal)
  226. if err := pool.journal.load(pool.AddLocals); err != nil {
  227. log.Warn("Failed to load transaction journal", "err", err)
  228. }
  229. if err := pool.journal.rotate(pool.local()); err != nil {
  230. log.Warn("Failed to rotate transaction journal", "err", err)
  231. }
  232. }
  233. // Subscribe events from blockchain
  234. pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh)
  235. // Start the event loop and return
  236. pool.wg.Add(1)
  237. go pool.loop()
  238. return pool
  239. }
  240. // loop is the transaction pool's main event loop, waiting for and reacting to
  241. // outside blockchain events as well as for various reporting and transaction
  242. // eviction events.
  243. func (pool *TxPool) loop() {
  244. defer pool.wg.Done()
  245. // Start the stats reporting and transaction eviction tickers
  246. var prevPending, prevQueued, prevStales int
  247. report := time.NewTicker(statsReportInterval)
  248. defer report.Stop()
  249. evict := time.NewTicker(evictionInterval)
  250. defer evict.Stop()
  251. journal := time.NewTicker(pool.config.Rejournal)
  252. defer journal.Stop()
  253. // Track the previous head headers for transaction reorgs
  254. head := pool.chain.CurrentBlock()
  255. // Keep waiting for and reacting to the various events
  256. for {
  257. select {
  258. // Handle ChainHeadEvent
  259. case ev := <-pool.chainHeadCh:
  260. if ev.Block != nil {
  261. pool.mu.Lock()
  262. if pool.chainconfig.IsHomestead(ev.Block.Number()) {
  263. pool.homestead = true
  264. }
  265. pool.reset(head.Header(), ev.Block.Header())
  266. head = ev.Block
  267. pool.mu.Unlock()
  268. }
  269. // Be unsubscribed due to system stopped
  270. case <-pool.chainHeadSub.Err():
  271. return
  272. // Handle stats reporting ticks
  273. case <-report.C:
  274. pool.mu.RLock()
  275. pending, queued := pool.stats()
  276. stales := pool.priced.stales
  277. pool.mu.RUnlock()
  278. if pending != prevPending || queued != prevQueued || stales != prevStales {
  279. log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales)
  280. prevPending, prevQueued, prevStales = pending, queued, stales
  281. }
  282. // Handle inactive account transaction eviction
  283. case <-evict.C:
  284. pool.mu.Lock()
  285. for addr := range pool.queue {
  286. // Skip local transactions from the eviction mechanism
  287. if pool.locals.contains(addr) {
  288. continue
  289. }
  290. // Any non-locals old enough should be removed
  291. if time.Since(pool.beats[addr]) > pool.config.Lifetime {
  292. for _, tx := range pool.queue[addr].Flatten() {
  293. pool.removeTx(tx.Hash(), true)
  294. }
  295. }
  296. }
  297. pool.mu.Unlock()
  298. // Handle local transaction journal rotation
  299. case <-journal.C:
  300. if pool.journal != nil {
  301. pool.mu.Lock()
  302. if err := pool.journal.rotate(pool.local()); err != nil {
  303. log.Warn("Failed to rotate local tx journal", "err", err)
  304. }
  305. pool.mu.Unlock()
  306. }
  307. }
  308. }
  309. }
  310. // lockedReset is a wrapper around reset to allow calling it in a thread safe
  311. // manner. This method is only ever used in the tester!
  312. func (pool *TxPool) lockedReset(oldHead, newHead *types.Header) {
  313. pool.mu.Lock()
  314. defer pool.mu.Unlock()
  315. pool.reset(oldHead, newHead)
  316. }
  317. // reset retrieves the current state of the blockchain and ensures the content
  318. // of the transaction pool is valid with regard to the chain state.
  319. func (pool *TxPool) reset(oldHead, newHead *types.Header) {
  320. // If we're reorging an old state, reinject all dropped transactions
  321. var reinject types.Transactions
  322. if oldHead != nil && oldHead.Hash() != newHead.ParentHash {
  323. // If the reorg is too deep, avoid doing it (will happen during fast sync)
  324. oldNum := oldHead.Number.Uint64()
  325. newNum := newHead.Number.Uint64()
  326. if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 {
  327. log.Debug("Skipping deep transaction reorg", "depth", depth)
  328. } else {
  329. // Reorg seems shallow enough to pull in all transactions into memory
  330. var discarded, included types.Transactions
  331. var (
  332. rem = pool.chain.GetBlock(oldHead.Hash(), oldHead.Number.Uint64())
  333. add = pool.chain.GetBlock(newHead.Hash(), newHead.Number.Uint64())
  334. )
  335. for rem.NumberU64() > add.NumberU64() {
  336. discarded = append(discarded, rem.Transactions()...)
  337. if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  338. log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  339. return
  340. }
  341. }
  342. for add.NumberU64() > rem.NumberU64() {
  343. included = append(included, add.Transactions()...)
  344. if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  345. log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  346. return
  347. }
  348. }
  349. for rem.Hash() != add.Hash() {
  350. discarded = append(discarded, rem.Transactions()...)
  351. if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  352. log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  353. return
  354. }
  355. included = append(included, add.Transactions()...)
  356. if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  357. log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  358. return
  359. }
  360. }
  361. reinject = types.TxDifference(discarded, included)
  362. }
  363. }
  364. // Initialize the internal state to the current head
  365. if newHead == nil {
  366. newHead = pool.chain.CurrentBlock().Header() // Special case during testing
  367. }
  368. statedb, err := pool.chain.StateAt(newHead.Root)
  369. if err != nil {
  370. log.Error("Failed to reset txpool state", "err", err)
  371. return
  372. }
  373. pool.currentState = statedb
  374. pool.pendingState = state.ManageState(statedb)
  375. pool.currentMaxGas = newHead.GasLimit
  376. // Inject any transactions discarded due to reorgs
  377. log.Debug("Reinjecting stale transactions", "count", len(reinject))
  378. senderCacher.recover(pool.signer, reinject)
  379. pool.addTxsLocked(reinject, false)
  380. // validate the pool of pending transactions, this will remove
  381. // any transactions that have been included in the block or
  382. // have been invalidated because of another transaction (e.g.
  383. // higher gas price)
  384. pool.demoteUnexecutables()
  385. // Update all accounts to the latest known pending nonce
  386. for addr, list := range pool.pending {
  387. txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway
  388. pool.pendingState.SetNonce(addr, txs[len(txs)-1].Nonce()+1)
  389. }
  390. // Check the queue and move transactions over to the pending if possible
  391. // or remove those that have become invalid
  392. pool.promoteExecutables(nil)
  393. }
  394. // Stop terminates the transaction pool.
  395. func (pool *TxPool) Stop() {
  396. // Unsubscribe all subscriptions registered from txpool
  397. pool.scope.Close()
  398. // Unsubscribe subscriptions registered from blockchain
  399. pool.chainHeadSub.Unsubscribe()
  400. pool.wg.Wait()
  401. if pool.journal != nil {
  402. pool.journal.close()
  403. }
  404. log.Info("Transaction pool stopped")
  405. }
  406. // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
  407. // starts sending event to the given channel.
  408. func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
  409. return pool.scope.Track(pool.txFeed.Subscribe(ch))
  410. }
  411. // GasPrice returns the current gas price enforced by the transaction pool.
  412. func (pool *TxPool) GasPrice() *big.Int {
  413. pool.mu.RLock()
  414. defer pool.mu.RUnlock()
  415. return new(big.Int).Set(pool.gasPrice)
  416. }
  417. // SetGasPrice updates the minimum price required by the transaction pool for a
  418. // new transaction, and drops all transactions below this threshold.
  419. func (pool *TxPool) SetGasPrice(price *big.Int) {
  420. pool.mu.Lock()
  421. defer pool.mu.Unlock()
  422. pool.gasPrice = price
  423. for _, tx := range pool.priced.Cap(price, pool.locals) {
  424. pool.removeTx(tx.Hash(), false)
  425. }
  426. log.Info("Transaction pool price threshold updated", "price", price)
  427. }
  428. // State returns the virtual managed state of the transaction pool.
  429. func (pool *TxPool) State() *state.ManagedState {
  430. pool.mu.RLock()
  431. defer pool.mu.RUnlock()
  432. return pool.pendingState
  433. }
  434. // Stats retrieves the current pool stats, namely the number of pending and the
  435. // number of queued (non-executable) transactions.
  436. func (pool *TxPool) Stats() (int, int) {
  437. pool.mu.RLock()
  438. defer pool.mu.RUnlock()
  439. return pool.stats()
  440. }
  441. // stats retrieves the current pool stats, namely the number of pending and the
  442. // number of queued (non-executable) transactions.
  443. func (pool *TxPool) stats() (int, int) {
  444. pending := 0
  445. for _, list := range pool.pending {
  446. pending += list.Len()
  447. }
  448. queued := 0
  449. for _, list := range pool.queue {
  450. queued += list.Len()
  451. }
  452. return pending, queued
  453. }
  454. // Content retrieves the data content of the transaction pool, returning all the
  455. // pending as well as queued transactions, grouped by account and sorted by nonce.
  456. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  457. pool.mu.Lock()
  458. defer pool.mu.Unlock()
  459. pending := make(map[common.Address]types.Transactions)
  460. for addr, list := range pool.pending {
  461. pending[addr] = list.Flatten()
  462. }
  463. queued := make(map[common.Address]types.Transactions)
  464. for addr, list := range pool.queue {
  465. queued[addr] = list.Flatten()
  466. }
  467. return pending, queued
  468. }
  469. // Pending retrieves all currently processable transactions, grouped by origin
  470. // account and sorted by nonce. The returned transaction set is a copy and can be
  471. // freely modified by calling code.
  472. func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
  473. pool.mu.Lock()
  474. defer pool.mu.Unlock()
  475. pending := make(map[common.Address]types.Transactions)
  476. for addr, list := range pool.pending {
  477. pending[addr] = list.Flatten()
  478. }
  479. return pending, nil
  480. }
  481. // Locals retrieves the accounts currently considered local by the pool.
  482. func (pool *TxPool) Locals() []common.Address {
  483. pool.mu.Lock()
  484. defer pool.mu.Unlock()
  485. return pool.locals.flatten()
  486. }
  487. // local retrieves all currently known local transactions, grouped by origin
  488. // account and sorted by nonce. The returned transaction set is a copy and can be
  489. // freely modified by calling code.
  490. func (pool *TxPool) local() map[common.Address]types.Transactions {
  491. txs := make(map[common.Address]types.Transactions)
  492. for addr := range pool.locals.accounts {
  493. if pending := pool.pending[addr]; pending != nil {
  494. txs[addr] = append(txs[addr], pending.Flatten()...)
  495. }
  496. if queued := pool.queue[addr]; queued != nil {
  497. txs[addr] = append(txs[addr], queued.Flatten()...)
  498. }
  499. }
  500. return txs
  501. }
  502. // validateTx checks whether a transaction is valid according to the consensus
  503. // rules and adheres to some heuristic limits of the local node (price and size).
  504. func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
  505. // Heuristic limit, reject transactions over 32KB to prevent DOS attacks
  506. if tx.Size() > 32*1024 {
  507. return ErrOversizedData
  508. }
  509. // Transactions can't be negative. This may never happen using RLP decoded
  510. // transactions but may occur if you create a transaction using the RPC.
  511. if tx.Value().Sign() < 0 {
  512. return ErrNegativeValue
  513. }
  514. // Ensure the transaction doesn't exceed the current block limit gas.
  515. if pool.currentMaxGas < tx.Gas() {
  516. return ErrGasLimit
  517. }
  518. // Make sure the transaction is signed properly
  519. from, err := types.Sender(pool.signer, tx)
  520. if err != nil {
  521. return ErrInvalidSender
  522. }
  523. // Drop non-local transactions under our own minimal accepted gas price
  524. local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network
  525. if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 {
  526. return ErrUnderpriced
  527. }
  528. // Ensure the transaction adheres to nonce ordering
  529. if pool.currentState.GetNonce(from) > tx.Nonce() {
  530. return ErrNonceTooLow
  531. }
  532. // Transactor should have enough funds to cover the costs
  533. // cost == V + GP * GL
  534. if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  535. return ErrInsufficientFunds
  536. }
  537. intrGas, err := IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead)
  538. if err != nil {
  539. return err
  540. }
  541. if tx.Gas() < intrGas {
  542. return ErrIntrinsicGas
  543. }
  544. return nil
  545. }
  546. // add validates a transaction and inserts it into the non-executable queue for
  547. // later pending promotion and execution. If the transaction is a replacement for
  548. // an already pending or queued one, it overwrites the previous and returns this
  549. // so outer code doesn't uselessly call promote.
  550. //
  551. // If a newly added transaction is marked as local, its sending account will be
  552. // whitelisted, preventing any associated transaction from being dropped out of
  553. // the pool due to pricing constraints.
  554. func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
  555. // If the transaction is already known, discard it
  556. hash := tx.Hash()
  557. if pool.all.Get(hash) != nil {
  558. log.Trace("Discarding already known transaction", "hash", hash)
  559. return false, fmt.Errorf("known transaction: %x", hash)
  560. }
  561. // If the transaction fails basic validation, discard it
  562. if err := pool.validateTx(tx, local); err != nil {
  563. log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
  564. invalidTxCounter.Inc(1)
  565. return false, err
  566. }
  567. // If the transaction pool is full, discard underpriced transactions
  568. if uint64(pool.all.Count()) >= pool.config.GlobalSlots+pool.config.GlobalQueue {
  569. // If the new transaction is underpriced, don't accept it
  570. if !local && pool.priced.Underpriced(tx, pool.locals) {
  571. log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
  572. underpricedTxCounter.Inc(1)
  573. return false, ErrUnderpriced
  574. }
  575. // New transaction is better than our worse ones, make room for it
  576. drop := pool.priced.Discard(pool.all.Count()-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals)
  577. for _, tx := range drop {
  578. log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
  579. underpricedTxCounter.Inc(1)
  580. pool.removeTx(tx.Hash(), false)
  581. }
  582. }
  583. // If the transaction is replacing an already pending one, do directly
  584. from, _ := types.Sender(pool.signer, tx) // already validated
  585. if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
  586. // Nonce already pending, check if required price bump is met
  587. inserted, old := list.Add(tx, pool.config.PriceBump)
  588. if !inserted {
  589. pendingDiscardCounter.Inc(1)
  590. return false, ErrReplaceUnderpriced
  591. }
  592. // New transaction is better, replace old one
  593. if old != nil {
  594. pool.all.Remove(old.Hash())
  595. pool.priced.Removed()
  596. pendingReplaceCounter.Inc(1)
  597. }
  598. pool.all.Add(tx)
  599. pool.priced.Put(tx)
  600. pool.journalTx(from, tx)
  601. log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
  602. // We've directly injected a replacement transaction, notify subsystems
  603. go pool.txFeed.Send(NewTxsEvent{types.Transactions{tx}})
  604. return old != nil, nil
  605. }
  606. // New transaction isn't replacing a pending one, push into queue
  607. replace, err := pool.enqueueTx(hash, tx)
  608. if err != nil {
  609. return false, err
  610. }
  611. // Mark local addresses and journal local transactions
  612. if local {
  613. if !pool.locals.contains(from) {
  614. log.Info("Setting new local account", "address", from)
  615. pool.locals.add(from)
  616. }
  617. }
  618. pool.journalTx(from, tx)
  619. log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
  620. return replace, nil
  621. }
  622. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  623. //
  624. // Note, this method assumes the pool lock is held!
  625. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) {
  626. // Try to insert the transaction into the future queue
  627. from, _ := types.Sender(pool.signer, tx) // already validated
  628. if pool.queue[from] == nil {
  629. pool.queue[from] = newTxList(false)
  630. }
  631. inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
  632. if !inserted {
  633. // An older transaction was better, discard this
  634. queuedDiscardCounter.Inc(1)
  635. return false, ErrReplaceUnderpriced
  636. }
  637. // Discard any previous transaction and mark this
  638. if old != nil {
  639. pool.all.Remove(old.Hash())
  640. pool.priced.Removed()
  641. queuedReplaceCounter.Inc(1)
  642. }
  643. if pool.all.Get(hash) == nil {
  644. pool.all.Add(tx)
  645. pool.priced.Put(tx)
  646. }
  647. return old != nil, nil
  648. }
  649. // journalTx adds the specified transaction to the local disk journal if it is
  650. // deemed to have been sent from a local account.
  651. func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
  652. // Only journal if it's enabled and the transaction is local
  653. if pool.journal == nil || !pool.locals.contains(from) {
  654. return
  655. }
  656. if err := pool.journal.insert(tx); err != nil {
  657. log.Warn("Failed to journal local transaction", "err", err)
  658. }
  659. }
  660. // promoteTx adds a transaction to the pending (processable) list of transactions
  661. // and returns whether it was inserted or an older was better.
  662. //
  663. // Note, this method assumes the pool lock is held!
  664. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool {
  665. // Try to insert the transaction into the pending queue
  666. if pool.pending[addr] == nil {
  667. pool.pending[addr] = newTxList(true)
  668. }
  669. list := pool.pending[addr]
  670. inserted, old := list.Add(tx, pool.config.PriceBump)
  671. if !inserted {
  672. // An older transaction was better, discard this
  673. pool.all.Remove(hash)
  674. pool.priced.Removed()
  675. pendingDiscardCounter.Inc(1)
  676. return false
  677. }
  678. // Otherwise discard any previous transaction and mark this
  679. if old != nil {
  680. pool.all.Remove(old.Hash())
  681. pool.priced.Removed()
  682. pendingReplaceCounter.Inc(1)
  683. }
  684. // Failsafe to work around direct pending inserts (tests)
  685. if pool.all.Get(hash) == nil {
  686. pool.all.Add(tx)
  687. pool.priced.Put(tx)
  688. }
  689. // Set the potentially new pending nonce and notify any subsystems of the new tx
  690. pool.beats[addr] = time.Now()
  691. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  692. return true
  693. }
  694. // AddLocal enqueues a single transaction into the pool if it is valid, marking
  695. // the sender as a local one in the mean time, ensuring it goes around the local
  696. // pricing constraints.
  697. func (pool *TxPool) AddLocal(tx *types.Transaction) error {
  698. return pool.addTx(tx, !pool.config.NoLocals)
  699. }
  700. // AddRemote enqueues a single transaction into the pool if it is valid. If the
  701. // sender is not among the locally tracked ones, full pricing constraints will
  702. // apply.
  703. func (pool *TxPool) AddRemote(tx *types.Transaction) error {
  704. return pool.addTx(tx, false)
  705. }
  706. // AddLocals enqueues a batch of transactions into the pool if they are valid,
  707. // marking the senders as a local ones in the mean time, ensuring they go around
  708. // the local pricing constraints.
  709. func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
  710. return pool.addTxs(txs, !pool.config.NoLocals)
  711. }
  712. // AddRemotes enqueues a batch of transactions into the pool if they are valid.
  713. // If the senders are not among the locally tracked ones, full pricing constraints
  714. // will apply.
  715. func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
  716. return pool.addTxs(txs, false)
  717. }
  718. // addTx enqueues a single transaction into the pool if it is valid.
  719. func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
  720. pool.mu.Lock()
  721. defer pool.mu.Unlock()
  722. // Try to inject the transaction and update any state
  723. replace, err := pool.add(tx, local)
  724. if err != nil {
  725. return err
  726. }
  727. // If we added a new transaction, run promotion checks and return
  728. if !replace {
  729. from, _ := types.Sender(pool.signer, tx) // already validated
  730. pool.promoteExecutables([]common.Address{from})
  731. }
  732. return nil
  733. }
  734. // addTxs attempts to queue a batch of transactions if they are valid.
  735. func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) []error {
  736. pool.mu.Lock()
  737. defer pool.mu.Unlock()
  738. return pool.addTxsLocked(txs, local)
  739. }
  740. // addTxsLocked attempts to queue a batch of transactions if they are valid,
  741. // whilst assuming the transaction pool lock is already held.
  742. func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) []error {
  743. // Add the batch of transactions, tracking the accepted ones
  744. dirty := make(map[common.Address]struct{})
  745. errs := make([]error, len(txs))
  746. for i, tx := range txs {
  747. var replace bool
  748. if replace, errs[i] = pool.add(tx, local); errs[i] == nil && !replace {
  749. from, _ := types.Sender(pool.signer, tx) // already validated
  750. dirty[from] = struct{}{}
  751. }
  752. }
  753. // Only reprocess the internal state if something was actually added
  754. if len(dirty) > 0 {
  755. addrs := make([]common.Address, 0, len(dirty))
  756. for addr := range dirty {
  757. addrs = append(addrs, addr)
  758. }
  759. pool.promoteExecutables(addrs)
  760. }
  761. return errs
  762. }
  763. // Status returns the status (unknown/pending/queued) of a batch of transactions
  764. // identified by their hashes.
  765. func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
  766. pool.mu.RLock()
  767. defer pool.mu.RUnlock()
  768. status := make([]TxStatus, len(hashes))
  769. for i, hash := range hashes {
  770. if tx := pool.all.Get(hash); tx != nil {
  771. from, _ := types.Sender(pool.signer, tx) // already validated
  772. if pool.pending[from] != nil && pool.pending[from].txs.items[tx.Nonce()] != nil {
  773. status[i] = TxStatusPending
  774. } else {
  775. status[i] = TxStatusQueued
  776. }
  777. }
  778. }
  779. return status
  780. }
  781. // Get returns a transaction if it is contained in the pool
  782. // and nil otherwise.
  783. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  784. return pool.all.Get(hash)
  785. }
  786. // removeTx removes a single transaction from the queue, moving all subsequent
  787. // transactions back to the future queue.
  788. func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {
  789. // Fetch the transaction we wish to delete
  790. tx := pool.all.Get(hash)
  791. if tx == nil {
  792. return
  793. }
  794. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  795. // Remove it from the list of known transactions
  796. pool.all.Remove(hash)
  797. if outofbound {
  798. pool.priced.Removed()
  799. }
  800. // Remove the transaction from the pending lists and reset the account nonce
  801. if pending := pool.pending[addr]; pending != nil {
  802. if removed, invalids := pending.Remove(tx); removed {
  803. // If no more pending transactions are left, remove the list
  804. if pending.Empty() {
  805. delete(pool.pending, addr)
  806. delete(pool.beats, addr)
  807. }
  808. // Postpone any invalidated transactions
  809. for _, tx := range invalids {
  810. pool.enqueueTx(tx.Hash(), tx)
  811. }
  812. // Update the account nonce if needed
  813. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  814. pool.pendingState.SetNonce(addr, nonce)
  815. }
  816. return
  817. }
  818. }
  819. // Transaction is in the future queue
  820. if future := pool.queue[addr]; future != nil {
  821. future.Remove(tx)
  822. if future.Empty() {
  823. delete(pool.queue, addr)
  824. }
  825. }
  826. }
  827. // promoteExecutables moves transactions that have become processable from the
  828. // future queue to the set of pending transactions. During this process, all
  829. // invalidated transactions (low nonce, low balance) are deleted.
  830. func (pool *TxPool) promoteExecutables(accounts []common.Address) {
  831. // Track the promoted transactions to broadcast them at once
  832. var promoted []*types.Transaction
  833. // Gather all the accounts potentially needing updates
  834. if accounts == nil {
  835. accounts = make([]common.Address, 0, len(pool.queue))
  836. for addr := range pool.queue {
  837. accounts = append(accounts, addr)
  838. }
  839. }
  840. // Iterate over all accounts and promote any executable transactions
  841. for _, addr := range accounts {
  842. list := pool.queue[addr]
  843. if list == nil {
  844. continue // Just in case someone calls with a non existing account
  845. }
  846. // Drop all transactions that are deemed too old (low nonce)
  847. for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) {
  848. hash := tx.Hash()
  849. log.Trace("Removed old queued transaction", "hash", hash)
  850. pool.all.Remove(hash)
  851. pool.priced.Removed()
  852. }
  853. // Drop all transactions that are too costly (low balance or out of gas)
  854. drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  855. for _, tx := range drops {
  856. hash := tx.Hash()
  857. log.Trace("Removed unpayable queued transaction", "hash", hash)
  858. pool.all.Remove(hash)
  859. pool.priced.Removed()
  860. queuedNofundsCounter.Inc(1)
  861. }
  862. // Gather all executable transactions and promote them
  863. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  864. hash := tx.Hash()
  865. if pool.promoteTx(addr, hash, tx) {
  866. log.Trace("Promoting queued transaction", "hash", hash)
  867. promoted = append(promoted, tx)
  868. }
  869. }
  870. // Drop all transactions over the allowed limit
  871. if !pool.locals.contains(addr) {
  872. for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
  873. hash := tx.Hash()
  874. pool.all.Remove(hash)
  875. pool.priced.Removed()
  876. queuedRateLimitCounter.Inc(1)
  877. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  878. }
  879. }
  880. // Delete the entire queue entry if it became empty.
  881. if list.Empty() {
  882. delete(pool.queue, addr)
  883. }
  884. }
  885. // Notify subsystem for new promoted transactions.
  886. if len(promoted) > 0 {
  887. go pool.txFeed.Send(NewTxsEvent{promoted})
  888. }
  889. // If the pending limit is overflown, start equalizing allowances
  890. pending := uint64(0)
  891. for _, list := range pool.pending {
  892. pending += uint64(list.Len())
  893. }
  894. if pending > pool.config.GlobalSlots {
  895. pendingBeforeCap := pending
  896. // Assemble a spam order to penalize large transactors first
  897. spammers := prque.New(nil)
  898. for addr, list := range pool.pending {
  899. // Only evict transactions from high rollers
  900. if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  901. spammers.Push(addr, int64(list.Len()))
  902. }
  903. }
  904. // Gradually drop transactions from offenders
  905. offenders := []common.Address{}
  906. for pending > pool.config.GlobalSlots && !spammers.Empty() {
  907. // Retrieve the next offender if not local address
  908. offender, _ := spammers.Pop()
  909. offenders = append(offenders, offender.(common.Address))
  910. // Equalize balances until all the same or below threshold
  911. if len(offenders) > 1 {
  912. // Calculate the equalization threshold for all current offenders
  913. threshold := pool.pending[offender.(common.Address)].Len()
  914. // Iteratively reduce all offenders until below limit or threshold reached
  915. for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  916. for i := 0; i < len(offenders)-1; i++ {
  917. list := pool.pending[offenders[i]]
  918. for _, tx := range list.Cap(list.Len() - 1) {
  919. // Drop the transaction from the global pools too
  920. hash := tx.Hash()
  921. pool.all.Remove(hash)
  922. pool.priced.Removed()
  923. // Update the account nonce to the dropped transaction
  924. if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce {
  925. pool.pendingState.SetNonce(offenders[i], nonce)
  926. }
  927. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  928. }
  929. pending--
  930. }
  931. }
  932. }
  933. }
  934. // If still above threshold, reduce to limit or min allowance
  935. if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  936. for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  937. for _, addr := range offenders {
  938. list := pool.pending[addr]
  939. for _, tx := range list.Cap(list.Len() - 1) {
  940. // Drop the transaction from the global pools too
  941. hash := tx.Hash()
  942. pool.all.Remove(hash)
  943. pool.priced.Removed()
  944. // Update the account nonce to the dropped transaction
  945. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  946. pool.pendingState.SetNonce(addr, nonce)
  947. }
  948. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  949. }
  950. pending--
  951. }
  952. }
  953. }
  954. pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending))
  955. }
  956. // If we've queued more transactions than the hard limit, drop oldest ones
  957. queued := uint64(0)
  958. for _, list := range pool.queue {
  959. queued += uint64(list.Len())
  960. }
  961. if queued > pool.config.GlobalQueue {
  962. // Sort all accounts with queued transactions by heartbeat
  963. addresses := make(addressesByHeartbeat, 0, len(pool.queue))
  964. for addr := range pool.queue {
  965. if !pool.locals.contains(addr) { // don't drop locals
  966. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  967. }
  968. }
  969. sort.Sort(addresses)
  970. // Drop transactions until the total is below the limit or only locals remain
  971. for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  972. addr := addresses[len(addresses)-1]
  973. list := pool.queue[addr.address]
  974. addresses = addresses[:len(addresses)-1]
  975. // Drop all transactions if they are less than the overflow
  976. if size := uint64(list.Len()); size <= drop {
  977. for _, tx := range list.Flatten() {
  978. pool.removeTx(tx.Hash(), true)
  979. }
  980. drop -= size
  981. queuedRateLimitCounter.Inc(int64(size))
  982. continue
  983. }
  984. // Otherwise drop only last few transactions
  985. txs := list.Flatten()
  986. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  987. pool.removeTx(txs[i].Hash(), true)
  988. drop--
  989. queuedRateLimitCounter.Inc(1)
  990. }
  991. }
  992. }
  993. }
  994. // demoteUnexecutables removes invalid and processed transactions from the pools
  995. // executable/pending queue and any subsequent transactions that become unexecutable
  996. // are moved back into the future queue.
  997. func (pool *TxPool) demoteUnexecutables() {
  998. // Iterate over all accounts and demote any non-executable transactions
  999. for addr, list := range pool.pending {
  1000. nonce := pool.currentState.GetNonce(addr)
  1001. // Drop all transactions that are deemed too old (low nonce)
  1002. for _, tx := range list.Forward(nonce) {
  1003. hash := tx.Hash()
  1004. log.Trace("Removed old pending transaction", "hash", hash)
  1005. pool.all.Remove(hash)
  1006. pool.priced.Removed()
  1007. }
  1008. // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  1009. drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  1010. for _, tx := range drops {
  1011. hash := tx.Hash()
  1012. log.Trace("Removed unpayable pending transaction", "hash", hash)
  1013. pool.all.Remove(hash)
  1014. pool.priced.Removed()
  1015. pendingNofundsCounter.Inc(1)
  1016. }
  1017. for _, tx := range invalids {
  1018. hash := tx.Hash()
  1019. log.Trace("Demoting pending transaction", "hash", hash)
  1020. pool.enqueueTx(hash, tx)
  1021. }
  1022. // If there's a gap in front, alert (should never happen) and postpone all transactions
  1023. if list.Len() > 0 && list.txs.Get(nonce) == nil {
  1024. for _, tx := range list.Cap(0) {
  1025. hash := tx.Hash()
  1026. log.Error("Demoting invalidated transaction", "hash", hash)
  1027. pool.enqueueTx(hash, tx)
  1028. }
  1029. }
  1030. // Delete the entire queue entry if it became empty.
  1031. if list.Empty() {
  1032. delete(pool.pending, addr)
  1033. delete(pool.beats, addr)
  1034. }
  1035. }
  1036. }
  1037. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  1038. type addressByHeartbeat struct {
  1039. address common.Address
  1040. heartbeat time.Time
  1041. }
  1042. type addressesByHeartbeat []addressByHeartbeat
  1043. func (a addressesByHeartbeat) Len() int { return len(a) }
  1044. func (a addressesByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  1045. func (a addressesByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  1046. // accountSet is simply a set of addresses to check for existence, and a signer
  1047. // capable of deriving addresses from transactions.
  1048. type accountSet struct {
  1049. accounts map[common.Address]struct{}
  1050. signer types.Signer
  1051. cache *[]common.Address
  1052. }
  1053. // newAccountSet creates a new address set with an associated signer for sender
  1054. // derivations.
  1055. func newAccountSet(signer types.Signer) *accountSet {
  1056. return &accountSet{
  1057. accounts: make(map[common.Address]struct{}),
  1058. signer: signer,
  1059. }
  1060. }
  1061. // contains checks if a given address is contained within the set.
  1062. func (as *accountSet) contains(addr common.Address) bool {
  1063. _, exist := as.accounts[addr]
  1064. return exist
  1065. }
  1066. // containsTx checks if the sender of a given tx is within the set. If the sender
  1067. // cannot be derived, this method returns false.
  1068. func (as *accountSet) containsTx(tx *types.Transaction) bool {
  1069. if addr, err := types.Sender(as.signer, tx); err == nil {
  1070. return as.contains(addr)
  1071. }
  1072. return false
  1073. }
  1074. // add inserts a new address into the set to track.
  1075. func (as *accountSet) add(addr common.Address) {
  1076. as.accounts[addr] = struct{}{}
  1077. as.cache = nil
  1078. }
  1079. // flatten returns the list of addresses within this set, also caching it for later
  1080. // reuse. The returned slice should not be changed!
  1081. func (as *accountSet) flatten() []common.Address {
  1082. if as.cache == nil {
  1083. accounts := make([]common.Address, 0, len(as.accounts))
  1084. for account := range as.accounts {
  1085. accounts = append(accounts, account)
  1086. }
  1087. as.cache = &accounts
  1088. }
  1089. return *as.cache
  1090. }
  1091. // txLookup is used internally by TxPool to track transactions while allowing lookup without
  1092. // mutex contention.
  1093. //
  1094. // Note, although this type is properly protected against concurrent access, it
  1095. // is **not** a type that should ever be mutated or even exposed outside of the
  1096. // transaction pool, since its internal state is tightly coupled with the pools
  1097. // internal mechanisms. The sole purpose of the type is to permit out-of-bound
  1098. // peeking into the pool in TxPool.Get without having to acquire the widely scoped
  1099. // TxPool.mu mutex.
  1100. type txLookup struct {
  1101. all map[common.Hash]*types.Transaction
  1102. lock sync.RWMutex
  1103. }
  1104. // newTxLookup returns a new txLookup structure.
  1105. func newTxLookup() *txLookup {
  1106. return &txLookup{
  1107. all: make(map[common.Hash]*types.Transaction),
  1108. }
  1109. }
  1110. // Range calls f on each key and value present in the map.
  1111. func (t *txLookup) Range(f func(hash common.Hash, tx *types.Transaction) bool) {
  1112. t.lock.RLock()
  1113. defer t.lock.RUnlock()
  1114. for key, value := range t.all {
  1115. if !f(key, value) {
  1116. break
  1117. }
  1118. }
  1119. }
  1120. // Get returns a transaction if it exists in the lookup, or nil if not found.
  1121. func (t *txLookup) Get(hash common.Hash) *types.Transaction {
  1122. t.lock.RLock()
  1123. defer t.lock.RUnlock()
  1124. return t.all[hash]
  1125. }
  1126. // Count returns the current number of items in the lookup.
  1127. func (t *txLookup) Count() int {
  1128. t.lock.RLock()
  1129. defer t.lock.RUnlock()
  1130. return len(t.all)
  1131. }
  1132. // Add adds a transaction to the lookup.
  1133. func (t *txLookup) Add(tx *types.Transaction) {
  1134. t.lock.Lock()
  1135. defer t.lock.Unlock()
  1136. t.all[tx.Hash()] = tx
  1137. }
  1138. // Remove removes a transaction from the lookup.
  1139. func (t *txLookup) Remove(hash common.Hash) {
  1140. t.lock.Lock()
  1141. defer t.lock.Unlock()
  1142. delete(t.all, hash)
  1143. }