Skip to main content

reth_stages/stages/
merkle.rs

1use alloy_consensus::BlockHeader;
2use alloy_primitives::{BlockNumber, Keccak256, 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    ChangeSetReader, DBProvider, HeaderProvider, ProviderError, StageCheckpointReader,
12    StageCheckpointWriter, StatsReader, StorageChangeSetReader, StorageSettingsCache, 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;
20
21use std::fmt::Debug;
22
23type DbStateRoot<'a, TX, A> = StateRoot<
24    reth_trie_db::DatabaseTrieCursorFactory<&'a TX, A>,
25    reth_trie_db::DatabaseHashedCursorFactory<&'a TX>,
26>;
27use tracing::*;
28
29// TODO: automate the process outlined below so the user can just send in a debugging package
30/// The error message that we include in invalid state root errors to tell users what information
31/// they should include in a bug report, since true state root errors can be impossible to debug
32/// with just basic logs.
33pub const INVALID_STATE_ROOT_ERROR_MESSAGE: &str = r#"
34Invalid state root error on stage verification!
35This is an error that likely requires a report to the reth team with additional information.
36Please include the following information in your report:
37 * This error message
38 * The state root of the block that was rejected
39 * The output of `reth db stats --checksum` from the database that was being used. This will take a long time to run!
40 * 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.
41 * The debug logs from __the same time period__. To find the default location for these logs, run:
42   `reth --help | grep -A 4 'log.file.directory'`
43
44Once you have this information, please submit a github issue at https://github.com/paradigmxyz/reth/issues/new
45"#;
46
47/// The default threshold (in number of blocks) for switching from incremental trie building
48/// of changes to whole rebuild.
49pub const MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD: u64 = 100_000;
50
51/// The default threshold (in number of blocks) to run the stage in incremental mode. The
52/// incremental mode will calculate the state root for a large range of blocks by calculating the
53/// new state root for this many blocks, in batches, repeating until we reach the desired block
54/// number.
55pub const MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD: u64 = 7_000;
56
57// Progress key binding the saved execution checkpoint to its target block hash and exact bytes,
58// kept apart from the checkpoint so its encoding stays readable by older nodes.
59const MERKLE_EXECUTE_BINDING: StageId = StageId::Other("MerkleExecuteBinding");
60
61/// The merkle hashing stage uses input from
62/// [`AccountHashingStage`][crate::stages::AccountHashingStage] and
63/// [`StorageHashingStage`][crate::stages::StorageHashingStage] to calculate intermediate hashes
64/// and state roots.
65///
66/// This stage should be run with the above two stages, otherwise it is a no-op.
67///
68/// This stage is split in two: one for calculating hashes and one for unwinding.
69///
70/// When run in execution, it's going to be executed AFTER the hashing stages, to generate
71/// the state root. When run in unwind mode, it's going to be executed BEFORE the hashing stages,
72/// so that it unwinds the intermediate hashes based on the unwound hashed state from the hashing
73/// stages. The order of these two variants is important. The unwind variant should be added to the
74/// pipeline before the execution variant.
75///
76/// An example pipeline to only hash state would be:
77///
78/// - [`MerkleStage::Unwind`]
79/// - [`AccountHashingStage`][crate::stages::AccountHashingStage]
80/// - [`StorageHashingStage`][crate::stages::StorageHashingStage]
81/// - [`MerkleStage::Execution`]
82#[derive(Debug, Clone)]
83pub enum MerkleStage {
84    /// The execution portion of the merkle stage.
85    Execution {
86        // TODO: make struct for holding incremental settings, for code reuse between `Execution`
87        // variant and `Both`
88        /// The threshold (in number of blocks) for switching from incremental trie building
89        /// of changes to whole rebuild.
90        rebuild_threshold: u64,
91        /// The threshold (in number of blocks) to run the stage in incremental mode. The
92        /// incremental mode will calculate the state root by calculating the new state root for
93        /// some number of blocks, repeating until we reach the desired block number.
94        incremental_threshold: u64,
95    },
96    /// The unwind portion of the merkle stage.
97    Unwind {
98        /// Whether every child of a changed branch path should be walked.
99        walk_all_changed_branch_children: bool,
100    },
101    /// Able to execute and unwind. Used for tests
102    #[cfg(any(test, feature = "test-utils"))]
103    Both {
104        /// The threshold (in number of blocks) for switching from incremental trie building
105        /// of changes to whole rebuild.
106        rebuild_threshold: u64,
107        /// The threshold (in number of blocks) to run the stage in incremental mode. The
108        /// incremental mode will calculate the state root by calculating the new state root for
109        /// some number of blocks, repeating until we reach the desired block number.
110        incremental_threshold: u64,
111    },
112}
113
114impl MerkleStage {
115    /// Stage default for the [`MerkleStage::Execution`].
116    pub const fn default_execution() -> Self {
117        Self::Execution {
118            rebuild_threshold: MERKLE_STAGE_DEFAULT_REBUILD_THRESHOLD,
119            incremental_threshold: MERKLE_STAGE_DEFAULT_INCREMENTAL_THRESHOLD,
120        }
121    }
122
123    /// Stage default for the [`MerkleStage::Unwind`].
124    pub const fn default_unwind() -> Self {
125        Self::new_unwind(false)
126    }
127
128    /// Create a new instance of [`MerkleStage::Unwind`].
129    pub const fn new_unwind(walk_all_changed_branch_children: bool) -> Self {
130        Self::Unwind { walk_all_changed_branch_children }
131    }
132
133    /// Create new instance of [`MerkleStage::Execution`].
134    pub const fn new_execution(rebuild_threshold: u64, incremental_threshold: u64) -> Self {
135        Self::Execution { rebuild_threshold, incremental_threshold }
136    }
137
138    /// Gets the hashing progress
139    pub fn get_execution_checkpoint(
140        &self,
141        provider: &impl StageCheckpointReader,
142    ) -> Result<Option<MerkleCheckpoint>, StageError> {
143        let buf =
144            provider.get_stage_checkpoint_progress(StageId::MerkleExecute)?.unwrap_or_default();
145
146        if buf.is_empty() {
147            return Ok(None)
148        }
149
150        let (checkpoint, _) = MerkleCheckpoint::from_compact(&buf, buf.len());
151        Ok(Some(checkpoint))
152    }
153
154    /// Saves the hashing progress
155    ///
156    /// The checkpoint is not bound to a target block, so the next execution rebuilds the trie
157    /// instead of resuming it.
158    pub fn save_execution_checkpoint(
159        &self,
160        provider: &impl StageCheckpointWriter,
161        checkpoint: Option<MerkleCheckpoint>,
162    ) -> Result<(), StageError> {
163        let buf = checkpoint.as_ref().map(encode_execution_checkpoint).unwrap_or_default();
164        provider.save_stage_checkpoint_progress(StageId::MerkleExecute, buf)?;
165        Ok(provider.save_stage_checkpoint_progress(MERKLE_EXECUTE_BINDING, Vec::new())?)
166    }
167
168    // Saves `checkpoint` bound to `target_hash`, so only a run toward that block resumes it.
169    fn save_resumable_execution_checkpoint(
170        &self,
171        provider: &impl StageCheckpointWriter,
172        checkpoint: &MerkleCheckpoint,
173        target_hash: B256,
174    ) -> Result<(), StageError> {
175        debug!(
176            target: "sync::stages::merkle::exec",
177            last_account_key = ?checkpoint.last_account_key,
178            "Saving inner merkle checkpoint"
179        );
180        let buf = encode_execution_checkpoint(checkpoint);
181        provider.save_stage_checkpoint_progress(
182            MERKLE_EXECUTE_BINDING,
183            checkpoint_binding(target_hash, &buf).to_vec(),
184        )?;
185        Ok(provider.save_stage_checkpoint_progress(StageId::MerkleExecute, buf)?)
186    }
187
188    // Loads the checkpoint saved toward `target_hash`, or none when another block or a writer that
189    // does not bind it, such as an older node, saved the current checkpoint.
190    fn resumable_execution_checkpoint(
191        &self,
192        provider: &impl StageCheckpointReader,
193        target_hash: B256,
194    ) -> Result<Option<MerkleCheckpoint>, StageError> {
195        let buf =
196            provider.get_stage_checkpoint_progress(StageId::MerkleExecute)?.unwrap_or_default();
197        if buf.is_empty() {
198            return Ok(None)
199        }
200        let bound = provider.get_stage_checkpoint_progress(MERKLE_EXECUTE_BINDING)?;
201        if bound.as_deref() != Some(checkpoint_binding(target_hash, &buf).as_slice()) {
202            debug!(
203                target: "sync::stages::merkle::exec",
204                ?target_hash,
205                "Discarding inner merkle checkpoint saved toward another target"
206            );
207            return Ok(None)
208        }
209        Ok(Some(MerkleCheckpoint::from_compact(&buf, buf.len()).0))
210    }
211}
212
213impl<Provider> Stage<Provider> for MerkleStage
214where
215    Provider: DBProvider<Tx: DbTxMut>
216        + TrieWriter
217        + StatsReader
218        + HeaderProvider
219        + ChangeSetReader
220        + StorageChangeSetReader
221        + StorageSettingsCache
222        + StageCheckpointReader
223        + StageCheckpointWriter,
224{
225    /// Return the id of the stage
226    fn id(&self) -> StageId {
227        match self {
228            Self::Execution { .. } => StageId::MerkleExecute,
229            Self::Unwind { .. } => StageId::MerkleUnwind,
230            #[cfg(any(test, feature = "test-utils"))]
231            Self::Both { .. } => StageId::Other("MerkleBoth"),
232        }
233    }
234
235    /// Execute the stage.
236    fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError> {
237        let (threshold, incremental_threshold) = match self {
238            Self::Unwind { .. } => {
239                info!(target: "sync::stages::merkle::unwind", "Stage is always skipped");
240                return Ok(ExecOutput::done(StageCheckpoint::new(input.target())))
241            }
242            Self::Execution { rebuild_threshold, incremental_threshold } => {
243                (*rebuild_threshold, *incremental_threshold)
244            }
245            #[cfg(any(test, feature = "test-utils"))]
246            Self::Both { rebuild_threshold, incremental_threshold } => {
247                (*rebuild_threshold, *incremental_threshold)
248            }
249        };
250        let incremental_threshold = incremental_threshold.max(1);
251
252        let range = input.next_block_range();
253        let (from_block, to_block) = range.clone().into_inner();
254        let current_block_number = input.checkpoint().block_number;
255
256        let target_block = SealedHeader::seal_slow(
257            provider
258                .header_by_number(to_block)?
259                .ok_or_else(|| ProviderError::HeaderNotFound(to_block.into()))?,
260        );
261        let target_block_root = target_block.state_root();
262
263        let (trie_root, entities_checkpoint) = if range.is_empty() {
264            (target_block_root, input.checkpoint().entities_stage_checkpoint().unwrap_or_default())
265        } else if to_block - from_block > threshold || from_block == 1 {
266            let checkpoint = self.resumable_execution_checkpoint(provider, target_block.hash())?;
267
268            // if there are more blocks than threshold it is faster to rebuild the trie
269            let mut entities_checkpoint = if let Some(checkpoint) = checkpoint.as_ref() {
270                debug!(
271                    target: "sync::stages::merkle::exec",
272                    current = ?current_block_number,
273                    target = ?to_block,
274                    last_account_key = ?checkpoint.last_account_key,
275                    "Continuing inner merkle checkpoint"
276                );
277
278                input.checkpoint().entities_stage_checkpoint()
279            } else {
280                debug!(
281                    target: "sync::stages::merkle::exec",
282                    current = ?current_block_number,
283                    target = ?to_block,
284                    "Rebuilding trie"
285                );
286                // Reset the checkpoint and clear trie tables
287                self.save_execution_checkpoint(provider, None)?;
288                provider.tx_ref().clear::<tables::AccountsTrie>()?;
289                provider.tx_ref().clear::<tables::StoragesTrie>()?;
290
291                None
292            }
293            .unwrap_or(EntitiesCheckpoint {
294                processed: 0,
295                total: (provider.count_entries::<tables::HashedAccounts>()? +
296                    provider.count_entries::<tables::HashedStorages>()?)
297                    as u64,
298            });
299
300            let tx = provider.tx_ref();
301            let progress = reth_trie_db::with_adapter!(provider, |A| {
302                DbStateRoot::<_, A>::from_tx(tx)
303                    .with_intermediate_state(checkpoint.map(IntermediateStateRootState::from))
304                    .root_with_progress()
305            })
306            .map_err(|e| {
307                error!(target: "sync::stages::merkle", %e, ?current_block_number, ?to_block, "State root with progress failed! {INVALID_STATE_ROOT_ERROR_MESSAGE}");
308                StageError::Fatal(Box::new(e))
309            })?;
310            match progress {
311                StateRootProgress::Progress(state, hashed_entries_walked, updates) => {
312                    provider.write_trie_updates(updates)?;
313
314                    let mut checkpoint = MerkleCheckpoint::new(
315                        to_block,
316                        state.account_root_state.last_hashed_key,
317                        state
318                            .account_root_state
319                            .walker_stack
320                            .into_iter()
321                            .map(StoredSubNode::from)
322                            .collect(),
323                        state.account_root_state.hash_builder.into(),
324                    );
325
326                    // Save storage root state if present
327                    if let Some(storage_state) = state.storage_root_state {
328                        checkpoint.storage_root_checkpoint =
329                            Some(StorageRootMerkleCheckpoint::new(
330                                storage_state.state.last_hashed_key,
331                                storage_state
332                                    .state
333                                    .walker_stack
334                                    .into_iter()
335                                    .map(StoredSubNode::from)
336                                    .collect(),
337                                storage_state.state.hash_builder.into(),
338                                storage_state.account,
339                            ));
340                    }
341                    self.save_resumable_execution_checkpoint(
342                        provider,
343                        &checkpoint,
344                        target_block.hash(),
345                    )?;
346
347                    entities_checkpoint.processed += hashed_entries_walked as u64;
348
349                    return Ok(ExecOutput::in_progress(
350                        input.checkpoint().with_entities_stage_checkpoint(entities_checkpoint),
351                    ))
352                }
353                StateRootProgress::Complete(root, hashed_entries_walked, updates) => {
354                    provider.write_trie_updates(updates)?;
355
356                    entities_checkpoint.processed += hashed_entries_walked as u64;
357
358                    (root, entities_checkpoint)
359                }
360            }
361        } else {
362            debug!(target: "sync::stages::merkle::exec", current = ?current_block_number, target = ?to_block, "Updating trie in chunks");
363            let mut final_root = None;
364            for start_block in range.step_by(incremental_threshold as usize) {
365                let chunk_to = start_block.saturating_add(incremental_threshold - 1).min(to_block);
366                let chunk_range = start_block..=chunk_to;
367                debug!(
368                    target: "sync::stages::merkle::exec",
369                    current = ?current_block_number,
370                    target = ?to_block,
371                    incremental_threshold,
372                    chunk_range = ?chunk_range,
373                    "Processing chunk"
374                );
375                let (root, updates) = reth_trie_db::with_adapter!(provider, |A| {
376                    DbStateRoot::<_, A>::incremental_root_with_updates(provider, chunk_range)
377                })
378                .map_err(|e| {
379                    error!(target: "sync::stages::merkle", %e, ?current_block_number, ?to_block, "Incremental state root failed! {INVALID_STATE_ROOT_ERROR_MESSAGE}");
380                    StageError::Fatal(Box::new(e))
381                })?;
382                provider.write_trie_updates(updates)?;
383                final_root = Some(root);
384            }
385
386            // if we had no final root, we must have not looped above, which should not be possible
387            let final_root = final_root.ok_or(StageError::Fatal(
388                "Incremental merkle hashing did not produce a final root".into(),
389            ))?;
390
391            let total_hashed_entries = (provider.count_entries::<tables::HashedAccounts>()? +
392                provider.count_entries::<tables::HashedStorages>()?)
393                as u64;
394
395            let entities_checkpoint = EntitiesCheckpoint {
396                // This is fine because `range` doesn't have an upper bound, so in this `else`
397                // branch we're just hashing all remaining accounts and storage slots we have in the
398                // database.
399                processed: total_hashed_entries,
400                total: total_hashed_entries,
401            };
402            // Save the checkpoint
403            (final_root, entities_checkpoint)
404        };
405
406        // Reset the checkpoint
407        self.save_execution_checkpoint(provider, None)?;
408
409        validate_state_root(trie_root, target_block, to_block)?;
410
411        Ok(ExecOutput::done(
412            StageCheckpoint::new(to_block).with_entities_stage_checkpoint(entities_checkpoint),
413        ))
414    }
415
416    /// Unwind the stage.
417    fn unwind(
418        &mut self,
419        provider: &Provider,
420        input: UnwindInput,
421    ) -> Result<UnwindOutput, StageError> {
422        let tx = provider.tx_ref();
423        let range = input.unwind_block_range();
424        if matches!(self, Self::Execution { .. }) {
425            info!(target: "sync::stages::merkle::unwind", "Stage is always skipped");
426            return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) })
427        }
428        let walk_all_changed_branch_children = match self {
429            Self::Unwind { walk_all_changed_branch_children } => *walk_all_changed_branch_children,
430            #[cfg(any(test, feature = "test-utils"))]
431            Self::Both { .. } => false,
432            Self::Execution { .. } => unreachable!(),
433        };
434
435        let mut entities_checkpoint =
436            input.checkpoint.entities_stage_checkpoint().unwrap_or(EntitiesCheckpoint {
437                processed: 0,
438                total: (tx.entries::<tables::HashedAccounts>()? +
439                    tx.entries::<tables::HashedStorages>()?) as u64,
440            });
441
442        if input.unwind_to == 0 {
443            tx.clear::<tables::AccountsTrie>()?;
444            tx.clear::<tables::StoragesTrie>()?;
445
446            entities_checkpoint.processed = 0;
447
448            return Ok(UnwindOutput {
449                checkpoint: StageCheckpoint::new(input.unwind_to)
450                    .with_entities_stage_checkpoint(entities_checkpoint),
451            })
452        }
453
454        // Unwind trie only if there are transitions
455        if range.is_empty() {
456            info!(target: "sync::stages::merkle::unwind", "Nothing to unwind");
457        } else {
458            let (block_root, updates) = reth_trie_db::with_adapter!(provider, |A| {
459                DbStateRoot::<_, A>::incremental_root_calculator(provider, range).and_then(
460                    |calculator| {
461                        calculator
462                            .with_walk_all_changed_branch_children(walk_all_changed_branch_children)
463                            .root_with_updates()
464                    },
465                )
466            })
467            .map_err(|e| StageError::Fatal(Box::new(e)))?;
468
469            // Validate the calculated state root
470            let target = provider
471                .header_by_number(input.unwind_to)?
472                .ok_or_else(|| ProviderError::HeaderNotFound(input.unwind_to.into()))?;
473
474            validate_state_root(block_root, SealedHeader::seal_slow(target), input.unwind_to)?;
475
476            // Validation passed, apply unwind changes to the database.
477            provider.write_trie_updates(updates)?;
478
479            // Update entities checkpoint to reflect the unwind operation
480            // Since we're unwinding, we need to recalculate the total entities at the target block
481            let accounts = tx.entries::<tables::HashedAccounts>()?;
482            let storages = tx.entries::<tables::HashedStorages>()?;
483            let total = (accounts + storages) as u64;
484            entities_checkpoint.total = total;
485            entities_checkpoint.processed = total;
486        }
487
488        Ok(UnwindOutput {
489            checkpoint: StageCheckpoint::new(input.unwind_to)
490                .with_entities_stage_checkpoint(entities_checkpoint),
491        })
492    }
493}
494
495/// Check that the computed state root matches the root in the expected header.
496#[inline]
497fn validate_state_root<H: BlockHeader + Sealable + Debug>(
498    got: B256,
499    expected: SealedHeader<H>,
500    target_block: BlockNumber,
501) -> Result<(), StageError> {
502    if got == expected.state_root() {
503        Ok(())
504    } else {
505        error!(target: "sync::stages::merkle", ?target_block, ?got, ?expected, "Failed to verify block state root! {INVALID_STATE_ROOT_ERROR_MESSAGE}");
506        Err(StageError::Block {
507            error: BlockErrorKind::Validation(ConsensusError::BodyStateRootDiff(
508                GotExpected { got, expected: expected.state_root() }.into(),
509            )),
510            block: Box::new(expected.block_with_parent()),
511        })
512    }
513}
514
515// Encodes an execution checkpoint as it is stored.
516fn encode_execution_checkpoint(checkpoint: &MerkleCheckpoint) -> Vec<u8> {
517    let mut buf = Vec::new();
518    checkpoint.to_compact(&mut buf);
519    buf
520}
521
522// Binds an encoded checkpoint to the block hash it was computed toward.
523fn checkpoint_binding(target_hash: B256, checkpoint: &[u8]) -> B256 {
524    let mut hasher = Keccak256::new();
525    hasher.update(target_hash);
526    hasher.update(checkpoint);
527    hasher.finalize()
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::test_utils::{
534        stage_test_suite_ext, ExecuteStageTestRunner, StageTestRunner, StorageKind,
535        TestRunnerError, TestStageDB, UnwindStageTestRunner,
536    };
537    use alloy_primitives::{keccak256, Address, U256};
538    use assert_matches::assert_matches;
539    use reth_db_api::cursor::{DbCursorRO, DbCursorRW, DbDupCursorRO};
540    use reth_primitives_traits::{Account, SealedBlock, StorageEntry};
541    use reth_provider::{providers::StaticFileWriter, StaticFileProviderFactory};
542    use reth_stages_api::StageUnitCheckpoint;
543    use reth_static_file_types::StaticFileSegment;
544    use reth_testing_utils::generators::{
545        self, random_block, random_block_range, random_changeset_range,
546        random_contract_account_range, random_eoa_accounts, random_header, random_header_range,
547        BlockParams, BlockRangeParams,
548    };
549    use reth_trie::test_utils::{state_root, state_root_prehashed};
550    use std::collections::BTreeMap;
551
552    // Height every rebuild test targets.
553    const REBUILD_TARGET: BlockNumber = 5;
554
555    // Entities a resumed rebuild has already counted, above any count a fresh rebuild reaches.
556    const RESUMED: u64 = 1_000_000;
557
558    // Seeds 200 random accounts without storage and returns their addresses.
559    fn seed_accounts(db: &TestStageDB) -> Vec<Address> {
560        let accounts = random_eoa_accounts(&mut generators::rng(), 200);
561        let addresses = accounts.iter().map(|(address, _)| *address).collect();
562        db.insert_accounts_and_storages(
563            accounts.into_iter().map(|(address, account)| (address, (account, []))),
564        )
565        .unwrap();
566        addresses
567    }
568
569    // Inserts a chain whose block at `REBUILD_TARGET` commits to the current hashed state and
570    // returns that block.
571    fn insert_rebuild_chain(db: &TestStageDB) -> SealedHeader {
572        let mut headers =
573            random_header_range(&mut generators::rng(), 0..REBUILD_TARGET + 1, B256::ZERO);
574        let mut target = headers.pop().unwrap().header().clone();
575        target.state_root = state_root_prehashed(
576            db.table::<tables::HashedAccounts>()
577                .unwrap()
578                .into_iter()
579                .map(|(key, account)| (key, (account, []))),
580        );
581        headers.push(SealedHeader::seal_slow(target));
582        db.insert_headers(headers.iter()).unwrap();
583        headers.pop().unwrap()
584    }
585
586    // Pauses a rebuild toward `REBUILD_TARGET` part way and commits its trie updates, as a
587    // restart leaves them, returning its checkpoint unsaved.
588    fn pause_rebuild(db: &TestStageDB) -> MerkleCheckpoint {
589        let provider_rw = db.factory.provider_rw().unwrap();
590        let provider = &*provider_rw;
591        let tx = provider.tx_ref();
592        let progress = reth_trie_db::with_adapter!(provider, |A| {
593            DbStateRoot::<_, A>::from_tx(tx).with_threshold(1).root_with_progress()
594        })
595        .unwrap();
596        let StateRootProgress::Progress(state, _, updates) = progress else {
597            panic!("expected the rebuild to pause")
598        };
599        provider.write_trie_updates(updates).unwrap();
600        provider_rw.commit().unwrap();
601        MerkleCheckpoint::new(
602            REBUILD_TARGET,
603            state.account_root_state.last_hashed_key,
604            state.account_root_state.walker_stack.into_iter().map(StoredSubNode::from).collect(),
605            state.account_root_state.hash_builder.into(),
606        )
607    }
608
609    // Runs the rebuild to `REBUILD_TARGET` from a checkpoint that has counted `RESUMED` entities
610    // and returns the entities counted once it is done.
611    fn rebuild(db: &TestStageDB) -> u64 {
612        let checkpoint = StageCheckpoint::new(0)
613            .with_entities_stage_checkpoint(EntitiesCheckpoint { processed: RESUMED, total: 0 });
614        let input = ExecInput { target: Some(REBUILD_TARGET), checkpoint: Some(checkpoint) };
615        let output = MerkleStage::new_execution(100_000, 7_000)
616            .execute(&*db.factory.provider_rw().unwrap(), input)
617            .unwrap();
618        assert!(output.done);
619        output.checkpoint.entities_stage_checkpoint().unwrap().processed
620    }
621
622    stage_test_suite_ext!(MerkleTestRunner, merkle);
623
624    /// Execute from genesis so as to merkelize whole state
625    #[tokio::test]
626    async fn execute_clean_merkle() {
627        let (previous_stage, stage_progress) = (500, 0);
628
629        // Set up the runner
630        let mut runner = MerkleTestRunner::default();
631        // set low threshold so we hash the whole storage
632        let input = ExecInput {
633            target: Some(previous_stage),
634            checkpoint: Some(StageCheckpoint::new(stage_progress)),
635        };
636
637        runner.seed_execution(input).expect("failed to seed execution");
638
639        let rx = runner.execute(input);
640
641        // Assert the successful result
642        let result = rx.await.unwrap();
643        assert_matches!(
644            result,
645            Ok(ExecOutput {
646                checkpoint: StageCheckpoint {
647                    block_number,
648                    stage_checkpoint: Some(StageUnitCheckpoint::Entities(EntitiesCheckpoint {
649                        processed,
650                        total
651                    }))
652                },
653                done: true
654            }) if block_number == previous_stage && processed == total &&
655                total == (
656                    runner.db.count_entries::<tables::HashedAccounts>().unwrap() +
657                    runner.db.count_entries::<tables::HashedStorages>().unwrap()
658                ) as u64
659        );
660
661        // Validate the stage execution
662        assert!(runner.validate_execution(input, result.ok()).is_ok(), "execution validation");
663    }
664
665    /// Update small trie
666    #[tokio::test]
667    async fn execute_small_merkle() {
668        let (previous_stage, stage_progress) = (2, 1);
669
670        // Set up the runner
671        let mut runner = MerkleTestRunner::default();
672        let input = ExecInput {
673            target: Some(previous_stage),
674            checkpoint: Some(StageCheckpoint::new(stage_progress)),
675        };
676
677        runner.seed_execution(input).expect("failed to seed execution");
678
679        let rx = runner.execute(input);
680
681        // Assert the successful result
682        let result = rx.await.unwrap();
683        assert_matches!(
684            result,
685            Ok(ExecOutput {
686                checkpoint: StageCheckpoint {
687                    block_number,
688                    stage_checkpoint: Some(StageUnitCheckpoint::Entities(EntitiesCheckpoint {
689                        processed,
690                        total
691                    }))
692                },
693                done: true
694            }) if block_number == previous_stage && processed == total &&
695                total == (
696                    runner.db.count_entries::<tables::HashedAccounts>().unwrap() +
697                    runner.db.count_entries::<tables::HashedStorages>().unwrap()
698                ) as u64
699        );
700
701        // Validate the stage execution
702        assert!(runner.validate_execution(input, result.ok()).is_ok(), "execution validation");
703    }
704
705    #[tokio::test]
706    async fn execute_chunked_merkle() {
707        for incremental_threshold in [0, 10, u64::MAX] {
708            execute_chunked_merkle_with(incremental_threshold).await;
709        }
710    }
711
712    async fn execute_chunked_merkle_with(incremental_threshold: u64) {
713        let (previous_stage, stage_progress) = (200, 100);
714        let clean_threshold = 100;
715
716        // Set up the runner
717        let mut runner =
718            MerkleTestRunner { db: TestStageDB::default(), clean_threshold, incremental_threshold };
719
720        let input = ExecInput {
721            target: Some(previous_stage),
722            checkpoint: Some(StageCheckpoint::new(stage_progress)),
723        };
724
725        runner.seed_execution(input).expect("failed to seed execution");
726        let rx = runner.execute(input);
727
728        // Assert the successful result
729        let result = rx.await.unwrap();
730        assert_matches!(
731            result,
732            Ok(ExecOutput {
733                checkpoint: StageCheckpoint {
734                    block_number,
735                    stage_checkpoint: Some(StageUnitCheckpoint::Entities(EntitiesCheckpoint {
736                        processed,
737                        total
738                    }))
739                },
740                done: true
741            }) if block_number == previous_stage && processed == total &&
742                total == (
743                    runner.db.count_entries::<tables::HashedAccounts>().unwrap() +
744                    runner.db.count_entries::<tables::HashedStorages>().unwrap()
745                ) as u64
746        );
747
748        // Validate the stage execution
749        let provider = runner.db.factory.provider().unwrap();
750        let header = provider.header_by_number(previous_stage).unwrap().unwrap();
751        let expected_root = header.state_root;
752
753        let actual_root = runner
754            .db
755            .query_with_provider(|provider| {
756                Ok(reth_trie_db::with_adapter!(provider, |A| {
757                    DbStateRoot::<_, A>::incremental_root_with_updates(
758                        &provider,
759                        stage_progress + 1..=previous_stage,
760                    )
761                }))
762            })
763            .unwrap();
764
765        assert_eq!(
766            actual_root.unwrap().0,
767            expected_root,
768            "State root mismatch after chunked processing"
769        );
770    }
771
772    struct MerkleTestRunner {
773        db: TestStageDB,
774        clean_threshold: u64,
775        incremental_threshold: u64,
776    }
777
778    impl Default for MerkleTestRunner {
779        fn default() -> Self {
780            Self {
781                db: TestStageDB::default(),
782                clean_threshold: 10000,
783                incremental_threshold: 10000,
784            }
785        }
786    }
787
788    impl StageTestRunner for MerkleTestRunner {
789        type S = MerkleStage;
790
791        fn db(&self) -> &TestStageDB {
792            &self.db
793        }
794
795        fn stage(&self) -> Self::S {
796            Self::S::Both {
797                rebuild_threshold: self.clean_threshold,
798                incremental_threshold: self.incremental_threshold,
799            }
800        }
801    }
802
803    impl ExecuteStageTestRunner for MerkleTestRunner {
804        type Seed = Vec<SealedBlock<reth_ethereum_primitives::Block>>;
805
806        #[allow(clippy::clone_on_copy)]
807        fn seed_execution(&mut self, input: ExecInput) -> Result<Self::Seed, TestRunnerError> {
808            let stage_progress = input.checkpoint().block_number;
809            let start = stage_progress + 1;
810            let end = input.target();
811            let mut rng = generators::rng();
812
813            let mut preblocks = vec![];
814            if stage_progress > 0 {
815                preblocks.append(&mut random_block_range(
816                    &mut rng,
817                    0..=stage_progress - 1,
818                    BlockRangeParams {
819                        parent: Some(B256::ZERO),
820                        tx_count: 0..1,
821                        ..Default::default()
822                    },
823                ));
824                self.db.insert_blocks(preblocks.iter(), StorageKind::Static)?;
825            }
826
827            let num_of_accounts = 31;
828            let accounts = random_contract_account_range(&mut rng, &mut (0..num_of_accounts))
829                .into_iter()
830                .collect::<BTreeMap<_, _>>();
831
832            self.db.insert_accounts_and_storages(
833                accounts.iter().map(|(addr, acc)| (*addr, (acc.clone(), std::iter::empty()))),
834            )?;
835
836            let (header, body) = random_block(
837                &mut rng,
838                stage_progress,
839                BlockParams { parent: preblocks.last().map(|b| b.hash()), ..Default::default() },
840            )
841            .split_sealed_header_body();
842            let mut header = header.unseal();
843
844            header.state_root = state_root(
845                accounts
846                    .clone()
847                    .into_iter()
848                    .map(|(address, account)| (address, (account, std::iter::empty()))),
849            );
850            let sealed_head = SealedBlock::<reth_ethereum_primitives::Block>::from_sealed_parts(
851                SealedHeader::seal_slow(header),
852                body,
853            );
854
855            let head_hash = sealed_head.hash();
856            let mut blocks = vec![sealed_head];
857            blocks.extend(random_block_range(
858                &mut rng,
859                start..=end,
860                BlockRangeParams { parent: Some(head_hash), tx_count: 0..3, ..Default::default() },
861            ));
862            let last_block = blocks.last().cloned().unwrap();
863            self.db.insert_blocks(blocks.iter(), StorageKind::Static)?;
864
865            let (transitions, final_state) = random_changeset_range(
866                &mut rng,
867                blocks.iter(),
868                accounts.into_iter().map(|(addr, acc)| (addr, (acc, Vec::new()))),
869                0..3,
870                0..256,
871            );
872            // add block changeset from block 1.
873            self.db.insert_changesets(transitions, Some(start))?;
874            self.db.insert_accounts_and_storages(final_state)?;
875
876            // Calculate state root
877            let root = self.db.query(|tx| {
878                let mut accounts = BTreeMap::default();
879                let mut accounts_cursor = tx.cursor_read::<tables::HashedAccounts>()?;
880                let mut storage_cursor = tx.cursor_dup_read::<tables::HashedStorages>()?;
881                for entry in accounts_cursor.walk_range(..)? {
882                    let (key, account) = entry?;
883                    let mut storage_entries = Vec::new();
884                    let mut entry = storage_cursor.seek_exact(key)?;
885                    while let Some((_, storage)) = entry {
886                        storage_entries.push(storage);
887                        entry = storage_cursor.next_dup()?;
888                    }
889                    let storage = storage_entries
890                        .into_iter()
891                        .filter(|v| !v.value.is_zero())
892                        .map(|v| (v.key, v.value))
893                        .collect::<Vec<_>>();
894                    accounts.insert(key, (account, storage));
895                }
896
897                Ok(state_root_prehashed(accounts))
898            })?;
899
900            let static_file_provider = self.db.factory.static_file_provider();
901            let mut writer =
902                static_file_provider.latest_writer(StaticFileSegment::Headers).unwrap();
903            let mut last_header = last_block.clone_sealed_header();
904            last_header.set_state_root(root);
905
906            let hash = last_header.hash_slow();
907            writer.prune_headers(1).unwrap();
908            writer.commit().unwrap();
909            writer.append_header(&last_header, &hash).unwrap();
910            writer.commit().unwrap();
911
912            Ok(blocks)
913        }
914
915        fn validate_execution(
916            &self,
917            _input: ExecInput,
918            _output: Option<ExecOutput>,
919        ) -> Result<(), TestRunnerError> {
920            // The execution is validated within the stage
921            Ok(())
922        }
923    }
924
925    impl UnwindStageTestRunner for MerkleTestRunner {
926        fn validate_unwind(&self, _input: UnwindInput) -> Result<(), TestRunnerError> {
927            // The unwind is validated within the stage
928            Ok(())
929        }
930
931        fn before_unwind(&self, input: UnwindInput) -> Result<(), TestRunnerError> {
932            let target_block = input.unwind_to + 1;
933
934            self.db
935                .commit(|tx| {
936                    let mut storage_changesets_cursor =
937                        tx.cursor_dup_read::<tables::StorageChangeSets>().unwrap();
938                    let mut storage_cursor =
939                        tx.cursor_dup_write::<tables::HashedStorages>().unwrap();
940
941                    let mut tree: BTreeMap<B256, BTreeMap<B256, U256>> = BTreeMap::new();
942
943                    let mut rev_changeset_walker =
944                        storage_changesets_cursor.walk_back(None).unwrap();
945                    while let Some((bn_address, entry)) =
946                        rev_changeset_walker.next().transpose().unwrap()
947                    {
948                        if bn_address.block_number() < target_block {
949                            break
950                        }
951
952                        tree.entry(keccak256(bn_address.address()))
953                            .or_default()
954                            .insert(keccak256(entry.key), entry.value);
955                    }
956                    for (hashed_address, storage) in tree {
957                        for (hashed_slot, value) in storage {
958                            let storage_entry = storage_cursor
959                                .seek_by_key_subkey(hashed_address, hashed_slot)
960                                .unwrap();
961                            if storage_entry.is_some_and(|v| v.key == hashed_slot) {
962                                storage_cursor.delete_current().unwrap();
963                            }
964
965                            if !value.is_zero() {
966                                let storage_entry = StorageEntry { key: hashed_slot, value };
967                                storage_cursor.upsert(hashed_address, &storage_entry).unwrap();
968                            }
969                        }
970                    }
971
972                    let mut changeset_cursor =
973                        tx.cursor_dup_write::<tables::AccountChangeSets>().unwrap();
974                    let mut rev_changeset_walker = changeset_cursor.walk_back(None).unwrap();
975
976                    while let Some((block_number, account_before_tx)) =
977                        rev_changeset_walker.next().transpose().unwrap()
978                    {
979                        if block_number < target_block {
980                            break
981                        }
982
983                        if let Some(acc) = account_before_tx.info {
984                            tx.put::<tables::HashedAccounts>(
985                                keccak256(account_before_tx.address),
986                                acc,
987                            )
988                            .unwrap();
989                        } else {
990                            tx.delete::<tables::HashedAccounts>(
991                                keccak256(account_before_tx.address),
992                                None,
993                            )
994                            .unwrap();
995                        }
996                    }
997                    Ok(())
998                })
999                .unwrap();
1000            Ok(())
1001        }
1002    }
1003
1004    #[reth_concurrency::test]
1005    fn a_paused_rebuild_resumes_from_the_checkpoint_it_saved() {
1006        let db = TestStageDB::default();
1007        seed_accounts(&db);
1008        let target = insert_rebuild_chain(&db);
1009        let checkpoint = pause_rebuild(&db);
1010        db.commit_with_provider(|provider| {
1011            MerkleStage::default_execution()
1012                .save_resumable_execution_checkpoint(provider, &checkpoint, target.hash())
1013                .unwrap();
1014            Ok(())
1015        })
1016        .unwrap();
1017
1018        // A resumed rebuild keeps the entities its checkpoint already counted.
1019        assert!(rebuild(&db) > RESUMED);
1020    }
1021
1022    #[reth_concurrency::test]
1023    fn a_paused_rebuild_toward_another_block_at_the_same_height_rebuilds() {
1024        let mut rng = generators::rng();
1025        let db = TestStageDB::default();
1026        let accounts = seed_accounts(&db);
1027        let replaced = random_header(&mut rng, REBUILD_TARGET, None);
1028        let checkpoint = pause_rebuild(&db);
1029        db.commit_with_provider(|provider| {
1030            MerkleStage::default_execution()
1031                .save_resumable_execution_checkpoint(provider, &checkpoint, replaced.hash())
1032                .unwrap();
1033            Ok(())
1034        })
1035        .unwrap();
1036
1037        // The block now at that height changes an account the paused rebuild already walked, to a
1038        // balance above any seeded one.
1039        let first = *accounts.iter().min_by_key(|address| keccak256(address)).unwrap();
1040        assert!(keccak256(first) <= checkpoint.last_account_key);
1041        let changed = Account { balance: U256::MAX, ..Default::default() };
1042        db.insert_accounts_and_storages([(first, (changed, []))]).unwrap();
1043        insert_rebuild_chain(&db);
1044
1045        assert_eq!(rebuild(&db), accounts.len() as u64);
1046    }
1047
1048    #[reth_concurrency::test]
1049    fn a_checkpoint_not_saved_toward_its_target_rebuilds() {
1050        let db = TestStageDB::default();
1051        let accounts = seed_accounts(&db);
1052        let target = insert_rebuild_chain(&db);
1053        let stage = MerkleStage::default_execution();
1054        let checkpoint = pause_rebuild(&db);
1055
1056        // A node from before the binding saves only the checkpoint.
1057        db.commit_with_provider(|provider| {
1058            let mut buf = Vec::new();
1059            checkpoint.to_compact(&mut buf);
1060            provider.save_stage_checkpoint_progress(StageId::MerkleExecute, buf).unwrap();
1061            Ok(())
1062        })
1063        .unwrap();
1064        assert_eq!(rebuild(&db), accounts.len() as u64);
1065
1066        // One also replaces a bound checkpoint with its own toward another block at the same
1067        // height, keeping the binding of the one it replaced.
1068        let checkpoint = pause_rebuild(&db);
1069        db.commit_with_provider(|provider| {
1070            stage
1071                .save_resumable_execution_checkpoint(provider, &checkpoint, target.hash())
1072                .unwrap();
1073            Ok(())
1074        })
1075        .unwrap();
1076        let first = *accounts.iter().min_by_key(|address| keccak256(address)).unwrap();
1077        let (_, original) = db
1078            .table::<tables::HashedAccounts>()
1079            .unwrap()
1080            .into_iter()
1081            .find(|(key, _)| *key == keccak256(first))
1082            .unwrap();
1083        let changed = Account { balance: U256::MAX, ..Default::default() };
1084        db.insert_accounts_and_storages([(first, (changed, []))]).unwrap();
1085        let replaced = pause_rebuild(&db);
1086        assert!(keccak256(first) <= replaced.last_account_key);
1087        db.commit_with_provider(|provider| {
1088            let mut buf = Vec::new();
1089            replaced.to_compact(&mut buf);
1090            provider.save_stage_checkpoint_progress(StageId::MerkleExecute, buf).unwrap();
1091            Ok(())
1092        })
1093        .unwrap();
1094        db.insert_accounts_and_storages([(first, (original, []))]).unwrap();
1095        assert_eq!(rebuild(&db), accounts.len() as u64);
1096
1097        // The public writer does not bind its checkpoint either.
1098        let checkpoint = pause_rebuild(&db);
1099        db.commit_with_provider(|provider| {
1100            stage
1101                .save_resumable_execution_checkpoint(provider, &checkpoint, target.hash())
1102                .unwrap();
1103            stage.save_execution_checkpoint(provider, Some(checkpoint)).unwrap();
1104            Ok(())
1105        })
1106        .unwrap();
1107        assert_eq!(rebuild(&db), accounts.len() as u64);
1108    }
1109}