Skip to main content

reth_provider/
changeset_walker.rs

1//! Account/storage changeset iteration support for walking through historical state changes in
2//! static files.
3
4use crate::ProviderResult;
5use alloy_primitives::BlockNumber;
6use reth_db::models::AccountBeforeTx;
7use reth_db_api::models::BlockNumberAddress;
8use reth_primitives_traits::StorageEntry;
9use reth_storage_api::{ChangeSetReader, StorageChangeSetReader};
10use std::{
11    ops::{Bound, RangeBounds, RangeInclusive},
12    vec::IntoIter,
13};
14
15/// Iterator that walks account changesets from static files in a block range.
16///
17/// This iterator fetches changesets block by block to avoid loading everything into memory.
18#[derive(Debug)]
19pub struct StaticFileAccountChangesetWalker<P> {
20    /// Static file provider.
21    provider: P,
22    /// Blocks still to be fetched.
23    blocks: RangeInclusive<BlockNumber>,
24    /// Block number attached to the buffered account changesets.
25    current_block: BlockNumber,
26    /// Remaining changesets for the current block.
27    current_changesets: IntoIter<AccountBeforeTx>,
28}
29
30impl<P> StaticFileAccountChangesetWalker<P> {
31    /// Create a new static file changeset walker.
32    ///
33    /// Accepts any range type that implements `RangeBounds<BlockNumber>`, including:
34    /// - `Range<BlockNumber>` (e.g., `0..100`)
35    /// - `RangeInclusive<BlockNumber>` (e.g., `0..=99`)
36    /// - `RangeFrom<BlockNumber>` (e.g., `0..`) - iterates until exhausted
37    ///
38    /// If there is no start bound, 0 is used as the start block.
39    pub fn new(provider: P, range: impl RangeBounds<BlockNumber>) -> Self {
40        Self {
41            provider,
42            blocks: changeset_block_range(range, BlockNumber::MAX),
43            current_block: 0,
44            current_changesets: Default::default(),
45        }
46    }
47}
48
49impl<P> Iterator for StaticFileAccountChangesetWalker<P>
50where
51    P: ChangeSetReader,
52{
53    type Item = ProviderResult<(BlockNumber, AccountBeforeTx)>;
54
55    fn next(&mut self) -> Option<Self::Item> {
56        loop {
57            if let Some(changeset) = self.current_changesets.next() {
58                return Some(Ok((self.current_block, changeset)))
59            }
60            self.current_block = self.blocks.next()?;
61            match self.provider.account_block_changeset(self.current_block) {
62                Ok(changesets) => self.current_changesets = changesets.into_iter(),
63                Err(err) => return Some(Err(err)),
64            }
65        }
66    }
67}
68
69/// Iterator that walks storage changesets from static files in a block range.
70#[derive(Debug)]
71pub struct StaticFileStorageChangesetWalker<P> {
72    /// Static file provider.
73    provider: P,
74    /// Blocks still to be fetched.
75    blocks: RangeInclusive<BlockNumber>,
76    /// Remaining changesets for the current block.
77    current_changesets: IntoIter<(BlockNumberAddress, StorageEntry)>,
78}
79
80impl<P> StaticFileStorageChangesetWalker<P> {
81    /// Create a new static file storage changeset walker.
82    pub fn new(provider: P, range: impl RangeBounds<BlockNumber>) -> Self {
83        Self {
84            provider,
85            blocks: changeset_block_range(range, BlockNumber::MAX),
86            current_changesets: Default::default(),
87        }
88    }
89}
90
91impl<P> Iterator for StaticFileStorageChangesetWalker<P>
92where
93    P: StorageChangeSetReader,
94{
95    type Item = ProviderResult<(BlockNumberAddress, StorageEntry)>;
96
97    fn next(&mut self) -> Option<Self::Item> {
98        loop {
99            if let Some(changeset) = self.current_changesets.next() {
100                return Some(Ok(changeset))
101            }
102            match self.provider.storage_changeset(self.blocks.next()?) {
103                Ok(changesets) => self.current_changesets = changesets.into_iter(),
104                Err(err) => return Some(Err(err)),
105            }
106        }
107    }
108}
109
110/// Converts changeset bounds to an inclusive block range capped at the available tip.
111pub(crate) fn changeset_block_range(
112    range: impl RangeBounds<BlockNumber>,
113    tip: BlockNumber,
114) -> RangeInclusive<BlockNumber> {
115    let start = match range.start_bound() {
116        Bound::Included(&n) => n,
117        Bound::Excluded(&BlockNumber::MAX) => return RangeInclusive::new(1, 0),
118        Bound::Excluded(&n) => n + 1,
119        Bound::Unbounded => 0,
120    };
121    let end = match range.end_bound() {
122        Bound::Included(&n) => n.min(tip),
123        Bound::Excluded(&0) => return RangeInclusive::new(1, 0),
124        Bound::Excluded(&n) => (n - 1).min(tip),
125        Bound::Unbounded => tip,
126    };
127    start..=end
128}