tx_pool.go 51 KB

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