tx_pool.go 54 KB

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