evm

package module
v1.0.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2026 License: Apache-2.0 Imports: 33 Imported by: 1

README

Go Execution EVM

This repository implements the execution.Executor interface from github.com/evstack/ev-node/core/execution (currently on feature branch feature/exec_api). It provides a pure Engine API-based execution client for Evolve.

EngineClient Implementation

The EngineClient is a 100% Engine API compatible implementation of the execution.Executor interface. It connects to an Ethereum execution client (like Reth) and uses both the Engine API and standard Ethereum JSON-RPC API to execute transactions.

Genesis and initial height

In the context of the EVM, the genesis block is designated as a unique block with the block number 0. To ensure compatibility with both evolve and the EVM, the only permissible initial height is 1. During InitChain EVM genesis block is acknowledged (at height 0), and empty block is created (at height 1). This approach ensures that the block numbers between the EVM and evolve remain consistent and synchronized.

Genesis Requirements

Since the PureEngineClient relies on the Engine API, the genesis configuration must properly enable it with the correct hardfork settings:

  1. The genesis file must include post-merge hardfork configurations
  2. terminalTotalDifficulty must be set to 0
  3. terminalTotalDifficultyPassed must be set to true
  4. Hardforks like mergeNetsplitBlock, shanghaiTime, cancunTime and pragueTime should be properly configured

Example of required genesis configuration:

{
  "config": {
    "chainId": 1234,
    "homesteadBlock": 0,
    "eip150Block": 0,
    "eip155Block": 0,
    "eip158Block": 0,
    "byzantiumBlock": 0,
    "constantinopleBlock": 0,
    "petersburgBlock": 0,
    "istanbulBlock": 0,
    "berlinBlock": 0,
    "londonBlock": 0,
    "mergeNetsplitBlock": 0,
    "terminalTotalDifficulty": 0,
    "terminalTotalDifficultyPassed": true,
    "shanghaiTime": 0,
    "cancunTime": 0,
    "pragueTime": 0
  }
}

Without these settings, the Engine API will not be available, and the PureEngineClient will not function correctly.

PayloadID Storage

The PureEngineClient maintains the payloadID between calls:

  1. During InitChain, a payload ID is obtained from the Engine API via engine_forkchoiceUpdatedV3
  2. This payload ID is stored in the client instance as c.payloadID
  3. The stored payload ID is used in subsequent calls to GetTxs to retrieve the current execution payload
  4. After each ExecuteTxs call, a new payload ID is obtained and stored for the next block
Payload as First Transaction

The PureEngineClient implements a unique approach to transaction execution:

  1. In GetTxs, the entire execution payload is serialized to JSON and returned as the first transaction
  2. In ExecuteTxs, this first transaction is deserialized back into an execution payload
  3. The remaining transactions are added to the payload's transaction list
  4. The complete payload is then submitted to the execution client via engine_newPayloadV4

This approach ensures that:

  • The execution payload structure is preserved between calls
  • All execution happens within the EVM
  • It's not possible to create a payload outside of the EVM
  • Transactions cannot be selected or ordered outside of the EVM
How Eth API is Used

The PureEngineClient uses the standard Ethereum JSON-RPC API for:

  1. Retrieving block information (via HeaderByNumber)
  2. Reading the genesis block hash and state root
  3. Getting gas limits and other block parameters

This allows the client to interact with the execution layer for read operations while using the Engine API for write operations.

Deployment Architecture

graph LR
    subgraph Evolve Binary
        EvolveCore[Evolve Core]
        PureEngineClient[PureEngineClient]
    end

    %% Connections
    EvolveCore --> PureEngineClient
    PureEngineClient -->|Engine API| Reth
    PureEngineClient -->|Eth API| Reth

Development and Testing

Running Reth in Docker
cd docker
docker compose up -d
Reading Genesis Information

If you've modified the genesis file, you can read the genesis hash and state root using the Ethereum JSON-RPC API:

# Get genesis block hash
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x0", false],"id":1}' http://localhost:8545 | jq -r '.result.hash'

# Get genesis state root
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x0", false],"id":1}' http://localhost:8545 | jq -r '.result.stateRoot'

Documentation

Index

Constants

View Source
const (
	// MaxPayloadStatusRetries is the maximum number of retries for SYNCING status.
	// According to the Engine API specification, SYNCING indicates temporary unavailability
	// and should be retried with exponential backoff.
	MaxPayloadStatusRetries = 3
	// InitialRetryBackoff is the initial backoff duration for retries.
	// The backoff doubles on each retry attempt (exponential backoff).
	InitialRetryBackoff = 1 * time.Second
	// SafeBlockLag is the number of blocks the safe block lags behind the head.
	// This provides a buffer for reorg protection - safe blocks won't be reorged
	// under normal operation. A value of 2 means when head is at block N,
	// safe is at block N-2.
	SafeBlockLag = 2
	// FinalizedBlockLag is the number of blocks the finalized block lags behind head.
	// This is a temporary mock value until proper DA-based finalization is wired up.
	// A value of 3 means when head is at block N, finalized is at block N-3.
	FinalizedBlockLag = 3
)
View Source
const (
	FlagEvmEthURL        = "evm.eth-url"
	FlagEvmEngineURL     = "evm.engine-url"
	FlagEvmJWTSecretFile = "evm.jwt-secret-file"
	FlagEvmGenesisHash   = "evm.genesis-hash"
	FlagEvmFeeRecipient  = "evm.fee-recipient"
)
View Source
const (
	ExecStageStarted   = "started"
	ExecStageBuilt     = "built"
	ExecStageSubmitted = "submitted"
	ExecStagePromoted  = "promoted"
)

ExecMeta stages

Variables

View Source
var (
	// ErrInvalidPayloadStatus indicates that the execution engine returned a permanent
	// failure status (INVALID or unknown status). This error should not be retried.
	ErrInvalidPayloadStatus = errors.New("invalid payload status")
	// ErrPayloadSyncing indicates that the execution engine is temporarily syncing.
	// According to the Engine API specification, this is a transient condition that
	// should be handled with retry logic rather than immediate failure.
	ErrPayloadSyncing = errors.New("payload syncing")
)

Functions

func CheckTxIncluded

func CheckTxIncluded(client *ethclient.Client, txHash common.Hash) bool

CheckTxIncluded checks if a transaction with the given hash was included in a block and succeeded.

func GetRandomTransaction

func GetRandomTransaction(t *testing.T, privateKeyHex, toAddressHex, chainID string, gasLimit uint64, lastNonce *uint64) *types.Transaction

GetRandomTransaction creates and signs a random Ethereum legacy transaction using the provided private key, recipient, chain ID, gas limit, and nonce.

Types

type EVMStore

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

EVMStore wraps a ds.Batching datastore with a prefix for EVM execution data. This keeps EVM-specific data isolated from other ev-node data.

func NewEVMStore

func NewEVMStore(db ds.Batching) *EVMStore

NewEVMStore creates a new EVMStore wrapping the given datastore.

func (*EVMStore) GetExecMeta

func (s *EVMStore) GetExecMeta(ctx context.Context, height uint64) (*ExecMeta, error)

GetExecMeta retrieves execution metadata for the given height. Returns nil, nil if not found.

func (*EVMStore) SaveExecMeta

func (s *EVMStore) SaveExecMeta(ctx context.Context, meta *ExecMeta) error

SaveExecMeta persists execution metadata for the given height.

func (*EVMStore) Sync

func (s *EVMStore) Sync(ctx context.Context) error

Sync ensures all pending writes are flushed to disk.

type EngineClient

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

EngineClient represents a client that interacts with an Ethereum execution engine through the Engine API. It manages connections to both the engine and standard Ethereum APIs, and maintains state related to block processing.

func NewEngineExecutionClient

func NewEngineExecutionClient(
	ethURL,
	engineURL string,
	jwtSecret string,
	genesisHash common.Hash,
	feeRecipient common.Address,
	db ds.Batching,
	tracingEnabled bool,
) (*EngineClient, error)

NewEngineExecutionClient creates a new instance of EngineAPIExecutionClient. The db parameter is required for ExecMeta tracking which enables idempotent execution and crash recovery. The db is wrapped with a prefix to isolate EVM execution data from other ev-node data. When tracingEnabled is true, the client will inject W3C trace context headers and wrap Engine API and Eth API calls with OpenTelemetry spans.

func (*EngineClient) ExecuteTxs

func (c *EngineClient) ExecuteTxs(ctx context.Context, txs [][]byte, blockHeight uint64, timestamp time.Time, prevStateRoot []byte) (updatedStateRoot []byte, err error)

ExecuteTxs executes the given transactions at the specified block height and timestamp.

ExecMeta tracking (if store is configured): - Checks for already-promoted blocks to enable idempotent execution - Saves ExecMeta with payloadID after forkchoiceUpdatedV3 for crash recovery - Updates ExecMeta to "promoted" after successful execution

func (*EngineClient) FilterTxs

func (c *EngineClient) FilterTxs(ctx context.Context, txs [][]byte, maxBytes, maxGas uint64, hasForceIncludedTransaction bool) ([]execution.FilterStatus, error)

FilterTxs validates force-included transactions and applies gas and size filtering for all passed txs. If hasForceIncludedTransaction is false, skip filtering entirely - mempool batch is already filtered. Returns a slice of FilterStatus for each transaction.

func (*EngineClient) GetExecutionInfo

func (c *EngineClient) GetExecutionInfo(ctx context.Context) (execution.ExecutionInfo, error)

GetExecutionInfo returns current execution layer parameters.

func (*EngineClient) GetLatestHeight

func (c *EngineClient) GetLatestHeight(ctx context.Context) (uint64, error)

GetLatestHeight returns the current block height of the execution layer

func (*EngineClient) GetTxs

func (c *EngineClient) GetTxs(ctx context.Context) ([][]byte, error)

GetTxs retrieves transactions from the current execution payload

func (*EngineClient) InitChain

func (c *EngineClient) InitChain(ctx context.Context, genesisTime time.Time, initialHeight uint64, chainID string) ([]byte, error)

InitChain initializes the blockchain with the given genesis parameters

func (*EngineClient) ResumePayload

func (c *EngineClient) ResumePayload(ctx context.Context, payloadIDBytes []byte) (stateRoot []byte, err error)

ResumePayload resumes an in-progress payload build using a stored payloadID. This is used for crash recovery when we have a payloadID but haven't yet retrieved and submitted the payload to the EL.

Returns the state root from the payload, or an error if resumption fails. Implements the execution.PayloadResumer interface.

func (*EngineClient) Rollback

func (c *EngineClient) Rollback(ctx context.Context, targetHeight uint64) error

Rollback resets the execution layer head to the specified height using forkchoice update. This is used for recovery when the EL is ahead of the consensus layer (e.g., during rolling restarts

Implements the execution.Rollbackable interface.

func (*EngineClient) SetFinal

func (c *EngineClient) SetFinal(ctx context.Context, blockHeight uint64) error

SetFinal marks the block at the given height as finalized

func (*EngineClient) SetFinalized

func (c *EngineClient) SetFinalized(ctx context.Context, blockHash common.Hash) error

SetFinalized explicitly sets the finalized block hash. This allows the derivation layer to advance finalization independently. Finalized indicates a block that will never be reorged (e.g., included in DA with sufficient confirmations).

func (*EngineClient) SetLogger

func (c *EngineClient) SetLogger(l zerolog.Logger)

SetLogger allows callers to attach a structured logger.

func (*EngineClient) SetSafe

func (c *EngineClient) SetSafe(ctx context.Context, blockHash common.Hash) error

SetSafe explicitly sets the safe block hash. This allows the derivation layer to advance the safe block independently of head. Safe indicates a block that is unlikely to be reorged (e.g., confirmed by DA).

func (*EngineClient) SetSafeByHeight

func (c *EngineClient) SetSafeByHeight(ctx context.Context, height uint64) error

SetSafeByHeight sets the safe block by looking up the block hash at the given height. Uses cached block hashes when available to avoid RPC calls. Falls back to RPC on cache miss (e.g., during restart before cache is warmed). Returns nil if the height doesn't exist yet (block not produced).

type EngineRPCClient

type EngineRPCClient interface {
	// ForkchoiceUpdated updates the forkchoice state and optionally starts payload building.
	ForkchoiceUpdated(ctx context.Context, state engine.ForkchoiceStateV1, args map[string]any) (*engine.ForkChoiceResponse, error)

	// GetPayload retrieves a previously requested execution payload.
	GetPayload(ctx context.Context, payloadID engine.PayloadID) (*engine.ExecutionPayloadEnvelope, error)

	// NewPayload submits a new execution payload for validation.
	NewPayload(ctx context.Context, payload *engine.ExecutableData, blobHashes []string, parentBeaconBlockRoot string, executionRequests [][]byte) (*engine.PayloadStatusV1, error)
}

EngineRPCClient abstracts Engine API RPC calls for tracing and testing.

func NewEngineRPCClient

func NewEngineRPCClient(client *rpc.Client) EngineRPCClient

NewEngineRPCClient creates a new Engine API client.

type EthRPCClient

type EthRPCClient interface {
	// HeaderByNumber retrieves a block header by number (nil = latest).
	HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)

	// GetTxs retrieves pending transactions from the transaction pool.
	GetTxs(ctx context.Context) ([]string, error)
}

EthRPCClient abstracts Ethereum JSON-RPC calls for tracing and testing.

func NewEthRPCClient

func NewEthRPCClient(client *ethclient.Client) EthRPCClient

type ExecMeta

type ExecMeta struct {
	// Height is the block height this execution metadata is for
	Height uint64
	// ParentHash is the EL parent block hash used for this execution
	ParentHash []byte
	// PayloadID is the Engine API payload ID (optional, set after forkchoiceUpdatedV3)
	PayloadID []byte
	// BlockHash is the EL block hash once built (set after getPayloadV4)
	BlockHash []byte
	// StateRoot is the state root from the execution payload
	StateRoot []byte
	// TxHash is the hash of the transaction list for sanity checks
	TxHash []byte
	// Timestamp is the block timestamp
	Timestamp int64
	// Stage indicates the current execution stage:
	// "started" - forkchoiceUpdatedV3 called, payloadID obtained
	// "built" - getPayloadV4 called, payload retrieved
	// "submitted" - newPayloadV4 called, payload marked VALID
	// "promoted" - final forkchoiceUpdatedV3 called, block is head
	Stage string
	// UpdatedAtUnix is the Unix timestamp when this metadata was last updated
	UpdatedAtUnix int64
}

ExecMeta tracks execution state per height for idempotent execution. This enables crash recovery and prevents sibling block creation on retries.

func (*ExecMeta) FromProto

func (em *ExecMeta) FromProto(other *pb.ExecMeta) error

FromProto fills ExecMeta with data from its protobuf representation.

func (*ExecMeta) ToProto

func (em *ExecMeta) ToProto() *pb.ExecMeta

ToProto converts ExecMeta into protobuf representation.

Directories

Path Synopsis
test module
types

Jump to

Keyboard shortcuts

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