github.com/isti4github/eth-ecc@v0.0.0-20201227085832-c337f2d99319/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/Onther-Tech/go-ethereum/common"
    29  	"github.com/Onther-Tech/go-ethereum/common/prque"
    30  	"github.com/Onther-Tech/go-ethereum/core/state"
    31  	"github.com/Onther-Tech/go-ethereum/core/types"
    32  	"github.com/Onther-Tech/go-ethereum/event"
    33  	"github.com/Onther-Tech/go-ethereum/log"
    34  	"github.com/Onther-Tech/go-ethereum/metrics"
    35  	"github.com/Onther-Tech/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  	istanbul bool // Fork indicator whether we are in the istanbul stage.
   221  
   222  	currentState  *state.StateDB // Current state in the blockchain head
   223  	pendingNonces *txNoncer      // Pending state tracking virtual nonces
   224  	currentMaxGas uint64         // Current gas limit for transaction caps
   225  
   226  	locals  *accountSet // Set of local transaction to exempt from eviction rules
   227  	journal *txJournal  // Journal of local transaction to back up to disk
   228  
   229  	pending map[common.Address]*txList   // All currently processable transactions
   230  	queue   map[common.Address]*txList   // Queued but non-processable transactions
   231  	beats   map[common.Address]time.Time // Last heartbeat from each known account
   232  	all     *txLookup                    // All transactions to allow lookups
   233  	priced  *txPricedList                // All transactions sorted by price
   234  
   235  	chainHeadCh     chan ChainHeadEvent
   236  	chainHeadSub    event.Subscription
   237  	reqResetCh      chan *txpoolResetRequest
   238  	reqPromoteCh    chan *accountSet
   239  	queueTxEventCh  chan *types.Transaction
   240  	reorgDoneCh     chan chan struct{}
   241  	reorgShutdownCh chan struct{}  // requests shutdown of scheduleReorgLoop
   242  	wg              sync.WaitGroup // tracks loop, scheduleReorgLoop
   243  }
   244  
   245  type txpoolResetRequest struct {
   246  	oldHead, newHead *types.Header
   247  }
   248  
   249  // NewTxPool creates a new transaction pool to gather, sort and filter inbound
   250  // transactions from the network.
   251  func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool {
   252  	// Sanitize the input to ensure no vulnerable gas prices are set
   253  	config = (&config).sanitize()
   254  
   255  	// Create the transaction pool with its initial settings
   256  	pool := &TxPool{
   257  		config:          config,
   258  		chainconfig:     chainconfig,
   259  		chain:           chain,
   260  		signer:          types.NewEIP155Signer(chainconfig.ChainID),
   261  		pending:         make(map[common.Address]*txList),
   262  		queue:           make(map[common.Address]*txList),
   263  		beats:           make(map[common.Address]time.Time),
   264  		all:             newTxLookup(),
   265  		chainHeadCh:     make(chan ChainHeadEvent, chainHeadChanSize),
   266  		reqResetCh:      make(chan *txpoolResetRequest),
   267  		reqPromoteCh:    make(chan *accountSet),
   268  		queueTxEventCh:  make(chan *types.Transaction),
   269  		reorgDoneCh:     make(chan chan struct{}),
   270  		reorgShutdownCh: make(chan struct{}),
   271  		gasPrice:        new(big.Int).SetUint64(config.PriceLimit),
   272  	}
   273  	pool.locals = newAccountSet(pool.signer)
   274  	for _, addr := range config.Locals {
   275  		log.Info("Setting new local account", "address", addr)
   276  		pool.locals.add(addr)
   277  	}
   278  	pool.priced = newTxPricedList(pool.all)
   279  	pool.reset(nil, chain.CurrentBlock().Header())
   280  
   281  	// Start the reorg loop early so it can handle requests generated during journal loading.
   282  	pool.wg.Add(1)
   283  	go pool.scheduleReorgLoop()
   284  
   285  	// If local transactions and journaling is enabled, load from disk
   286  	if !config.NoLocals && config.Journal != "" {
   287  		pool.journal = newTxJournal(config.Journal)
   288  
   289  		if err := pool.journal.load(pool.AddLocals); err != nil {
   290  			log.Warn("Failed to load transaction journal", "err", err)
   291  		}
   292  		if err := pool.journal.rotate(pool.local()); err != nil {
   293  			log.Warn("Failed to rotate transaction journal", "err", err)
   294  		}
   295  	}
   296  
   297  	// Subscribe events from blockchain and start the main event loop.
   298  	pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh)
   299  	pool.wg.Add(1)
   300  	go pool.loop()
   301  
   302  	return pool
   303  }
   304  
   305  // loop is the transaction pool's main event loop, waiting for and reacting to
   306  // outside blockchain events as well as for various reporting and transaction
   307  // eviction events.
   308  func (pool *TxPool) loop() {
   309  	defer pool.wg.Done()
   310  
   311  	var (
   312  		prevPending, prevQueued, prevStales int
   313  		// Start the stats reporting and transaction eviction tickers
   314  		report  = time.NewTicker(statsReportInterval)
   315  		evict   = time.NewTicker(evictionInterval)
   316  		journal = time.NewTicker(pool.config.Rejournal)
   317  		// Track the previous head headers for transaction reorgs
   318  		head = pool.chain.CurrentBlock()
   319  	)
   320  	defer report.Stop()
   321  	defer evict.Stop()
   322  	defer journal.Stop()
   323  
   324  	for {
   325  		select {
   326  		// Handle ChainHeadEvent
   327  		case ev := <-pool.chainHeadCh:
   328  			if ev.Block != nil {
   329  				pool.requestReset(head.Header(), ev.Block.Header())
   330  				head = ev.Block
   331  			}
   332  
   333  		// System shutdown.
   334  		case <-pool.chainHeadSub.Err():
   335  			close(pool.reorgShutdownCh)
   336  			return
   337  
   338  		// Handle stats reporting ticks
   339  		case <-report.C:
   340  			pool.mu.RLock()
   341  			pending, queued := pool.stats()
   342  			stales := pool.priced.stales
   343  			pool.mu.RUnlock()
   344  
   345  			if pending != prevPending || queued != prevQueued || stales != prevStales {
   346  				log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales)
   347  				prevPending, prevQueued, prevStales = pending, queued, stales
   348  			}
   349  
   350  		// Handle inactive account transaction eviction
   351  		case <-evict.C:
   352  			pool.mu.Lock()
   353  			for addr := range pool.queue {
   354  				// Skip local transactions from the eviction mechanism
   355  				if pool.locals.contains(addr) {
   356  					continue
   357  				}
   358  				// Any non-locals old enough should be removed
   359  				if time.Since(pool.beats[addr]) > pool.config.Lifetime {
   360  					for _, tx := range pool.queue[addr].Flatten() {
   361  						pool.removeTx(tx.Hash(), true)
   362  					}
   363  				}
   364  			}
   365  			pool.mu.Unlock()
   366  
   367  		// Handle local transaction journal rotation
   368  		case <-journal.C:
   369  			if pool.journal != nil {
   370  				pool.mu.Lock()
   371  				if err := pool.journal.rotate(pool.local()); err != nil {
   372  					log.Warn("Failed to rotate local tx journal", "err", err)
   373  				}
   374  				pool.mu.Unlock()
   375  			}
   376  		}
   377  	}
   378  }
   379  
   380  // Stop terminates the transaction pool.
   381  func (pool *TxPool) Stop() {
   382  	// Unsubscribe all subscriptions registered from txpool
   383  	pool.scope.Close()
   384  
   385  	// Unsubscribe subscriptions registered from blockchain
   386  	pool.chainHeadSub.Unsubscribe()
   387  	pool.wg.Wait()
   388  
   389  	if pool.journal != nil {
   390  		pool.journal.close()
   391  	}
   392  	log.Info("Transaction pool stopped")
   393  }
   394  
   395  // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
   396  // starts sending event to the given channel.
   397  func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
   398  	return pool.scope.Track(pool.txFeed.Subscribe(ch))
   399  }
   400  
   401  // GasPrice returns the current gas price enforced by the transaction pool.
   402  func (pool *TxPool) GasPrice() *big.Int {
   403  	pool.mu.RLock()
   404  	defer pool.mu.RUnlock()
   405  
   406  	return new(big.Int).Set(pool.gasPrice)
   407  }
   408  
   409  // SetGasPrice updates the minimum price required by the transaction pool for a
   410  // new transaction, and drops all transactions below this threshold.
   411  func (pool *TxPool) SetGasPrice(price *big.Int) {
   412  	pool.mu.Lock()
   413  	defer pool.mu.Unlock()
   414  
   415  	pool.gasPrice = price
   416  	for _, tx := range pool.priced.Cap(price, pool.locals) {
   417  		pool.removeTx(tx.Hash(), false)
   418  	}
   419  	log.Info("Transaction pool price threshold updated", "price", price)
   420  }
   421  
   422  // Nonce returns the next nonce of an account, with all transactions executable
   423  // by the pool already applied on top.
   424  func (pool *TxPool) Nonce(addr common.Address) uint64 {
   425  	pool.mu.RLock()
   426  	defer pool.mu.RUnlock()
   427  
   428  	return pool.pendingNonces.get(addr)
   429  }
   430  
   431  // Stats retrieves the current pool stats, namely the number of pending and the
   432  // number of queued (non-executable) transactions.
   433  func (pool *TxPool) Stats() (int, int) {
   434  	pool.mu.RLock()
   435  	defer pool.mu.RUnlock()
   436  
   437  	return pool.stats()
   438  }
   439  
   440  // stats retrieves the current pool stats, namely the number of pending and the
   441  // number of queued (non-executable) transactions.
   442  func (pool *TxPool) stats() (int, int) {
   443  	pending := 0
   444  	for _, list := range pool.pending {
   445  		pending += list.Len()
   446  	}
   447  	queued := 0
   448  	for _, list := range pool.queue {
   449  		queued += list.Len()
   450  	}
   451  	return pending, queued
   452  }
   453  
   454  // Content retrieves the data content of the transaction pool, returning all the
   455  // pending as well as queued transactions, grouped by account and sorted by nonce.
   456  func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
   457  	pool.mu.Lock()
   458  	defer pool.mu.Unlock()
   459  
   460  	pending := make(map[common.Address]types.Transactions)
   461  	for addr, list := range pool.pending {
   462  		pending[addr] = list.Flatten()
   463  	}
   464  	queued := make(map[common.Address]types.Transactions)
   465  	for addr, list := range pool.queue {
   466  		queued[addr] = list.Flatten()
   467  	}
   468  	return pending, queued
   469  }
   470  
   471  // Pending retrieves all currently processable transactions, grouped by origin
   472  // account and sorted by nonce. The returned transaction set is a copy and can be
   473  // freely modified by calling code.
   474  func (pool *TxPool) Pending() (map[common.Address]types.Transactions, error) {
   475  	pool.mu.Lock()
   476  	defer pool.mu.Unlock()
   477  
   478  	pending := make(map[common.Address]types.Transactions)
   479  	for addr, list := range pool.pending {
   480  		pending[addr] = list.Flatten()
   481  	}
   482  	return pending, nil
   483  }
   484  
   485  // Locals retrieves the accounts currently considered local by the pool.
   486  func (pool *TxPool) Locals() []common.Address {
   487  	pool.mu.Lock()
   488  	defer pool.mu.Unlock()
   489  
   490  	return pool.locals.flatten()
   491  }
   492  
   493  // local retrieves all currently known local transactions, grouped by origin
   494  // account and sorted by nonce. The returned transaction set is a copy and can be
   495  // freely modified by calling code.
   496  func (pool *TxPool) local() map[common.Address]types.Transactions {
   497  	txs := make(map[common.Address]types.Transactions)
   498  	for addr := range pool.locals.accounts {
   499  		if pending := pool.pending[addr]; pending != nil {
   500  			txs[addr] = append(txs[addr], pending.Flatten()...)
   501  		}
   502  		if queued := pool.queue[addr]; queued != nil {
   503  			txs[addr] = append(txs[addr], queued.Flatten()...)
   504  		}
   505  	}
   506  	return txs
   507  }
   508  
   509  // validateTx checks whether a transaction is valid according to the consensus
   510  // rules and adheres to some heuristic limits of the local node (price and size).
   511  func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
   512  	// Heuristic limit, reject transactions over 32KB to prevent DOS attacks
   513  	if tx.Size() > 32*1024 {
   514  		return ErrOversizedData
   515  	}
   516  	// Transactions can't be negative. This may never happen using RLP decoded
   517  	// transactions but may occur if you create a transaction using the RPC.
   518  	if tx.Value().Sign() < 0 {
   519  		return ErrNegativeValue
   520  	}
   521  	// Ensure the transaction doesn't exceed the current block limit gas.
   522  	if pool.currentMaxGas < tx.Gas() {
   523  		return ErrGasLimit
   524  	}
   525  	// Make sure the transaction is signed properly
   526  	from, err := types.Sender(pool.signer, tx)
   527  	if err != nil {
   528  		return ErrInvalidSender
   529  	}
   530  	// Drop non-local transactions under our own minimal accepted gas price
   531  	local = local || pool.locals.contains(from) // account may be local even if the transaction arrived from the network
   532  	if !local && pool.gasPrice.Cmp(tx.GasPrice()) > 0 {
   533  		return ErrUnderpriced
   534  	}
   535  	// Ensure the transaction adheres to nonce ordering
   536  	if pool.currentState.GetNonce(from) > tx.Nonce() {
   537  		return ErrNonceTooLow
   538  	}
   539  	// Transactor should have enough funds to cover the costs
   540  	// cost == V + GP * GL
   541  	if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
   542  		return ErrInsufficientFunds
   543  	}
   544  	// Ensure the transaction has more gas than the basic tx fee.
   545  	intrGas, err := IntrinsicGas(tx.Data(), tx.To() == nil, true, pool.istanbul)
   546  	if err != nil {
   547  		return err
   548  	}
   549  	if tx.Gas() < intrGas {
   550  		return ErrIntrinsicGas
   551  	}
   552  	return nil
   553  }
   554  
   555  // add validates a transaction and inserts it into the non-executable queue for later
   556  // pending promotion and execution. If the transaction is a replacement for an already
   557  // pending or queued one, it overwrites the previous transaction if its price is higher.
   558  //
   559  // If a newly added transaction is marked as local, its sending account will be
   560  // whitelisted, preventing any associated transaction from being dropped out of the pool
   561  // due to pricing constraints.
   562  func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err error) {
   563  	// If the transaction is already known, discard it
   564  	hash := tx.Hash()
   565  	if pool.all.Get(hash) != nil {
   566  		log.Trace("Discarding already known transaction", "hash", hash)
   567  		return false, fmt.Errorf("known transaction: %x", hash)
   568  	}
   569  
   570  	// If the transaction fails basic validation, discard it
   571  	if err := pool.validateTx(tx, local); err != nil {
   572  		log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
   573  		invalidTxMeter.Mark(1)
   574  		return false, err
   575  	}
   576  
   577  	// If the transaction pool is full, discard underpriced transactions
   578  	if uint64(pool.all.Count()) >= pool.config.GlobalSlots+pool.config.GlobalQueue {
   579  		// If the new transaction is underpriced, don't accept it
   580  		if !local && pool.priced.Underpriced(tx, pool.locals) {
   581  			log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
   582  			underpricedTxMeter.Mark(1)
   583  			return false, ErrUnderpriced
   584  		}
   585  		// New transaction is better than our worse ones, make room for it
   586  		drop := pool.priced.Discard(pool.all.Count()-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals)
   587  		for _, tx := range drop {
   588  			log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
   589  			underpricedTxMeter.Mark(1)
   590  			pool.removeTx(tx.Hash(), false)
   591  		}
   592  	}
   593  
   594  	// Try to replace an existing transaction in the pending pool
   595  	from, _ := types.Sender(pool.signer, tx) // already validated
   596  	if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
   597  		// Nonce already pending, check if required price bump is met
   598  		inserted, old := list.Add(tx, pool.config.PriceBump)
   599  		if !inserted {
   600  			pendingDiscardMeter.Mark(1)
   601  			return false, ErrReplaceUnderpriced
   602  		}
   603  		// New transaction is better, replace old one
   604  		if old != nil {
   605  			pool.all.Remove(old.Hash())
   606  			pool.priced.Removed(1)
   607  			pendingReplaceMeter.Mark(1)
   608  		}
   609  		pool.all.Add(tx)
   610  		pool.priced.Put(tx)
   611  		pool.journalTx(from, tx)
   612  		pool.queueTxEvent(tx)
   613  		log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
   614  		return old != nil, nil
   615  	}
   616  
   617  	// New transaction isn't replacing a pending one, push into queue
   618  	replaced, err = pool.enqueueTx(hash, tx)
   619  	if err != nil {
   620  		return false, err
   621  	}
   622  
   623  	// Mark local addresses and journal local transactions
   624  	if local {
   625  		if !pool.locals.contains(from) {
   626  			log.Info("Setting new local account", "address", from)
   627  			pool.locals.add(from)
   628  		}
   629  	}
   630  	if local || pool.locals.contains(from) {
   631  		localCounter.Inc(1)
   632  	}
   633  	pool.journalTx(from, tx)
   634  
   635  	log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
   636  	return replaced, nil
   637  }
   638  
   639  // enqueueTx inserts a new transaction into the non-executable transaction queue.
   640  //
   641  // Note, this method assumes the pool lock is held!
   642  func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction) (bool, error) {
   643  	// Try to insert the transaction into the future queue
   644  	from, _ := types.Sender(pool.signer, tx) // already validated
   645  	if pool.queue[from] == nil {
   646  		pool.queue[from] = newTxList(false)
   647  	}
   648  	inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
   649  	if !inserted {
   650  		// An older transaction was better, discard this
   651  		queuedDiscardMeter.Mark(1)
   652  		return false, ErrReplaceUnderpriced
   653  	}
   654  	// Discard any previous transaction and mark this
   655  	if old != nil {
   656  		pool.all.Remove(old.Hash())
   657  		pool.priced.Removed(1)
   658  		queuedReplaceMeter.Mark(1)
   659  	} else {
   660  		// Nothing was replaced, bump the queued counter
   661  		queuedCounter.Inc(1)
   662  	}
   663  	if pool.all.Get(hash) == nil {
   664  		pool.all.Add(tx)
   665  		pool.priced.Put(tx)
   666  	}
   667  	return old != nil, nil
   668  }
   669  
   670  // journalTx adds the specified transaction to the local disk journal if it is
   671  // deemed to have been sent from a local account.
   672  func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
   673  	// Only journal if it's enabled and the transaction is local
   674  	if pool.journal == nil || !pool.locals.contains(from) {
   675  		return
   676  	}
   677  	if err := pool.journal.insert(tx); err != nil {
   678  		log.Warn("Failed to journal local transaction", "err", err)
   679  	}
   680  }
   681  
   682  // promoteTx adds a transaction to the pending (processable) list of transactions
   683  // and returns whether it was inserted or an older was better.
   684  //
   685  // Note, this method assumes the pool lock is held!
   686  func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool {
   687  	// Try to insert the transaction into the pending queue
   688  	if pool.pending[addr] == nil {
   689  		pool.pending[addr] = newTxList(true)
   690  	}
   691  	list := pool.pending[addr]
   692  
   693  	inserted, old := list.Add(tx, pool.config.PriceBump)
   694  	if !inserted {
   695  		// An older transaction was better, discard this
   696  		pool.all.Remove(hash)
   697  		pool.priced.Removed(1)
   698  
   699  		pendingDiscardMeter.Mark(1)
   700  		return false
   701  	}
   702  	// Otherwise discard any previous transaction and mark this
   703  	if old != nil {
   704  		pool.all.Remove(old.Hash())
   705  		pool.priced.Removed(1)
   706  
   707  		pendingReplaceMeter.Mark(1)
   708  	} else {
   709  		// Nothing was replaced, bump the pending counter
   710  		pendingCounter.Inc(1)
   711  	}
   712  	// Failsafe to work around direct pending inserts (tests)
   713  	if pool.all.Get(hash) == nil {
   714  		pool.all.Add(tx)
   715  		pool.priced.Put(tx)
   716  	}
   717  	// Set the potentially new pending nonce and notify any subsystems of the new tx
   718  	pool.beats[addr] = time.Now()
   719  	pool.pendingNonces.set(addr, tx.Nonce()+1)
   720  
   721  	return true
   722  }
   723  
   724  // AddLocals enqueues a batch of transactions into the pool if they are valid, marking the
   725  // senders as a local ones, ensuring they go around the local pricing constraints.
   726  //
   727  // This method is used to add transactions from the RPC API and performs synchronous pool
   728  // reorganization and event propagation.
   729  func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
   730  	return pool.addTxs(txs, !pool.config.NoLocals, true)
   731  }
   732  
   733  // AddLocal enqueues a single local transaction into the pool if it is valid. This is
   734  // a convenience wrapper aroundd AddLocals.
   735  func (pool *TxPool) AddLocal(tx *types.Transaction) error {
   736  	errs := pool.AddLocals([]*types.Transaction{tx})
   737  	return errs[0]
   738  }
   739  
   740  // AddRemotes enqueues a batch of transactions into the pool if they are valid. If the
   741  // senders are not among the locally tracked ones, full pricing constraints will apply.
   742  //
   743  // This method is used to add transactions from the p2p network and does not wait for pool
   744  // reorganization and internal event propagation.
   745  func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
   746  	return pool.addTxs(txs, false, false)
   747  }
   748  
   749  // This is like AddRemotes, but waits for pool reorganization. Tests use this method.
   750  func (pool *TxPool) AddRemotesSync(txs []*types.Transaction) []error {
   751  	return pool.addTxs(txs, false, true)
   752  }
   753  
   754  // This is like AddRemotes with a single transaction, but waits for pool reorganization. Tests use this method.
   755  func (pool *TxPool) addRemoteSync(tx *types.Transaction) error {
   756  	errs := pool.AddRemotesSync([]*types.Transaction{tx})
   757  	return errs[0]
   758  }
   759  
   760  // AddRemote enqueues a single transaction into the pool if it is valid. This is a convenience
   761  // wrapper around AddRemotes.
   762  //
   763  // Deprecated: use AddRemotes
   764  func (pool *TxPool) AddRemote(tx *types.Transaction) error {
   765  	errs := pool.AddRemotes([]*types.Transaction{tx})
   766  	return errs[0]
   767  }
   768  
   769  // addTxs attempts to queue a batch of transactions if they are valid.
   770  func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error {
   771  	// Cache senders in transactions before obtaining lock (pool.signer is immutable)
   772  	for _, tx := range txs {
   773  		types.Sender(pool.signer, tx)
   774  	}
   775  
   776  	pool.mu.Lock()
   777  	errs, dirtyAddrs := pool.addTxsLocked(txs, local)
   778  	pool.mu.Unlock()
   779  
   780  	done := pool.requestPromoteExecutables(dirtyAddrs)
   781  	if sync {
   782  		<-done
   783  	}
   784  	return errs
   785  }
   786  
   787  // addTxsLocked attempts to queue a batch of transactions if they are valid.
   788  // The transaction pool lock must be held.
   789  func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) ([]error, *accountSet) {
   790  	dirty := newAccountSet(pool.signer)
   791  	errs := make([]error, len(txs))
   792  	for i, tx := range txs {
   793  		replaced, err := pool.add(tx, local)
   794  		errs[i] = err
   795  		if err == nil && !replaced {
   796  			dirty.addTx(tx)
   797  		}
   798  	}
   799  	validMeter.Mark(int64(len(dirty.accounts)))
   800  	return errs, dirty
   801  }
   802  
   803  // Status returns the status (unknown/pending/queued) of a batch of transactions
   804  // identified by their hashes.
   805  func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
   806  	pool.mu.RLock()
   807  	defer pool.mu.RUnlock()
   808  
   809  	status := make([]TxStatus, len(hashes))
   810  	for i, hash := range hashes {
   811  		if tx := pool.all.Get(hash); tx != nil {
   812  			from, _ := types.Sender(pool.signer, tx) // already validated
   813  			if pool.pending[from] != nil && pool.pending[from].txs.items[tx.Nonce()] != nil {
   814  				status[i] = TxStatusPending
   815  			} else {
   816  				status[i] = TxStatusQueued
   817  			}
   818  		}
   819  	}
   820  	return status
   821  }
   822  
   823  // Get returns a transaction if it is contained in the pool and nil otherwise.
   824  func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
   825  	return pool.all.Get(hash)
   826  }
   827  
   828  // removeTx removes a single transaction from the queue, moving all subsequent
   829  // transactions back to the future queue.
   830  func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {
   831  	// Fetch the transaction we wish to delete
   832  	tx := pool.all.Get(hash)
   833  	if tx == nil {
   834  		return
   835  	}
   836  	addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
   837  
   838  	// Remove it from the list of known transactions
   839  	pool.all.Remove(hash)
   840  	if outofbound {
   841  		pool.priced.Removed(1)
   842  	}
   843  	if pool.locals.contains(addr) {
   844  		localCounter.Dec(1)
   845  	}
   846  	// Remove the transaction from the pending lists and reset the account nonce
   847  	if pending := pool.pending[addr]; pending != nil {
   848  		if removed, invalids := pending.Remove(tx); removed {
   849  			// If no more pending transactions are left, remove the list
   850  			if pending.Empty() {
   851  				delete(pool.pending, addr)
   852  				delete(pool.beats, addr)
   853  			}
   854  			// Postpone any invalidated transactions
   855  			for _, tx := range invalids {
   856  				pool.enqueueTx(tx.Hash(), tx)
   857  			}
   858  			// Update the account nonce if needed
   859  			pool.pendingNonces.setIfLower(addr, tx.Nonce())
   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  	// Update all fork indicator by next pending block number.
  1125  	next := new(big.Int).Add(newHead.Number, big.NewInt(1))
  1126  	pool.istanbul = pool.chainconfig.IsIstanbul(next)
  1127  }
  1128  
  1129  // promoteExecutables moves transactions that have become processable from the
  1130  // future queue to the set of pending transactions. During this process, all
  1131  // invalidated transactions (low nonce, low balance) are deleted.
  1132  func (pool *TxPool) promoteExecutables(accounts []common.Address) []*types.Transaction {
  1133  	// Track the promoted transactions to broadcast them at once
  1134  	var promoted []*types.Transaction
  1135  
  1136  	// Iterate over all accounts and promote any executable transactions
  1137  	for _, addr := range accounts {
  1138  		list := pool.queue[addr]
  1139  		if list == nil {
  1140  			continue // Just in case someone calls with a non existing account
  1141  		}
  1142  		// Drop all transactions that are deemed too old (low nonce)
  1143  		forwards := list.Forward(pool.currentState.GetNonce(addr))
  1144  		for _, tx := range forwards {
  1145  			hash := tx.Hash()
  1146  			pool.all.Remove(hash)
  1147  			log.Trace("Removed old queued transaction", "hash", hash)
  1148  		}
  1149  		// Drop all transactions that are too costly (low balance or out of gas)
  1150  		drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  1151  		for _, tx := range drops {
  1152  			hash := tx.Hash()
  1153  			pool.all.Remove(hash)
  1154  			log.Trace("Removed unpayable queued transaction", "hash", hash)
  1155  		}
  1156  		queuedNofundsMeter.Mark(int64(len(drops)))
  1157  
  1158  		// Gather all executable transactions and promote them
  1159  		readies := list.Ready(pool.pendingNonces.get(addr))
  1160  		for _, tx := range readies {
  1161  			hash := tx.Hash()
  1162  			if pool.promoteTx(addr, hash, tx) {
  1163  				log.Trace("Promoting queued transaction", "hash", hash)
  1164  				promoted = append(promoted, tx)
  1165  			}
  1166  		}
  1167  		queuedCounter.Dec(int64(len(readies)))
  1168  
  1169  		// Drop all transactions over the allowed limit
  1170  		var caps types.Transactions
  1171  		if !pool.locals.contains(addr) {
  1172  			caps = list.Cap(int(pool.config.AccountQueue))
  1173  			for _, tx := range caps {
  1174  				hash := tx.Hash()
  1175  				pool.all.Remove(hash)
  1176  				log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  1177  			}
  1178  			queuedRateLimitMeter.Mark(int64(len(caps)))
  1179  		}
  1180  		// Mark all the items dropped as removed
  1181  		pool.priced.Removed(len(forwards) + len(drops) + len(caps))
  1182  		queuedCounter.Dec(int64(len(forwards) + len(drops) + len(caps)))
  1183  		if pool.locals.contains(addr) {
  1184  			localCounter.Dec(int64(len(forwards) + len(drops) + len(caps)))
  1185  		}
  1186  		// Delete the entire queue entry if it became empty.
  1187  		if list.Empty() {
  1188  			delete(pool.queue, addr)
  1189  		}
  1190  	}
  1191  	return promoted
  1192  }
  1193  
  1194  // truncatePending removes transactions from the pending queue if the pool is above the
  1195  // pending limit. The algorithm tries to reduce transaction counts by an approximately
  1196  // equal number for all for accounts with many pending transactions.
  1197  func (pool *TxPool) truncatePending() {
  1198  	pending := uint64(0)
  1199  	for _, list := range pool.pending {
  1200  		pending += uint64(list.Len())
  1201  	}
  1202  	if pending <= pool.config.GlobalSlots {
  1203  		return
  1204  	}
  1205  
  1206  	pendingBeforeCap := pending
  1207  	// Assemble a spam order to penalize large transactors first
  1208  	spammers := prque.New(nil)
  1209  	for addr, list := range pool.pending {
  1210  		// Only evict transactions from high rollers
  1211  		if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  1212  			spammers.Push(addr, int64(list.Len()))
  1213  		}
  1214  	}
  1215  	// Gradually drop transactions from offenders
  1216  	offenders := []common.Address{}
  1217  	for pending > pool.config.GlobalSlots && !spammers.Empty() {
  1218  		// Retrieve the next offender if not local address
  1219  		offender, _ := spammers.Pop()
  1220  		offenders = append(offenders, offender.(common.Address))
  1221  
  1222  		// Equalize balances until all the same or below threshold
  1223  		if len(offenders) > 1 {
  1224  			// Calculate the equalization threshold for all current offenders
  1225  			threshold := pool.pending[offender.(common.Address)].Len()
  1226  
  1227  			// Iteratively reduce all offenders until below limit or threshold reached
  1228  			for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  1229  				for i := 0; i < len(offenders)-1; i++ {
  1230  					list := pool.pending[offenders[i]]
  1231  
  1232  					caps := list.Cap(list.Len() - 1)
  1233  					for _, tx := range caps {
  1234  						// Drop the transaction from the global pools too
  1235  						hash := tx.Hash()
  1236  						pool.all.Remove(hash)
  1237  
  1238  						// Update the account nonce to the dropped transaction
  1239  						pool.pendingNonces.setIfLower(offenders[i], tx.Nonce())
  1240  						log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  1241  					}
  1242  					pool.priced.Removed(len(caps))
  1243  					pendingCounter.Dec(int64(len(caps)))
  1244  					if pool.locals.contains(offenders[i]) {
  1245  						localCounter.Dec(int64(len(caps)))
  1246  					}
  1247  					pending--
  1248  				}
  1249  			}
  1250  		}
  1251  	}
  1252  
  1253  	// If still above threshold, reduce to limit or min allowance
  1254  	if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  1255  		for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  1256  			for _, addr := range offenders {
  1257  				list := pool.pending[addr]
  1258  
  1259  				caps := list.Cap(list.Len() - 1)
  1260  				for _, tx := range caps {
  1261  					// Drop the transaction from the global pools too
  1262  					hash := tx.Hash()
  1263  					pool.all.Remove(hash)
  1264  
  1265  					// Update the account nonce to the dropped transaction
  1266  					pool.pendingNonces.setIfLower(addr, tx.Nonce())
  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  }