diff --git a/CHANGELOG.md b/CHANGELOG.md index 912343ec0..24b6f841a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,39 +9,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +* chore: Better check for stored meta not stale [#3221](https://github.com/evstack/ev-node/pull/3221) + ## v1.1.0-rc.1 ### Added -- Add AWS & GCP KMS signer backend [#3171](https://github.com/evstack/ev-node/pull/3171) -- Subscribe to forced inclusion namespace events [#3146](https://github.com/evstack/ev-node/pull/3146) -- Display block source in sync log [#3193](https://github.com/evstack/ev-node/pull/3193) +* Add AWS & GCP KMS signer backend [#3171](https://github.com/evstack/ev-node/pull/3171) +* Subscribe to forced inclusion namespace events [#3146](https://github.com/evstack/ev-node/pull/3146) +* Display block source in sync log [#3193](https://github.com/evstack/ev-node/pull/3193) ### Fixed -- Avoid evicting yet to be processed heights [#3204](https://github.com/evstack/ev-node/pull/3204) -- Bound Badger index cache memory to prevent growth with chain length [3209](https://github.com/evstack/ev-node/pull/3209) -- Refetch latest da height instead of da height +1 when P2P is offline [#3201](https://github.com/evstack/ev-node/pull/3201) -- Fix race on startup sync. [#3162](https://github.com/evstack/ev-node/pull/3162) -- Strict raft state. [#3167](https://github.com/evstack/ev-node/pull/3167) -- Retry fetching the timestamp on error in da-client [#3166](https://github.com/evstack/ev-node/pull/3166) +* Avoid evicting yet to be processed heights [#3204](https://github.com/evstack/ev-node/pull/3204) +* Bound Badger index cache memory to prevent growth with chain length [3209](https://github.com/evstack/ev-node/pull/3209) +* Refetch latest da height instead of da height +1 when P2P is offline [#3201](https://github.com/evstack/ev-node/pull/3201) +* Fix race on startup sync. [#3162](https://github.com/evstack/ev-node/pull/3162) +* Strict raft state. [#3167](https://github.com/evstack/ev-node/pull/3167) +* Retry fetching the timestamp on error in da-client [#3166](https://github.com/evstack/ev-node/pull/3166) ## v1.0.0 ### Fixed -- Persist cache snapshot only once at shutdown to avoid Badger vlog +* Persist cache snapshot only once at shutdown to avoid Badger vlog increase. [#3153](https://github.com/evstack/ev-node/pull/3153) ## v1.0.0-rc.5 ### Added -- Add disaster recovery for sequencer - - Catch up possible DA-only blocks when restarting. [#3057](https://github.com/evstack/ev-node/pull/3057) - - Verify DA and P2P state on restart (prevent double-signing). [#3061](https://github.com/evstack/ev-node/pull/3061) -- Node pruning support. [#2984](https://github.com/evstack/ev-node/pull/2984) - - Two different sort of pruning implemented: +* Add disaster recovery for sequencer + * Catch up possible DA-only blocks when restarting. [#3057](https://github.com/evstack/ev-node/pull/3057) + * Verify DA and P2P state on restart (prevent double-signing). [#3061](https://github.com/evstack/ev-node/pull/3061) +* Node pruning support. [#2984](https://github.com/evstack/ev-node/pull/2984) + * Two different sort of pruning implemented: _Classic pruning_ (`all`): prunes given `HEAD-n` blocks from the databases, including store metadatas. _Auto Storage Optimization_ (`metadata`): prunes only the state metadatas, keeps all blocks. By using one or the other, you are losing the ability to rollback or replay transactions earlier than `HEAD-n`. @@ -49,56 +53,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- Fix block timer to account for execution time. Previously, the block timer reset to the full `block_time` duration +* Fix block timer to account for execution time. Previously, the block timer reset to the full `block_time` duration after `ProduceBlock` completed, making the effective interval `block_time + execution_time`. Now the timer subtracts elapsed execution time so blocks are produced at the configured cadence. ### Changes -- Store pending blocks separately from executed blocks key. [#3073](https://github.com/evstack/ev-node/pull/3073) -- Fixes issues with force inclusion verification on sync nodes. [#3057](https://github.com/evstack/ev-node/pull/3057) -- Add flag to `local-da` to produce empty DA blocks (closer to the real +* Store pending blocks separately from executed blocks key. [#3073](https://github.com/evstack/ev-node/pull/3073) +* Fixes issues with force inclusion verification on sync nodes. [#3057](https://github.com/evstack/ev-node/pull/3057) +* Add flag to `local-da` to produce empty DA blocks (closer to the real system). [#3057](https://github.com/evstack/ev-node/pull/3057) -- Validate P2P DA height hints against the latest known DA height to prevent malicious peers from triggering runaway +* Validate P2P DA height hints against the latest known DA height to prevent malicious peers from triggering runaway catchup. [#3128](https://github.com/evstack/ev-node/pull/3128) -- Replace syncer DA polling system by DA subscription via +* Replace syncer DA polling system by DA subscription via websockets. [#3131](https://github.com/evstack/ev-node/pull/3131) ## v1.0.0-rc.4 ### Changes -- Skip draining when exec client unavailable. [#3060](https://github.com/evstack/ev-node/pull/3060) +* Skip draining when exec client unavailable. [#3060](https://github.com/evstack/ev-node/pull/3060) ## v1.0.0-rc.3 ### Added -- Add DA Hints for P2P transactions. This allows a catching up node to be on sync with both DA and +* Add DA Hints for P2P transactions. This allows a catching up node to be on sync with both DA and P2P. ([#2891](https://github.com/evstack/ev-node/pull/2891)) ### Changes -- Improve `cache.NumPendingData` to not return empty data. Automatically bumps `LastSubmittedHeight` to reflect +* Improve `cache.NumPendingData` to not return empty data. Automatically bumps `LastSubmittedHeight` to reflect that. ([#3046](https://github.com/evstack/ev-node/pull/3046)) -- **BREAKING** Make pending events cache and tx cache fully ephemeral. Those will be re-fetched on restart. DA Inclusion +* **BREAKING** Make pending events cache and tx cache fully ephemeral. Those will be re-fetched on restart. DA Inclusion cache persists until cleared up after DA inclusion has been processed. Persist accross restart using store metadata. ([#3047](https://github.com/evstack/ev-node/pull/3047)) -- Replace LRU cache by standard mem cache with manual eviction in `store_adapter`. When P2P blocks were fetched too +* Replace LRU cache by standard mem cache with manual eviction in `store_adapter`. When P2P blocks were fetched too fast, they would be evicted before being executed [#3051](https://github.com/evstack/ev-node/pull/3051) -- Fix replay logic leading to app hashes by verifying against the wrong +* Fix replay logic leading to app hashes by verifying against the wrong block [#3053](https://github.com/evstack/ev-node/pull/3053). ## v1.0.0-rc.2 ### Changes -- Improve cache handling when there is a significant backlog of pending headers and +* Improve cache handling when there is a significant backlog of pending headers and data. ([#3030](https://github.com/evstack/ev-node/pull/3030)) -- Decrease MaxBytesSize to `5MB` to increase compatibility with public +* Decrease MaxBytesSize to `5MB` to increase compatibility with public nodes. ([#3030](https://github.com/evstack/ev-node/pull/3030)) -- Proper counting of `DASubmitterPendingBlobs` metrics. [#3038](https://github.com/evstack/ev-node/pull/3038) -- Replace `go-header` store by `ev-node` store. This avoid duplication of all blocks in `go-header` and `ev-node` store. +* Proper counting of `DASubmitterPendingBlobs` metrics. [#3038](https://github.com/evstack/ev-node/pull/3038) +* Replace `go-header` store by `ev-node` store. This avoid duplication of all blocks in `go-header` and `ev-node` store. Thanks to the cached store from #3030, this should improve p2p performance as well. [#3036](https://github.com/evstack/ev-node/pull/3036) @@ -106,45 +110,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Added OpenTelemetry tracing support with OTLP export for distributed tracing across ev-node components including block +* Added OpenTelemetry tracing support with OTLP export for distributed tracing across ev-node components including block production, syncing, DA submission/retrieval, sequencer, store operations, and RPC layer. Configurable via `instrumentation.tracing`, `instrumentation.tracing_endpoint`, `instrumentation.tracing_service_name`, and `instrumentation.tracing_sample_rate` settings. ([#2956](https://github.com/evstack/ev-node/issues/2956)) -- **BREAKING:** Implement forced inclusion and batch sequencing ([#2797](https://github.com/evstack/ev-node/pull/2797)) +* **BREAKING:** Implement forced inclusion and batch sequencing ([#2797](https://github.com/evstack/ev-node/pull/2797)) **This change requires adding a `da_epoch_forced_inclusion` field to the node's `genesis.json` file.** The recommended value is `100`. Full support for this feature will be available in a future release. -- Added `post-tx` command and force inclusion server to submit transactions directly to the DA +* Added `post-tx` command and force inclusion server to submit transactions directly to the DA layer. ([#2888](https://github.com/evstack/ev-node/pull/2888)) Additionally, modified the core package to support marking transactions as forced included transactions. The execution client ought to perform basic validation on those transactions as they have skipped the execution client's mempool. -- Added batching strategies (default stay time-based, unchanged from previous betas). Currently available strategies are +* Added batching strategies (default stay time-based, unchanged from previous betas). Currently available strategies are `time`, `size`, `immediate` and `adaptive`. [Full documentation can be found here](https://github.com/evstack/ev-node/blob/122486de98d09ecd37d792b88814dcf07238f28a/docs/learn/config.md?plain=1#L521-L597). -- Added `FilterTxs` method to the execution interface. This method is meant to filter txs by size and if the execution +* Added `FilterTxs` method to the execution interface. This method is meant to filter txs by size and if the execution clients allows it, by gas. This is useful for force included transactions, as those aren't filtered by the sequencer's mempool. -- Added `GetExecutionInfo` method to the execution interface. This method returns some execution information, such as +* Added `GetExecutionInfo` method to the execution interface. This method returns some execution information, such as the maximum gas per block. ### Changed -- **BREAKING:** Renamed `evm-single` to `evm` and `grpc-single` to `evgrpc` for +* **BREAKING:** Renamed `evm-single` to `evm` and `grpc-single` to `evgrpc` for clarity. [#2839](https://github.com/evstack/ev-node/pull/2839). You may need to manually modify your evnode.yaml `signer.signer_path` if your $HOME folder is changed. -- Split cache interface into `CacheManager` and `PendingManager` and created `da` client to easy DA +* Split cache interface into `CacheManager` and `PendingManager` and created `da` client to easy DA handling. [#2878](https://github.com/evstack/ev-node/pull/2878) -- Improved startup DA retrieval height when cache is cleared or +* Improved startup DA retrieval height when cache is cleared or empty. [#2880](https://github.com/evstack/ev-node/pull/2880) ### Removed -- **BREAKING:** Removed unused and confusing metrics from sequencers and block processing, including sequencer-specific +* **BREAKING:** Removed unused and confusing metrics from sequencers and block processing, including sequencer-specific metrics (gas price, blob size, transaction status, pending blocks), channel buffer metrics, overly granular error metrics, block production categorization metrics, and sync lag metrics. Essential metrics for DA submission health, block production, and performance monitoring are retained. [#2904](https://github.com/evstack/ev-node/pull/2904) -- **BREAKING**: Removed `core/da` package and replaced DAClient with internal implementation. The DA client is exposed +* **BREAKING**: Removed `core/da` package and replaced DAClient with internal implementation. The DA client is exposed as `block.FullDAClient`, `block.DAClient`, `block.DAVerifier` without leaking implementation details. [#2910](https://github.com/evstack/ev-node/pull/2910) @@ -152,53 +156,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Improvements -- Loosen syncer validation for allowing swapping sequencer and full node +* Loosen syncer validation for allowing swapping sequencer and full node state [#2925](https://github.com/evstack/ev-node/pull/2925) ## v1.0.0-beta.10 ### Added -- Enhanced health check system with separate liveness (`/health/live`) and readiness (`/health/ready`) HTTP endpoints. +* Enhanced health check system with separate liveness (`/health/live`) and readiness (`/health/ready`) HTTP endpoints. Readiness endpoint includes P2P listening check and aggregator block production rate validation (5x block time threshold). ([#2800](https://github.com/evstack/ev-node/pull/2800)) -- Added `GetP2PStoreInfo` RPC method to retrieve head/tail metadata for go-header stores used by P2P +* Added `GetP2PStoreInfo` RPC method to retrieve head/tail metadata for go-header stores used by P2P sync ([#2835](https://github.com/evstack/ev-node/pull/2835)) -- Added protobuf definitions for `P2PStoreEntry` and `P2PStoreSnapshot` messages to support P2P store inspection +* Added protobuf definitions for `P2PStoreEntry` and `P2PStoreSnapshot` messages to support P2P store inspection ### Changed -- Improved EVM execution client payload status validation with proper retry logic for SYNCING states in `InitChain`, +* Improved EVM execution client payload status validation with proper retry logic for SYNCING states in `InitChain`, `ExecuteTxs`, and `SetFinal` methods. The implementation now follows Engine API specification by retrying SYNCING/ACCEPTED status with exponential backoff and failing immediately on INVALID status, preventing unnecessary node shutdowns during transient execution engine sync operations. ([#2863](https://github.com/evstack/ev-node/pull/2863)) -- Remove GasPrice and GasMultiplier from DA interface and configuration to use celestia-node's native fee +* Remove GasPrice and GasMultiplier from DA interface and configuration to use celestia-node's native fee estimation. ([#2822](https://github.com/evstack/ev-node/pull/2822)) -- Use cache instead of in memory store for reaper. Persist cache on reload. Autoclean after 24 +* Use cache instead of in memory store for reaper. Persist cache on reload. Autoclean after 24 hours. ([#2811](https://github.com/evstack/ev-node/pull/2811)) -- Improved P2P sync service store initialization to be atomic and prevent race +* Improved P2P sync service store initialization to be atomic and prevent race conditions ([#2838](https://github.com/evstack/ev-node/pull/2838)) -- Enhanced P2P bootstrap behavior to intelligently detect starting height from local store instead of requiring trusted +* Enhanced P2P bootstrap behavior to intelligently detect starting height from local store instead of requiring trusted hash -- Relaxed execution layer height validation in block replay to allow execution to be ahead of target height, enabling +* Relaxed execution layer height validation in block replay to allow execution to be ahead of target height, enabling recovery from manual intervention scenarios ### Removed -- **BREAKING:** Removed `evnode.v1.HealthService` gRPC endpoint. Use HTTP endpoints: `GET /health/live` and +* **BREAKING:** Removed `evnode.v1.HealthService` gRPC endpoint. Use HTTP endpoints: `GET /health/live` and `GET /health/ready`. ([#2800](https://github.com/evstack/ev-node/pull/2800)) -- **BREAKING:** Removed `TrustedHash` configuration option and `--evnode.node.trusted_hash` flag. Sync service now +* **BREAKING:** Removed `TrustedHash` configuration option and `--evnode.node.trusted_hash` flag. Sync service now automatically determines starting height from local store state ([#2838](https://github.com/evstack/ev-node/pull/2838)) -- **BREAKING:** Removed unused and confusing metrics from sequencers and block processing, including sequencer-specific +* **BREAKING:** Removed unused and confusing metrics from sequencers and block processing, including sequencer-specific metrics (gas price, blob size, transaction status, pending blocks), channel buffer metrics, overly granular error metrics, block production categorization metrics, and sync lag metrics. Essential metrics for DA submission health, block production, and performance monitoring are retained. [#2904](https://github.com/evstack/ev-node/pull/2904) ### Fixed -- Fixed sync service initialization issue when node is not on genesis but has an empty store +* Fixed sync service initialization issue when node is not on genesis but has an empty store ## v1.0.0-beta.9 @@ -206,34 +210,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 -- Added automated upgrade test for the `evm` app that verifies compatibility when moving from v1.0.0-beta.8 to HEAD in +* Added automated upgrade test for the `evm` app that verifies compatibility when moving from v1.0.0-beta.8 to HEAD in CI ([#2780](https://github.com/evstack/ev-node/pull/2780)) -- Added execution-layer replay mechanism so nodes can resynchronize by replaying missed batches against the +* Added execution-layer replay mechanism so nodes can resynchronize by replaying missed batches against the executor ([#2771](https://github.com/evstack/ev-node/pull/2771)) -- Added cache-pruning logic that evicts entries once heights are finalized to keep node memory usage +* Added cache-pruning logic that evicts entries once heights are finalized to keep node memory usage bounded ([#2761](https://github.com/evstack/ev-node/pull/2761)) -- Added Prometheus gauges and counters that surface DA submission failures, pending blobs, and resend attempts for +* Added Prometheus gauges and counters that surface DA submission failures, pending blobs, and resend attempts for easier operational monitoring ([#2756](https://github.com/evstack/ev-node/pull/2756)) -- Added gRPC execution client implementation for remote execution services using Connect-RPC +* Added gRPC execution client implementation for remote execution services using Connect-RPC protocol ([#2490](https://github.com/evstack/ev-node/pull/2490)) -- Added `ExecutorService` protobuf definition with InitChain, GetTxs, ExecuteTxs, and SetFinal +* Added `ExecutorService` protobuf definition with InitChain, GetTxs, ExecuteTxs, and SetFinal RPCs ([#2490](https://github.com/evstack/ev-node/pull/2490)) -- Added new `grpc` app for running EVNode with a remote execution layer via +* Added new `grpc` app for running EVNode with a remote execution layer via gRPC ([#2490](https://github.com/evstack/ev-node/pull/2490)) ### Changed -- Hardened signer CLI and block pipeline per security audit: passphrases must be provided via +* Hardened signer CLI and block pipeline per security audit: passphrases must be provided via `--evnode.signer.passphrase_file`, JWT secrets must be provided via `--evm.jwt-secret-file`, data/header validation enforces metadata and timestamp checks, and the reaper backs off on failures ( BREAKING) ([#2764](https://github.com/evstack/ev-node/pull/2764)) -- Added retries around executor `ExecuteTxs` calls to better tolerate transient execution +* Added retries around executor `ExecuteTxs` calls to better tolerate transient execution errors ([#2784](https://github.com/evstack/ev-node/pull/2784)) -- Increased default `ReadinessMaxBlocksBehind` from 3 to 30 blocks so `/health/ready` stays true during normal batch +* Increased default `ReadinessMaxBlocksBehind` from 3 to 30 blocks so `/health/ready` stays true during normal batch sync ([#2779](https://github.com/evstack/ev-node/pull/2779)) -- Updated EVM execution client to use new `txpoolExt_getTxs` RPC API for retrieving pending transactions as RLP-encoded +* Updated EVM execution client to use new `txpoolExt_getTxs` RPC API for retrieving pending transactions as RLP-encoded bytes ### Deprecated @@ -244,7 +248,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 -- Removed `LastCommitHash`, `ConsensusHash`, and `LastResultsHash` from the canonical header representation in favor of +* Removed `LastCommitHash`, `ConsensusHash`, and `LastResultsHash` from the canonical header representation in favor of slim headers (BREAKING; legacy hashes now live under `Header.Legacy`) ([#2766](https://github.com/evstack/ev-node/pull/2766)) @@ -326,6 +330,6 @@ Pre-release versions: 0.x.y (anything may change) -- +* [Unreleased]: https://github.com/evstack/ev-node/compare/v1.0.0-beta.1...HEAD diff --git a/execution/evm/execution.go b/execution/evm/execution.go index 15cddf641..306789336 100644 --- a/execution/evm/execution.go +++ b/execution/evm/execution.go @@ -756,24 +756,33 @@ func (c *EngineClient) reconcileExecutionAtHeight(ctx context.Context, height ui // If we have a started execution with a payloadID, validate it still exists before resuming. // After node restart, the EL's payload cache is ephemeral and the payloadID may be stale. if execMeta.Stage == ExecStageStarted && len(execMeta.PayloadID) == 8 { - var pid engine.PayloadID - copy(pid[:], execMeta.PayloadID) + requestedTxHash := hashTxs(txs) + if execMeta.Timestamp != timestamp.Unix() || !bytes.Equal(execMeta.TxHash, requestedTxHash) { + c.logger.Debug(). + Uint64("height", height). + Int64("execmeta_timestamp", execMeta.Timestamp). + Int64("requested_timestamp", timestamp.Unix()). + Msg("ExecuteTxs: ignoring stale in-progress execution for different block inputs") + } else { + var pid engine.PayloadID + copy(pid[:], execMeta.PayloadID) - // Validate payload still exists by attempting to retrieve it - if _, err = c.engineClient.GetPayload(ctx, pid); err == nil { - c.logger.Info(). + // Validate payload still exists by attempting to retrieve it + if _, err = c.engineClient.GetPayload(ctx, pid); err == nil { + c.logger.Info(). + Uint64("height", height). + Str("stage", execMeta.Stage). + Msg("ExecuteTxs: found in-progress execution with payloadID, returning payloadID for resume") + return nil, &pid, true, nil + } + // Payload is stale (expired or node restarted) - proceed with fresh execution + c.logger.Debug(). Uint64("height", height). - Str("stage", execMeta.Stage). - Msg("ExecuteTxs: found in-progress execution with payloadID, returning payloadID for resume") - return nil, &pid, true, nil + Str("payloadID", pid.String()). + Err(err). + Msg("ExecuteTxs: stale ExecMeta payloadID no longer valid in EL, will re-execute") + // Don't return - fall through to fresh execution } - // Payload is stale (expired or node restarted) - proceed with fresh execution - c.logger.Debug(). - Uint64("height", height). - Str("payloadID", pid.String()). - Err(err). - Msg("ExecuteTxs: stale ExecMeta payloadID no longer valid in EL, will re-execute") - // Don't return - fall through to fresh execution } } @@ -1023,13 +1032,7 @@ func (c *EngineClient) saveExecMeta(ctx context.Context, height uint64, timestam } // Compute tx hash for sanity checks on retry - if len(txs) > 0 { - h := sha256.New() - for _, tx := range txs { - h.Write(tx) - } - execMeta.TxHash = h.Sum(nil) - } + execMeta.TxHash = hashTxs(txs) if err := c.store.SaveExecMeta(ctx, execMeta); err != nil { c.logger.Warn().Err(err).Uint64("height", height).Msg("saveExecMeta: failed to save exec meta") @@ -1042,6 +1045,19 @@ func (c *EngineClient) saveExecMeta(ctx context.Context, height uint64, timestam Msg("saveExecMeta: saved execution metadata") } +func hashTxs(txs [][]byte) []byte { + if len(txs) == 0 { + return nil + } + + h := sha256.New() + for _, tx := range txs { + h.Write(tx) + } + + return h.Sum(nil) +} + // GetLatestHeight returns the current block height of the execution layer func (c *EngineClient) GetLatestHeight(ctx context.Context) (uint64, error) { header, err := c.ethClient.HeaderByNumber(ctx, nil) // nil = latest block diff --git a/execution/evm/execution_reconcile_test.go b/execution/evm/execution_reconcile_test.go new file mode 100644 index 000000000..7d1243f81 --- /dev/null +++ b/execution/evm/execution_reconcile_test.go @@ -0,0 +1,125 @@ +package evm + +import ( + "context" + "errors" + "math/big" + "testing" + "time" + + "github.com/ethereum/go-ethereum/beacon/engine" + "github.com/ethereum/go-ethereum/core/types" + ds "github.com/ipfs/go-datastore" + dssync "github.com/ipfs/go-datastore/sync" + "github.com/rs/zerolog" + "github.com/stretchr/testify/require" +) + +func TestReconcileExecutionAtHeight_StartedExecMeta(t *testing.T) { + specs := map[string]struct { + execMetaTimestamp int64 + execMetaTxs [][]byte + requestedTxs [][]byte + requestedTime time.Time + expectFound bool + expectPayloadID bool + expectGetPayloads int + }{ + "resume_when_inputs_match": { + execMetaTimestamp: 1700000012, + execMetaTxs: [][]byte{[]byte("tx-1")}, + requestedTxs: [][]byte{[]byte("tx-1")}, + requestedTime: time.Unix(1700000012, 0), + expectFound: true, + expectPayloadID: true, + expectGetPayloads: 1, + }, + "ignore_when_timestamp_differs": { + execMetaTimestamp: 1700000010, + execMetaTxs: [][]byte{[]byte("tx-1")}, + requestedTxs: [][]byte{[]byte("tx-1")}, + requestedTime: time.Unix(1700000012, 0), + expectFound: false, + expectPayloadID: false, + expectGetPayloads: 0, + }, + "ignore_when_txs_differ": { + execMetaTimestamp: 1700000012, + execMetaTxs: [][]byte{[]byte("tx-old")}, + requestedTxs: [][]byte{[]byte("tx-new")}, + requestedTime: time.Unix(1700000012, 0), + expectFound: false, + expectPayloadID: false, + expectGetPayloads: 0, + }, + } + for name, spec := range specs { + t.Run(name, func(t *testing.T) { + store := NewEVMStore(dssync.MutexWrap(ds.NewMapDatastore())) + payloadID := engine.PayloadID{1, 2, 3, 4, 5, 6, 7, 8} + require.NoError(t, store.SaveExecMeta(t.Context(), &ExecMeta{ + Height: 12, + PayloadID: payloadID[:], + TxHash: hashTxs(spec.execMetaTxs), + Timestamp: spec.execMetaTimestamp, + Stage: ExecStageStarted, + })) + + engineRPC := &mockReconcileEngineRPCClient{ + payloads: map[engine.PayloadID]*engine.ExecutionPayloadEnvelope{ + payloadID: {}, + }, + } + client := &EngineClient{ + engineClient: engineRPC, + ethClient: mockReconcileEthRPCClient{}, + store: store, + logger: zerolog.Nop(), + } + + stateRoot, gotPayloadID, found, err := client.reconcileExecutionAtHeight(t.Context(), 12, spec.requestedTime, spec.requestedTxs) + + require.NoError(t, err) + require.Nil(t, stateRoot) + require.Equal(t, spec.expectFound, found) + require.Equal(t, spec.expectPayloadID, gotPayloadID != nil) + if spec.expectPayloadID { + require.Equal(t, payloadID, *gotPayloadID) + } + require.Equal(t, spec.expectGetPayloads, engineRPC.getPayloadCalls) + }) + } +} + +type mockReconcileEngineRPCClient struct { + payloads map[engine.PayloadID]*engine.ExecutionPayloadEnvelope + getPayloadCalls int +} + +func (m *mockReconcileEngineRPCClient) ForkchoiceUpdated(_ context.Context, _ engine.ForkchoiceStateV1, _ map[string]any) (*engine.ForkChoiceResponse, error) { + return nil, errors.New("unexpected ForkchoiceUpdated call") +} + +func (m *mockReconcileEngineRPCClient) GetPayload(_ context.Context, payloadID engine.PayloadID) (*engine.ExecutionPayloadEnvelope, error) { + m.getPayloadCalls++ + payload, ok := m.payloads[payloadID] + if !ok { + return nil, errors.New("payload not found") + } + + return payload, nil +} + +func (m *mockReconcileEngineRPCClient) NewPayload(_ context.Context, _ *engine.ExecutableData, _ []string, _ string, _ [][]byte) (*engine.PayloadStatusV1, error) { + return nil, errors.New("unexpected NewPayload call") +} + +type mockReconcileEthRPCClient struct{} + +func (mockReconcileEthRPCClient) HeaderByNumber(_ context.Context, _ *big.Int) (*types.Header, error) { + return nil, errors.New("header not found") +} + +func (mockReconcileEthRPCClient) GetTxs(_ context.Context) ([]string, error) { + return nil, errors.New("unexpected GetTxs call") +}