ethereum

package
v0.0.0-...-d6e472d Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2025 License: MIT Imports: 14 Imported by: 2

README

Ethereum Pkg

Utilities and implementations for interacting with Ethereum networks.

Beacon Node

This package provides a Go client for connecting to and interacting with Ethereum beacon nodes. It includes support for metadata services, network detection, and health monitoring.

Installation
go get github.com/ethpandaops/ethcore/pkg/ethereum
Usage
Single Node Example
package main

import (
    "context"
    "log"
    "time"

    "github.com/ethpandaops/beacon/pkg/beacon"
    "github.com/ethpandaops/ethcore/pkg/ethereum"
    "github.com/sirupsen/logrus"
)

func main() {
    ctx := context.Background()
    logger := logrus.New()

    // Configure the beacon node
    config := &ethereum.Config{
        BeaconNodeAddress: "http://localhost:5052",
        BeaconNodeHeaders: map[string]string{
            "Authorization": "Bearer your-token",
        },
    }

    // Set up beacon options
    opts := beacon.DefaultOptions()
    opts.HealthCheck.Interval.Duration = time.Second * 3
    opts.HealthCheck.SuccessfulResponses = 1

    // Create the beacon node
    beaconNode, err := ethereum.NewBeaconNode(
        logger,
        "my-app",
        config,
        *opts,
    )
    if err != nil {
        log.Fatal("Failed to create beacon node:", err)
    }

    // Register a callback to be executed when the node is ready
    beaconNode.OnReady(ctx, func(ctx context.Context) error {
        logger.Info("Beacon node is ready! Starting application logic...")

        // Your application logic here
        metadata := beaconNode.Metadata()
        network := metadata.Network
        logger.WithFields(logrus.Fields{
            "network": network.Name,
            "network_id": network.ID,
        }).Info("Connected to network")

        return nil
    })

    // Start the beacon node
    if err := beaconNode.Start(ctx); err != nil {
        log.Fatal("Failed to start beacon node:", err)
    }

    // Keep the application running
    select {}
}
Multiple Nodes Example
package main

import (
    "context"
    "fmt"
    "log"
    "sync"
    "time"

    "github.com/ethpandaops/beacon/pkg/beacon"
    "github.com/ethpandaops/ethcore/pkg/ethereum"
    "github.com/sirupsen/logrus"
)

type BeaconNodeManager struct {
    nodes []*ethereum.BeaconNode
    mu    sync.Mutex
    wg    sync.WaitGroup
}

func main() {
    ctx := context.Background()
    logger := logrus.New()

    // Define multiple beacon node endpoints
    endpoints := []string{
        "http://beacon1:5052",
        "http://beacon2:5052",
        "http://beacon3:5052",
    }

    manager := &BeaconNodeManager{
        nodes: make([]*ethereum.BeaconNode, 0, len(endpoints)),
    }

    // Create and start all beacon nodes
    for i, endpoint := range endpoints {
        nodeLogger := logger.WithField("node", fmt.Sprintf("beacon-%d", i))

        config := &ethereum.Config{
            BeaconNodeAddress: endpoint,
        }

        opts := beacon.DefaultOptions()
        opts.HealthCheck.Interval.Duration = time.Second * 3

        // Create the beacon node
        node, err := ethereum.NewBeaconNode(
            nodeLogger,
            fmt.Sprintf("node-%d", i),
            config,
            *opts,
        )
        if err != nil {
            log.Printf("Failed to create beacon node %d: %v", i, err)
            continue
        }

        // Track this node
        manager.mu.Lock()
        manager.nodes = append(manager.nodes, node)
        manager.mu.Unlock()

        // Add to wait group for this node
        manager.wg.Add(1)

        // Register callback for when node is ready
        nodeIndex := i
        node.OnReady(ctx, func(ctx context.Context) error {
            defer manager.wg.Done()

            nodeLogger.Info("Node is ready")

            // Log network information
            metadata := node.Metadata()
            nodeLogger.WithFields(logrus.Fields{
                "network": metadata.Network.Name,
                "node_index": nodeIndex,
            }).Info("Node connected to network")

            return nil
        })

        // Start the node in a goroutine
        go func(n *ethereum.BeaconNode, idx int) {
            if err := n.Start(ctx); err != nil {
                nodeLogger.WithError(err).Error("Failed to start beacon node")
                manager.wg.Done() // Ensure we decrease the counter even on error
            }
        }(node, i)
    }

    // Wait for all nodes to be ready
    logger.Info("Waiting for all nodes to be ready...")
    manager.wg.Wait()
    logger.Info("All nodes are ready!")

    // Now all nodes are ready, you can use them
    manager.mu.Lock()
    for i, node := range manager.nodes {
        if node.IsHealthy() {
            logger.WithField("node", i).Info("Node is healthy")
        }
    }
    manager.mu.Unlock()

    // Keep the application running
    select {}
}

Documentation

Overview

Package ethereum provides Ethereum beacon node functionality

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ComputeForkDigest

func ComputeForkDigest(genesisValidatorsRoot phase0.Root, forkVersion phase0.Version, blobParams *BlobScheduleEntry) phase0.ForkDigest

Types

type BeaconNode

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

BeaconNode represents a connection to an Ethereum beacon node and manages any associated services (eg: metadata, etc).

func NewBeaconNode

func NewBeaconNode(
	log logrus.FieldLogger,
	namespace string,
	config *Config,
	opts *Options,
) (*BeaconNode, error)

NewBeaconNode creates a new beacon node instance with the given configuration. It initializes any services and configures the beacon subscriptions.

func (*BeaconNode) ForkDigest

func (b *BeaconNode) ForkDigest() (phase0.ForkDigest, error)

func (*BeaconNode) GetCurrentBlobSchedule

func (b *BeaconNode) GetCurrentBlobSchedule() (*BlobScheduleEntry, error)

GetCurrentBlobSchedule returns the current blob schedule for the current epoch.

func (*BeaconNode) GetEpoch

func (b *BeaconNode) GetEpoch(epoch uint64) ethwallclock.Epoch

GetEpoch returns the wallclock epoch for a given slot number.

func (*BeaconNode) GetEpochFromSlot

func (b *BeaconNode) GetEpochFromSlot(slot uint64) ethwallclock.Epoch

GetEpochFromSlot returns the wallclock epoch for a given slot.

func (*BeaconNode) GetSlot

func (b *BeaconNode) GetSlot(slot uint64) ethwallclock.Slot

GetSlot returns the wallclock slot for a given slot number.

func (*BeaconNode) GetWallclock

func (b *BeaconNode) GetWallclock() *ethwallclock.EthereumBeaconChain

GetWallclock returns the wallclock for the beacon chain.

func (*BeaconNode) IsHealthy

func (b *BeaconNode) IsHealthy() bool

IsHealthy returns whether the node is healthy.

func (*BeaconNode) Metadata

func (b *BeaconNode) Metadata() *services.MetadataService

Metadata returns the metadata service instance.

func (*BeaconNode) Node

func (b *BeaconNode) Node() beacon.Node

Node returns the underlying beacon node instance.

func (*BeaconNode) OnReady

func (b *BeaconNode) OnReady(callback func(ctx context.Context) error)

OnReady registers a callback to be executed when the beacon node is ready.

func (*BeaconNode) Start

func (b *BeaconNode) Start(ctx context.Context) error

Start starts the beacon node and waits for it to be ready.

func (*BeaconNode) Stop

func (b *BeaconNode) Stop(ctx context.Context) error

Stop gracefully shuts down the beacon node and its services.

func (*BeaconNode) Synced

func (b *BeaconNode) Synced(ctx context.Context) error

Synced checks if the beacon node is synced and ready It verifies sync state, wallclock, and service readiness.

type BlobScheduleEntry

type BlobScheduleEntry struct {
	Epoch            uint64
	MaxBlobsPerBlock uint64
}

BlobScheduleEntry represents a blob parameter configuration for a specific epoch.

type Config

type Config struct {
	// The address of the Beacon node to connect to
	BeaconNodeAddress string `yaml:"beaconNodeAddress"`
	// BeaconNodeHeaders is a map of headers to send to the beacon node.
	BeaconNodeHeaders map[string]string `yaml:"beaconNodeHeaders"`
	// NetworkOverride is an optional network name to use instead of what's reported by the beacon node
	NetworkOverride string `yaml:"networkOverride,omitempty"`
}

Config defines the configuration for the Ethereum beacon node.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the configuration for the beacon node.

type Options

type Options struct {
	*beacon.Options

	FetchBeaconCommittees bool
	FetchProposerDuties   bool
}

Options configures beacon node behavior.

Directories

Path Synopsis
node
enr
Package enr provides utilities for parsing and extracting data from Ethereum Node Records (ENR).
Package enr provides utilities for parsing and extracting data from Ethereum Node Records (ENR).

Jump to

Keyboard shortcuts

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