github.com/oskarth/go-ethereum@v1.6.8-0.20191013093314-dac24a9d3494/core/tx_pool.go (about)

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