tx_pool.go 53 KB

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