Skip to main content

miden_node_store/accounts/
mod.rs

1//! Historical tracking for `AccountTree` via mutation overlays
2
3use std::collections::{BTreeMap, HashMap};
4
5use miden_crypto::merkle::smt::RocksDbStorage;
6use miden_node_tracing::instrument;
7use miden_protocol::account::{AccountId, AccountIdPrefix};
8use miden_protocol::block::BlockNumber;
9use miden_protocol::block::account_tree::{AccountMutationSet, AccountTree, AccountWitness};
10use miden_protocol::crypto::merkle::smt::{
11    LargeSmt,
12    LeafIndex,
13    MemoryStorage,
14    NodeMutation,
15    SMT_DEPTH,
16    SmtLeaf,
17    SmtStorage,
18    SmtStorageReader,
19};
20use miden_protocol::crypto::merkle::{
21    EmptySubtreeRoots,
22    MerkleError,
23    MerklePath,
24    NodeIndex,
25    SparseMerklePath,
26};
27use miden_protocol::errors::AccountTreeError;
28use miden_protocol::{EMPTY_WORD, Word};
29
30#[cfg(test)]
31mod tests;
32
33/// Convenience for an in-memory-only account tree.
34pub type InMemoryAccountTree = AccountTree<LargeSmt<MemoryStorage>>;
35
36/// Convenience for a persistent account tree.
37pub type PersistentAccountTree = AccountTree<LargeSmt<RocksDbStorage>>;
38
39// HISTORICAL ERROR TYPES
40// ================================================================================================
41
42#[expect(missing_docs)]
43#[derive(thiserror::Error, Debug)]
44pub enum HistoricalError {
45    #[error(transparent)]
46    MerkleError(#[from] MerkleError),
47    #[error(transparent)]
48    AccountTreeError(#[from] AccountTreeError),
49}
50
51// HISTORICAL SELECTOR ENUM
52// ================================================================================================
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55enum HistoricalSelector {
56    /// The requested block is in the future (later than current block).
57    Future,
58    /// The requested block is available in history.
59    At(BlockNumber),
60    /// The requested block is the current/latest block.
61    Latest,
62    /// The requested block is too old and has been pruned from history.
63    TooAncient,
64}
65
66// HISTORICAL OVERLAY
67// ================================================================================================
68
69/// Captures reversion state for historical queries at a specific block.
70#[derive(Debug, Clone)]
71struct HistoricalOverlay {
72    block_number: BlockNumber,
73    root: Word,
74    node_mutations: HashMap<NodeIndex, Word>,
75    account_updates: HashMap<LeafIndex<SMT_DEPTH>, (Word, Word)>,
76}
77
78impl HistoricalOverlay {
79    fn new(block_number: BlockNumber, rev_set: AccountMutationSet) -> Self {
80        let root = rev_set.as_mutation_set().root();
81        let mut_set = rev_set.into_mutation_set();
82
83        let node_mutations = mut_set
84            .node_mutations()
85            .iter()
86            .map(|(node_index, mutation)| {
87                match mutation {
88                    NodeMutation::Addition(inner_node) => (*node_index, inner_node.hash()),
89                    NodeMutation::Removal => {
90                        // Store the actual empty subtree root for this depth depth() is 1-indexed
91                        // from leaf, so we use it directly for EmptySubtreeRoots
92                        let empty_root = *EmptySubtreeRoots::entry(SMT_DEPTH, node_index.depth());
93                        (*node_index, empty_root)
94                    },
95                }
96            })
97            .collect::<HashMap<_, _>>();
98
99        let account_updates = mut_set
100            .new_pairs()
101            .iter()
102            .map(|(&k, &v)| (LeafIndex::from(k), (k, v)))
103            .collect::<HashMap<_, _>>();
104
105        Self {
106            block_number,
107            root,
108            node_mutations,
109            account_updates,
110        }
111    }
112}
113
114// ACCOUNT TREE WITH HISTORY
115// ================================================================================================
116
117/// Wraps `AccountTree` with historical query support via reversion overlays.
118///
119/// This structure maintains a sliding window of historical account states by storing
120/// reversion data (mutations that undo changes). Historical witnesses are reconstructed
121/// by starting from the latest state and applying reversion overlays backwards in time.
122#[derive(Debug)]
123pub struct AccountTreeWithHistory<S: SmtStorageReader> {
124    /// The current block number (latest state).
125    block_number: BlockNumber,
126    /// The latest account tree state.
127    latest: AccountTree<LargeSmt<S>>,
128    /// Historical overlays indexed by block number, storing reversion data.
129    overlays: BTreeMap<BlockNumber, HistoricalOverlay>,
130}
131
132impl<S: SmtStorageReader> AccountTreeWithHistory<S> {
133    /// Maximum number of historical blocks to maintain.
134    pub const MAX_HISTORY: usize = 50;
135
136    // CONSTRUCTORS
137    // --------------------------------------------------------------------------------------------
138
139    /// Creates a new historical tree starting at the given block number.
140    pub fn new(account_tree: AccountTree<LargeSmt<S>>, block_number: BlockNumber) -> Self {
141        Self {
142            block_number,
143            latest: account_tree,
144            overlays: BTreeMap::new(),
145        }
146    }
147
148    /// Removes oldest overlays when exceeding the maximum history depth.
149    fn drain_excess(overlays: &mut BTreeMap<BlockNumber, HistoricalOverlay>) {
150        while overlays.len() > Self::MAX_HISTORY {
151            overlays.pop_first();
152        }
153    }
154
155    // PUBLIC ACCESSORS
156    // --------------------------------------------------------------------------------------------
157
158    /// Returns the latest block number.
159    pub fn block_number_latest(&self) -> BlockNumber {
160        self.block_number
161    }
162
163    /// Returns the root hash of the latest state.
164    pub fn root_latest(&self) -> Word {
165        self.latest.root()
166    }
167
168    /// Returns the root hash at a specific historical block.
169    ///
170    /// Returns `None` if the block is in the future or too old (pruned).
171    pub fn root_at(&self, block_number: BlockNumber) -> Option<Word> {
172        match self.historical_selector(block_number) {
173            HistoricalSelector::Latest => Some(self.latest.root()),
174            HistoricalSelector::At(block_number) => {
175                let overlay = self.overlays.get(&block_number)?;
176                debug_assert_eq!(overlay.block_number, block_number);
177                Some(overlay.root)
178            },
179            HistoricalSelector::Future | HistoricalSelector::TooAncient => None,
180        }
181    }
182
183    /// Returns the number of accounts in the latest state.
184    pub fn num_accounts_latest(&self) -> usize {
185        self.latest.num_accounts()
186    }
187
188    /// Returns the number of historical blocks currently stored.
189    pub fn history_len(&self) -> usize {
190        self.overlays.len()
191    }
192
193    /// Opens an account at the latest block, returning its witness.
194    #[instrument]
195    pub fn open_latest(&self, account_id: AccountId) -> AccountWitness {
196        self.latest.open(account_id)
197    }
198
199    /// Opens an account at a historical block, returning its witness.
200    ///
201    /// This method reconstructs the account witness at the given historical block by:
202    /// 1. Starting with the latest account state
203    /// 2. Applying reversion mutations from the overlays to walk back in time
204    /// 3. Reconstructing the Merkle path with the historical node values
205    ///
206    /// Returns `None` if the block is in the future or too old (pruned).
207    #[instrument]
208    pub fn open_at(
209        &self,
210        account_id: AccountId,
211        block_number: BlockNumber,
212    ) -> Option<AccountWitness> {
213        match self.historical_selector(block_number) {
214            HistoricalSelector::Latest => Some(self.latest.open(account_id)),
215            HistoricalSelector::At(block_number) => {
216                // Ensure overlay exists before reconstruction
217                self.overlays.get(&block_number)?;
218                Self::reconstruct_historical_witness(self, account_id, block_number)
219            },
220            HistoricalSelector::Future | HistoricalSelector::TooAncient => None,
221        }
222    }
223
224    /// Gets the account state commitment at the latest block.
225    pub fn get_latest_commitment(&self, account_id: AccountId) -> Word {
226        self.latest.get(account_id)
227    }
228
229    /// Checks if the tree contains an account with the given prefix.
230    pub fn contains_account_id_prefix_in_latest(&self, prefix: AccountIdPrefix) -> bool {
231        self.latest.contains_account_id_prefix(prefix)
232    }
233
234    // PRIVATE HELPERS - HISTORICAL RECONSTRUCTION
235    // --------------------------------------------------------------------------------------------
236
237    /// Determines the historical state selector of a requested block number.
238    fn historical_selector(&self, desired_block_number: BlockNumber) -> HistoricalSelector {
239        if desired_block_number == self.block_number {
240            return HistoricalSelector::Latest;
241        }
242
243        // Check if block is in the future
244        if self.block_number.checked_sub(desired_block_number.as_u32()).is_none() {
245            return HistoricalSelector::Future;
246        }
247
248        // Check if block exists in overlays
249        if !self.overlays.contains_key(&desired_block_number) {
250            return HistoricalSelector::TooAncient;
251        }
252
253        HistoricalSelector::At(desired_block_number)
254    }
255
256    /// Reconstructs a historical account witness by applying reversion overlays.
257    #[instrument]
258    fn reconstruct_historical_witness(
259        &self,
260        account_id: AccountId,
261        block_target: BlockNumber,
262    ) -> Option<AccountWitness> {
263        // Start with the latest witness
264        let latest_witness = self.latest.open(account_id);
265        let (latest_path, leaf) = latest_witness.into_proof().into_parts();
266        let path_nodes = Self::initialize_path_nodes(&latest_path);
267
268        let leaf_index = NodeIndex::from(leaf.index());
269
270        // Apply reversion overlays to reconstruct historical state. We reverse the overlay
271        // iteration (newest to oldest) to walk backwards in time from the latest state to the
272        // target block.
273        let (path, leaf) = Self::apply_reversion_overlays(
274            self.overlays.range(block_target..).rev().map(|(_, overlay)| overlay),
275            path_nodes,
276            leaf_index,
277            leaf,
278        )?;
279
280        // Extract commitment from leaf
281        let commitment = match leaf {
282            SmtLeaf::Empty(_) => EMPTY_WORD,
283            SmtLeaf::Single((_, value)) => value,
284            SmtLeaf::Multiple(_) => unreachable!("AccountTree uses prefix-free IDs"),
285        };
286
287        AccountWitness::new(account_id, commitment, path).ok()
288    }
289
290    /// Initializes the path nodes array from the latest state.
291    ///
292    /// Converts the sparse path to a dense path and reverses it for indexing by depth from leaf.
293    fn initialize_path_nodes(path: &SparseMerklePath) -> [Word; SMT_DEPTH as usize] {
294        let mut path_nodes: [Word; SMT_DEPTH as usize] = MerklePath::from(path.clone())
295            .to_vec()
296            .try_into()
297            .expect("MerklePath should have exactly SMT_DEPTH nodes");
298        path_nodes.reverse();
299        path_nodes
300    }
301
302    /// Applies reversion overlays to reconstruct the historical state.
303    ///
304    /// Iterates through overlays from newest to oldest (walking backwards in time),
305    /// updating both the path nodes and the leaf value based on reversion mutations.
306    #[instrument]
307    fn apply_reversion_overlays<'a>(
308        overlays: impl IntoIterator<Item = &'a HistoricalOverlay>,
309        mut path_nodes: [Word; SMT_DEPTH as usize],
310        leaf_index: NodeIndex,
311        mut leaf: SmtLeaf,
312    ) -> Option<(SparseMerklePath, SmtLeaf)> {
313        // Iterate through overlays
314        for overlay in overlays {
315            // Update path sibling nodes that changed in this overlay
316            for sibling in leaf_index.proof_indices() {
317                let height = sibling
318                    .depth()
319                    .checked_sub(1) // -1: Convert from 1-indexed to 0-indexed
320                    .expect("proof_indices should not include root")
321                    as usize;
322
323                // Apply reversion mutation if this node was modified. It's sound since
324                // `proof_indices()`` returns siblings on the path from leaf to root, hence the
325                // height is always less than `SMT_DEPTH`, the leaf and root are not included.
326                if let Some(hash) = overlay.node_mutations.get(&sibling) {
327                    path_nodes[height] = *hash;
328                }
329            }
330
331            // Update leaf if it was modified in this overlay
332            if let Some(&(key, value)) = overlay.account_updates.get(&leaf.index()) {
333                leaf = if value == EMPTY_WORD {
334                    SmtLeaf::new_empty(leaf.index())
335                } else {
336                    SmtLeaf::new_single(key, value)
337                };
338            }
339        }
340
341        // Build the Merkle path directly from the reconstructed nodes No need for build_dense_path
342        // since all nodes have actual values (not sentinels)
343        let dense: Vec<Word> = path_nodes.iter().rev().copied().collect();
344        let path = MerklePath::new(dense);
345        let path = SparseMerklePath::try_from(path).ok()?;
346        Some((path, leaf))
347    }
348}
349
350impl<S: SmtStorage> AccountTreeWithHistory<S> {
351    // PUBLIC MUTATORS
352    // --------------------------------------------------------------------------------------------
353
354    /// Computes and applies mutations in one operation.
355    ///
356    /// This is a convenience method primarily for testing.
357    pub fn compute_and_apply_mutations(
358        &mut self,
359        account_commitments: impl IntoIterator<Item = (AccountId, Word)>,
360    ) -> Result<(), HistoricalError> {
361        let mutations = self.compute_mutations(account_commitments)?;
362        self.apply_mutations(mutations)
363    }
364
365    /// Computes mutations relative to the latest state.
366    pub fn compute_mutations(
367        &self,
368        account_commitments: impl IntoIterator<Item = (AccountId, Word)>,
369    ) -> Result<AccountMutationSet, HistoricalError> {
370        Ok(self.latest.compute_mutations(account_commitments)?)
371    }
372
373    /// Applies mutations and advances to the next block.
374    ///
375    /// This method:
376    /// 1. Applies the mutations to the latest tree, getting back reversion data
377    /// 2. Stores the reversion data as a historical overlay
378    /// 3. Advances the block number
379    /// 4. Prunes old overlays if exceeding `MAX_HISTORY`
380    #[instrument]
381    pub fn apply_mutations(
382        &mut self,
383        mutations: AccountMutationSet,
384    ) -> Result<(), HistoricalError> {
385        // Apply mutations and get reversion data
386        let rev = self.latest.apply_mutations_with_reversion(mutations)?;
387
388        // Store reversion data for current block before advancing
389        let block_num = self.block_number;
390        let overlay = HistoricalOverlay::new(block_num, rev);
391        self.overlays.insert(block_num, overlay);
392
393        // Advance to next block
394        self.block_number = block_num.child();
395
396        // Prune old history if needed
397        Self::drain_excess(&mut self.overlays);
398
399        Ok(())
400    }
401
402    /// Returns a read-only snapshot of this tree backed by a reader view of the storage.
403    pub fn reader(&self) -> AccountTreeWithHistory<S::Reader> {
404        let latest = self.latest.reader().expect("snapshot creation should not fail");
405        AccountTreeWithHistory {
406            block_number: self.block_number,
407            latest,
408            overlays: self.overlays.clone(),
409        }
410    }
411}