miden_core/mast/mod.rs
1//! MAST forest: a collection of procedures represented as Merkle trees.
2//!
3//! # Deserializing from untrusted sources
4//!
5//! When loading a `MastForest` from bytes you don't fully trust (network, user upload, etc.),
6//! use [`UntrustedMastForest`] instead of calling `MastForest::read_from_bytes` directly:
7//!
8//! ```ignore
9//! use miden_core::mast::UntrustedMastForest;
10//!
11//! let forest = UntrustedMastForest::read_from_bytes(&bytes)?
12//! .validate()?;
13//! ```
14//!
15//! For maximum protection against denial-of-service attacks from malicious input, use
16//! [`UntrustedMastForest::read_from_bytes_with_budget`] which limits memory consumption:
17//!
18//! ```ignore
19//! use miden_core::mast::UntrustedMastForest;
20//!
21//! // Budget limits pre-allocation sizes and total bytes consumed
22//! let forest = UntrustedMastForest::read_from_bytes_with_budget(&bytes, bytes.len())?
23//! .validate()?;
24//! ```
25//!
26//! This recomputes all node hashes and checks structural invariants before returning a usable
27//! `MastForest`. Direct deserialization via `MastForest::read_from_bytes` trusts the serialized
28//! hashes and should only be used for data from trusted sources (e.g. compiled locally).
29
30use alloc::{
31 collections::{BTreeMap, BTreeSet},
32 string::String,
33 sync::Arc,
34 vec::Vec,
35};
36use core::{
37 fmt,
38 ops::{Index, IndexMut},
39};
40
41use miden_utils_sync::OnceLockCompat;
42#[cfg(feature = "serde")]
43use serde::{Deserialize, Serialize};
44
45mod node;
46#[cfg(any(test, feature = "arbitrary"))]
47pub use node::arbitrary;
48pub use node::{
49 BasicBlockNode, BasicBlockNodeBuilder, CallNode, CallNodeBuilder, DecoratedOpLink,
50 DecoratorOpLinkIterator, DecoratorStore, DynNode, DynNodeBuilder, ExternalNode,
51 ExternalNodeBuilder, JoinNode, JoinNodeBuilder, LoopNode, LoopNodeBuilder,
52 MastForestContributor, MastNode, MastNodeBuilder, MastNodeExt, OP_BATCH_SIZE, OP_GROUP_SIZE,
53 OpBatch, OperationOrDecorator, SplitNode, SplitNodeBuilder,
54};
55
56use crate::{
57 Felt, LexicographicWord, Word,
58 advice::AdviceMap,
59 field::PrimeField64,
60 operations::{AssemblyOp, Decorator},
61 serde::{
62 BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
63 SliceReader,
64 },
65 utils::{Idx, IndexVec, hash_string_to_word},
66};
67
68mod debuginfo;
69pub use debuginfo::{
70 AsmOpIndexError, DebugInfo, DecoratedLinks, DecoratedLinksIter, DecoratorIndexError,
71 NodeToDecoratorIds, OpToAsmOpId, OpToDecoratorIds,
72};
73
74mod serialization;
75
76mod merger;
77pub(crate) use merger::MastForestMerger;
78pub use merger::MastForestRootMap;
79
80mod multi_forest_node_iterator;
81pub(crate) use multi_forest_node_iterator::*;
82
83mod node_fingerprint;
84pub use node_fingerprint::{DecoratorFingerprint, MastNodeFingerprint};
85
86mod node_builder_utils;
87pub use node_builder_utils::build_node_with_remapped_ids;
88
89#[cfg(test)]
90mod tests;
91
92// MAST FOREST
93// ================================================================================================
94
95/// Represents one or more procedures, represented as a collection of [`MastNode`]s.
96///
97/// A [`MastForest`] does not have an entrypoint, and hence is not executable. A
98/// [`crate::program::Program`] can be built from a [`MastForest`] to specify an entrypoint.
99#[derive(Clone, Debug, Default)]
100pub struct MastForest {
101 /// All of the nodes local to the trees comprising the MAST forest.
102 nodes: IndexVec<MastNodeId, MastNode>,
103
104 /// Roots of procedures defined within this MAST forest.
105 roots: Vec<MastNodeId>,
106
107 /// Advice map to be loaded into the VM prior to executing procedures from this MAST forest.
108 advice_map: AdviceMap,
109
110 /// Debug information including decorators and error codes.
111 /// Always present (as per issue #1821), but can be empty for stripped builds.
112 debug_info: DebugInfo,
113
114 /// Cached commitment to this MAST forest (commitment to all roots).
115 /// This is computed lazily on first access and invalidated on any mutation.
116 commitment_cache: OnceLockCompat<Word>,
117}
118
119// ------------------------------------------------------------------------------------------------
120/// Constructors
121impl MastForest {
122 /// Creates a new empty [`MastForest`].
123 pub fn new() -> Self {
124 Self {
125 nodes: IndexVec::new(),
126 roots: Vec::new(),
127 advice_map: AdviceMap::default(),
128 debug_info: DebugInfo::new(),
129 commitment_cache: OnceLockCompat::new(),
130 }
131 }
132}
133
134// ------------------------------------------------------------------------------------------------
135/// Equality implementations
136impl PartialEq for MastForest {
137 fn eq(&self, other: &Self) -> bool {
138 // Compare all fields except commitment_cache, which is derived data
139 self.nodes == other.nodes
140 && self.roots == other.roots
141 && self.advice_map == other.advice_map
142 && self.debug_info == other.debug_info
143 }
144}
145
146impl Eq for MastForest {}
147
148// ------------------------------------------------------------------------------------------------
149/// State mutators
150impl MastForest {
151 /// The maximum number of nodes that can be stored in a single MAST forest.
152 const MAX_NODES: usize = (1 << 30) - 1;
153
154 /// Marks the given [`MastNodeId`] as being the root of a procedure.
155 ///
156 /// If the specified node is already marked as a root, this will have no effect.
157 ///
158 /// # Panics
159 /// - if `new_root_id`'s internal index is larger than the number of nodes in this forest (i.e.
160 /// clearly doesn't belong to this MAST forest).
161 pub fn make_root(&mut self, new_root_id: MastNodeId) {
162 assert!(new_root_id.to_usize() < self.nodes.len());
163
164 if !self.roots.contains(&new_root_id) {
165 self.roots.push(new_root_id);
166 // Invalidate the cached commitment since we modified the roots
167 self.commitment_cache.take();
168 }
169 }
170
171 /// Removes all nodes in the provided set from the MAST forest. The nodes MUST be orphaned (i.e.
172 /// have no parent). Otherwise, this parent's reference is considered "dangling" after the
173 /// removal (i.e. will point to an incorrect node after the removal), and this removal operation
174 /// would result in an invalid [`MastForest`].
175 ///
176 /// It also returns the map from old node IDs to new node IDs. Any [`MastNodeId`] used in
177 /// reference to the old [`MastForest`] should be remapped using this map.
178 pub fn remove_nodes(
179 &mut self,
180 nodes_to_remove: &BTreeSet<MastNodeId>,
181 ) -> BTreeMap<MastNodeId, MastNodeId> {
182 if nodes_to_remove.is_empty() {
183 return BTreeMap::new();
184 }
185
186 let old_nodes = core::mem::replace(&mut self.nodes, IndexVec::new());
187 let old_root_ids = core::mem::take(&mut self.roots);
188 let (retained_nodes, id_remappings) = remove_nodes(old_nodes.into_inner(), nodes_to_remove);
189
190 self.remap_and_add_nodes(retained_nodes, &id_remappings);
191 self.remap_and_add_roots(old_root_ids, &id_remappings);
192
193 // Remap the asm_op_storage to use the new node IDs
194 self.debug_info.remap_asm_op_storage(&id_remappings);
195
196 // Invalidate the cached commitment since we modified the forest structure
197 self.commitment_cache.take();
198
199 id_remappings
200 }
201
202 /// Clears all [`DebugInfo`] from this forest: decorators, error codes, and procedure names.
203 ///
204 /// ```
205 /// # use miden_core::mast::MastForest;
206 /// let mut forest = MastForest::new();
207 /// forest.clear_debug_info();
208 /// assert!(forest.decorators().is_empty());
209 /// ```
210 pub fn clear_debug_info(&mut self) {
211 self.debug_info = DebugInfo::empty_for_nodes(self.nodes.len());
212 }
213
214 /// Compacts the forest by merging duplicate nodes.
215 ///
216 /// This operation performs node deduplication by merging the forest with itself.
217 /// The method assumes that debug info has already been cleared if that is desired.
218 /// This method consumes the forest and returns a new compacted forest.
219 ///
220 /// The process works by:
221 /// 1. Merging the forest with itself to deduplicate identical nodes
222 /// 2. Updating internal node references and remappings
223 /// 3. Returning the compacted forest and root map
224 ///
225 /// # Examples
226 ///
227 /// ```rust
228 /// use miden_core::mast::MastForest;
229 ///
230 /// let mut forest = MastForest::new();
231 /// // Add nodes to the forest
232 ///
233 /// // First clear debug info if needed
234 /// forest.clear_debug_info();
235 ///
236 /// // Then compact the forest (consumes the original)
237 /// let (compacted_forest, root_map) = forest.compact();
238 ///
239 /// // compacted_forest is now compacted with duplicate nodes merged
240 /// ```
241 pub fn compact(self) -> (MastForest, MastForestRootMap) {
242 // Merge with itself to deduplicate nodes
243 // Note: This cannot fail for a self-merge under normal conditions.
244 // The only possible failures (TooManyNodes, TooManyDecorators) would require the
245 // original forest to be at capacity limits, at which point compaction wouldn't help.
246 MastForest::merge([&self])
247 .expect("Failed to compact MastForest: this should never happen during self-merge")
248 }
249
250 /// Merges all `forests` into a new [`MastForest`].
251 ///
252 /// Merging two forests means combining all their constituent parts, i.e. [`MastNode`]s,
253 /// [`Decorator`]s and roots. During this process, any duplicate or
254 /// unreachable nodes are removed. Additionally, [`MastNodeId`]s of nodes as well as
255 /// [`DecoratorId`]s of decorators may change and references to them are remapped to their new
256 /// location.
257 ///
258 /// For example, consider this representation of a forest's nodes with all of these nodes being
259 /// roots:
260 ///
261 /// ```text
262 /// [Block(foo), Block(bar)]
263 /// ```
264 ///
265 /// If we merge another forest into it:
266 ///
267 /// ```text
268 /// [Block(bar), Call(0)]
269 /// ```
270 ///
271 /// then we would expect this forest:
272 ///
273 /// ```text
274 /// [Block(foo), Block(bar), Call(1)]
275 /// ```
276 ///
277 /// - The `Call` to the `bar` block was remapped to its new index (now 1, previously 0).
278 /// - The `Block(bar)` was deduplicated any only exists once in the merged forest.
279 ///
280 /// The function also returns a vector of [`MastForestRootMap`]s, whose length equals the number
281 /// of passed `forests`. The indices in the vector correspond to the ones in `forests`. The map
282 /// of a given forest contains the new locations of its roots in the merged forest. To
283 /// illustrate, the above example would return a vector of two maps:
284 ///
285 /// ```text
286 /// vec![{0 -> 0, 1 -> 1}
287 /// {0 -> 1, 1 -> 2}]
288 /// ```
289 ///
290 /// - The root locations of the original forest are unchanged.
291 /// - For the second forest, the `bar` block has moved from index 0 to index 1 in the merged
292 /// forest, and the `Call` has moved from index 1 to 2.
293 ///
294 /// If any forest being merged contains an `External(qux)` node and another forest contains a
295 /// node whose digest is `qux`, then the external node will be replaced with the `qux` node,
296 /// which is effectively deduplication. Decorators are ignored when it comes to merging
297 /// External nodes. This means that an External node with decorators may be replaced by a node
298 /// without decorators or vice versa.
299 pub fn merge<'forest>(
300 forests: impl IntoIterator<Item = &'forest MastForest>,
301 ) -> Result<(MastForest, MastForestRootMap), MastForestError> {
302 MastForestMerger::merge(forests)
303 }
304}
305
306// ------------------------------------------------------------------------------------------------
307/// Helpers
308impl MastForest {
309 /// Adds all provided nodes to the internal set of nodes, remapping all [`MastNodeId`]
310 /// references in those nodes.
311 ///
312 /// # Panics
313 /// - Panics if the internal set of nodes is not empty.
314 fn remap_and_add_nodes(
315 &mut self,
316 nodes_to_add: Vec<MastNode>,
317 id_remappings: &BTreeMap<MastNodeId, MastNodeId>,
318 ) {
319 assert!(self.nodes.is_empty());
320 // extract decorator information from the nodes by converting them into builders
321 let node_builders =
322 nodes_to_add.into_iter().map(|node| node.to_builder(self)).collect::<Vec<_>>();
323
324 // Clear decorator storage after extracting builders (builders contain decorator data)
325 self.debug_info.clear_mappings();
326
327 // Add each node to the new MAST forest, making sure to rewrite any outdated internal
328 // `MastNodeId`s
329 for live_node_builder in node_builders {
330 live_node_builder.remap_children(id_remappings).add_to_forest(self).unwrap();
331 }
332 }
333
334 /// Remaps and adds all old root ids to the internal set of roots.
335 ///
336 /// # Panics
337 /// - Panics if the internal set of roots is not empty.
338 fn remap_and_add_roots(
339 &mut self,
340 old_root_ids: Vec<MastNodeId>,
341 id_remappings: &BTreeMap<MastNodeId, MastNodeId>,
342 ) {
343 assert!(self.roots.is_empty());
344
345 for old_root_id in old_root_ids {
346 let new_root_id = id_remappings.get(&old_root_id).copied().unwrap_or(old_root_id);
347 self.make_root(new_root_id);
348 }
349 }
350}
351
352/// Returns the set of nodes that are live, as well as the mapping from "old ID" to "new ID" for all
353/// live nodes.
354fn remove_nodes(
355 mast_nodes: Vec<MastNode>,
356 nodes_to_remove: &BTreeSet<MastNodeId>,
357) -> (Vec<MastNode>, BTreeMap<MastNodeId, MastNodeId>) {
358 // Note: this allows us to safely use `usize as u32`, guaranteeing that it won't wrap around.
359 assert!(mast_nodes.len() < u32::MAX as usize);
360
361 let mut retained_nodes = Vec::with_capacity(mast_nodes.len());
362 let mut id_remappings = BTreeMap::new();
363
364 for (old_node_index, old_node) in mast_nodes.into_iter().enumerate() {
365 let old_node_id: MastNodeId = MastNodeId(old_node_index as u32);
366
367 if !nodes_to_remove.contains(&old_node_id) {
368 let new_node_id: MastNodeId = MastNodeId(retained_nodes.len() as u32);
369 id_remappings.insert(old_node_id, new_node_id);
370
371 retained_nodes.push(old_node);
372 }
373 }
374
375 (retained_nodes, id_remappings)
376}
377
378// ------------------------------------------------------------------------------------------------
379/// Public accessors
380impl MastForest {
381 /// Returns the [`MastNode`] associated with the provided [`MastNodeId`] if valid, or else
382 /// `None`.
383 ///
384 /// This is the fallible version of indexing (e.g. `mast_forest[node_id]`).
385 #[inline(always)]
386 pub fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
387 self.nodes.get(node_id)
388 }
389
390 /// Returns the [`MastNodeId`] of the procedure associated with a given digest, if any.
391 #[inline(always)]
392 pub fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
393 self.roots.iter().find(|&&root_id| self[root_id].digest() == digest).copied()
394 }
395
396 /// Returns true if a node with the specified ID is a root of a procedure in this MAST forest.
397 pub fn is_procedure_root(&self, node_id: MastNodeId) -> bool {
398 self.roots.contains(&node_id)
399 }
400
401 /// Returns an iterator over the digests of all procedures in this MAST forest.
402 pub fn procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
403 self.roots.iter().map(|&root_id| self[root_id].digest())
404 }
405
406 /// Returns an iterator over the digests of local procedures in this MAST forest.
407 ///
408 /// A local procedure is defined as a procedure which is not a single external node.
409 pub fn local_procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
410 self.roots.iter().filter_map(|&root_id| {
411 let node = &self[root_id];
412 if node.is_external() { None } else { Some(node.digest()) }
413 })
414 }
415
416 /// Returns an iterator over the IDs of the procedures in this MAST forest.
417 pub fn procedure_roots(&self) -> &[MastNodeId] {
418 &self.roots
419 }
420
421 /// Returns the number of procedures in this MAST forest.
422 pub fn num_procedures(&self) -> u32 {
423 self.roots
424 .len()
425 .try_into()
426 .expect("MAST forest contains more than 2^32 procedures.")
427 }
428
429 /// Returns the [Word] representing the content hash of a subset of [`MastNodeId`]s.
430 ///
431 /// # Panics
432 /// This function panics if any `node_ids` is not a node of this forest.
433 pub fn compute_nodes_commitment<'a>(
434 &self,
435 node_ids: impl IntoIterator<Item = &'a MastNodeId>,
436 ) -> Word {
437 let mut digests: Vec<Word> = node_ids.into_iter().map(|&id| self[id].digest()).collect();
438 digests.sort_unstable_by_key(|word| LexicographicWord::from(*word));
439 miden_crypto::hash::poseidon2::Poseidon2::merge_many(&digests)
440 }
441
442 /// Returns the commitment to this MAST forest.
443 ///
444 /// The commitment is computed as the sequential hash of all procedure roots in the forest.
445 /// This value is cached after the first computation and reused for subsequent calls,
446 /// unless the forest is mutated (in which case the cache is invalidated).
447 ///
448 /// The commitment uniquely identifies the forest's structure, as each root's digest
449 /// transitively includes all of its descendants. Therefore, a commitment to all roots
450 /// is a commitment to the entire forest.
451 pub fn commitment(&self) -> Word {
452 *self.commitment_cache.get_or_init(|| self.compute_nodes_commitment(&self.roots))
453 }
454
455 /// Returns the number of nodes in this MAST forest.
456 pub fn num_nodes(&self) -> u32 {
457 self.nodes.len() as u32
458 }
459
460 /// Returns the underlying nodes in this MAST forest.
461 pub fn nodes(&self) -> &[MastNode] {
462 self.nodes.as_slice()
463 }
464
465 pub fn advice_map(&self) -> &AdviceMap {
466 &self.advice_map
467 }
468
469 pub fn advice_map_mut(&mut self) -> &mut AdviceMap {
470 &mut self.advice_map
471 }
472
473 // SERIALIZATION
474 // --------------------------------------------------------------------------------------------
475
476 /// Serializes this MastForest without debug information.
477 ///
478 /// This produces a smaller output by omitting decorators, error codes, and procedure names.
479 /// The resulting bytes can be deserialized with the standard [`Deserializable`] impl,
480 /// which auto-detects the format and creates an empty [`DebugInfo`].
481 ///
482 /// Use this for production builds where debug info is not needed.
483 ///
484 /// # Example
485 ///
486 /// ```
487 /// use miden_core::{mast::MastForest, serde::Serializable};
488 ///
489 /// let forest = MastForest::new();
490 ///
491 /// // Full serialization (with debug info)
492 /// let full_bytes = forest.to_bytes();
493 ///
494 /// // Stripped serialization (without debug info)
495 /// let mut stripped_bytes = Vec::new();
496 /// forest.write_stripped(&mut stripped_bytes);
497 ///
498 /// // Both can be deserialized the same way
499 /// // let restored = MastForest::read_from_bytes(&stripped_bytes).unwrap();
500 /// ```
501 pub fn write_stripped<W: ByteWriter>(&self, target: &mut W) {
502 use serialization::StrippedMastForest;
503 StrippedMastForest(self).write_into(target);
504 }
505}
506
507// ------------------------------------------------------------------------------------------------
508/// Decorator methods
509impl MastForest {
510 /// Returns a list of all decorators contained in this [MastForest].
511 pub fn decorators(&self) -> &[Decorator] {
512 self.debug_info.decorators()
513 }
514
515 /// Returns the [`Decorator`] associated with the provided [`DecoratorId`] if valid, or else
516 /// `None`.
517 ///
518 /// This is the fallible version of indexing (e.g. `mast_forest[decorator_id]`).
519 #[inline]
520 pub fn decorator_by_id(&self, decorator_id: DecoratorId) -> Option<&Decorator> {
521 self.debug_info.decorator(decorator_id)
522 }
523
524 /// Returns decorator indices for a specific operation within a node.
525 ///
526 /// This is the primary accessor for reading decorators from the centralized storage.
527 /// Returns a slice of decorator IDs for the given operation.
528 #[inline]
529 pub(crate) fn decorator_indices_for_op(
530 &self,
531 node_id: MastNodeId,
532 local_op_idx: usize,
533 ) -> &[DecoratorId] {
534 self.debug_info.decorators_for_operation(node_id, local_op_idx)
535 }
536
537 /// Returns an iterator over decorator references for a specific operation within a node.
538 ///
539 /// This is the preferred method for accessing decorators, as it provides direct
540 /// references to the decorator objects.
541 #[inline]
542 pub fn decorators_for_op<'a>(
543 &'a self,
544 node_id: MastNodeId,
545 local_op_idx: usize,
546 ) -> impl Iterator<Item = &'a Decorator> + 'a {
547 self.decorator_indices_for_op(node_id, local_op_idx)
548 .iter()
549 .map(move |&decorator_id| &self[decorator_id])
550 }
551
552 /// Returns the decorators to be executed before this node is executed.
553 #[inline]
554 pub fn before_enter_decorators(&self, node_id: MastNodeId) -> &[DecoratorId] {
555 self.debug_info.before_enter_decorators(node_id)
556 }
557
558 /// Returns the decorators to be executed after this node is executed.
559 #[inline]
560 pub fn after_exit_decorators(&self, node_id: MastNodeId) -> &[DecoratorId] {
561 self.debug_info.after_exit_decorators(node_id)
562 }
563
564 /// Returns decorator links for a node, including operation indices.
565 ///
566 /// This provides a flattened view of all decorators for a node with their operation indices.
567 #[inline]
568 pub(crate) fn decorator_links_for_node<'a>(
569 &'a self,
570 node_id: MastNodeId,
571 ) -> Result<DecoratedLinks<'a>, DecoratorIndexError> {
572 self.debug_info.decorator_links_for_node(node_id)
573 }
574
575 /// Adds a decorator to the forest, and returns the associated [`DecoratorId`].
576 pub fn add_decorator(&mut self, decorator: Decorator) -> Result<DecoratorId, MastForestError> {
577 self.debug_info.add_decorator(decorator)
578 }
579
580 /// Adds decorator IDs for a node to the storage.
581 ///
582 /// Used when building nodes for efficient decorator access during execution.
583 ///
584 /// # Note
585 /// This method does not validate decorator IDs immediately. Validation occurs during
586 /// operations that need to access the actual decorator data (e.g., merging, serialization).
587 #[inline]
588 pub(crate) fn register_node_decorators(
589 &mut self,
590 node_id: MastNodeId,
591 before_enter: &[DecoratorId],
592 after_exit: &[DecoratorId],
593 ) {
594 self.debug_info.register_node_decorators(node_id, before_enter, after_exit);
595 }
596
597 /// Returns the [`AssemblyOp`] associated with a node.
598 ///
599 /// For basic block nodes with a `target_op_idx`, returns the AssemblyOp for that operation.
600 /// For other nodes or when no `target_op_idx` is provided, returns the first AssemblyOp.
601 pub fn get_assembly_op(
602 &self,
603 node_id: MastNodeId,
604 target_op_idx: Option<usize>,
605 ) -> Option<&AssemblyOp> {
606 match target_op_idx {
607 Some(op_idx) => self.debug_info.asm_op_for_operation(node_id, op_idx),
608 None => self.debug_info.first_asm_op_for_node(node_id),
609 }
610 }
611}
612
613// ------------------------------------------------------------------------------------------------
614/// Validation methods
615impl MastForest {
616 /// Validates that all BasicBlockNodes in this forest satisfy the core invariants:
617 /// 1. Power-of-two number of groups in each batch
618 /// 2. No operation group ends with an operation requiring an immediate value
619 /// 3. The last operation group in a batch cannot contain operations requiring immediate values
620 /// 4. OpBatch structural consistency (num_groups <= BATCH_SIZE, group size <= GROUP_SIZE,
621 /// indptr integrity, bounds checking)
622 ///
623 /// This addresses the gap created by PR 2094, where padding NOOPs are now inserted
624 /// at assembly time rather than dynamically during execution, and adds comprehensive
625 /// structural validation to prevent deserialization-time panics.
626 pub fn validate(&self) -> Result<(), MastForestError> {
627 // Validate basic block batch invariants
628 for (node_id_idx, node) in self.nodes.iter().enumerate() {
629 let node_id =
630 MastNodeId::new_unchecked(node_id_idx.try_into().expect("too many nodes"));
631 if let MastNode::Block(basic_block) = node {
632 basic_block.validate_batch_invariants().map_err(|error_msg| {
633 MastForestError::InvalidBatchPadding(node_id, error_msg)
634 })?;
635 }
636 }
637
638 // Validate that all procedure name digests correspond to procedure roots in the forest
639 for (digest, _) in self.debug_info.procedure_names() {
640 if self.find_procedure_root(digest).is_none() {
641 return Err(MastForestError::InvalidProcedureNameDigest(digest));
642 }
643 }
644
645 Ok(())
646 }
647
648 /// Validates topological ordering of nodes and recomputes all node hashes.
649 ///
650 /// This method iterates through all nodes in index order, verifying:
651 /// 1. All child references point to nodes with smaller indices (topological order)
652 /// 2. Each node's recomputed digest matches its stored digest
653 ///
654 /// # Errors
655 ///
656 /// Returns `MastForestError::ForwardReference` if any node references a child that
657 /// appears later in the forest.
658 ///
659 /// Returns `MastForestError::HashMismatch` if any node's recomputed digest doesn't
660 /// match its stored digest.
661 fn validate_node_hashes(&self) -> Result<(), MastForestError> {
662 use crate::chiplets::hasher;
663
664 /// Checks that child_id references a node that appears before node_id in topological order.
665 fn check_no_forward_ref(
666 node_id: MastNodeId,
667 child_id: MastNodeId,
668 ) -> Result<(), MastForestError> {
669 if child_id.0 >= node_id.0 {
670 return Err(MastForestError::ForwardReference(node_id, child_id));
671 }
672 Ok(())
673 }
674
675 for (node_idx, node) in self.nodes.iter().enumerate() {
676 let node_id = MastNodeId::new_unchecked(node_idx as u32);
677
678 // Check topological ordering and compute expected digest
679 let computed_digest = match node {
680 MastNode::Block(block) => {
681 let op_groups: Vec<Felt> =
682 block.op_batches().iter().flat_map(|batch| *batch.groups()).collect();
683 hasher::hash_elements(&op_groups)
684 },
685 MastNode::Join(join) => {
686 let left_id = join.first();
687 let right_id = join.second();
688 check_no_forward_ref(node_id, left_id)?;
689 check_no_forward_ref(node_id, right_id)?;
690
691 let left_digest = self.nodes[left_id].digest();
692 let right_digest = self.nodes[right_id].digest();
693 hasher::merge_in_domain(&[left_digest, right_digest], JoinNode::DOMAIN)
694 },
695 MastNode::Split(split) => {
696 let true_id = split.on_true();
697 let false_id = split.on_false();
698 check_no_forward_ref(node_id, true_id)?;
699 check_no_forward_ref(node_id, false_id)?;
700
701 let true_digest = self.nodes[true_id].digest();
702 let false_digest = self.nodes[false_id].digest();
703 hasher::merge_in_domain(&[true_digest, false_digest], SplitNode::DOMAIN)
704 },
705 MastNode::Loop(loop_node) => {
706 let body_id = loop_node.body();
707 check_no_forward_ref(node_id, body_id)?;
708
709 let body_digest = self.nodes[body_id].digest();
710 hasher::merge_in_domain(&[body_digest, Word::default()], LoopNode::DOMAIN)
711 },
712 MastNode::Call(call) => {
713 let callee_id = call.callee();
714 check_no_forward_ref(node_id, callee_id)?;
715
716 let callee_digest = self.nodes[callee_id].digest();
717 let domain = if call.is_syscall() {
718 CallNode::SYSCALL_DOMAIN
719 } else {
720 CallNode::CALL_DOMAIN
721 };
722 hasher::merge_in_domain(&[callee_digest, Word::default()], domain)
723 },
724 MastNode::Dyn(dyn_node) => {
725 if dyn_node.is_dyncall() {
726 DynNode::DYNCALL_DEFAULT_DIGEST
727 } else {
728 DynNode::DYN_DEFAULT_DIGEST
729 }
730 },
731 MastNode::External(_) => {
732 // External nodes have externally-provided digests that cannot be recomputed
733 continue;
734 },
735 };
736
737 let stored_digest = node.digest();
738 if computed_digest != stored_digest {
739 return Err(MastForestError::HashMismatch {
740 node_id,
741 expected: stored_digest,
742 computed: computed_digest,
743 });
744 }
745 }
746
747 Ok(())
748 }
749}
750
751// ------------------------------------------------------------------------------------------------
752/// Error message methods
753impl MastForest {
754 /// Given an error code as a Felt, resolves it to its corresponding error message.
755 pub fn resolve_error_message(&self, code: Felt) -> Option<Arc<str>> {
756 let key = code.as_canonical_u64();
757 self.debug_info.error_message(key)
758 }
759
760 /// Registers an error message in the MAST Forest and returns the corresponding error code as a
761 /// Felt.
762 pub fn register_error(&mut self, msg: Arc<str>) -> Felt {
763 let code: Felt = error_code_from_msg(&msg);
764 // we use u64 as keys for the map
765 self.debug_info.insert_error_code(code.as_canonical_u64(), msg);
766 code
767 }
768}
769
770// ------------------------------------------------------------------------------------------------
771/// Procedure name methods
772impl MastForest {
773 /// Returns the procedure name for the given MAST root digest, if present.
774 pub fn procedure_name(&self, digest: &Word) -> Option<&str> {
775 self.debug_info.procedure_name(digest)
776 }
777
778 /// Returns an iterator over all (digest, name) pairs of procedure names.
779 pub fn procedure_names(&self) -> impl Iterator<Item = (Word, &Arc<str>)> {
780 self.debug_info.procedure_names()
781 }
782
783 /// Inserts a procedure name for the given MAST root digest.
784 pub fn insert_procedure_name(&mut self, digest: Word, name: Arc<str>) {
785 assert!(
786 self.find_procedure_root(digest).is_some(),
787 "attempted to insert procedure name for digest that is not a procedure root"
788 );
789 self.debug_info.insert_procedure_name(digest, name);
790 }
791
792 /// Returns a reference to the debug info for this forest.
793 pub fn debug_info(&self) -> &DebugInfo {
794 &self.debug_info
795 }
796
797 /// Returns a mutable reference to the debug info.
798 ///
799 /// This is intended for use by the assembler to register AssemblyOps and other debug
800 /// information during compilation.
801 pub fn debug_info_mut(&mut self) -> &mut DebugInfo {
802 &mut self.debug_info
803 }
804}
805
806// TEST HELPERS
807// ================================================================================================
808
809#[cfg(test)]
810impl MastForest {
811 /// Returns all decorators for a given node as a vector of (position, DecoratorId) tuples.
812 ///
813 /// This helper method combines before_enter, operation-indexed, and after_exit decorators
814 /// into a single collection, which is useful for testing decorator positions and ordering.
815 ///
816 /// **Performance Warning**: This method performs multiple allocations through collect() calls
817 /// and should not be relied upon for performance-critical code. It is intended for testing
818 /// only.
819 pub fn all_decorators(&self, node_id: MastNodeId) -> Vec<(usize, DecoratorId)> {
820 let node = &self[node_id];
821
822 // For non-basic blocks, just get before_enter and after_exit decorators at position 0
823 if !node.is_basic_block() {
824 let before_enter_decorators: Vec<_> = self
825 .before_enter_decorators(node_id)
826 .iter()
827 .map(|&deco_id| (0, deco_id))
828 .collect();
829
830 let after_exit_decorators: Vec<_> = self
831 .after_exit_decorators(node_id)
832 .iter()
833 .map(|&deco_id| (1, deco_id))
834 .collect();
835
836 return [before_enter_decorators, after_exit_decorators].concat();
837 }
838
839 // For basic blocks, we need to handle operation-indexed decorators with proper positioning
840 let block = node.unwrap_basic_block();
841
842 // Before-enter decorators are at position 0
843 let before_enter_decorators: Vec<_> = self
844 .before_enter_decorators(node_id)
845 .iter()
846 .map(|&deco_id| (0, deco_id))
847 .collect();
848
849 // Operation-indexed decorators with their actual positions
850 let op_indexed_decorators: Vec<_> =
851 self.decorator_links_for_node(node_id).unwrap().into_iter().collect();
852
853 // After-exit decorators are positioned after all operations
854 let after_exit_decorators: Vec<_> = self
855 .after_exit_decorators(node_id)
856 .iter()
857 .map(|&deco_id| (block.num_operations() as usize, deco_id))
858 .collect();
859
860 [before_enter_decorators, op_indexed_decorators, after_exit_decorators].concat()
861 }
862}
863
864// MAST FOREST INDEXING
865// ------------------------------------------------------------------------------------------------
866
867impl Index<MastNodeId> for MastForest {
868 type Output = MastNode;
869
870 #[inline(always)]
871 fn index(&self, node_id: MastNodeId) -> &Self::Output {
872 &self.nodes[node_id]
873 }
874}
875
876impl IndexMut<MastNodeId> for MastForest {
877 #[inline(always)]
878 fn index_mut(&mut self, node_id: MastNodeId) -> &mut Self::Output {
879 &mut self.nodes[node_id]
880 }
881}
882
883impl Index<DecoratorId> for MastForest {
884 type Output = Decorator;
885
886 #[inline(always)]
887 fn index(&self, decorator_id: DecoratorId) -> &Self::Output {
888 self.debug_info.decorator(decorator_id).expect("DecoratorId out of bounds")
889 }
890}
891
892impl IndexMut<DecoratorId> for MastForest {
893 #[inline(always)]
894 fn index_mut(&mut self, decorator_id: DecoratorId) -> &mut Self::Output {
895 self.debug_info.decorator_mut(decorator_id).expect("DecoratorId out of bounds")
896 }
897}
898
899// MAST NODE ID
900// ================================================================================================
901
902/// An opaque handle to a [`MastNode`] in some [`MastForest`]. It is the responsibility of the user
903/// to use a given [`MastNodeId`] with the corresponding [`MastForest`].
904///
905/// Note that the [`MastForest`] does *not* ensure that equal [`MastNode`]s have equal
906/// [`MastNodeId`] handles. Hence, [`MastNodeId`] equality must not be used to test for equality of
907/// the underlying [`MastNode`].
908#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
909#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
910#[cfg_attr(feature = "serde", serde(transparent))]
911#[cfg_attr(all(feature = "arbitrary", test), miden_test_serde_macros::serde_test)]
912pub struct MastNodeId(u32);
913
914/// Operations that mutate a MAST often produce this mapping between old and new NodeIds.
915pub type Remapping = BTreeMap<MastNodeId, MastNodeId>;
916
917impl MastNodeId {
918 /// Returns a new `MastNodeId` with the provided inner value, or an error if the provided
919 /// `value` is greater than the number of nodes in the forest.
920 ///
921 /// For use in deserialization.
922 pub fn from_u32_safe(
923 value: u32,
924 mast_forest: &MastForest,
925 ) -> Result<Self, DeserializationError> {
926 Self::from_u32_with_node_count(value, mast_forest.nodes.len())
927 }
928
929 /// Returns a new [`MastNodeId`] with the provided `node_id`, or an error if `node_id` is
930 /// greater than the number of nodes in the [`MastForest`] for which this ID is being
931 /// constructed.
932 pub fn from_usize_safe(
933 node_id: usize,
934 mast_forest: &MastForest,
935 ) -> Result<Self, DeserializationError> {
936 let node_id: u32 = node_id.try_into().map_err(|_| {
937 DeserializationError::InvalidValue(format!(
938 "node id '{node_id}' does not fit into a u32"
939 ))
940 })?;
941 MastNodeId::from_u32_safe(node_id, mast_forest)
942 }
943
944 /// Returns a new [`MastNodeId`] from the given `value` without checking its validity.
945 pub fn new_unchecked(value: u32) -> Self {
946 Self(value)
947 }
948
949 /// Returns a new [`MastNodeId`] with the provided `id`, or an error if `id` is greater or equal
950 /// to `node_count`. The `node_count` is the total number of nodes in the [`MastForest`] for
951 /// which this ID is being constructed.
952 ///
953 /// This function can be used when deserializing an id whose corresponding node is not yet in
954 /// the forest and [`Self::from_u32_safe`] would fail. For instance, when deserializing the ids
955 /// referenced by the Join node in this forest:
956 ///
957 /// ```text
958 /// [Join(1, 2), Block(foo), Block(bar)]
959 /// ```
960 ///
961 /// Since it is less safe than [`Self::from_u32_safe`] and usually not needed it is not public.
962 pub(super) fn from_u32_with_node_count(
963 id: u32,
964 node_count: usize,
965 ) -> Result<Self, DeserializationError> {
966 if (id as usize) < node_count {
967 Ok(Self(id))
968 } else {
969 Err(DeserializationError::InvalidValue(format!(
970 "Invalid deserialized MAST node ID '{id}', but {node_count} is the number of nodes in the forest",
971 )))
972 }
973 }
974
975 /// Remap the NodeId to its new position using the given [`Remapping`].
976 pub fn remap(&self, remapping: &Remapping) -> Self {
977 *remapping.get(self).unwrap_or(self)
978 }
979}
980
981impl From<u32> for MastNodeId {
982 fn from(value: u32) -> Self {
983 MastNodeId::new_unchecked(value)
984 }
985}
986
987impl Idx for MastNodeId {}
988
989impl From<MastNodeId> for u32 {
990 fn from(value: MastNodeId) -> Self {
991 value.0
992 }
993}
994
995impl fmt::Display for MastNodeId {
996 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
997 write!(f, "MastNodeId({})", self.0)
998 }
999}
1000
1001#[cfg(any(test, feature = "arbitrary"))]
1002impl proptest::prelude::Arbitrary for MastNodeId {
1003 type Parameters = ();
1004
1005 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
1006 use proptest::prelude::*;
1007 any::<u32>().prop_map(MastNodeId).boxed()
1008 }
1009
1010 type Strategy = proptest::prelude::BoxedStrategy<Self>;
1011}
1012
1013// ITERATOR
1014
1015/// Iterates over all the nodes a root depends on, in pre-order. The iteration can include other
1016/// roots in the same forest.
1017pub struct SubtreeIterator<'a> {
1018 forest: &'a MastForest,
1019 discovered: Vec<MastNodeId>,
1020 unvisited: Vec<MastNodeId>,
1021}
1022impl<'a> SubtreeIterator<'a> {
1023 pub fn new(root: &MastNodeId, forest: &'a MastForest) -> Self {
1024 let discovered = vec![];
1025 let unvisited = vec![*root];
1026 SubtreeIterator { forest, discovered, unvisited }
1027 }
1028}
1029impl Iterator for SubtreeIterator<'_> {
1030 type Item = MastNodeId;
1031 fn next(&mut self) -> Option<MastNodeId> {
1032 while let Some(id) = self.unvisited.pop() {
1033 let node = &self.forest[id];
1034 if !node.has_children() {
1035 return Some(id);
1036 } else {
1037 self.discovered.push(id);
1038 node.append_children_to(&mut self.unvisited);
1039 }
1040 }
1041 self.discovered.pop()
1042 }
1043}
1044
1045// DECORATOR ID
1046// ================================================================================================
1047
1048/// An opaque handle to a [`Decorator`] in some [`MastForest`]. It is the responsibility of the user
1049/// to use a given [`DecoratorId`] with the corresponding [`MastForest`].
1050#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1051#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1052#[cfg_attr(feature = "serde", serde(transparent))]
1053pub struct DecoratorId(u32);
1054
1055impl DecoratorId {
1056 /// Returns a new `DecoratorId` with the provided inner value, or an error if the provided
1057 /// `value` is greater than the number of nodes in the forest.
1058 ///
1059 /// For use in deserialization.
1060 pub fn from_u32_safe(
1061 value: u32,
1062 mast_forest: &MastForest,
1063 ) -> Result<Self, DeserializationError> {
1064 Self::from_u32_bounded(value, mast_forest.debug_info.num_decorators())
1065 }
1066
1067 /// Returns a new `DecoratorId` with the provided inner value, or an error if the provided
1068 /// `value` is greater than or equal to `bound`.
1069 ///
1070 /// For use in deserialization when the bound is known without needing the full MastForest.
1071 pub fn from_u32_bounded(value: u32, bound: usize) -> Result<Self, DeserializationError> {
1072 if (value as usize) < bound {
1073 Ok(Self(value))
1074 } else {
1075 Err(DeserializationError::InvalidValue(format!(
1076 "Invalid deserialized MAST decorator id '{}', but allows only {} decorators",
1077 value, bound,
1078 )))
1079 }
1080 }
1081
1082 /// Creates a new [`DecoratorId`] without checking its validity.
1083 pub(crate) fn new_unchecked(value: u32) -> Self {
1084 Self(value)
1085 }
1086}
1087
1088impl From<u32> for DecoratorId {
1089 fn from(value: u32) -> Self {
1090 DecoratorId::new_unchecked(value)
1091 }
1092}
1093
1094impl Idx for DecoratorId {}
1095
1096impl From<DecoratorId> for u32 {
1097 fn from(value: DecoratorId) -> Self {
1098 value.0
1099 }
1100}
1101
1102impl fmt::Display for DecoratorId {
1103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1104 write!(f, "DecoratorId({})", self.0)
1105 }
1106}
1107
1108impl Serializable for DecoratorId {
1109 fn write_into<W: ByteWriter>(&self, target: &mut W) {
1110 self.0.write_into(target)
1111 }
1112}
1113
1114impl Deserializable for DecoratorId {
1115 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
1116 let value = u32::read_from(source)?;
1117 Ok(Self(value))
1118 }
1119}
1120
1121// ASM OP ID
1122// ================================================================================================
1123
1124/// Unique identifier for an [`AssemblyOp`] within a [`MastForest`].
1125///
1126/// Unlike decorators (which are executed at runtime), AssemblyOps are metadata
1127/// used only for error context and debugging tools.
1128#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1129#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1130#[cfg_attr(feature = "serde", serde(transparent))]
1131pub struct AsmOpId(u32);
1132
1133impl AsmOpId {
1134 /// Creates a new [`AsmOpId`] with the provided inner value.
1135 pub const fn new(value: u32) -> Self {
1136 Self(value)
1137 }
1138}
1139
1140impl From<u32> for AsmOpId {
1141 fn from(value: u32) -> Self {
1142 AsmOpId::new(value)
1143 }
1144}
1145
1146impl Idx for AsmOpId {}
1147
1148impl From<AsmOpId> for u32 {
1149 fn from(id: AsmOpId) -> Self {
1150 id.0
1151 }
1152}
1153
1154impl fmt::Display for AsmOpId {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 write!(f, "AsmOpId({})", self.0)
1157 }
1158}
1159
1160impl Serializable for AsmOpId {
1161 fn write_into<W: ByteWriter>(&self, target: &mut W) {
1162 self.0.write_into(target)
1163 }
1164}
1165
1166impl Deserializable for AsmOpId {
1167 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
1168 let value = u32::read_from(source)?;
1169 Ok(Self(value))
1170 }
1171}
1172
1173/// Derives an error code from an error message by hashing the message and returning the 0th element
1174/// of the resulting [`Word`].
1175pub fn error_code_from_msg(msg: impl AsRef<str>) -> Felt {
1176 // hash the message and return 0th felt of the resulting Word
1177 hash_string_to_word(msg.as_ref())[0]
1178}
1179
1180// MAST FOREST ERROR
1181// ================================================================================================
1182
1183/// Represents the types of errors that can occur when dealing with MAST forest.
1184#[derive(Debug, thiserror::Error, PartialEq)]
1185pub enum MastForestError {
1186 #[error("MAST forest decorator count exceeds the maximum of {} decorators", u32::MAX)]
1187 TooManyDecorators,
1188 #[error("MAST forest node count exceeds the maximum of {} nodes", MastForest::MAX_NODES)]
1189 TooManyNodes,
1190 #[error("node id {0} is greater than or equal to forest length {1}")]
1191 NodeIdOverflow(MastNodeId, usize),
1192 #[error("decorator id {0} is greater than or equal to decorator count {1}")]
1193 DecoratorIdOverflow(DecoratorId, usize),
1194 #[error("basic block cannot be created from an empty list of operations")]
1195 EmptyBasicBlock,
1196 #[error(
1197 "decorator root of child with node id {0} is missing but is required for fingerprint computation"
1198 )]
1199 ChildFingerprintMissing(MastNodeId),
1200 #[error("advice map key {0} already exists when merging forests")]
1201 AdviceMapKeyCollisionOnMerge(Word),
1202 #[error("decorator storage error: {0}")]
1203 DecoratorError(DecoratorIndexError),
1204 #[error("digest is required for deserialization")]
1205 DigestRequiredForDeserialization,
1206 #[error("invalid batch in basic block node {0:?}: {1}")]
1207 InvalidBatchPadding(MastNodeId, String),
1208 #[error("procedure name references digest that is not a procedure root: {0:?}")]
1209 InvalidProcedureNameDigest(Word),
1210 #[error(
1211 "node {0:?} references child {1:?} which comes after it in the forest (forward reference)"
1212 )]
1213 ForwardReference(MastNodeId, MastNodeId),
1214 #[error("hash mismatch for node {node_id:?}: expected {expected:?}, computed {computed:?}")]
1215 HashMismatch {
1216 node_id: MastNodeId,
1217 expected: Word,
1218 computed: Word,
1219 },
1220}
1221
1222// Custom serde implementations for MastForest that handle linked decorators properly
1223// by delegating to the existing miden-crypto serialization which already handles
1224// the conversion between linked and owned decorator formats.
1225#[cfg(feature = "serde")]
1226impl serde::Serialize for MastForest {
1227 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1228 where
1229 S: serde::Serializer,
1230 {
1231 // Use the existing miden-crypto serialization which already handles linked decorators
1232 let bytes = Serializable::to_bytes(self);
1233 serializer.serialize_bytes(&bytes)
1234 }
1235}
1236
1237#[cfg(feature = "serde")]
1238impl<'de> serde::Deserialize<'de> for MastForest {
1239 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1240 where
1241 D: serde::Deserializer<'de>,
1242 {
1243 // Deserialize bytes, then use miden-crypto Deserializable
1244 let bytes = Vec::<u8>::deserialize(deserializer)?;
1245 let mut slice_reader = SliceReader::new(&bytes);
1246 Deserializable::read_from(&mut slice_reader).map_err(serde::de::Error::custom)
1247 }
1248}
1249
1250// UNTRUSTED MAST FOREST
1251// ================================================================================================
1252
1253/// A [`MastForest`] deserialized from untrusted input that has not yet been validated.
1254///
1255/// This type wraps a `MastForest` that was deserialized from bytes but has not had its
1256/// node hashes verified. Before using the forest, callers must call [`validate()`](Self::validate)
1257/// to verify structural integrity and recompute all node hashes.
1258///
1259/// # Usage
1260///
1261/// ```ignore
1262/// // Deserialize from untrusted bytes
1263/// let untrusted = UntrustedMastForest::read_from_bytes(&bytes)?;
1264///
1265/// // Validate structure and hashes
1266/// let forest = untrusted.validate()?;
1267///
1268/// // Now safe to use
1269/// let root = forest.procedure_roots()[0];
1270/// ```
1271///
1272/// # Security
1273///
1274/// This type exists to provide type-level safety for untrusted deserialization. The validation
1275/// performed by [`validate()`](Self::validate) includes:
1276///
1277/// 1. **Structural validation**: Checks that basic block batch invariants are satisfied and
1278/// procedure names reference valid roots.
1279/// 2. **Topological ordering**: Verifies that all node references point to nodes that appear
1280/// earlier in the forest (no forward references).
1281/// 3. **Hash recomputation**: Recomputes the digest for every node and verifies it matches the
1282/// stored digest.
1283#[derive(Debug, Clone)]
1284pub struct UntrustedMastForest(MastForest);
1285
1286impl UntrustedMastForest {
1287 /// Validates the forest by checking structural invariants and recomputing all node hashes.
1288 ///
1289 /// This method performs a complete validation of the deserialized forest:
1290 ///
1291 /// 1. Validates structural invariants (batch padding, procedure names)
1292 /// 2. Validates topological ordering (no forward references)
1293 /// 3. Recomputes all node hashes and compares against stored digests
1294 ///
1295 /// # Returns
1296 ///
1297 /// - `Ok(MastForest)` if validation succeeds
1298 /// - `Err(MastForestError)` with details about the first validation failure
1299 ///
1300 /// # Errors
1301 ///
1302 /// Returns an error if:
1303 /// - Any basic block has invalid batch structure ([`MastForestError::InvalidBatchPadding`])
1304 /// - Any procedure name references a non-root digest
1305 /// ([`MastForestError::InvalidProcedureNameDigest`])
1306 /// - Any node references a child that appears later in the forest
1307 /// ([`MastForestError::ForwardReference`])
1308 /// - Any node's recomputed hash doesn't match its stored digest
1309 /// ([`MastForestError::HashMismatch`])
1310 pub fn validate(self) -> Result<MastForest, MastForestError> {
1311 let forest = self.0;
1312
1313 // Step 1: Validate structural invariants (existing validate() checks)
1314 forest.validate()?;
1315
1316 // Step 2: Validate topological ordering and recompute hashes
1317 forest.validate_node_hashes()?;
1318
1319 Ok(forest)
1320 }
1321
1322 /// Deserializes an [`UntrustedMastForest`] from bytes.
1323 ///
1324 /// This method uses a [`BudgetedReader`] with a budget equal to the input size to protect
1325 /// against denial-of-service attacks from malicious input.
1326 ///
1327 /// For stricter limits, use
1328 /// [`read_from_bytes_with_budget`](Self::read_from_bytes_with_budget) with a custom budget.
1329 ///
1330 /// # Example
1331 ///
1332 /// ```ignore
1333 /// // Read from untrusted source
1334 /// let untrusted = UntrustedMastForest::read_from_bytes(&bytes)?;
1335 ///
1336 /// // Validate before use
1337 /// let forest = untrusted.validate()?;
1338 /// ```
1339 pub fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
1340 Self::read_from_bytes_with_budget(bytes, bytes.len())
1341 }
1342
1343 /// Deserializes an [`UntrustedMastForest`] from bytes with a byte budget.
1344 ///
1345 /// This method uses a [`BudgetedReader`] to limit memory consumption during deserialization,
1346 /// protecting against denial-of-service attacks from malicious input that claims to contain
1347 /// an excessive number of elements.
1348 ///
1349 /// # Arguments
1350 ///
1351 /// * `bytes` - The serialized forest bytes
1352 /// * `budget` - Maximum bytes to consume during deserialization. Set this to `bytes.len()` for
1353 /// typical use cases, or lower to enforce stricter limits.
1354 ///
1355 /// # Example
1356 ///
1357 /// ```ignore
1358 /// // Read from untrusted source with budget equal to input size
1359 /// let untrusted = UntrustedMastForest::read_from_bytes_with_budget(&bytes, bytes.len())?;
1360 ///
1361 /// // Validate before use
1362 /// let forest = untrusted.validate()?;
1363 /// ```
1364 ///
1365 /// # Security
1366 ///
1367 /// The budget limits:
1368 /// - Pre-allocation sizes when deserializing collections (via `max_alloc`)
1369 /// - Total bytes consumed during deserialization
1370 ///
1371 /// This prevents attacks where malicious input claims an unrealistic number of elements
1372 /// (e.g., `len = 2^60`), causing excessive memory allocation before any data is read.
1373 pub fn read_from_bytes_with_budget(
1374 bytes: &[u8],
1375 budget: usize,
1376 ) -> Result<Self, DeserializationError> {
1377 let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
1378 Self::read_from(&mut reader)
1379 }
1380}