tx_pool.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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. var (
  34. // Transaction Pool Errors
  35. ErrInvalidSender = errors.New("invalid sender")
  36. ErrNonce = errors.New("nonce too low")
  37. ErrUnderpriced = errors.New("transaction underpriced")
  38. ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")
  39. ErrBalance = errors.New("insufficient balance")
  40. ErrInsufficientFunds = errors.New("insufficient funds for gas * price + value")
  41. ErrIntrinsicGas = errors.New("intrinsic gas too low")
  42. ErrGasLimit = errors.New("exceeds block gas limit")
  43. ErrNegativeValue = errors.New("negative value")
  44. )
  45. var (
  46. minPendingPerAccount = uint64(16) // Min number of guaranteed transaction slots per address
  47. maxPendingTotal = uint64(4096) // Max limit of pending transactions from all accounts (soft)
  48. maxQueuedPerAccount = uint64(64) // Max limit of queued transactions per address
  49. maxQueuedTotal = uint64(1024) // Max limit of queued transactions from all accounts
  50. maxQueuedLifetime = 3 * time.Hour // Max amount of time transactions from idle accounts are queued
  51. minPriceBumpPercent = int64(10) // Minimum price bump needed to replace an old transaction
  52. evictionInterval = time.Minute // Time interval to check for evictable transactions
  53. statsReportInterval = 8 * time.Second // Time interval to report transaction pool stats
  54. )
  55. var (
  56. // Metrics for the pending pool
  57. pendingDiscardCounter = metrics.NewCounter("txpool/pending/discard")
  58. pendingReplaceCounter = metrics.NewCounter("txpool/pending/replace")
  59. pendingRLCounter = metrics.NewCounter("txpool/pending/ratelimit") // Dropped due to rate limiting
  60. pendingNofundsCounter = metrics.NewCounter("txpool/pending/nofunds") // Dropped due to out-of-funds
  61. // Metrics for the queued pool
  62. queuedDiscardCounter = metrics.NewCounter("txpool/queued/discard")
  63. queuedReplaceCounter = metrics.NewCounter("txpool/queued/replace")
  64. queuedRLCounter = metrics.NewCounter("txpool/queued/ratelimit") // Dropped due to rate limiting
  65. queuedNofundsCounter = metrics.NewCounter("txpool/queued/nofunds") // Dropped due to out-of-funds
  66. // General tx metrics
  67. invalidTxCounter = metrics.NewCounter("txpool/invalid")
  68. underpricedTxCounter = metrics.NewCounter("txpool/underpriced")
  69. )
  70. type stateFn func() (*state.StateDB, error)
  71. // TxPool contains all currently known transactions. Transactions
  72. // enter the pool when they are received from the network or submitted
  73. // locally. They exit the pool when they are included in the blockchain.
  74. //
  75. // The pool separates processable transactions (which can be applied to the
  76. // current state) and future transactions. Transactions move between those
  77. // two states over time as they are received and processed.
  78. type TxPool struct {
  79. config *params.ChainConfig
  80. currentState stateFn // The state function which will allow us to do some pre checks
  81. pendingState *state.ManagedState
  82. gasLimit func() *big.Int // The current gas limit function callback
  83. gasPrice *big.Int
  84. eventMux *event.TypeMux
  85. events *event.TypeMuxSubscription
  86. locals *txSet
  87. signer types.Signer
  88. mu sync.RWMutex
  89. pending map[common.Address]*txList // All currently processable transactions
  90. queue map[common.Address]*txList // Queued but non-processable transactions
  91. beats map[common.Address]time.Time // Last heartbeat from each known account
  92. all map[common.Hash]*types.Transaction // All transactions to allow lookups
  93. priced *txPricedList // All transactions sorted by price
  94. wg sync.WaitGroup // for shutdown sync
  95. quit chan struct{}
  96. homestead bool
  97. }
  98. func NewTxPool(config *params.ChainConfig, eventMux *event.TypeMux, currentStateFn stateFn, gasLimitFn func() *big.Int) *TxPool {
  99. pool := &TxPool{
  100. config: config,
  101. signer: types.NewEIP155Signer(config.ChainId),
  102. pending: make(map[common.Address]*txList),
  103. queue: make(map[common.Address]*txList),
  104. beats: make(map[common.Address]time.Time),
  105. all: make(map[common.Hash]*types.Transaction),
  106. eventMux: eventMux,
  107. currentState: currentStateFn,
  108. gasLimit: gasLimitFn,
  109. gasPrice: big.NewInt(1),
  110. pendingState: nil,
  111. locals: newTxSet(),
  112. events: eventMux.Subscribe(ChainHeadEvent{}, RemovedTransactionEvent{}),
  113. quit: make(chan struct{}),
  114. }
  115. pool.priced = newTxPricedList(&pool.all)
  116. pool.resetState()
  117. pool.wg.Add(2)
  118. go pool.eventLoop()
  119. go pool.expirationLoop()
  120. return pool
  121. }
  122. func (pool *TxPool) eventLoop() {
  123. defer pool.wg.Done()
  124. // Start a ticker and keep track of interesting pool stats to report
  125. var prevPending, prevQueued, prevStales int
  126. report := time.NewTicker(statsReportInterval)
  127. defer report.Stop()
  128. // Track chain events. When a chain events occurs (new chain canon block)
  129. // we need to know the new state. The new state will help us determine
  130. // the nonces in the managed state
  131. for {
  132. select {
  133. // Handle any events fired by the system
  134. case ev, ok := <-pool.events.Chan():
  135. if !ok {
  136. return
  137. }
  138. switch ev := ev.Data.(type) {
  139. case ChainHeadEvent:
  140. pool.mu.Lock()
  141. if ev.Block != nil {
  142. if pool.config.IsHomestead(ev.Block.Number()) {
  143. pool.homestead = true
  144. }
  145. }
  146. pool.resetState()
  147. pool.mu.Unlock()
  148. case RemovedTransactionEvent:
  149. pool.AddBatch(ev.Txs)
  150. }
  151. // Handle stats reporting ticks
  152. case <-report.C:
  153. pool.mu.RLock()
  154. pending, queued := pool.stats()
  155. stales := pool.priced.stales
  156. pool.mu.RUnlock()
  157. if pending != prevPending || queued != prevQueued || stales != prevStales {
  158. log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales)
  159. prevPending, prevQueued, prevStales = pending, queued, stales
  160. }
  161. }
  162. }
  163. }
  164. func (pool *TxPool) resetState() {
  165. currentState, err := pool.currentState()
  166. if err != nil {
  167. log.Error("Failed reset txpool state", "err", err)
  168. return
  169. }
  170. pool.pendingState = state.ManageState(currentState)
  171. // validate the pool of pending transactions, this will remove
  172. // any transactions that have been included in the block or
  173. // have been invalidated because of another transaction (e.g.
  174. // higher gas price)
  175. pool.demoteUnexecutables(currentState)
  176. // Update all accounts to the latest known pending nonce
  177. for addr, list := range pool.pending {
  178. txs := list.Flatten() // Heavy but will be cached and is needed by the miner anyway
  179. pool.pendingState.SetNonce(addr, txs[len(txs)-1].Nonce()+1)
  180. }
  181. // Check the queue and move transactions over to the pending if possible
  182. // or remove those that have become invalid
  183. pool.promoteExecutables(currentState)
  184. }
  185. // Stop stops a TxPool
  186. func (pool *TxPool) Stop() {
  187. pool.events.Unsubscribe()
  188. close(pool.quit)
  189. pool.wg.Wait()
  190. log.Info("Transaction pool stopped")
  191. }
  192. // GasPrice returns the current gas price enforced by the transaction pool.
  193. func (pool *TxPool) GasPrice() *big.Int {
  194. pool.mu.RLock()
  195. defer pool.mu.RUnlock()
  196. return new(big.Int).Set(pool.gasPrice)
  197. }
  198. // SetGasPrice updates the minimum price required by the transaction pool for a
  199. // new transaction, and drops all transactions below this threshold.
  200. func (pool *TxPool) SetGasPrice(price *big.Int) {
  201. pool.mu.Lock()
  202. defer pool.mu.Unlock()
  203. pool.gasPrice = price
  204. for _, tx := range pool.priced.Cap(price, pool.locals) {
  205. pool.removeTx(tx.Hash())
  206. }
  207. log.Info("Transaction pool price threshold updated", "price", price)
  208. }
  209. // State returns the state of TxPool
  210. func (pool *TxPool) State() *state.ManagedState {
  211. pool.mu.RLock()
  212. defer pool.mu.RUnlock()
  213. return pool.pendingState
  214. }
  215. // Stats retrieves the current pool stats, namely the number of pending and the
  216. // number of queued (non-executable) transactions.
  217. func (pool *TxPool) Stats() (int, int) {
  218. pool.mu.RLock()
  219. defer pool.mu.RUnlock()
  220. return pool.stats()
  221. }
  222. // stats retrieves the current pool stats, namely the number of pending and the
  223. // number of queued (non-executable) transactions.
  224. func (pool *TxPool) stats() (int, int) {
  225. pending := 0
  226. for _, list := range pool.pending {
  227. pending += list.Len()
  228. }
  229. queued := 0
  230. for _, list := range pool.queue {
  231. queued += list.Len()
  232. }
  233. return pending, queued
  234. }
  235. // Content retrieves the data content of the transaction pool, returning all the
  236. // pending as well as queued transactions, grouped by account and sorted by nonce.
  237. func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
  238. pool.mu.RLock()
  239. defer pool.mu.RUnlock()
  240. pending := make(map[common.Address]types.Transactions)
  241. for addr, list := range pool.pending {
  242. pending[addr] = list.Flatten()
  243. }
  244. queued := make(map[common.Address]types.Transactions)
  245. for addr, list := range pool.queue {
  246. queued[addr] = list.Flatten()
  247. }
  248. return pending, queued
  249. }
  250. // Pending retrieves all currently processable transactions, groupped by origin
  251. // account and sorted by nonce. The returned transaction set is a copy and can be
  252. // freely modified by calling code.
  253. func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
  254. pool.mu.Lock()
  255. defer pool.mu.Unlock()
  256. state, err := pool.currentState()
  257. if err != nil {
  258. return nil, err
  259. }
  260. // check queue first
  261. pool.promoteExecutables(state)
  262. // invalidate any txs
  263. pool.demoteUnexecutables(state)
  264. pending := make(map[common.Address]types.Transactions)
  265. for addr, list := range pool.pending {
  266. pending[addr] = list.Flatten()
  267. }
  268. return pending, nil
  269. }
  270. // SetLocal marks a transaction as local, skipping gas price
  271. // check against local miner minimum in the future
  272. func (pool *TxPool) SetLocal(tx *types.Transaction) {
  273. pool.mu.Lock()
  274. defer pool.mu.Unlock()
  275. pool.locals.add(tx.Hash())
  276. }
  277. // validateTx checks whether a transaction is valid according
  278. // to the consensus rules.
  279. func (pool *TxPool) validateTx(tx *types.Transaction) error {
  280. local := pool.locals.contains(tx.Hash())
  281. // Drop transactions under our own minimal accepted gas price
  282. if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 {
  283. return ErrUnderpriced
  284. }
  285. currentState, err := pool.currentState()
  286. if err != nil {
  287. return err
  288. }
  289. from, err := types.Sender(pool.signer, tx)
  290. if err != nil {
  291. return ErrInvalidSender
  292. }
  293. // Last but not least check for nonce errors
  294. if currentState.GetNonce(from) > tx.Nonce() {
  295. return ErrNonce
  296. }
  297. // Check the transaction doesn't exceed the current
  298. // block limit gas.
  299. if pool.gasLimit().Cmp(tx.Gas()) < 0 {
  300. return ErrGasLimit
  301. }
  302. // Transactions can't be negative. This may never happen
  303. // using RLP decoded transactions but may occur if you create
  304. // a transaction using the RPC for example.
  305. if tx.Value().Sign() < 0 {
  306. return ErrNegativeValue
  307. }
  308. // Transactor should have enough funds to cover the costs
  309. // cost == V + GP * GL
  310. if currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
  311. return ErrInsufficientFunds
  312. }
  313. intrGas := IntrinsicGas(tx.Data(), tx.To() == nil, pool.homestead)
  314. if tx.Gas().Cmp(intrGas) < 0 {
  315. return ErrIntrinsicGas
  316. }
  317. return nil
  318. }
  319. // add validates a transaction and inserts it into the non-executable queue for
  320. // later pending promotion and execution. If the transaction is a replacement for
  321. // an already pending or queued one, it overwrites the previous and returns this
  322. // so outer code doesn't uselessly call promote.
  323. func (pool *TxPool) add(tx *types.Transaction) (bool, error) {
  324. // If the transaction is already known, discard it
  325. hash := tx.Hash()
  326. if pool.all[hash] != nil {
  327. log.Trace("Discarding already known transaction", "hash", hash)
  328. return false, fmt.Errorf("known transaction: %x", hash)
  329. }
  330. // If the transaction fails basic validation, discard it
  331. if err := pool.validateTx(tx); err != nil {
  332. log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
  333. invalidTxCounter.Inc(1)
  334. return false, err
  335. }
  336. // If the transaction pool is full, discard underpriced transactions
  337. if uint64(len(pool.all)) >= maxPendingTotal+maxQueuedTotal {
  338. // If the new transaction is underpriced, don't accept it
  339. if pool.priced.Underpriced(tx, pool.locals) {
  340. log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
  341. underpricedTxCounter.Inc(1)
  342. return false, ErrUnderpriced
  343. }
  344. // New transaction is better than our worse ones, make room for it
  345. drop := pool.priced.Discard(len(pool.all)-int(maxPendingTotal+maxQueuedTotal-1), pool.locals)
  346. for _, tx := range drop {
  347. log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
  348. underpricedTxCounter.Inc(1)
  349. pool.removeTx(tx.Hash())
  350. }
  351. }
  352. // If the transaction is replacing an already pending one, do directly
  353. from, _ := types.Sender(pool.signer, tx) // already validated
  354. if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
  355. // Nonce already pending, check if required price bump is met
  356. inserted, old := list.Add(tx)
  357. if !inserted {
  358. pendingDiscardCounter.Inc(1)
  359. return false, ErrReplaceUnderpriced
  360. }
  361. // New transaction is better, replace old one
  362. if old != nil {
  363. delete(pool.all, old.Hash())
  364. pool.priced.Removed()
  365. pendingReplaceCounter.Inc(1)
  366. }
  367. pool.all[tx.Hash()] = tx
  368. pool.priced.Put(tx)
  369. log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
  370. return old != nil, nil
  371. }
  372. // New transaction isn't replacing a pending one, push into queue
  373. replace, err := pool.enqueueTx(hash, tx)
  374. if err != nil {
  375. return false, err
  376. }
  377. log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
  378. return replace, nil
  379. }
  380. // enqueueTx inserts a new transaction into the non-executable transaction queue.
  381. //
  382. // Note, this method assumes the pool lock is held!
  383. func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) {
  384. // Try to insert the transaction into the future queue
  385. from, _ := types.Sender(pool.signer, tx) // already validated
  386. if pool.queue[from] == nil {
  387. pool.queue[from] = newTxList(false)
  388. }
  389. inserted, old := pool.queue[from].Add(tx)
  390. if !inserted {
  391. // An older transaction was better, discard this
  392. queuedDiscardCounter.Inc(1)
  393. return false, ErrReplaceUnderpriced
  394. }
  395. // Discard any previous transaction and mark this
  396. if old != nil {
  397. delete(pool.all, old.Hash())
  398. pool.priced.Removed()
  399. queuedReplaceCounter.Inc(1)
  400. }
  401. pool.all[hash] = tx
  402. pool.priced.Put(tx)
  403. return old != nil, nil
  404. }
  405. // promoteTx adds a transaction to the pending (processable) list of transactions.
  406. //
  407. // Note, this method assumes the pool lock is held!
  408. func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) {
  409. // Try to insert the transaction into the pending queue
  410. if pool.pending[addr] == nil {
  411. pool.pending[addr] = newTxList(true)
  412. }
  413. list := pool.pending[addr]
  414. inserted, old := list.Add(tx)
  415. if !inserted {
  416. // An older transaction was better, discard this
  417. delete(pool.all, hash)
  418. pool.priced.Removed()
  419. pendingDiscardCounter.Inc(1)
  420. return
  421. }
  422. // Otherwise discard any previous transaction and mark this
  423. if old != nil {
  424. delete(pool.all, old.Hash())
  425. pool.priced.Removed()
  426. pendingReplaceCounter.Inc(1)
  427. }
  428. // Failsafe to work around direct pending inserts (tests)
  429. if pool.all[hash] == nil {
  430. pool.all[hash] = tx
  431. pool.priced.Put(tx)
  432. }
  433. // Set the potentially new pending nonce and notify any subsystems of the new tx
  434. pool.beats[addr] = time.Now()
  435. pool.pendingState.SetNonce(addr, tx.Nonce()+1)
  436. go pool.eventMux.Post(TxPreEvent{tx})
  437. }
  438. // Add queues a single transaction in the pool if it is valid.
  439. func (pool *TxPool) Add(tx *types.Transaction) error {
  440. pool.mu.Lock()
  441. defer pool.mu.Unlock()
  442. // Try to inject the transaction and update any state
  443. replace, err := pool.add(tx)
  444. if err != nil {
  445. return err
  446. }
  447. state, err := pool.currentState()
  448. if err != nil {
  449. return err
  450. }
  451. // If we added a new transaction, run promotion checks and return
  452. if !replace {
  453. pool.promoteExecutables(state)
  454. }
  455. return nil
  456. }
  457. // AddBatch attempts to queue a batch of transactions.
  458. func (pool *TxPool) AddBatch(txs []*types.Transaction) error {
  459. pool.mu.Lock()
  460. defer pool.mu.Unlock()
  461. // Add the batch of transaction, tracking the accepted ones
  462. replaced, added := true, 0
  463. for _, tx := range txs {
  464. if replace, err := pool.add(tx); err == nil {
  465. added++
  466. if !replace {
  467. replaced = false
  468. }
  469. }
  470. }
  471. // Only reprocess the internal state if something was actually added
  472. if added > 0 {
  473. state, err := pool.currentState()
  474. if err != nil {
  475. return err
  476. }
  477. if !replaced {
  478. pool.promoteExecutables(state)
  479. }
  480. }
  481. return nil
  482. }
  483. // Get returns a transaction if it is contained in the pool
  484. // and nil otherwise.
  485. func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
  486. pool.mu.RLock()
  487. defer pool.mu.RUnlock()
  488. return pool.all[hash]
  489. }
  490. // Remove removes the transaction with the given hash from the pool.
  491. func (pool *TxPool) Remove(hash common.Hash) {
  492. pool.mu.Lock()
  493. defer pool.mu.Unlock()
  494. pool.removeTx(hash)
  495. }
  496. // RemoveBatch removes all given transactions from the pool.
  497. func (pool *TxPool) RemoveBatch(txs types.Transactions) {
  498. pool.mu.Lock()
  499. defer pool.mu.Unlock()
  500. for _, tx := range txs {
  501. pool.removeTx(tx.Hash())
  502. }
  503. }
  504. // removeTx removes a single transaction from the queue, moving all subsequent
  505. // transactions back to the future queue.
  506. func (pool *TxPool) removeTx(hash common.Hash) {
  507. // Fetch the transaction we wish to delete
  508. tx, ok := pool.all[hash]
  509. if !ok {
  510. return
  511. }
  512. addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  513. // Remove it from the list of known transactions
  514. delete(pool.all, hash)
  515. pool.priced.Removed()
  516. // Remove the transaction from the pending lists and reset the account nonce
  517. if pending := pool.pending[addr]; pending != nil {
  518. if removed, invalids := pending.Remove(tx); removed {
  519. // If no more transactions are left, remove the list
  520. if pending.Empty() {
  521. delete(pool.pending, addr)
  522. delete(pool.beats, addr)
  523. } else {
  524. // Otherwise postpone any invalidated transactions
  525. for _, tx := range invalids {
  526. pool.enqueueTx(tx.Hash(), tx)
  527. }
  528. }
  529. // Update the account nonce if needed
  530. if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
  531. pool.pendingState.SetNonce(addr, tx.Nonce())
  532. }
  533. }
  534. }
  535. // Transaction is in the future queue
  536. if future := pool.queue[addr]; future != nil {
  537. future.Remove(tx)
  538. if future.Empty() {
  539. delete(pool.queue, addr)
  540. }
  541. }
  542. }
  543. // promoteExecutables moves transactions that have become processable from the
  544. // future queue to the set of pending transactions. During this process, all
  545. // invalidated transactions (low nonce, low balance) are deleted.
  546. func (pool *TxPool) promoteExecutables(state *state.StateDB) {
  547. // Iterate over all accounts and promote any executable transactions
  548. queued := uint64(0)
  549. for addr, list := range pool.queue {
  550. // Drop all transactions that are deemed too old (low nonce)
  551. for _, tx := range list.Forward(state.GetNonce(addr)) {
  552. hash := tx.Hash()
  553. log.Trace("Removed old queued transaction", "hash", hash)
  554. delete(pool.all, hash)
  555. pool.priced.Removed()
  556. }
  557. // Drop all transactions that are too costly (low balance)
  558. drops, _ := list.Filter(state.GetBalance(addr))
  559. for _, tx := range drops {
  560. hash := tx.Hash()
  561. log.Trace("Removed unpayable queued transaction", "hash", hash)
  562. delete(pool.all, hash)
  563. pool.priced.Removed()
  564. queuedNofundsCounter.Inc(1)
  565. }
  566. // Gather all executable transactions and promote them
  567. for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
  568. hash := tx.Hash()
  569. log.Trace("Promoting queued transaction", "hash", hash)
  570. pool.promoteTx(addr, hash, tx)
  571. }
  572. // Drop all transactions over the allowed limit
  573. for _, tx := range list.Cap(int(maxQueuedPerAccount)) {
  574. hash := tx.Hash()
  575. log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  576. delete(pool.all, hash)
  577. pool.priced.Removed()
  578. queuedRLCounter.Inc(1)
  579. }
  580. queued += uint64(list.Len())
  581. // Delete the entire queue entry if it became empty.
  582. if list.Empty() {
  583. delete(pool.queue, addr)
  584. }
  585. }
  586. // If the pending limit is overflown, start equalizing allowances
  587. pending := uint64(0)
  588. for _, list := range pool.pending {
  589. pending += uint64(list.Len())
  590. }
  591. if pending > maxPendingTotal {
  592. pendingBeforeCap := pending
  593. // Assemble a spam order to penalize large transactors first
  594. spammers := prque.New()
  595. for addr, list := range pool.pending {
  596. // Only evict transactions from high rollers
  597. if uint64(list.Len()) > minPendingPerAccount {
  598. // Skip local accounts as pools should maintain backlogs for themselves
  599. for _, tx := range list.txs.items {
  600. if !pool.locals.contains(tx.Hash()) {
  601. spammers.Push(addr, float32(list.Len()))
  602. }
  603. break // Checking on transaction for locality is enough
  604. }
  605. }
  606. }
  607. // Gradually drop transactions from offenders
  608. offenders := []common.Address{}
  609. for pending > maxPendingTotal && !spammers.Empty() {
  610. // Retrieve the next offender if not local address
  611. offender, _ := spammers.Pop()
  612. offenders = append(offenders, offender.(common.Address))
  613. // Equalize balances until all the same or below threshold
  614. if len(offenders) > 1 {
  615. // Calculate the equalization threshold for all current offenders
  616. threshold := pool.pending[offender.(common.Address)].Len()
  617. // Iteratively reduce all offenders until below limit or threshold reached
  618. for pending > maxPendingTotal && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  619. for i := 0; i < len(offenders)-1; i++ {
  620. list := pool.pending[offenders[i]]
  621. list.Cap(list.Len() - 1)
  622. pending--
  623. }
  624. }
  625. }
  626. }
  627. // If still above threshold, reduce to limit or min allowance
  628. if pending > maxPendingTotal && len(offenders) > 0 {
  629. for pending > maxPendingTotal && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > minPendingPerAccount {
  630. for _, addr := range offenders {
  631. list := pool.pending[addr]
  632. list.Cap(list.Len() - 1)
  633. pending--
  634. }
  635. }
  636. }
  637. pendingRLCounter.Inc(int64(pendingBeforeCap - pending))
  638. }
  639. // If we've queued more transactions than the hard limit, drop oldest ones
  640. if queued > maxQueuedTotal {
  641. // Sort all accounts with queued transactions by heartbeat
  642. addresses := make(addresssByHeartbeat, 0, len(pool.queue))
  643. for addr := range pool.queue {
  644. addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  645. }
  646. sort.Sort(addresses)
  647. // Drop transactions until the total is below the limit
  648. for drop := queued - maxQueuedTotal; drop > 0; {
  649. addr := addresses[len(addresses)-1]
  650. list := pool.queue[addr.address]
  651. addresses = addresses[:len(addresses)-1]
  652. // Drop all transactions if they are less than the overflow
  653. if size := uint64(list.Len()); size <= drop {
  654. for _, tx := range list.Flatten() {
  655. pool.removeTx(tx.Hash())
  656. }
  657. drop -= size
  658. queuedRLCounter.Inc(int64(size))
  659. continue
  660. }
  661. // Otherwise drop only last few transactions
  662. txs := list.Flatten()
  663. for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  664. pool.removeTx(txs[i].Hash())
  665. drop--
  666. queuedRLCounter.Inc(1)
  667. }
  668. }
  669. }
  670. }
  671. // demoteUnexecutables removes invalid and processed transactions from the pools
  672. // executable/pending queue and any subsequent transactions that become unexecutable
  673. // are moved back into the future queue.
  674. func (pool *TxPool) demoteUnexecutables(state *state.StateDB) {
  675. // Iterate over all accounts and demote any non-executable transactions
  676. for addr, list := range pool.pending {
  677. nonce := state.GetNonce(addr)
  678. // Drop all transactions that are deemed too old (low nonce)
  679. for _, tx := range list.Forward(nonce) {
  680. hash := tx.Hash()
  681. log.Trace("Removed old pending transaction", "hash", hash)
  682. delete(pool.all, hash)
  683. pool.priced.Removed()
  684. }
  685. // Drop all transactions that are too costly (low balance), and queue any invalids back for later
  686. drops, invalids := list.Filter(state.GetBalance(addr))
  687. for _, tx := range drops {
  688. hash := tx.Hash()
  689. log.Trace("Removed unpayable pending transaction", "hash", hash)
  690. delete(pool.all, hash)
  691. pool.priced.Removed()
  692. pendingNofundsCounter.Inc(1)
  693. }
  694. for _, tx := range invalids {
  695. hash := tx.Hash()
  696. log.Trace("Demoting pending transaction", "hash", hash)
  697. pool.enqueueTx(hash, tx)
  698. }
  699. // Delete the entire queue entry if it became empty.
  700. if list.Empty() {
  701. delete(pool.pending, addr)
  702. delete(pool.beats, addr)
  703. }
  704. }
  705. }
  706. // expirationLoop is a loop that periodically iterates over all accounts with
  707. // queued transactions and drop all that have been inactive for a prolonged amount
  708. // of time.
  709. func (pool *TxPool) expirationLoop() {
  710. defer pool.wg.Done()
  711. evict := time.NewTicker(evictionInterval)
  712. defer evict.Stop()
  713. for {
  714. select {
  715. case <-evict.C:
  716. pool.mu.Lock()
  717. for addr := range pool.queue {
  718. if time.Since(pool.beats[addr]) > maxQueuedLifetime {
  719. for _, tx := range pool.queue[addr].Flatten() {
  720. pool.removeTx(tx.Hash())
  721. }
  722. }
  723. }
  724. pool.mu.Unlock()
  725. case <-pool.quit:
  726. return
  727. }
  728. }
  729. }
  730. // addressByHeartbeat is an account address tagged with its last activity timestamp.
  731. type addressByHeartbeat struct {
  732. address common.Address
  733. heartbeat time.Time
  734. }
  735. type addresssByHeartbeat []addressByHeartbeat
  736. func (a addresssByHeartbeat) Len() int { return len(a) }
  737. func (a addresssByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  738. func (a addresssByHeartbeat) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  739. // txSet represents a set of transaction hashes in which entries
  740. // are automatically dropped after txSetDuration time
  741. type txSet struct {
  742. txMap map[common.Hash]struct{}
  743. txOrd map[uint64]txOrdType
  744. addPtr, delPtr uint64
  745. }
  746. const txSetDuration = time.Hour * 2
  747. // txOrdType represents an entry in the time-ordered list of transaction hashes
  748. type txOrdType struct {
  749. hash common.Hash
  750. time time.Time
  751. }
  752. // newTxSet creates a new transaction set
  753. func newTxSet() *txSet {
  754. return &txSet{
  755. txMap: make(map[common.Hash]struct{}),
  756. txOrd: make(map[uint64]txOrdType),
  757. }
  758. }
  759. // contains returns true if the set contains the given transaction hash
  760. // (not thread safe, should be called from a locked environment)
  761. func (ts *txSet) contains(hash common.Hash) bool {
  762. _, ok := ts.txMap[hash]
  763. return ok
  764. }
  765. // add adds a transaction hash to the set, then removes entries older than txSetDuration
  766. // (not thread safe, should be called from a locked environment)
  767. func (ts *txSet) add(hash common.Hash) {
  768. ts.txMap[hash] = struct{}{}
  769. now := time.Now()
  770. ts.txOrd[ts.addPtr] = txOrdType{hash: hash, time: now}
  771. ts.addPtr++
  772. delBefore := now.Add(-txSetDuration)
  773. for ts.delPtr < ts.addPtr && ts.txOrd[ts.delPtr].time.Before(delBefore) {
  774. delete(ts.txMap, ts.txOrd[ts.delPtr].hash)
  775. delete(ts.txOrd, ts.delPtr)
  776. ts.delPtr++
  777. }
  778. }