Skip to main content

ef_tests/cases/
blockchain_test.rs

1//! Test runners for `BlockchainTests` in <https://github.com/ethereum/tests>
2
3use crate::{
4    case::{load_json, run_workers},
5    models::{BlockchainTest, ForkSpec},
6    result::{FixtureResult, Rejection},
7    Case, Error, Suite,
8};
9use alloy_eip7928::{
10    bal::{Bal, RawBal},
11    BlockAccessList,
12};
13use alloy_eips::{
14    eip7002::WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, eip7251::CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS,
15};
16use alloy_primitives::B256;
17use alloy_rlp::Decodable;
18use rayon::iter::{IndexedParallelIterator, ParallelIterator};
19use reth_chainspec::{ChainSpec, EthereumHardforks};
20use reth_consensus::{Consensus, ConsensusError, HeaderValidator};
21use reth_db_common::init::{insert_genesis_hashes, insert_genesis_history, insert_genesis_state};
22use reth_ethereum_consensus::{validate_block_post_execution, EthBeaconConsensus};
23use reth_ethereum_primitives::Block;
24use reth_evm::{
25    database::StateProviderDatabase, execute::BlockExecutor, BlockExecutorFor, ConfigureEvm,
26};
27use reth_evm_ethereum::EthEvmConfig;
28use reth_primitives_traits::{
29    GotExpected, ParallelBridgeBuffered, RecoveredBlock, SealedBlock, SealedHeader,
30};
31use reth_provider::{
32    providers::{RocksDBBuilder, RocksDBProvider, StaticFileProviderBuilder},
33    test_utils::MockNodeTypesWithDB,
34    BlockWriter, DatabaseProviderFactory, ExecutionOutcome, HashedPostStateProvider, HistoryWriter,
35    OriginalValuesKnown, ProviderError, ProviderFactory, StateProvider, StateWriteConfig,
36    StateWriter, StaticFileProviderFactory, StaticFileSegment, StaticFileWriter,
37    StorageSettingsCache, TrieWriter,
38};
39use reth_storage_overlay::OverlayManager;
40use reth_tasks::Runtime;
41use reth_trie::StateRoot;
42use reth_trie_db::DatabaseStateRoot;
43use std::{
44    collections::BTreeMap,
45    fs,
46    path::{Path, PathBuf},
47    sync::{Arc, Mutex},
48};
49use tracing::debug;
50
51/// A handler for the blockchain test suite.
52#[derive(Debug)]
53pub struct BlockchainTests {
54    suite_path: PathBuf,
55}
56
57impl BlockchainTests {
58    /// Create a new suite for tests with blockchain tests format.
59    pub const fn new(suite_path: PathBuf) -> Self {
60        Self { suite_path }
61    }
62
63    /// Runs every fixture in the JSON `files`, one file at a time on each of `workers` threads,
64    /// and passes one result per fixture to `on_result` as it completes.
65    ///
66    /// Reports a file that fails to load as an error, without creating a fixture result.
67    ///
68    /// The files are not run on the rayon pool: a rayon thread waiting on block execution's own
69    /// parallel work would start other files meanwhile, with no bound on how many are open.
70    pub fn run_fixtures(
71        files: Vec<PathBuf>,
72        options: BlockTestOptions,
73        workers: usize,
74        on_result: &(dyn Fn(Result<FixtureResult, Error>) + Sync),
75    ) {
76        run_workers(files, workers, |files| {
77            for path in files {
78                Self::run_file(&path, options, on_result);
79            }
80        });
81    }
82
83    /// Runs every fixture in the JSON file at `path` and passes one result per fixture to
84    /// `on_result`.
85    fn run_file(
86        path: &Path,
87        options: BlockTestOptions,
88        on_result: &dyn Fn(Result<FixtureResult, Error>),
89    ) {
90        let tests = match load_json::<BTreeMap<String, BlockchainTest>>(path) {
91            Ok(tests) => tests,
92            Err(err) => return on_result(Err(err)),
93        };
94        for (name, test) in tests {
95            let fork = format!("{:?}", test.network);
96            let mut last_block_hash = test.genesis_block_header.hash;
97            let mut rejections = Vec::new();
98            let result = run_case(&name, &test, options, &mut last_block_hash, &mut rejections)
99                .and_then(|()| {
100                    if last_block_hash != test.lastblockhash {
101                        return Err(Error::Assertion(format!(
102                            "last block hash mismatch: got {last_block_hash}, expected {}",
103                            test.lastblockhash
104                        )))
105                    }
106                    Ok(())
107                });
108            on_result(Ok(FixtureResult::new(name, fork, result)
109                .with_last_block_hash(last_block_hash)
110                .with_rejections(rejections)));
111        }
112    }
113}
114
115impl Suite for BlockchainTests {
116    type Case = BlockchainTestCase;
117
118    fn suite_path(&self) -> &Path {
119        &self.suite_path
120    }
121}
122
123/// Options for running blockchain tests.
124#[derive(Debug, Clone, Copy, Default)]
125pub struct BlockTestOptions {
126    /// Whether blocks run on the sequential executor, as with the node's
127    /// `--engine.disable-bal-parallel-execution`. Block import always runs the sequential
128    /// executor, so this only changes the reported reason.
129    pub bal_sequential: bool,
130    /// Whether blocks execute without the access list the fixture delivers, as a block received
131    /// without its list does.
132    pub bal_withhold: bool,
133}
134
135/// An Ethereum blockchain test.
136#[derive(Debug, PartialEq, Eq)]
137pub struct BlockchainTestCase {
138    /// The tests within this test case.
139    pub tests: BTreeMap<String, BlockchainTest>,
140    /// Whether to skip this test case.
141    pub skip: bool,
142}
143
144impl BlockchainTestCase {
145    /// Returns `true` if the fork is not supported.
146    const fn excluded_fork(network: ForkSpec) -> bool {
147        matches!(
148            network,
149            ForkSpec::ByzantiumToConstantinopleAt5 |
150                ForkSpec::Constantinople |
151                ForkSpec::ConstantinopleFix |
152                ForkSpec::MergeEOF |
153                ForkSpec::MergeMeterInitCode |
154                ForkSpec::MergePush0
155        )
156    }
157
158    /// Returns `true` if the case runs Prague blocks without the EIP-7002 and EIP-7251 request
159    /// contracts, which makes them invalid. Legacy fixtures predate those predeploys, and their
160    /// state roots rule out adding them.
161    fn lacks_request_contracts(case: &BlockchainTest) -> bool {
162        case.network.to_chain_spec().is_prague_active_at_timestamp(u64::MAX) &&
163            [WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS]
164                .into_iter()
165                .any(|address| {
166                    case.pre.get(&address).is_none_or(|account| account.code.is_empty())
167                })
168    }
169
170    /// Checks if the test case is a particular test called `UncleFromSideChain`
171    ///
172    /// This fixture fails as expected, however it fails at the wrong block number.
173    /// Given we no longer have uncle blocks, this test case was pulled out such
174    /// that we ensure it still fails as expected, however we do not check the block number.
175    #[inline]
176    fn is_uncle_sidechain_case(name: &str) -> bool {
177        name.contains("UncleFromSideChain")
178    }
179
180    /// Execute a single `BlockchainTest`, validating the outcome against the
181    /// expectations encoded in the JSON file.
182    pub fn run_single_case(name: &str, case: &BlockchainTest) -> Result<(), Error> {
183        let mut last_block_hash = B256::ZERO;
184        let result = run_case(
185            name,
186            case,
187            BlockTestOptions::default(),
188            &mut last_block_hash,
189            &mut Vec::new(),
190        );
191        // Retain this legacy exception only for the old ethereum/tests suite.
192        if Self::is_uncle_sidechain_case(name) &&
193            matches!(result, Err(Error::BlockProcessingFailed { .. }))
194        {
195            Ok(())
196        } else {
197            result
198        }
199    }
200}
201
202impl Case for BlockchainTestCase {
203    fn load(path: &Path) -> Result<Self, Error> {
204        Ok(Self { tests: load_json(path)?, skip: should_skip(path) })
205    }
206
207    /// Runs the test cases for the Ethereum Forks test suite.
208    ///
209    /// # Errors
210    /// Returns an error if the test is flagged for skipping or encounters issues during execution.
211    fn run(self) -> Result<(), Error> {
212        // If the test is marked for skipping, return a Skipped error immediately.
213        if self.skip {
214            return Err(Error::Skipped);
215        }
216
217        // Iterate through test cases, filtering by the network type to exclude specific forks.
218        self.tests
219            .into_iter()
220            .filter(|(_, case)| {
221                !Self::excluded_fork(case.network) && !Self::lacks_request_contracts(case)
222            })
223            .par_bridge_buffered()
224            .with_min_len(64)
225            .try_for_each(|(name, case)| Self::run_single_case(&name, &case).map(|_| ()))
226    }
227}
228
229/// Executes a single `BlockchainTest` returning an error as soon as any block has a consensus
230/// validation failure.
231///
232/// A `BlockchainTest` represents a self-contained scenario:
233/// - It initializes a fresh blockchain state.
234/// - It sequentially decodes, executes, and inserts a predefined set of blocks.
235/// - It then verifies that the resulting blockchain state (post-state) matches the expected
236///   outcome.
237///
238/// Returns:
239/// - `Ok(())` if all blocks execute successfully.
240/// - `Err(Error)` if any block fails to execute correctly.
241fn run_case(
242    name: &str,
243    case: &BlockchainTest,
244    options: BlockTestOptions,
245    last_block_hash: &mut B256,
246    rejections: &mut Vec<Rejection>,
247) -> Result<(), Error> {
248    // Create a new test database and initialize a provider for the test case.
249    let chain_spec = Arc::new(case.chain_spec()?);
250    let factory = create_test_provider_factory(chain_spec.clone());
251    let provider = factory.database_provider_rw()?;
252
253    // Insert initial test state into the provider.
254    let genesis_block = SealedBlock::<Block>::from_sealed_parts(
255        SealedHeader::try_from(case.genesis_block_header.clone())?,
256        Default::default(),
257    )
258    .try_recover()
259    .map_err(|err| Error::block_failed(0, err))?;
260
261    provider.insert_block(&genesis_block)?;
262    *last_block_hash = genesis_block.hash();
263
264    // Increment block number for receipts static file
265    provider
266        .static_file_provider()
267        .latest_writer(StaticFileSegment::Receipts)
268        .and_then(|mut writer| writer.increment_block(0))?;
269
270    let genesis_state = case.pre.clone().into_genesis_state();
271    insert_genesis_state(&provider, genesis_state.iter())?;
272    insert_genesis_hashes(&provider, genesis_state.iter())?;
273    insert_genesis_history(&provider, genesis_state.iter())?;
274
275    // Build the genesis trie, as `init_genesis` does, so block 1 reads stored nodes.
276    let (_, trie_updates) = reth_trie_db::with_adapter!(provider, |A| {
277        StateRoot::<reth_trie_db::DatabaseTrieCursorFactory<_, A>, _>::from_tx(provider.tx_ref())
278            .root_with_updates()
279    })
280    .map_err(ProviderError::other)?;
281    provider.write_trie_updates(trie_updates)?;
282    // BLOCKHASH reads static files, including genesis during execution of block 1.
283    provider.static_file_provider().commit()?;
284
285    let executor_provider = EthEvmConfig::ethereum(chain_spec.clone());
286    let mut parent = genesis_block;
287    let mut bal_buf = Vec::new();
288
289    for (block_index, fixture_block) in case.blocks.iter().enumerate() {
290        // The blocks do not include the genesis block which is why we have the plus one.
291        // We also cannot use block.number because for invalid blocks, this may be incorrect.
292        let block_number = (block_index + 1) as u64;
293        let result = (|| -> Result<(), Error> {
294            // Decode only the block being imported; rejected blocks do not change the chain.
295            let block = &SealedBlock::<Block>::decode(&mut fixture_block.rlp.as_ref())
296                .map_err(|err| Error::block_failed(block_number, err))?
297                .try_recover()
298                .map_err(|err| Error::block_failed(block_number, err))?;
299
300            // Consensus checks before block execution
301            pre_execution_checks(chain_spec.clone(), &parent, block)
302                .map_err(|err| Error::block_failed(block_number, err))?;
303
304            // Like a block downloaded with its access list, the delivered list counts only when the
305            // header commits to one.
306            let delivered =
307                fixture_block.access_list().filter(|_| block.block_access_list_hash.is_some());
308            let access_list = delivered
309                .filter(|_| !options.bal_withhold)
310                .map(|access_list| check_delivered_access_list(block, access_list))
311                .transpose()
312                .map_err(|err| Error::block_failed(block_number, err))?
313                .flatten();
314            let attached = access_list.is_some();
315
316            let state_provider = provider.latest();
317            let state_db = StateProviderDatabase((&state_provider).into_evm_state_provider());
318            let mut executor = executor_provider
319                .executor_for_block(state_db, block.sealed_block())
320                .unwrap_or_else(|err| match err {});
321            if block.block_access_list_hash.is_some() {
322                executor.enable_block_access_list_builder();
323            }
324            if let Some(access_list) = access_list {
325                let access_list =
326                    <BlockExecutorFor<'_, EthEvmConfig> as BlockExecutor>::convert_block_access_list(
327                        &access_list.into(),
328                    )
329                    .map_err(|err| Error::block_failed(block_number, err))?;
330                executor.set_block_access_list(Arc::new(access_list));
331            }
332            report_execution_path(block, delivered.is_some(), attached, options);
333            executor
334                .apply_pre_execution_changes()
335                .map_err(|err| Error::block_execution_failed(block_number, err))?;
336            for transaction in block.transactions_recovered() {
337                executor
338                    .execute_transaction(transaction)
339                    .map_err(|err| Error::block_execution_failed(block_number, err))?;
340            }
341            let (output, built_bal) = executor
342                .finish_with_block_access_list()
343                .map_err(|err| Error::block_execution_failed(block_number, err))?;
344            let block_access_list_hash = built_bal
345                .map(|bal| {
346                    let bal = Bal::from(bal);
347                    bal.validate_gas_limit(block.gas_limit)
348                        .map(|()| bal.compute_hash_with_buf(&mut bal_buf))
349                })
350                .transpose()
351                .map_err(|err| Error::block_failed(block_number, err))?;
352
353            // Consensus checks after block execution
354            validate_block_post_execution(
355                block,
356                &chain_spec,
357                &output,
358                None,
359                block_access_list_hash,
360            )
361            .map_err(|err| Error::block_failed(block_number, err))?;
362
363            // Compute and check the post state root
364            let hashed_state = state_provider.hashed_post_state(&output.state)?;
365            let sorted = hashed_state.clone_into_sorted();
366            let (computed_state_root, trie_updates) = reth_trie_db::with_adapter!(provider, |A| {
367                StateRoot::<reth_trie_db::DatabaseTrieCursorFactory<_, A>, _>::overlay_root_with_updates(
368                    provider.tx_ref(),
369                    &sorted,
370                )
371            })
372            .map_err(ProviderError::other)?;
373            if computed_state_root != block.state_root {
374                return Err(Error::block_failed(
375                    block_number,
376                    ConsensusError::BodyStateRootDiff(
377                        GotExpected { got: computed_state_root, expected: block.state_root }.into(),
378                    ),
379                ));
380            }
381
382            // Publish a block only after all validation succeeds, so a rejected block leaves no
383            // writes.
384            provider.insert_block(block)?;
385            provider.static_file_provider().commit()?;
386
387            // Commit the post state/state diff to the database
388            provider.write_state(
389                &ExecutionOutcome::single(block.number, output),
390                OriginalValuesKnown::Yes,
391                StateWriteConfig::default(),
392            )?;
393
394            provider.write_hashed_state(&hashed_state.into_sorted())?;
395            // Persist the trie so later blocks read stored nodes.
396            provider.write_trie_updates(trie_updates)?;
397            provider.update_history_indices(block.number..=block.number)?;
398
399            // Since there were no errors, update the parent block
400            *last_block_hash = block.hash();
401            parent = block.clone();
402            Ok(())
403        })();
404        match result {
405            Ok(()) if fixture_block.expect_exception.is_some() => {
406                return Err(Error::Assertion(format!("Test case: {name}\nExpected failure at block {block_number}, but the block succeeded")))
407            }
408            Err(Error::BlockProcessingFailed { block_number, err }) => {
409                rejections.push(rejection(case, block_number, err.to_string()));
410                if fixture_block.expect_exception.is_none() {
411                    return Err(Error::BlockProcessingFailed { block_number, err })
412                }
413            }
414            Err(err) => return Err(err),
415            Ok(()) => {}
416        }
417    }
418
419    match &case.post_state {
420        Some(expected_post_state) => {
421            // Validate the post-state for the test case.
422            //
423            // If we get here then it means that the post-state root checks
424            // made after we execute each block was successful.
425            //
426            // If an error occurs here, then it is:
427            // - Either an issue with the test setup
428            // - Possibly an error in the test case where the post-state root in the last block does
429            //   not match the post-state values.
430            for (address, account) in expected_post_state {
431                account.assert_db(*address, provider.tx_ref())?;
432            }
433        }
434        None => {
435            // Some tests may not have post-state (e.g., state-heavy benchmark tests).
436            // In this case, we can skip the post-state validation.
437        }
438    }
439
440    Ok(())
441}
442
443/// The rejection of the fixture block with the given number, counted from 1, with its hash if
444/// it decodes.
445fn rejection(case: &BlockchainTest, block_number: u64, error: String) -> Rejection {
446    let index = (block_number - 1) as usize;
447    let hash = case
448        .blocks
449        .get(index)
450        .and_then(|block| SealedBlock::<Block>::decode(&mut block.rlp.as_ref()).ok())
451        .map(|block| block.hash());
452    Rejection { index, hash, error }
453}
454
455/// Checks the access list delivered beside a block the way reth's sync checks one downloaded with
456/// it. A list whose RLP, in the order delivered, does not hash to the header's commitment, or that
457/// does not decode, is dropped (`Ok(None)`) and the block is judged on its header alone. A matching
458/// list is committed to by the header, so it must also fit the block's gas limit.
459fn check_delivered_access_list(
460    block: &RecoveredBlock<Block>,
461    access_list: &serde_json::Value,
462) -> Result<Option<Bal>, ConsensusError> {
463    if let Some(expected) = block.block_access_list_hash &&
464        let Ok(access_list) = serde_json::from_value::<BlockAccessList>(access_list.clone()) &&
465        RawBal::new(alloy_rlp::encode(&access_list).into()).ensure_hash(expected).is_ok()
466    {
467        let access_list = Bal::from(access_list);
468        access_list.validate_gas_limit(block.gas_limit)?;
469        return Ok(Some(access_list))
470    }
471    Ok(None)
472}
473
474/// Reports which executor runs the block on the engine's execution-path tracing target. Block
475/// import has only the sequential executor, so the reason is the first gate that would also rule
476/// out the parallel one in the engine, or else `block-import`.
477fn report_execution_path(
478    block: &RecoveredBlock<Block>,
479    delivered: bool,
480    attached: bool,
481    options: BlockTestOptions,
482) {
483    let reason = execution_path_reason(delivered, attached, options);
484    debug!(
485        target: "engine::tree::bal_execution_path",
486        block = block.number,
487        hash = %block.hash(),
488        path = "sequential",
489        reason,
490        "Executing block"
491    );
492}
493
494/// The engine's gates in its order, the access list before the switch. A delivered list that was
495/// withheld or dropped is reported as `withheld` or `bad-access-list`, which therefore also come
496/// before `disabled`.
497const fn execution_path_reason(
498    delivered: bool,
499    attached: bool,
500    options: BlockTestOptions,
501) -> &'static str {
502    if !delivered {
503        "no-access-list"
504    } else if options.bal_withhold {
505        "withheld"
506    } else if !attached {
507        "bad-access-list"
508    } else if options.bal_sequential {
509        "disabled"
510    } else {
511        "block-import"
512    }
513}
514
515fn pre_execution_checks(
516    chain_spec: Arc<ChainSpec>,
517    parent: &RecoveredBlock<Block>,
518    block: &RecoveredBlock<Block>,
519) -> Result<(), Error> {
520    let consensus: EthBeaconConsensus<ChainSpec> = EthBeaconConsensus::new(chain_spec);
521
522    let sealed_header = block.sealed_header();
523
524    <EthBeaconConsensus<ChainSpec> as Consensus<Block>>::validate_body_against_header(
525        &consensus,
526        block.body(),
527        sealed_header,
528    )?;
529    consensus.validate_header_against_parent(sealed_header, parent.sealed_header())?;
530    consensus.validate_header(sealed_header)?;
531    consensus.validate_block_pre_execution(block)?;
532
533    Ok(())
534}
535
536/// Returns whether the test at the given path should be skipped.
537///
538/// Some tests are edge cases that cannot happen on mainnet, while others are skipped for
539/// convenience (e.g. they take a long time to run) or are temporarily disabled.
540///
541/// The reason should be documented in a comment above the file name(s).
542pub fn should_skip(path: &Path) -> bool {
543    let path_str = path.to_str().expect("Path is not valid UTF-8");
544    let name = path.file_name().unwrap().to_str().unwrap();
545    matches!(
546        name,
547        // funky test with `bigint 0x00` value in json :) not possible to happen on mainnet and require
548        // custom json parser. https://github.com/ethereum/tests/issues/971
549        | "ValueOverflow.json"
550        | "ValueOverflowParis.json"
551
552        // txbyte is of type 02 and we don't parse tx bytes for this test to fail.
553        | "typeTwoBerlin.json"
554
555        // Test checks if nonce overflows. We are handling this correctly but we are not parsing
556        // exception in testsuite. There are more nonce overflow tests that are internal
557        // call/create, and those tests are passing and are enabled.
558        | "CreateTransactionHighNonce.json"
559
560        // Test check if gas price overflows, we handle this correctly but does not match tests specific
561        // exception.
562        | "HighGasPrice.json"
563        | "HighGasPriceParis.json"
564
565        // Skip test where basefee/accesslist/difficulty is present but it shouldn't be supported in
566        // London/Berlin/TheMerge. https://github.com/ethereum/tests/blob/5b7e1ab3ffaf026d99d20b17bb30f533a2c80c8b/GeneralStateTests/stExample/eip1559.json#L130
567        // It is expected to not execute these tests.
568        | "accessListExample.json"
569        | "basefeeExample.json"
570        | "eip1559.json"
571        | "mergeTest.json"
572
573        // These tests are passing, but they take a lot of time to execute so we are going to skip them.
574        | "loopExp.json"
575        | "Call50000_sha256.json"
576        | "static_Call50000_sha256.json"
577        | "loopMul.json"
578        | "CALLBlake2f_MaxRounds.json"
579        | "shiftCombinations.json"
580
581        // Skipped by revm as well: <https://github.com/bluealloy/revm/blob/be92e1db21f1c47b34c5a58cfbf019f6b97d7e4b/bins/revme/src/cmd/statetest/runner.rs#L115-L125>
582        | "RevertInCreateInInit_Paris.json"
583        | "RevertInCreateInInit.json"
584        | "dynamicAccountOverwriteEmpty.json"
585        | "dynamicAccountOverwriteEmpty_Paris.json"
586        | "RevertInCreateInInitCreate2Paris.json"
587        | "create2collisionStorage.json"
588        | "RevertInCreateInInitCreate2.json"
589        | "create2collisionStorageParis.json"
590        | "InitCollision.json"
591        | "InitCollisionParis.json"
592    )
593    // Ignore outdated EOF tests that haven't been updated for Cancun yet.
594    || path_contains(path_str, &["EIPTests", "stEOF"])
595}
596
597/// `str::contains` but for a path. Takes into account the OS path separator (`/` or `\`).
598fn path_contains(path_str: &str, rhs: &[&str]) -> bool {
599    let rhs = rhs.join(std::path::MAIN_SEPARATOR_STR);
600    path_str.contains(&rhs)
601}
602
603/// Empty auxiliary database shared while v1-storage fixtures run.
604///
605/// Legacy suite processes retain their handle until exit. The CLI closes it after its workers
606/// join, before removing the backing directory.
607static SHARED_ROCKSDB: Mutex<Option<(PathBuf, RocksDBProvider)>> = Mutex::new(None);
608
609/// Returns the process's shared v1 auxiliary database, opening it on first use.
610fn shared_rocksdb() -> RocksDBProvider {
611    let mut shared = SHARED_ROCKSDB.lock().unwrap();
612    let (_, rocksdb) = shared.get_or_insert_with(|| {
613        let path = reth_db::test_utils::tempdir_path();
614        let rocksdb = RocksDBBuilder::new(path.join("rocksdb"))
615            .with_default_tables()
616            .build()
617            .expect("failed to create shared test RocksDB provider");
618        (path, rocksdb)
619    });
620    rocksdb.clone()
621}
622
623/// Closes and removes the shared database after every fixture worker has joined.
624///
625/// No fixture may be running when this is called.
626pub fn remove_shared_rocksdb() {
627    if let Some((path, rocksdb)) = SHARED_ROCKSDB.lock().unwrap().take() {
628        // Close the database before removing files which RocksDB still has open.
629        drop(rocksdb);
630        if let Err(err) = fs::remove_dir_all(&path) {
631            eprintln!("failed to remove {}: {err}", path.display());
632        }
633    }
634}
635
636/// Creates a provider factory for a single test case.
637///
638/// Mirrors [`reth_provider::test_utils::create_test_provider_factory_with_chain_spec`], except
639/// that it reuses [`SHARED_ROCKSDB`] instead of opening a new `RocksDB` instance. The temp datadir,
640/// MDBX, static files and runtime stay isolated per case.
641fn create_test_provider_factory(
642    chain_spec: Arc<ChainSpec>,
643) -> ProviderFactory<MockNodeTypesWithDB> {
644    let genesis_block_number = chain_spec.genesis.number.unwrap_or_default();
645
646    // A single temp directory holds the MDBX and static file dirs. `TempDatabase` removes the
647    // entire directory on drop.
648    let datadir_path = reth_db::test_utils::tempdir_path();
649    let static_files_path = datadir_path.join("static_files");
650    fs::create_dir_all(&static_files_path).expect("failed to create static_files dir");
651
652    let db = reth_db::test_utils::create_test_rw_db_with_datadir(&datadir_path);
653
654    let factory = ProviderFactory::new(
655        db,
656        chain_spec,
657        StaticFileProviderBuilder::read_write(static_files_path)
658            .with_genesis_block_number(genesis_block_number)
659            .build()
660            .expect("static file provider"),
661        shared_rocksdb(),
662        OverlayManager::default(),
663        Runtime::test(),
664    )
665    .expect("failed to create test provider factory");
666
667    assert!(
668        !factory.cached_storage_settings().any_in_rocksdb(),
669        "the shared RocksDB is only valid while ef-tests run with v1 storage settings"
670    );
671
672    factory
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678    use serde_json::json;
679
680    /// A block with the given gas limit whose header commits to `access_list`.
681    fn block_committing_to(
682        access_list: &serde_json::Value,
683        gas_limit: u64,
684    ) -> RecoveredBlock<Block> {
685        let access_list: Bal =
686            serde_json::from_value::<BlockAccessList>(access_list.clone()).unwrap().into();
687        let header = alloy_consensus::Header {
688            gas_limit,
689            block_access_list_hash: Some(access_list.compute_hash()),
690            ..Default::default()
691        };
692        RecoveredBlock::new_unhashed(Block { header, body: Default::default() }, Vec::new())
693    }
694
695    fn access_list(storage_read: &str) -> serde_json::Value {
696        json!([{
697            "address": "0x0000000000000000000000000000000000000001",
698            "storageChanges": [],
699            "storageReads": [storage_read],
700            "balanceChanges": [],
701            "nonceChanges": [],
702            "codeChanges": []
703        }])
704    }
705
706    #[test]
707    fn delivered_access_list_is_dropped_unless_it_matches() {
708        let block = block_committing_to(&access_list("0x1"), 30_000_000);
709        assert!(check_delivered_access_list(&block, &access_list("0x1")).unwrap().is_some());
710        assert!(check_delivered_access_list(&block, &access_list("0x2")).unwrap().is_none());
711        let undecodable = json!({"address": "0x01"});
712        assert!(check_delivered_access_list(&block, &undecodable).unwrap().is_none());
713
714        // A matching list is committed to by the header, so it still fails the gas limit.
715        let block = block_committing_to(&access_list("0x1"), 1);
716        assert!(check_delivered_access_list(&block, &access_list("0x1")).is_err());
717        assert!(check_delivered_access_list(&block, &access_list("0x2")).unwrap().is_none());
718    }
719
720    /// The list is hashed in the order delivered, so the same entries in another order are dropped.
721    #[test]
722    fn reordered_access_list_is_dropped() {
723        let account = |address: &str| {
724            json!({
725                "address": address,
726                "storageChanges": [],
727                "storageReads": [],
728                "balanceChanges": [],
729                "nonceChanges": [],
730                "codeChanges": []
731            })
732        };
733        let first = account("0x0000000000000000000000000000000000000001");
734        let second = account("0x0000000000000000000000000000000000000002");
735        let block = block_committing_to(&json!([first, second]), 30_000_000);
736        assert!(check_delivered_access_list(&block, &json!([first, second])).unwrap().is_some());
737        assert!(check_delivered_access_list(&block, &json!([second, first])).unwrap().is_none());
738    }
739
740    #[test]
741    fn dropped_or_withheld_access_list_is_reported_before_the_switch() {
742        let disabled = BlockTestOptions { bal_sequential: true, ..Default::default() };
743        let withheld = BlockTestOptions { bal_withhold: true, ..Default::default() };
744        let withheld_disabled = BlockTestOptions { bal_sequential: true, bal_withhold: true };
745        let default = BlockTestOptions::default();
746        assert_eq!(execution_path_reason(false, false, disabled), "no-access-list");
747        assert_eq!(execution_path_reason(false, false, withheld), "no-access-list");
748        assert_eq!(execution_path_reason(true, false, withheld), "withheld");
749        assert_eq!(execution_path_reason(true, false, withheld_disabled), "withheld");
750        assert_eq!(execution_path_reason(true, false, disabled), "bad-access-list");
751        assert_eq!(execution_path_reason(true, false, default), "bad-access-list");
752        assert_eq!(execution_path_reason(true, true, disabled), "disabled");
753        assert_eq!(execution_path_reason(true, true, default), "block-import");
754    }
755}