tx_pool.go 51 KB

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