github.com/4000d/go-ethereum@v1.8.2-0.20180223170251-423c8bb1d821/core/tx_pool.go (about)

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