powchain

package
v1.4.2-0...-e33850b Latest Latest
Warning

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

Go to latest
Published: May 11, 2022 License: GPL-3.0 Imports: 56 Imported by: 62

Documentation

Overview

Package powchain 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"
	// ForkchoiceUpdatedMethod v1 request string for JSON-RPC.
	ForkchoiceUpdatedMethod = "engine_forkchoiceUpdatedV1"
	// GetPayloadMethod v1 request string for JSON-RPC.
	GetPayloadMethod = "engine_getPayloadV1"
	// ExchangeTransitionConfigurationMethod v1 request string for JSON-RPC.
	ExchangeTransitionConfigurationMethod = "engine_exchangeTransitionConfigurationV1"
	// ExecutionBlockByHashMethod request string for JSON-RPC.
	ExecutionBlockByHashMethod = "eth_getBlockByHash"
	// ExecutionBlockByNumberMethod request string for JSON-RPC.
	ExecutionBlockByNumberMethod = "eth_getBlockByNumber"
)

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 -32001.
	ErrUnknownPayload = errors.New("payload does not exist or is not available")
	// ErrUnknownPayloadStatus when the payload status is unknown.
	ErrUnknownPayloadStatus = errors.New("unknown payload status")
	// ErrConfigMismatch when the execution node's terminal total difficulty or
	// terminal block hash received via the API mismatches Prysm's configuration value.
	ErrConfigMismatch = errors.New("execution client configuration mismatch")
	// 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")
	// ErrNilResponse when the response is nil.
	ErrNilResponse = errors.New("nil response")
)
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.

func HttpEndpoint added in v1.3.8

func HttpEndpoint(eth1Provider string) network.Endpoint

HttpEndpoint extracts an httputils.Endpoint from the provider parameter.

Types

type BeaconNodeStatsUpdater added in v1.3.9

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 {
	Eth2GenesisPowchainInfo() (uint64, *big.Int)
	IsConnectedToETH1() bool
	CurrentETH1Endpoint() string
	CurrentETH1ConnectionError() error
	ETH1Endpoints() []string
	ETH1ConnectionErrors() []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 *pb.ExecutionPayload) ([]byte, error)
	ForkchoiceUpdated(
		ctx context.Context, state *pb.ForkchoiceState, attrs *pb.PayloadAttributes,
	) (*pb.PayloadIDBytes, []byte, error)
	GetPayload(ctx context.Context, payloadId [8]byte) (*pb.ExecutionPayload, error)
	ExchangeTransitionConfiguration(
		ctx context.Context, cfg *pb.TransitionConfiguration,
	) error
	ExecutionBlockByHash(ctx context.Context, hash common.Hash) (*pb.ExecutionBlock, error)
	GetTerminalBlockHash(ctx context.Context) ([]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"`
}

ForkchoiceUpdatedResponse is the response kind received by the engine_forkchoiceUpdatedV1 endpoint.

type NopBeaconNodeStatsUpdater added in v1.3.9

type NopBeaconNodeStatsUpdater struct{}

func (*NopBeaconNodeStatsUpdater) Update added in v1.3.9

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 *depositcache.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 WithHttpEndpoints

func WithHttpEndpoints(endpointStrings []string) Option

WithHttpEndpoints deduplicates and parses http endpoints for the powchain service to use, and sets the "current" endpoint that will be used first.

func WithHttpEndpointsAndJWTSecret

func WithHttpEndpointsAndJWTSecret(endpointStrings []string, secret []byte) Option

WithHttpEndpointsAndJWTSecret for authenticating the execution node JSON-RPC endpoint.

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 PowchainCollector added in v1.3.9

type PowchainCollector struct {
	SyncEth1Connected          *prometheus.Desc
	SyncEth1FallbackConnected  *prometheus.Desc
	SyncEth1FallbackConfigured *prometheus.Desc // true if flag specified: --fallback-web3provider

	sync.Mutex
	// contains filtered or unexported fields
}

func NewPowchainCollector added in v1.3.9

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

func (*PowchainCollector) Collect added in v1.3.9

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 added in v1.3.9

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 added in v1.3.9

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

Update satisfies the BeaconNodeStatsUpdater

type RPCClient added in v0.3.0

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 RPCDataFetcher added in v1.0.0

type RPCDataFetcher interface {
	Close()
	HeaderByNumber(ctx context.Context, number *big.Int) (*gethTypes.Header, error)
	HeaderByHash(ctx context.Context, hash common.Hash) (*gethTypes.Header, error)
}

RPCDataFetcher defines a subset of methods conformed to by ETH1.0 RPC clients for fetching eth1 data from the clients.

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 added in v1.1.0

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

func (s *Service) ClearPreGenesisData()

ClearPreGenesisData clears out the stored chainstart deposits and beacon state.

func (*Service) CurrentETH1ConnectionError

func (s *Service) CurrentETH1ConnectionError() error

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

func (*Service) CurrentETH1Endpoint

func (s *Service) CurrentETH1Endpoint() string

CurrentETH1Endpoint returns the URL of the current ETH1 endpoint.

func (*Service) ETH1ConnectionErrors

func (s *Service) ETH1ConnectionErrors() []error

ETH1ConnectionErrors returns a slice of errors for each HTTP endpoint. An error of nil means the connection was successful.

func (*Service) ETH1Endpoints

func (s *Service) ETH1Endpoints() []string

ETH1Endpoints returns the slice of HTTP endpoint URLs (default is 0th element).

func (*Service) Eth2GenesisPowchainInfo

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

Eth2GenesisPowchainInfo retrieves the genesis time and eth1 block number of the beacon chain from the deposit contract.

func (*Service) ExchangeTransitionConfiguration

func (s *Service) ExchangeTransitionConfiguration(
	ctx context.Context, cfg *pb.TransitionConfiguration,
) error

ExchangeTransitionConfiguration calls the engine_exchangeTransitionConfigurationV1 method via JSON-RPC.

func (*Service) ExecutionBlockByHash

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

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

func (*Service) ForkchoiceUpdated

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

ForkchoiceUpdated calls the engine_forkchoiceUpdatedV1 method via JSON-RPC.

func (*Service) GetPayload

func (s *Service) GetPayload(ctx context.Context, payloadId [8]byte) (*pb.ExecutionPayload, error)

GetPayload calls the engine_getPayloadV1 method via JSON-RPC.

func (*Service) GetTerminalBlockHash

func (s *Service) GetTerminalBlockHash(ctx context.Context) ([]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) IsConnectedToETH1 added in v0.2.3

func (s *Service) IsConnectedToETH1() bool

IsConnectedToETH1 checks if the beacon node is connected to a ETH1 Node.

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 *pb.ExecutionPayload) ([]byte, error)

NewPayload calls the engine_newPayloadV1 method via JSON-RPC.

func (*Service) PreGenesisState added in v0.3.0

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

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