ethadapter

package
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2025 License: AGPL-3.0 Imports: 40 Imported by: 0

README

This package contains the Ethereum integration logic.

  1. The RPC connection to a geth node
  2. The ABIs for the smart contracts which the platform needs to know about.

Documentation

Index

Constants

View Source
const (
	RespondSecretMethod    = "respondNetworkSecret"
	RequestSecretMethod    = "requestNetworkSecret"
	InitializeSecretMethod = "initializeNetworkSecret" //#nosec

	AddRollupMethod = "addRollup"

	AddAdditionalAddressMethod = "addAdditionalAddress"
	MethodBytesLen             = 4
)
View Source
const (
	MaxBlobBytes = 32 * 4096
)

Variables

View Source
var (
	MessageBusABI, _               = abi.JSON(strings.NewReader(MessageBus.MessageBusMetaData.ABI))
	NetworkConfigABI, _            = abi.JSON(strings.NewReader(NetworkConfig.NetworkConfigMetaData.ABI))
	DataAvailabilityRegistryABI, _ = abi.JSON(strings.NewReader(DataAvailabilityRegistry.DataAvailabilityRegistryMetaData.ABI))
	EnclaveRegistryABI, _          = abi.JSON(strings.NewReader(NetworkEnclaveRegistry.NetworkEnclaveRegistryMetaData.ABI))

	CrossChainEventName                = "LogMessagePublished"
	ValueTransferEventName             = "ValueTransfer"
	NetworkSecretInitializedEventName  = "NetworkSecretInitialized"
	NetworkSecretRequestedEventName    = "NetworkSecretRequested"
	NetworkSecretRespondedEventName    = "NetworkSecretResponded"
	SequencerEnclaveGrantedEventName   = "SequencerEnclaveGranted"
	SequencerEnclaveRevokedEventName   = "SequencerEnclaveRevoked"
	RollupAddedEventName               = "RollupAdded"
	NetworkContractAddressAddedName    = "NetworkContractAddressAdded"
	AdditionalContractAddressAddedName = "AdditionalContractAddressAdded"

	CrossChainEventID                = MessageBusABI.Events[CrossChainEventName].ID
	ValueTransferEventID             = MessageBusABI.Events[ValueTransferEventName].ID
	NetworkSecretInitializedEventID  = EnclaveRegistryABI.Events[NetworkSecretInitializedEventName].ID
	SequencerEnclaveGrantedEventID   = EnclaveRegistryABI.Events[SequencerEnclaveGrantedEventName].ID
	SequencerEnclaveRevokedEventID   = EnclaveRegistryABI.Events[SequencerEnclaveRevokedEventName].ID
	NetworkSecretRequestedID         = EnclaveRegistryABI.Events[NetworkSecretRequestedEventName].ID
	NetworkSecretRespondedID         = EnclaveRegistryABI.Events[NetworkSecretRespondedEventName].ID
	RollupAddedID                    = DataAvailabilityRegistryABI.Events[RollupAddedEventName].ID
	NetworkContractAddressAddedID    = NetworkConfigABI.Events[NetworkContractAddressAddedName].ID
	AdditionalContractAddressAddedID = NetworkConfigABI.Events[AdditionalContractAddressAddedName].ID
)

Functions

func Base64DecodeFromString added in v1.1.0

func Base64DecodeFromString(in string) ([]byte, error)

Base64DecodeFromString decodes a string to a byte array

func Base64EncodeToString added in v1.1.0

func Base64EncodeToString(bytes []byte) string

Base64EncodeToString encodes a byte array to a string

func BlobsFromSidecars added in v0.28.0

func BlobsFromSidecars(blobSidecars []*BlobSidecar, hashes []gethcommon.Hash) ([]*kzg4844.Blob, error)

func BlocksBetween added in v1.1.0

func BlocksBetween(e EthClient, startBlock *types.Header, endBlock *types.Header) ([]*types.Header, error)

BlocksBetween returns a slice of Ethereum block headers between the startBlock and endBlock, inclusive, in order.

func DecodeBlobs added in v0.28.0

func DecodeBlobs(blobs []*kzg4844.Blob) ([]byte, error)

DecodeBlobs decodes blobs into the data encoded in them accounting for excess blob bits

func EncodeBlobs added in v0.28.0

func EncodeBlobs(data []byte) ([]*kzg4844.Blob, error)

EncodeBlobs converts bytes into blobs used for KZG commitment EIP-4844 transactions on Ethereum.

func KZGToVersionedHash added in v0.28.0

func KZGToVersionedHash(commitment kzg4844.Commitment) (out common.Hash)

KZGToVersionedHash computes the versioned hash of a blob-commitment, as used in a blob-tx.

func MakeSidecar added in v0.28.0

func MakeSidecar(blobs []*kzg4844.Blob, hasher BlobHasher) (*types.BlobTxSidecar, []gethcommon.Hash, error)

MakeSidecar builds & returns the BlobTxSidecar and corresponding blob hashes from the raw blob data.

func ReconstructRollup added in v0.28.0

func ReconstructRollup(blobs []*kzg4844.Blob) (*common.ExtRollup, error)

ReconstructRollup decodes and returns the ExtRollup in the blob

func SetTxGasPrice added in v1.0.0

func SetTxGasPrice(ctx context.Context, ethClient EthClient, txData types.TxData, from gethcommon.Address, nonce uint64, retryNumber int, l1ChainCfg *params.ChainConfig, logger gethlog.Logger) (types.TxData, error)

SetTxGasPrice takes a txData type and overrides the From, Gas and Gas Price field with current values it bumps the price by a multiplier for retries. retryNumber is zero on first attempt (no multiplier on price)

func VerifyBlobProof added in v0.28.0

func VerifyBlobProof(blob *kzg4844.Blob, commitment kzg4844.Commitment, proof kzg4844.Proof) error

VerifyBlobProof verifies that the given blob and proof corresponds to the given commitment

Types

type APIBlobData added in v0.28.0

type APIBlobData struct {
	VersionedHash string `json:"versionedHash"`
	Commitment    string `json:"commitment"`
	Proof         string `json:"proof"`
	Data          string `json:"data"`
}

type APIConfigResponse added in v0.28.0

type APIConfigResponse struct {
	Data ReducedConfigData `json:"data"`
}

type APIGenesisResponse added in v0.28.0

type APIGenesisResponse struct {
	Data ReducedGenesisData `json:"data"`
}

type APIGetBlobSidecarsResponse added in v0.28.0

type APIGetBlobSidecarsResponse struct {
	Data []*BlobSidecar `json:"data"`
}

type APIVersionResponse added in v0.28.0

type APIVersionResponse struct {
	Data VersionInformation `json:"data"`
}

type ArchivalBlobResponse added in v0.28.0

type ArchivalBlobResponse struct {
	Blob APIBlobData `json:"blob"`
}

ArchivalBlobResponse nested struct is needed to match the structure of the API response

type ArchivalHTTPClient added in v0.28.0

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

func NewArchivalHTTPClient added in v0.28.0

func NewArchivalHTTPClient(client *http.Client, baseURL string) *ArchivalHTTPClient

func (*ArchivalHTTPClient) BeaconBlobSidecars added in v0.28.0

func (ac *ArchivalHTTPClient) BeaconBlobSidecars(ctx context.Context, _ uint64, hashes []gethcommon.Hash) (APIGetBlobSidecarsResponse, error)

type BaseHTTPClient added in v0.28.0

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

BaseHTTPClient provides common HTTP functionality for different clients

func NewBaseHTTPClient added in v0.28.0

func NewBaseHTTPClient(client *http.Client, baseURL string) *BaseHTTPClient

func (*BaseHTTPClient) Request added in v0.28.0

func (chc *BaseHTTPClient) Request(ctx context.Context, dest any, reqPath string, reqQuery url.Values) error

type BeaconClient added in v0.28.0

type BeaconClient interface {
	NodeVersion(ctx context.Context) (string, error)
	ConfigSpec(ctx context.Context) (APIConfigResponse, error)
	BeaconGenesis(ctx context.Context) (APIGenesisResponse, error)
	BeaconBlobSidecars(ctx context.Context, slot uint64, hashes []gethcommon.Hash) (APIGetBlobSidecarsResponse, error)
}

BeaconClient is a thin wrapper over the Beacon APIs.

type BeaconHTTPClient added in v0.28.0

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

BeaconHTTPClient implements BeaconClient. It provides golang types over the basic Beacon API.

func NewBeaconHTTPClient added in v0.28.0

func NewBeaconHTTPClient(client *http.Client, baseURL string) *BeaconHTTPClient

func (*BeaconHTTPClient) BeaconBlobSidecars added in v0.28.0

func (bc *BeaconHTTPClient) BeaconBlobSidecars(ctx context.Context, slot uint64, _ []gethcommon.Hash) (APIGetBlobSidecarsResponse, error)

func (*BeaconHTTPClient) BeaconGenesis added in v0.28.0

func (bc *BeaconHTTPClient) BeaconGenesis(ctx context.Context) (APIGenesisResponse, error)

func (*BeaconHTTPClient) ConfigSpec added in v0.28.0

func (bc *BeaconHTTPClient) ConfigSpec(ctx context.Context) (APIConfigResponse, error)

func (*BeaconHTTPClient) NodeVersion added in v0.28.0

func (bc *BeaconHTTPClient) NodeVersion(ctx context.Context) (string, error)

type BlobHasher added in v1.0.0

type BlobHasher interface {
	BlobHash(blob *kzg4844.Blob) (gethcommon.Hash, kzg4844.Commitment, kzg4844.Proof, error)
}

type BlobRetrievalService added in v0.28.0

type BlobRetrievalService interface {
	BeaconBlobSidecars(ctx context.Context, slot uint64, hashes []gethcommon.Hash) (APIGetBlobSidecarsResponse, error)
}

BlobRetrievalService is a wrapper for clients that can fetch blobs from different sources.

type BlobSidecar added in v0.28.0

type BlobSidecar struct {
	// Blob is the actual blob data, a large byte array (up to 128 KB) that contains the off-chain data
	Blob kzg4844.Blob `json:"blob"`

	// Index is the position of this blob within the transaction's blob array
	// It's represented as a string to accommodate uint64 values in JSON
	Index Uint64String `json:"index"`

	// KZGCommitment is a cryptographic commitment to the blob content
	// This is what the EVM sees and uses to verify blob availability without accessing the full blob data
	// It's significantly smaller than the blob itself, reducing on-chain storage requirements
	KZGCommitment Bytes48 `json:"kzg_commitment"`

	// KZGProof is a zero-knowledge proof that allows verification of small portions of the blob
	// without needing the entire blob data
	// It's used to prove that the commitment corresponds to the actual blob data
	KZGProof Bytes48 `json:"kzg_proof"`
}

func MatchSidecarsWithHashes added in v0.28.0

func MatchSidecarsWithHashes(fetchedSidecars []*BlobSidecar, hashes []gethcommon.Hash) ([]*BlobSidecar, error)

MatchSidecarsWithHashes matches the fetched sidecars with the provided hashes.

type Bytes32 added in v0.28.0

type Bytes32 [32]byte

func (Bytes32) MarshalText added in v0.28.0

func (b Bytes32) MarshalText() ([]byte, error)

func (Bytes32) String added in v0.28.0

func (b Bytes32) String() string

func (*Bytes32) UnmarshalJSON added in v0.28.0

func (b *Bytes32) UnmarshalJSON(text []byte) error

func (*Bytes32) UnmarshalText added in v0.28.0

func (b *Bytes32) UnmarshalText(text []byte) error

type Bytes48 added in v0.28.0

type Bytes48 [48]byte

func (Bytes48) MarshalText added in v0.28.0

func (b Bytes48) MarshalText() ([]byte, error)

func (Bytes48) String added in v0.28.0

func (b Bytes48) String() string

func (Bytes48) TerminalString added in v0.28.0

func (b Bytes48) TerminalString() string

TerminalString implements log.TerminalStringer, formatting a string for console output during logging.

func (*Bytes48) UnmarshalJSON added in v0.28.0

func (b *Bytes48) UnmarshalJSON(text []byte) error

func (*Bytes48) UnmarshalText added in v0.28.0

func (b *Bytes48) UnmarshalText(text []byte) error

type ClientPool added in v0.28.0

type ClientPool[T any] struct {
	// contains filtered or unexported fields
}

ClientPool is a simple round-robin client pool

func NewClientPool added in v0.28.0

func NewClientPool[T any](clients ...T) *ClientPool[T]

func (*ClientPool[T]) Get added in v0.28.0

func (p *ClientPool[T]) Get() T

func (*ClientPool[T]) Len added in v0.28.0

func (p *ClientPool[T]) Len() int

func (*ClientPool[T]) Next added in v0.28.0

func (p *ClientPool[T]) Next()

type EthClient

type EthClient interface {
	BlockNumber() (uint64, error)                                                 // retrieves the number of the head block
	FetchHeadBlock() (*types.Header, error)                                       // retrieves the block at head height
	HeaderByHash(id gethcommon.Hash) (*types.Header, error)                       // retrieves a block header given a hash
	BlockByHash(id gethcommon.Hash) (*types.Block, error)                         // retrieves a block given a hash
	HeaderByNumber(n *big.Int) (*types.Header, error)                             // retrieves a block given a number - returns head block if n is nil
	SendTransaction(signedTx *types.Transaction) error                            // issues an ethereum transaction (expects signed tx)
	TransactionReceipt(hash gethcommon.Hash) (*types.Receipt, error)              // fetches the ethereum transaction receipt
	TransactionByHash(hash gethcommon.Hash) (*types.Transaction, bool, error)     // fetches the ethereum tx
	Nonce(address gethcommon.Address) (uint64, error)                             // fetches the account nonce to use in the next transaction
	BalanceAt(account gethcommon.Address, blockNumber *big.Int) (*big.Int, error) // fetches the balance of the account
	GetLogs(q ethereum.FilterQuery) ([]types.Log, error)                          // fetches the logs for a given query
	CallContract(msg ethereum.CallMsg) ([]byte, error)                            // Runs the provided call message on the latest block.
	SuggestGasTipCap(ctx context.Context) (*big.Int, error)                       // Suggests the gas tip cap
	EthClient() *ethclient.Client                                                 // returns the underlying eth client
	EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error)       // estimates the gas for a given call
	BlockListener() (chan *types.Header, ethereum.Subscription)                   // subscribes to new blocks and returns a listener with the blocks heads and the subscription handler
	ReconnectIfClosed() error                                                     // closes and creates a new connection
	Alive() bool                                                                  // returns whether the connection is live or not
	Info() Info                                                                   // retrieves the node Info
	Stop()                                                                        // tries to cleanly stop the client and release any resources
	SupportsEventLogs() bool                                                      // returns false for the in-mem simulation

	// todo - all the below should be removed from the interface
	FetchLastBatchSeqNo(address gethcommon.Address) (*big.Int, error)
}

EthClient defines the interface for RPC communications with the ethereum nodes

func NewEthClient

func NewEthClient(ipaddress string, port uint, timeout time.Duration, logger gethlog.Logger) (EthClient, error)

NewEthClient instantiates a new ethadapter.EthClient that connects to an ethereum node

func NewEthClientFromURL

func NewEthClientFromURL(rpcURL string, timeout time.Duration, logger gethlog.Logger) (EthClient, error)

NewEthClientFromURL instantiates a new ethadapter.EthClient that connects to an ethereum node

type Info

type Info struct {
	L2ID gethcommon.Address // the address of the Obscuro node this client is dedicated to
}

Info forces the RPC EthClient to return the data in the same format (independently of its implementation)

type KZGToVersionedHasher added in v1.0.0

type KZGToVersionedHasher struct{}

func (KZGToVersionedHasher) BlobHash added in v1.0.0

type L1BeaconClient added in v0.28.0

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

func NewL1BeaconClient added in v0.28.0

func NewL1BeaconClient(cl BeaconClient, fallbacks ...BlobRetrievalService) *L1BeaconClient

NewL1BeaconClient returns a client for making requests to an L1 consensus layer node. Fallbacks are optional clients that will be used for fetching blobs. L1BeaconClient will rotate between the `cl` and the fallbacks whenever a client runs into an error while fetching blobs.

func (*L1BeaconClient) FetchBlobs added in v0.28.0

func (cl *L1BeaconClient) FetchBlobs(ctx context.Context, b *types.Header, hashes []gethcommon.Hash) ([]*kzg4844.Blob, error)

FetchBlobs fetches blobs that were confirmed in the specified L1 block with the hashes. Confirms each blob's validity by checking its proof against the commitment, and confirming the commitment hashes to the expected value. Returns error if any blob is found invalid.

func (*L1BeaconClient) GetBlobSidecars added in v0.28.0

func (cl *L1BeaconClient) GetBlobSidecars(ctx context.Context, b *types.Header, hashes []gethcommon.Hash) ([]*BlobSidecar, error)

GetBlobSidecars fetches blob sidecars that were confirmed in the specified L1 block. If hashes are provided, only returns sidecars matching those hashes. If no hashes are provided, returns all sidecars for the block.

func (*L1BeaconClient) GetTimeToSlot added in v0.28.0

func (cl *L1BeaconClient) GetTimeToSlot(ctx context.Context) (TimeToSlot, error)

GetTimeToSlot returns a function that converts a timestamp to a slot number.

func (*L1BeaconClient) Init added in v0.28.0

func (cl *L1BeaconClient) Init(ctx context.Context) error

type ReducedConfigData added in v0.28.0

type ReducedConfigData struct {
	SecondsPerSlot Uint64String `json:"SECONDS_PER_SLOT"`
}

type ReducedGenesisData added in v0.28.0

type ReducedGenesisData struct {
	GenesisTime Uint64String `json:"genesis_time"`
}

type TimeToSlot added in v0.28.0

type TimeToSlot func(timestamp uint64) (uint64, error)

TimeToSlot cache the function to avoid recomputing it for every block.

type Uint64String added in v0.28.0

type Uint64String uint64

Uint64String is a decimal string representation of an uint64, for usage in the Beacon API JSON encoding

func (Uint64String) MarshalText added in v0.28.0

func (v Uint64String) MarshalText() (out []byte, err error)

func (*Uint64String) UnmarshalText added in v0.28.0

func (v *Uint64String) UnmarshalText(b []byte) error

type VersionInformation added in v0.28.0

type VersionInformation struct {
	Version string `json:"version"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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