beacon

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2026 License: GPL-3.0 Imports: 28 Imported by: 0

Documentation

Overview

Package beacon provides a client for interacting with Ethereum consensus layer nodes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BidRejected added in v0.0.3

func BidRejected(err error) bool

BidRejected reports whether err is the beacon node answering a bid submission with a rejection, as opposed to the submission never reaching it. The distinction matters because a rejected bid WAS seen — retrying it unchanged only repeats the rejection — while a transport failure leaves the bid unsent and worth retrying.

Types

type AttestationEvent

type AttestationEvent struct {
	AggregationBits []byte
	Slot            phase0.Slot
	Index           uint64
	BeaconBlockRoot phase0.Root
	CommitteeBits   []byte // nil for pre-Electra
	ReceivedAt      time.Time
}

AttestationEvent is a reduced aggregate-format attestation (as found in block bodies): committee_bits + concatenated aggregation_bits on Electra+, Index = committee pre-Electra. Consumed by the head vote tracker's subnet coverage measurement via GetBlockAttestations.

func BlockAttestationEvents added in v0.0.3

func BlockAttestationEvents(block *eth2all.SignedBeaconBlock) []*AttestationEvent

BlockAttestationEvents reduces a block's attestations to the AttestationEvent shape consumed by the head vote tracker. Handles both the Electra+ format (committee_bits + concatenated aggregation_bits) and the pre-Electra format (data.index = committee).

type AttrParentKey added in v0.0.3

type AttrParentKey struct {
	Root phase0.Root
	Hash phase0.Hash32
}

AttrParentKey identifies a payload-attributes variant by the parent tuple it builds on: the beacon parent block root and the execution parent hash.

func AttrParentKeyOf added in v0.0.3

func AttrParentKeyOf(event *PayloadAttributesEvent) AttrParentKey

AttrParentKeyOf returns the parent tuple of a payload-attributes event.

type BidEvent

type BidEvent struct {
	Slot               phase0.Slot
	ParentBlockHash    phase0.Hash32
	ParentBlockRoot    phase0.Root
	BlockHash          phase0.Hash32
	FeeRecipient       [20]byte
	GasLimit           uint64
	BuilderIndex       uint64
	Value              uint64
	ExecutionPayment   uint64
	BlobKZGCommitments [][]byte
	Signature          phase0.BLSSignature
	ReceivedAt         time.Time
}

BidEvent represents an execution payload bid event.

type BlockInfo

type BlockInfo struct {
	Slot               phase0.Slot
	Root               phase0.Root
	ExecutionBlockHash phase0.Hash32
	// Execution block hash safe to use as an FCU safe/finalized hash; always
	// present on the EL. See agnosticFinalitySafeExecutionBlockHash.
	FinalitySafeExecutionBlockHash phase0.Hash32
	ParentRoot                     phase0.Root
	StateRoot                      phase0.Root
	// Gas limit the block committed to: the embedded payload's gas limit
	// pre-Gloas, the bid's gas limit from Gloas on (the envelope check
	// enforces payload.gas_limit == bid.gas_limit, so the values agree
	// whenever the payload is revealed).
	GasLimit uint64
	// Execution block number of the committed payload. Only known pre-Gloas
	// (the payload is embedded in the block); zero from Gloas on, where the
	// number requires the revealed envelope.
	ExecutionBlockNumber uint64
	// BuilderIndex is the builder the block's execution payload bid came from
	// (Gloas+). It is the ground truth for which of our keys won a slot — the
	// payload alone cannot say, since several of our keys may have bid the very
	// same payload. BuilderIndexKnown is false pre-Gloas, where the payload is
	// embedded in the block and no builder is named.
	BuilderIndex      uint64
	BuilderIndexKnown bool
}

BlockInfo contains execution-relevant information from a beacon block.

type ChainReorgEvent added in v0.0.3

type ChainReorgEvent struct {
	Slot                phase0.Slot
	Depth               uint64
	OldHeadBlock        phase0.Root
	NewHeadBlock        phase0.Root
	OldHeadState        phase0.Root
	NewHeadState        phase0.Root
	Epoch               phase0.Epoch
	ExecutionOptimistic bool
}

ChainReorgEvent represents a chain_reorg event from the beacon node. Emitted when fork choice switches the head to a block that is not a descendant of the previous head. Not all clients emit this reliably, so consumers must treat it as a hint and derive reorgs from head-event parent-root discontinuities as the primary mechanism.

type ChainStatusResult

type ChainStatusResult struct {
	FinalizedRoot  phase0.Root
	FinalizedEpoch uint64
	HeadRoot       phase0.Root
	HeadSlot       uint64
}

ChainStatusResult holds the head and finality data needed to populate a libp2p StatusV2 message. Fork digest computation is intentionally excluded here — callers that have access to the chain spec (BPO schedule) are responsible for computing it and applying all cumulative BPO XORs.

type Client

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

Client wraps the consensus layer client for beacon node interactions.

func NewClient

func NewClient(ctx context.Context, baseURL string, log logrus.FieldLogger) (*Client, error)

NewClient creates a new CL client connected to the specified beacon node. The client allows delayed start so it can be created even when the beacon node is not yet reachable; callers should retry API calls until the node is ready.

func (*Client) Close

func (c *Client) Close()

Close closes the client and stops the event stream.

func (*Client) Events

func (c *Client) Events() *EventStream

Events returns the event stream for subscribing to beacon events.

func (*Client) GetBaseURL

func (c *Client) GetBaseURL() string

GetBaseURL returns the base URL of the beacon node.

func (*Client) GetBlockInfo

func (c *Client) GetBlockInfo(ctx context.Context, blockID string) (*BlockInfo, error)

GetBlockInfo fetches beacon block info at the given block ID.

It uses the fork-agnostic block type and computes the block root via dynssz, which honours the network's spec (set via InitGlobalSSZSpecs). The versioned type's Root() routes through fastssz code generated for mainnet preset sizes, so it returns wrong roots on non-mainnet presets (e.g. minimal).

func (*Client) GetChainStatus

func (c *Client) GetChainStatus(ctx context.Context) (*ChainStatusResult, error)

GetChainStatus fetches the current chain head and finality data from the beacon node. It does NOT compute the fork digest — use GetCurrentForkVersion alongside the chain spec's BlobSchedule to compute the correct BPO-modified fork digest for StatusV2 messages.

func (*Client) GetCurrentForkVersion

func (c *Client) GetCurrentForkVersion(ctx context.Context) (phase0.Version, error)

GetCurrentForkVersion fetches the current fork version from the beacon node's head state. This reflects the currently active fork (e.g. Fulu or Gloas), not a future scheduled fork.

func (*Client) GetExecutionPayloadEnvelope

func (c *Client) GetExecutionPayloadEnvelope(
	ctx context.Context,
	blockID string,
) (*eth2all.SignedExecutionPayloadEnvelope, error)

GetExecutionPayloadEnvelope fetches the signed execution payload envelope for a block as the full fork-agnostic object (consumers reduce it to whatever shape they need). The blockID can be a block root (hex), slot number, or "head"/"finalized"/"genesis".

func (*Client) GetFinalityInfo

func (c *Client) GetFinalityInfo(ctx context.Context) (*FinalityInfo, error)

GetFinalityInfo fetches finality checkpoints and returns execution block hashes.

func (*Client) GetForkVersion

func (c *Client) GetForkVersion(ctx context.Context) (phase0.Version, error)

GetForkVersion returns the current fork version.

func (*Client) GetGenesis

func (c *Client) GetGenesis(ctx context.Context) (*Genesis, error)

GetGenesis fetches genesis information from the beacon node via direct HTTP. This bypasses go-eth2-client's active check so it works before the node is fully ready.

func (*Client) GetNodeIdentity

func (c *Client) GetNodeIdentity(ctx context.Context) (*NodeIdentity, error)

GetNodeIdentity fetches the beacon node's P2P identity via /eth/v1/node/identity.

func (*Client) GetRawClient

func (c *Client) GetRawClient() eth2client.Service

GetRawClient returns the underlying eth2client.Service for direct API access.

func (*Client) GetRawSpecData

func (c *Client) GetRawSpecData(ctx context.Context) (map[string]string, map[string]json.RawMessage, error)

GetRawSpecData fetches /eth/v1/config/spec via direct HTTP, bypassing go-eth2-client. Returns both a string map (for simple values) and the raw JSON map (for complex values like BLOB_SCHEDULE).

func (*Client) GetSignedBlock added in v0.0.3

func (c *Client) GetSignedBlock(ctx context.Context, blockID string) (*eth2all.SignedBeaconBlock, error)

GetSignedBlock fetches a beacon block as the fork-agnostic signed block.

func (*Client) GetValidatorIndexToPubkeyMap

func (c *Client) GetValidatorIndexToPubkeyMap(ctx context.Context, stateID string) (map[phase0.ValidatorIndex]phase0.BLSPubKey, error)

GetValidatorIndexToPubkeyMap fetches the beacon state once and returns a map of validator index to pubkey. Used to refresh an index→pubkey cache once per epoch instead of querying per payload build.

func (*Client) InitGlobalSSZSpecs

func (c *Client) InitGlobalSSZSpecs(ctx context.Context) error

InitGlobalSSZSpecs configures the global dynssz instance with this network's spec values. The go-eth2-client SSZ codecs (e.g. block.Root()) route through dynssz.GetGlobalDynSsz(), which otherwise defaults to mainnet preset sizes — producing wrong hash-tree-roots on minimal-preset networks. We reuse the spec map go-eth2-client already parses (SpecProvider.Spec), which is directly compatible with dynssz.SetGlobalSpecs.

func (*Client) SubmitExecutionPayloadBid

func (c *Client) SubmitExecutionPayloadBid(ctx context.Context, bid *eth2all.SignedExecutionPayloadBid) error

SubmitExecutionPayloadBid submits a signed execution payload bid to the beacon node. The consensus version header and body encoding (SSZ or JSON per the client's content negotiation) are derived from the bid's Version by go-eth2-client.

func (*Client) SubmitExecutionPayloadEnvelope

func (c *Client) SubmitExecutionPayloadEnvelope(
	ctx context.Context,
	envelope *eth2all.SignedExecutionPayloadEnvelope,
	blobs [][]byte,
	kzgProofs [][]byte,
	broadcastValidation string,
) error

SubmitExecutionPayloadEnvelope submits a signed execution payload envelope using the stateless flow (SignedExecutionPayloadEnvelopeContents body, Eth-Blob-Data-Included true). The stateful flow only works when the beacon node cached the blob data from its own block production (produceBlockV4); buildoor builds payloads externally, so the beacon node never has them cached and the stateless form is the only valid one.

The consensus version header and body encoding (SSZ or JSON per the client's content negotiation) are derived from the envelope's Version by go-eth2-client.

func (*Client) SubmitProposal

func (c *Client) SubmitProposal(ctx context.Context, opts *api.SubmitProposalOpts) error

SubmitProposal submits a full signed proposal (e.g. SignedBlockContents) to the beacon node. Used by the builder API after unblinding a blinded block.

func (*Client) SubmitVoluntaryExit

func (c *Client) SubmitVoluntaryExit(ctx context.Context, exit *phase0.SignedVoluntaryExit) error

SubmitVoluntaryExit submits a signed voluntary exit to the beacon node.

type EventStream

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

EventStream manages SSE connections to the beacon node event stream.

func NewEventStream

func NewEventStream(client *Client) *EventStream

NewEventStream creates a new event stream for the given client.

func (*EventStream) CleanupPayloadAttributesCache

func (e *EventStream) CleanupPayloadAttributesCache(beforeSlot phase0.Slot)

CleanupPayloadAttributesCache removes cached payload_attributes entries for slots older than beforeSlot.

func (*EventStream) GetLatestPayloadAttributes

func (e *EventStream) GetLatestPayloadAttributes(slot phase0.Slot) *PayloadAttributesEvent

GetLatestPayloadAttributes returns the newest cached payload_attributes event for the given slot (across all parent variants), or nil if none has been received.

func (*EventStream) GetPayloadAttributesVariant added in v0.0.3

func (e *EventStream) GetPayloadAttributesVariant(
	slot phase0.Slot, key AttrParentKey,
) *PayloadAttributesEvent

GetPayloadAttributesVariant returns the cached payload_attributes event for the given slot and parent tuple, or nil.

func (*EventStream) GetPayloadAttributesVariants added in v0.0.3

func (e *EventStream) GetPayloadAttributesVariants(slot phase0.Slot) []*PayloadAttributesEvent

GetPayloadAttributesVariants returns every cached payload_attributes variant for the given slot (one per parent tuple, arbitrary order).

func (*EventStream) InjectPayloadAttributes added in v0.0.3

func (e *EventStream) InjectPayloadAttributes(event *PayloadAttributesEvent) bool

InjectPayloadAttributes caches and dispatches a locally synthesized payload_attributes event exactly like one received from the beacon node (used by the missing-block fallback and candidate synthesis). A node-received event always wins: injection is dropped when the slot already has an event for the same parent tuple, and an injected event only becomes the slot's newest when the slot had none at all. Returns whether the event was injected.

func (*EventStream) Start

func (e *EventStream) Start(ctx context.Context) error

Start begins listening to beacon node events.

func (*EventStream) Stop

func (e *EventStream) Stop()

Stop stops the event stream.

func (*EventStream) SubscribeBids

func (e *EventStream) SubscribeBids() *utils.Subscription[*BidEvent]

SubscribeBids returns a subscription for bid events.

func (*EventStream) SubscribeChainReorgs added in v0.0.3

func (e *EventStream) SubscribeChainReorgs() *utils.Subscription[*ChainReorgEvent]

SubscribeChainReorgs returns a subscription for chain_reorg events.

func (*EventStream) SubscribeHead

func (e *EventStream) SubscribeHead() *utils.Subscription[*HeadEvent]

SubscribeHead returns a subscription for head events.

func (*EventStream) SubscribePayloadAttributes

func (e *EventStream) SubscribePayloadAttributes() *utils.Subscription[*PayloadAttributesEvent]

SubscribePayloadAttributes returns a subscription for payload attributes events.

func (*EventStream) SubscribePayloadAvailable

func (e *EventStream) SubscribePayloadAvailable() *utils.Subscription[*PayloadAvailableEvent]

SubscribePayloadAvailable returns a subscription for execution_payload_available events.

func (*EventStream) SubscribeProposerPreferences

func (e *EventStream) SubscribeProposerPreferences() *utils.Subscription[*gloas.SignedProposerPreferences]

SubscribeProposerPreferences returns a subscription for proposer_preferences events.

func (*EventStream) SubscribeSingleAttestations added in v0.0.3

func (e *EventStream) SubscribeSingleAttestations() *utils.Subscription[*SingleAttestationEvent]

SubscribeSingleAttestations returns a subscription for single_attestation events. The buffer is sized for the raw-vote firehose (~active_validators/32 events per slot with a subscribe-all-subnets beacon node); consumers must do O(1) work per event.

type FinalityInfo

type FinalityInfo struct {
	HeadExecutionBlockHash      phase0.Hash32
	SafeExecutionBlockHash      phase0.Hash32
	FinalizedExecutionBlockHash phase0.Hash32
}

FinalityInfo contains finality checkpoint execution block hashes.

type Genesis

type Genesis struct {
	GenesisTime           time.Time
	GenesisValidatorsRoot phase0.Root
	GenesisForkVersion    phase0.Version
}

Genesis holds genesis information.

type HeadEvent

type HeadEvent struct {
	Slot                      phase0.Slot
	Block                     phase0.Root
	State                     phase0.Root
	EpochTransition           bool
	ExecutionOptimistic       bool
	PreviousDutyDependentRoot phase0.Root
	CurrentDutyDependentRoot  phase0.Root
}

HeadEvent represents a head event from the beacon node.

type NodeIdentity

type NodeIdentity struct {
	PeerID       string   `json:"peer_id"`
	P2PAddresses []string `json:"p2p_addresses"`
}

NodeIdentity holds the beacon node's P2P identity information.

type PayloadAttributesEvent

type PayloadAttributesEvent struct {
	Version                   string
	ProposalSlot              phase0.Slot
	ProposerIndex             phase0.ValidatorIndex
	ParentBlockRoot           phase0.Root
	ParentBlockNumber         uint64
	ParentBlockHash           phase0.Hash32
	Timestamp                 uint64
	PrevRandao                phase0.Root
	SuggestedFeeRecipient     common.Address
	Withdrawals               []*capella.Withdrawal
	ParentBeaconBlockRoot     phase0.Root
	TargetGasLimit            uint64
	InclusionListTransactions [][]byte
}

PayloadAttributesEvent represents a payload_attributes event from the beacon node. This is emitted when a validator is scheduled to propose and contains all parameters needed for building an execution payload.

type PayloadAvailableEvent

type PayloadAvailableEvent struct {
	Slot       phase0.Slot
	BlockRoot  phase0.Root // Beacon block root this payload belongs to
	ReceivedAt time.Time
}

PayloadAvailableEvent represents an execution_payload_available event (Gloas). This is emitted when the node has verified that the execution payload and blobs for a block are available and ready for payload attestation.

type SingleAttestationEvent added in v0.0.3

type SingleAttestationEvent struct {
	Slot            phase0.Slot
	CommitteeIndex  phase0.CommitteeIndex
	AttesterIndex   phase0.ValidatorIndex
	BeaconBlockRoot phase0.Root
	ReceivedAt      time.Time
}

SingleAttestationEvent represents a single_attestation event (Electra+): one raw, unaggregated attestation the beacon node accepted from an attestation subnet or the API. AttesterIndex is the global validator index.

Jump to

Keyboard shortcuts

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