legacypool

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package legacypool implements the normal EVM execution transaction pool.

Index

Constants

View Source
const (
	RemovalReasonLifetime               txpool.RemovalReason = "lifetime"           // Tx has been in queued for too long
	RemovalReasonBelowTip               txpool.RemovalReason = "belowtip"           // Min gas tip changed and these txs are too low
	RemovalReasonTruncatedOverflow      txpool.RemovalReason = "truncated_overflow" // We have to truncate a pool and this account has too many txs
	RemovalReasonTruncatedLast          txpool.RemovalReason = "truncated_last"     // We have to truncate a pool and these txs are the last ones in so they are the first out
	RemovalReasonUnderpricedFull        txpool.RemovalReason = "underpriced_full"   // New tx came in that has a better price. The pool is also full so we kicked a tx out to make room.
	RemovalReasonCapExceeded            txpool.RemovalReason = "capped"             // Too many txs for this account
	RemovalReasonRunTxRecheck           txpool.RemovalReason = "runtx_recheck"
	RemovalReasonRunTxFinalize          txpool.RemovalReason = "runtx_finalize"
	RemovalReasonPrepareProposalInvalid txpool.RemovalReason = "prepare_proposal_invalid"
)

Variables

View Source
var (
	// ErrTxPoolOverflow is returned if the transaction pool is full and can't accept
	// another remote transaction.
	ErrTxPoolOverflow = errors.New("txpool is full")

	// ErrOutOfOrderTxFromDelegated is returned when the transaction with gapped
	// nonce received from the accounts with delegation or pending delegation.
	ErrOutOfOrderTxFromDelegated = errors.New("gapped-nonce tx from delegated accounts")

	// ErrAuthorityReserved is returned if a transaction has an authorization
	// signed by an address which already has in-flight transactions known to the
	// pool.
	ErrAuthorityReserved = errors.New("authority already reserved")

	// ErrFutureReplacePending is returned if a future transaction replaces a pending
	// one. Future transactions should only be able to replace other future transactions.
	ErrFutureReplacePending = errors.New("future transaction tries to replace pending")
)
View Source
var DefaultConfig = Config{
	Journal:   "transactions.rlp",
	Rejournal: time.Hour,

	PriceLimit: 1,
	PriceBump:  10,

	AccountSlots: 16,
	GlobalSlots:  4096 + 1024,
	AccountQueue: 64,
	GlobalQueue:  1024,

	Lifetime: 3 * time.Hour,

	IncludedNonceCacheSize: 4096,
}

DefaultConfig contains the default configurations for the transaction pool.

Functions

This section is empty.

Types

type BlockChain

type BlockChain interface {
	// Config retrieves the chain's fork configuration.
	Config() *params.ChainConfig

	// CurrentBlock returns the current head of the chain.
	CurrentBlock() *types.Header

	// GetBlock retrieves a specific block, used during pool resets.
	GetBlock(hash common.Hash, number uint64) *types.Block

	// StateAt returns a state database for a given root hash (generally the head).
	StateAt(root common.Hash) (vm.StateDB, error)

	// GetLatestContext returns the latest SDK context for the chain.
	GetLatestContext() (sdk.Context, error)
}

BlockChain defines the minimal set of methods needed to back a tx pool with a chain. Exists to allow mocking the live chain out of tests.

type Config

type Config struct {
	Locals    []common.Address // Addresses that should be treated by default as local
	NoLocals  bool             // Whether local transaction handling should be disabled
	Journal   string           // Journal of local transactions to survive node restarts
	Rejournal time.Duration    // Time interval to regenerate the local transaction journal

	PriceLimit uint64 // Minimum gas price to enforce for acceptance into the pool
	PriceBump  uint64 // Minimum price bump percentage to replace an already existing transaction (nonce)

	AccountSlots uint64 // Number of executable transaction slots guaranteed per account
	GlobalSlots  uint64 // Maximum number of executable transaction slots for all accounts
	AccountQueue uint64 // Maximum number of non-executable transaction slots permitted per account
	GlobalQueue  uint64 // Maximum number of non-executable transaction slots for all accounts

	Lifetime time.Duration // Maximum amount of time non-executable transaction are queued

	IncludedNonceCacheSize int // Max entries in the included nonce LRU cache
}

Config are the configuration parameters of the transaction pool.

type LegacyPool

type LegacyPool struct {
	// contains filtered or unexported fields
}

LegacyPool contains all currently known transactions. Transactions enter the pool when they are received from the network or submitted locally. They exit the pool when they are included in the blockchain.

The pool separates processable transactions (which can be applied to the current state) and future transactions. Transactions move between those two states over time as they are received and processed.

In addition to tracking transactions, the pool also tracks a set of pending SetCode authorizations (EIP7702). This helps minimize number of transactions that can be trivially churned in the pool. As a standard rule, any account with a deployed delegation or an in-flight authorization to deploy a delegation will only be allowed a single transaction slot instead of the standard number. This is due to the possibility of the account being sweeped by an unrelated account.

Because SetCode transactions can have many authorizations included, we avoid explicitly checking their validity to save the state lookup. So long as the encompassing transaction is valid, the authorization will be accepted and tracked by the pool. In case the pool is tracking a pending / queued transaction from a specific account, it will reject new transactions with delegations from that account with standard in-flight transactions.

func New

func New(
	config Config,
	logger cosmoslog.Logger,
	chain BlockChain,
	reapList *reaplist.ReapList,
	tracker txtracker.Tracker,
	opts ...Option,
) *LegacyPool

New creates a new transaction pool to gather, sort and filter inbound transactions from the network. reapList and tracker are required: they observe every pending-pool transition and are load-bearing for both broadcast (reapList) and telemetry (tracker).

func (*LegacyPool) Add

func (pool *LegacyPool) Add(txs []*types.Transaction, sync bool) []error

Add enqueues a batch of transactions into the pool if they are valid.

Note, if sync is set the method will block until all internal maintenance related to the add is finished. Only use this during tests for determinism.

func (*LegacyPool) CancelReset added in v0.7.0

func (pool *LegacyPool) CancelReset()

CancelReset implements txpool.SubPool, signals the legacypool to stop processing its current reset request since a new block arrived and the work it is doing to reset at the current height will be invalidated.

func (*LegacyPool) Clear

func (pool *LegacyPool) Clear()

Clear implements txpool.SubPool, removing all tracked txs from the pool and rotating the journal.

Note, do not use this in production / live code. In live code, the pool is meant to reset on a separate thread to avoid DoS vectors.

func (*LegacyPool) Close

func (pool *LegacyPool) Close() error

Close terminates the transaction pool.

func (*LegacyPool) Content

func (pool *LegacyPool) Content() (map[common.Address][]*types.Transaction, map[common.Address][]*types.Transaction)

Content retrieves the data content of the transaction pool, returning all the pending as well as queued transactions, grouped by account and sorted by nonce.

func (*LegacyPool) ContentFrom

func (pool *LegacyPool) ContentFrom(addr common.Address) ([]*types.Transaction, []*types.Transaction)

ContentFrom retrieves the data content of the transaction pool, returning the pending as well as queued transactions of this address, grouped by nonce.

func (*LegacyPool) Filter

func (pool *LegacyPool) Filter(tx *types.Transaction) bool

Filter returns whether the given transaction can be consumed by the legacy pool, specifically, whether it is a Legacy, AccessList or Dynamic transaction.

func (*LegacyPool) Get

func (pool *LegacyPool) Get(hash common.Hash) *types.Transaction

Get returns a transaction if it is contained in the pool and nil otherwise.

func (*LegacyPool) GetBlobs

func (pool *LegacyPool) GetBlobs(vhashes []common.Hash) ([]*kzg4844.Blob, []*kzg4844.Proof)

GetBlobs is not supported by the legacy transaction pool, it is just here to implement the txpool.SubPool interface.

func (*LegacyPool) GetMetadata

func (pool *LegacyPool) GetMetadata(hash common.Hash) *txpool.TxMetadata

GetMetadata returns the transaction type and transaction size with the given transaction hash.

func (*LegacyPool) GetRLP

func (pool *LegacyPool) GetRLP(hash common.Hash) []byte

GetRLP returns a RLP-encoded transaction if it is contained in the pool.

func (*LegacyPool) Has

func (pool *LegacyPool) Has(hash common.Hash) bool

Has returns an indicator whether txpool has a transaction cached with the given hash.

func (*LegacyPool) HasPendingAuth

func (pool *LegacyPool) HasPendingAuth(addr common.Address) bool

HasPendingAuth returns a flag indicating whether there are pending authorizations from the specific address cached in the pool.

func (*LegacyPool) Init

func (pool *LegacyPool) Init(gasTip uint64, head *types.Header, reserver reserver.Reserver) error

Init sets the gas price needed to keep a transaction in the pool and the chain head to allow balance / nonce checks. The internal goroutines will be spun up and the pool deemed operational afterwards.

func (*LegacyPool) LatestNonce added in v0.7.0

func (pool *LegacyPool) LatestNonce(addr common.Address) (uint64, bool)

LatestNonce returns the most recently recorded latest-included nonce for addr and whether an entry exists in the cache. Primarily useful for tests and debugging.

func (*LegacyPool) Nonce

func (pool *LegacyPool) Nonce(addr common.Address) uint64

Nonce returns the next nonce of an account, with all transactions executable by the pool already applied on top.

func (*LegacyPool) Pending

Pending retrieves all currently processable transactions, grouped by origin account and sorted by nonce.

The transactions can also be pre-filtered by the dynamic fee components to reduce allocations and load on downstream subsystems.

func (*LegacyPool) Rechecked added in v0.7.0

func (pool *LegacyPool) Rechecked(ctx context.Context, height *big.Int, filter txpool.PendingFilter) map[common.Address][]*txpool.LazyTransaction

Rechecked retrieves all currently rechecked transactions, grouped by origin account and sorted by nonce.

The transactions can also be pre-filtered by the dynamic fee components to reduce allocations and load on downstream subsystems.

func (*LegacyPool) RemoveTx

func (pool *LegacyPool) RemoveTx(hash common.Hash, outofbound bool, unreserve bool, reason txpool.RemovalReason) int

RemoveTx removes a single transaction from the queue, moving all subsequent transactions back to the future queue.

In unreserve is false, the account will not be relinquished to the main txpool even if there are no more references to it. This is used to handle a race when a tx being added, and it evicts a previously scheduled tx from the same account, which could lead to a premature release of the lock.

Returns the number of transactions removed from the pending queue.

func (*LegacyPool) Reset

func (pool *LegacyPool) Reset(oldHead, newHead *types.Header)

Reset implements txpool.SubPool, allowing the legacy pool's internal state to be kept in sync with the main transaction pool's internal state.

func (*LegacyPool) SetGasTip

func (pool *LegacyPool) SetGasTip(tip *big.Int)

SetGasTip updates the minimum gas tip required by the transaction pool for a new transaction, and drops all transactions below this threshold.

func (*LegacyPool) SetLatestNonce added in v0.7.0

func (pool *LegacyPool) SetLatestNonce(sender common.Address, nonce uint64)

SetLatestNonce records the latest on chain nonce observed for an account.

func (*LegacyPool) Stats

func (pool *LegacyPool) Stats() (int, int)

Stats retrieves the current pool stats, namely the number of pending and the number of queued (non-executable) transactions.

func (*LegacyPool) Status

func (pool *LegacyPool) Status(hash common.Hash) txpool.TxStatus

Status returns the status (unknown/pending/queued) of a batch of transactions identified by their hashes.

func (*LegacyPool) SubscribeTransactions

func (pool *LegacyPool) SubscribeTransactions(ch chan<- core.NewTxsEvent, reorgs bool) event.Subscription

SubscribeTransactions registers a subscription for new transaction events, supporting feeding only newly seen or also resurrected transactions.

func (*LegacyPool) ValidateTxBasics

func (pool *LegacyPool) ValidateTxBasics(tx *types.Transaction) error

ValidateTxBasics checks whether a transaction is valid according to the consensus rules, but does not check state-dependent validation such as sufficient balance. This check is meant as an early check which only needs to be performed once, and does not require the pool mutex to be held.

type Option added in v0.7.0

type Option func(pool *LegacyPool)

Option is a function that sets an optional parameter on the legacypool

func WithRecheck added in v0.7.0

func WithRecheck(rechecker Rechecker) Option

WithRecheck enables recheck evicting of transactions from the mempool.

type PoolType added in v0.7.0

type PoolType string
const (
	Pending PoolType = "pending"
	Queue   PoolType = "queue"
)

type Rechecker added in v0.7.0

type Rechecker interface {
	// GetContext gets a branch of the current context that transactions should
	// be rechecked against. Changes to ctx will only be persisted back to the
	// Reckecker once the write function is invoked.
	GetContext() (ctx sdk.Context, write func())

	// RecheckEVM performs validation of an EVM tx against a context, and
	// returns an updated context.
	RecheckEVM(ctx sdk.Context, tx *types.Transaction) (sdk.Context, error)

	// Update updates the main context returned by GetContext to be the base
	// chain context at header. The caller provides the SDK context directly.
	Update(ctx sdk.Context, header *types.Header)
}

Rechecker defines the minimal set of methods needed to recheck transactions and manage the context that the transactions are rechecked against.

type SortedMap

type SortedMap struct {
	// contains filtered or unexported fields
}

SortedMap is a nonce->transaction hash map with a heap based index to allow iterating over the contents in a nonce-incrementing way.

func NewSortedMap

func NewSortedMap() *SortedMap

NewSortedMap creates a new nonce-sorted transaction map.

func (*SortedMap) Cap

func (m *SortedMap) Cap(threshold int) types.Transactions

Cap places a hard limit on the number of items, returning all transactions exceeding that limit.

func (*SortedMap) Filter

func (m *SortedMap) Filter(filter func(*types.Transaction) bool) types.Transactions

Filter iterates over the list of transactions and removes all of them for which the specified function evaluates to true. Filter, as opposed to 'filter', re-initialises the heap after the operation is done. If you want to do several consecutive filterings, it's therefore better to first do a .filter(func1) followed by .Filter(func2) or reheap()

func (*SortedMap) FilterSorted added in v0.7.0

func (m *SortedMap) FilterSorted(filter func(*types.Transaction) bool) types.Transactions

FilterSorted iterates over the list of transactions and removes all of them for which the specified function evaluates to true. FilterSorted iterates over transactions from lowest nonce to highest nonce. FilterSorted, as opposed to 'filterSorted', re-initialises the heap after the operation is done. If you want to do several consecutive filterings, it's therefore better to first do a .filterSorted(func1) followed by .FilterSorted(func2) or reheap()

func (*SortedMap) Flatten

func (m *SortedMap) Flatten() types.Transactions

Flatten creates a nonce-sorted slice of transactions based on the loosely sorted internal representation. The result of the sorting is cached in case it's requested again before any modifications are made to the contents.

func (*SortedMap) Forward

func (m *SortedMap) Forward(threshold uint64) types.Transactions

Forward removes all transactions from the map with a nonce lower than the provided threshold. Every removed transaction is returned for any post-removal maintenance.

func (*SortedMap) Get

func (m *SortedMap) Get(nonce uint64) *types.Transaction

Get retrieves the current transactions associated with the given nonce.

func (*SortedMap) LastElement

func (m *SortedMap) LastElement() *types.Transaction

LastElement returns the last element of a flattened list, thus, the transaction with the highest nonce

func (*SortedMap) Len

func (m *SortedMap) Len() int

Len returns the length of the transaction map.

func (*SortedMap) Put

func (m *SortedMap) Put(tx *types.Transaction)

Put inserts a new transaction into the map, also updating the map's nonce index. If a transaction already exists with the same nonce, it's overwritten.

func (*SortedMap) Ready

func (m *SortedMap) Ready(start uint64) types.Transactions

Ready retrieves a sequentially increasing list of transactions starting at the provided nonce that is ready for processing. The returned transactions will be removed from the list.

Note, all transactions with nonces lower than start will also be returned to prevent getting into an invalid state. This is not something that should ever happen but better to be self correcting than failing!

func (*SortedMap) Remove

func (m *SortedMap) Remove(nonce uint64) bool

Remove deletes a transaction from the maintained map, returning whether the transaction was found.

type TxStore added in v0.7.0

type TxStore struct {
	// contains filtered or unexported fields
}

TxStore is a set of transactions at a height that can be added to or removed from.

func NewTxStore added in v0.7.0

func NewTxStore(logger log.Logger) *TxStore

NewTxStore creates a new TxStore.

func (*TxStore) AddTx added in v0.7.0

func (t *TxStore) AddTx(addr common.Address, tx *types.Transaction)

AddTx adds a single tx to the store.

func (*TxStore) AddTxs added in v0.7.0

func (t *TxStore) AddTxs(addr common.Address, txs types.Transactions)

AddTxs adds txs to the store.

func (*TxStore) RemoveTx added in v0.7.0

func (t *TxStore) RemoveTx(addr common.Address, tx *types.Transaction)

RemoveTx removes a tx for an address from the current set.

func (*TxStore) RemoveTxsFromNonce added in v0.7.0

func (t *TxStore) RemoveTxsFromNonce(addr common.Address, minNonce uint64)

RemoveTxsFromNonce removes all txs for addr whose nonce is >= minNonce.

func (*TxStore) Txs added in v0.7.0

Get returns the current set of txs in the store.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL