1use 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#[derive(Debug)]
53pub struct BlockchainTests {
54 suite_path: PathBuf,
55}
56
57impl BlockchainTests {
58 pub const fn new(suite_path: PathBuf) -> Self {
60 Self { suite_path }
61 }
62
63 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 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#[derive(Debug, Clone, Copy, Default)]
125pub struct BlockTestOptions {
126 pub bal_sequential: bool,
130 pub bal_withhold: bool,
133}
134
135#[derive(Debug, PartialEq, Eq)]
137pub struct BlockchainTestCase {
138 pub tests: BTreeMap<String, BlockchainTest>,
140 pub skip: bool,
142}
143
144impl BlockchainTestCase {
145 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 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 #[inline]
176 fn is_uncle_sidechain_case(name: &str) -> bool {
177 name.contains("UncleFromSideChain")
178 }
179
180 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 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 fn run(self) -> Result<(), Error> {
212 if self.skip {
214 return Err(Error::Skipped);
215 }
216
217 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
229fn 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 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 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 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 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 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 let block_number = (block_index + 1) as u64;
293 let result = (|| -> Result<(), Error> {
294 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 pre_execution_checks(chain_spec.clone(), &parent, block)
302 .map_err(|err| Error::block_failed(block_number, err))?;
303
304 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 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 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 provider.insert_block(block)?;
385 provider.static_file_provider().commit()?;
386
387 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 provider.write_trie_updates(trie_updates)?;
397 provider.update_history_indices(block.number..=block.number)?;
398
399 *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 for (address, account) in expected_post_state {
431 account.assert_db(*address, provider.tx_ref())?;
432 }
433 }
434 None => {
435 }
438 }
439
440 Ok(())
441}
442
443fn 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
455fn 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
474fn 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
494const 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
536pub 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 | "ValueOverflow.json"
550 | "ValueOverflowParis.json"
551
552 | "typeTwoBerlin.json"
554
555 | "CreateTransactionHighNonce.json"
559
560 | "HighGasPrice.json"
563 | "HighGasPriceParis.json"
564
565 | "accessListExample.json"
569 | "basefeeExample.json"
570 | "eip1559.json"
571 | "mergeTest.json"
572
573 | "loopExp.json"
575 | "Call50000_sha256.json"
576 | "static_Call50000_sha256.json"
577 | "loopMul.json"
578 | "CALLBlake2f_MaxRounds.json"
579 | "shiftCombinations.json"
580
581 | "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 || path_contains(path_str, &["EIPTests", "stEOF"])
595}
596
597fn 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
603static SHARED_ROCKSDB: Mutex<Option<(PathBuf, RocksDBProvider)>> = Mutex::new(None);
608
609fn 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
623pub fn remove_shared_rocksdb() {
627 if let Some((path, rocksdb)) = SHARED_ROCKSDB.lock().unwrap().take() {
628 drop(rocksdb);
630 if let Err(err) = fs::remove_dir_all(&path) {
631 eprintln!("failed to remove {}: {err}", path.display());
632 }
633 }
634}
635
636fn 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 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 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 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 #[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}