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