miden_node_store/accounts/
mod.rs1use 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
35pub type InMemoryAccountTree = AccountTree<LargeSmt<MemoryStorage>>;
37
38pub type PersistentAccountTree = AccountTree<LargeSmt<RocksDbStorage>>;
40
41#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum HistoricalSelector {
58 Future,
60 At(BlockNumber),
62 Latest,
64 TooAncient,
66}
67
68#[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 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#[derive(Debug)]
125pub struct AccountTreeWithHistory<S: SmtStorageReader> {
126 block_number: BlockNumber,
128 latest: AccountTree<LargeSmt<S>>,
130 overlays: BTreeMap<BlockNumber, HistoricalOverlay>,
132}
133
134impl<S: SmtStorageReader> AccountTreeWithHistory<S> {
135 pub const MAX_HISTORY: usize = 50;
137
138 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 fn drain_excess(overlays: &mut BTreeMap<BlockNumber, HistoricalOverlay>) {
152 while overlays.len() > Self::MAX_HISTORY {
153 overlays.pop_first();
154 }
155 }
156
157 pub fn block_number_latest(&self) -> BlockNumber {
162 self.block_number
163 }
164
165 pub fn root_latest(&self) -> Word {
167 self.latest.root()
168 }
169
170 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 pub fn num_accounts_latest(&self) -> usize {
187 self.latest.num_accounts()
188 }
189
190 pub fn history_len(&self) -> usize {
192 self.overlays.len()
193 }
194
195 #[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 #[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 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 pub fn get_latest_commitment(&self, account_id: AccountId) -> Word {
232 self.latest.get(account_id)
233 }
234
235 pub fn contains_account_id_prefix_in_latest(&self, prefix: AccountIdPrefix) -> bool {
237 self.latest.contains_account_id_prefix(prefix)
238 }
239
240 fn historical_selector(&self, desired_block_number: BlockNumber) -> HistoricalSelector {
245 if desired_block_number == self.block_number {
246 return HistoricalSelector::Latest;
247 }
248
249 if self.block_number.checked_sub(desired_block_number.as_u32()).is_none() {
251 return HistoricalSelector::Future;
252 }
253
254 if !self.overlays.contains_key(&desired_block_number) {
256 return HistoricalSelector::TooAncient;
257 }
258
259 HistoricalSelector::At(desired_block_number)
260 }
261
262 #[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 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 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 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 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 #[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 for overlay in overlays {
325 for sibling in leaf_index.proof_indices() {
327 let height = sibling
328 .depth()
329 .checked_sub(1) .expect("proof_indices should not include root")
331 as usize;
332
333 if let Some(hash) = overlay.node_mutations.get(&sibling) {
337 path_nodes[height] = *hash;
338 }
339 }
340
341 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 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 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 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 #[miden_instrument(
391 target = COMPONENT,
392 )]
393 pub fn apply_mutations(
394 &mut self,
395 mutations: AccountMutationSet,
396 ) -> Result<(), HistoricalError> {
397 let rev = self.latest.apply_mutations_with_reversion(mutations)?;
399
400 let block_num = self.block_number;
402 let overlay = HistoricalOverlay::new(block_num, rev);
403 self.overlays.insert(block_num, overlay);
404
405 self.block_number = block_num.child();
407
408 Self::drain_excess(&mut self.overlays);
410
411 Ok(())
412 }
413
414 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}