tx_pool.go 54 KB

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