miden_node_store/accounts/
mod.rs1use 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
33pub type InMemoryAccountTree = AccountTree<LargeSmt<MemoryStorage>>;
35
36pub type PersistentAccountTree = AccountTree<LargeSmt<RocksDbStorage>>;
38
39#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55enum HistoricalSelector {
56 Future,
58 At(BlockNumber),
60 Latest,
62 TooAncient,
64}
65
66#[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 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#[derive(Debug)]
123pub struct AccountTreeWithHistory<S: SmtStorageReader> {
124 block_number: BlockNumber,
126 latest: AccountTree<LargeSmt<S>>,
128 overlays: BTreeMap<BlockNumber, HistoricalOverlay>,
130}
131
132impl<S: SmtStorageReader> AccountTreeWithHistory<S> {
133 pub const MAX_HISTORY: usize = 50;
135
136 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 fn drain_excess(overlays: &mut BTreeMap<BlockNumber, HistoricalOverlay>) {
150 while overlays.len() > Self::MAX_HISTORY {
151 overlays.pop_first();
152 }
153 }
154
155 pub fn block_number_latest(&self) -> BlockNumber {
160 self.block_number
161 }
162
163 pub fn root_latest(&self) -> Word {
165 self.latest.root()
166 }
167
168 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 pub fn num_accounts_latest(&self) -> usize {
185 self.latest.num_accounts()
186 }
187
188 pub fn history_len(&self) -> usize {
190 self.overlays.len()
191 }
192
193 #[instrument]
195 pub fn open_latest(&self, account_id: AccountId) -> AccountWitness {
196 self.latest.open(account_id)
197 }
198
199 #[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 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 pub fn get_latest_commitment(&self, account_id: AccountId) -> Word {
226 self.latest.get(account_id)
227 }
228
229 pub fn contains_account_id_prefix_in_latest(&self, prefix: AccountIdPrefix) -> bool {
231 self.latest.contains_account_id_prefix(prefix)
232 }
233
234 fn historical_selector(&self, desired_block_number: BlockNumber) -> HistoricalSelector {
239 if desired_block_number == self.block_number {
240 return HistoricalSelector::Latest;
241 }
242
243 if self.block_number.checked_sub(desired_block_number.as_u32()).is_none() {
245 return HistoricalSelector::Future;
246 }
247
248 if !self.overlays.contains_key(&desired_block_number) {
250 return HistoricalSelector::TooAncient;
251 }
252
253 HistoricalSelector::At(desired_block_number)
254 }
255
256 #[instrument]
258 fn reconstruct_historical_witness(
259 &self,
260 account_id: AccountId,
261 block_target: BlockNumber,
262 ) -> Option<AccountWitness> {
263 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 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 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 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 #[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 for overlay in overlays {
315 for sibling in leaf_index.proof_indices() {
317 let height = sibling
318 .depth()
319 .checked_sub(1) .expect("proof_indices should not include root")
321 as usize;
322
323 if let Some(hash) = overlay.node_mutations.get(&sibling) {
327 path_nodes[height] = *hash;
328 }
329 }
330
331 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 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 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 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 #[instrument]
381 pub fn apply_mutations(
382 &mut self,
383 mutations: AccountMutationSet,
384 ) -> Result<(), HistoricalError> {
385 let rev = self.latest.apply_mutations_with_reversion(mutations)?;
387
388 let block_num = self.block_number;
390 let overlay = HistoricalOverlay::new(block_num, rev);
391 self.overlays.insert(block_num, overlay);
392
393 self.block_number = block_num.child();
395
396 Self::drain_excess(&mut self.overlays);
398
399 Ok(())
400 }
401
402 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}