Skip to main content

ef_tests/cases/
engine_test.rs

1//! Test runner for blockchain tests in the engine format.
2//!
3//! Each fixture gets a fresh temporary database with its genesis, and the engine stack a node
4//! builds on it: the engine tree with [`BasicEngineValidator`] and its persistence service, and
5//! the [`EngineApi`] handler. The fixture's parameters go, unchanged, through the handler's
6//! JSON-RPC method table for `engine_newPayloadV<n>` and `engine_forkchoiceUpdatedV<n>` at the
7//! versions the fixture names, so the handler's own parameter decoding and version checks run.
8//! No node, RPC server or network is started.
9
10use crate::{
11    case::{load_json, run_workers},
12    models::{EngineNewPayload, EngineTest},
13    result::{FixtureResult, Rejection},
14    Error,
15};
16use alloy_primitives::B256;
17use alloy_rpc_types_engine::{ClientCode, ClientVersionV1};
18use futures::StreamExt;
19use jsonrpsee::{
20    types::{Response, ResponsePayload},
21    RpcModule,
22};
23use reth_chain_state::{CanonicalInMemoryStateWriter, InMemoryState};
24use reth_chainspec::{ChainSpec, EthChainSpec};
25use reth_db::{
26    init_db,
27    mdbx::{DatabaseArguments, SyncMode},
28    DatabaseEnv,
29};
30use reth_db_common::init::init_genesis_with_settings;
31use reth_engine_primitives::{ConsensusEngineHandle, NoopInvalidBlockHook};
32use reth_engine_tree::{
33    chain::{ChainEvent, FromOrchestrator},
34    engine::{EngineApiKind, EngineRequestHandler},
35    launch::EngineOrchestratorBuilder,
36    tree::{BasicEngineValidator, TreeConfig},
37};
38use reth_eth_wire_types::EthNetworkPrimitives;
39use reth_ethereum_consensus::EthBeaconConsensus;
40use reth_evm_ethereum::EthEvmConfig;
41use reth_network_api::noop::NoopNetwork;
42use reth_network_p2p::full_block::NoopFullBlockClient;
43use reth_node_core::args::EngineArgs;
44use reth_node_ethereum::{EthEngineTypes, EthereumEngineValidator, EthereumNode};
45use reth_node_types::NodeTypesWithDBAdapter;
46use reth_payload_builder::{PayloadBuilderHandle, PayloadStore};
47use reth_provider::{
48    providers::{BlockchainProvider, RocksDBBuilder, RocksDBProvider, StaticFileProvider},
49    BlockNumReader, ProviderFactory, StorageSettings,
50};
51use reth_prune::{PruneModes, PrunerBuilder};
52use reth_rpc_api::EngineApiServer;
53use reth_rpc_engine_api::{EngineApi, EngineCapabilities};
54use reth_stages_api::Pipeline;
55use reth_static_file::StaticFileProducer;
56use reth_storage_overlay::OverlayManager;
57use reth_tasks::Runtime;
58use reth_transaction_pool::noop::NoopTransactionPool;
59use serde_json::{json, Value};
60use std::{
61    collections::BTreeMap,
62    fs,
63    num::NonZeroUsize,
64    path::{Path, PathBuf},
65    sync::{Arc, Mutex},
66    time::Duration,
67};
68use tokio_stream::wrappers::UnboundedReceiverStream;
69
70/// The cross-block cache size of each fixture's engine, in MB (`--engine.cross-block-cache-size`).
71const CROSS_BLOCK_CACHE_SIZE_MB: usize = 1;
72
73/// BAL prewarm workers per fixture engine; production nodes use their normal pool size.
74const BAL_PREWARM_THREADS: NonZeroUsize = NonZeroUsize::new(2).unwrap();
75
76/// The engine tree's persistence threshold (`--engine.persistence-threshold`): more blocks than a
77/// fixture has, so the tree persists them only when it terminates.
78const PERSISTENCE_THRESHOLD: u64 = 1_000_000;
79
80/// How long a fixture's engine tree gets to persist its blocks and stop.
81const ENGINE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(10);
82
83/// Maximum number of fixture runtimes waiting for background database handles per worker.
84const MAX_PENDING_ENGINES: usize = 8;
85
86/// Bound requests so a stopped or stuck engine cannot hang the whole fixture set.
87const ENGINE_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
88
89/// Runs every fixture in the JSON `files` on `workers` threads and passes one result per
90/// fixture to `on_result` as it completes. A file that fails to load is reported as an error,
91/// without creating a fixture result. Each datadir is created in the temporary directory
92/// (`TMPDIR`), where a tmpfs avoids disk syncs, and its genesis is written with `storage_settings`.
93/// Returns an error if the fixture engines cannot be cleaned up completely.
94pub fn run_fixtures(
95    files: Vec<PathBuf>,
96    bal_sequential: bool,
97    storage_settings: StorageSettings,
98    workers: usize,
99    on_result: &(dyn Fn(Result<FixtureResult, Error>) + Sync),
100) -> Result<(), Error> {
101    let tree_config = tree_config(bal_sequential);
102    let datadir_root = std::env::temp_dir();
103    let cleanup_error = Mutex::new(None);
104    let record_error = |err| {
105        let mut first = cleanup_error.lock().unwrap();
106        if first.is_none() {
107            *first = Some(err);
108        } else {
109            eprintln!("error: {err}");
110        }
111    };
112    run_workers(files, workers, |files| {
113        let mut cleanup = Cleanup::default();
114        for path in files {
115            let tests = match load_json::<BTreeMap<String, EngineTest>>(&path) {
116                Ok(tests) => tests,
117                Err(err) => {
118                    on_result(Err(err));
119                    continue
120                }
121            };
122            for (name, test) in tests {
123                let (result, remains) =
124                    run_fixture(name, &test, &tree_config, storage_settings, &datadir_root);
125                on_result(Ok(result));
126                if let Err(err) = cleanup.push(remains) {
127                    record_error(err);
128                    return
129                }
130            }
131        }
132        if let Err(err) = cleanup.finish() {
133            record_error(err);
134        }
135    });
136    cleanup_error.into_inner().unwrap().map_or(Ok(()), Err)
137}
138
139/// Returns the engine tree configuration of the node with the runner's engine arguments.
140fn tree_config(bal_sequential: bool) -> TreeConfig {
141    let engine_args = EngineArgs {
142        bal_parallel_execution_disabled: bal_sequential,
143        // The default 4 GB cache would dominate the memory of concurrent workers.
144        cross_block_cache_size: CROSS_BLOCK_CACHE_SIZE_MB,
145        // Keep a fixture's blocks in memory instead of persisting them while it runs.
146        persistence_threshold: PERSISTENCE_THRESHOLD,
147        ..Default::default()
148    };
149    engine_args.validate().expect("the runner's engine arguments are valid");
150    // Fixtures have their own engine; avoid creating the production pool's 128 threads per case.
151    engine_args.tree_config().with_bal_prewarm_threads(BAL_PREWARM_THREADS)
152}
153
154/// What the engine ended with, reported beside the verdict.
155#[derive(Debug, Default)]
156struct Outcome {
157    last_block_hash: Option<B256>,
158    last_payload_status: Option<String>,
159    rejections: Vec<Rejection>,
160}
161
162/// What a fixture leaves behind: its runtime, on which the engine's background tasks can run
163/// for seconds after the tree stopped, its databases and its datadir.
164struct Remains {
165    runtime: Runtime,
166    databases: Option<Databases>,
167    datadir: Option<PathBuf>,
168}
169
170impl Remains {
171    /// Whether the background tasks released the fixture's databases.
172    fn is_released(&self) -> bool {
173        self.databases.as_ref().is_none_or(Databases::is_released)
174    }
175
176    /// Closes the databases, drops the runtime, joining its threads, and tries to remove the
177    /// datadir. Returns the datadir if a task still writing to it made the removal fail.
178    fn clear(self) -> Option<PathBuf> {
179        let Self { runtime, databases, datadir } = self;
180        drop(databases);
181        drop(runtime);
182        datadir.filter(|datadir| fs::remove_dir_all(datadir).is_err())
183    }
184}
185
186/// A fixture's databases, held by the runner so that they are closed on a worker thread once the
187/// engine's background tasks release them.
188///
189/// A task holding the last provider factory releases the MDBX handle before the `RocksDB` one, and
190/// closing `RocksDB` flushes it. Were it closed on that task's thread, it could still be closing
191/// while the runner moves on or the process exits, which crashes the runner.
192struct Databases {
193    mdbx: Arc<DatabaseEnv>,
194    rocksdb: RocksDBProvider,
195}
196
197impl Databases {
198    /// Whether the runner holds the last handle to each database.
199    fn is_released(&self) -> bool {
200        Arc::strong_count(&self.mdbx) == 1 && self.rocksdb.is_last_handle()
201    }
202}
203
204/// What a worker still has to clean up.
205#[derive(Default)]
206struct Cleanup {
207    remains: Vec<Remains>,
208    datadirs: Vec<PathBuf>,
209}
210
211impl Cleanup {
212    /// Applies backpressure before pending runtimes or directories can grow beyond the limit.
213    fn push(&mut self, remains: Remains) -> Result<(), Error> {
214        self.remains.push(remains);
215        self.sweep();
216        if self.remains.len() >= MAX_PENDING_ENGINES || self.datadirs.len() >= MAX_PENDING_ENGINES {
217            std::mem::take(self).finish()?;
218        }
219        Ok(())
220    }
221
222    /// Clears the remains whose databases were released and retries the datadirs that could not be
223    /// removed yet.
224    fn sweep(&mut self) {
225        let (released, pending): (Vec<_>, Vec<_>) =
226            std::mem::take(&mut self.remains).into_iter().partition(Remains::is_released);
227        self.remains = pending;
228        self.datadirs.retain(|datadir| fs::remove_dir_all(datadir).is_err());
229        self.datadirs.extend(released.into_iter().filter_map(Remains::clear));
230    }
231
232    /// Sweeps until everything is cleaned up or [`ENGINE_SHUTDOWN_TIMEOUT`] passes, then clears
233    /// what is left and reports the datadirs that could not be removed.
234    fn finish(mut self) -> Result<(), Error> {
235        let deadline = std::time::Instant::now() + ENGINE_SHUTDOWN_TIMEOUT;
236        self.sweep();
237        while !(self.remains.is_empty() && self.datadirs.is_empty()) &&
238            std::time::Instant::now() < deadline
239        {
240            std::thread::sleep(Duration::from_millis(10));
241            self.sweep();
242        }
243        let unreleased = self.remains.len();
244        self.datadirs.extend(self.remains.into_iter().filter_map(Remains::clear));
245        for path in self.datadirs {
246            fs::remove_dir_all(&path).map_err(|error| Error::Io { path, error })?;
247        }
248        if unreleased > 0 {
249            return Err(Error::Assertion(format!(
250                "{unreleased} fixture engines retained database handles after shutdown"
251            )))
252        }
253        Ok(())
254    }
255}
256
257/// Runs one fixture against a fresh engine on a runtime of its own, and returns what it leaves
258/// behind.
259///
260/// The runtime is per fixture because the engine's background tasks can outlive a fixture's
261/// tree by seconds, and on a runtime shared with the next fixtures they slowed those by seconds.
262/// The runtime's async tasks stop with the fixture; it is dropped, and the datadir removed, once
263/// the remaining tasks released the databases, from the worker thread rather than from one of
264/// the runtime's own threads, which could not join itself.
265fn run_fixture(
266    name: String,
267    test: &EngineTest,
268    tree_config: &TreeConfig,
269    storage_settings: StorageSettings,
270    datadir_root: &Path,
271) -> (FixtureResult, Remains) {
272    let fork = format!("{:?}", test.network);
273    let mut outcome = Outcome::default();
274    let runtime = Runtime::test();
275    let mut remains = Remains { runtime: runtime.clone(), databases: None, datadir: None };
276    let result = runtime.handle().block_on(run_case(
277        test,
278        tree_config,
279        storage_settings,
280        datadir_root,
281        &runtime,
282        &mut outcome,
283        &mut remains,
284    ));
285    // Join Tokio workers before the next fixture starts, even while `remains` retains a clone.
286    runtime.shutdown_timeout(ENGINE_SHUTDOWN_TIMEOUT);
287    let mut result = FixtureResult::new(name, fork, result).with_rejections(outcome.rejections);
288    result.last_block_hash = outcome.last_block_hash;
289    result.last_payload_status = outcome.last_payload_status;
290    (result, remains)
291}
292
293type FixtureNode = NodeTypesWithDBAdapter<EthereumNode, Arc<DatabaseEnv>>;
294
295async fn run_case(
296    test: &EngineTest,
297    tree_config: &TreeConfig,
298    storage_settings: StorageSettings,
299    datadir_root: &Path,
300    runtime: &Runtime,
301    outcome: &mut Outcome,
302    remains: &mut Remains,
303) -> Result<(), Error> {
304    let chain_spec = Arc::new(test.chain_spec()?);
305    let genesis_hash = chain_spec.genesis_hash();
306    if genesis_hash != test.genesis_block_header.hash {
307        return Err(Error::Assertion(format!(
308            "genesis hash mismatch: the chain spec has {genesis_hash}, the fixture {}",
309            test.genesis_block_header.hash
310        )))
311    }
312
313    let datadir = tempfile::Builder::new()
314        .prefix("reth-enginetest-")
315        .tempdir_in(datadir_root)
316        .map_err(|err| Error::Io { path: datadir_root.to_path_buf(), error: err })?
317        .keep();
318    remains.datadir = Some(datadir.clone());
319    let engine = Engine::start(chain_spec, &datadir, tree_config, storage_settings, runtime)?;
320    let result = drive(&engine.rpc, test, outcome).await;
321    let head = engine.provider.chain_info().map(|info| info.best_hash);
322    let (databases, shutdown) = engine.stop().await;
323    remains.databases = Some(databases);
324    outcome.last_block_hash = Some(head?);
325    result?;
326    shutdown?;
327
328    match outcome.last_block_hash {
329        Some(hash) if hash == test.lastblockhash => Ok(()),
330        hash => Err(Error::Assertion(format!(
331            "last block hash mismatch: got {hash:?}, expected {}",
332            test.lastblockhash
333        ))),
334    }
335}
336
337/// The engine stack of one fixture, wired as the node's engine launcher wires it,
338/// without the network, the RPC servers, the transaction pool or the payload builder, which the
339/// fixtures do not reach.
340struct Engine {
341    /// The `engine_` JSON-RPC methods of the [`EngineApi`] handler.
342    rpc: RpcModule<()>,
343    provider: BlockchainProvider<FixtureNode>,
344    databases: Databases,
345    handler: tokio::task::JoinHandle<()>,
346    to_handler: tokio::sync::mpsc::UnboundedSender<FromOrchestrator>,
347}
348
349impl Engine {
350    fn start(
351        chain_spec: Arc<ChainSpec>,
352        datadir: &Path,
353        tree_config: &TreeConfig,
354        storage_settings: StorageSettings,
355        runtime: &Runtime,
356    ) -> Result<Self, Error> {
357        let db = Arc::new(
358            init_db(
359                datadir.join("db"),
360                // The database is thrown away after the fixture, so skip MDBX's durable syncs
361                // (`--db.sync-mode safe-no-sync`).
362                DatabaseArguments::test().with_sync_mode(Some(SyncMode::SafeNoSync)),
363            )
364            .map_err(|err| Error::engine("failed to set up the engine", err))?,
365        );
366        let rocksdb = RocksDBBuilder::new(datadir.join("rocksdb"))
367            .with_default_tables()
368            .build()
369            .map_err(|err| Error::engine("failed to set up the engine", err))?;
370        let (in_memory_state, in_memory_state_writer) = InMemoryState::new();
371        let overlay_manager = OverlayManager::with_worker_pool(
372            in_memory_state,
373            runtime.state_trie_overlay_worker_pool(),
374        );
375        let factory = ProviderFactory::<FixtureNode>::new(
376            db.clone(),
377            chain_spec.clone(),
378            StaticFileProvider::read_write(datadir.join("static_files"))
379                .map_err(|err| Error::engine("failed to set up the engine", err))?,
380            rocksdb.clone(),
381            overlay_manager.clone(),
382            runtime.clone(),
383        )
384        .map_err(|err| Error::engine("failed to set up the engine", err))?;
385        init_genesis_with_settings(&factory, storage_settings)
386            .map_err(|err| Error::engine("failed to set up the engine", err))?;
387        let canonical_in_memory_state_writer = CanonicalInMemoryStateWriter::new(
388            factory
389                .chain_info_headers()
390                .map_err(|err| Error::engine("failed to set up the engine", err))?,
391            in_memory_state_writer,
392        );
393        let provider = BlockchainProvider::with_canonical_in_memory_state(
394            factory.clone(),
395            canonical_in_memory_state_writer.canonical_in_memory_state().clone(),
396        );
397
398        let consensus = Arc::new(EthBeaconConsensus::new(chain_spec.clone()));
399        let evm_config = EthEvmConfig::new(chain_spec.clone());
400        let validator = BasicEngineValidator::new(
401            provider.clone(),
402            consensus.clone(),
403            evm_config.clone(),
404            EthereumEngineValidator::new(chain_spec.clone()),
405            tree_config.clone(),
406            Box::new(NoopInvalidBlockHook::default()),
407            overlay_manager.clone(),
408            runtime.clone(),
409        );
410        let payload_builder = PayloadBuilderHandle::<EthEngineTypes>::noop();
411        let (to_engine, from_api) = tokio::sync::mpsc::unbounded_channel();
412        let (sync_metrics_tx, _) = tokio::sync::mpsc::unbounded_channel();
413        // Built as the node's engine launcher builds it. A fixture's payloads extend blocks the
414        // engine already has, so nothing is downloaded or backfilled: the block client is a no-op
415        // and the backfill pipeline has no stages.
416        let mut orchestrator = EngineOrchestratorBuilder {
417            engine_kind: EngineApiKind::Ethereum,
418            consensus,
419            client: NoopFullBlockClient::<EthNetworkPrimitives>::default(),
420            incoming_requests: UnboundedReceiverStream::new(from_api),
421            pipeline: Pipeline::<FixtureNode>::builder().build(
422                factory.clone(),
423                StaticFileProducer::new(factory.clone(), PruneModes::default()),
424            ),
425            pipeline_task_spawner: runtime.clone(),
426            provider: factory.clone(),
427            blockchain_db: provider.clone(),
428            canonical_in_memory_state_writer,
429            pruner: PrunerBuilder::default().build_with_provider_factory(factory),
430            payload_builder: payload_builder.clone(),
431            payload_validator: validator,
432            overlay_manager,
433            tree_config: tree_config.clone(),
434            sync_metrics_tx,
435            evm_config,
436            runtime: runtime.clone(),
437        }
438        .build();
439
440        // Polls the orchestrator as the node's consensus engine task does, without the network
441        // and event bookkeeping, and passes on the runner's terminate request.
442        let (to_handler, mut from_runner) =
443            tokio::sync::mpsc::unbounded_channel::<FromOrchestrator>();
444        let handler = runtime.handle().spawn(async move {
445            loop {
446                tokio::select! {
447                    event = orchestrator.next() => {
448                        if matches!(event, None | Some(ChainEvent::FatalError)) {
449                            break
450                        }
451                    }
452                    Some(event) = from_runner.recv() => {
453                        orchestrator.handler_mut().handler_mut().on_event(event.into());
454                    }
455                }
456            }
457        });
458
459        let api = EngineApi::new(
460            provider.clone(),
461            chain_spec.clone(),
462            ConsensusEngineHandle::new(to_engine),
463            PayloadStore::new(payload_builder),
464            NoopTransactionPool::default(),
465            runtime.clone(),
466            ClientVersionV1 {
467                code: ClientCode::RH,
468                name: "reth".to_string(),
469                version: env!("CARGO_PKG_VERSION").to_string(),
470                commit: String::new(),
471            },
472            EngineCapabilities::default(),
473            EthereumEngineValidator::new(chain_spec),
474            false,
475            NoopNetwork::default(),
476        );
477
478        let databases = Databases { mdbx: db, rocksdb };
479        Ok(Self { rpc: api.into_rpc().remove_context(), provider, databases, handler, to_handler })
480    }
481
482    /// Asks the engine tree to persist its blocks and stop, as a node does on shutdown, and
483    /// returns the databases, which background tasks may still hold.
484    async fn stop(self) -> (Databases, Result<(), Error>) {
485        let Self { rpc, provider, databases, handler, to_handler } = self;
486        drop(rpc);
487        let (tx, rx) = tokio::sync::oneshot::channel();
488        let shutdown = if to_handler.send(FromOrchestrator::Terminate { tx }).is_ok() {
489            match tokio::time::timeout(ENGINE_SHUTDOWN_TIMEOUT, rx).await {
490                Ok(result) => {
491                    result.map_err(|err| Error::engine("engine stopped before persisting", err))
492                }
493                Err(err) => Err(Error::engine("timed out stopping the engine", err)),
494            }
495        } else {
496            Err(Error::Assertion("engine handler stopped before termination".to_string()))
497        };
498        handler.abort();
499        let joined = match tokio::time::timeout(ENGINE_SHUTDOWN_TIMEOUT, handler).await {
500            Ok(Ok(())) => Ok(()),
501            Ok(Err(err)) if err.is_cancelled() => Ok(()),
502            Ok(Err(err)) => Err(Error::engine("engine handler panicked", err)),
503            Err(err) => Err(Error::engine("timed out joining the engine handler", err)),
504        };
505        drop(provider);
506        (databases, shutdown.and(joined))
507    }
508}
509
510/// Sends the fixture's payloads in order, each valid one followed by a forkchoice update that
511/// makes it the head, as a consensus client would.
512async fn drive(rpc: &RpcModule<()>, test: &EngineTest, outcome: &mut Outcome) -> Result<(), Error> {
513    let Some(first) = test.engine_new_payloads.first() else { return Ok(()) };
514    forkchoice_updated(rpc, &first.forkchoice_updated_version, test.genesis_block_header.hash)
515        .await?;
516
517    for (idx, payload) in test.engine_new_payloads.iter().enumerate() {
518        new_payload(rpc, idx, payload, outcome).await?;
519        if payload.validation_error.is_none() && payload.error_code.is_none() {
520            let head = payload.params[0]["blockHash"].as_str().unwrap_or_default();
521            let head = head.parse().map_err(|err| {
522                Error::Assertion(format!("payload {idx}: invalid blockHash {head:?}: {err}"))
523            })?;
524            forkchoice_updated(rpc, &payload.forkchoice_updated_version, head).await?;
525        }
526    }
527    Ok(())
528}
529
530/// A JSON-RPC error returned by the handler.
531#[derive(Debug)]
532struct RpcError {
533    code: i64,
534    message: String,
535    data: Option<Value>,
536}
537
538impl std::error::Error for RpcError {}
539
540impl std::fmt::Display for RpcError {
541    /// Formats the error as `<code>: <message>`, followed by `: <data>` when it carries data: a
542    /// string as is, anything else as compact JSON.
543    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
544        write!(f, "{}: {}", self.code, self.message)?;
545        match &self.data {
546            None | Some(Value::Null) => Ok(()),
547            Some(Value::String(data)) => write!(f, ": {data}"),
548            Some(data) => write!(f, ": {data}"),
549        }
550    }
551}
552
553/// Separates dispatch failures from client JSON-RPC responses, so a timeout is never reported as
554/// a rejected payload or matched against a fixture's `errorCode`.
555async fn call(
556    rpc: &RpcModule<()>,
557    method: &str,
558    params: Value,
559) -> Result<Result<Value, RpcError>, Error> {
560    let request =
561        json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).to_string();
562    let (response, _) =
563        tokio::time::timeout(ENGINE_REQUEST_TIMEOUT, rpc.raw_json_request(&request, 1))
564            .await
565            .map_err(|err| Error::engine(format!("{method} timed out"), err))?
566            .map_err(|err| Error::engine(method, err))?;
567    let response: Response<'_, Value> = serde_json::from_str(&response)
568        .map_err(|err| Error::engine(format!("cannot decode {method} response"), err))?;
569    Ok(match response.payload {
570        ResponsePayload::Success(result) => Ok(result.into_owned()),
571        ResponsePayload::Error(error) => Err(RpcError {
572            code: i64::from(error.code()),
573            message: error.message().to_string(),
574            data: error
575                .data()
576                .map(|data| serde_json::from_str(data.get()))
577                .transpose()
578                .map_err(|err| Error::engine(format!("cannot decode {method} error data"), err))?,
579        }),
580    })
581}
582
583/// Calls `engine_newPayloadV<n>` with the fixture's payload at `index`, records a rejection
584/// with reth's error, and checks the response against the fixture's expectation.
585async fn new_payload(
586    rpc: &RpcModule<()>,
587    index: usize,
588    payload: &EngineNewPayload,
589    outcome: &mut Outcome,
590) -> Result<(), Error> {
591    let method = format!("engine_newPayloadV{}", payload.new_payload_version);
592    let expected_code = payload
593        .error_code
594        .as_deref()
595        .map(str::parse::<i64>)
596        .transpose()
597        .map_err(|err| Error::engine("invalid fixture errorCode", err))?;
598
599    match call(rpc, &method, Value::from(payload.params.clone())).await? {
600        Ok(response) => {
601            let status = response["status"].as_str().unwrap_or_default().to_string();
602            outcome.last_payload_status = Some(status.clone());
603            if matches!(status.as_str(), "INVALID" | "INVALID_BLOCK_HASH") {
604                let error = response["validationError"].as_str().unwrap_or_default().to_string();
605                outcome.rejections.push(Rejection { index, hash: None, error });
606            }
607            let expected = if payload.validation_error.is_some() { "INVALID" } else { "VALID" };
608            if status != expected {
609                return Err(Error::Assertion(format!(
610                    "{method} returned {response}, expected status {expected}"
611                )))
612            }
613            if let Some(code) = expected_code {
614                return Err(Error::Assertion(format!(
615                    "{method} returned {response}, expected error code {code}"
616                )))
617            }
618            Ok(())
619        }
620        Err(err) => {
621            let code = err.code;
622            outcome.last_payload_status = Some(format!("error {code}"));
623            outcome.rejections.push(Rejection { index, hash: None, error: err.to_string() });
624            if expected_code == Some(code) {
625                Ok(())
626            } else {
627                Err(Error::engine(method, err))
628            }
629        }
630    }
631}
632
633/// Calls `engine_forkchoiceUpdatedV<n>` without payload attributes and requires a valid head.
634async fn forkchoice_updated(rpc: &RpcModule<()>, version: &str, head: B256) -> Result<(), Error> {
635    let method = format!("engine_forkchoiceUpdatedV{version}");
636    let state = json!({
637        "headBlockHash": head,
638        "safeBlockHash": B256::ZERO,
639        "finalizedBlockHash": B256::ZERO,
640    });
641    let response = call(rpc, &method, json!([state, null]))
642        .await?
643        .map_err(|err| Error::engine(&method, err))?;
644    match response["payloadStatus"]["status"].as_str() {
645        Some("VALID") => Ok(()),
646        _ => Err(Error::Assertion(format!("{method} returned {response}, expected status VALID"))),
647    }
648}
649
650#[cfg(test)]
651mod tests {
652    use super::*;
653    use crate::models::{ForkSpec, Header, State};
654    use alloy_consensus::{
655        proofs::calculate_transaction_root, SignableTransaction, TxLegacy, EMPTY_OMMER_ROOT_HASH,
656        EMPTY_ROOT_HASH,
657    };
658    use alloy_eips::{eip1559::BaseFeeParams, eip2718::Encodable2718};
659    use alloy_primitives::{Address, Bloom, Bytes, Signature, TxKind, U256, U64};
660    use alloy_rpc_types_engine::ExecutionPayloadV1;
661    use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
662    use reth_evm::{database::StateProviderDatabase, ConfigureEvm, Evm};
663    use reth_primitives_traits::{SignedTransaction, SignerRecoverable};
664    use reth_provider::{
665        test_utils::{ExtendedAccount, MockEthProvider},
666        DatabaseProviderFactory, StateProvider, StorageSettingsCache,
667    };
668    use std::process::Command;
669
670    /// A Paris fixture whose one payload is an empty block on genesis with the given state root,
671    /// and that payload's block hash.
672    fn empty_block_fixture(state_root: Option<B256>) -> (EngineTest, B256) {
673        block_fixture(State::default(), Vec::new(), state_root)
674    }
675
676    fn block_fixture(
677        pre: State,
678        transactions: Vec<TransactionSigned>,
679        state_root: Option<B256>,
680    ) -> (EngineTest, B256) {
681        let mut test = EngineTest {
682            genesis_block_header: Header {
683                gas_limit: U256::from(30_000_000),
684                base_fee_per_gas: Some(U256::from(1_000_000_000)),
685                ..Default::default()
686            },
687            pre,
688            lastblockhash: B256::ZERO,
689            network: ForkSpec::Merge,
690            config: Default::default(),
691            engine_new_payloads: Vec::new(),
692        };
693        let chain_spec = test.chain_spec().unwrap();
694        let genesis = chain_spec.genesis_header();
695        test.genesis_block_header.hash = chain_spec.genesis_hash();
696
697        let header = alloy_consensus::Header {
698            parent_hash: chain_spec.genesis_hash(),
699            ommers_hash: EMPTY_OMMER_ROOT_HASH,
700            state_root: state_root.unwrap_or(genesis.state_root),
701            transactions_root: calculate_transaction_root(&transactions),
702            receipts_root: EMPTY_ROOT_HASH,
703            number: 1,
704            gas_limit: genesis.gas_limit,
705            timestamp: 12,
706            base_fee_per_gas: genesis.next_block_base_fee(BaseFeeParams::ethereum()),
707            ..Default::default()
708        };
709        let block_hash = header.hash_slow();
710        let payload = ExecutionPayloadV1 {
711            parent_hash: header.parent_hash,
712            fee_recipient: Address::ZERO,
713            state_root: header.state_root,
714            receipts_root: header.receipts_root,
715            logs_bloom: Bloom::ZERO,
716            prev_randao: B256::ZERO,
717            block_number: header.number,
718            gas_limit: header.gas_limit,
719            gas_used: 0,
720            timestamp: header.timestamp,
721            extra_data: Default::default(),
722            base_fee_per_gas: U256::from(header.base_fee_per_gas.unwrap()),
723            block_hash,
724            transactions: transactions.into_iter().map(|tx| tx.encoded_2718().into()).collect(),
725        };
726        test.engine_new_payloads.push(EngineNewPayload {
727            params: vec![serde_json::to_value(payload).unwrap()],
728            new_payload_version: "1".to_string(),
729            forkchoice_updated_version: "1".to_string(),
730            validation_error: None,
731            error_code: None,
732        });
733        (test, block_hash)
734    }
735
736    /// Runs a fixture as a worker does and checks that its datadir is removed.
737    fn run(test: &EngineTest) -> FixtureResult {
738        let datadir_root = tempfile::tempdir().unwrap();
739        let (result, remains) = run_fixture(
740            "test".to_string(),
741            test,
742            &tree_config(false),
743            StorageSettings::base(),
744            datadir_root.path(),
745        );
746        let mut cleanup = Cleanup::default();
747        cleanup.remains.push(remains);
748        cleanup.finish().unwrap();
749        assert_eq!(fs::read_dir(datadir_root.path()).unwrap().count(), 0, "datadir left behind");
750        result
751    }
752
753    #[test]
754    fn engine_runs_on_the_given_storage_layout() {
755        for storage_settings in [StorageSettings::v2(), StorageSettings::v1()] {
756            let (test, _) = empty_block_fixture(None);
757            let datadir_root = tempfile::tempdir().unwrap();
758            let datadir = datadir_root.path().join("datadir");
759            fs::create_dir(&datadir).unwrap();
760            let runtime = Runtime::test();
761            let databases = runtime.handle().block_on(async {
762                let engine = Engine::start(
763                    Arc::new(test.chain_spec().unwrap()),
764                    &datadir,
765                    &tree_config(false),
766                    storage_settings,
767                    &runtime,
768                )
769                .unwrap();
770                let stored =
771                    engine.provider.database_provider_ro().unwrap().cached_storage_settings();
772                assert_eq!(stored, storage_settings);
773                let (databases, shutdown) = engine.stop().await;
774                shutdown.unwrap();
775                databases
776            });
777            runtime.clone().shutdown_timeout(ENGINE_SHUTDOWN_TIMEOUT);
778            let mut cleanup = Cleanup::default();
779            cleanup.remains.push(Remains {
780                runtime,
781                databases: Some(databases),
782                datadir: Some(datadir),
783            });
784            cleanup.finish().unwrap();
785            let left = fs::read_dir(datadir_root.path()).unwrap().count();
786            assert_eq!(left, 0, "datadir left behind");
787        }
788    }
789
790    #[test]
791    fn valid_payload_becomes_head() {
792        let (mut test, block_hash) = empty_block_fixture(None);
793        test.lastblockhash = block_hash;
794
795        let result = run(&test);
796        assert!(result.pass, "{}", result.error);
797        assert_eq!(result.last_block_hash, Some(block_hash));
798        assert_eq!(result.last_payload_status.as_deref(), Some("VALID"));
799        assert_eq!(result.rejections, []);
800    }
801
802    #[test]
803    fn invalid_payload_is_rejected() {
804        let (mut test, _) = empty_block_fixture(Some(B256::repeat_byte(1)));
805        test.lastblockhash = test.genesis_block_header.hash;
806        test.engine_new_payloads[0].validation_error = Some("state root mismatch".to_string());
807
808        let result = run(&test);
809        assert!(result.pass, "{}", result.error);
810        assert_eq!(result.last_block_hash, Some(test.genesis_block_header.hash));
811        assert_eq!(result.last_payload_status.as_deref(), Some("INVALID"));
812        let [rejection] = result.rejections.as_slice() else { panic!("{:?}", result.rejections) };
813        assert_eq!(rejection.index, 0);
814        assert!(rejection.error.contains("mismatched block state root"), "{}", rejection.error);
815    }
816
817    #[test]
818    fn payload_rejected_with_an_rpc_error() {
819        // Paris has no `engine_newPayloadV3`, and V3 takes three parameters, not one.
820        let (mut test, _) = empty_block_fixture(None);
821        test.lastblockhash = test.genesis_block_header.hash;
822        test.engine_new_payloads[0].new_payload_version = "3".to_string();
823        test.engine_new_payloads[0].error_code = Some("-32602".to_string());
824
825        let result = run(&test);
826        assert!(result.pass, "{}", result.error);
827        let [rejection] = result.rejections.as_slice() else { panic!("{:?}", result.rejections) };
828        assert_eq!(rejection.index, 0);
829        assert!(rejection.error.starts_with("-32602: "), "{}", rejection.error);
830    }
831
832    #[test]
833    fn unexpected_verdict_fails() {
834        let (mut test, block_hash) = empty_block_fixture(Some(B256::repeat_byte(1)));
835        test.lastblockhash = block_hash;
836
837        let result = run(&test);
838        assert!(!result.pass);
839        assert_eq!(result.last_payload_status.as_deref(), Some("INVALID"));
840    }
841    /// A protected transaction calling a contract on a chain chosen by the fixture, with a
842    /// deliberately wrong gas-used header so completed execution returns INVALID.
843    fn transaction_fixture(chain_id: u64, code: Bytes) -> EngineTest {
844        let contract = Address::with_last_byte(0x42);
845        let tx = TransactionSigned::Legacy(
846            TxLegacy {
847                chain_id: Some(1),
848                nonce: 0,
849                gas_limit: 30_000_000,
850                gas_price: 1_000_000_000,
851                to: TxKind::Call(contract),
852                ..Default::default()
853            }
854            .into_signed(Signature::test_signature()),
855        );
856        let sender = tx.recover_signer().unwrap();
857        let pre = serde_json::from_value(json!({
858            sender.to_string(): {"balance": "0xffffffffffffffffffffffff", "nonce": "0x0", "code": "0x", "storage": {}},
859            contract.to_string(): {"balance": "0x0", "nonce": "0x1", "code": code, "storage": {}}
860        })).unwrap();
861        let (mut test, _) = block_fixture(pre, vec![tx], Some(B256::repeat_byte(1)));
862        test.config.chain_id = Some(U64::from(chain_id));
863        test.lastblockhash = test.genesis_block_header.hash;
864        test.engine_new_payloads[0].validation_error = Some("invalid block".to_string());
865        test
866    }
867
868    #[test]
869    fn protected_transaction_uses_fixture_chain_id() {
870        let result = run(&transaction_fixture(7, Bytes::from_static(&[0x00])));
871        assert!(result.pass, "{}", result.error);
872        assert_eq!(result.last_payload_status.as_deref(), Some("INVALID"));
873        assert_eq!(result.rejections.len(), 1);
874        assert_eq!(
875            result.rejections[0].error,
876            "EVM reported invalid transaction (0xb74c71ef0df77555a822630371d46d129d235b18edb45f1ad1f646ef7beb4f11): invalid chain id: expected 7, got 1"
877        );
878    }
879
880    #[test]
881    fn deeply_nested_calls_fit_the_engine_thread_stack() {
882        with_runner_stack("deeply_nested_calls_fit_the_engine_thread_stack", || {
883            // Repeated CALL to ADDRESS with all remaining gas recurses until the EIP-150 gas bound.
884            let code = Bytes::from_static(&[
885                0x60, 0, 0x60, 0, 0x60, 0, 0x60, 0, 0x60, 0, 0x30, 0x5a, 0xf1, 0x00,
886            ]);
887            let result = run(&transaction_fixture(1, code));
888            assert!(result.pass, "{}", result.error);
889            assert_eq!(result.last_payload_status.as_deref(), Some("INVALID"));
890            assert_eq!(result.rejections.len(), 1);
891            assert!(
892                result.rejections[0].error.starts_with("block gas used mismatch:"),
893                "{}",
894                result.rejections[0].error
895            );
896        });
897    }
898
899    #[test]
900    fn deeply_nested_calls_fit_speculative_worker_stacks() {
901        with_runner_stack("deeply_nested_calls_fit_speculative_worker_stacks", || {
902            let runtime = Runtime::test();
903            for pool in [runtime.prewarming_pool(), runtime.bal_streaming_pool()] {
904                pool.install_fn(|| {
905                    let sender = Address::with_last_byte(0x41);
906                    let contract = Address::with_last_byte(0x42);
907                    let provider = MockEthProvider::<EthPrimitives>::default();
908                    provider.add_account(sender, ExtendedAccount::new(0, U256::MAX));
909                    provider.add_account(
910                        contract,
911                        ExtendedAccount::new(1, U256::ZERO).with_bytecode(Bytes::from_static(&[
912                            0x60, 0, 0x60, 0, 0x60, 0, 0x60, 0, 0x60, 0, 0x30, 0x5a, 0xf1, 0x00,
913                        ])),
914                    );
915                    let config = EthEvmConfig::new(ForkSpec::Merge.to_chain_spec());
916                    let env = config
917                        .evm_env(&alloy_consensus::Header {
918                            gas_limit: 30_000_000,
919                            base_fee_per_gas: Some(0),
920                            ..Default::default()
921                        })
922                        .unwrap();
923                    let tx = TransactionSigned::Legacy(
924                        TxLegacy {
925                            chain_id: Some(1),
926                            gas_limit: 30_000_000,
927                            to: TxKind::Call(contract),
928                            ..Default::default()
929                        }
930                        .into_signed(Signature::test_signature()),
931                    );
932                    let tx = config.tx_env(tx.with_signer(sender));
933                    let mut evm = config.evm_with_env(
934                        StateProviderDatabase(provider.into_evm_state_provider()),
935                        env,
936                    );
937                    evm.transact_and_discard(&tx, |_| {}).unwrap();
938                });
939            }
940        });
941    }
942
943    #[test]
944    fn fixture_configuration_errors_are_reported_without_starting_an_engine() {
945        let (mut test, _) = empty_block_fixture(None);
946        test.network = ForkSpec::MergePush0;
947        let result = run(&test);
948        assert!(!result.pass);
949        assert_eq!(result.error, "unsupported fixture fork: MergePush0");
950        test.network = ForkSpec::Merge;
951        test.genesis_block_header.gas_limit = U256::from(u64::MAX) + U256::ONE;
952        let result = run(&test);
953        assert!(!result.pass);
954        assert_eq!(result.last_payload_status, None);
955        assert!(result.rejections.is_empty());
956    }
957
958    #[tokio::test(start_paused = true)]
959    async fn request_timeout_is_not_a_payload_rejection() {
960        let mut rpc = RpcModule::new(());
961        rpc.register_async_method("engine_newPayloadV1", |_, _| async {
962            std::future::pending::<Result<Value, jsonrpsee::types::ErrorObjectOwned>>().await
963        })
964        .unwrap();
965        let (test, _) = empty_block_fixture(None);
966        let mut outcome = Outcome::default();
967        let error =
968            new_payload(&rpc, 0, &test.engine_new_payloads[0], &mut outcome).await.unwrap_err();
969        assert_eq!(error.to_string(), "engine_newPayloadV1 timed out: deadline has elapsed");
970        assert_eq!(outcome.rejections, []);
971        assert_eq!(outcome.last_payload_status, None);
972    }
973
974    #[test]
975    fn cleanup_keeps_pending_runtimes_bounded() {
976        let dir = tempfile::tempdir().unwrap();
977        let mut cleanup = Cleanup::default();
978        let (mut test, hash) = empty_block_fixture(None);
979        test.lastblockhash = hash;
980        for _ in 0..MAX_PENDING_ENGINES * 2 {
981            let (result, remains) = run_fixture(
982                "test".to_string(),
983                &test,
984                &tree_config(false),
985                StorageSettings::base(),
986                dir.path(),
987            );
988            assert!(result.pass, "{}", result.error);
989            cleanup.push(remains).unwrap();
990            assert!(cleanup.remains.len() < MAX_PENDING_ENGINES);
991            assert!(cleanup.datadirs.len() < MAX_PENDING_ENGINES);
992        }
993        cleanup.finish().unwrap();
994        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 0);
995    }
996
997    #[test]
998    fn fixture_engines_bound_bal_prewarm_workers_without_disabling_parallel_execution() {
999        let config = tree_config(false);
1000        assert_eq!(config.bal_prewarm_threads(), Some(BAL_PREWARM_THREADS));
1001        assert!(!config.disable_bal_parallel_execution());
1002        assert_eq!(TreeConfig::default().bal_prewarm_threads(), None);
1003    }
1004
1005    /// Exercises deep calls in a process started with the runner's stack policy, without
1006    /// changing environment variables while the test harness has other threads running.
1007    fn with_runner_stack(test: &str, run: impl FnOnce()) {
1008        let minimum_stack_size = 8 * 1024 * 1024;
1009        if matches!(std::env::var("RUST_MIN_STACK"), Ok(value) if value.parse::<usize>().is_ok_and(|size| size >= minimum_stack_size))
1010        {
1011            run();
1012            return
1013        }
1014        let module = module_path!().split_once("::").unwrap().1;
1015        let test = format!("{module}::{test}");
1016        let output = Command::new(std::env::current_exe().unwrap())
1017            .env("RUST_MIN_STACK", minimum_stack_size.to_string())
1018            .args(["--exact", &test, "--color", "never"])
1019            .output()
1020            .unwrap();
1021        assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
1022        let stdout = String::from_utf8(output.stdout).unwrap();
1023        let expected = format!("test {test} ... ok");
1024        assert!(stdout.lines().any(|line| line == expected), "{stdout}");
1025    }
1026}