github.com/aaa256/atlantis@v0.0.0-20210707112435-42ee889287a2/core/tx_pool.go (about)

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