tx_pool.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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/big"
  21. "sort"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/core/state"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/event"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/metrics"
  30. "github.com/ethereum/go-ethereum/params"
  31. "gopkg.in/karalabe/cookiejar.v2/collections/prque"
  32. )
  33. const (
  34. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  35. chainHeadChanSize = 10
  36. // rmTxChanSize is the size of channel listening to RemovedTransactionEvent.
  37. rmTxChanSize = 10
  38. )
  39. var (
  40. // ErrInvalidSender is returned if the transaction contains an invalid signature.
  41. ErrInvalidSender = errors.New("invalid sender")
  42. // ErrNonceTooLow is returned if the nonce of a transaction is lower than the
  43. // one present in the local chain.
  44. ErrNonceTooLow = errors.New("nonce too low")
  45. // ErrUnderpriced is returned if a transaction's gas price is below the minimum
  46. // configured for the transaction pool.
  47. ErrUnderpriced = errors.New("transaction underpriced")
  48. // ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
  49. // with a different one without the required price bump.
  50. ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")
  51. // ErrInsufficientFunds is returned if the total cost of executing a transaction
  52. // is higher than the balance of the user's account.
  53. ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value")
  54. // ErrIntrinsicGas is returned if the transaction is specified to use less gas
  55. // than required to start the invocation.
  56. ErrIntrinsicGas = errors.New("intrinsic gas too low")
  57. // ErrGasLimit is returned if a transaction's requested gas limit exceeds the
  58. // maximum allowance of the current block.
  59. ErrGasLimit = errors.New("exceeds block gas limit")
  60. // ErrNegativeValue is a sanity error to ensure noone is able to specify a
  61. // transaction with a negative value.
  62. ErrNegativeValue = errors.New("negative value")
  63. // ErrOversizedData is returned if the input data of a transaction is greater
  64. // than some meaningful limit a user might use. This is not a consensus error
  65. // making the transaction invalid, rather a DOS protection.
  66. ErrOversizedData = errors.New("oversized data")
  67. )
  68. var (
  69. evictionInterval = time.Minute // Time interval to check for evictable transactions
  70. statsReportInterval = 8 * time.Second // Time interval to report transaction pool stats
  71. )
  72. var (
  73. // Metrics for the pending pool
  74. pendingDiscardCounter = metrics.NewCounter("txpool/pending/discard")
  75. pendingReplaceCounter = metrics.NewCounter("txpool/pending/replace")
  76. pendingRateLimitCounter = metrics.NewCounter("txpool/pending/ratelimit") // Dropped due to rate limiting
  77. pendingNofundsCounter = metrics.NewCounter("txpool/pending/nofunds") // Dropped due to out-of-funds
  78. // Metrics for the queued pool
  79. queuedDiscardCounter = metrics.NewCounter("txpool/queued/discard")
  80. queuedReplaceCounter = metrics.NewCounter("txpool/queued/replace")
  81. queuedRateLimitCounter = metrics.NewCounter("txpool/queued/ratelimit") // Dropped due to rate limiting
  82. queuedNofundsCounter = metrics.NewCounter("txpool/queued/nofunds") // Dropped due to out-of-funds
  83. // General tx metrics
  84. invalidTxCounter = metrics.NewCounter("txpool/invalid")
  85. underpricedTxCounter = metrics.NewCounter("txpool/underpriced")
  86. )
  87. // blockChain provides the state of blockchain and current gas limit to do
  88. // some pre checks in tx pool and event subscribers.
  89. type blockChain interface {
  90. CurrentHeader() *types.Header
  91. SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
  92. GetBlock(hash common.Hash, number uint64) *types.Block
  93. StateAt(root common.Hash) (*state.StateDB, error)
  94. }
  95. // TxPoolConfig are the configuration parameters of the transaction pool.
  96. type TxPoolConfig struct {
  97. NoLocals bool // Whether local transaction handling should be disabled
  98. Journal string // Journal of local transactions to survive node restarts
  99. Rejournal time.Duration // Time interval to regenerate the local transaction journal
  100. PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
  101. PriceBump uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)
  102. AccountSlots uint64 // Minimum number of executable transaction slots guaranteed per account
  103. GlobalSlots uint64 // Maximum number of executable transaction slots for all accounts
  104. AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
  105. GlobalQueue uint64 // Maximum number of non-executable transaction slots for all accounts
  106. Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
  107. }
  108. // DefaultTxPoolConfig contains the default configurations for the transaction
  109. // pool.
  110. var DefaultTxPoolConfig = TxPoolConfig{
  111. Journal: "transactions.rlp",
  112. Rejournal: time.Hour,
  113. PriceLimit: 1,
  114. PriceBump: 10,
  115. AccountSlots: 16,
  116. GlobalSlots: 4096,
  117. AccountQueue: 64,
  118. GlobalQueue: 1024,
  119. Lifetime: 3 * time.Hour,
  120. }
  121. // sanitize checks the provided user configurations and changes anything that's
  122. // unreasonable or unworkable.
  123. func (config *TxPoolConfig) sanitize() TxPoolConfig {
  124. conf := *config
  125. if conf.Rejournal < time.Second {
  126. log.Warn("Sanitizing invalid txpool journal time", "provided", conf.Rejournal, "updated", time.Second)
  127. conf.Rejournal = time.Second
  128. }
  129. if conf.PriceLimit < 1 {
  130. log.Warn("Sanitizing invalid txpool price limit", "provided", conf.PriceLimit, "updated", DefaultTxPoolConfig.PriceLimit)
  131. conf.PriceLimit = DefaultTxPoolConfig.PriceLimit
  132. }
  133. if conf.PriceBump < 1 {
  134. log.Warn("Sanitizing invalid txpool price bump", "provided", conf.PriceBump, "updated", DefaultTxPoolConfig.PriceBump)
  135. conf.PriceBump = DefaultTxPoolConfig.PriceBump
  136. }
  137. return conf
  138. }
  139. // TxPool contains all currently known transactions. Transactions
  140. // enter the pool when they are received from the network or submitted
  141. // locally. They exit the pool when they are included in the blockchain.
  142. //
  143. // The pool separates processable transactions (which can be applied to the
  144. // current state) and future transactions. Transactions move between those
  145. // two states over time as they are received and processed.
  146. type TxPool struct {
  147. config TxPoolConfig
  148. chainconfig *params.ChainConfig
  149. chain blockChain
  150. gasPrice *big.Int
  151. txFeed event.Feed
  152. scope event.SubscriptionScope
  153. chainHeadCh chan ChainHeadEvent
  154. chainHeadSub event.Subscription
  155. signer types.Signer
  156. mu sync.RWMutex
  157. currentState *state.StateDB // Current state in the blockchain head
  158. pendingState *state.ManagedState // Pending state tracking virtual nonces
  159. currentMaxGas *big.Int // Current gas limit for transaction caps
  160. locals *accountSet // Set of local transaction to exepmt from evicion rules
  161. journal *txJournal // Journal of local transaction to back up to disk
  162. pending map[common.Address]*txList // All currently processable transactions
  163. queue map[common.Address]*txList // Queued but non-processable transactions
  164. beats map[common.Address]time.Time // Last heartbeat from each known account
  165. all map[common.Hash]*types.Transaction // All transactions to allow lookups
  166. priced *txPricedList // All transactions sorted by price
  167. wg sync.WaitGroup // for shutdown sync
  168. homestead bool
  169. }
  170. // NewTxPool creates a new transaction pool to gather, sort and filter inbound
  171. // trnsactions from the network.
  172. func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool {
  173. // Sanitize the input to ensure no vulnerable gas prices are set
  174. config = (&config).sanitize()
  175. // Create the transaction pool with its initial settings
  176. pool := &TxPool{
  177. config: config,
  178. chainconfig: chainconfig,
  179. chain: chain,
  180. signer: types.NewEIP155Signer(chainconfig.ChainId),
  181. pending: make(map[common.Address]*txList),
  182. queue: make(map[common.Address]*txList),
  183. beats: make(map[common.Address]time.Time),
  184. all: make(map[common.Hash]*types.Transaction),
  185. chainHeadCh: make(chan ChainHeadEvent, chainHeadChanSize),
  186. gasPrice: new(big.Int).SetUint64(config.PriceLimit),
  187. }
  188. pool.locals = newAccountSet(pool.signer)
  189. pool.priced = newTxPricedList(&pool.all)
  190. pool.reset(nil, chain.CurrentHeader())
  191. // If local transactions and journaling is enabled, load from disk
  192. if !config.NoLocals && config.Journal != "" {
  193. pool.journal = newTxJournal(config.Journal)
  194. if err := pool.journal.load(pool.AddLocal); err != nil {
  195. log.Warn("Failed to load transaction journal", "err", err)
  196. }
  197. if err := pool.journal.rotate(pool.local()); err != nil {
  198. log.Warn("Failed to rotate transaction journal", "err", err)
  199. }
  200. }
  201. // Subscribe events from blockchain
  202. pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh)
  203. // Start the event loop and return
  204. pool.wg.Add(1)
  205. go pool.loop()
  206. return pool
  207. }
  208. // loop is the transaction pool's main event loop, waiting for and reacting to
  209. // outside blockchain events as well as for various reporting and transaction
  210. // eviction events.
  211. func (pool *TxPool) loop() {
  212. defer pool.wg.Done()
  213. // Start the stats reporting and transaction eviction tickers
  214. var prevPending, prevQueued, prevStales int
  215. report := time.NewTicker(statsReportInterval)
  216. defer report.Stop()
  217. evict := time.NewTicker(evictionInterval)
  218. defer evict.Stop()
  219. journal := time.NewTicker(pool.config.Rejournal)
  220. defer journal.Stop()
  221. // Track the previous head headers for transaction reorgs
  222. head := pool.chain.CurrentHeader()
  223. // Keep waiting for and reacting to the various events
  224. for {
  225. select {
  226. // Handle ChainHeadEvent
  227. case ev := <-pool.chainHeadCh:
  228. if ev.Block != nil {
  229. pool.mu.Lock()
  230. if pool.chainconfig.IsHomestead(ev.Block.Number()) {
  231. pool.homestead = true
  232. }
  233. pool.reset(head, ev.Block.Header())
  234. head = ev.Block.Header()
  235. pool.mu.Unlock()
  236. }
  237. // Be unsubscribed due to system stopped
  238. case <-pool.chainHeadSub.Err():
  239. return
  240. // Handle stats reporting ticks
  241. case <-report.C:
  242. pool.mu.RLock()
  243. pending, queued := pool.stats()
  244. stales := pool.priced.stales
  245. pool.mu.RUnlock()
  246. if pending != prevPending || queued != prevQueued || stales != prevStales {
  247. log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales)
  248. prevPending, prevQueued, prevStales = pending, queued, stales
  249. }
  250. // Handle inactive account transaction eviction
  251. case <-evict.C:
  252. pool.mu.Lock()
  253. for addr := range pool.queue {
  254. // Skip local transactions from the eviction mechanism
  255. if pool.locals.contains(addr) {
  256. continue
  257. }
  258. // Any non-locals old enough should be removed
  259. if time.Since(pool.beats[addr]) > pool.config.Lifetime {
  260. for _, tx := range pool.queue[addr].Flatten() {
  261. pool.removeTx(tx.Hash())
  262. }
  263. }
  264. }
  265. pool.mu.Unlock()
  266. // Handle local transaction journal rotation
  267. case <-journal.C:
  268. if pool.journal != nil {
  269. pool.mu.Lock()
  270. if err := pool.journal.rotate(pool.local()); err != nil {
  271. log.Warn("Failed to rotate local tx journal", "err", err)
  272. }
  273. pool.mu.Unlock()
  274. }
  275. }
  276. }
  277. }
  278. // lockedReset is a wrapper around reset to allow calling it in a thread safe
  279. // manner. This method is only ever used in the tester!
  280. func (pool *TxPool) lockedReset(oldHead, newHead *types.Header) {
  281. pool.mu.Lock()
  282. defer pool.mu.Unlock()
  283. pool.reset(oldHead, newHead)
  284. }
  285. // reset retrieves the current state of the blockchain and ensures the content
  286. // of the transaction pool is valid with regard to the chain state.
  287. func (pool *TxPool) reset(oldHead, newHead *types.Header) {
  288. // If we're reorging an old state, reinject all dropped transactions
  289. var reinject types.Transactions
  290. if oldHead != nil && oldHead.Hash() != newHead.ParentHash {
  291. var discarded, included types.Transactions
  292. var (
  293. rem = pool.chain.GetBlock(oldHead.Hash(), oldHead.Number.Uint64())
  294. add = pool.chain.GetBlock(newHead.Hash(), newHead.Number.Uint64())
  295. )
  296. for rem.NumberU64() > add.NumberU64() {
  297. discarded = append(discarded, rem.Transactions()...)
  298. if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  299. log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  300. return
  301. }
  302. }
  303. for add.NumberU64() > rem.NumberU64() {
  304. included = append(included, add.Transactions()...)
  305. if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  306. log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  307. return
  308. }
  309. }
  310. for rem.Hash() != add.Hash() {
  311. discarded = append(discarded, rem.Transactions()...)
  312. if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  313. log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  314. return
  315. }
  316. included = append(included, add.Transactions()...)
  317. if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  318. log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  319. return
  320. }
  321. }
  322. reinject = types.TxDifference(discarded, included)
  323. }
  324. // Initialize the internal state to the current head
  325. if newHead == nil {
  326. newHead = pool.chain.CurrentHeader() // Special case during testing
  327. }
  328. statedb, err := pool.chain.StateAt(newHead.Root)
  329. if err != nil {
  330. log.Error("Failed to reset txpool state", "err", err)
  331. return
  332. }
  333. pool.currentState = statedb
  334. pool.pendingState = state.ManageState(statedb)
  335. pool.currentMaxGas = newHead.GasLimit
  336. // Inject any transactions discarded due to reorgs
  337. log.Debug("Reinjecting stale transactions", "count", len(reinject))
  338. pool.addTxsLocked(reinject, false)
  339. // validate the pool of pending transactions, this will remove
  340. // any transactions that have been included in the block or
  341. // have been invalidated because of another transaction (e.g.
  342. // higher gas price)
  343. pool.demoteUnexecutables()
  344. // Update all accounts to the latest known pending nonce
  345. for addr, list := range pool.pending {
  346. txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway
  347. pool.pendingState.SetNonce(addr, txs[len(txs)-1].Nonce()+1)
  348. }
  349. // Check the queue and move transactions over to the pending if possible
  350. // or remove those that have become invalid
  351. pool.promoteExecutables(nil)
  352. }
  353. // Stop terminates the transaction pool.
  354. func (pool *TxPool) Stop() {
  355. // Unsubscribe all subscriptions registered from txpool
  356. pool.scope.Close()
  357. // Unsubscribe subscriptions registered from blockchain
  358. pool.chainHeadSub.Unsubscribe()
  359. pool.wg.Wait()
  360. if pool.journal != nil {
  361. pool.journal.close()
  362. }
  363. log.Info("Transaction pool stopped")
  364. }
  365. // SubscribeTxPreEvent registers a subscription of TxPreEvent and
  366. // starts sending event to the given channel.
  367. func (pool *TxPool) SubscribeTxPreEvent(ch chan<- TxPreEvent) event.Subscription {
  368. return pool.scope.Track(pool.txFeed.Subscribe(ch))
  369. }
  370. // GasPrice returns the current gas price enforced by the transaction pool.
  371. func (pool *TxPool) GasPrice() *big.Int {
  372. pool.mu.RLock()
  373. defer pool.mu.RUnlock()
  374. return new(big.Int).Set(pool.gasPrice)
  375. }
  376. // SetGasPrice updates the minimum price required by the transaction pool for a
  377. // new transaction, and drops all transactions below this threshold.
  378. func (pool *TxPool) SetGasPrice(price *big.Int) {
  379. pool.mu.Lock()
  380. defer pool.mu.Unlock()
  381. pool.gasPrice = price
  382. for _, tx := range pool.priced.Cap(price, pool.locals) {
  383. pool.removeTx(tx.Hash())
  384. }
  385. log.Info("Transaction pool price threshold updated", "price", price)
  386. }
  387. // State returns the virtual managed state of the transaction pool.
  388. func (pool *TxPool) State() *state.ManagedState {
  389. pool.mu.RLock()
  390. defer pool.mu.RUnlock()
  391. return pool.pendingState
  392. }
  393. // Stats retrieves the current pool stats, namely the number of pending and the
  394. // number of queued (non-executable) transactions.
  395. func (pool *TxPool) Stats() (int, int) {
  396. pool.mu.RLock()
  397. defer pool.mu.RUnlock()
  398. return pool.stats()
  399. }
  400. // stats retrieves the current pool stats, namely the number of pending and the
  401. // number of queued (non-executable) transactions.
  402. func (pool *TxPool) stats() (int, int) {
  403. pending := 0
  404. for _, list := range pool.pending {
  405. pending += list.Len()
  406. }
  407. queued := 0
  408. for _, list := range pool.queue {
  409. queued += list.Len()
  410. }
  411. return pending, queued
  412. }
  413. // Content retrieves the data content of the transaction pool, returning all the
  414. // pending as well as queued transactions, grouped by account and sorted by nonce.
  415. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  416. pool.mu.Lock()
  417. defer pool.mu.Unlock()
  418. pending := make(map[common.Address]types.Transactions)
  419. for addr, list := range pool.pending {
  420. pending[addr] = list.Flatten()
  421. }
  422. queued := make(map[common.Address]types.Transactions)
  423. for addr, list := range pool.queue {
  424. queued[addr] = list.Flatten()
  425. }
  426. return pending, queued
  427. }
  428. // Pending retrieves all currently processable transactions, groupped by origin
  429. // account and sorted by nonce. The returned transaction set is a copy and can be
  430. // freely modified by calling code.
  431. func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
  432. pool.mu.Lock()
  433. defer pool.mu.Unlock()
  434. pending := make(map[common.Address]types.Transactions)
  435. for addr, list := range pool.pending {
  436. pending[addr] = list.Flatten()
  437. }
  438. return pending, nil
  439. }
  440. // local retrieves all currently known local transactions, groupped by origin
  441. // account and sorted by nonce. The returned transaction set is a copy and can be
  442. // freely modified by calling code.
  443. func (pool *TxPool) local() map[common.Address]types.Transactions {
  444. txs := make(map[common.Address]types.Transactions)
  445. for addr := range pool.locals.accounts {
  446. if pending := pool.pending[addr]; pending != nil {
  447. txs[addr] = append(txs[addr], pending.Flatten()...)
  448. }
  449. if queued := pool.queue[addr]; queued != nil {
  450. txs[addr] = append(txs[addr], queued.Flatten()...)
  451. }
  452. }
  453. return txs
  454. }
  455. // validateTx checks whether a transaction is valid according to the consensus
  456. // rules and adheres to some heuristic limits of the local node (price and size).
  457. func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
  458. // Heuristic limit, reject transactions over 32KB to prevent DOS attacks
  459. if tx.Size() > 32*1024 {
  460. return ErrOversizedData
  461. }
  462. // Transactions can't be negative. This may never happen using RLP decoded
  463. // transactions but may occur if you create a transaction using the RPC.
  464. if tx.Value().Sign() < 0 {
  465. return ErrNegativeValue
  466. }
  467. // Ensure the transaction doesn't exceed the current block limit gas.
  468. if pool.currentMaxGas.Cmp(tx.Gas()) < 0 {
  469. return ErrGasLimit
  470. }
  471. // Make sure the transaction is signed properly
  472. from, err := types.Sender(pool.signer, tx)
  473. if err != nil {
  474. return ErrInvalidSender
  475. }
  476. // Drop non-local transactions under our own minimal accepted gas price
  477. local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network
  478. if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 {
  479. return ErrUnderpriced
  480. }
  481. // Ensure the transaction adheres to nonce ordering
  482. if pool.currentState.GetNonce(from) > tx.Nonce() {
  483. return ErrNonceTooLow
  484. }
  485. // Transactor should have enough funds to cover the costs
  486. // cost == V + GP * GL
  487. if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  488. return ErrInsufficientFunds
  489. }
  490. intrGas := IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead)
  491. if tx.Gas().Cmp(intrGas) < 0 {
  492. return ErrIntrinsicGas
  493. }
  494. return nil
  495. }
  496. // add validates a transaction and inserts it into the non-executable queue for
  497. // later pending promotion and execution. If the transaction is a replacement for
  498. // an already pending or queued one, it overwrites the previous and returns this
  499. // so outer code doesn't uselessly call promote.
  500. //
  501. // If a newly added transaction is marked as local, its sending account will be
  502. // whitelisted, preventing any associated transaction from being dropped out of
  503. // the pool due to pricing constraints.
  504. func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
  505. // If the transaction is already known, discard it
  506. hash := tx.Hash()
  507. if pool.all[hash] != nil {
  508. log.Trace("Discarding already known transaction", "hash", hash)
  509. return false, fmt.Errorf("known transaction: %x", hash)
  510. }
  511. // If the transaction fails basic validation, discard it
  512. if err := pool.validateTx(tx, local); err != nil {
  513. log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
  514. invalidTxCounter.Inc(1)
  515. return false, err
  516. }
  517. // If the transaction pool is full, discard underpriced transactions
  518. if uint64(len(pool.all)) >= pool.config.GlobalSlots+pool.config.GlobalQueue {
  519. // If the new transaction is underpriced, don't accept it
  520. if pool.priced.Underpriced(tx, pool.locals) {
  521. log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
  522. underpricedTxCounter.Inc(1)
  523. return false, ErrUnderpriced
  524. }
  525. // New transaction is better than our worse ones, make room for it
  526. drop := pool.priced.Discard(len(pool.all)-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals)
  527. for _, tx := range drop {
  528. log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
  529. underpricedTxCounter.Inc(1)
  530. pool.removeTx(tx.Hash())
  531. }
  532. }
  533. // If the transaction is replacing an already pending one, do directly
  534. from, _ := types.Sender(pool.signer, tx) // already validated
  535. if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
  536. // Nonce already pending, check if required price bump is met
  537. inserted, old := list.Add(tx, pool.config.PriceBump)
  538. if !inserted {
  539. pendingDiscardCounter.Inc(1)
  540. return false, ErrReplaceUnderpriced
  541. }
  542. // New transaction is better, replace old one
  543. if old != nil {
  544. delete(pool.all, old.Hash())
  545. pool.priced.Removed()
  546. pendingReplaceCounter.Inc(1)
  547. }
  548. pool.all[tx.Hash()] = tx
  549. pool.priced.Put(tx)
  550. pool.journalTx(from, tx)
  551. log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
  552. return old != nil, nil
  553. }
  554. // New transaction isn't replacing a pending one, push into queue
  555. replace, err := pool.enqueueTx(hash, tx)
  556. if err != nil {
  557. return false, err
  558. }
  559. // Mark local addresses and journal local transactions
  560. if local {
  561. pool.locals.add(from)
  562. }
  563. pool.journalTx(from, tx)
  564. log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
  565. return replace, nil
  566. }
  567. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  568. //
  569. // Note, this method assumes the pool lock is held!
  570. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) {
  571. // Try to insert the transaction into the future queue
  572. from, _ := types.Sender(pool.signer, tx) // already validated
  573. if pool.queue[from] == nil {
  574. pool.queue[from] = newTxList(false)
  575. }
  576. inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
  577. if !inserted {
  578. // An older transaction was better, discard this
  579. queuedDiscardCounter.Inc(1)
  580. return false, ErrReplaceUnderpriced
  581. }
  582. // Discard any previous transaction and mark this
  583. if old != nil {
  584. delete(pool.all, old.Hash())
  585. pool.priced.Removed()
  586. queuedReplaceCounter.Inc(1)
  587. }
  588. pool.all[hash] = tx
  589. pool.priced.Put(tx)
  590. return old != nil, nil
  591. }
  592. // journalTx adds the specified transaction to the local disk journal if it is
  593. // deemed to have been sent from a local account.
  594. func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
  595. // Only journal if it's enabled and the transaction is local
  596. if pool.journal == nil || !pool.locals.contains(from) {
  597. return
  598. }
  599. if err := pool.journal.insert(tx); err != nil {
  600. log.Warn("Failed to journal local transaction", "err", err)
  601. }
  602. }
  603. // promoteTx adds a transaction to the pending (processable) list of transactions.
  604. //
  605. // Note, this method assumes the pool lock is held!
  606. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) {
  607. // Try to insert the transaction into the pending queue
  608. if pool.pending[addr] == nil {
  609. pool.pending[addr] = newTxList(true)
  610. }
  611. list := pool.pending[addr]
  612. inserted, old := list.Add(tx, pool.config.PriceBump)
  613. if !inserted {
  614. // An older transaction was better, discard this
  615. delete(pool.all, hash)
  616. pool.priced.Removed()
  617. pendingDiscardCounter.Inc(1)
  618. return
  619. }
  620. // Otherwise discard any previous transaction and mark this
  621. if old != nil {
  622. delete(pool.all, old.Hash())
  623. pool.priced.Removed()
  624. pendingReplaceCounter.Inc(1)
  625. }
  626. // Failsafe to work around direct pending inserts (tests)
  627. if pool.all[hash] == nil {
  628. pool.all[hash] = tx
  629. pool.priced.Put(tx)
  630. }
  631. // Set the potentially new pending nonce and notify any subsystems of the new tx
  632. pool.beats[addr] = time.Now()
  633. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  634. go pool.txFeed.Send(TxPreEvent{tx})
  635. }
  636. // AddLocal enqueues a single transaction into the pool if it is valid, marking
  637. // the sender as a local one in the mean time, ensuring it goes around the local
  638. // pricing constraints.
  639. func (pool *TxPool) AddLocal(tx *types.Transaction) error {
  640. return pool.addTx(tx, !pool.config.NoLocals)
  641. }
  642. // AddRemote enqueues a single transaction into the pool if it is valid. If the
  643. // sender is not among the locally tracked ones, full pricing constraints will
  644. // apply.
  645. func (pool *TxPool) AddRemote(tx *types.Transaction) error {
  646. return pool.addTx(tx, false)
  647. }
  648. // AddLocals enqueues a batch of transactions into the pool if they are valid,
  649. // marking the senders as a local ones in the mean time, ensuring they go around
  650. // the local pricing constraints.
  651. func (pool *TxPool) AddLocals(txs []*types.Transaction) error {
  652. return pool.addTxs(txs, !pool.config.NoLocals)
  653. }
  654. // AddRemotes enqueues a batch of transactions into the pool if they are valid.
  655. // If the senders are not among the locally tracked ones, full pricing constraints
  656. // will apply.
  657. func (pool *TxPool) AddRemotes(txs []*types.Transaction) error {
  658. return pool.addTxs(txs, false)
  659. }
  660. // addTx enqueues a single transaction into the pool if it is valid.
  661. func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
  662. pool.mu.Lock()
  663. defer pool.mu.Unlock()
  664. // Try to inject the transaction and update any state
  665. replace, err := pool.add(tx, local)
  666. if err != nil {
  667. return err
  668. }
  669. // If we added a new transaction, run promotion checks and return
  670. if !replace {
  671. from, _ := types.Sender(pool.signer, tx) // already validated
  672. pool.promoteExecutables([]common.Address{from})
  673. }
  674. return nil
  675. }
  676. // addTxs attempts to queue a batch of transactions if they are valid.
  677. func (pool *TxPool) addTxs(txs []*types.Transaction, local bool) error {
  678. pool.mu.Lock()
  679. defer pool.mu.Unlock()
  680. return pool.addTxsLocked(txs, local)
  681. }
  682. // addTxsLocked attempts to queue a batch of transactions if they are valid,
  683. // whilst assuming the transaction pool lock is already held.
  684. func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) error {
  685. // Add the batch of transaction, tracking the accepted ones
  686. dirty := make(map[common.Address]struct{})
  687. for _, tx := range txs {
  688. if replace, err := pool.add(tx, local); err == nil {
  689. if !replace {
  690. from, _ := types.Sender(pool.signer, tx) // already validated
  691. dirty[from] = struct{}{}
  692. }
  693. }
  694. }
  695. // Only reprocess the internal state if something was actually added
  696. if len(dirty) > 0 {
  697. addrs := make([]common.Address, 0, len(dirty))
  698. for addr, _ := range dirty {
  699. addrs = append(addrs, addr)
  700. }
  701. pool.promoteExecutables(addrs)
  702. }
  703. return nil
  704. }
  705. // Get returns a transaction if it is contained in the pool
  706. // and nil otherwise.
  707. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  708. pool.mu.RLock()
  709. defer pool.mu.RUnlock()
  710. return pool.all[hash]
  711. }
  712. // removeTx removes a single transaction from the queue, moving all subsequent
  713. // transactions back to the future queue.
  714. func (pool *TxPool) removeTx(hash common.Hash) {
  715. // Fetch the transaction we wish to delete
  716. tx, ok := pool.all[hash]
  717. if !ok {
  718. return
  719. }
  720. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  721. // Remove it from the list of known transactions
  722. delete(pool.all, hash)
  723. pool.priced.Removed()
  724. // Remove the transaction from the pending lists and reset the account nonce
  725. if pending := pool.pending[addr]; pending != nil {
  726. if removed, invalids := pending.Remove(tx); removed {
  727. // If no more transactions are left, remove the list
  728. if pending.Empty() {
  729. delete(pool.pending, addr)
  730. delete(pool.beats, addr)
  731. } else {
  732. // Otherwise postpone any invalidated transactions
  733. for _, tx := range invalids {
  734. pool.enqueueTx(tx.Hash(), tx)
  735. }
  736. }
  737. // Update the account nonce if needed
  738. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  739. pool.pendingState.SetNonce(addr, nonce)
  740. }
  741. return
  742. }
  743. }
  744. // Transaction is in the future queue
  745. if future := pool.queue[addr]; future != nil {
  746. future.Remove(tx)
  747. if future.Empty() {
  748. delete(pool.queue, addr)
  749. }
  750. }
  751. }
  752. // promoteExecutables moves transactions that have become processable from the
  753. // future queue to the set of pending transactions. During this process, all
  754. // invalidated transactions (low nonce, low balance) are deleted.
  755. func (pool *TxPool) promoteExecutables(accounts []common.Address) {
  756. // Gather all the accounts potentially needing updates
  757. if accounts == nil {
  758. accounts = make([]common.Address, 0, len(pool.queue))
  759. for addr, _ := range pool.queue {
  760. accounts = append(accounts, addr)
  761. }
  762. }
  763. // Iterate over all accounts and promote any executable transactions
  764. for _, addr := range accounts {
  765. list := pool.queue[addr]
  766. if list == nil {
  767. continue // Just in case someone calls with a non existing account
  768. }
  769. // Drop all transactions that are deemed too old (low nonce)
  770. for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) {
  771. hash := tx.Hash()
  772. log.Trace("Removed old queued transaction", "hash", hash)
  773. delete(pool.all, hash)
  774. pool.priced.Removed()
  775. }
  776. // Drop all transactions that are too costly (low balance or out of gas)
  777. drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  778. for _, tx := range drops {
  779. hash := tx.Hash()
  780. log.Trace("Removed unpayable queued transaction", "hash", hash)
  781. delete(pool.all, hash)
  782. pool.priced.Removed()
  783. queuedNofundsCounter.Inc(1)
  784. }
  785. // Gather all executable transactions and promote them
  786. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  787. hash := tx.Hash()
  788. log.Trace("Promoting queued transaction", "hash", hash)
  789. pool.promoteTx(addr, hash, tx)
  790. }
  791. // Drop all transactions over the allowed limit
  792. if !pool.locals.contains(addr) {
  793. for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
  794. hash := tx.Hash()
  795. delete(pool.all, hash)
  796. pool.priced.Removed()
  797. queuedRateLimitCounter.Inc(1)
  798. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  799. }
  800. }
  801. // Delete the entire queue entry if it became empty.
  802. if list.Empty() {
  803. delete(pool.queue, addr)
  804. }
  805. }
  806. // If the pending limit is overflown, start equalizing allowances
  807. pending := uint64(0)
  808. for _, list := range pool.pending {
  809. pending += uint64(list.Len())
  810. }
  811. if pending > pool.config.GlobalSlots {
  812. pendingBeforeCap := pending
  813. // Assemble a spam order to penalize large transactors first
  814. spammers := prque.New()
  815. for addr, list := range pool.pending {
  816. // Only evict transactions from high rollers
  817. if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  818. spammers.Push(addr, float32(list.Len()))
  819. }
  820. }
  821. // Gradually drop transactions from offenders
  822. offenders := []common.Address{}
  823. for pending > pool.config.GlobalSlots && !spammers.Empty() {
  824. // Retrieve the next offender if not local address
  825. offender, _ := spammers.Pop()
  826. offenders = append(offenders, offender.(common.Address))
  827. // Equalize balances until all the same or below threshold
  828. if len(offenders) > 1 {
  829. // Calculate the equalization threshold for all current offenders
  830. threshold := pool.pending[offender.(common.Address)].Len()
  831. // Iteratively reduce all offenders until below limit or threshold reached
  832. for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  833. for i := 0; i < len(offenders)-1; i++ {
  834. list := pool.pending[offenders[i]]
  835. for _, tx := range list.Cap(list.Len() - 1) {
  836. // Drop the transaction from the global pools too
  837. hash := tx.Hash()
  838. delete(pool.all, hash)
  839. pool.priced.Removed()
  840. // Update the account nonce to the dropped transaction
  841. if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce {
  842. pool.pendingState.SetNonce(offenders[i], nonce)
  843. }
  844. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  845. }
  846. pending--
  847. }
  848. }
  849. }
  850. }
  851. // If still above threshold, reduce to limit or min allowance
  852. if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  853. for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  854. for _, addr := range offenders {
  855. list := pool.pending[addr]
  856. for _, tx := range list.Cap(list.Len() - 1) {
  857. // Drop the transaction from the global pools too
  858. hash := tx.Hash()
  859. delete(pool.all, hash)
  860. pool.priced.Removed()
  861. // Update the account nonce to the dropped transaction
  862. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  863. pool.pendingState.SetNonce(addr, nonce)
  864. }
  865. log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  866. }
  867. pending--
  868. }
  869. }
  870. }
  871. pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending))
  872. }
  873. // If we've queued more transactions than the hard limit, drop oldest ones
  874. queued := uint64(0)
  875. for _, list := range pool.queue {
  876. queued += uint64(list.Len())
  877. }
  878. if queued > pool.config.GlobalQueue {
  879. // Sort all accounts with queued transactions by heartbeat
  880. addresses := make(addresssByHeartbeat, 0, len(pool.queue))
  881. for addr := range pool.queue {
  882. if !pool.locals.contains(addr) { // don't drop locals
  883. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  884. }
  885. }
  886. sort.Sort(addresses)
  887. // Drop transactions until the total is below the limit or only locals remain
  888. for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  889. addr := addresses[len(addresses)-1]
  890. list := pool.queue[addr.address]
  891. addresses = addresses[:len(addresses)-1]
  892. // Drop all transactions if they are less than the overflow
  893. if size := uint64(list.Len()); size <= drop {
  894. for _, tx := range list.Flatten() {
  895. pool.removeTx(tx.Hash())
  896. }
  897. drop -= size
  898. queuedRateLimitCounter.Inc(int64(size))
  899. continue
  900. }
  901. // Otherwise drop only last few transactions
  902. txs := list.Flatten()
  903. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  904. pool.removeTx(txs[i].Hash())
  905. drop--
  906. queuedRateLimitCounter.Inc(1)
  907. }
  908. }
  909. }
  910. }
  911. // demoteUnexecutables removes invalid and processed transactions from the pools
  912. // executable/pending queue and any subsequent transactions that become unexecutable
  913. // are moved back into the future queue.
  914. func (pool *TxPool) demoteUnexecutables() {
  915. // Iterate over all accounts and demote any non-executable transactions
  916. for addr, list := range pool.pending {
  917. nonce := pool.currentState.GetNonce(addr)
  918. // Drop all transactions that are deemed too old (low nonce)
  919. for _, tx := range list.Forward(nonce) {
  920. hash := tx.Hash()
  921. log.Trace("Removed old pending transaction", "hash", hash)
  922. delete(pool.all, hash)
  923. pool.priced.Removed()
  924. }
  925. // Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  926. drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  927. for _, tx := range drops {
  928. hash := tx.Hash()
  929. log.Trace("Removed unpayable pending transaction", "hash", hash)
  930. delete(pool.all, hash)
  931. pool.priced.Removed()
  932. pendingNofundsCounter.Inc(1)
  933. }
  934. for _, tx := range invalids {
  935. hash := tx.Hash()
  936. log.Trace("Demoting pending transaction", "hash", hash)
  937. pool.enqueueTx(hash, tx)
  938. }
  939. // If there's a gap in front, warn (should never happen) and postpone all transactions
  940. if list.Len() > 0 && list.txs.Get(nonce) == nil {
  941. for _, tx := range list.Cap(0) {
  942. hash := tx.Hash()
  943. log.Error("Demoting invalidated transaction", "hash", hash)
  944. pool.enqueueTx(hash, tx)
  945. }
  946. }
  947. // Delete the entire queue entry if it became empty.
  948. if list.Empty() {
  949. delete(pool.pending, addr)
  950. delete(pool.beats, addr)
  951. }
  952. }
  953. }
  954. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  955. type addressByHeartbeat struct {
  956. address common.Address
  957. heartbeat time.Time
  958. }
  959. type addresssByHeartbeat []addressByHeartbeat
  960. func (a addresssByHeartbeat) Len() int { return len(a) }
  961. func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  962. func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  963. // accountSet is simply a set of addresses to check for existence, and a signer
  964. // capable of deriving addresses from transactions.
  965. type accountSet struct {
  966. accounts map[common.Address]struct{}
  967. signer types.Signer
  968. }
  969. // newAccountSet creates a new address set with an associated signer for sender
  970. // derivations.
  971. func newAccountSet(signer types.Signer) *accountSet {
  972. return &accountSet{
  973. accounts: make(map[common.Address]struct{}),
  974. signer: signer,
  975. }
  976. }
  977. // contains checks if a given address is contained within the set.
  978. func (as *accountSet) contains(addr common.Address) bool {
  979. _, exist := as.accounts[addr]
  980. return exist
  981. }
  982. // containsTx checks if the sender of a given tx is within the set. If the sender
  983. // cannot be derived, this method returns false.
  984. func (as *accountSet) containsTx(tx *types.Transaction) bool {
  985. if addr, err := types.Sender(as.signer, tx); err == nil {
  986. return as.contains(addr)
  987. }
  988. return false
  989. }
  990. // add inserts a new address into the set to track.
  991. func (as *accountSet) add(addr common.Address) {
  992. as.accounts[addr] = struct{}{}
  993. }