Skip to main content

reth_stages/stages/execution/
mod.rs

1use crate::stages::MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD;
2use alloy_consensus::BlockHeader;
3use alloy_eip7928::bal::Bal;
4use alloy_primitives::BlockNumber;
5use num_traits::Zero;
6use reth_chainspec::{ChainSpecProvider, EthereumHardforks};
7use reth_config::config::ExecutionConfig;
8use reth_consensus::FullConsensus;
9use reth_db::{static_file::HeaderMask, tables};
10use reth_evm::{execute::Executor, metrics::ExecutorMetrics, ConfigureEvm};
11use reth_execution_types::Chain;
12use reth_exex::{ExExManagerHandle, ExExNotification, ExExNotificationSource};
13use reth_primitives_traits::{format_gas_throughput, BlockBody, NodePrimitives};
14use reth_provider::{
15    providers::{StaticFileProvider, StaticFileWriter},
16    BlockHashReader, BlockReader, DBProvider, EitherWriter, ExecutionOutcome,
17    HashedPostStateProvider, HeaderProvider, LatestStateProviderRef, OriginalValuesKnown,
18    ProviderError, StateWriteConfig, StateWriter, StaticFileProviderFactory, StatsReader,
19    StoragePath, StorageSettingsCache, TransactionVariant,
20};
21use reth_revm::database::StateProviderDatabase;
22use reth_stages_api::{
23    BlockErrorKind, CheckpointBlockRange, EntitiesCheckpoint, ExecInput, ExecOutput,
24    ExecutionCheckpoint, ExecutionStageThresholds, Stage, StageCheckpoint, StageError, StageId,
25    UnwindInput, UnwindOutput,
26};
27use reth_static_file_types::StaticFileSegment;
28use std::{
29    cmp::{max, Ordering},
30    collections::BTreeMap,
31    ops::RangeInclusive,
32    sync::Arc,
33    task::{ready, Context, Poll},
34    time::{Duration, Instant},
35};
36use tracing::*;
37
38use super::missing_static_data_error;
39
40/// Slot-preimage database for recovering plain storage keys from hashed keys during
41/// pre-Cancun `SELFDESTRUCT` handling.
42pub mod slot_preimages;
43
44/// The execution stage executes all transactions and
45/// update history indexes.
46///
47/// Input tables:
48/// - [`tables::CanonicalHeaders`] get next block to execute.
49/// - [`tables::Headers`] get for revm environment variables.
50/// - [`tables::BlockBodyIndices`] to get tx number
51/// - [`tables::Transactions`] to execute
52///
53/// For state access [`LatestStateProviderRef`] provides us latest state and history state
54/// For latest most recent state [`LatestStateProviderRef`] would need (Used for execution Stage):
55/// - [`tables::PlainAccountState`]
56/// - [`tables::Bytecodes`]
57/// - [`tables::PlainStorageState`]
58///
59/// Tables updated after state finishes execution:
60/// - [`tables::PlainAccountState`]
61/// - [`tables::PlainStorageState`]
62/// - [`tables::Bytecodes`]
63/// - [`tables::AccountChangeSets`]
64/// - [`tables::StorageChangeSets`]
65///
66/// For unwinds we are accessing:
67/// - [`tables::BlockBodyIndices`] get tx index to know what needs to be unwinded
68/// - [`tables::AccountsHistory`] to remove change set and apply old values to
69/// - [`tables::PlainAccountState`] [`tables::StoragesHistory`] to remove change set and apply old
70///   values to [`tables::PlainStorageState`]
71// false positive, we cannot derive it if !DB: Debug.
72#[derive(Debug)]
73pub struct ExecutionStage<E>
74where
75    E: ConfigureEvm,
76{
77    /// The stage's internal block executor
78    evm_config: E,
79    /// The consensus instance for validating blocks.
80    consensus: Arc<dyn FullConsensus<E::Primitives>>,
81    /// The commit thresholds of the execution stage.
82    thresholds: ExecutionStageThresholds,
83    /// The highest threshold (in number of blocks) for switching between incremental
84    /// and full calculations across [`super::MerkleStage`], [`super::AccountHashingStage`] and
85    /// [`super::StorageHashingStage`]. This is required to figure out if can prune or not
86    /// changesets on subsequent pipeline runs.
87    external_clean_threshold: u64,
88    /// Input for the post execute commit hook.
89    /// Set after every [`ExecutionStage::execute`] and cleared after
90    /// [`ExecutionStage::post_execute_commit`].
91    post_execute_commit_input: Option<Chain<E::Primitives>>,
92    /// Input for the post unwind commit hook.
93    /// Set after every [`ExecutionStage::unwind`] and cleared after
94    /// [`ExecutionStage::post_unwind_commit`].
95    post_unwind_commit_input: Option<Chain<E::Primitives>>,
96    /// Handle to communicate with `ExEx` manager.
97    exex_manager_handle: ExExManagerHandle<E::Primitives>,
98    /// Executor metrics.
99    metrics: ExecutorMetrics,
100}
101
102impl<E> ExecutionStage<E>
103where
104    E: ConfigureEvm,
105{
106    /// Create new execution stage with specified config.
107    pub fn new(
108        evm_config: E,
109        consensus: Arc<dyn FullConsensus<E::Primitives>>,
110        thresholds: ExecutionStageThresholds,
111        external_clean_threshold: u64,
112        exex_manager_handle: ExExManagerHandle<E::Primitives>,
113    ) -> Self {
114        Self {
115            external_clean_threshold,
116            evm_config,
117            consensus,
118            thresholds,
119            post_execute_commit_input: None,
120            post_unwind_commit_input: None,
121            exex_manager_handle,
122            metrics: ExecutorMetrics::default(),
123        }
124    }
125
126    /// Create an execution stage with the provided executor.
127    ///
128    /// The commit threshold will be set to [`MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD`].
129    pub fn new_with_executor(
130        evm_config: E,
131        consensus: Arc<dyn FullConsensus<E::Primitives>>,
132    ) -> Self {
133        Self::new(
134            evm_config,
135            consensus,
136            ExecutionStageThresholds::default(),
137            MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD,
138            ExExManagerHandle::empty(),
139        )
140    }
141
142    /// Create new instance of [`ExecutionStage`] from configuration.
143    pub fn from_config(
144        evm_config: E,
145        consensus: Arc<dyn FullConsensus<E::Primitives>>,
146        config: ExecutionConfig,
147        external_clean_threshold: u64,
148    ) -> Self {
149        Self::new(
150            evm_config,
151            consensus,
152            config.into(),
153            external_clean_threshold,
154            ExExManagerHandle::empty(),
155        )
156    }
157
158    /// Returns whether we can perform pruning of [`tables::AccountChangeSets`] and
159    /// [`tables::StorageChangeSets`].
160    ///
161    /// This function verifies whether the [`super::MerkleStage`] or Hashing stages will run from
162    /// scratch. If at least one stage isn't starting anew, it implies that pruning of
163    /// changesets cannot occur. This is determined by checking the highest clean threshold
164    /// (`self.external_clean_threshold`) across the stages.
165    ///
166    /// Given that `start_block` changes with each checkpoint, it's necessary to inspect
167    /// [`tables::AccountsTrie`] to ensure that [`super::MerkleStage`] hasn't
168    /// been previously executed.
169    fn can_prune_changesets(
170        &self,
171        provider: impl StatsReader,
172        start_block: u64,
173        max_block: u64,
174    ) -> Result<bool, StageError> {
175        // We can only prune changesets if we're not executing MerkleStage from scratch (by
176        // threshold or first-sync)
177        Ok(max_block - start_block > self.external_clean_threshold ||
178            provider.count_entries::<tables::AccountsTrie>()?.is_zero())
179    }
180
181    /// Performs consistency check on static files.
182    ///
183    /// This function compares the highest receipt number recorded in the database with that in the
184    /// static file to detect any discrepancies due to unexpected shutdowns or database rollbacks.
185    /// **If the height in the static file is higher**, it rolls back (unwinds) the static file.
186    /// **Conversely, if the height in the database is lower**, it triggers a rollback in the
187    /// database (by returning [`StageError`]) until the heights in both the database and static
188    /// file match.
189    fn ensure_consistency<Provider>(
190        &self,
191        provider: &Provider,
192        checkpoint: u64,
193        unwind_to: Option<u64>,
194    ) -> Result<(), StageError>
195    where
196        Provider: StaticFileProviderFactory
197            + DBProvider
198            + BlockReader
199            + HeaderProvider
200            + StorageSettingsCache,
201    {
202        // On old nodes, if there's any receipts pruning configured, receipts are written directly
203        // to database and inconsistencies are expected.
204        if EitherWriter::receipts_destination(provider).is_database() {
205            return Ok(())
206        }
207
208        // Get next expected receipt number
209        let next_receipt_num =
210            provider.block_body_indices(checkpoint)?.map(|b| b.next_tx_num()).unwrap_or(0);
211
212        let static_file_provider = provider.static_file_provider();
213
214        // Get next expected receipt number in static files
215        let next_static_file_receipt_num = static_file_provider
216            .get_highest_static_file_tx(StaticFileSegment::Receipts)
217            .map(|num| num + 1)
218            .unwrap_or(0);
219
220        // Get highest block number in static files for receipts
221        let static_file_block_num = static_file_provider
222            .get_highest_static_file_block(StaticFileSegment::Receipts)
223            .unwrap_or(0);
224
225        // Check if we had any unexpected shutdown after committing to static files, but
226        // NOT committing to database.
227        match static_file_block_num.cmp(&checkpoint) {
228            // It can be equal when it's a chain of empty blocks, but we still need to update the
229            // last block in the range.
230            Ordering::Greater | Ordering::Equal => {
231                let mut static_file_producer =
232                    static_file_provider.latest_writer(StaticFileSegment::Receipts)?;
233                static_file_producer.prune_receipts(
234                    next_static_file_receipt_num.saturating_sub(next_receipt_num),
235                    checkpoint,
236                )?;
237                // Since this is a database <-> static file inconsistency, we commit the change
238                // straight away.
239                static_file_producer.commit()?;
240            }
241            Ordering::Less => {
242                // If we are already in the process of unwind, this might be fine because we will
243                // fix the inconsistency right away.
244                if let Some(unwind_to) = unwind_to &&
245                    unwind_to <= static_file_block_num
246                {
247                    return Ok(())
248                }
249
250                // Otherwise, this is a real inconsistency - database has more blocks than static
251                // files
252                return Err(missing_static_data_error(
253                    next_static_file_receipt_num.saturating_sub(1),
254                    &static_file_provider,
255                    provider,
256                    StaticFileSegment::Receipts,
257                )?)
258            }
259        }
260
261        Ok(())
262    }
263}
264
265impl<E, Provider> Stage<Provider> for ExecutionStage<E>
266where
267    E: ConfigureEvm,
268    Provider: DBProvider
269        + BlockReader<
270            Block = <E::Primitives as NodePrimitives>::Block,
271            Header = <E::Primitives as NodePrimitives>::BlockHeader,
272        > + StaticFileProviderFactory<
273            Primitives: NodePrimitives<BlockHeader: reth_db_api::table::Value>,
274        > + StatsReader
275        + BlockHashReader
276        + StateWriter<Receipt = <E::Primitives as NodePrimitives>::Receipt>
277        + StorageSettingsCache
278        + StoragePath
279        + ChainSpecProvider<ChainSpec: EthereumHardforks>,
280{
281    /// Return the id of the stage
282    fn id(&self) -> StageId {
283        StageId::Execution
284    }
285
286    fn poll_execute_ready(
287        &mut self,
288        cx: &mut Context<'_>,
289        _: ExecInput,
290    ) -> Poll<Result<(), StageError>> {
291        ready!(self.exex_manager_handle.poll_ready(cx));
292
293        Poll::Ready(Ok(()))
294    }
295
296    /// Execute the stage
297    fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError> {
298        if input.target_reached() {
299            return Ok(ExecOutput::done(input.checkpoint()))
300        }
301
302        let start_block = input.next_block();
303        let max_block = input.target();
304        let static_file_provider = provider.static_file_provider();
305
306        self.ensure_consistency(provider, input.checkpoint().block_number, None)?;
307
308        let db = StateProviderDatabase(LatestStateProviderRef::new(provider));
309        let mut executor = self.evm_config.batch_executor(db);
310
311        // Progress tracking
312        let mut stage_progress = start_block;
313        let mut stage_checkpoint = execution_checkpoint(
314            &static_file_provider,
315            start_block,
316            max_block,
317            input.checkpoint(),
318        )?;
319
320        let mut fetch_block_duration = Duration::default();
321        let mut execution_duration = Duration::default();
322
323        let mut last_block = start_block;
324        let mut last_execution_duration = Duration::default();
325        let mut last_cumulative_gas = 0;
326        let mut last_log_instant = Instant::now();
327        let log_duration = Duration::from_secs(10);
328
329        debug!(target: "sync::stages::execution", start = start_block, end = max_block, "Executing range");
330
331        // Execute block range
332        let mut cumulative_gas = 0;
333        let batch_start = Instant::now();
334
335        let mut blocks = Vec::new();
336        let mut results = Vec::new();
337        // Reused across blocks for BAL hash encoding.
338        let mut bal_buf = Vec::new();
339        for block_number in start_block..=max_block {
340            // Fetch the block
341            let fetch_block_start = Instant::now();
342
343            // we need the block's transactions but we don't need the transaction hashes
344            let block = provider
345                .recovered_block(block_number.into(), TransactionVariant::NoHash)?
346                .ok_or_else(|| ProviderError::HeaderNotFound(block_number.into()))?;
347
348            fetch_block_duration += fetch_block_start.elapsed();
349
350            cumulative_gas += block.header().gas_used();
351
352            // Configure the executor to use the current state.
353            trace!(target: "sync::stages::execution", number = block_number, txs = block.body().transactions().len(), "Executing block");
354
355            // Execute the block
356            let execute_start = Instant::now();
357
358            let result = self.metrics.metered_one(&block, |input| {
359                executor.execute_one(input).map_err(|error| StageError::Block {
360                    block: Box::new(block.block_with_parent()),
361                    error: BlockErrorKind::Execution(error),
362                })
363            })?;
364
365            let built_bal = executor.take_bal().map(Bal::from);
366            if let Some(bal) = &built_bal &&
367                let Err(err) = bal.validate_gas_limit(block.header().gas_limit())
368            {
369                return Err(StageError::Block {
370                    block: Box::new(block.block_with_parent()),
371                    error: BlockErrorKind::Validation(err.into()),
372                })
373            }
374            let bal_hash = built_bal.as_ref().map(|bal| bal.compute_hash_with_buf(&mut bal_buf));
375
376            if let Err(err) =
377                self.consensus.validate_block_post_execution(&block, &result, None, bal_hash)
378            {
379                return Err(StageError::Block {
380                    block: Box::new(block.block_with_parent()),
381                    error: BlockErrorKind::Validation(err),
382                })
383            }
384            results.push(result);
385
386            execution_duration += execute_start.elapsed();
387
388            // Log execution throughput
389            if last_log_instant.elapsed() >= log_duration {
390                info!(
391                    target: "sync::stages::execution",
392                    start = last_block,
393                    end = block_number,
394                    throughput = format_gas_throughput(cumulative_gas - last_cumulative_gas, execution_duration - last_execution_duration),
395                    "Executed block range"
396                );
397
398                last_block = block_number + 1;
399                last_execution_duration = execution_duration;
400                last_cumulative_gas = cumulative_gas;
401                last_log_instant = Instant::now();
402            }
403
404            stage_progress = block_number;
405            stage_checkpoint.progress.processed += block.header().gas_used();
406
407            // If we have ExExes we need to save the block in memory for later
408            if self.exex_manager_handle.has_exexs() {
409                blocks.push(block);
410            }
411
412            // Check if we should commit now
413            if self.thresholds.is_end_of_batch(
414                block_number - start_block,
415                executor.size_hint() as u64,
416                cumulative_gas,
417                batch_start.elapsed(),
418            ) {
419                break
420            }
421        }
422
423        // prepare execution output for writing
424        let time = Instant::now();
425        let mut state = ExecutionOutcome::from_blocks(
426            start_block,
427            executor.into_state().take_bundle(),
428            results,
429        );
430        let write_preparation_duration = time.elapsed();
431
432        // log the gas per second for the range we just executed
433        debug!(
434            target: "sync::stages::execution",
435            start = start_block,
436            end = stage_progress,
437            throughput = format_gas_throughput(cumulative_gas, execution_duration),
438            "Finished executing block range"
439        );
440
441        // Prepare the input for post execute commit hook, where an `ExExNotification` will be sent.
442        //
443        // Note: Since we only write to `blocks` if there are any ExExes, we don't need to perform
444        // the `has_exexs` check here as well
445        if !blocks.is_empty() {
446            let previous_input = self.post_execute_commit_input.replace(Chain::new(
447                blocks,
448                state.clone(),
449                BTreeMap::new(),
450            ));
451
452            if previous_input.is_some() {
453                // Not processing the previous post execute commit input is a critical error, as it
454                // means that we didn't send the notification to ExExes
455                return Err(StageError::PostExecuteCommit(
456                    "Previous post execute commit input wasn't processed",
457                ))
458            }
459        }
460
461        let time = Instant::now();
462
463        if self.can_prune_changesets(provider, start_block, max_block)? {
464            let prune_modes = provider.prune_modes_ref();
465
466            // Iterate over all reverts and clear them if pruning is configured.
467            for block_number in start_block..=max_block {
468                let Some(reverts) =
469                    state.bundle.reverts.get_mut((block_number - start_block) as usize)
470                else {
471                    break
472                };
473
474                // If both account history and storage history pruning is configured, clear reverts
475                // for this block.
476                if prune_modes
477                    .account_history
478                    .is_some_and(|m| m.should_prune(block_number, max_block)) &&
479                    prune_modes
480                        .storage_history
481                        .is_some_and(|m| m.should_prune(block_number, max_block))
482                {
483                    reverts.clear();
484                }
485            }
486        }
487
488        // When using hashed state (storage.v2), inject plain storage-slot keys into wipe
489        // reverts for self-destructed accounts. Without this, the changeset writer would only
490        // see hashed slot keys (from `HashedStorages`) which pollutes the entire codebase.
491        //
492        // SELFDESTRUCT no longer destroys storage post-Cancun, so this is only needed for
493        // pre-Cancun blocks. Post-Cancun we can remove the preimage db entirely.
494        if provider.cached_storage_settings().use_hashed_state() {
495            let start_header = provider
496                .header_by_number(start_block)?
497                .ok_or_else(|| ProviderError::HeaderNotFound(start_block.into()))?;
498
499            let path = provider.storage_path().join("preimage");
500            if !provider.chain_spec().is_cancun_active_at_timestamp(start_header.timestamp()) {
501                slot_preimages::inject_plain_wipe_slots(&path, provider, &mut state)?;
502            } else if path.exists() {
503                // Post-Cancun: no more self-destructs, preimage db is no longer needed.
504                let _ = std::fs::remove_dir_all(&path);
505            }
506        }
507
508        // Write output. When `use_hashed_state` is enabled, `write_state` skips writing to
509        // plain account/storage tables and only writes bytecodes and changesets. The hashed
510        // state is then written separately below.
511        provider.write_state(&state, OriginalValuesKnown::Yes, StateWriteConfig::default())?;
512
513        if provider.cached_storage_settings().use_hashed_state() {
514            let hashed_state =
515                LatestStateProviderRef::new(provider).hashed_post_state(&state.bundle)?;
516            provider.write_hashed_state(&hashed_state.into_sorted())?;
517        }
518
519        let db_write_duration = time.elapsed();
520        debug!(
521            target: "sync::stages::execution",
522            block_fetch = ?fetch_block_duration,
523            execution = ?execution_duration,
524            write_preparation = ?write_preparation_duration,
525            write = ?db_write_duration,
526            "Execution time"
527        );
528
529        let done = stage_progress == max_block;
530        Ok(ExecOutput {
531            checkpoint: StageCheckpoint::new(stage_progress)
532                .with_execution_stage_checkpoint(stage_checkpoint),
533            done,
534        })
535    }
536
537    fn post_execute_commit(&mut self) -> Result<(), StageError> {
538        let Some(chain) = self.post_execute_commit_input.take() else { return Ok(()) };
539
540        // NOTE: We can ignore the error here, since an error means that the channel is closed,
541        // which means the manager has died, which then in turn means the node is shutting down.
542        let _ = self.exex_manager_handle.send(
543            ExExNotificationSource::Pipeline,
544            ExExNotification::ChainCommitted { new: Arc::new(chain) },
545        );
546
547        Ok(())
548    }
549
550    /// Unwind the stage.
551    fn unwind(
552        &mut self,
553        provider: &Provider,
554        input: UnwindInput,
555    ) -> Result<UnwindOutput, StageError> {
556        let (range, unwind_to, _) =
557            input.unwind_block_range_with_threshold(self.thresholds.max_blocks.unwrap_or(u64::MAX));
558        if range.is_empty() {
559            return Ok(UnwindOutput {
560                checkpoint: input.checkpoint.with_block_number(input.unwind_to),
561            })
562        }
563
564        reject_cancun_boundary_unwind(provider, input.checkpoint.block_number, unwind_to)?;
565
566        self.ensure_consistency(provider, input.checkpoint.block_number, Some(unwind_to))?;
567
568        // Unwind account and storage changesets, as well as receipts.
569        //
570        // This also updates `PlainStorageState` and `PlainAccountState`.
571        let bundle_state_with_receipts = provider.take_state_above(unwind_to)?;
572
573        // Prepare the input for post unwind commit hook, where an `ExExNotification` will be sent.
574        if self.exex_manager_handle.has_exexs() {
575            // Get the blocks for the unwound range.
576            let blocks = provider.recovered_block_range(range.clone())?;
577            let previous_input = self.post_unwind_commit_input.replace(Chain::new(
578                blocks,
579                bundle_state_with_receipts,
580                BTreeMap::new(),
581            ));
582
583            debug_assert!(
584                previous_input.is_none(),
585                "Previous post unwind commit input wasn't processed"
586            );
587            if let Some(previous_input) = previous_input {
588                tracing::debug!(target: "sync::stages::execution", ?previous_input, "Previous post unwind commit input wasn't processed");
589            }
590        }
591
592        // Update the checkpoint.
593        let mut stage_checkpoint = input.checkpoint.execution_stage_checkpoint();
594        if let Some(stage_checkpoint) = stage_checkpoint.as_mut() {
595            for block_number in range {
596                stage_checkpoint.progress.processed -= provider
597                    .header_by_number(block_number)?
598                    .ok_or_else(|| ProviderError::HeaderNotFound(block_number.into()))?
599                    .gas_used();
600            }
601        }
602        let checkpoint = if let Some(stage_checkpoint) = stage_checkpoint {
603            StageCheckpoint::new(unwind_to).with_execution_stage_checkpoint(stage_checkpoint)
604        } else {
605            StageCheckpoint::new(unwind_to)
606        };
607
608        Ok(UnwindOutput { checkpoint })
609    }
610
611    fn post_unwind_commit(&mut self) -> Result<(), StageError> {
612        let Some(chain) = self.post_unwind_commit_input.take() else { return Ok(()) };
613
614        // NOTE: We can ignore the error here, since an error means that the channel is closed,
615        // which means the manager has died, which then in turn means the node is shutting down.
616        let _ = self.exex_manager_handle.send(
617            ExExNotificationSource::Pipeline,
618            ExExNotification::ChainReverted { old: Arc::new(chain) },
619        );
620
621        Ok(())
622    }
623}
624
625fn reject_cancun_boundary_unwind<Provider>(
626    provider: &Provider,
627    checkpoint_block: u64,
628    unwind_to: u64,
629) -> Result<(), StageError>
630where
631    Provider: HeaderProvider + ChainSpecProvider<ChainSpec: EthereumHardforks>,
632{
633    let checkpoint_header = provider
634        .header_by_number(checkpoint_block)?
635        .ok_or_else(|| ProviderError::HeaderNotFound(checkpoint_block.into()))?;
636    let unwind_to_header = provider
637        .header_by_number(unwind_to)?
638        .ok_or_else(|| ProviderError::HeaderNotFound(unwind_to.into()))?;
639    let checkpoint_is_cancun =
640        provider.chain_spec().is_cancun_active_at_timestamp(checkpoint_header.timestamp());
641    let unwind_to_is_cancun =
642        provider.chain_spec().is_cancun_active_at_timestamp(unwind_to_header.timestamp());
643    if checkpoint_is_cancun && !unwind_to_is_cancun {
644        return Err(StageError::Fatal(
645            std::io::Error::other(format!(
646                "execution unwind across Cancun activation boundary is not allowed: checkpoint \
647                 block #{checkpoint_block} (ts={}) is Cancun-active but unwind target \
648                 #{unwind_to} (ts={}) is pre-Cancun",
649                checkpoint_header.timestamp(),
650                unwind_to_header.timestamp()
651            ))
652            .into(),
653        ))
654    }
655
656    Ok(())
657}
658
659fn execution_checkpoint<N>(
660    provider: &StaticFileProvider<N>,
661    start_block: BlockNumber,
662    max_block: BlockNumber,
663    checkpoint: StageCheckpoint,
664) -> Result<ExecutionCheckpoint, ProviderError>
665where
666    N: NodePrimitives<BlockHeader: reth_db_api::table::Value>,
667{
668    Ok(match checkpoint.execution_stage_checkpoint() {
669        // If checkpoint block range fully matches our range,
670        // we take the previously used stage checkpoint as-is.
671        Some(stage_checkpoint @ ExecutionCheckpoint { block_range, .. })
672            if block_range == CheckpointBlockRange::from(start_block..=max_block) =>
673        {
674            stage_checkpoint
675        }
676        // If checkpoint block range precedes our range seamlessly, we take the previously used
677        // stage checkpoint and add the amount of gas from our range to the checkpoint total.
678        Some(ExecutionCheckpoint {
679            block_range: CheckpointBlockRange { to, .. },
680            progress: EntitiesCheckpoint { processed, total },
681        }) if to == start_block - 1 => ExecutionCheckpoint {
682            block_range: CheckpointBlockRange { from: start_block, to: max_block },
683            progress: EntitiesCheckpoint {
684                processed,
685                total: total + calculate_gas_used_from_headers(provider, start_block..=max_block)?,
686            },
687        },
688        // If checkpoint block range ends on the same block as our range, we take the previously
689        // used stage checkpoint.
690        Some(ExecutionCheckpoint { block_range: CheckpointBlockRange { to, .. }, progress })
691            if to == max_block =>
692        {
693            ExecutionCheckpoint {
694                block_range: CheckpointBlockRange { from: start_block, to: max_block },
695                progress,
696            }
697        }
698        // If there's any other non-empty checkpoint, we calculate the remaining amount of total gas
699        // to be processed not including the checkpoint range.
700        Some(ExecutionCheckpoint { progress: EntitiesCheckpoint { processed, .. }, .. }) => {
701            let after_checkpoint_block_number =
702                calculate_gas_used_from_headers(provider, checkpoint.block_number + 1..=max_block)?;
703
704            ExecutionCheckpoint {
705                block_range: CheckpointBlockRange { from: start_block, to: max_block },
706                progress: EntitiesCheckpoint {
707                    processed,
708                    total: processed + after_checkpoint_block_number,
709                },
710            }
711        }
712        // Otherwise, we recalculate the whole stage checkpoint including the amount of gas
713        // already processed, if there's any.
714        _ => {
715            let genesis_block_number = provider.genesis_block_number();
716            let processed = calculate_gas_used_from_headers(
717                provider,
718                genesis_block_number..=max(start_block - 1, genesis_block_number),
719            )?;
720
721            ExecutionCheckpoint {
722                block_range: CheckpointBlockRange { from: start_block, to: max_block },
723                progress: EntitiesCheckpoint {
724                    processed,
725                    total: processed +
726                        calculate_gas_used_from_headers(provider, start_block..=max_block)?,
727                },
728            }
729        }
730    })
731}
732
733/// Calculates the total amount of gas used from the headers in the given range.
734pub fn calculate_gas_used_from_headers<N>(
735    provider: &StaticFileProvider<N>,
736    range: RangeInclusive<BlockNumber>,
737) -> Result<u64, ProviderError>
738where
739    N: NodePrimitives<BlockHeader: reth_db_api::table::Value>,
740{
741    debug!(target: "sync::stages::execution", ?range, "Calculating gas used from headers");
742
743    let mut gas_total = 0;
744
745    let start = Instant::now();
746
747    for entry in provider.fetch_range_iter(
748        StaticFileSegment::Headers,
749        *range.start()..*range.end() + 1,
750        |cursor, number| cursor.get_one::<HeaderMask<N::BlockHeader>>(number.into()),
751    )? {
752        if let Some(entry) = entry? {
753            gas_total += entry.gas_used();
754        }
755    }
756
757    let duration = start.elapsed();
758    debug!(target: "sync::stages::execution", ?range, ?duration, "Finished calculating gas used from headers");
759
760    Ok(gas_total)
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766    use crate::{stages::MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD, test_utils::TestStageDB};
767    use alloy_primitives::{address, hex_literal::hex, keccak256, Address, B256, U256};
768    use alloy_rlp::Decodable;
769    use assert_matches::assert_matches;
770    use reth_chainspec::{ChainSpecBuilder, EthereumHardfork, ForkCondition};
771    use reth_db_api::{
772        models::{metadata::StorageSettings, AccountBeforeTx},
773        transaction::{DbTx, DbTxMut},
774    };
775    use reth_ethereum_consensus::EthBeaconConsensus;
776    use reth_ethereum_primitives::Block;
777    use reth_evm_ethereum::EthEvmConfig;
778    use reth_primitives_traits::{Account, Block as _, Bytecode, SealedBlock, StorageEntry};
779    use reth_provider::{
780        test_utils::{create_test_provider_factory, create_test_provider_factory_with_chain_spec},
781        AccountReader, BlockWriter, DatabaseProviderFactory, ReceiptProvider,
782        StaticFileProviderFactory,
783    };
784    use reth_prune::PruneModes;
785    use reth_prune_types::{PruneMode, ReceiptsLogPruneConfig};
786    use reth_revm::revm::database::{AccountStatus, BundleAccount};
787    use reth_stages_api::StageUnitCheckpoint;
788    use reth_testing_utils::generators;
789    use std::collections::BTreeMap;
790
791    fn stage() -> ExecutionStage<EthEvmConfig> {
792        let evm_config =
793            EthEvmConfig::new(Arc::new(ChainSpecBuilder::mainnet().berlin_activated().build()));
794        let consensus = Arc::new(EthBeaconConsensus::new(Arc::new(
795            ChainSpecBuilder::mainnet().berlin_activated().build(),
796        )));
797        ExecutionStage::new(
798            evm_config,
799            consensus,
800            ExecutionStageThresholds {
801                max_blocks: Some(100),
802                max_changes: None,
803                max_cumulative_gas: None,
804                max_duration: None,
805            },
806            MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD,
807            ExExManagerHandle::empty(),
808        )
809    }
810
811    #[test]
812    fn destroyed_storage_is_materialized_without_reverts() {
813        let factory = create_test_provider_factory();
814        let provider = factory.database_provider_rw().unwrap();
815        let address = Address::repeat_byte(0x11);
816        let hashed_address = keccak256(address);
817        let first_slot = B256::repeat_byte(0x22);
818        let second_slot = B256::repeat_byte(0x33);
819
820        provider
821            .tx_ref()
822            .put::<tables::HashedStorages>(
823                hashed_address,
824                StorageEntry { key: first_slot, value: U256::from(2) },
825            )
826            .unwrap();
827        provider
828            .tx_ref()
829            .put::<tables::HashedStorages>(
830                hashed_address,
831                StorageEntry { key: second_slot, value: U256::from(3) },
832            )
833            .unwrap();
834
835        let mut state = ExecutionOutcome::<()>::default();
836        state.bundle.state.insert(
837            address,
838            BundleAccount::new(
839                Some(Default::default()),
840                None,
841                Default::default(),
842                AccountStatus::Destroyed,
843            ),
844        );
845
846        let hashed_state = provider.latest().hashed_post_state(&state.bundle).unwrap();
847
848        let storage = &hashed_state.storages[&hashed_address];
849        assert!(!storage.wiped);
850        assert_eq!(storage.storage[&first_slot], U256::ZERO);
851        assert_eq!(storage.storage[&second_slot], U256::ZERO);
852        assert!(state.bundle.reverts.is_empty());
853    }
854
855    #[test]
856    fn execution_checkpoint_matches() {
857        let factory = create_test_provider_factory();
858
859        let previous_stage_checkpoint = ExecutionCheckpoint {
860            block_range: CheckpointBlockRange { from: 0, to: 0 },
861            progress: EntitiesCheckpoint { processed: 1, total: 2 },
862        };
863        let previous_checkpoint = StageCheckpoint {
864            block_number: 0,
865            stage_checkpoint: Some(StageUnitCheckpoint::Execution(previous_stage_checkpoint)),
866        };
867
868        let stage_checkpoint = execution_checkpoint(
869            &factory.static_file_provider(),
870            previous_stage_checkpoint.block_range.from,
871            previous_stage_checkpoint.block_range.to,
872            previous_checkpoint,
873        );
874
875        assert!(
876            matches!(stage_checkpoint, Ok(checkpoint) if checkpoint == previous_stage_checkpoint)
877        );
878    }
879
880    #[test]
881    fn execution_checkpoint_precedes() {
882        let factory = create_test_provider_factory();
883        let provider = factory.provider_rw().unwrap();
884
885        let mut genesis_rlp = hex!("f901faf901f5a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa045571b40ae66ca7480791bbb2887286e4e4c4b1b298b191c889d6959023a32eda056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000808502540be400808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0").as_slice();
886        let genesis = SealedBlock::<Block>::decode(&mut genesis_rlp).unwrap();
887        let mut block_rlp = hex!("f90262f901f9a075c371ba45999d87f4542326910a11af515897aebce5265d3f6acd1f1161f82fa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa098f2dcd87c8ae4083e7017a05456c14eea4b1db2032126e27b3b1563d57d7cc0a08151d548273f6683169524b66ca9fe338b9ce42bc3540046c828fd939ae23bcba03f4e5c2ec5b2170b711d97ee755c160457bb58d8daa338e835ec02ae6860bbabb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018502540be40082a8798203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f863f861800a8405f5e10094100000000000000000000000000000000000000080801ba07e09e26678ed4fac08a249ebe8ed680bf9051a5e14ad223e4b2b9d26e0208f37a05f6e3f188e3e6eab7d7d3b6568f5eac7d687b08d307d3154ccd8c87b4630509bc0").as_slice();
888        let block = SealedBlock::<Block>::decode(&mut block_rlp).unwrap();
889        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
890        provider.insert_block(&block.clone().try_recover().unwrap()).unwrap();
891        provider
892            .static_file_provider()
893            .latest_writer(StaticFileSegment::Headers)
894            .unwrap()
895            .commit()
896            .unwrap();
897        provider.commit().unwrap();
898
899        let previous_stage_checkpoint = ExecutionCheckpoint {
900            block_range: CheckpointBlockRange { from: 0, to: 0 },
901            progress: EntitiesCheckpoint { processed: 1, total: 1 },
902        };
903        let previous_checkpoint = StageCheckpoint {
904            block_number: 1,
905            stage_checkpoint: Some(StageUnitCheckpoint::Execution(previous_stage_checkpoint)),
906        };
907
908        let stage_checkpoint =
909            execution_checkpoint(&factory.static_file_provider(), 1, 1, previous_checkpoint);
910
911        assert_matches!(stage_checkpoint, Ok(ExecutionCheckpoint {
912            block_range: CheckpointBlockRange { from: 1, to: 1 },
913            progress: EntitiesCheckpoint {
914                processed,
915                total
916            }
917        }) if processed == previous_stage_checkpoint.progress.processed &&
918            total == previous_stage_checkpoint.progress.total + block.gas_used);
919    }
920
921    #[test]
922    fn execution_checkpoint_recalculate_full_previous_some() {
923        let factory = create_test_provider_factory();
924        let provider = factory.provider_rw().unwrap();
925
926        let mut genesis_rlp = hex!("f901faf901f5a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa045571b40ae66ca7480791bbb2887286e4e4c4b1b298b191c889d6959023a32eda056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000808502540be400808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0").as_slice();
927        let genesis = SealedBlock::<Block>::decode(&mut genesis_rlp).unwrap();
928        let mut block_rlp = hex!("f90262f901f9a075c371ba45999d87f4542326910a11af515897aebce5265d3f6acd1f1161f82fa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa098f2dcd87c8ae4083e7017a05456c14eea4b1db2032126e27b3b1563d57d7cc0a08151d548273f6683169524b66ca9fe338b9ce42bc3540046c828fd939ae23bcba03f4e5c2ec5b2170b711d97ee755c160457bb58d8daa338e835ec02ae6860bbabb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018502540be40082a8798203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f863f861800a8405f5e10094100000000000000000000000000000000000000080801ba07e09e26678ed4fac08a249ebe8ed680bf9051a5e14ad223e4b2b9d26e0208f37a05f6e3f188e3e6eab7d7d3b6568f5eac7d687b08d307d3154ccd8c87b4630509bc0").as_slice();
929        let block = SealedBlock::<Block>::decode(&mut block_rlp).unwrap();
930        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
931        provider.insert_block(&block.clone().try_recover().unwrap()).unwrap();
932        provider
933            .static_file_provider()
934            .latest_writer(StaticFileSegment::Headers)
935            .unwrap()
936            .commit()
937            .unwrap();
938        provider.commit().unwrap();
939
940        let previous_stage_checkpoint = ExecutionCheckpoint {
941            block_range: CheckpointBlockRange { from: 0, to: 0 },
942            progress: EntitiesCheckpoint { processed: 1, total: 1 },
943        };
944        let previous_checkpoint = StageCheckpoint {
945            block_number: 1,
946            stage_checkpoint: Some(StageUnitCheckpoint::Execution(previous_stage_checkpoint)),
947        };
948
949        let stage_checkpoint =
950            execution_checkpoint(&factory.static_file_provider(), 1, 1, previous_checkpoint);
951
952        assert_matches!(stage_checkpoint, Ok(ExecutionCheckpoint {
953            block_range: CheckpointBlockRange { from: 1, to: 1 },
954            progress: EntitiesCheckpoint {
955                processed,
956                total
957            }
958        }) if processed == previous_stage_checkpoint.progress.processed &&
959            total == previous_stage_checkpoint.progress.total + block.gas_used());
960    }
961
962    #[test]
963    fn execution_checkpoint_recalculate_full_previous_none() {
964        let factory = create_test_provider_factory();
965        let provider = factory.provider_rw().unwrap();
966
967        let mut genesis_rlp = hex!("f901faf901f5a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa045571b40ae66ca7480791bbb2887286e4e4c4b1b298b191c889d6959023a32eda056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000808502540be400808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0").as_slice();
968        let genesis = SealedBlock::<Block>::decode(&mut genesis_rlp).unwrap();
969        let mut block_rlp = hex!("f90262f901f9a075c371ba45999d87f4542326910a11af515897aebce5265d3f6acd1f1161f82fa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa098f2dcd87c8ae4083e7017a05456c14eea4b1db2032126e27b3b1563d57d7cc0a08151d548273f6683169524b66ca9fe338b9ce42bc3540046c828fd939ae23bcba03f4e5c2ec5b2170b711d97ee755c160457bb58d8daa338e835ec02ae6860bbabb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018502540be40082a8798203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f863f861800a8405f5e10094100000000000000000000000000000000000000080801ba07e09e26678ed4fac08a249ebe8ed680bf9051a5e14ad223e4b2b9d26e0208f37a05f6e3f188e3e6eab7d7d3b6568f5eac7d687b08d307d3154ccd8c87b4630509bc0").as_slice();
970        let block = SealedBlock::<Block>::decode(&mut block_rlp).unwrap();
971        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
972        provider.insert_block(&block.clone().try_recover().unwrap()).unwrap();
973        provider
974            .static_file_provider()
975            .latest_writer(StaticFileSegment::Headers)
976            .unwrap()
977            .commit()
978            .unwrap();
979        provider.commit().unwrap();
980
981        let previous_checkpoint = StageCheckpoint { block_number: 1, stage_checkpoint: None };
982
983        let stage_checkpoint =
984            execution_checkpoint(&factory.static_file_provider(), 1, 1, previous_checkpoint);
985
986        assert_matches!(stage_checkpoint, Ok(ExecutionCheckpoint {
987            block_range: CheckpointBlockRange { from: 1, to: 1 },
988            progress: EntitiesCheckpoint {
989                processed: 0,
990                total
991            }
992        }) if total == block.gas_used);
993    }
994
995    #[tokio::test]
996    async fn sanity_execution_of_block() {
997        let factory = create_test_provider_factory();
998        let provider = factory.provider_rw().unwrap();
999        let input = ExecInput { target: Some(1), checkpoint: None };
1000        let mut genesis_rlp = hex!("f901faf901f5a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa045571b40ae66ca7480791bbb2887286e4e4c4b1b298b191c889d6959023a32eda056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000808502540be400808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0").as_slice();
1001        let genesis = SealedBlock::<Block>::decode(&mut genesis_rlp).unwrap();
1002        let mut block_rlp = hex!("f90262f901f9a075c371ba45999d87f4542326910a11af515897aebce5265d3f6acd1f1161f82fa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa098f2dcd87c8ae4083e7017a05456c14eea4b1db2032126e27b3b1563d57d7cc0a08151d548273f6683169524b66ca9fe338b9ce42bc3540046c828fd939ae23bcba03f4e5c2ec5b2170b711d97ee755c160457bb58d8daa338e835ec02ae6860bbabb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018502540be40082a8798203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f863f861800a8405f5e10094100000000000000000000000000000000000000080801ba07e09e26678ed4fac08a249ebe8ed680bf9051a5e14ad223e4b2b9d26e0208f37a05f6e3f188e3e6eab7d7d3b6568f5eac7d687b08d307d3154ccd8c87b4630509bc0").as_slice();
1003        let block = SealedBlock::<Block>::decode(&mut block_rlp).unwrap();
1004        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
1005        provider.insert_block(&block.clone().try_recover().unwrap()).unwrap();
1006        provider
1007            .static_file_provider()
1008            .latest_writer(StaticFileSegment::Headers)
1009            .unwrap()
1010            .commit()
1011            .unwrap();
1012        {
1013            let static_file_provider = provider.static_file_provider();
1014            let mut receipts_writer =
1015                static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1016            receipts_writer.increment_block(0).unwrap();
1017            receipts_writer.commit().unwrap();
1018        }
1019        provider.commit().unwrap();
1020
1021        // insert pre state
1022        let provider = factory.provider_rw().unwrap();
1023
1024        let db_tx = provider.tx_ref();
1025        let acc1 = address!("0x1000000000000000000000000000000000000000");
1026        let acc2 = address!("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b");
1027        let code = hex!("5a465a905090036002900360015500");
1028        let balance = U256::from(0x3635c9adc5dea00000u128);
1029        let code_hash = keccak256(code);
1030        db_tx
1031            .put::<tables::PlainAccountState>(
1032                acc1,
1033                Account { nonce: 0, balance: U256::ZERO, bytecode_hash: Some(code_hash) },
1034            )
1035            .unwrap();
1036        db_tx
1037            .put::<tables::PlainAccountState>(
1038                acc2,
1039                Account { nonce: 0, balance, bytecode_hash: None },
1040            )
1041            .unwrap();
1042        db_tx.put::<tables::Bytecodes>(code_hash, Bytecode::new_raw(code.to_vec().into())).unwrap();
1043        provider.commit().unwrap();
1044
1045        // execute
1046
1047        // If there is a pruning configuration, then it's forced to use the database.
1048        // This way we test both cases.
1049        let modes = [None, Some(PruneModes::default())];
1050        let random_filter = ReceiptsLogPruneConfig(BTreeMap::from([(
1051            Address::random(),
1052            PruneMode::Distance(100000),
1053        )]));
1054
1055        // Tests node with database and node with static files
1056        for mut mode in modes {
1057            let mut provider = factory.database_provider_rw().unwrap();
1058
1059            if let Some(mode) = &mut mode {
1060                // Simulating a full node where we write receipts to database
1061                mode.receipts_log_filter = random_filter.clone();
1062            }
1063
1064            let mut execution_stage = stage();
1065            provider.set_prune_modes(mode.clone().unwrap_or_default());
1066
1067            let output = execution_stage.execute(&provider, input).unwrap();
1068            provider.commit().unwrap();
1069
1070            assert_matches!(output, ExecOutput {
1071                checkpoint: StageCheckpoint {
1072                    block_number: 1,
1073                    stage_checkpoint: Some(StageUnitCheckpoint::Execution(ExecutionCheckpoint {
1074                        block_range: CheckpointBlockRange {
1075                            from: 1,
1076                            to: 1,
1077                        },
1078                        progress: EntitiesCheckpoint {
1079                            processed,
1080                            total
1081                        }
1082                    }))
1083                },
1084                done: true
1085            } if processed == total && total == block.gas_used);
1086
1087            {
1088                let provider = factory.provider().unwrap();
1089
1090                // check post state
1091                let account1 = address!("0x1000000000000000000000000000000000000000");
1092                let account1_info =
1093                    Account { balance: U256::ZERO, nonce: 0x00, bytecode_hash: Some(code_hash) };
1094                let account2 = address!("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba");
1095                let account2_info = Account {
1096                    balance: U256::from(0x1bc16d674ece94bau128),
1097                    nonce: 0x00,
1098                    bytecode_hash: None,
1099                };
1100                let account3 = address!("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b");
1101                let account3_info = Account {
1102                    balance: U256::from(0x3635c9adc5de996b46u128),
1103                    nonce: 0x01,
1104                    bytecode_hash: None,
1105                };
1106
1107                // assert accounts
1108                assert!(matches!(
1109                    provider.basic_account(&account1),
1110                    Ok(Some(acc)) if acc == account1_info
1111                ));
1112                assert!(matches!(
1113                    provider.basic_account(&account2),
1114                    Ok(Some(acc)) if acc == account2_info
1115                ));
1116                assert!(matches!(
1117                    provider.basic_account(&account3),
1118                    Ok(Some(acc)) if acc == account3_info
1119                ));
1120                // assert storage
1121                // Get on dupsort would return only first value. This is good enough for this test.
1122                assert!(matches!(
1123                    provider.tx_ref().get::<tables::PlainStorageState>(account1),
1124                    Ok(Some(entry)) if entry.key == B256::with_last_byte(1) && entry.value == U256::from(2)
1125                ));
1126            }
1127
1128            let mut provider = factory.database_provider_rw().unwrap();
1129            let mut stage = stage();
1130            provider.set_prune_modes(mode.unwrap_or_default());
1131
1132            let _result = stage
1133                .unwind(
1134                    &provider,
1135                    UnwindInput { checkpoint: output.checkpoint, unwind_to: 0, bad_block: None },
1136                )
1137                .unwrap();
1138            provider.commit().unwrap();
1139        }
1140    }
1141
1142    #[tokio::test]
1143    async fn sanity_execute_unwind() {
1144        let factory = create_test_provider_factory();
1145        let provider = factory.provider_rw().unwrap();
1146        let input = ExecInput { target: Some(1), checkpoint: None };
1147        let mut genesis_rlp = hex!("f901faf901f5a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa045571b40ae66ca7480791bbb2887286e4e4c4b1b298b191c889d6959023a32eda056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000808502540be400808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0").as_slice();
1148        let genesis = SealedBlock::<Block>::decode(&mut genesis_rlp).unwrap();
1149        let mut block_rlp = hex!("f90262f901f9a075c371ba45999d87f4542326910a11af515897aebce5265d3f6acd1f1161f82fa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa098f2dcd87c8ae4083e7017a05456c14eea4b1db2032126e27b3b1563d57d7cc0a08151d548273f6683169524b66ca9fe338b9ce42bc3540046c828fd939ae23bcba03f4e5c2ec5b2170b711d97ee755c160457bb58d8daa338e835ec02ae6860bbabb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000018502540be40082a8798203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f863f861800a8405f5e10094100000000000000000000000000000000000000080801ba07e09e26678ed4fac08a249ebe8ed680bf9051a5e14ad223e4b2b9d26e0208f37a05f6e3f188e3e6eab7d7d3b6568f5eac7d687b08d307d3154ccd8c87b4630509bc0").as_slice();
1150        let block = SealedBlock::<Block>::decode(&mut block_rlp).unwrap();
1151        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
1152        provider.insert_block(&block.clone().try_recover().unwrap()).unwrap();
1153        provider
1154            .static_file_provider()
1155            .latest_writer(StaticFileSegment::Headers)
1156            .unwrap()
1157            .commit()
1158            .unwrap();
1159        {
1160            let static_file_provider = provider.static_file_provider();
1161            let mut receipts_writer =
1162                static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1163            receipts_writer.increment_block(0).unwrap();
1164            receipts_writer.commit().unwrap();
1165        }
1166        provider.commit().unwrap();
1167
1168        // variables
1169        let code = hex!("5a465a905090036002900360015500");
1170        let balance = U256::from(0x3635c9adc5dea00000u128);
1171        let code_hash = keccak256(code);
1172        // pre state
1173        let provider = factory.provider_rw().unwrap();
1174
1175        let db_tx = provider.tx_ref();
1176        let acc1 = address!("0x1000000000000000000000000000000000000000");
1177        let acc1_info = Account { nonce: 0, balance: U256::ZERO, bytecode_hash: Some(code_hash) };
1178        let acc2 = address!("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b");
1179        let acc2_info = Account { nonce: 0, balance, bytecode_hash: None };
1180
1181        db_tx.put::<tables::PlainAccountState>(acc1, acc1_info).unwrap();
1182        db_tx.put::<tables::PlainAccountState>(acc2, acc2_info).unwrap();
1183        db_tx.put::<tables::Bytecodes>(code_hash, Bytecode::new_raw(code.to_vec().into())).unwrap();
1184        provider.commit().unwrap();
1185
1186        // execute
1187        let mut provider = factory.database_provider_rw().unwrap();
1188
1189        // If there is a pruning configuration, then it's forced to use the database.
1190        // This way we test both cases.
1191        let modes = [None, Some(PruneModes::default())];
1192        let random_filter = ReceiptsLogPruneConfig(BTreeMap::from([(
1193            Address::random(),
1194            PruneMode::Before(100000),
1195        )]));
1196
1197        // Tests node with database and node with static files
1198        for mut mode in modes {
1199            if let Some(mode) = &mut mode {
1200                // Simulating a full node where we write receipts to database
1201                mode.receipts_log_filter = random_filter.clone();
1202            }
1203
1204            // Test Execution
1205            let mut execution_stage = stage();
1206            provider.set_prune_modes(mode.clone().unwrap_or_default());
1207
1208            let result = execution_stage.execute(&provider, input).unwrap();
1209            provider.commit().unwrap();
1210
1211            // Test Unwind
1212            provider = factory.database_provider_rw().unwrap();
1213            let mut stage = stage();
1214            provider.set_prune_modes(mode.clone().unwrap_or_default());
1215
1216            let result = stage
1217                .unwind(
1218                    &provider,
1219                    UnwindInput { checkpoint: result.checkpoint, unwind_to: 0, bad_block: None },
1220                )
1221                .unwrap();
1222
1223            provider.static_file_provider().commit().unwrap();
1224
1225            assert_matches!(result, UnwindOutput {
1226                checkpoint: StageCheckpoint {
1227                    block_number: 0,
1228                    stage_checkpoint: Some(StageUnitCheckpoint::Execution(ExecutionCheckpoint {
1229                        block_range: CheckpointBlockRange {
1230                            from: 1,
1231                            to: 1,
1232                        },
1233                        progress: EntitiesCheckpoint {
1234                            processed: 0,
1235                            total
1236                        }
1237                    }))
1238                }
1239            } if total == block.gas_used);
1240
1241            // assert unwind stage
1242            assert!(matches!(provider.basic_account(&acc1), Ok(Some(acc)) if acc == acc1_info));
1243            assert!(matches!(provider.basic_account(&acc2), Ok(Some(acc)) if acc == acc2_info));
1244
1245            let miner_acc = address!("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba");
1246            assert!(matches!(provider.basic_account(&miner_acc), Ok(None)));
1247
1248            assert!(matches!(provider.receipt(0), Ok(None)));
1249        }
1250    }
1251
1252    #[test]
1253    fn unwind_from_cancun_to_pre_cancun_is_rejected() {
1254        let chain_spec = Arc::new(
1255            ChainSpecBuilder::mainnet()
1256                .berlin_activated()
1257                .with_fork(EthereumHardfork::Cancun, ForkCondition::Timestamp(15))
1258                .build(),
1259        );
1260        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
1261        let provider = factory.database_provider_rw().unwrap();
1262
1263        let mut rng = generators::rng();
1264        let mut genesis = generators::random_block(
1265            &mut rng,
1266            0,
1267            generators::BlockParams { tx_count: Some(0), ..Default::default() },
1268        )
1269        .unseal();
1270        genesis.header.timestamp = 0;
1271        let genesis = genesis.seal_slow();
1272
1273        let mut block_1 = generators::random_block(
1274            &mut rng,
1275            1,
1276            generators::BlockParams {
1277                parent: Some(genesis.hash()),
1278                tx_count: Some(0),
1279                ..Default::default()
1280            },
1281        )
1282        .unseal();
1283        block_1.header.timestamp = 10;
1284        let block_1 = block_1.seal_slow();
1285
1286        let mut block_2 = generators::random_block(
1287            &mut rng,
1288            2,
1289            generators::BlockParams {
1290                parent: Some(block_1.hash()),
1291                tx_count: Some(0),
1292                ..Default::default()
1293            },
1294        )
1295        .unseal();
1296        block_2.header.timestamp = 20;
1297        let block_2 = block_2.seal_slow();
1298
1299        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
1300        provider.insert_block(&block_1.try_recover().unwrap()).unwrap();
1301        provider.insert_block(&block_2.try_recover().unwrap()).unwrap();
1302        provider
1303            .static_file_provider()
1304            .latest_writer(StaticFileSegment::Headers)
1305            .unwrap()
1306            .commit()
1307            .unwrap();
1308
1309        let mut execution_stage = stage();
1310        let err = execution_stage
1311            .unwind(
1312                &provider,
1313                UnwindInput { checkpoint: StageCheckpoint::new(2), unwind_to: 1, bad_block: None },
1314            )
1315            .unwrap_err();
1316
1317        assert_matches!(err, StageError::Fatal(_));
1318        assert!(err.to_string().contains("across Cancun activation boundary"));
1319    }
1320
1321    #[tokio::test]
1322    async fn test_selfdestruct() {
1323        let test_db = TestStageDB::default();
1324        let provider = test_db.factory.database_provider_rw().unwrap();
1325        let input = ExecInput { target: Some(1), checkpoint: None };
1326        let mut genesis_rlp = hex!("f901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa0c9ceb8372c88cb461724d8d3d87e8b933f6fc5f679d4841800e662f4428ffd0da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808000a00000000000000000000000000000000000000000000000000000000000000000880000000000000000c0c0").as_slice();
1327        let genesis = SealedBlock::<Block>::decode(&mut genesis_rlp).unwrap();
1328        let mut block_rlp = hex!("f9025ff901f7a0c86e8cc0310ae7c531c758678ddbfd16fc51c8cef8cec650b032de9869e8b94fa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942adc25665018aa1fe0e6bc666dac8fc2697ff9baa050554882fbbda2c2fd93fdc466db9946ea262a67f7a76cc169e714f105ab583da00967f09ef1dfed20c0eacfaa94d5cd4002eda3242ac47eae68972d07b106d192a0e3c8b47fbfc94667ef4cceb17e5cc21e3b1eebd442cebb27f07562b33836290db90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001830f42408238108203e800a00000000000000000000000000000000000000000000000000000000000000000880000000000000000f862f860800a83061a8094095e7baea6a6c7c4c2dfeb977efac326af552d8780801ba072ed817487b84ba367d15d2f039b5fc5f087d0a8882fbdf73e8cb49357e1ce30a0403d800545b8fc544f92ce8124e2255f8c3c6af93f28243a120585d4c4c6a2a3c0").as_slice();
1329        let block = SealedBlock::<Block>::decode(&mut block_rlp).unwrap();
1330        provider.insert_block(&genesis.try_recover().unwrap()).unwrap();
1331        provider.insert_block(&block.clone().try_recover().unwrap()).unwrap();
1332        provider
1333            .static_file_provider()
1334            .latest_writer(StaticFileSegment::Headers)
1335            .unwrap()
1336            .commit()
1337            .unwrap();
1338        {
1339            let static_file_provider = provider.static_file_provider();
1340            let mut receipts_writer =
1341                static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1342            receipts_writer.increment_block(0).unwrap();
1343            receipts_writer.commit().unwrap();
1344        }
1345        provider.commit().unwrap();
1346
1347        // variables
1348        let caller_address = address!("0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b");
1349        let destroyed_address = address!("0x095e7baea6a6c7c4c2dfeb977efac326af552d87");
1350        let beneficiary_address = address!("0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba");
1351
1352        let code = hex!("73095e7baea6a6c7c4c2dfeb977efac326af552d8731ff00");
1353        let balance = U256::from(0x0de0b6b3a7640000u64);
1354        let code_hash = keccak256(code);
1355
1356        // pre state
1357        let caller_info = Account { nonce: 0, balance, bytecode_hash: None };
1358        let destroyed_info =
1359            Account { nonce: 0, balance: U256::ZERO, bytecode_hash: Some(code_hash) };
1360
1361        // set account
1362        let provider = test_db.factory.provider_rw().unwrap();
1363        provider.tx_ref().put::<tables::PlainAccountState>(caller_address, caller_info).unwrap();
1364        provider
1365            .tx_ref()
1366            .put::<tables::PlainAccountState>(destroyed_address, destroyed_info)
1367            .unwrap();
1368        provider
1369            .tx_ref()
1370            .put::<tables::Bytecodes>(code_hash, Bytecode::new_raw(code.to_vec().into()))
1371            .unwrap();
1372        // set storage to check when account gets destroyed.
1373        provider
1374            .tx_ref()
1375            .put::<tables::PlainStorageState>(
1376                destroyed_address,
1377                StorageEntry { key: B256::ZERO, value: U256::ZERO },
1378            )
1379            .unwrap();
1380        provider
1381            .tx_ref()
1382            .put::<tables::PlainStorageState>(
1383                destroyed_address,
1384                StorageEntry { key: B256::with_last_byte(1), value: U256::from(1u64) },
1385            )
1386            .unwrap();
1387
1388        provider.commit().unwrap();
1389
1390        // execute
1391        let provider = test_db.factory.database_provider_rw().unwrap();
1392        let mut execution_stage = stage();
1393        let _ = execution_stage.execute(&provider, input).unwrap();
1394        provider.commit().unwrap();
1395
1396        // assert unwind stage
1397        let provider = test_db.factory.database_provider_rw().unwrap();
1398        assert!(matches!(provider.basic_account(&destroyed_address), Ok(None)));
1399
1400        assert!(matches!(
1401            provider.tx_ref().get::<tables::PlainStorageState>(destroyed_address),
1402            Ok(None)
1403        ));
1404        // drops tx so that it returns write privilege to test_tx
1405        drop(provider);
1406        let plain_accounts = test_db.table::<tables::PlainAccountState>().unwrap();
1407        let plain_storage = test_db.table::<tables::PlainStorageState>().unwrap();
1408
1409        assert_eq!(
1410            plain_accounts,
1411            vec![
1412                (
1413                    beneficiary_address,
1414                    Account {
1415                        nonce: 0,
1416                        balance: U256::from(0x1bc16d674eca30a0u64),
1417                        bytecode_hash: None
1418                    }
1419                ),
1420                (
1421                    caller_address,
1422                    Account {
1423                        nonce: 1,
1424                        balance: U256::from(0xde0b6b3a761cf60u64),
1425                        bytecode_hash: None
1426                    }
1427                )
1428            ]
1429        );
1430        assert!(plain_storage.is_empty());
1431
1432        let account_changesets = test_db.table::<tables::AccountChangeSets>().unwrap();
1433        let storage_changesets = test_db.table::<tables::StorageChangeSets>().unwrap();
1434
1435        assert_eq!(
1436            account_changesets,
1437            vec![
1438                (
1439                    block.number,
1440                    AccountBeforeTx { address: destroyed_address, info: Some(destroyed_info) },
1441                ),
1442                (block.number, AccountBeforeTx { address: beneficiary_address, info: None }),
1443                (
1444                    block.number,
1445                    AccountBeforeTx { address: caller_address, info: Some(caller_info) }
1446                ),
1447            ]
1448        );
1449
1450        assert_eq!(
1451            storage_changesets,
1452            vec![
1453                (
1454                    (block.number, destroyed_address).into(),
1455                    StorageEntry { key: B256::ZERO, value: U256::ZERO }
1456                ),
1457                (
1458                    (block.number, destroyed_address).into(),
1459                    StorageEntry { key: B256::with_last_byte(1), value: U256::from(1u64) }
1460                )
1461            ]
1462        );
1463    }
1464
1465    #[test]
1466    fn test_ensure_consistency_with_skipped_receipts() {
1467        // Test that ensure_consistency allows the case where receipts are intentionally
1468        // skipped. When receipts are skipped, blocks are still incremented in static files
1469        // but no receipt data is written.
1470
1471        let factory = create_test_provider_factory();
1472        factory.set_storage_settings_cache(StorageSettings::v2());
1473
1474        // Setup with block 1
1475        let provider_rw = factory.database_provider_rw().unwrap();
1476        let mut rng = generators::rng();
1477        let genesis = generators::random_block(&mut rng, 0, Default::default());
1478        provider_rw
1479            .insert_block(&genesis.try_recover().unwrap())
1480            .expect("failed to insert genesis");
1481        let block = generators::random_block(
1482            &mut rng,
1483            1,
1484            generators::BlockParams { tx_count: Some(2), ..Default::default() },
1485        );
1486        provider_rw.insert_block(&block.try_recover().unwrap()).expect("failed to insert block");
1487
1488        let static_file_provider = provider_rw.static_file_provider();
1489        static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap().commit().unwrap();
1490
1491        // Simulate skipped receipts: increment block in receipts static file but don't write
1492        // receipts
1493        {
1494            let mut receipts_writer =
1495                static_file_provider.latest_writer(StaticFileSegment::Receipts).unwrap();
1496            receipts_writer.increment_block(0).unwrap();
1497            receipts_writer.increment_block(1).unwrap();
1498            receipts_writer.commit().unwrap();
1499        } // Explicitly drop receipts_writer here
1500
1501        provider_rw.commit().expect("failed to commit");
1502
1503        // Verify blocks are incremented but no receipts written
1504        assert_eq!(
1505            factory
1506                .static_file_provider()
1507                .get_highest_static_file_block(StaticFileSegment::Receipts),
1508            Some(1)
1509        );
1510        assert_eq!(
1511            factory.static_file_provider().get_highest_static_file_tx(StaticFileSegment::Receipts),
1512            None
1513        );
1514
1515        // Create execution stage
1516        let stage = stage();
1517
1518        // Run ensure_consistency - should NOT error
1519        // Block numbers match (both at 1), but tx numbers don't (database has txs, static files
1520        // don't) This is fine - receipts are being skipped
1521        let provider = factory.provider().unwrap();
1522        stage
1523            .ensure_consistency(&provider, 1, None)
1524            .expect("ensure_consistency should succeed when receipts are intentionally skipped");
1525    }
1526}