tx_pool.go 47 KB

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