execution

package
v5.1.2-mekong Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2024 License: GPL-3.0 Imports: 59 Imported by: 0

Documentation

Overview

Package execution defines a runtime service which is tasked with communicating with an eth1 endpoint, processing logs from a deposit contract, and the latest eth1 data headers for usage in the beacon node.

Index

Constants

View Source
const (
	// NewPayloadMethod v1 request string for JSON-RPC.
	NewPayloadMethod = "engine_newPayloadV1"
	// NewPayloadMethodV2 v2 request string for JSON-RPC.
	NewPayloadMethodV2 = "engine_newPayloadV2"
	NewPayloadMethodV3 = "engine_newPayloadV3"
	// NewPayloadMethodV4 is the engine_newPayloadVX method added at Electra.
	NewPayloadMethodV4 = "engine_newPayloadV4"
	// ForkchoiceUpdatedMethod v1 request string for JSON-RPC.
	ForkchoiceUpdatedMethod = "engine_forkchoiceUpdatedV1"
	// ForkchoiceUpdatedMethodV2 v2 request string for JSON-RPC.
	ForkchoiceUpdatedMethodV2 = "engine_forkchoiceUpdatedV2"
	// ForkchoiceUpdatedMethodV3 v3 request string for JSON-RPC.
	ForkchoiceUpdatedMethodV3 = "engine_forkchoiceUpdatedV3"
	// GetPayloadMethod v1 request string for JSON-RPC.
	GetPayloadMethod = "engine_getPayloadV1"
	// GetPayloadMethodV2 v2 request string for JSON-RPC.
	GetPayloadMethodV2 = "engine_getPayloadV2"
	// GetPayloadMethodV3 is the get payload method added for deneb
	GetPayloadMethodV3 = "engine_getPayloadV3"
	// GetPayloadMethodV4 is the get payload method added for electra
	GetPayloadMethodV4 = "engine_getPayloadV4"
	// BlockByHashMethod request string for JSON-RPC.
	BlockByHashMethod = "eth_getBlockByHash"
	// BlockByNumberMethod request string for JSON-RPC.
	BlockByNumberMethod = "eth_getBlockByNumber"
	// GetPayloadBodiesByHashV1 is the engine_getPayloadBodiesByHashX JSON-RPC method for pre-Electra payloads.
	GetPayloadBodiesByHashV1 = "engine_getPayloadBodiesByHashV1"
	// GetPayloadBodiesByRangeV1 is the engine_getPayloadBodiesByRangeX JSON-RPC method for pre-Electra payloads.
	GetPayloadBodiesByRangeV1 = "engine_getPayloadBodiesByRangeV1"
	// ExchangeCapabilities request string for JSON-RPC.
	ExchangeCapabilities = "engine_exchangeCapabilities"
)

Variables

View Source
var (
	// ErrParse corresponds to JSON-RPC code -32700.
	ErrParse = errors.New("invalid JSON was received by the server")
	// ErrInvalidRequest corresponds to JSON-RPC code -32600.
	ErrInvalidRequest = errors.New("JSON sent is not valid request object")
	// ErrMethodNotFound corresponds to JSON-RPC code -32601.
	ErrMethodNotFound = errors.New("method not found")
	// ErrInvalidParams corresponds to JSON-RPC code -32602.
	ErrInvalidParams = errors.New("invalid method parameter(s)")
	// ErrInternal corresponds to JSON-RPC code -32603.
	ErrInternal = errors.New("internal JSON-RPC error")
	// ErrServer corresponds to JSON-RPC code -32000.
	ErrServer = errors.New("client error while processing request")
	// ErrUnknownPayload corresponds to JSON-RPC code -38001.
	ErrUnknownPayload = errors.New("payload does not exist or is not available")
	// ErrInvalidForkchoiceState corresponds to JSON-RPC code -38002.
	ErrInvalidForkchoiceState = errors.New("invalid forkchoice state")
	// ErrInvalidPayloadAttributes corresponds to JSON-RPC code -38003.
	ErrInvalidPayloadAttributes = errors.New("payload attributes are invalid / inconsistent")
	// ErrUnknownPayloadStatus when the payload status is unknown.
	ErrUnknownPayloadStatus = errors.New("unknown payload status")
	// ErrAcceptedSyncingPayloadStatus when the status of the payload is syncing or accepted.
	ErrAcceptedSyncingPayloadStatus = errors.New("payload status is SYNCING or ACCEPTED")
	// ErrInvalidPayloadStatus when the status of the payload is invalid.
	ErrInvalidPayloadStatus = errors.New("payload status is INVALID")
	// ErrInvalidBlockHashPayloadStatus when the status of the payload fails to validate block hash.
	ErrInvalidBlockHashPayloadStatus = errors.New("payload status is INVALID_BLOCK_HASH")
	// ErrNilResponse when the response is nil.
	ErrNilResponse = errors.New("nil response")
	// ErrRequestTooLarge when the request is too large
	ErrRequestTooLarge = errors.New("request too large")
	// ErrUnsupportedVersion represents a case where a payload is requested for a block type that doesn't have a known mapping.
	ErrUnsupportedVersion = errors.New("unknown ExecutionPayload schema for block version")
)
View Source
var ErrEmptyBlockHash = errors.New("Block hash is empty 0x0000...")
View Source
var ErrHTTPTimeout = errors.New("timeout from http.Client")

ErrHTTPTimeout returns true if the error is a http.Client timeout error.

View Source
var (
	// ErrNotAHeaderInfo will be returned when a cache object is not a pointer to
	// a headerInfo struct.
	ErrNotAHeaderInfo = errors.New("object is not a header info")
)

Functions

func DepositContractAddress

func DepositContractAddress() (string, error)

DepositContractAddress returns the deposit contract address for the given chain.

Types

type BeaconNodeStatsUpdater

type BeaconNodeStatsUpdater interface {
	Update(stats clientstats.BeaconNodeStats)
}

type Chain

Chain defines a standard interface for the powchain service in Prysm.

type ChainInfoFetcher

type ChainInfoFetcher interface {
	GenesisExecutionChainInfo() (uint64, *big.Int)
	ExecutionClientConnected() bool
	ExecutionClientEndpoint() string
	ExecutionClientConnectionErr() error
}

ChainInfoFetcher retrieves information about eth1 metadata at the Ethereum consensus genesis time.

type ChainStartFetcher

type ChainStartFetcher interface {
	ChainStartEth1Data() *ethpb.Eth1Data
	PreGenesisState() state.BeaconState
	ClearPreGenesisData()
}

ChainStartFetcher retrieves information pertaining to the chain start event of the beacon chain for usage across various services.

type EngineCaller

type EngineCaller interface {
	NewPayload(ctx context.Context, payload interfaces.ExecutionData, versionedHashes []common.Hash, parentBlockRoot *common.Hash, executionRequests *pb.ExecutionRequests) ([]byte, error)
	ForkchoiceUpdated(
		ctx context.Context, state *pb.ForkchoiceState, attrs payloadattribute.Attributer,
	) (*pb.PayloadIDBytes, []byte, error)
	GetPayload(ctx context.Context, payloadId [8]byte, slot primitives.Slot) (*blocks.GetPayloadResponse, error)
	ExecutionBlockByHash(ctx context.Context, hash common.Hash, withTxs bool) (*pb.ExecutionBlock, error)
	GetTerminalBlockHash(ctx context.Context, transitionTime uint64) ([]byte, bool, error)
}

EngineCaller defines a client that can interact with an Ethereum execution node's engine service via JSON-RPC.

type ForkchoiceUpdatedResponse

type ForkchoiceUpdatedResponse struct {
	Status          *pb.PayloadStatus  `json:"payloadStatus"`
	PayloadId       *pb.PayloadIDBytes `json:"payloadId"`
	ValidationError string             `json:"validationError"`
}

ForkchoiceUpdatedResponse is the response kind received by the engine_forkchoiceUpdatedV1 endpoint.

type NopBeaconNodeStatsUpdater

type NopBeaconNodeStatsUpdater struct{}

func (*NopBeaconNodeStatsUpdater) Update

type Option

type Option func(s *Service) error

func WithBeaconNodeStatsUpdater

func WithBeaconNodeStatsUpdater(updater BeaconNodeStatsUpdater) Option

WithBeaconNodeStatsUpdater to set the beacon node stats updater.

func WithDatabase

func WithDatabase(database db.HeadAccessDatabase) Option

WithDatabase for the beacon chain database.

func WithDepositCache

func WithDepositCache(cache cache.DepositCache) Option

WithDepositCache for caching deposits.

func WithDepositContractAddress

func WithDepositContractAddress(addr common.Address) Option

WithDepositContractAddress for the deposit contract.

func WithEth1HeaderRequestLimit

func WithEth1HeaderRequestLimit(limit uint64) Option

WithEth1HeaderRequestLimit to set the upper limit of eth1 header requests.

func WithFinalizedStateAtStartup

func WithFinalizedStateAtStartup(st state.BeaconState) Option

WithFinalizedStateAtStartup to set the beacon node's finalized state at startup.

func WithHeaders

func WithHeaders(headers []string) Option

WithHeaders adds headers to the execution node JSON-RPC requests.

func WithHttpEndpoint

func WithHttpEndpoint(endpointString string) Option

WithHttpEndpoint parse http endpoint for the powchain service to use.

func WithHttpEndpointAndJWTSecret

func WithHttpEndpointAndJWTSecret(endpointString string, secret []byte) Option

WithHttpEndpointAndJWTSecret for authenticating the execution node JSON-RPC endpoint.

func WithJwtId

func WithJwtId(jwtId string) Option

func WithStateGen

func WithStateGen(gen *stategen.State) Option

WithStateGen to regenerate beacon states from checkpoints.

func WithStateNotifier

func WithStateNotifier(notifier statefeed.Notifier) Option

WithStateNotifier for subscribing to state changes.

type POWBlockFetcher

type POWBlockFetcher interface {
	BlockTimeByHeight(ctx context.Context, height *big.Int) (uint64, error)
	BlockByTimestamp(ctx context.Context, time uint64) (*types.HeaderInfo, error)
	BlockHashByHeight(ctx context.Context, height *big.Int) (common.Hash, error)
	BlockExists(ctx context.Context, hash common.Hash) (bool, *big.Int, error)
}

POWBlockFetcher defines a struct that can retrieve mainchain blocks.

type PayloadReconstructor

type PayloadReconstructor interface {
	ReconstructFullBlock(
		ctx context.Context, blindedBlock interfaces.ReadOnlySignedBeaconBlock,
	) (interfaces.SignedBeaconBlock, error)
	ReconstructFullBellatrixBlockBatch(
		ctx context.Context, blindedBlocks []interfaces.ReadOnlySignedBeaconBlock,
	) ([]interfaces.SignedBeaconBlock, error)
}

PayloadReconstructor defines a service that can reconstruct a full beacon block with an execution payload from a signed beacon block and a connection to an execution client's engine API.

type PowchainCollector

type PowchainCollector struct {
	SyncEth1Connected *prometheus.Desc

	sync.Mutex
	// contains filtered or unexported fields
}

func NewPowchainCollector

func NewPowchainCollector(ctx context.Context) (*PowchainCollector, error)

func (*PowchainCollector) Collect

func (pc *PowchainCollector) Collect(ch chan<- prometheus.Metric)

Collect is invoked by the prometheus collection loop. It returns a set of Metrics representing the observation for the current collection period. In the case of this collector, we use values from the latest BeaconNodeStats value sent by the powchain Service, which updates this value whenever an internal event could change the state of one of the metrics. Describe and Collect together satisfy the prometheus.Collector interface.

func (*PowchainCollector) Describe

func (pc *PowchainCollector) Describe(ch chan<- *prometheus.Desc)

Describe is invoked by the prometheus collection loop. It returns a set of metric Descriptor references which are also used in Collect to group collected metrics into a family. Describe and Collect together satisfy the prometheus.Collector interface.

func (*PowchainCollector) Update

func (pc *PowchainCollector) Update(update clientstats.BeaconNodeStats)

Update satisfies the BeaconNodeStatsUpdater

type RPCClient

type RPCClient interface {
	Close()
	BatchCall(b []gethRPC.BatchElem) error
	CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
}

RPCClient defines the rpc methods required to interact with the eth1 node.

type RPCClientEmpty

type RPCClientEmpty struct {
}

func (RPCClientEmpty) BatchCall

func (RPCClientEmpty) BatchCall([]gethRPC.BatchElem) error

func (RPCClientEmpty) CallContext

func (RPCClientEmpty) CallContext(context.Context, interface{}, string, ...interface{}) error

func (RPCClientEmpty) Close

func (RPCClientEmpty) Close()

type Service

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

Service fetches important information about the canonical eth1 chain via a web3 endpoint using an ethclient. The beacon chain requires synchronization with the eth1 chain's current block hash, block number, and access to logs within the Validator Registration Contract on the eth1 chain to kick off the beacon chain's validator registration process.

func NewService

func NewService(ctx context.Context, opts ...Option) (*Service, error)

NewService sets up a new instance with an ethclient when given a web3 endpoint as a string in the config.

func (*Service) BlockByTimestamp

func (s *Service) BlockByTimestamp(ctx context.Context, time uint64) (*types.HeaderInfo, error)

BlockByTimestamp returns the most recent block number up to a given timestamp. This is an optimized version with the worst case being O(2*repeatedSearches) number of calls while in best case search for the block is performed in O(1).

func (*Service) BlockExists

func (s *Service) BlockExists(ctx context.Context, hash common.Hash) (bool, *big.Int, error)

BlockExists returns true if the block exists, its height and any possible error encountered.

func (*Service) BlockHashByHeight

func (s *Service) BlockHashByHeight(ctx context.Context, height *big.Int) (common.Hash, error)

BlockHashByHeight returns the block hash of the block at the given height.

func (*Service) BlockTimeByHeight

func (s *Service) BlockTimeByHeight(ctx context.Context, height *big.Int) (uint64, error)

BlockTimeByHeight fetches an eth1 block timestamp by its height.

func (*Service) ChainStartEth1Data

func (s *Service) ChainStartEth1Data() *ethpb.Eth1Data

ChainStartEth1Data returns the eth1 data at chainstart.

func (*Service) ClearPreGenesisData

func (s *Service) ClearPreGenesisData()

ClearPreGenesisData clears out the stored chainstart deposits and beacon state.

func (*Service) ExchangeCapabilities

func (s *Service) ExchangeCapabilities(ctx context.Context) ([]string, error)

func (*Service) ExecutionBlockByHash

func (s *Service) ExecutionBlockByHash(ctx context.Context, hash common.Hash, withTxs bool) (*pb.ExecutionBlock, error)

ExecutionBlockByHash fetches an execution engine block by hash by calling eth_blockByHash via JSON-RPC.

func (*Service) ExecutionBlocksByHashes

func (s *Service) ExecutionBlocksByHashes(ctx context.Context, hashes []common.Hash, withTxs bool) ([]*pb.ExecutionBlock, error)

ExecutionBlocksByHashes fetches a batch of execution engine blocks by hash by calling eth_blockByHash via JSON-RPC.

func (*Service) ExecutionClientConnected

func (s *Service) ExecutionClientConnected() bool

ExecutionClientConnected checks whether are connected via RPC.

func (*Service) ExecutionClientConnectionErr

func (s *Service) ExecutionClientConnectionErr() error

ExecutionClientConnectionErr returns the error (if any) of the current connection.

func (*Service) ExecutionClientEndpoint

func (s *Service) ExecutionClientEndpoint() string

ExecutionClientEndpoint returns the URL of the current, connected execution client.

func (*Service) ForkchoiceUpdated

func (s *Service) ForkchoiceUpdated(
	ctx context.Context, state *pb.ForkchoiceState, attrs payloadattribute.Attributer,
) (*pb.PayloadIDBytes, []byte, error)

ForkchoiceUpdated calls the engine_forkchoiceUpdatedV1 method via JSON-RPC.

func (*Service) GenesisExecutionChainInfo

func (s *Service) GenesisExecutionChainInfo() (uint64, *big.Int)

GenesisExecutionChainInfo retrieves the genesis time and execution block number of the beacon chain from the deposit contract.

func (*Service) GetPayload

func (s *Service) GetPayload(ctx context.Context, payloadId [8]byte, slot primitives.Slot) (*blocks.GetPayloadResponse, error)

GetPayload calls the engine_getPayloadVX method via JSON-RPC. It returns the execution data as well as the blobs bundle.

func (*Service) GetTerminalBlockHash

func (s *Service) GetTerminalBlockHash(ctx context.Context, transitionTime uint64) ([]byte, bool, error)

GetTerminalBlockHash returns the valid terminal block hash based on total difficulty.

Spec code: def get_pow_block_at_terminal_total_difficulty(pow_chain: Dict[Hash32, PowBlock]) -> Optional[PowBlock]:

# `pow_chain` abstractly represents all blocks in the PoW chain
for block in pow_chain:
    parent = pow_chain[block.parent_hash]
    block_reached_ttd = block.total_difficulty >= TERMINAL_TOTAL_DIFFICULTY
    parent_reached_ttd = parent.total_difficulty >= TERMINAL_TOTAL_DIFFICULTY
    if block_reached_ttd and not parent_reached_ttd:
        return block

return None

func (*Service) HeaderByHash

func (s *Service) HeaderByHash(ctx context.Context, hash common.Hash) (*types.HeaderInfo, error)

HeaderByHash returns the relevant header details for the provided block hash.

func (*Service) HeaderByNumber

func (s *Service) HeaderByNumber(ctx context.Context, number *big.Int) (*types.HeaderInfo, error)

HeaderByNumber returns the relevant header details for the provided block number.

func (*Service) LatestExecutionBlock

func (s *Service) LatestExecutionBlock(ctx context.Context) (*pb.ExecutionBlock, error)

LatestExecutionBlock fetches the latest execution engine block by calling eth_blockByNumber via JSON-RPC.

func (*Service) NewPayload

func (s *Service) NewPayload(ctx context.Context, payload interfaces.ExecutionData, versionedHashes []common.Hash, parentBlockRoot *common.Hash, executionRequests *pb.ExecutionRequests) ([]byte, error)

NewPayload request calls the engine_newPayloadVX method via JSON-RPC.

func (*Service) PreGenesisState

func (s *Service) PreGenesisState() state.BeaconState

PreGenesisState returns a state that contains pre-chainstart deposits.

func (*Service) ProcessChainStart

func (s *Service) ProcessChainStart(genesisTime uint64, eth1BlockHash [32]byte, blockNumber *big.Int)

ProcessChainStart processes the log which had been received from the eth1 chain by trying to determine when to start the beacon chain.

func (*Service) ProcessDepositLog

func (s *Service) ProcessDepositLog(ctx context.Context, depositLog *gethtypes.Log) error

ProcessDepositLog processes the log which had been received from the eth1 chain by trying to ascertain which participant deposited in the contract.

func (*Service) ProcessETH1Block

func (s *Service) ProcessETH1Block(ctx context.Context, blkNum *big.Int) error

ProcessETH1Block processes logs from the provided eth1 block.

func (*Service) ProcessLog

func (s *Service) ProcessLog(ctx context.Context, depositLog *gethtypes.Log) error

ProcessLog is the main method which handles the processing of all logs from the deposit contract on the eth1 chain.

func (*Service) ReconstructFullBellatrixBlockBatch

func (s *Service) ReconstructFullBellatrixBlockBatch(
	ctx context.Context, blindedBlocks []interfaces.ReadOnlySignedBeaconBlock,
) ([]interfaces.SignedBeaconBlock, error)

ReconstructFullBellatrixBlockBatch takes in a batch of blinded beacon blocks and reconstructs them with a full execution payload for each block via the engine API.

func (*Service) ReconstructFullBlock

func (s *Service) ReconstructFullBlock(
	ctx context.Context, blindedBlock interfaces.ReadOnlySignedBeaconBlock,
) (interfaces.SignedBeaconBlock, error)

ReconstructFullBlock takes in a blinded beacon block and reconstructs a beacon block with a full execution payload via the engine API.

func (*Service) Start

func (s *Service) Start()

Start the powchain service's main event loop.

func (*Service) Status

func (s *Service) Status() error

Status is service health checks. Return nil or error.

func (*Service) Stop

func (s *Service) Stop() error

Stop the web3 service's main event loop and associated goroutines.

Directories

Path Synopsis
Package testing provides useful mocks for an eth1 powchain service as needed by unit tests for the beacon node.
Package testing provides useful mocks for an eth1 powchain service as needed by unit tests for the beacon node.

Jump to

Keyboard shortcuts

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