tx_pool.go 52 KB

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