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