blockchain

package
v3.2.2 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2023 License: GPL-3.0 Imports: 62 Imported by: 20

Documentation

Overview

Package blockchain defines the life-cycle of the blockchain at the core of Ethereum, including processing of new blocks and attestations using proof of stake.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidPayload is returned when the payload is invalid
	ErrInvalidPayload = invalidBlock{/* contains filtered or unexported fields */}
	// ErrInvalidBlockHashPayloadStatus is returned when the payload has invalid block hash.
	ErrInvalidBlockHashPayloadStatus = invalidBlock{/* contains filtered or unexported fields */}
	// ErrUndefinedExecutionEngineError is returned when the execution engine returns an error that is not defined
	ErrUndefinedExecutionEngineError = errors.New("received an undefined execution engine error")

	// errNotDescendantOfFinalized is returned when a block is not a descendant of the finalized checkpoint
	ErrNotDescendantOfFinalized = invalidBlock{/* contains filtered or unexported fields */}
)

Functions

func InvalidAncestorRoots

func InvalidAncestorRoots(e error) [][32]byte

InvalidAncestorRoots returns a list of invalid roots up to last valid root.

func InvalidBlockRoot

func InvalidBlockRoot(e error) [32]byte

InvalidBlockRoot returns the invalid block root. If the error doesn't have an invalid blockroot. [32]byte{} is returned.

func IsInvalidBlock

func IsInvalidBlock(e error) bool

IsInvalidBlock returns true if the error has `invalidBlock`.

Types

type AttestationReceiver

type AttestationReceiver interface {
	AttestationStateFetcher
	VerifyLmdFfgConsistency(ctx context.Context, att *ethpb.Attestation) error
	InForkchoice([32]byte) bool
}

AttestationReceiver interface defines the methods of chain service receive and processing new attestations.

type AttestationStateFetcher

type AttestationStateFetcher interface {
	AttestationTargetState(ctx context.Context, target *ethpb.Checkpoint) (state.BeaconState, error)
}

AttestationStateFetcher allows for retrieving a beacon state corresponding to the block root of an attestation's target checkpoint.

type BlockReceiver

type BlockReceiver interface {
	ReceiveBlock(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock, blockRoot [32]byte) error
	ReceiveBlockBatch(ctx context.Context, blocks []interfaces.ReadOnlySignedBeaconBlock, blkRoots [][32]byte) error
	HasBlock(ctx context.Context, root [32]byte) bool
}

BlockReceiver interface defines the methods of chain service for receiving and processing new blocks.

type CanonicalFetcher

type CanonicalFetcher interface {
	IsCanonical(ctx context.Context, blockRoot [32]byte) (bool, error)
}

CanonicalFetcher retrieves the current chain's canonical information.

type ChainInfoFetcher

ChainInfoFetcher defines a common interface for methods in blockchain service which directly retrieve chain info related data.

type FinalizationFetcher

type FinalizationFetcher interface {
	FinalizedCheckpt() *ethpb.Checkpoint
	CurrentJustifiedCheckpt() *ethpb.Checkpoint
	PreviousJustifiedCheckpt() *ethpb.Checkpoint
	InForkchoice([32]byte) bool
	IsFinalized(ctx context.Context, blockRoot [32]byte) bool
}

FinalizationFetcher defines a common interface for methods in blockchain service which directly retrieve finalization and justification related data.

type ForkFetcher

type ForkFetcher interface {
	ForkChoicer() forkchoice.ForkChoicer
	CurrentFork() *ethpb.Fork
	GenesisFetcher
	TimeFetcher
}

ForkFetcher retrieves the current fork information of the Ethereum beacon chain.

type GenesisFetcher

type GenesisFetcher interface {
	GenesisValidatorsRoot() [32]byte
}

GenesisFetcher retrieves the Ethereum consensus data related to its genesis.

type HeadDomainFetcher

type HeadDomainFetcher interface {
	HeadSyncCommitteeDomain(ctx context.Context, slot primitives.Slot) ([]byte, error)
	HeadSyncSelectionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error)
	HeadSyncContributionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error)
}

HeadDomainFetcher is the interface that wraps the head sync domain related functions. The head sync committee domain functions return callers domain data with respect to slot and head state.

type HeadFetcher

type HeadFetcher interface {
	HeadSlot() primitives.Slot
	HeadRoot(ctx context.Context) ([]byte, error)
	HeadBlock(ctx context.Context) (interfaces.ReadOnlySignedBeaconBlock, error)
	HeadState(ctx context.Context) (state.BeaconState, error)
	HeadStateReadOnly(ctx context.Context) (state.ReadOnlyBeaconState, error)
	HeadValidatorsIndices(ctx context.Context, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error)
	HeadGenesisValidatorsRoot() [32]byte
	HeadETH1Data() *ethpb.Eth1Data
	HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool)
	HeadValidatorIndexToPublicKey(ctx context.Context, index primitives.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error)
	ChainHeads() ([][32]byte, []primitives.Slot)
	HeadSyncCommitteeFetcher
	HeadDomainFetcher
}

HeadFetcher defines a common interface for methods in blockchain service which directly retrieve head related data.

type HeadSyncCommitteeFetcher

type HeadSyncCommitteeFetcher interface {
	HeadSyncCommitteeIndices(ctx context.Context, index primitives.ValidatorIndex, slot primitives.Slot) ([]primitives.CommitteeIndex, error)
	HeadSyncCommitteePubKeys(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) ([][]byte, error)
}

HeadSyncCommitteeFetcher is the interface that wraps the head sync committee related functions. The head sync committee functions return callers sync committee indices and public keys with respect to current head state.

type HeadUpdater

type HeadUpdater interface {
	UpdateHead(context.Context) error
}

HeadUpdater defines a common interface for methods in blockchain service which allow to update the head info

type OptimisticModeFetcher

type OptimisticModeFetcher interface {
	IsOptimistic(ctx context.Context) (bool, error)
	IsOptimisticForRoot(ctx context.Context, root [32]byte) (bool, error)
}

OptimisticModeFetcher retrieves information about optimistic status of the node.

type Option

type Option func(s *Service) error

func WithAttestationPool

func WithAttestationPool(p attestations.Pool) Option

WithAttestationPool for attestation lifecycle after chain inclusion.

func WithAttestationService

func WithAttestationService(srv *attestations.Service) Option

WithAttestationService for dealing with attestation lifecycles.

func WithBLSToExecPool added in v3.2.0

func WithBLSToExecPool(p blstoexec.PoolManager) Option

WithBLSToExecPool to keep track of BLS to Execution address changes.

func WithChainStartFetcher

func WithChainStartFetcher(f execution.ChainStartFetcher) Option

WithChainStartFetcher to retrieve information about genesis.

func WithDatabase

func WithDatabase(beaconDB db.HeadAccessDatabase) Option

WithDatabase for head access.

func WithDepositCache

func WithDepositCache(c *depositcache.DepositCache) Option

WithDepositCache for deposit lifecycle after chain inclusion.

func WithExecutionEngineCaller

func WithExecutionEngineCaller(c execution.EngineCaller) Option

WithExecutionEngineCaller to call execution engine.

func WithExitPool

func WithExitPool(p voluntaryexits.PoolManager) Option

WithExitPool for exits lifecycle after chain inclusion.

func WithFinalizedStateAtStartUp

func WithFinalizedStateAtStartUp(st state.BeaconState) Option

WithFinalizedStateAtStartUp to store finalized state at start up.

func WithForkChoiceStore

func WithForkChoiceStore(f forkchoice.ForkChoicer) Option

WithForkChoiceStore to update an optimized fork-choice representation.

func WithMaxGoroutines

func WithMaxGoroutines(x int) Option

WithMaxGoroutines to control resource use of the blockchain service.

func WithP2PBroadcaster

func WithP2PBroadcaster(p p2p.Broadcaster) Option

WithP2PBroadcaster to broadcast messages after appropriate processing.

func WithProposerIdsCache

func WithProposerIdsCache(c *cache.ProposerPayloadIDsCache) Option

WithProposerIdsCache for proposer id cache.

func WithSlasherAttestationsFeed

func WithSlasherAttestationsFeed(f *event.Feed) Option

WithSlasherAttestationsFeed to forward attestations into slasher if enabled.

func WithSlashingPool

func WithSlashingPool(p slashings.PoolManager) Option

WithSlashingPool for slashings lifecycle after chain inclusion.

func WithStateGen

func WithStateGen(g *stategen.State) Option

WithStateGen for managing state regeneration and replay.

func WithStateNotifier

func WithStateNotifier(n statefeed.Notifier) Option

WithStateNotifier to notify an event feed of state processing.

func WithWeakSubjectivityCheckpoint

func WithWeakSubjectivityCheckpoint(c *ethpb.Checkpoint) Option

WithWeakSubjectivityCheckpoint for checkpoint sync.

type Service

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

Service represents a service that handles the internal logic of managing the full PoS beacon chain.

func NewService

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

NewService instantiates a new block service instance that will be registered into a running beacon node.

func (*Service) AttestationTargetState

func (s *Service) AttestationTargetState(ctx context.Context, target *ethpb.Checkpoint) (state.BeaconState, error)

AttestationTargetState returns the pre state of attestation.

func (*Service) BestJustifiedCheckpt

func (s *Service) BestJustifiedCheckpt() *ethpb.Checkpoint

BestJustifiedCheckpt returns the best justified checkpoint from store.

func (*Service) ChainHeads

func (s *Service) ChainHeads() ([][32]byte, []primitives.Slot)

ChainHeads returns all possible chain heads (leaves of fork choice tree). Heads roots and heads slots are returned.

func (*Service) CurrentFork

func (s *Service) CurrentFork() *ethpb.Fork

CurrentFork retrieves the latest fork information of the beacon chain.

func (*Service) CurrentJustifiedCheckpt

func (s *Service) CurrentJustifiedCheckpt() *ethpb.Checkpoint

CurrentJustifiedCheckpt returns the current justified checkpoint from chain store.

func (*Service) CurrentSlot

func (s *Service) CurrentSlot() primitives.Slot

CurrentSlot returns the current slot based on time.

func (*Service) FinalizedCheckpt

func (s *Service) FinalizedCheckpt() *ethpb.Checkpoint

FinalizedCheckpt returns the latest finalized checkpoint from chain store.

func (*Service) ForkChoiceStore

func (s *Service) ForkChoiceStore() forkchoice.ForkChoicer

ForkChoiceStore returns the fork choice store in the service.

func (*Service) ForkChoicer

func (s *Service) ForkChoicer() forkchoice.ForkChoicer

ForkChoicer returns the forkchoice interface.

func (*Service) GenesisTime

func (s *Service) GenesisTime() time.Time

GenesisTime returns the genesis time of beacon chain.

func (*Service) GenesisValidatorsRoot

func (s *Service) GenesisValidatorsRoot() [32]byte

GenesisValidatorsRoot returns the genesis validators root of the chain.

func (*Service) HasBlock

func (s *Service) HasBlock(ctx context.Context, root [32]byte) bool

HasBlock returns true if the block of the input root exists in initial sync blocks cache or DB.

func (*Service) HeadBlock

HeadBlock returns the head block of the chain. If the head is nil from service struct, it will attempt to get the head block from DB.

func (*Service) HeadETH1Data

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

HeadETH1Data returns the eth1data of the current head state.

func (*Service) HeadGenesisValidatorsRoot

func (s *Service) HeadGenesisValidatorsRoot() [32]byte

HeadGenesisValidatorsRoot returns genesis validators root of the head state.

func (*Service) HeadPublicKeyToValidatorIndex

func (s *Service) HeadPublicKeyToValidatorIndex(pubKey [fieldparams.BLSPubkeyLength]byte) (primitives.ValidatorIndex, bool)

HeadPublicKeyToValidatorIndex returns the validator index of the `pubkey` in current head state.

func (*Service) HeadRoot

func (s *Service) HeadRoot(ctx context.Context) ([]byte, error)

HeadRoot returns the root of the head of the chain.

func (*Service) HeadSlot

func (s *Service) HeadSlot() primitives.Slot

HeadSlot returns the slot of the head of the chain.

func (*Service) HeadState

func (s *Service) HeadState(ctx context.Context) (state.BeaconState, error)

HeadState returns the head state of the chain. If the head is nil from service struct, it will attempt to get the head state from DB.

func (*Service) HeadStateReadOnly added in v3.2.1

func (s *Service) HeadStateReadOnly(ctx context.Context) (state.ReadOnlyBeaconState, error)

HeadStateReadOnly returns the read only head state of the chain. If the head is nil from service struct, it will attempt to get the head state from DB. Any callers of this method MUST only use the state instance to read fields from the state. Any type assertions back to the concrete type and subsequent use of it could lead to corruption of the state.

func (*Service) HeadSyncCommitteeDomain

func (s *Service) HeadSyncCommitteeDomain(ctx context.Context, slot primitives.Slot) ([]byte, error)

HeadSyncCommitteeDomain returns the head sync committee domain using current head state advanced up to `slot`.

func (*Service) HeadSyncCommitteeIndices

func (s *Service) HeadSyncCommitteeIndices(ctx context.Context, index primitives.ValidatorIndex, slot primitives.Slot) ([]primitives.CommitteeIndex, error)

HeadSyncCommitteeIndices returns the sync committee index position using the head state. Input `slot` is taken in consideration where validator's duty for `slot - 1` is used for block inclusion in `slot`. That means when a validator is at epoch boundary across EPOCHS_PER_SYNC_COMMITTEE_PERIOD then the valiator will be considered using next period sync committee.

Spec definition: Being assigned to a sync committee for a given slot means that the validator produces and broadcasts signatures for slot - 1 for inclusion in slot. This means that when assigned to an epoch sync committee signatures must be produced and broadcast for slots on range [compute_start_slot_at_epoch(epoch) - 1, compute_start_slot_at_epoch(epoch) + SLOTS_PER_EPOCH - 1) rather than for the range [compute_start_slot_at_epoch(epoch), compute_start_slot_at_epoch(epoch) + SLOTS_PER_EPOCH)

func (*Service) HeadSyncCommitteePubKeys

func (s *Service) HeadSyncCommitteePubKeys(ctx context.Context, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) ([][]byte, error)

HeadSyncCommitteePubKeys returns the head sync committee public keys with respect to `slot` and subcommittee index `committeeIndex`. Head state advanced up to `slot` is used for calculation.

func (*Service) HeadSyncContributionProofDomain

func (s *Service) HeadSyncContributionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error)

HeadSyncContributionProofDomain returns the head sync committee domain using current head state advanced up to `slot`.

func (*Service) HeadSyncSelectionProofDomain

func (s *Service) HeadSyncSelectionProofDomain(ctx context.Context, slot primitives.Slot) ([]byte, error)

HeadSyncSelectionProofDomain returns the head sync committee domain using current head state advanced up to `slot`.

func (*Service) HeadValidatorIndexToPublicKey

func (s *Service) HeadValidatorIndexToPublicKey(_ context.Context, index primitives.ValidatorIndex) ([fieldparams.BLSPubkeyLength]byte, error)

HeadValidatorIndexToPublicKey returns the pubkey of the validator `index` in current head state.

func (*Service) HeadValidatorsIndices

func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error)

HeadValidatorsIndices returns a list of active validator indices from the head view of a given epoch.

func (*Service) InForkchoice added in v3.2.2

func (s *Service) InForkchoice(root [32]byte) bool

InForkchoice returns true if the given root is found in forkchoice This in particular means that the blockroot is a descendant of the finalized checkpoint

func (*Service) InsertSlashingsToForkChoiceStore

func (s *Service) InsertSlashingsToForkChoiceStore(ctx context.Context, slashings []*ethpb.AttesterSlashing)

InsertSlashingsToForkChoiceStore inserts attester slashing indices to fork choice store. To call this function, it's caller's responsibility to ensure the slashing object is valid. This function requires a write lock on forkchoice.

func (*Service) IsCanonical

func (s *Service) IsCanonical(ctx context.Context, blockRoot [32]byte) (bool, error)

IsCanonical returns true if the input block root is part of the canonical chain.

func (*Service) IsFinalized

func (s *Service) IsFinalized(ctx context.Context, root [32]byte) bool

IsFinalized returns true if the input root is finalized. It first checks latest finalized root then checks finalized root index in DB.

func (*Service) IsOptimistic

func (s *Service) IsOptimistic(ctx context.Context) (bool, error)

IsOptimistic returns true if the current head is optimistic.

func (*Service) IsOptimisticForRoot

func (s *Service) IsOptimisticForRoot(ctx context.Context, root [32]byte) (bool, error)

IsOptimisticForRoot takes the root as argument instead of the current head and returns true if it is optimistic.

func (*Service) OnAttestation

func (s *Service) OnAttestation(ctx context.Context, a *ethpb.Attestation) error

OnAttestation is called whenever an attestation is received, verifies the attestation is valid and saves it to the DB. As a stateless function, this does not hold nor delay attestation based on the spec descriptions. The delay is handled by the caller in `processAttestations`.

Spec pseudocode definition:

def on_attestation(store: Store, attestation: Attestation) -> None:
 """
 Run ``on_attestation`` upon receiving a new ``attestation`` from either within a block or directly on the wire.

 An ``attestation`` that is asserted as invalid may be valid at a later time,
 consider scheduling it for later processing in such case.
 """
 validate_on_attestation(store, attestation)
 store_target_checkpoint_state(store, attestation.data.target)

 # Get state at the `target` to fully validate attestation
 target_state = store.checkpoint_states[attestation.data.target]
 indexed_attestation = get_indexed_attestation(target_state, attestation)
 assert is_valid_indexed_attestation(target_state, indexed_attestation)

 # Update latest messages for attesting indices
 update_latest_messages(store, indexed_attestation.attesting_indices, attestation)

func (*Service) PreviousJustifiedCheckpt

func (s *Service) PreviousJustifiedCheckpt() *ethpb.Checkpoint

PreviousJustifiedCheckpt returns the current justified checkpoint from chain store.

func (*Service) ReceiveAttesterSlashing

func (s *Service) ReceiveAttesterSlashing(ctx context.Context, slashing *ethpb.AttesterSlashing)

ReceiveAttesterSlashing receives an attester slashing and inserts it to forkchoice

func (*Service) ReceiveBlock

func (s *Service) ReceiveBlock(ctx context.Context, block interfaces.ReadOnlySignedBeaconBlock, blockRoot [32]byte) error

ReceiveBlock is a function that defines the operations (minus pubsub) that are performed on a received block. The operations consist of:

  1. Validate block, apply state transition and update checkpoints
  2. Apply fork choice to the processed block
  3. Save latest head info

func (*Service) ReceiveBlockBatch

func (s *Service) ReceiveBlockBatch(ctx context.Context, blocks []interfaces.ReadOnlySignedBeaconBlock, blkRoots [][32]byte) error

ReceiveBlockBatch processes the whole block batch at once, assuming the block batch is linear ,transitioning the state, performing batch verification of all collected signatures and then performing the appropriate actions for a block post-transition.

func (*Service) SetGenesisTime

func (s *Service) SetGenesisTime(t time.Time)

SetGenesisTime sets the genesis time of beacon chain.

func (*Service) Start

func (s *Service) Start()

Start a blockchain service's main event loop.

func (*Service) StartFromSavedState

func (s *Service) StartFromSavedState(saved state.BeaconState) error

StartFromSavedState initializes the blockchain using a previously saved finalized checkpoint.

func (*Service) Status

func (s *Service) Status() error

Status always returns nil unless there is an error condition that causes this service to be unhealthy.

func (*Service) Stop

func (s *Service) Stop() error

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

func (*Service) UpdateAndSaveHeadWithBalances

func (s *Service) UpdateAndSaveHeadWithBalances(ctx context.Context) error

UpdateAndSaveHeadWithBalances updates the beacon state head after getting justified balanced from cache. This function is only used in spec-tests, it does save the head after updating it.

func (*Service) UpdateHead

func (s *Service) UpdateHead(ctx context.Context) error

UpdateHead updates the canonical head of the chain based on information from fork-choice attestations and votes. It requires no external inputs.

func (*Service) VerifyLmdFfgConsistency

func (s *Service) VerifyLmdFfgConsistency(ctx context.Context, a *ethpb.Attestation) error

VerifyLmdFfgConsistency verifies that attestation's LMD and FFG votes are consistency to each other.

type SlashingReceiver

type SlashingReceiver interface {
	ReceiveAttesterSlashing(ctx context.Context, slashings *ethpb.AttesterSlashing)
}

SlashingReceiver interface defines the methods of chain service for receiving validated slashing over the wire.

type TimeFetcher

type TimeFetcher interface {
	GenesisTime() time.Time
	CurrentSlot() primitives.Slot
}

TimeFetcher retrieves the Ethereum consensus data that's related to time.

type WeakSubjectivityVerifier

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

func NewWeakSubjectivityVerifier

func NewWeakSubjectivityVerifier(wsc *ethpb.Checkpoint, db weakSubjectivityDB) (*WeakSubjectivityVerifier, error)

NewWeakSubjectivityVerifier validates a checkpoint, and if valid, uses it to initialize a weak subjectivity verifier.

func (*WeakSubjectivityVerifier) VerifyWeakSubjectivity

func (v *WeakSubjectivityVerifier) VerifyWeakSubjectivity(ctx context.Context, finalizedEpoch primitives.Epoch) error

VerifyWeakSubjectivity verifies the weak subjectivity root in the service struct. Reference design: https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/weak-subjectivity.md#weak-subjectivity-sync-procedure

Directories

Path Synopsis
Package testing includes useful mocks for writing unit tests which depend on logic from the blockchain package.
Package testing includes useful mocks for writing unit tests which depend on logic from the blockchain package.

Jump to

Keyboard shortcuts

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