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