reth_stages/stages/
merkle.rs

1use alloy_consensus::{constants::KECCAK_EMPTY, BlockHeader};
2use alloy_primitives::{BlockNumber, Sealable, B256};
3use reth_codecs::Compact;
4use reth_consensus::ConsensusError;
5use reth_db_api::{
6    tables,
7    transaction::{DbTx, DbTxMut},
8};
9use reth_primitives_traits::{GotExpected, SealedHeader};
10use reth_provider::{
11    DBProvider, HeaderProvider, ProviderError, StageCheckpointReader, StageCheckpointWriter,
12    StatsReader, TrieWriter,
13};
14use reth_stages_api::{
15    BlockErrorKind, EntitiesCheckpoint, ExecInput, ExecOutput, MerkleCheckpoint, Stage,
16    StageCheckpoint, StageError, StageId, StorageRootMerkleCheckpoint, UnwindInput, UnwindOutput,
17};
18use reth_trie::{IntermediateStateRootState, StateRoot, StateRootProgress, StoredSubNode};
19use reth_trie_db::DatabaseStateRoot;
20use std::fmt::Debug;
21use tracing::*;
22
23// TODO: automate the process outlined below so the user can just send in a debugging package
24/// The error message that we include in invalid state root errors to tell users what information
25/// they should include in a bug report, since true state root errors can be impossible to debug
26/// with just basic logs.
27pub const INVALID_STATE_ROOT_ERROR_MESSAGE: &str = r#"
28Invalid state root error on stage verification!
29This is an error that likely requires a report to the reth team with additional information.
30Please include the following information in your report:
31 * This error message
32 * The state root of the block that was rejected
33 * The output of `reth db stats --checksum` from the database that was being used. This will take a long time to run!
34 * 50-100 lines of logs before and after the first occurrence of the log message with the state root of the block that was rejected.
35 * The debug logs from __the same time period__. To find the default location for these logs, run:
36   `reth --help | grep -A 4 'log.file.directory'`
37
38Once you have this information, please submit a github issue at https://github.com/paradigmxyz/reth/issues/new
39"#;
40
41/// The default threshold (in number of blocks) for switching from incremental trie building
42/// of changes to whole rebuild.
43pub const MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD: u64 = 100_000;
44
45/// The default threshold (in number of blocks) to run the stage in incremental mode. The
46/// incremental mode will calculate the state root for a large range of blocks by calculating the
47/// new state root for this many blocks, in batches, repeating until we reach the desired block
48/// number.
49pub const MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD: u64 = 7_000;
50
51/// The merkle hashing stage uses input from
52/// [`AccountHashingStage`][crate::stages::AccountHashingStage] and
53/// [`StorageHashingStage`][crate::stages::StorageHashingStage] to calculate intermediate hashes
54/// and state roots.
55///
56/// This stage should be run with the above two stages, otherwise it is a no-op.
57///
58/// This stage is split in two: one for calculating hashes and one for unwinding.
59///
60/// When run in execution, it's going to be executed AFTER the hashing stages, to generate
61/// the state root. When run in unwind mode, it's going to be executed BEFORE the hashing stages,
62/// so that it unwinds the intermediate hashes based on the unwound hashed state from the hashing
63/// stages. The order of these two variants is important. The unwind variant should be added to the
64/// pipeline before the execution variant.
65///
66/// An example pipeline to only hash state would be:
67///
68/// - [`MerkleStage::Unwind`]
69/// - [`AccountHashingStage`][crate::stages::AccountHashingStage]
70/// - [`StorageHashingStage`][crate::stages::StorageHashingStage]
71/// - [`MerkleStage::Execution`]
72#[derive(Debug, Clone)]
73pub enum MerkleStage {
74    /// The execution portion of the merkle stage.
75    Execution {
76        // TODO: make struct for holding incremental settings, for code reuse between `Execution`
77        // variant and `Both`
78        /// The threshold (in number of blocks) for switching from incremental trie building
79        /// of changes to whole rebuild.
80        rebuild_threshold: u64,
81        /// The threshold (in number of blocks) to run the stage in incremental mode. The
82        /// incremental mode will calculate the state root by calculating the new state root for
83        /// some number of blocks, repeating until we reach the desired block number.
84        incremental_threshold: u64,
85    },
86    /// The unwind portion of the merkle stage.
87    Unwind,
88    /// Able to execute and unwind. Used for tests
89    #[cfg(any(test, feature = "test-utils"))]
90    Both {
91        /// The threshold (in number of blocks) for switching from incremental trie building
92        /// of changes to whole rebuild.
93        rebuild_threshold: u64,
94        /// The threshold (in number of blocks) to run the stage in incremental mode. The
95        /// incremental mode will calculate the state root by calculating the new state root for
96        /// some number of blocks, repeating until we reach the desired block number.
97        incremental_threshold: u64,
98    },
99}
100
101impl MerkleStage {
102    /// Stage default for the [`MerkleStage::Execution`].
103    pub const fn default_execution() -> Self {
104        Self::Execution {
105            rebuild_threshold: MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD,
106            incremental_threshold: MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD,
107        }
108    }
109
110    /// Stage default for the [`MerkleStage::Unwind`].
111    pub const fn default_unwind() -> Self {
112        Self::Unwind
113    }
114
115    /// Create new instance of [`MerkleStage::Execution`].
116    pub const fn new_execution(rebuild_threshold: u64, incremental_threshold: u64) -> Self {
117        Self::Execution { rebuild_threshold, incremental_threshold }
118    }
119
120    /// Gets the hashing progress
121    pub fn get_execution_checkpoint(
122        &self,
123        provider: &impl StageCheckpointReader,
124    ) -> Result<Option<MerkleCheckpoint>, StageError> {
125        let buf =
126            provider.get_stage_checkpoint_progress(StageId::MerkleExecute)?.unwrap_or_default();
127
128        if buf.is_empty() {
129            return Ok(None)
130        }
131
132        let (checkpoint, _) = MerkleCheckpoint::from_compact(&buf, buf.len());
133        Ok(Some(checkpoint))
134    }
135
136    /// Saves the hashing progress
137    pub fn save_execution_checkpoint(
138        &self,
139        provider: &impl StageCheckpointWriter,
140        checkpoint: Option<MerkleCheckpoint>,
141    ) -> Result<(), StageError> {
142        let mut buf = vec![];
143        if let Some(checkpoint) = checkpoint {
144            debug!(
145                target: "sync::stages::merkle::exec",
146                last_account_key = ?checkpoint.last_account_key,
147                "Saving inner merkle checkpoint"
148            );
149            checkpoint.to_compact(&mut buf);
150        }
151        Ok(provider.save_stage_checkpoint_progress(StageId::MerkleExecute, buf)?)
152    }
153}
154
155impl<Provider> Stage<Provider> for MerkleStage
156where
157    Provider: DBProvider<Tx: DbTxMut>
158        + TrieWriter
159        + StatsReader
160        + HeaderProvider
161        + StageCheckpointReader
162        + StageCheckpointWriter,
163{
164    /// Return the id of the stage
165    fn id(&self) -> StageId {
166        match self {
167            Self::Execution { .. } => StageId::MerkleExecute,
168            Self::Unwind => StageId::MerkleUnwind,
169            #[cfg(any(test, feature = "test-utils"))]
170            Self::Both { .. } => StageId::Other("MerkleBoth"),
171        }
172    }
173
174    /// Execute the stage.
175    fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError> {
176        let (threshold, incremental_threshold) = match self {
177            Self::Unwind => {
178                info!(target: "sync::stages::merkle::unwind", "Stage is always skipped");
179                return Ok(ExecOutput::done(StageCheckpoint::new(input.target())))
180            }
181            Self::Execution { rebuild_threshold, incremental_threshold } => {
182                (*rebuild_threshold, *incremental_threshold)
183            }
184            #[cfg(any(test, feature = "test-utils"))]
185            Self::Both { rebuild_threshold, incremental_threshold } => {
186                (*rebuild_threshold, *incremental_threshold)
187            }
188        };
189
190        let range = input.next_block_range();
191        let (from_block, to_block) = range.clone().into_inner();
192        let current_block_number = input.checkpoint().block_number;
193
194        let target_block = provider
195            .header_by_number(to_block)?
196            .ok_or_else(|| ProviderError::HeaderNotFound(to_block.into()))?;
197        let target_block_root = target_block.state_root();
198
199        let mut checkpoint = self.get_execution_checkpoint(provider)?;
200        let (trie_root, entities_checkpoint) = if range.is_empty() {
201            (target_block_root, input.checkpoint().entities_stage_checkpoint().unwrap_or_default())
202        } else if to_block - from_block > threshold || from_block == 1 {
203            // if there are more blocks than threshold it is faster to rebuild the trie
204            let mut entities_checkpoint = if let Some(checkpoint) =
205                checkpoint.as_ref().filter(|c| c.target_block == to_block)
206            {
207                debug!(
208                    target: "sync::stages::merkle::exec",
209                    current = ?current_block_number,
210                    target = ?to_block,
211                    last_account_key = ?checkpoint.last_account_key,
212                    "Continuing inner merkle checkpoint"
213                );
214
215                input.checkpoint().entities_stage_checkpoint()
216            } else {
217                debug!(
218                    target: "sync::stages::merkle::exec",
219                    current = ?current_block_number,
220                    target = ?to_block,
221                    previous_checkpoint = ?checkpoint,
222                    "Rebuilding trie"
223                );
224                // Reset the checkpoint and clear trie tables
225                checkpoint = None;
226                self.save_execution_checkpoint(provider, None)?;
227                provider.tx_ref().clear::<tables::AccountsTrie>()?;
228                provider.tx_ref().clear::<tables::StoragesTrie>()?;
229
230                None
231            }
232            .unwrap_or(EntitiesCheckpoint {
233                processed: 0,
234                total: (provider.count_entries::<tables::HashedAccounts>()? +
235                    provider.count_entries::<tables::HashedStorages>()?)
236                    as u64,
237            });
238
239            let tx = provider.tx_ref();
240            let progress = StateRoot::from_tx(tx)
241                .with_intermediate_state(checkpoint.map(IntermediateStateRootState::from))
242                .root_with_progress()
243                .map_err(|e| {
244                    error!(target: "sync::stages::merkle", %e, ?current_block_number, ?to_block, "State root with progress failed! {INVALID_STATE_ROOT_ERROR_MESSAGE}");
245                    StageError::Fatal(Box::new(e))
246                })?;
247            match progress {
248                StateRootProgress::Progress(state, hashed_entries_walked, updates) => {
249                    provider.write_trie_updates(&updates)?;
250
251                    let mut checkpoint = MerkleCheckpoint::new(
252                        to_block,
253                        state.account_root_state.last_hashed_key,
254                        state
255                            .account_root_state
256                            .walker_stack
257                            .into_iter()
258                            .map(StoredSubNode::from)
259                            .collect(),
260                        state.account_root_state.hash_builder.into(),
261                    );
262
263                    // Save storage root state if present
264                    if let Some(storage_state) = state.storage_root_state {
265                        checkpoint.storage_root_checkpoint =
266                            Some(StorageRootMerkleCheckpoint::new(
267                                storage_state.state.last_hashed_key,
268                                storage_state
269                                    .state
270                                    .walker_stack
271                                    .into_iter()
272                                    .map(StoredSubNode::from)
273                                    .collect(),
274                                storage_state.state.hash_builder.into(),
275                                storage_state.account.nonce,
276                                storage_state.account.balance,
277                                storage_state.account.bytecode_hash.unwrap_or(KECCAK_EMPTY),
278                            ));
279                    }
280                    self.save_execution_checkpoint(provider, Some(checkpoint))?;
281
282                    entities_checkpoint.processed += hashed_entries_walked as u64;
283
284                    return Ok(ExecOutput {
285                        checkpoint: input
286                            .checkpoint()
287                            .with_entities_stage_checkpoint(entities_checkpoint),
288                        done: false,
289                    })
290                }
291                StateRootProgress::Complete(root, hashed_entries_walked, updates) => {
292                    provider.write_trie_updates(&updates)?;
293
294                    entities_checkpoint.processed += hashed_entries_walked as u64;
295
296                    (root, entities_checkpoint)
297                }
298            }
299        } else {
300            debug!(target: "sync::stages::merkle::exec", current = ?current_block_number, target = ?to_block, "Updating trie in chunks");
301            let mut final_root = None;
302            for start_block in range.step_by(incremental_threshold as usize) {
303                let chunk_to = std::cmp::min(start_block + incremental_threshold, to_block);
304                let chunk_range = start_block..=chunk_to;
305                debug!(
306                    target: "sync::stages::merkle::exec",
307                    current = ?current_block_number,
308                    target = ?to_block,
309                    incremental_threshold,
310                    chunk_range = ?chunk_range,
311                    "Processing chunk"
312                );
313                let (root, updates) =
314                StateRoot::incremental_root_with_updates(provider.tx_ref(), chunk_range)
315                    .map_err(|e| {
316                        error!(target: "sync::stages::merkle", %e, ?current_block_number, ?to_block, "Incremental state root failed! {INVALID_STATE_ROOT_ERROR_MESSAGE}");
317                        StageError::Fatal(Box::new(e))
318                    })?;
319                provider.write_trie_updates(&updates)?;
320                final_root = Some(root);
321            }
322
323            // if we had no final root, we must have not looped above, which should not be possible
324            let final_root = final_root.ok_or(StageError::Fatal(
325                "Incremental merkle hashing did not produce a final root".into(),
326            ))?;
327
328            let total_hashed_entries = (provider.count_entries::<tables::HashedAccounts>()? +
329                provider.count_entries::<tables::HashedStorages>()?)
330                as u64;
331
332            let entities_checkpoint = EntitiesCheckpoint {
333                // This is fine because `range` doesn't have an upper bound, so in this `else`
334                // branch we're just hashing all remaining accounts and storage slots we have in the
335                // database.
336                processed: total_hashed_entries,
337                total: total_hashed_entries,
338            };
339            // Save the checkpoint
340            (final_root, entities_checkpoint)
341        };
342
343        // Reset the checkpoint
344        self.save_execution_checkpoint(provider, None)?;
345
346        validate_state_root(trie_root, SealedHeader::seal_slow(target_block), to_block)?;
347
348        Ok(ExecOutput {
349            checkpoint: StageCheckpoint::new(to_block)
350                .with_entities_stage_checkpoint(entities_checkpoint),
351            done: true,
352        })
353    }
354
355    /// Unwind the stage.
356    fn unwind(
357        &mut self,
358        provider: &Provider,
359        input: UnwindInput,
360    ) -> Result<UnwindOutput, StageError> {
361        let tx = provider.tx_ref();
362        let range = input.unwind_block_range();
363        if matches!(self, Self::Execution { .. }) {
364            info!(target: "sync::stages::merkle::unwind", "Stage is always skipped");
365            return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) })
366        }
367
368        let mut entities_checkpoint =
369            input.checkpoint.entities_stage_checkpoint().unwrap_or(EntitiesCheckpoint {
370                processed: 0,
371                total: (tx.entries::<tables::HashedAccounts>()? +
372                    tx.entries::<tables::HashedStorages>()?) as u64,
373            });
374
375        if input.unwind_to == 0 {
376            tx.clear::<tables::AccountsTrie>()?;
377            tx.clear::<tables::StoragesTrie>()?;
378
379            entities_checkpoint.processed = 0;
380
381            return Ok(UnwindOutput {
382                checkpoint: StageCheckpoint::new(input.unwind_to)
383                    .with_entities_stage_checkpoint(entities_checkpoint),
384            })
385        }
386
387        // Unwind trie only if there are transitions
388        if range.is_empty() {
389            info!(target: "sync::stages::merkle::unwind", "Nothing to unwind");
390        } else {
391            let (block_root, updates) = StateRoot::incremental_root_with_updates(tx, range)
392                .map_err(|e| StageError::Fatal(Box::new(e)))?;
393
394            // Validate the calculated state root
395            let target = provider
396                .header_by_number(input.unwind_to)?
397                .ok_or_else(|| ProviderError::HeaderNotFound(input.unwind_to.into()))?;
398
399            validate_state_root(block_root, SealedHeader::seal_slow(target), input.unwind_to)?;
400
401            // Validation passed, apply unwind changes to the database.
402            provider.write_trie_updates(&updates)?;
403
404            // TODO(alexey): update entities checkpoint
405        }
406
407        Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) })
408    }
409}
410
411/// Check that the computed state root matches the root in the expected header.
412#[inline]
413fn validate_state_root<H: BlockHeader + Sealable + Debug>(
414    got: B256,
415    expected: SealedHeader<H>,
416    target_block: BlockNumber,
417) -> Result<(), StageError> {
418    if got == expected.state_root() {
419        Ok(())
420    } else {
421        error!(target: "sync::stages::merkle", ?target_block, ?got, ?expected, "Failed to verify block state root! {INVALID_STATE_ROOT_ERROR_MESSAGE}");
422        Err(StageError::Block {
423            error: BlockErrorKind::Validation(ConsensusError::BodyStateRootDiff(
424                GotExpected { got, expected: expected.state_root() }.into(),
425            )),
426            block: Box::new(expected.block_with_parent()),
427        })
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434    use crate::test_utils::{
435        stage_test_suite_ext, ExecuteStageTestRunner, StageTestRunner, StorageKind,
436        TestRunnerError, TestStageDB, UnwindStageTestRunner,
437    };
438    use alloy_primitives::{keccak256, U256};
439    use assert_matches::assert_matches;
440    use reth_db_api::cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO};
441    use reth_primitives_traits::{SealedBlock, StorageEntry};
442    use reth_provider::{providers::StaticFileWriter, StaticFileProviderFactory};
443    use reth_stages_api::StageUnitCheckpoint;
444    use reth_static_file_types::StaticFileSegment;
445    use reth_testing_utils::generators::{
446        self, random_block, random_block_range, random_changeset_range,
447        random_contract_account_range, BlockParams, BlockRangeParams,
448    };
449    use reth_trie::test_utils::{state_root, state_root_prehashed};
450    use std::collections::BTreeMap;
451
452    stage_test_suite_ext!(MerkleTestRunner, merkle);
453
454    /// Execute from genesis so as to merkelize whole state
455    #[tokio::test]
456    async fn execute_clean_merkle() {
457        let (previous_stage, stage_progress) = (500, 0);
458
459        // Set up the runner
460        let mut runner = MerkleTestRunner::default();
461        // set low threshold so we hash the whole storage
462        let input = ExecInput {
463            target: Some(previous_stage),
464            checkpoint: Some(StageCheckpoint::new(stage_progress)),
465        };
466
467        runner.seed_execution(input).expect("failed to seed execution");
468
469        let rx = runner.execute(input);
470
471        // Assert the successful result
472        let result = rx.await.unwrap();
473        assert_matches!(
474            result,
475            Ok(ExecOutput {
476                checkpoint: StageCheckpoint {
477                    block_number,
478                    stage_checkpoint: Some(StageUnitCheckpoint::Entities(EntitiesCheckpoint {
479                        processed,
480                        total
481                    }))
482                },
483                done: true
484            }) if block_number == previous_stage && processed == total &&
485                total == (
486                    runner.db.table::<tables::HashedAccounts>().unwrap().len() +
487                    runner.db.table::<tables::HashedStorages>().unwrap().len()
488                ) as u64
489        );
490
491        // Validate the stage execution
492        assert!(runner.validate_execution(input, result.ok()).is_ok(), "execution validation");
493    }
494
495    /// Update small trie
496    #[tokio::test]
497    async fn execute_small_merkle() {
498        let (previous_stage, stage_progress) = (2, 1);
499
500        // Set up the runner
501        let mut runner = MerkleTestRunner::default();
502        let input = ExecInput {
503            target: Some(previous_stage),
504            checkpoint: Some(StageCheckpoint::new(stage_progress)),
505        };
506
507        runner.seed_execution(input).expect("failed to seed execution");
508
509        let rx = runner.execute(input);
510
511        // Assert the successful result
512        let result = rx.await.unwrap();
513        assert_matches!(
514            result,
515            Ok(ExecOutput {
516                checkpoint: StageCheckpoint {
517                    block_number,
518                    stage_checkpoint: Some(StageUnitCheckpoint::Entities(EntitiesCheckpoint {
519                        processed,
520                        total
521                    }))
522                },
523                done: true
524            }) if block_number == previous_stage && processed == total &&
525                total == (
526                    runner.db.table::<tables::HashedAccounts>().unwrap().len() +
527                    runner.db.table::<tables::HashedStorages>().unwrap().len()
528                ) as u64
529        );
530
531        // Validate the stage execution
532        assert!(runner.validate_execution(input, result.ok()).is_ok(), "execution validation");
533    }
534
535    #[tokio::test]
536    async fn execute_chunked_merkle() {
537        let (previous_stage, stage_progress) = (200, 100);
538        let clean_threshold = 100;
539        let incremental_threshold = 10;
540
541        // Set up the runner
542        let mut runner =
543            MerkleTestRunner { db: TestStageDB::default(), clean_threshold, incremental_threshold };
544
545        let input = ExecInput {
546            target: Some(previous_stage),
547            checkpoint: Some(StageCheckpoint::new(stage_progress)),
548        };
549
550        runner.seed_execution(input).expect("failed to seed execution");
551        let rx = runner.execute(input);
552
553        // Assert the successful result
554        let result = rx.await.unwrap();
555        assert_matches!(
556            result,
557            Ok(ExecOutput {
558                checkpoint: StageCheckpoint {
559                    block_number,
560                    stage_checkpoint: Some(StageUnitCheckpoint::Entities(EntitiesCheckpoint {
561                        processed,
562                        total
563                    }))
564                },
565                done: true
566            }) if block_number == previous_stage && processed == total &&
567                total == (
568                    runner.db.table::<tables::HashedAccounts>().unwrap().len() +
569                    runner.db.table::<tables::HashedStorages>().unwrap().len()
570                ) as u64
571        );
572
573        // Validate the stage execution
574        let provider = runner.db.factory.provider().unwrap();
575        let header = provider.header_by_number(previous_stage).unwrap().unwrap();
576        let expected_root = header.state_root;
577
578        let actual_root = runner
579            .db
580            .query(|tx| {
581                Ok(StateRoot::incremental_root_with_updates(
582                    tx,
583                    stage_progress + 1..=previous_stage,
584                ))
585            })
586            .unwrap();
587
588        assert_eq!(
589            actual_root.unwrap().0,
590            expected_root,
591            "State root mismatch after chunked processing"
592        );
593    }
594
595    struct MerkleTestRunner {
596        db: TestStageDB,
597        clean_threshold: u64,
598        incremental_threshold: u64,
599    }
600
601    impl Default for MerkleTestRunner {
602        fn default() -> Self {
603            Self {
604                db: TestStageDB::default(),
605                clean_threshold: 10000,
606                incremental_threshold: 10000,
607            }
608        }
609    }
610
611    impl StageTestRunner for MerkleTestRunner {
612        type S = MerkleStage;
613
614        fn db(&self) -> &TestStageDB {
615            &self.db
616        }
617
618        fn stage(&self) -> Self::S {
619            Self::S::Both {
620                rebuild_threshold: self.clean_threshold,
621                incremental_threshold: self.incremental_threshold,
622            }
623        }
624    }
625
626    impl ExecuteStageTestRunner for MerkleTestRunner {
627        type Seed = Vec<SealedBlock<reth_ethereum_primitives::Block>>;
628
629        fn seed_execution(&mut self, input: ExecInput) -> Result<Self::Seed, TestRunnerError> {
630            let stage_progress = input.checkpoint().block_number;
631            let start = stage_progress + 1;
632            let end = input.target();
633            let mut rng = generators::rng();
634
635            let mut preblocks = vec![];
636            if stage_progress > 0 {
637                preblocks.append(&mut random_block_range(
638                    &mut rng,
639                    0..=stage_progress - 1,
640                    BlockRangeParams {
641                        parent: Some(B256::ZERO),
642                        tx_count: 0..1,
643                        ..Default::default()
644                    },
645                ));
646                self.db.insert_blocks(preblocks.iter(), StorageKind::Static)?;
647            }
648
649            let num_of_accounts = 31;
650            let accounts = random_contract_account_range(&mut rng, &mut (0..num_of_accounts))
651                .into_iter()
652                .collect::<BTreeMap<_, _>>();
653
654            self.db.insert_accounts_and_storages(
655                accounts.iter().map(|(addr, acc)| (*addr, (*acc, std::iter::empty()))),
656            )?;
657
658            let (header, body) = random_block(
659                &mut rng,
660                stage_progress,
661                BlockParams { parent: preblocks.last().map(|b| b.hash()), ..Default::default() },
662            )
663            .split_sealed_header_body();
664            let mut header = header.unseal();
665
666            header.state_root = state_root(
667                accounts
668                    .clone()
669                    .into_iter()
670                    .map(|(address, account)| (address, (account, std::iter::empty()))),
671            );
672            let sealed_head = SealedBlock::<reth_ethereum_primitives::Block>::from_sealed_parts(
673                SealedHeader::seal_slow(header),
674                body,
675            );
676
677            let head_hash = sealed_head.hash();
678            let mut blocks = vec![sealed_head];
679            blocks.extend(random_block_range(
680                &mut rng,
681                start..=end,
682                BlockRangeParams { parent: Some(head_hash), tx_count: 0..3, ..Default::default() },
683            ));
684            let last_block = blocks.last().cloned().unwrap();
685            self.db.insert_blocks(blocks.iter(), StorageKind::Static)?;
686
687            let (transitions, final_state) = random_changeset_range(
688                &mut rng,
689                blocks.iter(),
690                accounts.into_iter().map(|(addr, acc)| (addr, (acc, Vec::new()))),
691                0..3,
692                0..256,
693            );
694            // add block changeset from block 1.
695            self.db.insert_changesets(transitions, Some(start))?;
696            self.db.insert_accounts_and_storages(final_state)?;
697
698            // Calculate state root
699            let root = self.db.query(|tx| {
700                let mut accounts = BTreeMap::default();
701                let mut accounts_cursor = tx.cursor_read::<tables::HashedAccounts>()?;
702                let mut storage_cursor = tx.cursor_dup_read::<tables::HashedStorages>()?;
703                for entry in accounts_cursor.walk_range(..)? {
704                    let (key, account) = entry?;
705                    let mut storage_entries = Vec::new();
706                    let mut entry = storage_cursor.seek_exact(key)?;
707                    while let Some((_, storage)) = entry {
708                        storage_entries.push(storage);
709                        entry = storage_cursor.next_dup()?;
710                    }
711                    let storage = storage_entries
712                        .into_iter()
713                        .filter(|v| !v.value.is_zero())
714                        .map(|v| (v.key, v.value))
715                        .collect::<Vec<_>>();
716                    accounts.insert(key, (account, storage));
717                }
718
719                Ok(state_root_prehashed(accounts.into_iter()))
720            })?;
721
722            let static_file_provider = self.db.factory.static_file_provider();
723            let mut writer =
724                static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
725            let mut last_header = last_block.clone_sealed_header();
726            last_header.set_state_root(root);
727
728            let hash = last_header.hash_slow();
729            writer.prune_headers(1).unwrap();
730            writer.commit().unwrap();
731            writer.append_header(&last_header, U256::ZERO, &hash).unwrap();
732            writer.commit().unwrap();
733
734            Ok(blocks)
735        }
736
737        fn validate_execution(
738            &self,
739            _input: ExecInput,
740            _output: Option<ExecOutput>,
741        ) -> Result<(), TestRunnerError> {
742            // The execution is validated within the stage
743            Ok(())
744        }
745    }
746
747    impl UnwindStageTestRunner for MerkleTestRunner {
748        fn validate_unwind(&self, _input: UnwindInput) -> Result<(), TestRunnerError> {
749            // The unwind is validated within the stage
750            Ok(())
751        }
752
753        fn before_unwind(&self, input: UnwindInput) -> Result<(), TestRunnerError> {
754            let target_block = input.unwind_to + 1;
755
756            self.db
757                .commit(|tx| {
758                    let mut storage_changesets_cursor =
759                        tx.cursor_dup_read::<tables::StorageChangeSets>().unwrap();
760                    let mut storage_cursor =
761                        tx.cursor_dup_write::<tables::HashedStorages>().unwrap();
762
763                    let mut tree: BTreeMap<B256, BTreeMap<B256, U256>> = BTreeMap::new();
764
765                    let mut rev_changeset_walker =
766                        storage_changesets_cursor.walk_back(None).unwrap();
767                    while let Some((bn_address, entry)) =
768                        rev_changeset_walker.next().transpose().unwrap()
769                    {
770                        if bn_address.block_number() < target_block {
771                            break
772                        }
773
774                        tree.entry(keccak256(bn_address.address()))
775                            .or_default()
776                            .insert(keccak256(entry.key), entry.value);
777                    }
778                    for (hashed_address, storage) in tree {
779                        for (hashed_slot, value) in storage {
780                            let storage_entry = storage_cursor
781                                .seek_by_key_subkey(hashed_address, hashed_slot)
782                                .unwrap();
783                            if storage_entry.is_some_and(|v| v.key == hashed_slot) {
784                                storage_cursor.delete_current().unwrap();
785                            }
786
787                            if !value.is_zero() {
788                                let storage_entry = StorageEntry { key: hashed_slot, value };
789                                storage_cursor.upsert(hashed_address, &storage_entry).unwrap();
790                            }
791                        }
792                    }
793
794                    let mut changeset_cursor =
795                        tx.cursor_dup_write::<tables::AccountChangeSets>().unwrap();
796                    let mut rev_changeset_walker = changeset_cursor.walk_back(None).unwrap();
797
798                    while let Some((block_number, account_before_tx)) =
799                        rev_changeset_walker.next().transpose().unwrap()
800                    {
801                        if block_number < target_block {
802                            break
803                        }
804
805                        if let Some(acc) = account_before_tx.info {
806                            tx.put::<tables::HashedAccounts>(
807                                keccak256(account_before_tx.address),
808                                acc,
809                            )
810                            .unwrap();
811                        } else {
812                            tx.delete::<tables::HashedAccounts>(
813                                keccak256(account_before_tx.address),
814                                None,
815                            )
816                            .unwrap();
817                        }
818                    }
819                    Ok(())
820                })
821                .unwrap();
822            Ok(())
823        }
824    }
825}