1use super::{
26 ordered_outputs::{ordered_worker_outputs, OrderedWorkerOutputError},
27 worker, BalExecutionError,
28};
29use alloy_eip7928::{
30 bal::{Bal, DecodedBal},
31 compute_block_access_list_hash, BlockAccessList,
32};
33use alloy_primitives::Address;
34use evm2::evm::Bal as EvmBal;
35use reth_concurrency::sync::{
36 channel,
37 channel::{Receiver, Sender},
38 rayon::Scope,
39};
40use reth_engine_primitives::BlockAccessListDecodeError;
41use reth_evm::{
42 BlockExecutionOutput, BlockExecutor, BlockExecutorFactory, BlockExecutorFor, ConfigureEvm,
43 Database, EvmEnvFor, ExecutableTxFor, ExecutionCtxFor,
44};
45use reth_primitives_traits::ReceiptTy;
46use reth_tasks::Runtime;
47use std::sync::Arc;
48
49use crate::tree::payload_processor::receipt_root_task::IndexedReceipt;
50
51#[expect(clippy::too_many_arguments, clippy::type_complexity)]
56pub fn execute_block<'a, Evm, Tx, Err, DB, MakeDb>(
57 runtime: &Runtime,
58 evm_config: &'a Evm,
59 make_db: &'a MakeDb,
60 input_bal: Arc<DecodedBal>,
61 evm_env: EvmEnvFor<Evm>,
62 ctx: ExecutionCtxFor<'a, Evm>,
63 transaction_count: usize,
64 txs: Receiver<(usize, Result<Tx, Err>)>,
65 receipt_tx: Sender<IndexedReceipt<ReceiptTy<Evm::Primitives>>>,
66) -> Result<
67 (BlockExecutionOutput<ReceiptTy<Evm::Primitives>>, Vec<Address>, BlockAccessList, Arc<EvmBal>),
68 BalExecutionError,
69>
70where
71 Evm: ConfigureEvm + 'static,
72 Tx: ExecutableTxFor<Evm> + Send + 'a,
73 Err: core::error::Error + Send + Sync + 'static,
74 DB: Database + Send + 'a,
75 MakeDb: Fn(bool) -> Result<DB, BalExecutionError> + Sync + 'a,
76{
77 let worker_pool = runtime.bal_streaming_pool();
78 let worker_count = worker_pool.current_num_threads().max(1).min(transaction_count);
79
80 worker_pool.in_place_scope(|scope| {
81 execute_block_inner(
82 scope,
83 evm_config,
84 make_db,
85 input_bal,
86 evm_env,
87 ctx,
88 transaction_count,
89 txs,
90 receipt_tx,
91 worker_count,
92 )
93 })
94}
95
96#[expect(clippy::too_many_arguments, clippy::type_complexity)]
97fn execute_block_inner<'scope, Evm, Tx, Err, DB, MakeDb>(
98 scope: &Scope<'scope>,
99 evm_config: &'scope Evm,
100 make_db: &'scope MakeDb,
101 input_bal: Arc<DecodedBal>,
102 evm_env: EvmEnvFor<Evm>,
103 ctx: ExecutionCtxFor<'scope, Evm>,
104 transaction_count: usize,
105 txs: Receiver<(usize, Result<Tx, Err>)>,
106 receipt_tx: Sender<IndexedReceipt<ReceiptTy<Evm::Primitives>>>,
107 worker_count: usize,
108) -> Result<
109 (BlockExecutionOutput<ReceiptTy<Evm::Primitives>>, Vec<Address>, BlockAccessList, Arc<EvmBal>),
110 BalExecutionError,
111>
112where
113 Evm: ConfigureEvm + 'scope,
114 Tx: ExecutableTxFor<Evm> + Send + 'scope,
115 Err: core::error::Error + Send + Sync + 'static,
116 DB: Database + Send + 'scope,
117 MakeDb: Fn(bool) -> Result<DB, BalExecutionError> + Sync + 'scope,
118{
119 let received_bal = Arc::new(
132 <BlockExecutorFor<'scope, Evm> as BlockExecutor>::convert_block_access_list(
133 input_bal.as_bal().as_vec(),
134 )
135 .map_err(BlockAccessListDecodeError::new)?,
136 );
137 let (result_tx, result_rx) = channel::unbounded();
138 let (abort_guard, abort_rx) = AbortGuard::new();
139
140 for _ in 0..worker_count {
141 worker::spawn_worker(
142 scope,
143 txs.clone(),
144 abort_rx.clone(),
145 result_tx.clone(),
146 evm_config,
147 make_db,
148 Arc::clone(&received_bal),
149 evm_env.clone(),
150 ctx.clone(),
151 );
152 }
153 drop(result_tx);
154
155 let evm = evm_config.evm_with_env(make_db(false)?, evm_env);
156 let mut canonical_executor =
157 evm_config.block_executor_factory().create_executor(evm, ctx.clone());
158 canonical_executor.enable_block_access_list_builder();
159 canonical_executor.apply_pre_execution_changes()?;
160
161 let mut senders = Vec::with_capacity(transaction_count);
162 let mut last_sent_len = 0;
163 for output in ordered_worker_outputs(&result_rx, transaction_count) {
164 let output = match output {
165 Ok(output) => output,
166 Err(OrderedWorkerOutputError::Worker(worker::BalWorkerError::Execution {
167 tx_index,
168 tx_gas_limit,
169 source,
170 })) => {
171 canonical_executor.validate_transaction_gas_limit(tx_gas_limit)?;
174
175 return Err(
178 worker::BalWorkerError::Execution { tx_index, tx_gas_limit, source }.into()
179 );
180 }
181 Err(error) => return Err(error.into()),
182 };
183 canonical_executor.validate_transaction_gas_limit(output.tx_gas_limit)?;
184 canonical_executor.commit_transaction(output.result)?;
185 senders.push(output.signer);
186
187 let current_len = canonical_executor.receipts().len();
188 if current_len > last_sent_len {
189 last_sent_len = current_len;
190 if let Some(receipt) = canonical_executor.receipts().last() {
191 let _ = receipt_tx.send(IndexedReceipt::new(current_len - 1, receipt.clone()));
192 }
193 }
194 }
195 drop(abort_guard);
196
197 let (output, built_bal) = canonical_executor.finish_with_block_access_list()?;
198 let built_bal = built_bal.expect("BAL builder was enabled for parallel execution");
199 log_bal_divergence(&built_bal, input_bal.as_bal());
200 Ok((output, senders, built_bal, received_bal))
201}
202
203fn log_bal_divergence(built_bal: &BlockAccessList, received_bal: &Bal) {
204 if tracing::enabled!(target: "engine::tree::payload_processor::bal", tracing::Level::DEBUG) &&
205 built_bal.as_slice() != received_bal.as_slice()
206 {
207 let rebuilt = compute_block_access_list_hash(built_bal);
208 let expected = compute_block_access_list_hash(received_bal.as_slice());
209 let div = received_bal.diff(built_bal.as_slice());
210 tracing::debug!(
211 target: "engine::tree::payload_processor::bal",
212 %rebuilt,
213 %expected,
214 %div,
215 "first BAL divergence",
216 );
217 }
218}
219
220struct AbortGuard {
222 _tx: Sender<()>,
223}
224
225impl AbortGuard {
226 fn new() -> (Self, Receiver<()>) {
227 let (tx, rx) = channel::bounded(0);
228 (Self { _tx: tx }, rx)
229 }
230}
231
232#[cfg(test)]
233mod tests {
234
235 use super::*;
236 use alloy_consensus::{BlockHeader, Header, TxLegacy};
237 use alloy_eip7928::{
238 bal::Bal as AlloyBal, AccountChanges, BlockAccessIndex, BlockAccessList, CodeChange,
239 };
240 use alloy_eips::{
241 eip2935::{HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE},
242 eip4788::{BEACON_ROOTS_ADDRESS, BEACON_ROOTS_CODE},
243 eip7002::{WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS, WITHDRAWAL_REQUEST_PREDEPLOY_CODE},
244 eip7251::{CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS, CONSOLIDATION_REQUEST_PREDEPLOY_CODE},
245 };
246 use alloy_primitives::{Bytes, B256, U256};
247 use evm2::evm::{
248 CacheDB, EmptyDB, BUILDER_DEPOSIT_REQUEST_ADDRESS, BUILDER_EXIT_REQUEST_ADDRESS,
249 };
250 use reth_chainspec::{ChainSpecBuilder, MAINNET};
251 use reth_concurrency::sync::atomic::{AtomicUsize, Ordering};
252 use reth_engine_primitives::{InsertBlockErrorKind, InsertBlockValidationError};
253 use reth_ethereum_primitives::{Block, BlockBody, Receipt, Transaction, TransactionSigned};
254 use reth_evm::{
255 cached::{AccountInfo, Bytecode},
256 BlockExecutionOutput, BlockValidationError,
257 };
258 use reth_evm_ethereum::EthEvmConfig;
259 use reth_primitives_traits::{Block as _, Recovered, SealedBlock};
260 use reth_testing_utils::generators::{generate_key, rng, sign_tx_with_key_pair};
261 use std::{convert::Infallible, io};
262
263 fn test_evm_config() -> EthEvmConfig {
264 EthEvmConfig::new(Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().build()))
265 }
266
267 fn non_amsterdam_evm_config() -> EthEvmConfig {
268 EthEvmConfig::new(Arc::new(ChainSpecBuilder::mainnet().osaka_activated().build()))
269 }
270
271 fn to_arc_decoded(bal: BlockAccessList) -> Arc<DecodedBal> {
273 let alloy_bal: AlloyBal = bal.into();
274 let raw = alloy_rlp::encode(&alloy_bal).into();
275 Arc::new(DecodedBal::new(alloy_bal, raw))
276 }
277
278 fn system_contracts_db() -> CacheDB<EmptyDB> {
283 let mut db = CacheDB::<EmptyDB>::default();
284 db.insert_account_info(
285 &BEACON_ROOTS_ADDRESS,
286 AccountInfo::default()
287 .with_nonce(1)
288 .with_code(Bytecode::new_raw(BEACON_ROOTS_CODE.clone())),
289 );
290 db.insert_account_info(
291 &WITHDRAWAL_REQUEST_PREDEPLOY_ADDRESS,
292 AccountInfo::default()
293 .with_nonce(1)
294 .with_code(Bytecode::new_raw(WITHDRAWAL_REQUEST_PREDEPLOY_CODE.clone())),
295 );
296 db.insert_account_info(
297 &CONSOLIDATION_REQUEST_PREDEPLOY_ADDRESS,
298 AccountInfo::default()
299 .with_nonce(1)
300 .with_code(Bytecode::new_raw(CONSOLIDATION_REQUEST_PREDEPLOY_CODE.clone())),
301 );
302 for address in [BUILDER_DEPOSIT_REQUEST_ADDRESS, BUILDER_EXIT_REQUEST_ADDRESS] {
303 db.insert_account_info(
304 &address,
305 AccountInfo::default()
306 .with_nonce(1)
307 .with_code(Bytecode::new_legacy(Bytes::from_static(&[0x00]))),
308 );
309 }
310 db.insert_account_info(
311 &HISTORY_STORAGE_ADDRESS,
312 AccountInfo::default()
313 .with_nonce(1)
314 .with_code(Bytecode::new_raw(HISTORY_STORAGE_CODE.clone())),
315 );
316 db
317 }
318
319 fn empty_amsterdam_block(header_bal_hash: B256) -> SealedBlock<Block> {
321 empty_amsterdam_block_with_gas_limit(header_bal_hash, 30_000_000)
322 }
323
324 fn empty_amsterdam_block_with_gas_limit(
325 header_bal_hash: B256,
326 gas_limit: u64,
327 ) -> SealedBlock<Block> {
328 let header = Header {
329 timestamp: 1,
330 number: 1,
331 gas_limit,
332 parent_beacon_block_root: Some(B256::ZERO),
333 withdrawals_root: Some(alloy_consensus::EMPTY_ROOT_HASH),
334 requests_hash: Some(alloy_eips::eip7685::EMPTY_REQUESTS_HASH),
335 excess_blob_gas: Some(0),
336 blob_gas_used: Some(0),
337 block_access_list_hash: Some(header_bal_hash),
338 slot_number: Some(0),
339 ..Header::default()
340 };
341 Block {
342 header,
343 body: BlockBody {
344 transactions: vec![],
345 ommers: vec![],
346 withdrawals: Some(vec![].into()),
347 },
348 }
349 .seal_slow()
350 }
351
352 fn db_factory(
353 db: CacheDB<EmptyDB>,
354 ) -> impl Fn(bool) -> Result<CacheDB<EmptyDB>, BalExecutionError> + Sync {
355 move |_| Ok(db.clone())
356 }
357
358 fn tx_stream<Tx>(txs: Vec<Tx>) -> Receiver<(usize, Result<Tx, Infallible>)> {
359 let (tx, rx) = channel::unbounded();
360 for (index, transaction) in txs.into_iter().enumerate() {
361 tx.send((index, Ok(transaction))).unwrap();
362 }
363 rx
364 }
365
366 fn run_execute_block<Tx, DB, MakeDb>(
367 runtime: &Runtime,
368 evm_config: EthEvmConfig,
369 make_db: MakeDb,
370 input_bal: Arc<DecodedBal>,
371 block: &SealedBlock<Block>,
372 txs: Vec<Tx>,
373 ) -> Result<BlockExecutionOutput<Receipt>, BalExecutionError>
374 where
375 Tx: ExecutableTxFor<EthEvmConfig> + Send,
376 DB: Database + Send,
377 MakeDb: Fn(bool) -> Result<DB, BalExecutionError> + Sync,
378 {
379 run_execute_block_full(runtime, evm_config, make_db, input_bal, block, txs)
380 .map(|(output, _)| output)
381 }
382
383 fn run_execute_block_full<Tx, DB, MakeDb>(
384 runtime: &Runtime,
385 evm_config: EthEvmConfig,
386 make_db: MakeDb,
387 input_bal: Arc<DecodedBal>,
388 block: &SealedBlock<Block>,
389 txs: Vec<Tx>,
390 ) -> Result<(BlockExecutionOutput<Receipt>, BlockAccessList), BalExecutionError>
391 where
392 Tx: ExecutableTxFor<EthEvmConfig> + Send,
393 DB: Database + Send,
394 MakeDb: Fn(bool) -> Result<DB, BalExecutionError> + Sync,
395 {
396 let transaction_count = txs.len();
397 let (receipt_tx, _receipt_rx) = channel::unbounded();
398 let evm_env = evm_config.evm_env(block.header()).unwrap();
399 let execution_ctx = evm_config.context_for_block(block).unwrap();
400 execute_block(
401 runtime,
402 &evm_config,
403 &make_db,
404 input_bal,
405 evm_env,
406 execution_ctx,
407 transaction_count,
408 tx_stream(txs),
409 receipt_tx,
410 )
411 .map(|(output, _, built_bal, _)| (output, built_bal))
412 }
413
414 fn insert_funded(db: &mut CacheDB<EmptyDB>, address: Address, balance: U256) {
416 db.insert_account_info(&address, AccountInfo::default().with_balance(balance));
417 }
418
419 fn run_serial_path(
422 evm_config: &EthEvmConfig,
423 canonical_db: CacheDB<EmptyDB>,
424 block: &SealedBlock<Block>,
425 txs: &[Recovered<TransactionSigned>],
426 ) -> (BlockExecutionOutput<Receipt>, BlockAccessList) {
427 let mut executor =
428 evm_config.executor_for_block(canonical_db, block).expect("build serial executor");
429 executor.enable_block_access_list_builder();
430 executor.apply_pre_execution_changes().expect("serial pre-exec");
431 for (index, tx) in txs.iter().cloned().enumerate() {
432 executor
433 .execute_transaction(tx)
434 .unwrap_or_else(|err| panic!("serial tx {index} failed: {err:?}"));
435 }
436 let (output, bal) = executor.finish_with_block_access_list().expect("serial post-exec");
437 (output, bal.expect("BAL builder was enabled"))
438 }
439
440 fn reference_bal_for_empty_block(evm_config: &EthEvmConfig) -> BlockAccessList {
447 run_serial_path(evm_config, system_contracts_db(), &empty_amsterdam_block(B256::ZERO), &[])
448 .1
449 }
450
451 fn reference_bal_for_block(
454 evm_config: &EthEvmConfig,
455 db: CacheDB<EmptyDB>,
456 block: &SealedBlock<Block>,
457 txs: &[Recovered<TransactionSigned>],
458 ) -> BlockAccessList {
459 run_serial_path(evm_config, db, block, txs).1
460 }
461
462 fn transfer(to: Address, value: u64, nonce: u64, gas_limit: u64) -> Transaction {
463 Transaction::Legacy(TxLegacy {
464 chain_id: Some(MAINNET.chain.id()),
465 nonce,
466 gas_price: 1,
467 gas_limit,
468 to: alloy_primitives::TxKind::Call(to),
469 value: U256::from(value),
470 input: Default::default(),
471 })
472 }
473
474 macro_rules! signed_transfer {
475 ($key:expr, $signer:expr, $to:expr, $value:expr, $nonce:expr, $gas_limit:expr) => {
476 Recovered::new_unchecked(
477 sign_tx_with_key_pair($key, transfer($to, $value, $nonce, $gas_limit)),
478 $signer,
479 )
480 };
481 }
482
483 fn assert_shadow_equal(
490 evm_config: EthEvmConfig,
491 canonical_db_template: CacheDB<EmptyDB>,
492 block_header_only: SealedBlock<Block>,
493 txs: Vec<Recovered<TransactionSigned>>,
494 ) {
495 let (mut serial, reference_bal) =
497 run_serial_path(&evm_config, canonical_db_template.clone(), &block_header_only, &txs);
498 let block = empty_amsterdam_block_with_gas_limit(
500 compute_block_access_list_hash(&reference_bal),
501 block_header_only.header().gas_limit(),
502 );
503 let (mut bal_out, built_bal) = run_execute_block_full(
504 &Runtime::test(),
505 evm_config,
506 db_factory(canonical_db_template),
507 to_arc_decoded(reference_bal.clone()),
508 &block,
509 txs,
510 )
511 .unwrap_or_else(|e| panic!("BAL path failed: {e:?}"));
512
513 assert_eq!(reference_bal, built_bal, "rebuilt BAL diverged");
515 assert_eq!(serial.receipts, bal_out.receipts, "receipts diverged");
516 assert_eq!(serial.gas_used, bal_out.gas_used, "gas used diverged");
517 assert_eq!(serial.requests, bal_out.requests, "requests diverged");
518 serial.state.reverts.sort();
519 bal_out.state.reverts.sort();
520 assert_eq!(serial.state, bal_out.state, "execution state diverged");
521 }
522
523 #[test]
524 fn invalid_bal_bytecode_is_validation_error() {
525 let bal = vec![AccountChanges {
526 address: Address::ZERO,
527 code_changes: vec![CodeChange::new(
528 BlockAccessIndex::new(1),
529 vec![0xef, 0x01, 0xde].into(),
530 )],
531 ..Default::default()
532 }];
533 let error =
534 <BlockExecutorFor<'_, EthEvmConfig> as BlockExecutor>::convert_block_access_list(&bal)
535 .unwrap_err();
536 let error = BalExecutionError::from(BlockAccessListDecodeError::new(error));
537 let error = InsertBlockErrorKind::from(error);
538 assert!(matches!(
539 error.ensure_validation_error(),
540 Ok(InsertBlockValidationError::BlockAccessListDecode(_))
541 ));
542 }
543
544 #[reth_concurrency::test]
545 fn empty_block_happy_path_round_trip() {
546 let evm_config = test_evm_config();
552 let input_bal = reference_bal_for_empty_block(&evm_config);
553 assert!(!input_bal.is_empty(), "system calls should populate the BAL");
555 let block = empty_amsterdam_block(compute_block_access_list_hash(&input_bal));
556
557 let output = run_execute_block(
558 &Runtime::test(),
559 evm_config,
560 db_factory(system_contracts_db()),
561 to_arc_decoded(input_bal),
562 &block,
563 Vec::<Recovered<TransactionSigned>>::new(),
564 )
565 .expect("empty BAL block should execute");
566 assert!(output.receipts.is_empty());
567 }
568
569 #[reth_concurrency::test]
570 fn multi_tx_happy_path_round_trip() {
571 let evm_config = test_evm_config();
579 let carol = Address::repeat_byte(0xca);
580 let sender_balance = U256::from(alloy_consensus::constants::ETH_TO_WEI);
581
582 let alice_kp = generate_key(&mut rng());
584 let alice =
585 Address::from_raw_public_key(&alice_kp.public_key().serialize_uncompressed()[1..]);
586 let bob_kp = generate_key(&mut rng());
587 let bob = Address::from_raw_public_key(&bob_kp.public_key().serialize_uncompressed()[1..]);
588
589 let txs = vec![
591 signed_transfer!(alice_kp, alice, carol, 100, 0, 21_000),
592 signed_transfer!(bob_kp, bob, carol, 200, 0, 21_000),
593 ];
594
595 let mut db = system_contracts_db();
597 insert_funded(&mut db, alice, sender_balance);
598 insert_funded(&mut db, bob, sender_balance);
599
600 let reference_bal = reference_bal_for_block(
602 &evm_config,
603 db.clone(),
604 &empty_amsterdam_block(B256::ZERO),
605 &txs,
606 );
607 let block = empty_amsterdam_block(compute_block_access_list_hash(&reference_bal));
608
609 let output = run_execute_block(
610 &Runtime::test(),
611 evm_config,
612 db_factory(db),
613 to_arc_decoded(reference_bal),
614 &block,
615 txs,
616 )
617 .expect("multi-transaction BAL block should execute");
618 assert_eq!(output.receipts.len(), 2);
619 assert!(output.gas_used >= 42_000);
620 }
621
622 #[reth_concurrency::test]
623 fn shadow_empty_block() {
624 assert_shadow_equal(
627 test_evm_config(),
628 system_contracts_db(),
629 empty_amsterdam_block(B256::ZERO),
630 Vec::new(),
631 );
632 }
633
634 #[reth_concurrency::test]
635 fn shadow_multi_value_transfer() {
636 let evm_config = test_evm_config();
639 let carol = Address::repeat_byte(0xca);
640 let sender_balance = U256::from(alloy_consensus::constants::ETH_TO_WEI);
641 let alice_kp = generate_key(&mut rng());
642 let alice =
643 Address::from_raw_public_key(&alice_kp.public_key().serialize_uncompressed()[1..]);
644 let bob_kp = generate_key(&mut rng());
645 let bob = Address::from_raw_public_key(&bob_kp.public_key().serialize_uncompressed()[1..]);
646 let mut db = system_contracts_db();
647 insert_funded(&mut db, alice, sender_balance);
648 insert_funded(&mut db, bob, sender_balance);
649 let txs = vec![
650 signed_transfer!(alice_kp, alice, carol, 100, 0, 21_000),
651 signed_transfer!(bob_kp, bob, carol, 200, 0, 21_000),
652 ];
653 assert_shadow_equal(evm_config, db, empty_amsterdam_block(B256::ZERO), txs);
654 }
655
656 #[reth_concurrency::test]
657 fn rejects_tx_gas_limit_that_exceeds_remaining_block_gas() {
658 let evm_config = test_evm_config();
662 let carol = Address::repeat_byte(0xca);
663 let sender_balance = U256::from(alloy_consensus::constants::ETH_TO_WEI);
664 let alice_kp = generate_key(&mut rng());
665 let alice =
666 Address::from_raw_public_key(&alice_kp.public_key().serialize_uncompressed()[1..]);
667 let bob_kp = generate_key(&mut rng());
668 let bob = Address::from_raw_public_key(&bob_kp.public_key().serialize_uncompressed()[1..]);
669 let txs = vec![
670 signed_transfer!(alice_kp, alice, carol, 100, 0, 990_000),
671 signed_transfer!(bob_kp, bob, carol, 200, 0, 990_000),
672 ];
673 let mut pre_block_db = system_contracts_db();
674 insert_funded(&mut pre_block_db, alice, sender_balance);
675 insert_funded(&mut pre_block_db, bob, sender_balance);
676 let reference_bal = reference_bal_for_block(
680 &evm_config,
681 pre_block_db.clone(),
682 &empty_amsterdam_block(B256::ZERO),
683 &txs,
684 );
685 let block = empty_amsterdam_block_with_gas_limit(
686 compute_block_access_list_hash(&reference_bal),
687 1_000_000,
688 );
689
690 let result = run_execute_block(
691 &Runtime::test(),
692 evm_config,
693 db_factory(pre_block_db),
694 to_arc_decoded(reference_bal),
695 &block,
696 txs,
697 );
698 match result {
699 Err(BalExecutionError::Execution(err)) => assert!(matches!(
700 err.as_validation(),
701 Some(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { .. })
702 )),
703 other => panic!("expected block gas validation error, got {other:?}"),
704 }
705 }
706
707 #[reth_concurrency::test]
708 fn shadow_tx_with_revert() {
709 let evm_config = test_evm_config();
715 let contract = Address::repeat_byte(0xde);
716 let key = generate_key(&mut rng());
717 let signer = Address::from_raw_public_key(&key.public_key().serialize_uncompressed()[1..]);
718 let mut db = system_contracts_db();
719 insert_funded(&mut db, signer, U256::from(alloy_consensus::constants::ETH_TO_WEI));
720 db.insert_account_info(
721 &contract,
722 AccountInfo::default()
723 .with_nonce(1)
724 .with_code(Bytecode::new_raw(Bytes::from_static(&[0x60, 0x00, 0x60, 0x00, 0xfd]))),
725 );
726 let tx = signed_transfer!(key, signer, contract, 0, 0, 50_000);
727 assert_shadow_equal(evm_config, db, empty_amsterdam_block(B256::ZERO), vec![tx]);
728 }
729
730 #[reth_concurrency::test]
731 fn shadow_tx_with_sstore() {
732 let evm_config = test_evm_config();
738 let contract = Address::repeat_byte(0x55);
739 let key = generate_key(&mut rng());
740 let signer = Address::from_raw_public_key(&key.public_key().serialize_uncompressed()[1..]);
741 let mut db = system_contracts_db();
742 insert_funded(&mut db, signer, U256::from(alloy_consensus::constants::ETH_TO_WEI));
743 db.insert_account_info(
744 &contract,
745 AccountInfo::default().with_nonce(1).with_code(Bytecode::new_raw(Bytes::from_static(
746 &[0x60, 0x42, 0x60, 0x00, 0x55, 0x00],
747 ))),
748 );
749 let tx = signed_transfer!(key, signer, contract, 0, 0, 100_000);
750 assert_shadow_equal(evm_config, db, empty_amsterdam_block(B256::ZERO), vec![tx]);
751 }
752
753 #[reth_concurrency::test]
754 fn returns_built_bal_for_final_hash_mismatch() {
755 let evm_config = test_evm_config();
760
761 let real_bal = reference_bal_for_empty_block(&evm_config);
763
764 let mut tampered_entries: Vec<AccountChanges> = real_bal;
766 tampered_entries.push(AccountChanges::new(Address::repeat_byte(0xff)));
767 let tampered_bal = AlloyBal::new(tampered_entries);
768
769 let tampered_access_list: BlockAccessList = tampered_bal.clone().into();
771 let tampered_hash = compute_block_access_list_hash(&tampered_access_list);
772 let block = empty_amsterdam_block(tampered_hash);
773 let received = Arc::new(DecodedBal::new(
774 tampered_bal.clone(),
775 alloy_rlp::encode(&tampered_bal).into(),
776 ));
777
778 let (_, built_bal) = run_execute_block_full(
779 &Runtime::test(),
780 evm_config,
781 db_factory(system_contracts_db()),
782 received,
783 &block,
784 Vec::<Recovered<TransactionSigned>>::new(),
785 )
786 .expect("BAL execution should return the rebuilt list");
787 assert_ne!(compute_block_access_list_hash(&built_bal), tampered_hash);
788 }
789
790 #[reth_concurrency::test]
791 fn canonical_make_db_failure() {
792 let block = empty_amsterdam_block(B256::ZERO);
794 let failing_make_db = |_: bool| -> Result<CacheDB<EmptyDB>, BalExecutionError> {
795 Err(reth_provider::ProviderError::BestBlockNotFound.into())
796 };
797 let result = run_execute_block(
798 &Runtime::test(),
799 test_evm_config(),
800 failing_make_db,
801 to_arc_decoded(BlockAccessList::default()),
802 &block,
803 Vec::<Recovered<TransactionSigned>>::new(),
804 );
805 assert!(matches!(result, Err(BalExecutionError::Provider(_))));
806 }
807
808 #[reth_concurrency::test]
809 fn worker_tx_recovery_error_becomes_validation_error() {
810 let evm_config = test_evm_config();
814 let block = empty_amsterdam_block(B256::ZERO);
815 let (tx_tx, tx_rx) =
816 channel::unbounded::<(usize, Result<Recovered<TransactionSigned>, io::Error>)>();
817 tx_tx.send((0, Err(io::Error::other("sig fail")))).unwrap();
818 drop(tx_tx);
819 let (receipt_tx, _receipt_rx) = channel::unbounded();
820 let evm_env = evm_config.evm_env(block.header()).unwrap();
821 let execution_ctx = evm_config.context_for_block(&block).unwrap();
822
823 let result = execute_block(
824 &Runtime::test(),
825 &evm_config,
826 &db_factory(system_contracts_db()),
827 to_arc_decoded(BlockAccessList::default()),
828 evm_env,
829 execution_ctx,
830 1, tx_rx,
832 receipt_tx,
833 );
834 assert!(matches!(
835 result,
836 Err(BalExecutionError::Execution(reth_evm::BlockExecutionError::Validation(_)))
837 ));
838 }
839
840 #[reth_concurrency::test]
841 fn gas_tracker_non_amsterdam_uses_cumulative_gas() {
842 let evm_config = non_amsterdam_evm_config();
845 let recipient = Address::repeat_byte(0xca);
846 let balance = U256::from(alloy_consensus::constants::ETH_TO_WEI);
847 let alice_key = generate_key(&mut rng());
848 let alice =
849 Address::from_raw_public_key(&alice_key.public_key().serialize_uncompressed()[1..]);
850 let bob_key = generate_key(&mut rng());
851 let bob = Address::from_raw_public_key(&bob_key.public_key().serialize_uncompressed()[1..]);
852 let txs = vec![
853 signed_transfer!(alice_key, alice, recipient, 1, 0, 21_000),
854 signed_transfer!(bob_key, bob, recipient, 1, 0, 980_000),
855 ];
856 let mut db = system_contracts_db();
857 insert_funded(&mut db, alice, balance);
858 insert_funded(&mut db, bob, balance);
859 let reference_bal = reference_bal_for_block(
860 &evm_config,
861 db.clone(),
862 &empty_amsterdam_block(B256::ZERO),
863 &txs,
864 );
865 let block = empty_amsterdam_block_with_gas_limit(
866 compute_block_access_list_hash(&reference_bal),
867 1_000_000,
868 );
869
870 let result = run_execute_block(
871 &Runtime::test(),
872 evm_config,
873 db_factory(db),
874 to_arc_decoded(reference_bal),
875 &block,
876 txs,
877 );
878 assert!(matches!(result, Err(BalExecutionError::Execution(_))));
879 }
880
881 #[reth_concurrency::test]
882 fn gas_tracker_caps_oversized_tx_gas_limit_at_tx_gas_limit_cap() {
883 const TX_GAS_LIMIT_CAP: u64 = 1 << 24;
886
887 let evm_config = test_evm_config();
888 let loop_contract = Address::repeat_byte(0x44);
889 let recipient = Address::repeat_byte(0xca);
890 let key = generate_key(&mut rng());
891 let signer = Address::from_raw_public_key(&key.public_key().serialize_uncompressed()[1..]);
892 let mut db = system_contracts_db();
893 insert_funded(&mut db, signer, U256::from(alloy_consensus::constants::ETH_TO_WEI));
894 db.insert_account_info(
895 &loop_contract,
896 AccountInfo::default()
897 .with_nonce(1)
898 .with_code(Bytecode::new_raw(Bytes::from_static(&[0x5b, 0x60, 0x00, 0x56]))),
899 );
900 let txs = vec![
901 signed_transfer!(key, signer, loop_contract, 0, 0, 13_100_000),
902 signed_transfer!(key, signer, recipient, 1, 1, TX_GAS_LIMIT_CAP + 1_000_000),
903 ];
904 let reference_block = empty_amsterdam_block(B256::ZERO);
905 let reference_bal =
906 reference_bal_for_block(&evm_config, db.clone(), &reference_block, &txs);
907 let block = empty_amsterdam_block(compute_block_access_list_hash(&reference_bal));
908
909 let output = run_execute_block(
910 &Runtime::test(),
911 evm_config,
912 db_factory(db),
913 to_arc_decoded(reference_bal),
914 &block,
915 txs,
916 )
917 .expect("the capped regular gas limit should fit the remaining block gas");
918 assert_eq!(output.receipts.len(), 2);
919 }
920
921 fn two_transfers(
924 tx1_gas_limit: u64,
925 tx2_gas_limit: u64,
926 fund_recipient: bool,
927 ) -> (CacheDB<EmptyDB>, Recovered<TransactionSigned>, Recovered<TransactionSigned>) {
928 let recipient = Address::repeat_byte(0xca);
929 let balance = U256::from(alloy_consensus::constants::ETH_TO_WEI);
930
931 let alice_kp = generate_key(&mut rng());
932 let alice =
933 Address::from_raw_public_key(&alice_kp.public_key().serialize_uncompressed()[1..]);
934 let bob_kp = generate_key(&mut rng());
935 let bob = Address::from_raw_public_key(&bob_kp.public_key().serialize_uncompressed()[1..]);
936
937 let mut pre_block_db = system_contracts_db();
938 insert_funded(&mut pre_block_db, alice, balance);
939 insert_funded(&mut pre_block_db, bob, balance);
940 if fund_recipient {
941 insert_funded(&mut pre_block_db, recipient, balance);
942 }
943
944 let chain_id = MAINNET.chain.id();
945 let make_tx = |kp, gas_limit, value| {
946 sign_tx_with_key_pair(
947 kp,
948 Transaction::Legacy(TxLegacy {
949 chain_id: Some(chain_id),
950 nonce: 0,
951 gas_price: 1,
952 gas_limit,
953 to: alloy_primitives::TxKind::Call(recipient),
954 value: U256::from(value),
955 input: Default::default(),
956 }),
957 )
958 };
959 let tx1 = Recovered::new_unchecked(make_tx(alice_kp, tx1_gas_limit, 100u64), alice);
960 let tx2 = Recovered::new_unchecked(make_tx(bob_kp, tx2_gas_limit, 200u64), bob);
961 (pre_block_db, tx1, tx2)
962 }
963
964 fn two_transfers_with_reference_bal(
967 evm_config: &EthEvmConfig,
968 tx_gas_limit: u64,
969 bal_covers_first: bool,
970 ) -> (
971 CacheDB<EmptyDB>,
972 BlockAccessList,
973 Recovered<reth_ethereum_primitives::TransactionSigned>,
974 Recovered<reth_ethereum_primitives::TransactionSigned>,
975 ) {
976 let (pre_block_db, tx1, tx2) = two_transfers(tx_gas_limit, tx_gas_limit, false);
977 let reference_block = empty_amsterdam_block(B256::ZERO);
978 let covered = if bal_covers_first { vec![tx1.clone()] } else { vec![] };
979 let reference_bal =
980 reference_bal_for_block(evm_config, pre_block_db.clone(), &reference_block, &covered);
981 (pre_block_db, reference_bal, tx1, tx2)
982 }
983
984 #[reth_concurrency::test]
985 fn default_tx_gas_limit_cap_matches_serial_execution() {
986 let evm_config = test_evm_config();
987 let block_gas_limit = 20_000_000;
988 let (db, tx1, tx2) = two_transfers(100_000, 19_990_000, true);
991 let txs = vec![tx1, tx2];
992 let (serial, bal) = run_serial_path(
993 &evm_config,
994 db.clone(),
995 &empty_amsterdam_block_with_gas_limit(B256::ZERO, block_gas_limit),
996 &txs,
997 );
998 let block = empty_amsterdam_block_with_gas_limit(
999 compute_block_access_list_hash(&bal),
1000 block_gas_limit,
1001 );
1002 let parallel = run_execute_block(
1003 &Runtime::test(),
1004 evm_config,
1005 db_factory(db),
1006 to_arc_decoded(bal),
1007 &block,
1008 txs,
1009 )
1010 .expect("the default regular cap must match serial execution");
1011 assert_eq!(parallel.receipts, serial.receipts);
1012 }
1013
1014 #[reth_concurrency::test]
1015 fn propagates_bal_miss_of_admitted_transaction_as_block_verdict() {
1016 let (pre_block_db, reference_bal, tx1, tx2) =
1019 two_transfers_with_reference_bal(&test_evm_config(), 100_000, false);
1020 let bal_hash = alloy_eip7928::compute_block_access_list_hash(&reference_bal);
1021 let block = empty_amsterdam_block(bal_hash);
1022
1023 let result = run_execute_block(
1024 &Runtime::test(),
1025 test_evm_config(),
1026 db_factory(pre_block_db),
1027 to_arc_decoded(reference_bal),
1028 &block,
1029 vec![tx1, tx2],
1030 );
1031
1032 match result {
1033 Err(BalExecutionError::Execution(err)) => {
1034 let Some(BlockValidationError::EVM { error, .. }) = err.as_validation() else {
1035 panic!("expected EVM validation error, got {err:?}");
1036 };
1037 let Some(evm2::registry::HandlerError::Database(database_error)) =
1038 error.downcast_ref::<evm2::registry::HandlerError>()
1039 else {
1040 panic!("expected owned database error, got {error:?}");
1041 };
1042 assert!(!database_error.is_fatal());
1043 assert!(database_error.downcast_ref::<evm2::evm::bal::BalError>().is_some());
1044 }
1045 Err(err) => panic!("expected BAL execution error, got {err:?}"),
1046 Ok(_) => panic!("expected BAL execution error, got Ok"),
1047 }
1048 }
1049
1050 #[reth_concurrency::test]
1051 fn admission_rejects_before_speculative_worker_failure_surfaces() {
1052 let (pre_block_db, reference_bal, tx1, tx2) =
1055 two_transfers_with_reference_bal(&test_evm_config(), 990_000, true);
1056 let bal_hash = alloy_eip7928::compute_block_access_list_hash(&reference_bal);
1057 let low_gas_block = empty_amsterdam_block_with_gas_limit(bal_hash, 1_000_000);
1058
1059 let result = run_execute_block(
1060 &Runtime::test(),
1061 test_evm_config(),
1062 db_factory(pre_block_db),
1063 to_arc_decoded(reference_bal),
1064 &low_gas_block,
1065 vec![tx1, tx2],
1066 );
1067
1068 match result {
1069 Err(BalExecutionError::Execution(err)) => assert!(
1070 matches!(
1071 err.as_validation(),
1072 Some(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { .. })
1073 ),
1074 "expected block gas validation error, got {err:?}"
1075 ),
1076 Err(err) => panic!("expected block gas validation error, got {err:?}"),
1077 Ok(_) => panic!("expected block gas validation error, got Ok"),
1078 }
1079 }
1080
1081 #[reth_concurrency::test]
1082 fn worker_reuses_provider_after_failure_and_finishes_earlier_transactions() {
1083 let evm_config = test_evm_config();
1084 let (pre_block_db, reference_bal, tx1, tx2) =
1085 two_transfers_with_reference_bal(&evm_config, 100_000, true);
1086 let block = empty_amsterdam_block(B256::ZERO);
1087 let received_bal = Arc::new(
1088 <BlockExecutorFor<'_, EthEvmConfig> as BlockExecutor>::convert_block_access_list(
1089 &reference_bal,
1090 )
1091 .unwrap(),
1092 );
1093 let setups = AtomicUsize::new(0);
1094 let make_db = |_: bool| {
1095 if setups.fetch_add(1, Ordering::Relaxed) != 0 {
1098 return Err(BalExecutionError::Provider(
1099 reth_errors::ProviderError::HeaderNotFound(B256::ZERO.into()),
1100 ));
1101 }
1102 Ok(pre_block_db.clone())
1103 };
1104 let (tx_tx, tx_rx) = channel::unbounded();
1105 tx_tx.send((2, Err(io::Error::other("sig fail")))).unwrap();
1108 tx_tx.send((1, Ok(tx2))).unwrap();
1109 tx_tx.send((0, Ok(tx1.clone()))).unwrap();
1110 drop(tx_tx);
1111 let (_abort_guard, abort_rx) = AbortGuard::new();
1112 let (result_tx, result_rx) = channel::unbounded();
1113 let runtime = Runtime::test();
1114 runtime.bal_streaming_pool().in_place_scope(|scope| {
1115 worker::spawn_worker(
1116 scope,
1117 tx_rx,
1118 abort_rx,
1119 result_tx,
1120 &evm_config,
1121 &make_db,
1122 received_bal,
1123 evm_config.evm_env(block.header()).unwrap(),
1124 evm_config.context_for_block(&block).unwrap(),
1125 );
1126 });
1127 let mut outputs = ordered_worker_outputs(&result_rx, 3);
1128 let output = outputs.next().unwrap().unwrap();
1129 assert_eq!(output.index, 0);
1130 assert_eq!(output.signer, tx1.signer());
1131 let mut serial = evm_config.executor_for_block(pre_block_db, &block).unwrap();
1132 serial.apply_pre_execution_changes().unwrap();
1133 let expected = serial.execute_transaction_without_commit(tx1).unwrap();
1134 assert_eq!(output.result.result(), expected.result());
1135 assert!(matches!(
1136 outputs.next().unwrap(),
1137 Err(OrderedWorkerOutputError::Worker(worker::BalWorkerError::Execution {
1138 tx_index: 1,
1139 ..
1140 }))
1141 ));
1142 let error = outputs.next().unwrap().err().unwrap();
1143 assert!(matches!(
1144 error,
1145 OrderedWorkerOutputError::Worker(worker::BalWorkerError::Transaction {
1146 tx_index: 2,
1147 ..
1148 })
1149 ));
1150 assert!(matches!(
1151 BalExecutionError::from(error),
1152 BalExecutionError::Execution(reth_evm::BlockExecutionError::Validation(_))
1153 ));
1154 assert!(outputs.next().is_none());
1155 assert_eq!(setups.load(Ordering::Relaxed), 1);
1156 }
1157
1158 #[reth_concurrency::test]
1159 fn amsterdam_state_gas_admission_matches_serial_execution() {
1160 let evm_config = EthEvmConfig::new(Arc::new(
1161 reth_chainspec::ChainSpecBuilder::mainnet().amsterdam_activated().build(),
1162 ));
1163 for (tx_gas_limit, complete_bal) in [(500_000, true), (990_000, true), (990_000, false)] {
1164 let (pre_block_db, partial_bal, tx1, tx2) =
1165 two_transfers_with_reference_bal(&evm_config, tx_gas_limit, true);
1166 let reference_block = empty_amsterdam_block(B256::ZERO);
1167 let reference_bal = if complete_bal {
1168 reference_bal_for_block(
1169 &evm_config,
1170 pre_block_db.clone(),
1171 &reference_block,
1172 &[tx1.clone(), tx2.clone()],
1173 )
1174 } else {
1175 partial_bal
1177 };
1178 let block = empty_amsterdam_block_with_gas_limit(
1179 compute_block_access_list_hash(&reference_bal),
1180 1_000_000,
1181 );
1182 let mut evm_env = evm_config.evm_env(block.header()).unwrap();
1183 assert!(evm_env.version.feature(evm2::EvmFeatures::EIP8037));
1184 evm_env.version.tx_gas_limit_cap = 400_000;
1187 let ctx = evm_config.context_for_block(&block).unwrap();
1188 let evm = evm_config.evm_with_env(pre_block_db.clone(), evm_env.clone());
1189 let mut serial = evm_config.block_executor_factory().create_executor(evm, ctx.clone());
1190 serial.apply_pre_execution_changes().unwrap();
1191 serial.execute_transaction(tx1.clone()).unwrap();
1192 let serial_result = serial.execute_transaction(tx2.clone());
1193
1194 let (receipt_tx, _receipt_rx) = channel::unbounded();
1195 let parallel_result = execute_block(
1196 &Runtime::test(),
1197 &evm_config,
1198 &|_: bool| Ok(pre_block_db.clone()),
1199 to_arc_decoded(reference_bal),
1200 evm_env,
1201 ctx,
1202 2,
1203 tx_stream(vec![tx1, tx2]),
1204 receipt_tx,
1205 );
1206 if tx_gas_limit == 500_000 {
1207 serial_result.unwrap();
1208 assert_eq!(parallel_result.unwrap().0.receipts, serial.receipts());
1209 } else {
1210 let serial_error = serial_result.unwrap_err();
1211 let Some(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas {
1212 block_available_gas,
1213 ..
1214 }) = serial_error.as_validation()
1215 else {
1216 panic!("expected serial state-gas admission error, got {serial_error:?}");
1217 };
1218 assert!(*block_available_gas < 990_000);
1219 let Err(BalExecutionError::Execution(parallel_error)) = parallel_result else {
1220 panic!("expected parallel state-gas admission error");
1221 };
1222 assert_eq!(parallel_error.to_string(), serial_error.to_string());
1223 }
1224 }
1225 }
1226}