github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/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  	"math"
    22  	"math/big"
    23  	"sort"
    24  	"sync"
    25  	"sync/atomic"
    26  	"time"
    27  
    28  	"github.com/ethxdao/go-ethereum/common"
    29  	"github.com/ethxdao/go-ethereum/common/prque"
    30  	"github.com/ethxdao/go-ethereum/consensus/misc"
    31  	"github.com/ethxdao/go-ethereum/core/state"
    32  	"github.com/ethxdao/go-ethereum/core/types"
    33  	"github.com/ethxdao/go-ethereum/event"
    34  	"github.com/ethxdao/go-ethereum/log"
    35  	"github.com/ethxdao/go-ethereum/metrics"
    36  	"github.com/ethxdao/go-ethereum/params"
    37  )
    38  
    39  const (
    40  	// chainHeadChanSize is the size of channel listening to ChainHeadEvent.
    41  	chainHeadChanSize = 10
    42  
    43  	// txSlotSize is used to calculate how many data slots a single transaction
    44  	// takes up based on its size. The slots are used as DoS protection, ensuring
    45  	// that validating a new transaction remains a constant operation (in reality
    46  	// O(maxslots), where max slots are 4 currently).
    47  	txSlotSize = 32 * 1024
    48  
    49  	// txMaxSize is the maximum size a single transaction can have. This field has
    50  	// non-trivial consequences: larger transactions are significantly harder and
    51  	// more expensive to propagate; larger transactions also take more resources
    52  	// to validate whether they fit into the pool or not.
    53  	txMaxSize = 4 * txSlotSize // 128KB
    54  )
    55  
    56  var (
    57  	// ErrAlreadyKnown is returned if the transactions is already contained
    58  	// within the pool.
    59  	ErrAlreadyKnown = errors.New("already known")
    60  
    61  	// ErrInvalidSender is returned if the transaction contains an invalid signature.
    62  	ErrInvalidSender = errors.New("invalid sender")
    63  
    64  	// ErrUnderpriced is returned if a transaction's gas price is below the minimum
    65  	// configured for the transaction pool.
    66  	ErrUnderpriced = errors.New("transaction underpriced")
    67  
    68  	// ErrTxPoolOverflow is returned if the transaction pool is full and can't accpet
    69  	// another remote transaction.
    70  	ErrTxPoolOverflow = errors.New("txpool is full")
    71  
    72  	// ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
    73  	// with a different one without the required price bump.
    74  	ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")
    75  
    76  	// ErrGasLimit is returned if a transaction's requested gas limit exceeds the
    77  	// maximum allowance of the current block.
    78  	ErrGasLimit = errors.New("exceeds block gas limit")
    79  
    80  	// ErrNegativeValue is a sanity error to ensure no one is able to specify a
    81  	// transaction with a negative value.
    82  	ErrNegativeValue = errors.New("negative value")
    83  
    84  	// ErrOversizedData is returned if the input data of a transaction is greater
    85  	// than some meaningful limit a user might use. This is not a consensus error
    86  	// making the transaction invalid, rather a DOS protection.
    87  	ErrOversizedData = errors.New("oversized data")
    88  )
    89  
    90  var (
    91  	evictionInterval    = time.Minute     // Time interval to check for evictable transactions
    92  	statsReportInterval = 8 * time.Second // Time interval to report transaction pool stats
    93  )
    94  
    95  var (
    96  	// Metrics for the pending pool
    97  	pendingDiscardMeter   = metrics.NewRegisteredMeter("txpool/pending/discard", nil)
    98  	pendingReplaceMeter   = metrics.NewRegisteredMeter("txpool/pending/replace", nil)
    99  	pendingRateLimitMeter = metrics.NewRegisteredMeter("txpool/pending/ratelimit", nil) // Dropped due to rate limiting
   100  	pendingNofundsMeter   = metrics.NewRegisteredMeter("txpool/pending/nofunds", nil)   // Dropped due to out-of-funds
   101  
   102  	// Metrics for the queued pool
   103  	queuedDiscardMeter   = metrics.NewRegisteredMeter("txpool/queued/discard", nil)
   104  	queuedReplaceMeter   = metrics.NewRegisteredMeter("txpool/queued/replace", nil)
   105  	queuedRateLimitMeter = metrics.NewRegisteredMeter("txpool/queued/ratelimit", nil) // Dropped due to rate limiting
   106  	queuedNofundsMeter   = metrics.NewRegisteredMeter("txpool/queued/nofunds", nil)   // Dropped due to out-of-funds
   107  	queuedEvictionMeter  = metrics.NewRegisteredMeter("txpool/queued/eviction", nil)  // Dropped due to lifetime
   108  
   109  	// General tx metrics
   110  	knownTxMeter       = metrics.NewRegisteredMeter("txpool/known", nil)
   111  	validTxMeter       = metrics.NewRegisteredMeter("txpool/valid", nil)
   112  	invalidTxMeter     = metrics.NewRegisteredMeter("txpool/invalid", nil)
   113  	underpricedTxMeter = metrics.NewRegisteredMeter("txpool/underpriced", nil)
   114  	overflowedTxMeter  = metrics.NewRegisteredMeter("txpool/overflowed", nil)
   115  	// throttleTxMeter counts how many transactions are rejected due to too-many-changes between
   116  	// txpool reorgs.
   117  	throttleTxMeter = metrics.NewRegisteredMeter("txpool/throttle", nil)
   118  	// reorgDurationTimer measures how long time a txpool reorg takes.
   119  	reorgDurationTimer = metrics.NewRegisteredTimer("txpool/reorgtime", nil)
   120  	// dropBetweenReorgHistogram counts how many drops we experience between two reorg runs. It is expected
   121  	// that this number is pretty low, since txpool reorgs happen very frequently.
   122  	dropBetweenReorgHistogram = metrics.NewRegisteredHistogram("txpool/dropbetweenreorg", nil, metrics.NewExpDecaySample(1028, 0.015))
   123  
   124  	pendingGauge = metrics.NewRegisteredGauge("txpool/pending", nil)
   125  	queuedGauge  = metrics.NewRegisteredGauge("txpool/queued", nil)
   126  	localGauge   = metrics.NewRegisteredGauge("txpool/local", nil)
   127  	slotsGauge   = metrics.NewRegisteredGauge("txpool/slots", nil)
   128  
   129  	reheapTimer = metrics.NewRegisteredTimer("txpool/reheap", nil)
   130  )
   131  
   132  // TxStatus is the current status of a transaction as seen by the pool.
   133  type TxStatus uint
   134  
   135  const (
   136  	TxStatusUnknown TxStatus = iota
   137  	TxStatusQueued
   138  	TxStatusPending
   139  	TxStatusIncluded
   140  )
   141  
   142  // blockChain provides the state of blockchain and current gas limit to do
   143  // some pre checks in tx pool and event subscribers.
   144  type blockChain interface {
   145  	CurrentBlock() *types.Block
   146  	GetBlock(hash common.Hash, number uint64) *types.Block
   147  	StateAt(root common.Hash) (*state.StateDB, error)
   148  
   149  	SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
   150  }
   151  
   152  // TxPoolConfig are the configuration parameters of the transaction pool.
   153  type TxPoolConfig struct {
   154  	Locals    []common.Address // Addresses that should be treated by default as local
   155  	NoLocals  bool             // Whether local transaction handling should be disabled
   156  	Journal   string           // Journal of local transactions to survive node restarts
   157  	Rejournal time.Duration    // Time interval to regenerate the local transaction journal
   158  
   159  	PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
   160  	PriceBump  uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)
   161  
   162  	AccountSlots uint64 // Number of executable transaction slots guaranteed per account
   163  	GlobalSlots  uint64 // Maximum number of executable transaction slots for all accounts
   164  	AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
   165  	GlobalQueue  uint64 // Maximum number of non-executable transaction slots for all accounts
   166  
   167  	Lifetime time.Duration // Maximum amount of time non-executable transaction are queued
   168  }
   169  
   170  // DefaultTxPoolConfig contains the default configurations for the transaction
   171  // pool.
   172  var DefaultTxPoolConfig = TxPoolConfig{
   173  	Journal:   "transactions.rlp",
   174  	Rejournal: time.Hour,
   175  
   176  	PriceLimit: 1,
   177  	PriceBump:  10,
   178  
   179  	AccountSlots: 16,
   180  	GlobalSlots:  4096 + 1024, // urgent + floating queue capacity with 4:1 ratio
   181  	AccountQueue: 64,
   182  	GlobalQueue:  1024,
   183  
   184  	Lifetime: 3 * time.Hour,
   185  }
   186  
   187  // sanitize checks the provided user configurations and changes anything that's
   188  // unreasonable or unworkable.
   189  func (config *TxPoolConfig) sanitize() TxPoolConfig {
   190  	conf := *config
   191  	if conf.Rejournal < time.Second {
   192  		log.Warn("Sanitizing invalid txpool journal time", "provided", conf.Rejournal, "updated", time.Second)
   193  		conf.Rejournal = time.Second
   194  	}
   195  	if conf.PriceLimit < 1 {
   196  		log.Warn("Sanitizing invalid txpool price limit", "provided", conf.PriceLimit, "updated", DefaultTxPoolConfig.PriceLimit)
   197  		conf.PriceLimit = DefaultTxPoolConfig.PriceLimit
   198  	}
   199  	if conf.PriceBump < 1 {
   200  		log.Warn("Sanitizing invalid txpool price bump", "provided", conf.PriceBump, "updated", DefaultTxPoolConfig.PriceBump)
   201  		conf.PriceBump = DefaultTxPoolConfig.PriceBump
   202  	}
   203  	if conf.AccountSlots < 1 {
   204  		log.Warn("Sanitizing invalid txpool account slots", "provided", conf.AccountSlots, "updated", DefaultTxPoolConfig.AccountSlots)
   205  		conf.AccountSlots = DefaultTxPoolConfig.AccountSlots
   206  	}
   207  	if conf.GlobalSlots < 1 {
   208  		log.Warn("Sanitizing invalid txpool global slots", "provided", conf.GlobalSlots, "updated", DefaultTxPoolConfig.GlobalSlots)
   209  		conf.GlobalSlots = DefaultTxPoolConfig.GlobalSlots
   210  	}
   211  	if conf.AccountQueue < 1 {
   212  		log.Warn("Sanitizing invalid txpool account queue", "provided", conf.AccountQueue, "updated", DefaultTxPoolConfig.AccountQueue)
   213  		conf.AccountQueue = DefaultTxPoolConfig.AccountQueue
   214  	}
   215  	if conf.GlobalQueue < 1 {
   216  		log.Warn("Sanitizing invalid txpool global queue", "provided", conf.GlobalQueue, "updated", DefaultTxPoolConfig.GlobalQueue)
   217  		conf.GlobalQueue = DefaultTxPoolConfig.GlobalQueue
   218  	}
   219  	if conf.Lifetime < 1 {
   220  		log.Warn("Sanitizing invalid txpool lifetime", "provided", conf.Lifetime, "updated", DefaultTxPoolConfig.Lifetime)
   221  		conf.Lifetime = DefaultTxPoolConfig.Lifetime
   222  	}
   223  	return conf
   224  }
   225  
   226  // TxPool contains all currently known transactions. Transactions
   227  // enter the pool when they are received from the network or submitted
   228  // locally. They exit the pool when they are included in the blockchain.
   229  //
   230  // The pool separates processable transactions (which can be applied to the
   231  // current state) and future transactions. Transactions move between those
   232  // two states over time as they are received and processed.
   233  type TxPool struct {
   234  	config      TxPoolConfig
   235  	chainconfig *params.ChainConfig
   236  	chain       blockChain
   237  	gasPrice    *big.Int
   238  	txFeed      event.Feed
   239  	scope       event.SubscriptionScope
   240  	signer      types.Signer
   241  	mu          sync.RWMutex
   242  
   243  	istanbul bool // Fork indicator whether we are in the istanbul stage.
   244  	eip2718  bool // Fork indicator whether we are using EIP-2718 type transactions.
   245  	eip1559  bool // Fork indicator whether we are using EIP-1559 type transactions.
   246  
   247  	isrome bool // Fork
   248  
   249  	currentState  *state.StateDB // Current state in the blockchain head
   250  	pendingNonces *txNoncer      // Pending state tracking virtual nonces
   251  	currentMaxGas uint64         // Current gas limit for transaction caps
   252  
   253  	locals  *accountSet // Set of local transaction to exempt from eviction rules
   254  	journal *txJournal  // Journal of local transaction to back up to disk
   255  
   256  	pending map[common.Address]*txList   // All currently processable transactions
   257  	queue   map[common.Address]*txList   // Queued but non-processable transactions
   258  	beats   map[common.Address]time.Time // Last heartbeat from each known account
   259  	all     *txLookup                    // All transactions to allow lookups
   260  	priced  *txPricedList                // All transactions sorted by price
   261  
   262  	chainHeadCh     chan ChainHeadEvent
   263  	chainHeadSub    event.Subscription
   264  	reqResetCh      chan *txpoolResetRequest
   265  	reqPromoteCh    chan *accountSet
   266  	queueTxEventCh  chan *types.Transaction
   267  	reorgDoneCh     chan chan struct{}
   268  	reorgShutdownCh chan struct{}  // requests shutdown of scheduleReorgLoop
   269  	wg              sync.WaitGroup // tracks loop, scheduleReorgLoop
   270  	initDoneCh      chan struct{}  // is closed once the pool is initialized (for tests)
   271  
   272  	changesSinceReorg int // A counter for how many drops we've performed in-between reorg.
   273  }
   274  
   275  type txpoolResetRequest struct {
   276  	oldHead, newHead *types.Header
   277  }
   278  
   279  // NewTxPool creates a new transaction pool to gather, sort and filter inbound
   280  // transactions from the network.
   281  func NewTxPool(config TxPoolConfig, chainconfig *params.ChainConfig, chain blockChain) *TxPool {
   282  	// Sanitize the input to ensure no vulnerable gas prices are set
   283  	config = (&config).sanitize()
   284  
   285  	// Create the transaction pool with its initial settings
   286  	pool := &TxPool{
   287  		config:          config,
   288  		chainconfig:     chainconfig,
   289  		chain:           chain,
   290  		signer:          types.LatestSigner(chainconfig),
   291  		pending:         make(map[common.Address]*txList),
   292  		queue:           make(map[common.Address]*txList),
   293  		beats:           make(map[common.Address]time.Time),
   294  		all:             newTxLookup(),
   295  		chainHeadCh:     make(chan ChainHeadEvent, chainHeadChanSize),
   296  		reqResetCh:      make(chan *txpoolResetRequest),
   297  		reqPromoteCh:    make(chan *accountSet),
   298  		queueTxEventCh:  make(chan *types.Transaction),
   299  		reorgDoneCh:     make(chan chan struct{}),
   300  		reorgShutdownCh: make(chan struct{}),
   301  		initDoneCh:      make(chan struct{}),
   302  		gasPrice:        new(big.Int).SetUint64(config.PriceLimit),
   303  	}
   304  	pool.locals = newAccountSet(pool.signer)
   305  	for _, addr := range config.Locals {
   306  		log.Info("Setting new local account", "address", addr)
   307  		pool.locals.add(addr)
   308  	}
   309  	pool.priced = newTxPricedList(pool.all)
   310  	pool.reset(nil, chain.CurrentBlock().Header())
   311  
   312  	// Start the reorg loop early so it can handle requests generated during journal loading.
   313  	pool.wg.Add(1)
   314  	go pool.scheduleReorgLoop()
   315  
   316  	// If local transactions and journaling is enabled, load from disk
   317  	if !config.NoLocals && config.Journal != "" {
   318  		pool.journal = newTxJournal(config.Journal)
   319  
   320  		if err := pool.journal.load(pool.AddLocals); err != nil {
   321  			log.Warn("Failed to load transaction journal", "err", err)
   322  		}
   323  		if err := pool.journal.rotate(pool.local()); err != nil {
   324  			log.Warn("Failed to rotate transaction journal", "err", err)
   325  		}
   326  	}
   327  
   328  	// Subscribe events from blockchain and start the main event loop.
   329  	pool.chainHeadSub = pool.chain.SubscribeChainHeadEvent(pool.chainHeadCh)
   330  	pool.wg.Add(1)
   331  	go pool.loop()
   332  
   333  	return pool
   334  }
   335  
   336  // loop is the transaction pool's main event loop, waiting for and reacting to
   337  // outside blockchain events as well as for various reporting and transaction
   338  // eviction events.
   339  func (pool *TxPool) loop() {
   340  	defer pool.wg.Done()
   341  
   342  	var (
   343  		prevPending, prevQueued, prevStales int
   344  		// Start the stats reporting and transaction eviction tickers
   345  		report  = time.NewTicker(statsReportInterval)
   346  		evict   = time.NewTicker(evictionInterval)
   347  		journal = time.NewTicker(pool.config.Rejournal)
   348  		// Track the previous head headers for transaction reorgs
   349  		head = pool.chain.CurrentBlock()
   350  	)
   351  	defer report.Stop()
   352  	defer evict.Stop()
   353  	defer journal.Stop()
   354  
   355  	// Notify tests that the init phase is done
   356  	close(pool.initDoneCh)
   357  	for {
   358  		select {
   359  		// Handle ChainHeadEvent
   360  		case ev := <-pool.chainHeadCh:
   361  			if ev.Block != nil {
   362  				pool.requestReset(head.Header(), ev.Block.Header())
   363  				head = ev.Block
   364  			}
   365  
   366  		// System shutdown.
   367  		case <-pool.chainHeadSub.Err():
   368  			close(pool.reorgShutdownCh)
   369  			return
   370  
   371  		// Handle stats reporting ticks
   372  		case <-report.C:
   373  			pool.mu.RLock()
   374  			pending, queued := pool.stats()
   375  			pool.mu.RUnlock()
   376  			stales := int(atomic.LoadInt64(&pool.priced.stales))
   377  
   378  			if pending != prevPending || queued != prevQueued || stales != prevStales {
   379  				log.Debug("Transaction pool status report", "executable", pending, "queued", queued, "stales", stales)
   380  				prevPending, prevQueued, prevStales = pending, queued, stales
   381  			}
   382  
   383  		// Handle inactive account transaction eviction
   384  		case <-evict.C:
   385  			pool.mu.Lock()
   386  			for addr := range pool.queue {
   387  				// Skip local transactions from the eviction mechanism
   388  				if pool.locals.contains(addr) {
   389  					continue
   390  				}
   391  				// Any non-locals old enough should be removed
   392  				if time.Since(pool.beats[addr]) > pool.config.Lifetime {
   393  					list := pool.queue[addr].Flatten()
   394  					for _, tx := range list {
   395  						pool.removeTx(tx.Hash(), true)
   396  					}
   397  					queuedEvictionMeter.Mark(int64(len(list)))
   398  				}
   399  			}
   400  			pool.mu.Unlock()
   401  
   402  		// Handle local transaction journal rotation
   403  		case <-journal.C:
   404  			if pool.journal != nil {
   405  				pool.mu.Lock()
   406  				if err := pool.journal.rotate(pool.local()); err != nil {
   407  					log.Warn("Failed to rotate local tx journal", "err", err)
   408  				}
   409  				pool.mu.Unlock()
   410  			}
   411  		}
   412  	}
   413  }
   414  
   415  // Stop terminates the transaction pool.
   416  func (pool *TxPool) Stop() {
   417  	// Unsubscribe all subscriptions registered from txpool
   418  	pool.scope.Close()
   419  
   420  	// Unsubscribe subscriptions registered from blockchain
   421  	pool.chainHeadSub.Unsubscribe()
   422  	pool.wg.Wait()
   423  
   424  	if pool.journal != nil {
   425  		pool.journal.close()
   426  	}
   427  	log.Info("Transaction pool stopped")
   428  }
   429  
   430  // SubscribeNewTxsEvent registers a subscription of NewTxsEvent and
   431  // starts sending event to the given channel.
   432  func (pool *TxPool) SubscribeNewTxsEvent(ch chan<- NewTxsEvent) event.Subscription {
   433  	return pool.scope.Track(pool.txFeed.Subscribe(ch))
   434  }
   435  
   436  // GasPrice returns the current gas price enforced by the transaction pool.
   437  func (pool *TxPool) GasPrice() *big.Int {
   438  	pool.mu.RLock()
   439  	defer pool.mu.RUnlock()
   440  
   441  	return new(big.Int).Set(pool.gasPrice)
   442  }
   443  
   444  // SetGasPrice updates the minimum price required by the transaction pool for a
   445  // new transaction, and drops all transactions below this threshold.
   446  func (pool *TxPool) SetGasPrice(price *big.Int) {
   447  	pool.mu.Lock()
   448  	defer pool.mu.Unlock()
   449  
   450  	old := pool.gasPrice
   451  	pool.gasPrice = price
   452  	// if the min miner fee increased, remove transactions below the new threshold
   453  	if price.Cmp(old) > 0 {
   454  		// pool.priced is sorted by GasFeeCap, so we have to iterate through pool.all instead
   455  		drop := pool.all.RemotesBelowTip(price)
   456  		for _, tx := range drop {
   457  			pool.removeTx(tx.Hash(), false)
   458  		}
   459  		pool.priced.Removed(len(drop))
   460  	}
   461  
   462  	log.Info("Transaction pool price threshold updated", "price", price)
   463  }
   464  
   465  // Nonce returns the next nonce of an account, with all transactions executable
   466  // by the pool already applied on top.
   467  func (pool *TxPool) Nonce(addr common.Address) uint64 {
   468  	pool.mu.RLock()
   469  	defer pool.mu.RUnlock()
   470  
   471  	return pool.pendingNonces.get(addr)
   472  }
   473  
   474  // Stats retrieves the current pool stats, namely the number of pending and the
   475  // number of queued (non-executable) transactions.
   476  func (pool *TxPool) Stats() (int, int) {
   477  	pool.mu.RLock()
   478  	defer pool.mu.RUnlock()
   479  
   480  	return pool.stats()
   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  	pending := 0
   487  	for _, list := range pool.pending {
   488  		pending += list.Len()
   489  	}
   490  	queued := 0
   491  	for _, list := range pool.queue {
   492  		queued += list.Len()
   493  	}
   494  	return pending, queued
   495  }
   496  
   497  // Content retrieves the data content of the transaction pool, returning all the
   498  // pending as well as queued transactions, grouped by account and sorted by nonce.
   499  func (pool *TxPool) Content() (map[common.Address]types.Transactions, map[common.Address]types.Transactions) {
   500  	pool.mu.Lock()
   501  	defer pool.mu.Unlock()
   502  
   503  	pending := make(map[common.Address]types.Transactions)
   504  	for addr, list := range pool.pending {
   505  		pending[addr] = list.Flatten()
   506  	}
   507  	queued := make(map[common.Address]types.Transactions)
   508  	for addr, list := range pool.queue {
   509  		queued[addr] = list.Flatten()
   510  	}
   511  	return pending, queued
   512  }
   513  
   514  // ContentFrom retrieves the data content of the transaction pool, returning the
   515  // pending as well as queued transactions of this address, grouped by nonce.
   516  func (pool *TxPool) ContentFrom(addr common.Address) (types.Transactions, types.Transactions) {
   517  	pool.mu.RLock()
   518  	defer pool.mu.RUnlock()
   519  
   520  	var pending types.Transactions
   521  	if list, ok := pool.pending[addr]; ok {
   522  		pending = list.Flatten()
   523  	}
   524  	var queued types.Transactions
   525  	if list, ok := pool.queue[addr]; ok {
   526  		queued = list.Flatten()
   527  	}
   528  	return pending, queued
   529  }
   530  
   531  // Pending retrieves all currently processable transactions, grouped by origin
   532  // account and sorted by nonce. The returned transaction set is a copy and can be
   533  // freely modified by calling code.
   534  //
   535  // The enforceTips parameter can be used to do an extra filtering on the pending
   536  // transactions and only return those whose **effective** tip is large enough in
   537  // the next pending execution environment.
   538  func (pool *TxPool) Pending(enforceTips bool) map[common.Address]types.Transactions {
   539  	pool.mu.Lock()
   540  	defer pool.mu.Unlock()
   541  
   542  	pending := make(map[common.Address]types.Transactions)
   543  	for addr, list := range pool.pending {
   544  		txs := list.Flatten()
   545  
   546  		// If the miner requests tip enforcement, cap the lists now
   547  		if enforceTips && !pool.locals.contains(addr) {
   548  			for i, tx := range txs {
   549  				if tx.EffectiveGasTipIntCmp(pool.gasPrice, pool.priced.urgent.baseFee) < 0 {
   550  					txs = txs[:i]
   551  					break
   552  				}
   553  			}
   554  		}
   555  		if len(txs) > 0 {
   556  			pending[addr] = txs
   557  		}
   558  	}
   559  	return pending
   560  }
   561  
   562  // Locals retrieves the accounts currently considered local by the pool.
   563  func (pool *TxPool) Locals() []common.Address {
   564  	pool.mu.Lock()
   565  	defer pool.mu.Unlock()
   566  
   567  	return pool.locals.flatten()
   568  }
   569  
   570  // local retrieves all currently known local transactions, grouped by origin
   571  // account and sorted by nonce. The returned transaction set is a copy and can be
   572  // freely modified by calling code.
   573  func (pool *TxPool) local() map[common.Address]types.Transactions {
   574  	txs := make(map[common.Address]types.Transactions)
   575  	for addr := range pool.locals.accounts {
   576  		if pending := pool.pending[addr]; pending != nil {
   577  			txs[addr] = append(txs[addr], pending.Flatten()...)
   578  		}
   579  		if queued := pool.queue[addr]; queued != nil {
   580  			txs[addr] = append(txs[addr], queued.Flatten()...)
   581  		}
   582  	}
   583  	return txs
   584  }
   585  
   586  // validateTx checks whether a transaction is valid according to the consensus
   587  // rules and adheres to some heuristic limits of the local node (price and size).
   588  func (pool *TxPool) validateTx(tx *types.Transaction, local bool) error {
   589  	// Accept only legacy transactions until EIP-2718/2930 activates.
   590  	if !pool.eip2718 && tx.Type() != types.LegacyTxType {
   591  		return ErrTxTypeNotSupported
   592  	}
   593  	// Reject dynamic fee transactions until EIP-1559 activates.
   594  	if !pool.eip1559 && tx.Type() == types.DynamicFeeTxType {
   595  		return ErrTxTypeNotSupported
   596  	}
   597  
   598  	if pool.isrome {
   599  		pool.signer = types.LatestSigner(pool.chainconfig)
   600  	}
   601  	// Reject transactions over defined size to prevent DOS attacks
   602  	if uint64(tx.Size()) > txMaxSize {
   603  		return ErrOversizedData
   604  	}
   605  	// Transactions can't be negative. This may never happen using RLP decoded
   606  	// transactions but may occur if you create a transaction using the RPC.
   607  	if tx.Value().Sign() < 0 {
   608  		return ErrNegativeValue
   609  	}
   610  	// Ensure the transaction doesn't exceed the current block limit gas.
   611  	if pool.currentMaxGas < tx.Gas() {
   612  		return ErrGasLimit
   613  	}
   614  	// Sanity check for extremely large numbers
   615  	if tx.GasFeeCap().BitLen() > 256 {
   616  		return ErrFeeCapVeryHigh
   617  	}
   618  	if tx.GasTipCap().BitLen() > 256 {
   619  		return ErrTipVeryHigh
   620  	}
   621  	// Ensure gasFeeCap is greater than or equal to gasTipCap.
   622  	if tx.GasFeeCapIntCmp(tx.GasTipCap()) < 0 {
   623  		return ErrTipAboveFeeCap
   624  	}
   625  	// Make sure the transaction is signed properly.
   626  	from, err := types.Sender(pool.signer, tx)
   627  	if err != nil {
   628  		return ErrInvalidSender
   629  	}
   630  	// Drop non-local transactions under our own minimal accepted gas price or tip
   631  	if !local && tx.GasTipCapIntCmp(pool.gasPrice) < 0 {
   632  		return ErrUnderpriced
   633  	}
   634  	// Ensure the transaction adheres to nonce ordering
   635  	if pool.currentState.GetNonce(from) > tx.Nonce() {
   636  		return ErrNonceTooLow
   637  	}
   638  	// Transactor should have enough funds to cover the costs
   639  	// cost == V + GP * GL
   640  	if pool.currentState.GetBalance(from).Cmp(tx.Cost()) < 0 {
   641  		return ErrInsufficientFunds
   642  	}
   643  	// Ensure the transaction has more gas than the basic tx fee.
   644  	intrGas, err := IntrinsicGas(tx.Data(), tx.AccessList(), tx.To() == nil, true, pool.istanbul)
   645  	if err != nil {
   646  		return err
   647  	}
   648  	if tx.Gas() < intrGas {
   649  		return ErrIntrinsicGas
   650  	}
   651  	return nil
   652  }
   653  
   654  // add validates a transaction and inserts it into the non-executable queue for later
   655  // pending promotion and execution. If the transaction is a replacement for an already
   656  // pending or queued one, it overwrites the previous transaction if its price is higher.
   657  //
   658  // If a newly added transaction is marked as local, its sending account will be
   659  // be added to the allowlist, preventing any associated transaction from being dropped
   660  // out of the pool due to pricing constraints.
   661  func (pool *TxPool) add(tx *types.Transaction, local bool) (replaced bool, err error) {
   662  	// If the transaction is already known, discard it
   663  	hash := tx.Hash()
   664  	if pool.all.Get(hash) != nil {
   665  		log.Trace("Discarding already known transaction", "hash", hash)
   666  		knownTxMeter.Mark(1)
   667  		return false, ErrAlreadyKnown
   668  	}
   669  	// Make the local flag. If it's from local source or it's from the network but
   670  	// the sender is marked as local previously, treat it as the local transaction.
   671  	isLocal := local || pool.locals.containsTx(tx)
   672  
   673  	// If the transaction fails basic validation, discard it
   674  	if err := pool.validateTx(tx, isLocal); err != nil {
   675  		log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
   676  		invalidTxMeter.Mark(1)
   677  		return false, err
   678  	}
   679  	// If the transaction pool is full, discard underpriced transactions
   680  	if uint64(pool.all.Slots()+numSlots(tx)) > pool.config.GlobalSlots+pool.config.GlobalQueue {
   681  		// If the new transaction is underpriced, don't accept it
   682  		if !isLocal && pool.priced.Underpriced(tx) {
   683  			log.Trace("Discarding underpriced transaction", "hash", hash, "gasTipCap", tx.GasTipCap(), "gasFeeCap", tx.GasFeeCap())
   684  			underpricedTxMeter.Mark(1)
   685  			return false, ErrUnderpriced
   686  		}
   687  		// We're about to replace a transaction. The reorg does a more thorough
   688  		// analysis of what to remove and how, but it runs async. We don't want to
   689  		// do too many replacements between reorg-runs, so we cap the number of
   690  		// replacements to 25% of the slots
   691  		if pool.changesSinceReorg > int(pool.config.GlobalSlots/4) {
   692  			throttleTxMeter.Mark(1)
   693  			return false, ErrTxPoolOverflow
   694  		}
   695  
   696  		// New transaction is better than our worse ones, make room for it.
   697  		// If it's a local transaction, forcibly discard all available transactions.
   698  		// Otherwise if we can't make enough room for new one, abort the operation.
   699  		drop, success := pool.priced.Discard(pool.all.Slots()-int(pool.config.GlobalSlots+pool.config.GlobalQueue)+numSlots(tx), isLocal)
   700  
   701  		// Special case, we still can't make the room for the new remote one.
   702  		if !isLocal && !success {
   703  			log.Trace("Discarding overflown transaction", "hash", hash)
   704  			overflowedTxMeter.Mark(1)
   705  			return false, ErrTxPoolOverflow
   706  		}
   707  		// Bump the counter of rejections-since-reorg
   708  		pool.changesSinceReorg += len(drop)
   709  		// Kick out the underpriced remote transactions.
   710  		for _, tx := range drop {
   711  			log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "gasTipCap", tx.GasTipCap(), "gasFeeCap", tx.GasFeeCap())
   712  			underpricedTxMeter.Mark(1)
   713  			pool.removeTx(tx.Hash(), false)
   714  		}
   715  	}
   716  	// Try to replace an existing transaction in the pending pool
   717  	from, _ := types.Sender(pool.signer, tx) // already validated
   718  	if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
   719  		// Nonce already pending, check if required price bump is met
   720  		inserted, old := list.Add(tx, pool.config.PriceBump)
   721  		if !inserted {
   722  			pendingDiscardMeter.Mark(1)
   723  			return false, ErrReplaceUnderpriced
   724  		}
   725  		// New transaction is better, replace old one
   726  		if old != nil {
   727  			pool.all.Remove(old.Hash())
   728  			pool.priced.Removed(1)
   729  			pendingReplaceMeter.Mark(1)
   730  		}
   731  		pool.all.Add(tx, isLocal)
   732  		pool.priced.Put(tx, isLocal)
   733  		pool.journalTx(from, tx)
   734  		pool.queueTxEvent(tx)
   735  		log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
   736  
   737  		// Successful promotion, bump the heartbeat
   738  		pool.beats[from] = time.Now()
   739  		return old != nil, nil
   740  	}
   741  	// New transaction isn't replacing a pending one, push into queue
   742  	replaced, err = pool.enqueueTx(hash, tx, isLocal, true)
   743  	if err != nil {
   744  		return false, err
   745  	}
   746  	// Mark local addresses and journal local transactions
   747  	if local && !pool.locals.contains(from) {
   748  		log.Info("Setting new local account", "address", from)
   749  		pool.locals.add(from)
   750  		pool.priced.Removed(pool.all.RemoteToLocals(pool.locals)) // Migrate the remotes if it's marked as local first time.
   751  	}
   752  	if isLocal {
   753  		localGauge.Inc(1)
   754  	}
   755  	pool.journalTx(from, tx)
   756  
   757  	log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
   758  	return replaced, nil
   759  }
   760  
   761  // enqueueTx inserts a new transaction into the non-executable transaction queue.
   762  //
   763  // Note, this method assumes the pool lock is held!
   764  func (pool *TxPool) enqueueTx(hash common.Hash, tx *types.Transaction, local bool, addAll bool) (bool, error) {
   765  	// Try to insert the transaction into the future queue
   766  	from, _ := types.Sender(pool.signer, tx) // already validated
   767  	if pool.queue[from] == nil {
   768  		pool.queue[from] = newTxList(false)
   769  	}
   770  	inserted, old := pool.queue[from].Add(tx, pool.config.PriceBump)
   771  	if !inserted {
   772  		// An older transaction was better, discard this
   773  		queuedDiscardMeter.Mark(1)
   774  		return false, ErrReplaceUnderpriced
   775  	}
   776  	// Discard any previous transaction and mark this
   777  	if old != nil {
   778  		pool.all.Remove(old.Hash())
   779  		pool.priced.Removed(1)
   780  		queuedReplaceMeter.Mark(1)
   781  	} else {
   782  		// Nothing was replaced, bump the queued counter
   783  		queuedGauge.Inc(1)
   784  	}
   785  	// If the transaction isn't in lookup set but it's expected to be there,
   786  	// show the error log.
   787  	if pool.all.Get(hash) == nil && !addAll {
   788  		log.Error("Missing transaction in lookup set, please report the issue", "hash", hash)
   789  	}
   790  	if addAll {
   791  		pool.all.Add(tx, local)
   792  		pool.priced.Put(tx, local)
   793  	}
   794  	// If we never record the heartbeat, do it right now.
   795  	if _, exist := pool.beats[from]; !exist {
   796  		pool.beats[from] = time.Now()
   797  	}
   798  	return old != nil, nil
   799  }
   800  
   801  // journalTx adds the specified transaction to the local disk journal if it is
   802  // deemed to have been sent from a local account.
   803  func (pool *TxPool) journalTx(from common.Address, tx *types.Transaction) {
   804  	// Only journal if it's enabled and the transaction is local
   805  	if pool.journal == nil || !pool.locals.contains(from) {
   806  		return
   807  	}
   808  	if err := pool.journal.insert(tx); err != nil {
   809  		log.Warn("Failed to journal local transaction", "err", err)
   810  	}
   811  }
   812  
   813  // promoteTx adds a transaction to the pending (processable) list of transactions
   814  // and returns whether it was inserted or an older was better.
   815  //
   816  // Note, this method assumes the pool lock is held!
   817  func (pool *TxPool) promoteTx(addr common.Address, hash common.Hash, tx *types.Transaction) bool {
   818  	// Try to insert the transaction into the pending queue
   819  	if pool.pending[addr] == nil {
   820  		pool.pending[addr] = newTxList(true)
   821  	}
   822  	list := pool.pending[addr]
   823  
   824  	inserted, old := list.Add(tx, pool.config.PriceBump)
   825  	if !inserted {
   826  		// An older transaction was better, discard this
   827  		pool.all.Remove(hash)
   828  		pool.priced.Removed(1)
   829  		pendingDiscardMeter.Mark(1)
   830  		return false
   831  	}
   832  	// Otherwise discard any previous transaction and mark this
   833  	if old != nil {
   834  		pool.all.Remove(old.Hash())
   835  		pool.priced.Removed(1)
   836  		pendingReplaceMeter.Mark(1)
   837  	} else {
   838  		// Nothing was replaced, bump the pending counter
   839  		pendingGauge.Inc(1)
   840  	}
   841  	// Set the potentially new pending nonce and notify any subsystems of the new tx
   842  	pool.pendingNonces.set(addr, tx.Nonce()+1)
   843  
   844  	// Successful promotion, bump the heartbeat
   845  	pool.beats[addr] = time.Now()
   846  	return true
   847  }
   848  
   849  // AddLocals enqueues a batch of transactions into the pool if they are valid, marking the
   850  // senders as a local ones, ensuring they go around the local pricing constraints.
   851  //
   852  // This method is used to add transactions from the RPC API and performs synchronous pool
   853  // reorganization and event propagation.
   854  func (pool *TxPool) AddLocals(txs []*types.Transaction) []error {
   855  	return pool.addTxs(txs, !pool.config.NoLocals, true)
   856  }
   857  
   858  // AddLocal enqueues a single local transaction into the pool if it is valid. This is
   859  // a convenience wrapper aroundd AddLocals.
   860  func (pool *TxPool) AddLocal(tx *types.Transaction) error {
   861  	errs := pool.AddLocals([]*types.Transaction{tx})
   862  	return errs[0]
   863  }
   864  
   865  // AddRemotes enqueues a batch of transactions into the pool if they are valid. If the
   866  // senders are not among the locally tracked ones, full pricing constraints will apply.
   867  //
   868  // This method is used to add transactions from the p2p network and does not wait for pool
   869  // reorganization and internal event propagation.
   870  func (pool *TxPool) AddRemotes(txs []*types.Transaction) []error {
   871  	return pool.addTxs(txs, false, false)
   872  }
   873  
   874  // This is like AddRemotes, but waits for pool reorganization. Tests use this method.
   875  func (pool *TxPool) AddRemotesSync(txs []*types.Transaction) []error {
   876  	return pool.addTxs(txs, false, true)
   877  }
   878  
   879  // This is like AddRemotes with a single transaction, but waits for pool reorganization. Tests use this method.
   880  func (pool *TxPool) addRemoteSync(tx *types.Transaction) error {
   881  	errs := pool.AddRemotesSync([]*types.Transaction{tx})
   882  	return errs[0]
   883  }
   884  
   885  // AddRemote enqueues a single transaction into the pool if it is valid. This is a convenience
   886  // wrapper around AddRemotes.
   887  //
   888  // Deprecated: use AddRemotes
   889  func (pool *TxPool) AddRemote(tx *types.Transaction) error {
   890  	errs := pool.AddRemotes([]*types.Transaction{tx})
   891  	return errs[0]
   892  }
   893  
   894  // addTxs attempts to queue a batch of transactions if they are valid.
   895  func (pool *TxPool) addTxs(txs []*types.Transaction, local, sync bool) []error {
   896  	// Filter out known ones without obtaining the pool lock or recovering signatures
   897  	var (
   898  		errs = make([]error, len(txs))
   899  		news = make([]*types.Transaction, 0, len(txs))
   900  	)
   901  	for i, tx := range txs {
   902  
   903  		// If the transaction is known, pre-set the error slot
   904  		if pool.all.Get(tx.Hash()) != nil {
   905  			errs[i] = ErrAlreadyKnown
   906  			knownTxMeter.Mark(1)
   907  			continue
   908  		}
   909  
   910  		if pool.isrome {
   911  			pool.signer = types.LatestSigner(pool.chainconfig)
   912  		}
   913  
   914  		// Exclude transactions with invalid signatures as soon as
   915  		// possible and cache senders in transactions before
   916  		// obtaining lock
   917  		_, err := types.Sender(pool.signer, tx)
   918  		if err != nil {
   919  			errs[i] = ErrInvalidSender
   920  			invalidTxMeter.Mark(1)
   921  			continue
   922  		}
   923  		// Accumulate all unknown transactions for deeper processing
   924  		news = append(news, tx)
   925  	}
   926  	if len(news) == 0 {
   927  		return errs
   928  	}
   929  
   930  	// Process all the new transaction and merge any errors into the original slice
   931  	pool.mu.Lock()
   932  	newErrs, dirtyAddrs := pool.addTxsLocked(news, local)
   933  	pool.mu.Unlock()
   934  
   935  	var nilSlot = 0
   936  	for _, err := range newErrs {
   937  		for errs[nilSlot] != nil {
   938  			nilSlot++
   939  		}
   940  		errs[nilSlot] = err
   941  		nilSlot++
   942  	}
   943  	// Reorg the pool internals if needed and return
   944  	done := pool.requestPromoteExecutables(dirtyAddrs)
   945  	if sync {
   946  		<-done
   947  	}
   948  	return errs
   949  }
   950  
   951  // addTxsLocked attempts to queue a batch of transactions if they are valid.
   952  // The transaction pool lock must be held.
   953  func (pool *TxPool) addTxsLocked(txs []*types.Transaction, local bool) ([]error, *accountSet) {
   954  	dirty := newAccountSet(pool.signer)
   955  	errs := make([]error, len(txs))
   956  	for i, tx := range txs {
   957  		replaced, err := pool.add(tx, local)
   958  		errs[i] = err
   959  		if err == nil && !replaced {
   960  			dirty.addTx(tx)
   961  		}
   962  	}
   963  	validTxMeter.Mark(int64(len(dirty.accounts)))
   964  	return errs, dirty
   965  }
   966  
   967  // Status returns the status (unknown/pending/queued) of a batch of transactions
   968  // identified by their hashes.
   969  func (pool *TxPool) Status(hashes []common.Hash) []TxStatus {
   970  	status := make([]TxStatus, len(hashes))
   971  	for i, hash := range hashes {
   972  		tx := pool.Get(hash)
   973  		if tx == nil {
   974  			continue
   975  		}
   976  		from, _ := types.Sender(pool.signer, tx) // already validated
   977  		pool.mu.RLock()
   978  		if txList := pool.pending[from]; txList != nil && txList.txs.items[tx.Nonce()] != nil {
   979  			status[i] = TxStatusPending
   980  		} else if txList := pool.queue[from]; txList != nil && txList.txs.items[tx.Nonce()] != nil {
   981  			status[i] = TxStatusQueued
   982  		}
   983  		// implicit else: the tx may have been included into a block between
   984  		// checking pool.Get and obtaining the lock. In that case, TxStatusUnknown is correct
   985  		pool.mu.RUnlock()
   986  	}
   987  	return status
   988  }
   989  
   990  // Get returns a transaction if it is contained in the pool and nil otherwise.
   991  func (pool *TxPool) Get(hash common.Hash) *types.Transaction {
   992  	return pool.all.Get(hash)
   993  }
   994  
   995  // Has returns an indicator whether txpool has a transaction cached with the
   996  // given hash.
   997  func (pool *TxPool) Has(hash common.Hash) bool {
   998  	return pool.all.Get(hash) != nil
   999  }
  1000  
  1001  // removeTx removes a single transaction from the queue, moving all subsequent
  1002  // transactions back to the future queue.
  1003  func (pool *TxPool) removeTx(hash common.Hash, outofbound bool) {
  1004  	// Fetch the transaction we wish to delete
  1005  	tx := pool.all.Get(hash)
  1006  	if tx == nil {
  1007  		return
  1008  	}
  1009  	addr, _ := types.Sender(pool.signer, tx) // already validated during insertion
  1010  
  1011  	// Remove it from the list of known transactions
  1012  	pool.all.Remove(hash)
  1013  	if outofbound {
  1014  		pool.priced.Removed(1)
  1015  	}
  1016  	if pool.locals.contains(addr) {
  1017  		localGauge.Dec(1)
  1018  	}
  1019  	// Remove the transaction from the pending lists and reset the account nonce
  1020  	if pending := pool.pending[addr]; pending != nil {
  1021  		if removed, invalids := pending.Remove(tx); removed {
  1022  			// If no more pending transactions are left, remove the list
  1023  			if pending.Empty() {
  1024  				delete(pool.pending, addr)
  1025  			}
  1026  			// Postpone any invalidated transactions
  1027  			for _, tx := range invalids {
  1028  				// Internal shuffle shouldn't touch the lookup set.
  1029  				pool.enqueueTx(tx.Hash(), tx, false, false)
  1030  			}
  1031  			// Update the account nonce if needed
  1032  			pool.pendingNonces.setIfLower(addr, tx.Nonce())
  1033  			// Reduce the pending counter
  1034  			pendingGauge.Dec(int64(1 + len(invalids)))
  1035  			return
  1036  		}
  1037  	}
  1038  	// Transaction is in the future queue
  1039  	if future := pool.queue[addr]; future != nil {
  1040  		if removed, _ := future.Remove(tx); removed {
  1041  			// Reduce the queued counter
  1042  			queuedGauge.Dec(1)
  1043  		}
  1044  		if future.Empty() {
  1045  			delete(pool.queue, addr)
  1046  			delete(pool.beats, addr)
  1047  		}
  1048  	}
  1049  }
  1050  
  1051  // requestReset requests a pool reset to the new head block.
  1052  // The returned channel is closed when the reset has occurred.
  1053  func (pool *TxPool) requestReset(oldHead *types.Header, newHead *types.Header) chan struct{} {
  1054  	select {
  1055  	case pool.reqResetCh <- &txpoolResetRequest{oldHead, newHead}:
  1056  		return <-pool.reorgDoneCh
  1057  	case <-pool.reorgShutdownCh:
  1058  		return pool.reorgShutdownCh
  1059  	}
  1060  }
  1061  
  1062  // requestPromoteExecutables requests transaction promotion checks for the given addresses.
  1063  // The returned channel is closed when the promotion checks have occurred.
  1064  func (pool *TxPool) requestPromoteExecutables(set *accountSet) chan struct{} {
  1065  	select {
  1066  	case pool.reqPromoteCh <- set:
  1067  		return <-pool.reorgDoneCh
  1068  	case <-pool.reorgShutdownCh:
  1069  		return pool.reorgShutdownCh
  1070  	}
  1071  }
  1072  
  1073  // queueTxEvent enqueues a transaction event to be sent in the next reorg run.
  1074  func (pool *TxPool) queueTxEvent(tx *types.Transaction) {
  1075  	select {
  1076  	case pool.queueTxEventCh <- tx:
  1077  	case <-pool.reorgShutdownCh:
  1078  	}
  1079  }
  1080  
  1081  // scheduleReorgLoop schedules runs of reset and promoteExecutables. Code above should not
  1082  // call those methods directly, but request them being run using requestReset and
  1083  // requestPromoteExecutables instead.
  1084  func (pool *TxPool) scheduleReorgLoop() {
  1085  	defer pool.wg.Done()
  1086  
  1087  	var (
  1088  		curDone       chan struct{} // non-nil while runReorg is active
  1089  		nextDone      = make(chan struct{})
  1090  		launchNextRun bool
  1091  		reset         *txpoolResetRequest
  1092  		dirtyAccounts *accountSet
  1093  		queuedEvents  = make(map[common.Address]*txSortedMap)
  1094  	)
  1095  	for {
  1096  		// Launch next background reorg if needed
  1097  		if curDone == nil && launchNextRun {
  1098  			// Run the background reorg and announcements
  1099  			go pool.runReorg(nextDone, reset, dirtyAccounts, queuedEvents)
  1100  
  1101  			// Prepare everything for the next round of reorg
  1102  			curDone, nextDone = nextDone, make(chan struct{})
  1103  			launchNextRun = false
  1104  
  1105  			reset, dirtyAccounts = nil, nil
  1106  			queuedEvents = make(map[common.Address]*txSortedMap)
  1107  		}
  1108  
  1109  		select {
  1110  		case req := <-pool.reqResetCh:
  1111  			// Reset request: update head if request is already pending.
  1112  			if reset == nil {
  1113  				reset = req
  1114  			} else {
  1115  				reset.newHead = req.newHead
  1116  			}
  1117  			launchNextRun = true
  1118  			pool.reorgDoneCh <- nextDone
  1119  
  1120  		case req := <-pool.reqPromoteCh:
  1121  			// Promote request: update address set if request is already pending.
  1122  			if dirtyAccounts == nil {
  1123  				dirtyAccounts = req
  1124  			} else {
  1125  				dirtyAccounts.merge(req)
  1126  			}
  1127  			launchNextRun = true
  1128  			pool.reorgDoneCh <- nextDone
  1129  
  1130  		case tx := <-pool.queueTxEventCh:
  1131  			// Queue up the event, but don't schedule a reorg. It's up to the caller to
  1132  			// request one later if they want the events sent.
  1133  			addr, _ := types.Sender(pool.signer, tx)
  1134  			if _, ok := queuedEvents[addr]; !ok {
  1135  				queuedEvents[addr] = newTxSortedMap()
  1136  			}
  1137  			queuedEvents[addr].Put(tx)
  1138  
  1139  		case <-curDone:
  1140  			curDone = nil
  1141  
  1142  		case <-pool.reorgShutdownCh:
  1143  			// Wait for current run to finish.
  1144  			if curDone != nil {
  1145  				<-curDone
  1146  			}
  1147  			close(nextDone)
  1148  			return
  1149  		}
  1150  	}
  1151  }
  1152  
  1153  // runReorg runs reset and promoteExecutables on behalf of scheduleReorgLoop.
  1154  func (pool *TxPool) runReorg(done chan struct{}, reset *txpoolResetRequest, dirtyAccounts *accountSet, events map[common.Address]*txSortedMap) {
  1155  	defer func(t0 time.Time) {
  1156  		reorgDurationTimer.Update(time.Since(t0))
  1157  	}(time.Now())
  1158  	defer close(done)
  1159  
  1160  	var promoteAddrs []common.Address
  1161  	if dirtyAccounts != nil && reset == nil {
  1162  		// Only dirty accounts need to be promoted, unless we're resetting.
  1163  		// For resets, all addresses in the tx queue will be promoted and
  1164  		// the flatten operation can be avoided.
  1165  		promoteAddrs = dirtyAccounts.flatten()
  1166  	}
  1167  	pool.mu.Lock()
  1168  	if reset != nil {
  1169  		// Reset from the old head to the new, rescheduling any reorged transactions
  1170  		pool.reset(reset.oldHead, reset.newHead)
  1171  
  1172  		// Nonces were reset, discard any events that became stale
  1173  		for addr := range events {
  1174  			events[addr].Forward(pool.pendingNonces.get(addr))
  1175  			if events[addr].Len() == 0 {
  1176  				delete(events, addr)
  1177  			}
  1178  		}
  1179  		// Reset needs promote for all addresses
  1180  		promoteAddrs = make([]common.Address, 0, len(pool.queue))
  1181  		for addr := range pool.queue {
  1182  			promoteAddrs = append(promoteAddrs, addr)
  1183  		}
  1184  	}
  1185  	// Check for pending transactions for every account that sent new ones
  1186  	promoted := pool.promoteExecutables(promoteAddrs)
  1187  
  1188  	// If a new block appeared, validate the pool of pending transactions. This will
  1189  	// remove any transaction that has been included in the block or was invalidated
  1190  	// because of another transaction (e.g. higher gas price).
  1191  	if reset != nil {
  1192  		pool.demoteUnexecutables()
  1193  		if reset.newHead != nil && pool.chainconfig.IsLondon(new(big.Int).Add(reset.newHead.Number, big.NewInt(1))) {
  1194  			pendingBaseFee := misc.CalcBaseFee(pool.chainconfig, reset.newHead)
  1195  			pool.priced.SetBaseFee(pendingBaseFee)
  1196  		}
  1197  		// Update all accounts to the latest known pending nonce
  1198  		nonces := make(map[common.Address]uint64, len(pool.pending))
  1199  		for addr, list := range pool.pending {
  1200  			highestPending := list.LastElement()
  1201  			nonces[addr] = highestPending.Nonce() + 1
  1202  		}
  1203  		pool.pendingNonces.setAll(nonces)
  1204  	}
  1205  	// Ensure pool.queue and pool.pending sizes stay within the configured limits.
  1206  	pool.truncatePending()
  1207  	pool.truncateQueue()
  1208  
  1209  	dropBetweenReorgHistogram.Update(int64(pool.changesSinceReorg))
  1210  	pool.changesSinceReorg = 0 // Reset change counter
  1211  	pool.mu.Unlock()
  1212  
  1213  	// Notify subsystems for newly added transactions
  1214  	for _, tx := range promoted {
  1215  		addr, _ := types.Sender(pool.signer, tx)
  1216  		if _, ok := events[addr]; !ok {
  1217  			events[addr] = newTxSortedMap()
  1218  		}
  1219  		events[addr].Put(tx)
  1220  	}
  1221  	if len(events) > 0 {
  1222  		var txs []*types.Transaction
  1223  		for _, set := range events {
  1224  			txs = append(txs, set.Flatten()...)
  1225  		}
  1226  		pool.txFeed.Send(NewTxsEvent{txs})
  1227  	}
  1228  }
  1229  
  1230  // reset retrieves the current state of the blockchain and ensures the content
  1231  // of the transaction pool is valid with regard to the chain state.
  1232  func (pool *TxPool) reset(oldHead, newHead *types.Header) {
  1233  	// If we're reorging an old state, reinject all dropped transactions
  1234  	var reinject types.Transactions
  1235  
  1236  	if oldHead != nil && oldHead.Hash() != newHead.ParentHash {
  1237  		// If the reorg is too deep, avoid doing it (will happen during fast sync)
  1238  		oldNum := oldHead.Number.Uint64()
  1239  		newNum := newHead.Number.Uint64()
  1240  
  1241  		if depth := uint64(math.Abs(float64(oldNum) - float64(newNum))); depth > 64 {
  1242  			log.Debug("Skipping deep transaction reorg", "depth", depth)
  1243  		} else {
  1244  			// Reorg seems shallow enough to pull in all transactions into memory
  1245  			var discarded, included types.Transactions
  1246  			var (
  1247  				rem = pool.chain.GetBlock(oldHead.Hash(), oldHead.Number.Uint64())
  1248  				add = pool.chain.GetBlock(newHead.Hash(), newHead.Number.Uint64())
  1249  			)
  1250  			if rem == nil {
  1251  				// This can happen if a setHead is performed, where we simply discard the old
  1252  				// head from the chain.
  1253  				// If that is the case, we don't have the lost transactions any more, and
  1254  				// there's nothing to add
  1255  				if newNum >= oldNum {
  1256  					// If we reorged to a same or higher number, then it's not a case of setHead
  1257  					log.Warn("Transaction pool reset with missing oldhead",
  1258  						"old", oldHead.Hash(), "oldnum", oldNum, "new", newHead.Hash(), "newnum", newNum)
  1259  					return
  1260  				}
  1261  				// If the reorg ended up on a lower number, it's indicative of setHead being the cause
  1262  				log.Debug("Skipping transaction reset caused by setHead",
  1263  					"old", oldHead.Hash(), "oldnum", oldNum, "new", newHead.Hash(), "newnum", newNum)
  1264  				// We still need to update the current state s.th. the lost transactions can be readded by the user
  1265  			} else {
  1266  				for rem.NumberU64() > add.NumberU64() {
  1267  					discarded = append(discarded, rem.Transactions()...)
  1268  					if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  1269  						log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  1270  						return
  1271  					}
  1272  				}
  1273  				for add.NumberU64() > rem.NumberU64() {
  1274  					included = append(included, add.Transactions()...)
  1275  					if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  1276  						log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  1277  						return
  1278  					}
  1279  				}
  1280  				for rem.Hash() != add.Hash() {
  1281  					discarded = append(discarded, rem.Transactions()...)
  1282  					if rem = pool.chain.GetBlock(rem.ParentHash(), rem.NumberU64()-1); rem == nil {
  1283  						log.Error("Unrooted old chain seen by tx pool", "block", oldHead.Number, "hash", oldHead.Hash())
  1284  						return
  1285  					}
  1286  					included = append(included, add.Transactions()...)
  1287  					if add = pool.chain.GetBlock(add.ParentHash(), add.NumberU64()-1); add == nil {
  1288  						log.Error("Unrooted new chain seen by tx pool", "block", newHead.Number, "hash", newHead.Hash())
  1289  						return
  1290  					}
  1291  				}
  1292  				reinject = types.TxDifference(discarded, included)
  1293  			}
  1294  		}
  1295  	}
  1296  	// Initialize the internal state to the current head
  1297  	if newHead == nil {
  1298  		newHead = pool.chain.CurrentBlock().Header() // Special case during testing
  1299  	}
  1300  	statedb, err := pool.chain.StateAt(newHead.Root)
  1301  	if err != nil {
  1302  		log.Error("Failed to reset txpool state", "err", err)
  1303  		return
  1304  	}
  1305  	pool.currentState = statedb
  1306  	pool.pendingNonces = newTxNoncer(statedb)
  1307  	pool.currentMaxGas = newHead.GasLimit
  1308  
  1309  	// Inject any transactions discarded due to reorgs
  1310  	log.Debug("Reinjecting stale transactions", "count", len(reinject))
  1311  	senderCacher.recover(pool.signer, reinject)
  1312  	pool.addTxsLocked(reinject, false)
  1313  
  1314  	// Update all fork indicator by next pending block number.
  1315  	next := new(big.Int).Add(newHead.Number, big.NewInt(1))
  1316  	pool.istanbul = pool.chainconfig.IsIstanbul(next)
  1317  	pool.eip2718 = pool.chainconfig.IsBerlin(next)
  1318  	pool.eip1559 = pool.chainconfig.IsLondon(next)
  1319  	pool.isrome = pool.chainconfig.IsRome(next)
  1320  }
  1321  
  1322  // promoteExecutables moves transactions that have become processable from the
  1323  // future queue to the set of pending transactions. During this process, all
  1324  // invalidated transactions (low nonce, low balance) are deleted.
  1325  func (pool *TxPool) promoteExecutables(accounts []common.Address) []*types.Transaction {
  1326  	// Track the promoted transactions to broadcast them at once
  1327  	var promoted []*types.Transaction
  1328  
  1329  	// Iterate over all accounts and promote any executable transactions
  1330  	for _, addr := range accounts {
  1331  		list := pool.queue[addr]
  1332  		if list == nil {
  1333  			continue // Just in case someone calls with a non existing account
  1334  		}
  1335  		// Drop all transactions that are deemed too old (low nonce)
  1336  		forwards := list.Forward(pool.currentState.GetNonce(addr))
  1337  		for _, tx := range forwards {
  1338  			hash := tx.Hash()
  1339  			pool.all.Remove(hash)
  1340  		}
  1341  		log.Trace("Removed old queued transactions", "count", len(forwards))
  1342  		// Drop all transactions that are too costly (low balance or out of gas)
  1343  		drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  1344  		for _, tx := range drops {
  1345  			hash := tx.Hash()
  1346  			pool.all.Remove(hash)
  1347  		}
  1348  		log.Trace("Removed unpayable queued transactions", "count", len(drops))
  1349  		queuedNofundsMeter.Mark(int64(len(drops)))
  1350  
  1351  		// Gather all executable transactions and promote them
  1352  		readies := list.Ready(pool.pendingNonces.get(addr))
  1353  		for _, tx := range readies {
  1354  			hash := tx.Hash()
  1355  			if pool.promoteTx(addr, hash, tx) {
  1356  				promoted = append(promoted, tx)
  1357  			}
  1358  		}
  1359  		log.Trace("Promoted queued transactions", "count", len(promoted))
  1360  		queuedGauge.Dec(int64(len(readies)))
  1361  
  1362  		// Drop all transactions over the allowed limit
  1363  		var caps types.Transactions
  1364  		if !pool.locals.contains(addr) {
  1365  			caps = list.Cap(int(pool.config.AccountQueue))
  1366  			for _, tx := range caps {
  1367  				hash := tx.Hash()
  1368  				pool.all.Remove(hash)
  1369  				log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
  1370  			}
  1371  			queuedRateLimitMeter.Mark(int64(len(caps)))
  1372  		}
  1373  		// Mark all the items dropped as removed
  1374  		pool.priced.Removed(len(forwards) + len(drops) + len(caps))
  1375  		queuedGauge.Dec(int64(len(forwards) + len(drops) + len(caps)))
  1376  		if pool.locals.contains(addr) {
  1377  			localGauge.Dec(int64(len(forwards) + len(drops) + len(caps)))
  1378  		}
  1379  		// Delete the entire queue entry if it became empty.
  1380  		if list.Empty() {
  1381  			delete(pool.queue, addr)
  1382  			delete(pool.beats, addr)
  1383  		}
  1384  	}
  1385  	return promoted
  1386  }
  1387  
  1388  // truncatePending removes transactions from the pending queue if the pool is above the
  1389  // pending limit. The algorithm tries to reduce transaction counts by an approximately
  1390  // equal number for all for accounts with many pending transactions.
  1391  func (pool *TxPool) truncatePending() {
  1392  	pending := uint64(0)
  1393  	for _, list := range pool.pending {
  1394  		pending += uint64(list.Len())
  1395  	}
  1396  	if pending <= pool.config.GlobalSlots {
  1397  		return
  1398  	}
  1399  
  1400  	pendingBeforeCap := pending
  1401  	// Assemble a spam order to penalize large transactors first
  1402  	spammers := prque.New(nil)
  1403  	for addr, list := range pool.pending {
  1404  		// Only evict transactions from high rollers
  1405  		if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
  1406  			spammers.Push(addr, int64(list.Len()))
  1407  		}
  1408  	}
  1409  	// Gradually drop transactions from offenders
  1410  	offenders := []common.Address{}
  1411  	for pending > pool.config.GlobalSlots && !spammers.Empty() {
  1412  		// Retrieve the next offender if not local address
  1413  		offender, _ := spammers.Pop()
  1414  		offenders = append(offenders, offender.(common.Address))
  1415  
  1416  		// Equalize balances until all the same or below threshold
  1417  		if len(offenders) > 1 {
  1418  			// Calculate the equalization threshold for all current offenders
  1419  			threshold := pool.pending[offender.(common.Address)].Len()
  1420  
  1421  			// Iteratively reduce all offenders until below limit or threshold reached
  1422  			for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
  1423  				for i := 0; i < len(offenders)-1; i++ {
  1424  					list := pool.pending[offenders[i]]
  1425  
  1426  					caps := list.Cap(list.Len() - 1)
  1427  					for _, tx := range caps {
  1428  						// Drop the transaction from the global pools too
  1429  						hash := tx.Hash()
  1430  						pool.all.Remove(hash)
  1431  
  1432  						// Update the account nonce to the dropped transaction
  1433  						pool.pendingNonces.setIfLower(offenders[i], tx.Nonce())
  1434  						log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  1435  					}
  1436  					pool.priced.Removed(len(caps))
  1437  					pendingGauge.Dec(int64(len(caps)))
  1438  					if pool.locals.contains(offenders[i]) {
  1439  						localGauge.Dec(int64(len(caps)))
  1440  					}
  1441  					pending--
  1442  				}
  1443  			}
  1444  		}
  1445  	}
  1446  
  1447  	// If still above threshold, reduce to limit or min allowance
  1448  	if pending > pool.config.GlobalSlots && len(offenders) > 0 {
  1449  		for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
  1450  			for _, addr := range offenders {
  1451  				list := pool.pending[addr]
  1452  
  1453  				caps := list.Cap(list.Len() - 1)
  1454  				for _, tx := range caps {
  1455  					// Drop the transaction from the global pools too
  1456  					hash := tx.Hash()
  1457  					pool.all.Remove(hash)
  1458  
  1459  					// Update the account nonce to the dropped transaction
  1460  					pool.pendingNonces.setIfLower(addr, tx.Nonce())
  1461  					log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
  1462  				}
  1463  				pool.priced.Removed(len(caps))
  1464  				pendingGauge.Dec(int64(len(caps)))
  1465  				if pool.locals.contains(addr) {
  1466  					localGauge.Dec(int64(len(caps)))
  1467  				}
  1468  				pending--
  1469  			}
  1470  		}
  1471  	}
  1472  	pendingRateLimitMeter.Mark(int64(pendingBeforeCap - pending))
  1473  }
  1474  
  1475  // truncateQueue drops the oldest transactions in the queue if the pool is above the global queue limit.
  1476  func (pool *TxPool) truncateQueue() {
  1477  	queued := uint64(0)
  1478  	for _, list := range pool.queue {
  1479  		queued += uint64(list.Len())
  1480  	}
  1481  	if queued <= pool.config.GlobalQueue {
  1482  		return
  1483  	}
  1484  
  1485  	// Sort all accounts with queued transactions by heartbeat
  1486  	addresses := make(addressesByHeartbeat, 0, len(pool.queue))
  1487  	for addr := range pool.queue {
  1488  		if !pool.locals.contains(addr) { // don't drop locals
  1489  			addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
  1490  		}
  1491  	}
  1492  	sort.Sort(sort.Reverse(addresses))
  1493  
  1494  	// Drop transactions until the total is below the limit or only locals remain
  1495  	for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
  1496  		addr := addresses[len(addresses)-1]
  1497  		list := pool.queue[addr.address]
  1498  
  1499  		addresses = addresses[:len(addresses)-1]
  1500  
  1501  		// Drop all transactions if they are less than the overflow
  1502  		if size := uint64(list.Len()); size <= drop {
  1503  			for _, tx := range list.Flatten() {
  1504  				pool.removeTx(tx.Hash(), true)
  1505  			}
  1506  			drop -= size
  1507  			queuedRateLimitMeter.Mark(int64(size))
  1508  			continue
  1509  		}
  1510  		// Otherwise drop only last few transactions
  1511  		txs := list.Flatten()
  1512  		for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
  1513  			pool.removeTx(txs[i].Hash(), true)
  1514  			drop--
  1515  			queuedRateLimitMeter.Mark(1)
  1516  		}
  1517  	}
  1518  }
  1519  
  1520  // demoteUnexecutables removes invalid and processed transactions from the pools
  1521  // executable/pending queue and any subsequent transactions that become unexecutable
  1522  // are moved back into the future queue.
  1523  //
  1524  // Note: transactions are not marked as removed in the priced list because re-heaping
  1525  // is always explicitly triggered by SetBaseFee and it would be unnecessary and wasteful
  1526  // to trigger a re-heap is this function
  1527  func (pool *TxPool) demoteUnexecutables() {
  1528  	// Iterate over all accounts and demote any non-executable transactions
  1529  	for addr, list := range pool.pending {
  1530  		nonce := pool.currentState.GetNonce(addr)
  1531  
  1532  		// Drop all transactions that are deemed too old (low nonce)
  1533  		olds := list.Forward(nonce)
  1534  		for _, tx := range olds {
  1535  			hash := tx.Hash()
  1536  			pool.all.Remove(hash)
  1537  			log.Trace("Removed old pending transaction", "hash", hash)
  1538  		}
  1539  		// Drop all transactions that are too costly (low balance or out of gas), and queue any invalids back for later
  1540  		drops, invalids := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
  1541  		for _, tx := range drops {
  1542  			hash := tx.Hash()
  1543  			log.Trace("Removed unpayable pending transaction", "hash", hash)
  1544  			pool.all.Remove(hash)
  1545  		}
  1546  		pendingNofundsMeter.Mark(int64(len(drops)))
  1547  
  1548  		for _, tx := range invalids {
  1549  			hash := tx.Hash()
  1550  			log.Trace("Demoting pending transaction", "hash", hash)
  1551  
  1552  			// Internal shuffle shouldn't touch the lookup set.
  1553  			pool.enqueueTx(hash, tx, false, false)
  1554  		}
  1555  		pendingGauge.Dec(int64(len(olds) + len(drops) + len(invalids)))
  1556  		if pool.locals.contains(addr) {
  1557  			localGauge.Dec(int64(len(olds) + len(drops) + len(invalids)))
  1558  		}
  1559  		// If there's a gap in front, alert (should never happen) and postpone all transactions
  1560  		if list.Len() > 0 && list.txs.Get(nonce) == nil {
  1561  			gapped := list.Cap(0)
  1562  			for _, tx := range gapped {
  1563  				hash := tx.Hash()
  1564  				log.Error("Demoting invalidated transaction", "hash", hash)
  1565  
  1566  				// Internal shuffle shouldn't touch the lookup set.
  1567  				pool.enqueueTx(hash, tx, false, false)
  1568  			}
  1569  			pendingGauge.Dec(int64(len(gapped)))
  1570  			// This might happen in a reorg, so log it to the metering
  1571  			blockReorgInvalidatedTx.Mark(int64(len(gapped)))
  1572  		}
  1573  		// Delete the entire pending entry if it became empty.
  1574  		if list.Empty() {
  1575  			delete(pool.pending, addr)
  1576  		}
  1577  	}
  1578  }
  1579  
  1580  // addressByHeartbeat is an account address tagged with its last activity timestamp.
  1581  type addressByHeartbeat struct {
  1582  	address   common.Address
  1583  	heartbeat time.Time
  1584  }
  1585  
  1586  type addressesByHeartbeat []addressByHeartbeat
  1587  
  1588  func (a addressesByHeartbeat) Len() int           { return len(a) }
  1589  func (a addressesByHeartbeat) Less(i, j int) bool { return a[i].heartbeat.Before(a[j].heartbeat) }
  1590  func (a addressesByHeartbeat) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
  1591  
  1592  // accountSet is simply a set of addresses to check for existence, and a signer
  1593  // capable of deriving addresses from transactions.
  1594  type accountSet struct {
  1595  	accounts map[common.Address]struct{}
  1596  	signer   types.Signer
  1597  	cache    *[]common.Address
  1598  }
  1599  
  1600  // newAccountSet creates a new address set with an associated signer for sender
  1601  // derivations.
  1602  func newAccountSet(signer types.Signer, addrs ...common.Address) *accountSet {
  1603  	as := &accountSet{
  1604  		accounts: make(map[common.Address]struct{}),
  1605  		signer:   signer,
  1606  	}
  1607  	for _, addr := range addrs {
  1608  		as.add(addr)
  1609  	}
  1610  	return as
  1611  }
  1612  
  1613  // contains checks if a given address is contained within the set.
  1614  func (as *accountSet) contains(addr common.Address) bool {
  1615  	_, exist := as.accounts[addr]
  1616  	return exist
  1617  }
  1618  
  1619  // containsTx checks if the sender of a given tx is within the set. If the sender
  1620  // cannot be derived, this method returns false.
  1621  func (as *accountSet) containsTx(tx *types.Transaction) bool {
  1622  	if addr, err := types.Sender(as.signer, tx); err == nil {
  1623  		return as.contains(addr)
  1624  	}
  1625  	return false
  1626  }
  1627  
  1628  // add inserts a new address into the set to track.
  1629  func (as *accountSet) add(addr common.Address) {
  1630  	as.accounts[addr] = struct{}{}
  1631  	as.cache = nil
  1632  }
  1633  
  1634  // addTx adds the sender of tx into the set.
  1635  func (as *accountSet) addTx(tx *types.Transaction) {
  1636  	if addr, err := types.Sender(as.signer, tx); err == nil {
  1637  		as.add(addr)
  1638  	}
  1639  }
  1640  
  1641  // flatten returns the list of addresses within this set, also caching it for later
  1642  // reuse. The returned slice should not be changed!
  1643  func (as *accountSet) flatten() []common.Address {
  1644  	if as.cache == nil {
  1645  		accounts := make([]common.Address, 0, len(as.accounts))
  1646  		for account := range as.accounts {
  1647  			accounts = append(accounts, account)
  1648  		}
  1649  		as.cache = &accounts
  1650  	}
  1651  	return *as.cache
  1652  }
  1653  
  1654  // merge adds all addresses from the 'other' set into 'as'.
  1655  func (as *accountSet) merge(other *accountSet) {
  1656  	for addr := range other.accounts {
  1657  		as.accounts[addr] = struct{}{}
  1658  	}
  1659  	as.cache = nil
  1660  }
  1661  
  1662  // txLookup is used internally by TxPool to track transactions while allowing
  1663  // lookup without mutex contention.
  1664  //
  1665  // Note, although this type is properly protected against concurrent access, it
  1666  // is **not** a type that should ever be mutated or even exposed outside of the
  1667  // transaction pool, since its internal state is tightly coupled with the pools
  1668  // internal mechanisms. The sole purpose of the type is to permit out-of-bound
  1669  // peeking into the pool in TxPool.Get without having to acquire the widely scoped
  1670  // TxPool.mu mutex.
  1671  //
  1672  // This lookup set combines the notion of "local transactions", which is useful
  1673  // to build upper-level structure.
  1674  type txLookup struct {
  1675  	slots   int
  1676  	lock    sync.RWMutex
  1677  	locals  map[common.Hash]*types.Transaction
  1678  	remotes map[common.Hash]*types.Transaction
  1679  }
  1680  
  1681  // newTxLookup returns a new txLookup structure.
  1682  func newTxLookup() *txLookup {
  1683  	return &txLookup{
  1684  		locals:  make(map[common.Hash]*types.Transaction),
  1685  		remotes: make(map[common.Hash]*types.Transaction),
  1686  	}
  1687  }
  1688  
  1689  // Range calls f on each key and value present in the map. The callback passed
  1690  // should return the indicator whether the iteration needs to be continued.
  1691  // Callers need to specify which set (or both) to be iterated.
  1692  func (t *txLookup) Range(f func(hash common.Hash, tx *types.Transaction, local bool) bool, local bool, remote bool) {
  1693  	t.lock.RLock()
  1694  	defer t.lock.RUnlock()
  1695  
  1696  	if local {
  1697  		for key, value := range t.locals {
  1698  			if !f(key, value, true) {
  1699  				return
  1700  			}
  1701  		}
  1702  	}
  1703  	if remote {
  1704  		for key, value := range t.remotes {
  1705  			if !f(key, value, false) {
  1706  				return
  1707  			}
  1708  		}
  1709  	}
  1710  }
  1711  
  1712  // Get returns a transaction if it exists in the lookup, or nil if not found.
  1713  func (t *txLookup) Get(hash common.Hash) *types.Transaction {
  1714  	t.lock.RLock()
  1715  	defer t.lock.RUnlock()
  1716  
  1717  	if tx := t.locals[hash]; tx != nil {
  1718  		return tx
  1719  	}
  1720  	return t.remotes[hash]
  1721  }
  1722  
  1723  // GetLocal returns a transaction if it exists in the lookup, or nil if not found.
  1724  func (t *txLookup) GetLocal(hash common.Hash) *types.Transaction {
  1725  	t.lock.RLock()
  1726  	defer t.lock.RUnlock()
  1727  
  1728  	return t.locals[hash]
  1729  }
  1730  
  1731  // GetRemote returns a transaction if it exists in the lookup, or nil if not found.
  1732  func (t *txLookup) GetRemote(hash common.Hash) *types.Transaction {
  1733  	t.lock.RLock()
  1734  	defer t.lock.RUnlock()
  1735  
  1736  	return t.remotes[hash]
  1737  }
  1738  
  1739  // Count returns the current number of transactions in the lookup.
  1740  func (t *txLookup) Count() int {
  1741  	t.lock.RLock()
  1742  	defer t.lock.RUnlock()
  1743  
  1744  	return len(t.locals) + len(t.remotes)
  1745  }
  1746  
  1747  // LocalCount returns the current number of local transactions in the lookup.
  1748  func (t *txLookup) LocalCount() int {
  1749  	t.lock.RLock()
  1750  	defer t.lock.RUnlock()
  1751  
  1752  	return len(t.locals)
  1753  }
  1754  
  1755  // RemoteCount returns the current number of remote transactions in the lookup.
  1756  func (t *txLookup) RemoteCount() int {
  1757  	t.lock.RLock()
  1758  	defer t.lock.RUnlock()
  1759  
  1760  	return len(t.remotes)
  1761  }
  1762  
  1763  // Slots returns the current number of slots used in the lookup.
  1764  func (t *txLookup) Slots() int {
  1765  	t.lock.RLock()
  1766  	defer t.lock.RUnlock()
  1767  
  1768  	return t.slots
  1769  }
  1770  
  1771  // Add adds a transaction to the lookup.
  1772  func (t *txLookup) Add(tx *types.Transaction, local bool) {
  1773  	t.lock.Lock()
  1774  	defer t.lock.Unlock()
  1775  
  1776  	t.slots += numSlots(tx)
  1777  	slotsGauge.Update(int64(t.slots))
  1778  
  1779  	if local {
  1780  		t.locals[tx.Hash()] = tx
  1781  	} else {
  1782  		t.remotes[tx.Hash()] = tx
  1783  	}
  1784  }
  1785  
  1786  // Remove removes a transaction from the lookup.
  1787  func (t *txLookup) Remove(hash common.Hash) {
  1788  	t.lock.Lock()
  1789  	defer t.lock.Unlock()
  1790  
  1791  	tx, ok := t.locals[hash]
  1792  	if !ok {
  1793  		tx, ok = t.remotes[hash]
  1794  	}
  1795  	if !ok {
  1796  		log.Error("No transaction found to be deleted", "hash", hash)
  1797  		return
  1798  	}
  1799  	t.slots -= numSlots(tx)
  1800  	slotsGauge.Update(int64(t.slots))
  1801  
  1802  	delete(t.locals, hash)
  1803  	delete(t.remotes, hash)
  1804  }
  1805  
  1806  // RemoteToLocals migrates the transactions belongs to the given locals to locals
  1807  // set. The assumption is held the locals set is thread-safe to be used.
  1808  func (t *txLookup) RemoteToLocals(locals *accountSet) int {
  1809  	t.lock.Lock()
  1810  	defer t.lock.Unlock()
  1811  
  1812  	var migrated int
  1813  	for hash, tx := range t.remotes {
  1814  		if locals.containsTx(tx) {
  1815  			t.locals[hash] = tx
  1816  			delete(t.remotes, hash)
  1817  			migrated += 1
  1818  		}
  1819  	}
  1820  	return migrated
  1821  }
  1822  
  1823  // RemotesBelowTip finds all remote transactions below the given tip threshold.
  1824  func (t *txLookup) RemotesBelowTip(threshold *big.Int) types.Transactions {
  1825  	found := make(types.Transactions, 0, 128)
  1826  	t.Range(func(hash common.Hash, tx *types.Transaction, local bool) bool {
  1827  		if tx.GasTipCapIntCmp(threshold) < 0 {
  1828  			found = append(found, tx)
  1829  		}
  1830  		return true
  1831  	}, false, true) // Only iterate remotes
  1832  	return found
  1833  }
  1834  
  1835  // numSlots calculates the number of slots needed for a single transaction.
  1836  func numSlots(tx *types.Transaction) int {
  1837  	return int((tx.Size() + txSlotSize - 1) / txSlotSize)
  1838  }