Skip to main content

reth_evm_ethereum/
executor.rs

1//! EVM-backed Ethereum executor.
2//!
3//! [`EthBlockExecutor`] wraps evm2's [`evm2::block::ethereum::EthBlockExecutor`], which implements
4//! Ethereum block execution, and adapts it to reth's [`BlockExecutor`] trait.
5
6use reth_execution_types::{BlockState, StateUpdate};
7
8use crate::{
9    factory::{EthBlockExecutorFactory, EvmFactory},
10    EthBlockExecutionCtx, EthEvmEnv, RethReceiptBuilder,
11};
12use alloc::{borrow::Cow, sync::Arc, vec::Vec};
13use alloy_consensus::transaction::TransactionEnvelope;
14use alloy_eip7928::{BlockAccessIndex, BlockAccessList};
15use alloy_eips::{eip2718::Typed2718, eip7685::Requests};
16use alloy_primitives::B256;
17use evm2::{
18    block::{
19        ethereum::{self as evm2_eth, EthBlockRules, EthPostExecutionOutput},
20        BlockExecutor as _,
21    },
22    ethereum::TxEnvelope,
23    evm::Bal,
24    interpreter::Host,
25    BaseEvmTypes, Evm, EvmTypes,
26};
27use reth_chainspec::EthChainSpec;
28use reth_ethereum_forks::EthereumHardforks;
29use reth_ethereum_primitives::{Receipt, TransactionSigned};
30use reth_evm::{
31    BlockExecutionError, BlockExecutionOutput, BlockExecutor, ExecutorTx, GasOutput,
32    ReceiptBuilder, ReceiptBuilderCtx, RecoveredTx,
33};
34
35pub use evm2::block::ethereum::EthTransactionResultWithState;
36
37/// Adapts a reth [`ReceiptBuilder`] to evm2's receipt builder.
38#[derive(Debug, Clone, Copy, Default)]
39pub struct ReceiptBuilderAdapter<R>(pub R);
40
41impl<R: ReceiptBuilder> evm2::block::ReceiptBuilder for ReceiptBuilderAdapter<R> {
42    type Transaction = R::Transaction;
43    type Receipt = R::Receipt;
44
45    fn build_receipt<T: EvmTypes>(
46        &self,
47        ctx: ReceiptBuilderCtx<<R::Transaction as TransactionEnvelope>::TxType, evm2::TxResult<T>>,
48    ) -> R::Receipt {
49        self.0.build_receipt::<T>(ctx)
50    }
51}
52
53/// Configured Ethereum block executor backed by evm2.
54#[expect(missing_debug_implementations)]
55pub struct EthBlockExecutor<'a, T = BaseEvmTypes, R = RethReceiptBuilder>
56where
57    T: EvmTypes<Tx: Typed2718, TxResultExt: Send + Sync>,
58    R: ReceiptBuilder,
59{
60    /// evm2 executor that runs the block.
61    pub inner: evm2_eth::EthBlockExecutor<'a, T, ReceiptBuilderAdapter<R>>,
62    ctx: EthBlockExecutionCtx<'a>,
63}
64
65/// Converts reth's execution context into evm2's.
66fn evm2_ctx<'a>(ctx: &EthBlockExecutionCtx<'a>) -> evm2_eth::EthBlockExecutionCtx<'a> {
67    evm2_eth::EthBlockExecutionCtx {
68        tx_count_hint: ctx.tx_count_hint,
69        parent_hash: ctx.parent_hash,
70        parent_beacon_block_root: ctx.parent_beacon_block_root,
71        ommers: Cow::Borrowed(ctx.ommers),
72        withdrawals: ctx.withdrawals.clone(),
73    }
74}
75
76impl<'a, T, R> EthBlockExecutor<'a, T, R>
77where
78    T: EvmTypes<Tx: Typed2718, TxResultExt: Send + Sync>,
79    R: ReceiptBuilder,
80{
81    /// Creates a configured Ethereum block executor.
82    pub fn new<C>(
83        mut evm: Evm<'a, T>,
84        ctx: EthBlockExecutionCtx<'a>,
85        chain_spec: &C,
86        receipt_builder: R,
87    ) -> Self
88    where
89        C: EthChainSpec + EthereumHardforks + ?Sized,
90    {
91        let block_number = evm.block_env().number.to::<u64>();
92        let rules = EthBlockRules::new(
93            chain_spec,
94            block_number,
95            chain_spec.deposit_contract().map(|contract| contract.address),
96        );
97        let inner = evm2_eth::EthBlockExecutor::new(
98            evm,
99            evm2_ctx(&ctx),
100            rules,
101            ReceiptBuilderAdapter(receipt_builder),
102        );
103        Self { inner, ctx }
104    }
105
106    /// Returns the block execution context.
107    pub const fn context(&self) -> &EthBlockExecutionCtx<'a> {
108        &self.ctx
109    }
110
111    /// Returns the accumulated block state.
112    pub const fn block_state(&self) -> &BlockState {
113        self.inner.block_state()
114    }
115
116    /// Commits detached state without recording a transaction receipt or gas usage.
117    pub fn commit_pending_state(&mut self, state: &evm2::evm::PendingState) {
118        self.inner.commit_pending_state(state);
119    }
120
121    /// Sets the Ethereum fork used for block system calls and deposit request processing.
122    pub const fn set_spec_id(&mut self, spec_id: evm2::SpecId) {
123        self.inner.set_spec_id(spec_id);
124    }
125}
126
127impl<'a, T, R> BlockExecutor for EthBlockExecutor<'a, T, R>
128where
129    T: EvmTypes<Tx: Typed2718, TxResultExt: Send + Sync>,
130    R: ReceiptBuilder,
131{
132    type Transaction = R::Transaction;
133    type Receipt = R::Receipt;
134    type Evm = Evm<'a, T>;
135    type TransactionResultWithState =
136        EthTransactionResultWithState<T, <R::Transaction as TransactionEnvelope>::TxType>;
137    type BlockAccessList = Bal;
138
139    fn evm(&self) -> &Self::Evm {
140        &self.inner.evm
141    }
142
143    fn evm_mut(&mut self) -> &mut Self::Evm {
144        &mut self.inner.evm
145    }
146
147    fn set_state_hook(&mut self, hook: impl FnMut(StateUpdate) + Send + 'static) -> bool {
148        self.inner.set_state_hook(hook)
149    }
150
151    fn convert_block_access_list(
152        block_access_list: &BlockAccessList,
153    ) -> Result<Self::BlockAccessList, BlockExecutionError> {
154        Bal::try_from(block_access_list.as_slice()).map_err(BlockExecutionError::other)
155    }
156
157    fn set_block_access_list(&mut self, block_access_list: Arc<Self::BlockAccessList>) {
158        self.inner.set_block_access_list(block_access_list);
159    }
160
161    fn set_block_access_index(&mut self, index: BlockAccessIndex) {
162        self.inner.set_block_access_index(index);
163    }
164
165    fn enable_block_access_list_builder(&mut self) {
166        self.inner.enable_block_access_list_builder();
167    }
168
169    fn take_block_access_list(&mut self) -> Option<BlockAccessList> {
170        self.inner.take_block_access_list().map(Into::into)
171    }
172
173    fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> {
174        self.inner.apply_pre_execution_changes()
175    }
176
177    fn into_state(self) -> reth_evm::BundleState {
178        self.inner.into_state()
179    }
180
181    fn validate_transaction_gas_limit(
182        &mut self,
183        transaction_gas_limit: u64,
184    ) -> Result<(), BlockExecutionError> {
185        self.inner.validate_transaction_gas_limit(transaction_gas_limit)
186    }
187
188    fn execute_transaction_with_commit_condition(
189        &mut self,
190        transaction: impl ExecutorTx<Self>,
191        commit: impl FnOnce(&evm2::TxResult<T>, evm2::TxStateChanges<'_>) -> reth_evm::CommitChanges,
192    ) -> Result<Option<GasOutput>, BlockExecutionError> {
193        let (transaction, tx) = transaction.into_parts();
194        self.inner.execute_transaction_with_commit_condition((transaction, tx.tx()), commit)
195    }
196
197    fn execute_transaction_without_commit(
198        &mut self,
199        transaction: impl ExecutorTx<Self>,
200    ) -> Result<Self::TransactionResultWithState, BlockExecutionError> {
201        let (transaction, tx) = transaction.into_parts();
202        self.inner.execute_transaction_without_commit((transaction, tx.tx()))
203    }
204
205    fn commit_transaction(
206        &mut self,
207        output: Self::TransactionResultWithState,
208    ) -> Result<GasOutput, BlockExecutionError> {
209        self.inner.commit_transaction(output)
210    }
211
212    fn receipts(&self) -> &[Self::Receipt] {
213        &self.inner.receipts
214    }
215
216    fn finish_with_block_access_list(
217        self,
218    ) -> Result<(BlockExecutionOutput<Self::Receipt>, Option<BlockAccessList>), BlockExecutionError>
219    {
220        let (output, bal) = self.finish_with_prepared_block_access_list()?;
221        Ok((output, bal.map(Into::into)))
222    }
223
224    fn finish_with_prepared_block_access_list(
225        self,
226    ) -> Result<(BlockExecutionOutput<Self::Receipt>, Option<Bal>), BlockExecutionError> {
227        let (output, bal) = self.inner.finish_with_block_access_list()?;
228        Ok((output.into(), bal))
229    }
230}
231
232/// One block execution segment inside a merged big-block payload.
233pub struct EthBigBlockSegment<'a, T = BaseEvmTypes>
234where
235    T: EvmTypes<Tx = TxEnvelope>,
236{
237    /// Transaction index at which this segment starts.
238    pub start_tx: usize,
239    /// EVM environment for this segment.
240    pub evm_env: EthEvmEnv<T>,
241    /// Ethereum execution context for this segment.
242    pub ctx: EthBlockExecutionCtx<'a>,
243}
244
245impl<'a, T> Clone for EthBigBlockSegment<'a, T>
246where
247    T: EvmTypes<Tx = TxEnvelope>,
248{
249    fn clone(&self) -> Self {
250        Self { start_tx: self.start_tx, evm_env: self.evm_env.clone(), ctx: self.ctx.clone() }
251    }
252}
253
254impl<'a, T> core::fmt::Debug for EthBigBlockSegment<'a, T>
255where
256    T: EvmTypes<Tx = TxEnvelope>,
257    T::SpecId: core::fmt::Debug,
258{
259    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
260        f.debug_struct("EthBigBlockSegment")
261            .field("start_tx", &self.start_tx)
262            .field("evm_env", &self.evm_env)
263            .field("ctx", &self.ctx)
264            .finish()
265    }
266}
267
268/// Execution plan for a merged big-block payload.
269pub struct EthBigBlockPlan<'a, T = BaseEvmTypes>
270where
271    T: EvmTypes<Tx = TxEnvelope>,
272{
273    /// Ordered execution segments.
274    pub segments: Vec<EthBigBlockSegment<'a, T>>,
275    /// Total number of transactions across all segments.
276    pub transaction_count: usize,
277    /// Block hashes that must be available to `BLOCKHASH` during execution.
278    pub block_hashes: Vec<(u64, B256)>,
279}
280
281impl<'a, T> Clone for EthBigBlockPlan<'a, T>
282where
283    T: EvmTypes<Tx = TxEnvelope>,
284{
285    fn clone(&self) -> Self {
286        Self {
287            segments: self.segments.clone(),
288            transaction_count: self.transaction_count,
289            block_hashes: self.block_hashes.clone(),
290        }
291    }
292}
293
294impl<'a, T> core::fmt::Debug for EthBigBlockPlan<'a, T>
295where
296    T: EvmTypes<Tx = TxEnvelope>,
297    T::SpecId: core::fmt::Debug,
298{
299    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
300        f.debug_struct("EthBigBlockPlan")
301            .field("segments", &self.segments)
302            .field("transaction_count", &self.transaction_count)
303            .field("block_hashes", &self.block_hashes)
304            .finish()
305    }
306}
307
308impl<'a, T> EthBigBlockPlan<'a, T>
309where
310    T: EvmTypes<Tx = TxEnvelope>,
311{
312    /// Creates a plan and adds hashes for the boundaries between segments.
313    pub fn new(
314        segments: Vec<EthBigBlockSegment<'a, T>>,
315        prior_block_hashes: Vec<(u64, B256)>,
316        transaction_count: usize,
317    ) -> Self {
318        let mut block_hashes = segments
319            .iter()
320            .skip(1)
321            .map(|segment| {
322                (
323                    segment.evm_env.block.number.to::<u64>().saturating_sub(1),
324                    segment.ctx.parent_hash,
325                )
326            })
327            .collect::<Vec<_>>();
328        block_hashes.extend(prior_block_hashes);
329        block_hashes.sort_unstable_by_key(|(number, _)| *number);
330        Self { segments, transaction_count, block_hashes }
331    }
332
333    fn hashes_for_block(&self, block_number: u64) -> impl Iterator<Item = (u64, B256)> + '_ {
334        let min = block_number.saturating_sub(256);
335        self.block_hashes
336            .iter()
337            .copied()
338            .filter(move |(number, _)| *number >= min && *number < block_number)
339    }
340
341    fn segment_index_for_tx(&self, tx_index: usize) -> usize {
342        self.segments.partition_point(|segment| segment.start_tx <= tx_index).saturating_sub(1)
343    }
344}
345
346struct FinishedBigBlockSegment {
347    requests: Requests,
348    gas_used: u64,
349    blob_gas_used: u64,
350}
351
352/// Block executor for merged payloads that switches the EVM context at block boundaries.
353#[expect(missing_debug_implementations)]
354pub struct EthBigBlockExecutor<'a, C, F = crate::factory::RethEvmFactory>
355where
356    F: EvmFactory,
357    F::Types: EvmTypes<Tx = TxEnvelope>,
358    <F::Types as evm2::EvmTypesHost>::Tx: Typed2718,
359    <F::Types as evm2::EvmTypesHost>::TxResultExt: Send + Sync,
360{
361    inner: EthBlockExecutor<'a, F::Types, &'a RethReceiptBuilder>,
362    factory: &'a EthBlockExecutorFactory<RethReceiptBuilder, C, F>,
363    chain_spec: Arc<C>,
364    plan: EthBigBlockPlan<'a, F::Types>,
365    next_segment: usize,
366    tx_counter: usize,
367    segment_receipt_start: usize,
368    worker_segment: Option<usize>,
369    initialized: bool,
370    requests: Requests,
371    gas_used_offset: u64,
372    receipt_gas_used_offset: u64,
373    blob_gas_used_offset: u64,
374}
375
376impl<'a, C, F> EthBigBlockExecutor<'a, C, F>
377where
378    C: EthereumHardforks,
379    F: EvmFactory,
380    F::Types: EvmTypes<Tx = TxEnvelope>,
381    <F::Types as evm2::EvmTypesHost>::Tx: Typed2718,
382    <F::Types as evm2::EvmTypesHost>::TxResultExt: Send + Sync,
383{
384    pub(crate) fn new(
385        inner: EthBlockExecutor<'a, F::Types, &'a RethReceiptBuilder>,
386        factory: &'a EthBlockExecutorFactory<RethReceiptBuilder, C, F>,
387        chain_spec: Arc<C>,
388        plan: EthBigBlockPlan<'a, F::Types>,
389    ) -> Self {
390        assert!(!plan.segments.is_empty(), "big-block execution requires at least one segment");
391        Self {
392            inner,
393            factory,
394            chain_spec,
395            plan,
396            next_segment: 1,
397            tx_counter: 0,
398            segment_receipt_start: 0,
399            worker_segment: None,
400            initialized: false,
401            requests: Requests::default(),
402            gas_used_offset: 0,
403            receipt_gas_used_offset: 0,
404            blob_gas_used_offset: 0,
405        }
406    }
407
408    fn configure_segment(&mut self, segment_idx: usize) {
409        let segment = &self.plan.segments[segment_idx];
410        let env = &segment.evm_env;
411        // The version carries more than the spec and features (blob cap, gas caps, code limits), so
412        // install the whole segment config.
413        self.factory.reconfigure_evm(&mut self.inner.inner.evm, env);
414
415        let block_number = env.block.number.to::<u64>();
416        let rules = EthBlockRules::new(
417            self.chain_spec.as_ref(),
418            block_number,
419            self.inner.inner.rules().deposit_contract_address,
420        );
421        self.inner.ctx = segment.ctx.clone();
422        self.inner.inner.start_block(evm2_ctx(&segment.ctx), rules, segment_idx as u64 * 2);
423    }
424
425    fn reseed_block_hashes(&mut self, block_number: u64) {
426        for (number, hash) in self.plan.hashes_for_block(block_number) {
427            let number = evm2::interpreter::Word::from(number);
428            self.inner.inner.evm.overlay_db_mut().insert_block_hash(&number, &hash);
429        }
430    }
431
432    fn initialize(&mut self) -> Result<(), BlockExecutionError> {
433        if self.initialized {
434            return Ok(())
435        }
436
437        let raw_index = self.inner.inner.evm.state().bal_index().get();
438        let segment_idx = if raw_index == 0 {
439            0
440        } else {
441            let tx_index = (raw_index - 1) as usize;
442            if tx_index >= self.plan.transaction_count {
443                return Err(BlockExecutionError::msg("BAL index is outside big-block transactions"))
444            }
445            let segment_idx = self.plan.segment_index_for_tx(tx_index);
446            self.worker_segment = Some(segment_idx);
447            self.inner
448                .inner
449                .evm
450                .state_mut()
451                .set_bal_index(BlockAccessIndex::new(raw_index + segment_idx as u64 * 2));
452            self.next_segment = self.plan.segments.len();
453            segment_idx
454        };
455
456        self.configure_segment(segment_idx);
457        self.reseed_block_hashes(self.plan.segments[segment_idx].evm_env.block.number.to::<u64>());
458        self.initialized = true;
459        Ok(())
460    }
461
462    fn finish_segment(&mut self) -> Result<FinishedBigBlockSegment, BlockExecutionError> {
463        let EthPostExecutionOutput { requests, gas_used, blob_gas_used } =
464            self.inner.inner.apply_post_execution_changes(self.segment_receipt_start)?;
465        Ok(FinishedBigBlockSegment { requests, gas_used, blob_gas_used })
466    }
467
468    fn merge_segment(&mut self, segment: FinishedBigBlockSegment) {
469        self.requests.extend(segment.requests);
470        self.gas_used_offset += segment.gas_used;
471        self.receipt_gas_used_offset += self.inner.inner.cumulative_gas_used;
472        self.blob_gas_used_offset += segment.blob_gas_used;
473        self.inner.inner.reset_gas_used();
474    }
475
476    fn after_committed_transaction(&mut self) -> Result<(), BlockExecutionError> {
477        if let Some(receipt) = self.inner.inner.receipts.last_mut() {
478            receipt.cumulative_gas_used += self.receipt_gas_used_offset;
479        }
480        self.tx_counter += 1;
481        while self.worker_segment.is_none() &&
482            self.next_segment < self.plan.segments.len() &&
483            self.tx_counter == self.plan.segments[self.next_segment].start_tx
484        {
485            self.apply_segment_boundary()?;
486        }
487        Ok(())
488    }
489
490    fn apply_segment_boundary(&mut self) -> Result<(), BlockExecutionError> {
491        let segment = self.finish_segment()?;
492        self.merge_segment(segment);
493        self.inner.inner.evm.state_mut().bump_bal_index();
494
495        let segment_idx = self.next_segment;
496        self.next_segment += 1;
497        self.segment_receipt_start = self.inner.inner.receipts.len();
498        self.configure_segment(segment_idx);
499        self.reseed_block_hashes(self.plan.segments[segment_idx].evm_env.block.number.to::<u64>());
500        self.inner.apply_pre_execution_changes()
501    }
502}
503
504impl<'a, C, F> BlockExecutor for EthBigBlockExecutor<'a, C, F>
505where
506    C: EthereumHardforks,
507    F: EvmFactory,
508    F::Types: EvmTypes<Tx = TxEnvelope>,
509    <F::Types as evm2::EvmTypesHost>::Tx: Typed2718,
510    <F::Types as evm2::EvmTypesHost>::TxResultExt: Send + Sync,
511{
512    type Transaction = TransactionSigned;
513    type Receipt = Receipt;
514    type Evm = Evm<'a, F::Types>;
515    type TransactionResultWithState = EthTransactionResultWithState<F::Types>;
516    type BlockAccessList = Bal;
517
518    fn evm(&self) -> &Self::Evm {
519        self.inner.evm()
520    }
521
522    fn evm_mut(&mut self) -> &mut Self::Evm {
523        self.inner.evm_mut()
524    }
525
526    fn set_state_hook(&mut self, hook: impl FnMut(StateUpdate) + Send + 'static) -> bool {
527        self.inner.set_state_hook(hook)
528    }
529
530    fn convert_block_access_list(
531        block_access_list: &BlockAccessList,
532    ) -> Result<Self::BlockAccessList, BlockExecutionError> {
533        EthBlockExecutor::<F::Types>::convert_block_access_list(block_access_list)
534    }
535
536    fn set_block_access_list(&mut self, block_access_list: Arc<Self::BlockAccessList>) {
537        self.inner.set_block_access_list(block_access_list);
538    }
539
540    fn set_block_access_index(&mut self, index: BlockAccessIndex) {
541        let index = if let Some(current_segment) = self.worker_segment {
542            let raw_index = index.get();
543            if let Some(tx_index) = raw_index.checked_sub(1).map(|index| index as usize) {
544                if tx_index < self.plan.transaction_count {
545                    let segment = self.plan.segment_index_for_tx(tx_index);
546                    if segment != current_segment {
547                        self.configure_segment(segment);
548                        self.reseed_block_hashes(
549                            self.plan.segments[segment].evm_env.block.number.to::<u64>(),
550                        );
551                    }
552                    self.worker_segment = Some(segment);
553                    BlockAccessIndex::new(raw_index + segment as u64 * 2)
554                } else {
555                    index
556                }
557            } else {
558                index
559            }
560        } else {
561            index
562        };
563        self.inner.set_block_access_index(index);
564    }
565
566    fn enable_block_access_list_builder(&mut self) {
567        self.inner.enable_block_access_list_builder();
568    }
569
570    fn take_block_access_list(&mut self) -> Option<BlockAccessList> {
571        self.inner.take_block_access_list()
572    }
573
574    fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> {
575        self.initialize()?;
576        self.inner.apply_pre_execution_changes()?;
577        while self.worker_segment.is_none() &&
578            self.next_segment < self.plan.segments.len() &&
579            self.tx_counter == self.plan.segments[self.next_segment].start_tx
580        {
581            self.apply_segment_boundary()?;
582        }
583        Ok(())
584    }
585
586    fn into_state(self) -> reth_evm::BundleState {
587        self.inner.into_state()
588    }
589
590    fn validate_transaction_gas_limit(
591        &mut self,
592        gas_limit: u64,
593    ) -> Result<(), BlockExecutionError> {
594        self.inner.validate_transaction_gas_limit(gas_limit)
595    }
596
597    fn execute_transaction_with_commit_condition(
598        &mut self,
599        transaction: impl ExecutorTx<Self>,
600        commit: impl FnOnce(
601            &evm2::TxResult<F::Types>,
602            evm2::TxStateChanges<'_>,
603        ) -> reth_evm::CommitChanges,
604    ) -> Result<Option<GasOutput>, BlockExecutionError> {
605        self.initialize()?;
606        let output = self.inner.execute_transaction_with_commit_condition(transaction, commit)?;
607        if output.is_some() {
608            self.after_committed_transaction()?;
609        }
610        Ok(output)
611    }
612
613    fn execute_transaction_without_commit(
614        &mut self,
615        transaction: impl ExecutorTx<Self>,
616    ) -> Result<Self::TransactionResultWithState, BlockExecutionError> {
617        self.initialize()?;
618        self.inner.execute_transaction_without_commit(transaction)
619    }
620
621    fn commit_transaction(
622        &mut self,
623        output: Self::TransactionResultWithState,
624    ) -> Result<GasOutput, BlockExecutionError> {
625        self.initialize()?;
626        let output = self.inner.commit_transaction(output)?;
627        self.after_committed_transaction()?;
628        Ok(output)
629    }
630
631    fn receipts(&self) -> &[Receipt] {
632        self.inner.inner.receipts()
633    }
634
635    fn finish_with_block_access_list(
636        self,
637    ) -> Result<(BlockExecutionOutput<Receipt>, Option<BlockAccessList>), BlockExecutionError> {
638        let (output, bal) = self.finish_with_prepared_block_access_list()?;
639        Ok((output, bal.map(Into::into)))
640    }
641
642    fn finish_with_prepared_block_access_list(
643        mut self,
644    ) -> Result<(BlockExecutionOutput<Receipt>, Option<Bal>), BlockExecutionError> {
645        self.initialize()?;
646        let segment = self.finish_segment()?;
647        self.merge_segment(segment);
648        let block_access_list = self.inner.inner.evm.state_mut().take_bal_builder();
649        let result = reth_execution_types::BlockExecutionResult {
650            receipts: core::mem::take(&mut self.inner.inner.receipts),
651            requests: self.requests,
652            gas_used: self.gas_used_offset,
653            blob_gas_used: self.blob_gas_used_offset,
654        };
655        Ok((
656            BlockExecutionOutput::new(result, self.inner.inner.block_state.into_bundle()),
657            block_access_list,
658        ))
659    }
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665    use crate::dao_fork;
666    use alloy_consensus::{SignableTransaction, TxEip4844, TxLegacy};
667    use alloy_eip7928::BlockAccessIndex;
668    use alloy_primitives::{address, Address, Bytes, Signature, TxKind, B256, U256};
669    use evm2::{
670        block::ethereum::final_block_gas_used,
671        bytecode::Bytecode,
672        env::BlockEnv,
673        evm::{
674            AccountInfo, Database, Db, BUILDER_DEPOSIT_REQUEST_ADDRESS,
675            BUILDER_EXIT_REQUEST_ADDRESS, CONSOLIDATION_REQUEST_ADDRESS,
676            WITHDRAWAL_REQUEST_ADDRESS,
677        },
678        interpreter::Word,
679        BaseEvmTypes, SpecId,
680    };
681    use reth_chainspec::{Chain, ChainSpecBuilder, EthereumHardfork, ForkCondition};
682    use reth_ethereum_primitives::TransactionSigned;
683    use reth_evm::{BlockExecutor, BlockExecutorFactory, CommitChanges};
684    use reth_primitives_traits::Recovered;
685    use std::{collections::BTreeMap, convert::Infallible, sync::Arc};
686
687    fn segment(
688        start_tx: usize,
689        block_number: u64,
690        parent_hash: B256,
691    ) -> EthBigBlockSegment<'static> {
692        let block =
693            BlockEnv::<BaseEvmTypes> { number: U256::from(block_number), ..Default::default() };
694        EthBigBlockSegment {
695            start_tx,
696            evm_env: EthEvmEnv { block, ..EthEvmEnv::default() },
697            ctx: EthBlockExecutionCtx {
698                tx_count_hint: Some(1),
699                parent_hash,
700                parent_beacon_block_root: None,
701                ommers: &[],
702                withdrawals: None,
703                extra_data: Bytes::new(),
704                slot_number: None,
705            },
706        }
707    }
708
709    #[test]
710    fn big_block_plan_tracks_segment_boundaries_and_hashes() {
711        let plan = EthBigBlockPlan::new(
712            vec![segment(0, 10, B256::with_last_byte(1)), segment(2, 11, B256::with_last_byte(2))],
713            vec![(8, B256::with_last_byte(8)), (9, B256::with_last_byte(9))],
714            3,
715        );
716
717        assert_eq!(plan.transaction_count, 3);
718        assert_eq!(plan.segment_index_for_tx(0), 0);
719        assert_eq!(plan.segment_index_for_tx(1), 0);
720        assert_eq!(plan.segment_index_for_tx(2), 1);
721        assert_eq!(
722            plan.block_hashes,
723            vec![
724                (8, B256::with_last_byte(8)),
725                (9, B256::with_last_byte(9)),
726                (10, B256::with_last_byte(2)),
727            ]
728        );
729    }
730
731    #[derive(Default)]
732    struct TestDatabase {
733        accounts: BTreeMap<Address, AccountInfo>,
734    }
735
736    impl Database for TestDatabase {
737        type Error = Infallible;
738
739        fn get_account(&mut self, address: &Address) -> Result<Option<AccountInfo>, Self::Error> {
740            Ok(self.accounts.get(address).cloned())
741        }
742
743        fn get_code_by_hash(&mut self, _code_hash: &B256) -> Result<Bytecode, Self::Error> {
744            Ok(Bytecode::default())
745        }
746
747        fn get_storage(&mut self, _address: &Address, _key: &Word) -> Result<Word, Self::Error> {
748            Ok(Word::ZERO)
749        }
750
751        fn get_block_hash(&mut self, _number: &Word) -> Result<B256, Self::Error> {
752            Ok(B256::ZERO)
753        }
754    }
755
756    /// Deploys no-op request contracts, which blocks from Prague on call.
757    fn insert_request_contracts(database: &mut TestDatabase) {
758        let code = Bytecode::new_legacy(Bytes::from_static(&[0x00]));
759        for address in [
760            WITHDRAWAL_REQUEST_ADDRESS,
761            CONSOLIDATION_REQUEST_ADDRESS,
762            BUILDER_DEPOSIT_REQUEST_ADDRESS,
763            BUILDER_EXIT_REQUEST_ADDRESS,
764        ] {
765            database.accounts.insert(address, AccountInfo::default().with_code(code.clone()));
766        }
767    }
768
769    fn transfer(from: Address, to: Address, nonce: u64) -> Recovered<TransactionSigned> {
770        let tx = TransactionSigned::Legacy(
771            TxLegacy {
772                chain_id: Some(1),
773                nonce,
774                gas_limit: 21_000,
775                gas_price: 1,
776                to: TxKind::Call(to),
777                value: U256::from(1),
778                ..Default::default()
779            }
780            .into_signed(Signature::test_signature()),
781        );
782        Recovered::new_unchecked(tx, from)
783    }
784
785    #[test]
786    fn big_block_executor_preserves_state_across_segment_switch() {
787        let from = address!("0000000000000000000000000000000000000001");
788        let first_target = address!("0000000000000000000000000000000000000010");
789        let second_target = address!("0000000000000000000000000000000000000020");
790        let mut database = TestDatabase::default();
791        database
792            .accounts
793            .insert(from, AccountInfo::default().with_balance(U256::from(1_000_000u64)));
794
795        let mut first = segment(0, 1, B256::with_last_byte(1));
796        first.evm_env = EthEvmEnv::new(SpecId::LONDON, first.evm_env.block, 1);
797        first.evm_env.block.basefee = U256::from(1);
798        let mut second = segment(1, 2, B256::with_last_byte(2));
799        second.evm_env = EthEvmEnv::new(SpecId::SHANGHAI, second.evm_env.block, 1);
800        second.evm_env.block.basefee = U256::from(1);
801        let plan = EthBigBlockPlan::new(vec![first, second], Vec::new(), 2);
802        let chain_spec =
803            ChainSpecBuilder::mainnet().chain(Chain::mainnet()).paris_activated().build();
804        let factory = super::super::factory::EthBigBlockExecutorFactory::new(
805            super::super::factory::EthBlockExecutorFactory::new(Arc::new(chain_spec)),
806        );
807        let mut env = plan.segments[0].evm_env.clone();
808        env.version.features.remove(evm2::EvmFeatures::BASE_FEE_CHECK);
809        let evm = factory.evm_with_env(Db::new(database), env);
810        let mut executor = factory.create_executor(evm, plan);
811
812        executor.apply_pre_execution_changes().expect("first segment pre-execution");
813        assert!(executor
814            .execute_transaction_with_commit_condition(
815                transfer(from, first_target, 0),
816                |_, changes| {
817                    // The callback sees the uncommitted state changes before deciding.
818                    assert_eq!(changes.account_info(&from).expect("sender changed").nonce, 1);
819                    CommitChanges::No
820                }
821            )
822            .expect("discarded transaction")
823            .is_none());
824        executor
825            .execute_transaction_with_commit_condition(transfer(from, first_target, 0), |_, _| {
826                CommitChanges::Yes
827            })
828            .expect("first segment transaction")
829            .expect("transaction committed");
830        executor
831            .execute_transaction_with_commit_condition(transfer(from, second_target, 1), |_, _| {
832                CommitChanges::Yes
833            })
834            .expect("second segment transaction")
835            .expect("transaction committed");
836        let (output, _) = executor.finish_with_block_access_list().expect("finish big block");
837
838        assert_eq!(output.result.receipts.len(), 2);
839        assert_eq!(output.result.gas_used, 42_000);
840        assert_eq!(output.account(&first_target).unwrap().unwrap().balance, U256::from(1));
841        assert_eq!(output.account(&second_target).unwrap().unwrap().balance, U256::from(1));
842        // The prewarming environment must not change the beneficiary reward during execution.
843        assert_eq!(
844            output
845                .account(&Address::ZERO)
846                .flatten()
847                .map(|account| account.balance)
848                .unwrap_or_default(),
849            U256::ZERO
850        );
851    }
852
853    #[test]
854    fn amsterdam_admission_enforces_uncapped_state_gas_budget() {
855        let factory = super::super::factory::EthBlockExecutorFactory::new(Arc::new(
856            ChainSpecBuilder::mainnet().amsterdam_activated().build(),
857        ));
858        let ctx = segment(0, 1, B256::ZERO).ctx;
859        for cap in [u64::MAX, 400_000] {
860            let mut env = EthEvmEnv::new(
861                SpecId::AMSTERDAM,
862                BlockEnv::<BaseEvmTypes> { gas_limit: U256::from(1_000_000), ..Default::default() },
863                1,
864            );
865            env.version.tx_gas_limit_cap = cap;
866            let evm = factory.evm_with_env(Db::new(TestDatabase::default()), env);
867            let mut executor = factory.create_executor(evm, ctx.clone());
868            executor.inner.block_state_gas_used = 600_000;
869            executor.inner.block_regular_gas_used = 0;
870            assert!(executor.validate_transaction_gas_limit(500_000).is_err());
871            assert!(executor.validate_transaction_gas_limit(400_000).is_ok());
872        }
873    }
874
875    #[test]
876    fn pre_london_creation_preserves_legacy_ef01_code() {
877        let sender = Address::with_last_byte(1);
878        let mut database = TestDatabase::default();
879        database
880            .accounts
881            .insert(sender, AccountInfo::default().with_balance(U256::from(1_000_000)));
882        let factory = super::super::factory::EthBlockExecutorFactory::new(Arc::new(
883            ChainSpecBuilder::mainnet().berlin_activated().build(),
884        ));
885        let env = EthEvmEnv::new(
886            SpecId::BERLIN,
887            BlockEnv::<BaseEvmTypes> { gas_limit: U256::from(1_000_000), ..Default::default() },
888            1,
889        );
890        let evm = factory.evm_with_env(Db::new(database), env);
891        let mut executor = factory.create_executor(evm, segment(0, 1, B256::ZERO).ctx);
892        let tx = TransactionSigned::Legacy(
893            TxLegacy {
894                chain_id: Some(1),
895                gas_limit: 100_000,
896                gas_price: 1,
897                to: TxKind::Create,
898                // Return the two-byte runtime code 0xEF01 from initcode.
899                input: alloy_primitives::bytes!("61ef016000526002601ef3"),
900                ..Default::default()
901            }
902            .into_signed(Signature::test_signature()),
903        );
904        executor.apply_pre_execution_changes().unwrap();
905        executor.execute_transaction(Recovered::new_unchecked(tx, sender)).unwrap();
906        let (output, _) = executor.finish_with_block_access_list().unwrap();
907        let code = &output.state.contracts[&alloy_primitives::keccak256([0xef, 0x01])];
908        assert!(code.is_legacy());
909        assert_eq!(code.original_bytes().as_ref(), &[0xef, 0x01]);
910    }
911
912    #[test]
913    fn executor_applies_dao_fork_balance_transfer_before_rewards() {
914        let dao_account = address!("d4fe7bc31cedb7bfb8a345f31e668033056b2728");
915        let beneficiary = address!("bf4ed7b27f1d666546e30d74d50d173d20bca754");
916        let mut database = TestDatabase::default();
917        database.accounts.insert(dao_account, AccountInfo::default().with_balance(U256::from(7)));
918
919        let chain_spec = ChainSpecBuilder::mainnet()
920            .with_fork(EthereumHardfork::Dao, ForkCondition::Block(1))
921            .build();
922        let factory = super::super::factory::EthBlockExecutorFactory::new(Arc::new(chain_spec));
923        let env = EthEvmEnv::new(
924            SpecId::FRONTIER,
925            BlockEnv::<BaseEvmTypes> {
926                number: U256::from(1),
927                gas_limit: U256::from(30_000),
928                beneficiary: dao_account,
929                ..Default::default()
930            },
931            1,
932        );
933        let evm = factory.evm_with_env(Db::new(database), env);
934        let mut executor = factory.create_executor(
935            evm,
936            EthBlockExecutionCtx {
937                tx_count_hint: Some(0),
938                parent_hash: B256::ZERO,
939                parent_beacon_block_root: None,
940                ommers: &[],
941                withdrawals: None,
942                extra_data: Bytes::new(),
943                slot_number: None,
944            },
945        );
946
947        executor.apply_pre_execution_changes().expect("DAO block pre-execution succeeds");
948        let (output, _) =
949            executor.finish_with_block_access_list().expect("DAO block post-execution succeeds");
950
951        assert_eq!(
952            output.account(&dao_account).unwrap().unwrap().balance,
953            U256::from(5 * alloy_consensus::constants::ETH_TO_WEI)
954        );
955        assert_eq!(output.account(&beneficiary).unwrap().unwrap().balance, U256::from(7));
956    }
957
958    #[test]
959    fn dao_fork_drain_keeps_empty_accounts() {
960        let [absent, empty, empty_with_balance, nonce_only, ..] = dao_fork::DAO_HARDFORK_ACCOUNTS;
961        let beneficiary = dao_fork::DAO_HARDFORK_BENEFICIARY;
962
963        let execute = |accounts: &[(Address, AccountInfo)]| {
964            let mut database = TestDatabase::default();
965            database.accounts.extend(accounts.iter().cloned());
966            let chain_spec = ChainSpecBuilder::mainnet()
967                .with_fork(EthereumHardfork::Dao, ForkCondition::Block(1))
968                .build();
969            let factory = super::super::factory::EthBlockExecutorFactory::new(Arc::new(chain_spec));
970            let env = EthEvmEnv::new(
971                SpecId::FRONTIER,
972                BlockEnv::<BaseEvmTypes> {
973                    number: U256::from(1),
974                    gas_limit: U256::from(30_000),
975                    beneficiary: Address::with_last_byte(0xbe),
976                    ..Default::default()
977                },
978                1,
979            );
980            let evm = factory.evm_with_env(Db::new(database), env);
981            let mut executor = factory.create_executor(evm, segment(0, 1, B256::ZERO).ctx);
982            let (tx, rx) = std::sync::mpsc::channel();
983            executor.set_state_hook(move |update| tx.send(update).unwrap());
984            executor.apply_pre_execution_changes().unwrap();
985            let output = executor.finish_with_block_access_list().unwrap().0;
986            // The streamed updates hash to the same state as the finished bundle.
987            let mut streamed = reth_trie_common::HashedPostState::default();
988            for update in rx.try_iter() {
989                streamed.extend(reth_execution_types::state_update_to_hashed_post_state(&update));
990            }
991            let bundled = reth_trie_common::HashedPostState::from_bundle_state::<
992                reth_trie_common::KeccakKeyHasher,
993            >(&output.state.state);
994            assert_eq!(streamed.into_sorted(), bundled.into_sorted());
995            output
996        };
997
998        // The fork predates EIP-161, so drained accounts stay, absent and empty ones included.
999        let output = execute(&[
1000            (empty, AccountInfo::default()),
1001            (empty_with_balance, AccountInfo::default().with_balance(U256::from(7))),
1002            (nonce_only, AccountInfo { nonce: 1, balance: U256::from(3), ..Default::default() }),
1003        ]);
1004        assert_eq!(output.account(&absent).unwrap().unwrap().balance, U256::ZERO);
1005        assert_eq!(output.account(&empty), None);
1006        assert_eq!(output.account(&empty_with_balance).unwrap().unwrap().balance, U256::ZERO);
1007        let nonce_only_account = output.account(&nonce_only).unwrap().unwrap();
1008        assert_eq!((nonce_only_account.nonce, nonce_only_account.balance), (1, U256::ZERO));
1009        assert_eq!(output.account(&beneficiary).unwrap().unwrap().balance, U256::from(10));
1010
1011        // Nothing is drained, and the empty beneficiary stays unchanged.
1012        let output = execute(&[(beneficiary, AccountInfo::default())]);
1013        assert_eq!(output.account(&beneficiary), None);
1014    }
1015
1016    #[test]
1017    fn big_block_worker_switches_segments_from_bal_index() {
1018        let from = address!("0000000000000000000000000000000000000001");
1019        let target = address!("0000000000000000000000000000000000000010");
1020        let mut database = TestDatabase::default();
1021        database
1022            .accounts
1023            .insert(from, AccountInfo::default().with_balance(U256::from(1_000_000u64)));
1024
1025        let mut first = segment(0, 1, B256::with_last_byte(1));
1026        first.evm_env = EthEvmEnv::new(SpecId::FRONTIER, first.evm_env.block, 1);
1027        let mut second = segment(1, 2, B256::with_last_byte(2));
1028        second.evm_env = EthEvmEnv::new(SpecId::LONDON, second.evm_env.block, 1);
1029        let plan = EthBigBlockPlan::new(vec![first, second], Vec::new(), 2);
1030        let chain_spec =
1031            ChainSpecBuilder::mainnet().chain(Chain::mainnet()).paris_activated().build();
1032        let factory = super::super::factory::EthBigBlockExecutorFactory::new(
1033            super::super::factory::EthBlockExecutorFactory::new(Arc::new(chain_spec)),
1034        );
1035        let evm = factory.evm_with_env(Db::new(database), plan.segments[0].evm_env.clone());
1036        let mut executor = factory.create_executor(evm, plan);
1037
1038        executor.set_block_access_index(BlockAccessIndex::new(2));
1039        executor
1040            .execute_transaction_without_commit(transfer(from, target, 0))
1041            .expect("worker transaction in second segment");
1042        assert_eq!(executor.evm().block().number, U256::from(2));
1043
1044        executor.set_block_access_index(BlockAccessIndex::new(1));
1045        executor
1046            .execute_transaction_without_commit(transfer(from, target, 0))
1047            .expect("worker transaction in first segment");
1048        assert_eq!(executor.evm().block().number, U256::from(1));
1049    }
1050
1051    #[test]
1052    fn amsterdam_header_uses_bottleneck_gas_dimension() {
1053        assert_eq!(final_block_gas_used(true, 90, 70, 120), 120);
1054        assert_eq!(final_block_gas_used(true, 90, 130, 120), 130);
1055        assert_eq!(final_block_gas_used(false, 90, 130, 120), 90);
1056    }
1057
1058    #[test]
1059    fn amsterdam_segment_receipts_use_transaction_gas() {
1060        let sender = Address::with_last_byte(0x10);
1061        let mut database = TestDatabase::default();
1062        database.accounts.insert(
1063            sender,
1064            AccountInfo::default().with_balance(U256::from(1_000_000_000_000_000_000u64)),
1065        );
1066        insert_request_contracts(&mut database);
1067        let segments = (0..2)
1068            .map(|index| {
1069                let mut segment = segment(index, index as u64 + 1, B256::ZERO);
1070                segment.ctx.parent_beacon_block_root = Some(B256::ZERO);
1071                segment.evm_env = EthEvmEnv::new(
1072                    SpecId::AMSTERDAM,
1073                    BlockEnv::<BaseEvmTypes> {
1074                        number: U256::from(index + 1),
1075                        gas_limit: U256::from(30_000_000),
1076                        ..Default::default()
1077                    },
1078                    1,
1079                );
1080                segment
1081            })
1082            .collect();
1083        let plan = EthBigBlockPlan::new(segments, Vec::new(), 2);
1084        let factory = super::super::factory::EthBigBlockExecutorFactory::new(
1085            super::super::factory::EthBlockExecutorFactory::new(Arc::new(
1086                ChainSpecBuilder::mainnet().amsterdam_activated().build(),
1087            )),
1088        );
1089        let evm = factory.evm_with_env(Db::new(database), plan.segments[0].evm_env.clone());
1090        let mut executor = factory.create_executor(evm, plan);
1091        executor.apply_pre_execution_changes().unwrap();
1092        let mut receipt_gas = 0;
1093        let mut block_gas = 0;
1094        for nonce in 0..2 {
1095            // Creating a recipient charges state gas, separating receipt and block gas totals.
1096            let tx = TransactionSigned::Legacy(
1097                TxLegacy {
1098                    chain_id: Some(1),
1099                    nonce,
1100                    gas_limit: 1_000_000,
1101                    gas_price: 1,
1102                    to: TxKind::Call(Address::with_last_byte(0x20 + nonce as u8)),
1103                    value: U256::from(1),
1104                    ..Default::default()
1105                }
1106                .into_signed(Signature::test_signature()),
1107            );
1108            let gas = executor.execute_transaction(Recovered::new_unchecked(tx, sender)).unwrap();
1109            let segment_block_gas = gas.regular_gas_used().max(gas.state_gas_used());
1110            assert_ne!(gas.tx_gas_used(), segment_block_gas);
1111            receipt_gas += gas.tx_gas_used();
1112            block_gas += segment_block_gas;
1113            let receipt = executor.receipts().last().unwrap();
1114            assert!(receipt.success);
1115            assert_eq!(receipt.cumulative_gas_used, receipt_gas);
1116        }
1117        let (output, _) = executor.finish_with_block_access_list().unwrap();
1118        assert_eq!(output.result.gas_used, block_gas);
1119    }
1120
1121    #[test]
1122    fn big_block_segment_switch_installs_segment_blob_cap() {
1123        let sender = Address::with_last_byte(0x10);
1124        let mut database = TestDatabase::default();
1125        database.accounts.insert(
1126            sender,
1127            AccountInfo::default().with_balance(U256::from(1_000_000_000_000_000_000u64)),
1128        );
1129        insert_request_contracts(&mut database);
1130        let segments = [9, 6]
1131            .into_iter()
1132            .enumerate()
1133            .map(|(index, max_blobs_per_tx)| {
1134                let mut segment = segment(index, index as u64 + 1, B256::ZERO);
1135                segment.ctx.parent_beacon_block_root = Some(B256::ZERO);
1136                segment.evm_env = EthEvmEnv::new(
1137                    SpecId::PRAGUE,
1138                    BlockEnv::<BaseEvmTypes> {
1139                        number: U256::from(index + 1),
1140                        gas_limit: U256::from(30_000_000),
1141                        ..Default::default()
1142                    },
1143                    1,
1144                );
1145                segment.evm_env.version.max_blobs_per_tx = max_blobs_per_tx;
1146                segment
1147            })
1148            .collect();
1149        let plan = EthBigBlockPlan::new(segments, Vec::new(), 2);
1150        let factory = super::super::factory::EthBigBlockExecutorFactory::new(
1151            super::super::factory::EthBlockExecutorFactory::new(Arc::new(
1152                ChainSpecBuilder::mainnet().prague_activated().build(),
1153            )),
1154        );
1155        let evm = factory.evm_with_env(Db::new(database), plan.segments[0].evm_env.clone());
1156        let mut executor = factory.create_executor(evm, plan);
1157        executor.apply_pre_execution_changes().unwrap();
1158
1159        let blob_tx = |nonce| {
1160            let tx = TransactionSigned::Eip4844(
1161                TxEip4844 {
1162                    chain_id: 1,
1163                    nonce,
1164                    gas_limit: 100_000,
1165                    max_fee_per_gas: 1,
1166                    max_priority_fee_per_gas: 1,
1167                    to: Address::with_last_byte(0x20),
1168                    max_fee_per_blob_gas: 1,
1169                    blob_versioned_hashes: vec![B256::repeat_byte(1); 7],
1170                    ..Default::default()
1171                }
1172                .into_signed(Signature::test_signature()),
1173            );
1174            Recovered::new_unchecked(tx, sender)
1175        };
1176        executor.execute_transaction(blob_tx(0)).expect("seven blobs fit the first segment cap");
1177        let err = executor.execute_transaction(blob_tx(1)).unwrap_err();
1178        assert!(err.to_string().contains("too many blobs: have 7, max 6"), "{err}");
1179    }
1180}