txpool

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2024 License: GPL-3.0, LGPL-3.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAlreadyKnown is returned if the transactions is already contained
	// within the pool.
	ErrAlreadyKnown = errors.New("already known")

	// ErrInvalidSender is returned if the transaction contains an invalid signature.
	ErrInvalidSender = errors.New("invalid sender")

	// ErrUnderpriced is returned if a transaction's gas price is below the minimum
	// configured for the transaction pool.
	ErrUnderpriced = errors.New("transaction underpriced")

	// ErrReplaceUnderpriced is returned if a transaction is attempted to be replaced
	// with a different one without the required price bump.
	ErrReplaceUnderpriced = errors.New("replacement transaction underpriced")

	// ErrAccountLimitExceeded is returned if a transaction would exceed the number
	// allowed by a pool for a single account.
	ErrAccountLimitExceeded = errors.New("account limit exceeded")

	// ErrGasLimit is returned if a transaction's requested gas limit exceeds the
	// maximum allowance of the current block.
	ErrGasLimit = errors.New("exceeds block gas limit")

	// ErrNegativeValue is a sanity error to ensure no one is able to specify a
	// transaction with a negative value.
	ErrNegativeValue = errors.New("negative value")

	// ErrOversizedData is returned if the input data of a transaction is greater
	// than some meaningful limit a user might use. This is not a consensus error
	// making the transaction invalid, rather a DOS protection.
	ErrOversizedData = errors.New("oversized data")

	// 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")

	// ErrAlreadyReserved is returned if the sender address has a pending transaction
	// in a different subpool. For example, this error is returned in response to any
	// input transaction of non-blob type when a blob transaction from this sender
	// remains pending (and vice-versa).
	ErrAlreadyReserved = errors.New("address already reserved")
)
View Source
var (
	// ErrOverdraft is returned if a transaction would cause the senders balance to go negative
	// thus invalidating a potential large number of transactions.
	ErrOverdraft = errors.New("transaction would cause overdraft")
)

Functions

func ValidateTransaction added in v0.6.3

func ValidateTransaction(tx *types.Transaction, head *types.Header, signer types.Signer, opts *ValidationOptions) error

ValidateTransaction is a helper method to check whether a transaction is valid according to the consensus rules, but does not check state-dependent validation (balance, nonce, etc).

This check is public to allow different transaction pools to check the basic rules without duplicating code and running the risk of missed updates.

func ValidateTransactionWithState added in v0.6.3

func ValidateTransactionWithState(tx *types.Transaction, signer types.Signer, opts *ValidationOptionsWithState) error

ValidateTransactionWithState is a helper method to check whether a transaction is valid according to the pool's internal state checks (balance, nonce, gaps).

This check is public to allow different transaction pools to check the stateful rules without duplicating code and running the risk of missed updates.

Types

type AddressReserver added in v0.6.3

type AddressReserver func(addr common.Address, reserve bool) error

AddressReserver is passed by the main transaction pool to subpools, so they may request (and relinquish) exclusive access to certain addresses.

type BlockChain added in v0.6.3

type BlockChain interface {
	// CurrentBlock returns the current head of the chain.
	CurrentBlock() *types.Header

	// SubscribeChainHeadEvent subscribes to new blocks being added to the chain.
	SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
}

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 LazyResolver added in v0.6.5

type LazyResolver interface {
	// Get returns a transaction if it is contained in the pool, or nil otherwise.
	Get(hash common.Hash) *types.Transaction
}

LazyResolver is a minimal interface needed for a transaction pool to satisfy resolving lazy transactions. It's mostly a helper to avoid the entire sub- pool being injected into the lazy transaction.

type LazyTransaction added in v0.6.3

type LazyTransaction struct {
	Pool LazyResolver       // Transaction resolver to pull the real transaction up
	Hash common.Hash        // Transaction hash to pull up if needed
	Tx   *types.Transaction // Transaction if already resolved

	Time      time.Time    // Time when the transaction was first seen
	GasFeeCap *uint256.Int // Maximum fee per gas the transaction may consume
	GasTipCap *uint256.Int // Maximum miner tip per gas the transaction can pay

	Gas     uint64 // Amount of gas required by the transaction
	BlobGas uint64 // Amount of blob gas required by the transaction
}

LazyTransaction contains a small subset of the transaction properties that is enough for the miner and other APIs to handle large batches of transactions; and supports pulling up the entire transaction when really needed.

func (*LazyTransaction) Resolve added in v0.6.3

func (ltx *LazyTransaction) Resolve() *types.Transaction

Resolve retrieves the full transaction belonging to a lazy handle if it is still maintained by the transaction pool.

Note, the method will *not* cache the retrieved transaction if the original pool has not cached it. The idea being, that if the tx was too big to insert originally, silently saving it will cause more trouble down the line (and indeed seems to have caused a memory bloat in the original implementation which did just that).

type PendingFilter added in v0.6.9

type PendingFilter struct {
	MinTip  *uint256.Int // Minimum miner tip required to include a transaction
	BaseFee *uint256.Int // Minimum 1559 basefee needed to include a transaction
	BlobFee *uint256.Int // Minimum 4844 blobfee needed to include a blob transaction

	OnlyPlainTxs bool // Return only plain EVM transactions (peer-join announces, block space filling)
	OnlyBlobTxs  bool // Return only blob transactions (block blob-space filling)
}

PendingFilter is a collection of filter rules to allow retrieving a subset of transactions for announcement or mining.

Note, the entries here are not arbitrary useful filters, rather each one has a very specific call site in mind and each one can be evaluated very cheaply by the pool implementations. Only add new ones that satisfy those constraints.

type SubPool added in v0.6.3

type SubPool interface {
	// Filter is a selector used to decide whether a transaction would be added
	// to this particular subpool.
	Filter(tx *types.Transaction) bool

	// Init sets the base parameters of the subpool, allowing it to load any saved
	// transactions from disk and also permitting internal maintenance routines to
	// start up.
	//
	// These should not be passed as a constructor argument - nor should the pools
	// start by themselves - in order to keep multiple subpools in lockstep with
	// one another.
	Init(gasTip uint64, head *types.Header, reserve AddressReserver) error

	// Close terminates any background processing threads and releases any held
	// resources.
	Close() error

	// Reset retrieves the current state of the blockchain and ensures the content
	// of the transaction pool is valid with regard to the chain state.
	Reset(oldHead, newHead *types.Header)

	// SetGasTip updates the minimum price required by the subpool for a new
	// transaction, and drops all transactions below this threshold.
	SetGasTip(tip *big.Int)
	SetMinFee(fee *big.Int)

	// Has returns an indicator whether subpool has a transaction cached with the
	// given hash.
	Has(hash common.Hash) bool
	HasLocal(hash common.Hash) bool

	// Get returns a transaction if it is contained in the pool, or nil otherwise.
	Get(hash common.Hash) *types.Transaction

	// Add enqueues a batch of transactions into the pool if they are valid. Due
	// to the large transaction churn, add may postpone fully integrating the tx
	// to a later point to batch multiple ones together.
	Add(txs []*types.Transaction, local bool, sync bool) []error

	// 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.
	Pending(filter PendingFilter) map[common.Address][]*LazyTransaction
	IteratePending(f func(tx *types.Transaction) bool) bool // Returns false if iteration was interrupted.

	// SubscribeTransactions subscribes to new transaction events. The subscriber
	// can decide whether to receive notifications only for newly seen transactions
	// or also for reorged out ones.
	SubscribeTransactions(ch chan<- core.NewTxsEvent, reorgs bool) event.Subscription

	// Nonce returns the next nonce of an account, with all transactions executable
	// by the pool already applied on top.
	Nonce(addr common.Address) uint64

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

	// 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.
	Content() (map[common.Address][]*types.Transaction, map[common.Address][]*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.
	ContentFrom(addr common.Address) ([]*types.Transaction, []*types.Transaction)

	// Locals retrieves the accounts currently considered local by the pool.
	Locals() []common.Address

	// Status returns the known status (unknown/pending/queued) of a transaction
	// identified by their hashes.
	Status(hash common.Hash) TxStatus
}

SubPool represents a specialized transaction pool that lives on its own (e.g. blob pool). Since independent of how many specialized pools we have, they do need to be updated in lockstep and assemble into one coherent view for block production, this interface defines the common methods that allow the primary transaction pool to manage the subpools.

type TxPool

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

TxPool is an aggregator for various transaction specific pools, collectively tracking all the transactions deemed interesting by the node. 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 or evicted due to resource constraints.

func New added in v0.6.3

func New(gasTip uint64, chain BlockChain, subpools []SubPool) (*TxPool, error)

New creates a new transaction pool to gather, sort and filter inbound transactions from the network.

func (*TxPool) Add added in v0.6.3

func (p *TxPool) Add(txs []*types.Transaction, local bool, sync bool) []error

Add enqueues a batch of transactions into the pool if they are valid. Due to the large transaction churn, add may postpone fully integrating the tx to a later point to batch multiple ones together.

func (*TxPool) AddRemotesSync

func (p *TxPool) AddRemotesSync(txs []*types.Transaction) []error

func (*TxPool) Close added in v0.6.3

func (p *TxPool) Close() error

Close terminates the transaction pool and all its subpools.

func (*TxPool) Content

func (p *TxPool) 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 (*TxPool) ContentFrom

func (p *TxPool) 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 (*TxPool) GasTip added in v0.6.3

func (p *TxPool) GasTip() *big.Int

GasTip returns the current gas tip enforced by the transaction pool.

func (*TxPool) Get

func (p *TxPool) Get(hash common.Hash) *types.Transaction

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

func (*TxPool) Has

func (p *TxPool) Has(hash common.Hash) bool

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

func (*TxPool) HasLocal

func (p *TxPool) HasLocal(hash common.Hash) bool

HasLocal returns an indicator whether the pool has a local transaction cached with the given hash.

func (*TxPool) IteratePending added in v0.5.6

func (p *TxPool) IteratePending(f func(tx *types.Transaction) bool)

IteratePending iterates over [pool.pending] until [f] returns false. The caller must not modify [tx].

func (*TxPool) Locals

func (p *TxPool) Locals() []common.Address

Locals retrieves the accounts currently considered local by the pool.

func (*TxPool) Nonce

func (p *TxPool) 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 (*TxPool) Pending

func (p *TxPool) Pending(filter PendingFilter) map[common.Address][]*LazyTransaction

Pending retrieves all currently processable transactions, grouped by origin account and sorted by nonce. The returned transaction set is a copy and can be freely modified by calling code.

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

func (*TxPool) PendingSize

func (p *TxPool) PendingSize(filter PendingFilter) int

PendingSize returns the number of pending txs in the tx pool.

The filter parameter can be used to do an extra filtering on the pending transactions.

func (*TxPool) SetGasTip added in v0.6.3

func (p *TxPool) 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 (*TxPool) SetMinFee

func (p *TxPool) SetMinFee(fee *big.Int)

SetMinFee updates the minimum fee required by the transaction pool for a new transaction, and drops all transactions below this threshold.

func (*TxPool) Stats

func (p *TxPool) Stats() (int, int)

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

func (*TxPool) Status

func (p *TxPool) Status(hash common.Hash) TxStatus

Status returns the known status (unknown/pending/queued) of a transaction identified by its hash.

func (*TxPool) SubscribeNewReorgEvent

func (p *TxPool) SubscribeNewReorgEvent(ch chan<- core.NewTxPoolReorgEvent) event.Subscription

SubscribeNewReorgEvent registers a subscription of NewReorgEvent and starts sending event to the given channel.

func (*TxPool) SubscribeTransactions added in v0.6.5

func (p *TxPool) 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 (*TxPool) Sync added in v0.6.9

func (p *TxPool) Sync() error

Sync is a helper method for unit tests or simulator runs where the chain events are arriving in quick succession, without any time in between them to run the internal background reset operations. This method will run an explicit reset operation to ensure the pool stabilises, thus avoiding flakey behavior.

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.

type TxStatus

type TxStatus uint

TxStatus is the current status of a transaction as seen by the pool.

const (
	TxStatusUnknown TxStatus = iota
	TxStatusQueued
	TxStatusPending
)

type ValidationOptions added in v0.6.3

type ValidationOptions struct {
	Config *params.ChainConfig // Chain configuration to selectively validate based on current fork rules

	Accept  uint8    // Bitmap of transaction types that should be accepted for the calling pool
	MaxSize uint64   // Maximum size of a transaction that the caller can meaningfully handle
	MinTip  *big.Int // Minimum gas tip needed to allow a transaction into the caller pool
}

ValidationOptions define certain differences between transaction validation across the different pools without having to duplicate those checks.

type ValidationOptionsWithState added in v0.6.3

type ValidationOptionsWithState struct {
	State *state.StateDB // State database to check nonces and balances against

	// FirstNonceGap is an optional callback to retrieve the first nonce gap in
	// the list of pooled transactions of a specific account. If this method is
	// set, nonce gaps will be checked and forbidden. If this method is not set,
	// nonce gaps will be ignored and permitted.
	FirstNonceGap func(addr common.Address) uint64

	// UsedAndLeftSlots is a mandatory callback to retrieve the number of tx slots
	// used and the number still permitted for an account. New transactions will
	// be rejected once the number of remaining slots reaches zero.
	UsedAndLeftSlots func(addr common.Address) (int, int)

	// ExistingExpenditure is a mandatory callback to retrieve the cumulative
	// cost of the already pooled transactions to check for overdrafts.
	ExistingExpenditure func(addr common.Address) *big.Int

	// ExistingCost is a mandatory callback to retrieve an already pooled
	// transaction's cost with the given nonce to check for overdrafts.
	ExistingCost func(addr common.Address, nonce uint64) *big.Int

	Rules      params.Rules
	MinimumFee *big.Int
}

ValidationOptionsWithState define certain differences between stateful transaction validation across the different pools without having to duplicate those checks.

Directories

Path Synopsis
Package blobpool implements the EIP-4844 blob transaction pool.
Package blobpool implements the EIP-4844 blob transaction pool.
Package legacypool implements the normal EVM execution transaction pool.
Package legacypool implements the normal EVM execution transaction pool.

Jump to

Keyboard shortcuts

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