Skip to main content

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//! [`UntrustedMastForest::read_from_bytes`] applies default parsing and validation budgets derived
16//! from the input size. Use [`UntrustedMastForest::read_from_bytes_with_options`] with
17//! [`UntrustedMastForestReadOptions`] to tune the wire byte budget. This limits allocations driven
18//! directly by wire counts while reading the payload. A separate validation helper budget is
19//! derived from it for later allocations needed to materialize and check hashless payloads.
20//!
21//! ```ignore
22//! use miden_core::mast::{UntrustedMastForest, UntrustedMastForestReadOptions};
23//!
24//! let options = UntrustedMastForestReadOptions::new()
25//!     .with_wire_byte_budget(bytes.len());
26//! let forest = UntrustedMastForest::read_from_bytes_with_options(&bytes, options)?
27//!     .validate()?;
28//! ```
29//!
30//! This recomputes all node hashes and checks structural invariants before returning a usable
31//! `MastForest`. Direct deserialization via `MastForest::read_from_bytes` trusts the serialized
32//! hashes and should only be used for data from trusted sources (e.g. compiled locally).
33//!
34//! In practice, the public entry points split into three policies:
35//! - [`MastForest::read_from_bytes`]: trusted full deserialization; rejects hashless payloads and
36//!   trusts serialized non-external digests.
37//! - [`MastForestWireView::new`]: trusted wire-backed cache access; scans only the layout needed
38//!   for random access and rejects hashless payloads.
39//! - [`UntrustedMastForest::read_from_bytes`] and
40//!   [`UntrustedMastForest::read_from_bytes_with_options`]: untrusted paths; parse with bounded
41//!   readers and require [`UntrustedMastForest::validate`] before use.
42
43#[cfg(test)]
44use alloc::collections::BTreeSet;
45use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec};
46use core::{fmt, ops::Index};
47
48use dense_order::{
49    canonicalize_parts, validate_dense_node_order, validate_mast_forest_parts_bounds,
50};
51#[cfg(any(test, feature = "arbitrary"))]
52use proptest::prelude::*;
53
54mod dense_order;
55mod node;
56#[cfg(any(test, feature = "arbitrary"))]
57pub use node::arbitrary;
58pub(crate) use node::collect_immediate_placements;
59pub use node::{
60    BasicBlockNode, BasicBlockNodeBuilder, CallNode, CallNodeBuilder, DynNode, DynNodeBuilder,
61    ExternalNode, ExternalNodeBuilder, JoinNode, JoinNodeBuilder, LoopNode, LoopNodeBuilder,
62    MastForestContributor, MastNode, MastNodeBuilder, MastNodeContext, MastNodeExt, OP_BATCH_SIZE,
63    OP_GROUP_SIZE, OpBatch, SplitNode, SplitNodeBuilder,
64};
65
66use crate::{
67    Felt, Word,
68    advice::AdviceMap,
69    serde::{ByteWriter, Deserializable, DeserializationError, Serializable},
70    utils::{DenseIdMap, Idx, IndexVec, hash_string_to_word},
71};
72
73mod serialization;
74pub use serialization::{
75    AdviceMapView, AdviceValueView, MastForestReadMode, MastForestReadView, MastForestView,
76    MastForestWireView, MastNodeEntry, MastNodeInfo,
77};
78
79mod dense_builder;
80pub use dense_builder::DenseMastForestBuilder;
81
82mod untrusted;
83pub use untrusted::{UntrustedMastForest, UntrustedMastForestReadOptions};
84
85mod merger;
86pub use merger::{MastForestMergeSource, MastForestRootMap};
87pub(crate) use merger::{MastForestMerger, MixedMastForestMerger};
88
89mod multi_forest_node_iterator;
90pub(crate) use multi_forest_node_iterator::*;
91
92mod node_builder_utils;
93pub use node_builder_utils::build_node_with_remapped_ids;
94
95mod sparse;
96pub use sparse::{MastForestId, SparseMastForest, SparseMastForestBuilder, VisitKind};
97
98mod forest_read;
99pub use forest_read::MastForestRead;
100pub(crate) use forest_read::StoredContentKey;
101
102#[cfg(test)]
103mod tests;
104
105// MAST FOREST
106// ================================================================================================
107
108/// Represents one or more procedures, represented as a collection of [`MastNode`]s.
109///
110/// A [`MastForest`] does not have an entrypoint, and hence is not executable. A
111/// [`crate::program::Program`] can be built from a [`MastForest`] to specify an entrypoint.
112///
113/// Finalized dense forests keep nodes in final dense order:
114/// - external nodes first, sorted by digest, with no duplicate external digests;
115/// - basic blocks next, in the input order seen by finalization;
116/// - internal nodes last, with every child before its parent and finalization input order as the
117///   tie-breaker.
118///
119/// Serialization expects this in-memory order and validates it before writing.
120///
121/// Normal construction goes through builders. Once finalized, a `MastForest` exposes no append API;
122/// code that changes dense nodes must rebuild and finalize a new forest so ordering, root, and
123/// commitment invariants stay in sync.
124#[derive(Clone, Debug, Default)]
125#[cfg_attr(
126    all(feature = "arbitrary", test),
127    miden_test_serialization_macros::serialization_test
128)]
129pub struct MastForest {
130    /// All of the nodes local to the trees comprising the MAST forest.
131    nodes: IndexVec<MastNodeId, MastNode>,
132
133    /// Roots of procedures defined within this MAST forest.
134    roots: Vec<MastNodeId>,
135
136    /// Advice map to be loaded into the VM prior to executing procedures from this MAST forest.
137    advice_map: AdviceMap,
138
139    /// Commitments to this MAST forest's roots, external dependencies, and advice map.
140    commitment: MastForestCommitment,
141}
142
143/// Commitment values derived from a MAST forest.
144///
145/// Commitment roles:
146/// - [`MastForest::interface_commitment`] identifies the public procedure roots only.
147/// - [`MastForest::dependency_commitment`] identifies the external dependency digests only.
148/// - [`MastForest::advice_commitment`] identifies the stored advice map only.
149/// - [`MastForest::commitment`] identifies the stored dense forest data: public roots, external
150///   dependencies, and advice. Direct forest-backed static libraries use this value as their source
151///   identity. Package-backed static libraries use the package commitment, which is derived from
152///   this forest commitment.
153#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
154struct MastForestCommitment {
155    /// Commitment to the forest's roots, external dependencies, and advice map.
156    commitment: Word,
157
158    /// Commitment to this MAST forest's public procedure roots.
159    interface_commitment: Word,
160
161    /// Commitment to this MAST forest's external dependencies.
162    dependency_commitment: Word,
163
164    /// Commitment to this MAST forest's advice map.
165    advice_commitment: Word,
166}
167
168/// Complete parts needed to construct a finalized [`MastForest`].
169pub(crate) struct MastForestParts {
170    pub nodes: IndexVec<MastNodeId, MastNode>,
171    pub roots: Vec<MastNodeId>,
172    pub advice_map: AdviceMap,
173}
174
175// ------------------------------------------------------------------------------------------------
176/// Constructors
177impl MastForest {
178    /// Creates a new empty [`MastForest`].
179    pub fn new() -> Self {
180        Self {
181            nodes: IndexVec::new(),
182            roots: Vec::new(),
183            advice_map: AdviceMap::default(),
184            commitment: empty_mast_forest_commitment(),
185        }
186    }
187
188    /// Builds a [`MastForest`] from raw parts and validates local structure.
189    ///
190    /// This is hidden because raw dense parts are not a stable public construction API.
191    #[doc(hidden)]
192    pub fn from_raw_parts(
193        nodes: IndexVec<MastNodeId, MastNode>,
194        roots: Vec<MastNodeId>,
195        advice_map: AdviceMap,
196    ) -> Result<Self, MastForestError> {
197        Self::from_parts(MastForestParts { nodes, roots, advice_map })
198    }
199
200    /// Builds a [`MastForest`] from raw parts and returns the node ID remapping applied during
201    /// canonicalization.
202    ///
203    /// This is hidden because raw dense parts and builder-local ID remapping are only used by
204    /// internal builders and tests.
205    #[doc(hidden)]
206    pub fn from_raw_parts_with_id_map(
207        nodes: IndexVec<MastNodeId, MastNode>,
208        roots: Vec<MastNodeId>,
209        advice_map: AdviceMap,
210    ) -> Result<(Self, DenseIdMap<MastNodeId, MastNodeId>), MastForestError> {
211        Self::from_parts_with_id_map(MastForestParts { nodes, roots, advice_map })
212    }
213
214    /// Builds a [`MastForest`] from completed parts.
215    pub(crate) fn from_parts(parts: MastForestParts) -> Result<Self, MastForestError> {
216        Self::from_parts_with_id_map(parts).map(|(forest, _remapping)| forest)
217    }
218
219    pub(crate) fn from_parts_with_id_map(
220        parts: MastForestParts,
221    ) -> Result<(Self, DenseIdMap<MastNodeId, MastNodeId>), MastForestError> {
222        validate_mast_forest_parts_bounds(&parts)?;
223        let (parts, id_remapping) = canonicalize_parts(parts)?;
224
225        let forest = Self {
226            commitment: compute_mast_forest_commitment(
227                &parts.nodes,
228                &parts.roots,
229                &parts.advice_map,
230            ),
231            nodes: parts.nodes,
232            roots: parts.roots,
233            advice_map: parts.advice_map,
234        };
235
236        forest.validate_dense_node_order()?;
237        forest.validate()?;
238        forest.validate_node_hashes()?;
239        Ok((forest, id_remapping))
240    }
241
242    pub(in crate::mast) fn from_trusted_deserialization_parts(
243        parts: MastForestParts,
244    ) -> Result<Self, MastForestError> {
245        validate_mast_forest_parts_bounds(&parts)?;
246        // Trusted dense serialization is expected to have checked this already. Re-check the
247        // cheap ordering invariant here as a precaution before accepting the finalized forest.
248        validate_dense_node_order(&parts.nodes)?;
249        Ok(Self {
250            commitment: compute_mast_forest_commitment(
251                &parts.nodes,
252                &parts.roots,
253                &parts.advice_map,
254            ),
255            nodes: parts.nodes,
256            roots: parts.roots,
257            advice_map: parts.advice_map,
258        })
259    }
260}
261
262// ------------------------------------------------------------------------------------------------
263/// Equality implementations
264impl PartialEq for MastForest {
265    fn eq(&self, other: &Self) -> bool {
266        self.nodes == other.nodes
267            && self.roots == other.roots
268            && self.advice_map == other.advice_map
269    }
270}
271
272impl Eq for MastForest {}
273
274// ------------------------------------------------------------------------------------------------
275/// State mutators
276impl MastForest {
277    /// The maximum number of nodes that can be stored in a single MAST forest.
278    const MAX_NODES: usize = (1 << 30) - 1;
279
280    /// Marks the given [`MastNodeId`] as being the root of a procedure.
281    ///
282    /// If the specified node is already marked as a root, this will have no effect.
283    ///
284    /// # Panics
285    /// - if `new_root_id`'s internal index is larger than the number of nodes in this forest (i.e.
286    ///   clearly doesn't belong to this MAST forest).
287    #[cfg(any(test, feature = "arbitrary"))]
288    pub fn make_root(&mut self, new_root_id: MastNodeId) {
289        assert!(new_root_id.to_usize() < self.nodes.len());
290
291        if !self.roots.contains(&new_root_id) {
292            self.roots.push(new_root_id);
293            self.commitment = self.compute_mast_forest_commitment();
294        }
295    }
296
297    /// Removes all nodes in the provided set from the MAST forest. The nodes MUST be orphaned (i.e.
298    /// have no parent). Otherwise, this parent's reference is considered "dangling" after the
299    /// removal (i.e. will point to an incorrect node after the removal), and this removal operation
300    /// would result in an invalid [`MastForest`].
301    ///
302    /// It also returns the map from old node IDs to new node IDs. Any [`MastNodeId`] used in
303    /// reference to the old [`MastForest`] should be remapped using this map.
304    #[cfg(test)]
305    fn remove_nodes(
306        &mut self,
307        nodes_to_remove: &BTreeSet<MastNodeId>,
308    ) -> BTreeMap<MastNodeId, MastNodeId> {
309        if nodes_to_remove.is_empty() {
310            return BTreeMap::new();
311        }
312
313        self.assert_nodes_to_remove_are_orphaned(nodes_to_remove);
314
315        let old_nodes = core::mem::replace(&mut self.nodes, IndexVec::new());
316        let old_root_ids = core::mem::take(&mut self.roots);
317        let (retained_nodes, id_remappings) = remove_nodes(old_nodes.into_inner(), nodes_to_remove);
318
319        self.remap_and_add_nodes(retained_nodes, &id_remappings);
320        self.remap_and_add_roots(old_root_ids, &id_remappings);
321
322        self.commitment = self.compute_mast_forest_commitment();
323
324        id_remappings
325    }
326
327    /// Merges all `forests` into a new [`MastForest`].
328    ///
329    /// Merging two forests means combining all their constituent parts, i.e. [`MastNode`]s and
330    /// roots. During this process, any duplicate or unreachable nodes are removed. Additionally,
331    /// [`MastNodeId`]s of nodes may change and references to them are remapped to their new
332    /// location.
333    ///
334    /// For example, consider this representation of a forest's nodes with all of these nodes being
335    /// roots:
336    ///
337    /// ```text
338    /// [Block(foo), Block(bar)]
339    /// ```
340    ///
341    /// If we merge another forest into it:
342    ///
343    /// ```text
344    /// [Block(bar), Call(0)]
345    /// ```
346    ///
347    /// then we would expect this forest:
348    ///
349    /// ```text
350    /// [Block(foo), Block(bar), Call(1)]
351    /// ```
352    ///
353    /// - The `Call` to the `bar` block was remapped to its new index (now 1, previously 0).
354    /// - The `Block(bar)` was deduplicated any only exists once in the merged forest.
355    ///
356    /// The function also returns a vector of [`MastForestRootMap`]s, whose length equals the number
357    /// of passed `forests`. The indices in the vector correspond to the ones in `forests`. The map
358    /// of a given forest contains the new locations of its roots in the merged forest. To
359    /// illustrate, the above example would return a vector of two maps:
360    ///
361    /// ```text
362    /// vec![{0 -> 0, 1 -> 1}
363    ///      {0 -> 1, 1 -> 2}]
364    /// ```
365    ///
366    /// - The root locations of the original forest are unchanged.
367    /// - For the second forest, the `bar` block has moved from index 0 to index 1 in the merged
368    ///   forest, and the `Call` has moved from index 1 to 2.
369    ///
370    /// If any forest being merged contains an `External(qux)` node and another forest contains a
371    /// node whose digest is `qux`, then the external node will be replaced with the `qux` node,
372    /// which is effectively deduplication.
373    pub fn merge<'forest, F>(
374        forests: impl IntoIterator<Item = F>,
375    ) -> Result<(MastForest, MastForestRootMap), MastForestError>
376    where
377        F: Into<MastForestMergeSource<'forest>>,
378    {
379        let forests = forests.into_iter().map(Into::into).collect::<Vec<_>>();
380        if forests.iter().all(|forest| forest.as_dense().is_some()) {
381            return MastForestMerger::merge(forests.iter().map(|forest| {
382                forest.as_dense().expect("all merge sources were checked as dense")
383            }));
384        }
385
386        MixedMastForestMerger::merge_dense(forests)
387    }
388}
389
390// ------------------------------------------------------------------------------------------------
391/// Helpers
392impl MastForest {
393    #[cfg(test)]
394    fn assert_nodes_to_remove_are_orphaned(&self, nodes_to_remove: &BTreeSet<MastNodeId>) {
395        for (node_idx, node) in self.nodes.iter().enumerate() {
396            let node_id = MastNodeId::new_unchecked(node_idx.try_into().expect("too many nodes"));
397            if nodes_to_remove.contains(&node_id) {
398                continue;
399            }
400
401            node.for_each_child(|child_id| {
402                assert!(
403                    !nodes_to_remove.contains(&child_id),
404                    "cannot remove node {child_id:?}; retained node {node_id:?} references it"
405                );
406            });
407        }
408    }
409
410    /// Adds all provided nodes to the internal set of nodes, remapping all [`MastNodeId`]
411    /// references in those nodes.
412    ///
413    /// # Panics
414    /// - Panics if the internal set of nodes is not empty.
415    #[cfg(test)]
416    fn remap_and_add_nodes(
417        &mut self,
418        nodes_to_add: Vec<MastNode>,
419        id_remappings: &BTreeMap<MastNodeId, MastNodeId>,
420    ) {
421        assert!(self.nodes.is_empty());
422        let node_builders =
423            nodes_to_add.into_iter().map(|node| node.to_builder(self)).collect::<Vec<_>>();
424
425        // Add each node to the new MAST forest, making sure to rewrite any outdated internal
426        // `MastNodeId`s
427        for live_node_builder in node_builders {
428            let node = live_node_builder.remap_children(id_remappings).build_linked().unwrap();
429            self.nodes.push(node).unwrap();
430        }
431    }
432
433    /// Remaps and adds all old root ids to the internal set of roots.
434    ///
435    /// # Panics
436    /// - Panics if the internal set of roots is not empty.
437    #[cfg(test)]
438    fn remap_and_add_roots(
439        &mut self,
440        old_root_ids: Vec<MastNodeId>,
441        id_remappings: &BTreeMap<MastNodeId, MastNodeId>,
442    ) {
443        assert!(self.roots.is_empty());
444
445        for old_root_id in old_root_ids {
446            if let Some(new_root_id) = id_remappings.get(&old_root_id).copied() {
447                self.make_root(new_root_id);
448            }
449        }
450    }
451}
452
453/// Returns the set of nodes that are live, as well as the mapping from "old ID" to "new ID" for all
454/// live nodes.
455#[cfg(test)]
456fn remove_nodes(
457    mast_nodes: Vec<MastNode>,
458    nodes_to_remove: &BTreeSet<MastNodeId>,
459) -> (Vec<MastNode>, BTreeMap<MastNodeId, MastNodeId>) {
460    // Note: this allows us to safely use `usize as u32`, guaranteeing that it won't wrap around.
461    assert!(mast_nodes.len() < u32::MAX as usize);
462
463    let mut retained_nodes = Vec::with_capacity(mast_nodes.len());
464    let mut id_remappings = BTreeMap::new();
465
466    for (old_node_index, old_node) in mast_nodes.into_iter().enumerate() {
467        let old_node_id: MastNodeId = MastNodeId(old_node_index as u32);
468
469        if !nodes_to_remove.contains(&old_node_id) {
470            let new_node_id: MastNodeId = MastNodeId(retained_nodes.len() as u32);
471            id_remappings.insert(old_node_id, new_node_id);
472
473            retained_nodes.push(old_node);
474        }
475    }
476
477    (retained_nodes, id_remappings)
478}
479
480fn empty_mast_forest_commitment() -> MastForestCommitment {
481    let interface_commitment = crate::chiplets::hasher::hash_words(&[]);
482    let dependency_commitment = crate::chiplets::hasher::hash_words(&[]);
483    let advice_commitment = AdviceMap::default().commitment();
484    MastForestCommitment::new(interface_commitment, dependency_commitment, advice_commitment)
485}
486
487fn compute_nodes_commitment(
488    nodes: &IndexVec<MastNodeId, MastNode>,
489    node_ids: &[MastNodeId],
490) -> Word {
491    let mut digests: Vec<Word> = node_ids.iter().map(|&id| nodes[id].digest()).collect();
492    digests.sort_unstable();
493    crate::chiplets::hasher::hash_words(&digests)
494}
495
496fn compute_dependency_commitment(nodes: &IndexVec<MastNodeId, MastNode>) -> Word {
497    let mut digests: Vec<Word> = nodes
498        .iter()
499        .filter(|node| node.is_external())
500        .map(MastNodeExt::digest)
501        .collect();
502    digests.sort_unstable();
503    crate::chiplets::hasher::hash_words(&digests)
504}
505
506impl MastForestCommitment {
507    fn new(
508        interface_commitment: Word,
509        dependency_commitment: Word,
510        advice_commitment: Word,
511    ) -> Self {
512        let commitment = crate::chiplets::hasher::hash_words(&[
513            interface_commitment,
514            dependency_commitment,
515            advice_commitment,
516        ]);
517        Self {
518            commitment,
519            interface_commitment,
520            dependency_commitment,
521            advice_commitment,
522        }
523    }
524}
525
526fn compute_mast_forest_commitment(
527    nodes: &IndexVec<MastNodeId, MastNode>,
528    roots: &[MastNodeId],
529    advice_map: &AdviceMap,
530) -> MastForestCommitment {
531    let interface_commitment = compute_nodes_commitment(nodes, roots);
532    let dependency_commitment = compute_dependency_commitment(nodes);
533    let advice_commitment = advice_map.commitment();
534    MastForestCommitment::new(interface_commitment, dependency_commitment, advice_commitment)
535}
536
537// ------------------------------------------------------------------------------------------------
538/// Public accessors
539impl MastForest {
540    /// Returns the [`MastNode`] associated with the provided [`MastNodeId`] if valid, or else
541    /// `None`.
542    ///
543    /// This is the fallible version of indexing (e.g. `mast_forest[node_id]`).
544    #[inline(always)]
545    pub fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
546        self.nodes.get(node_id)
547    }
548
549    /// Returns the [`MastNodeId`] of the procedure associated with a given digest, if any.
550    #[inline(always)]
551    pub fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
552        self.roots.iter().find(|&&root_id| self[root_id].digest() == digest).copied()
553    }
554
555    /// Returns true if a node with the specified ID is a root of a procedure in this MAST forest.
556    pub fn is_procedure_root(&self, node_id: MastNodeId) -> bool {
557        self.roots.contains(&node_id)
558    }
559
560    /// Returns true if a node with the specified ID is a root of a procedure in this MAST forest,
561    /// and the digest of that procedure is `digest`.
562    ///
563    /// This is primarily intended for use in confirming that procedure exports of a package,
564    /// which declare their MAST node and digest, actually exist in the MAST.
565    pub fn is_procedure_root_with_exact_digest(&self, node_id: MastNodeId, digest: Word) -> bool {
566        self.is_procedure_root(node_id) && self[node_id].digest() == digest
567    }
568
569    /// Returns an iterator over the digests of all procedures in this MAST forest.
570    pub fn procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
571        self.roots.iter().map(|&root_id| self[root_id].digest())
572    }
573
574    /// Returns an iterator over the digests of local procedures in this MAST forest.
575    ///
576    /// A local procedure is defined as a procedure which is not a single external node.
577    pub fn local_procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
578        self.roots.iter().filter_map(|&root_id| {
579            let node = &self[root_id];
580            if node.is_external() { None } else { Some(node.digest()) }
581        })
582    }
583
584    /// Returns an iterator over the IDs of the procedures in this MAST forest.
585    pub fn procedure_roots(&self) -> &[MastNodeId] {
586        &self.roots
587    }
588
589    /// Returns the number of procedures in this MAST forest.
590    pub fn num_procedures(&self) -> u32 {
591        self.roots
592            .len()
593            .try_into()
594            .expect("MAST forest contains more than 2^32 procedures.")
595    }
596
597    /// Returns the [Word] representing the content hash of a subset of [`MastNodeId`]s.
598    ///
599    /// # Panics
600    /// This function panics if any `node_ids` is not a node of this forest.
601    pub fn compute_nodes_commitment<'a>(
602        &self,
603        node_ids: impl IntoIterator<Item = &'a MastNodeId>,
604    ) -> Word {
605        let node_ids = node_ids.into_iter().copied().collect::<Vec<_>>();
606        compute_nodes_commitment(&self.nodes, &node_ids)
607    }
608
609    /// Returns the commitment to this MAST forest's public procedure roots.
610    ///
611    /// The commitment is computed as the sequential hash of all procedure root digests after
612    /// sorting them by digest.
613    pub fn interface_commitment(&self) -> Word {
614        self.commitment.interface_commitment
615    }
616
617    /// Returns the commitment to this MAST forest's external dependencies.
618    ///
619    /// The commitment is computed as the sequential hash of all external node digests after
620    /// sorting them by digest.
621    pub fn dependency_commitment(&self) -> Word {
622        self.commitment.dependency_commitment
623    }
624
625    /// Returns the commitment to this MAST forest's advice map.
626    ///
627    /// The commitment is computed over advice entries in key order.
628    pub fn advice_commitment(&self) -> Word {
629        self.commitment.advice_commitment
630    }
631
632    fn compute_mast_forest_commitment(&self) -> MastForestCommitment {
633        compute_mast_forest_commitment(&self.nodes, &self.roots, &self.advice_map)
634    }
635
636    /// Returns the commitment to this MAST forest.
637    ///
638    /// The commitment is computed from the interface, dependency, and advice commitments.
639    pub fn commitment(&self) -> Word {
640        self.commitment.commitment
641    }
642
643    /// Returns the number of nodes in this MAST forest.
644    pub fn num_nodes(&self) -> u32 {
645        self.nodes.len() as u32
646    }
647
648    /// Returns the underlying nodes in this MAST forest.
649    pub fn nodes(&self) -> &[MastNode] {
650        self.nodes.as_slice()
651    }
652
653    pub fn advice_map(&self) -> &AdviceMap {
654        &self.advice_map
655    }
656
657    /// Returns this forest with `advice_map` entries added.
658    pub fn with_advice_map(mut self, advice_map: AdviceMap) -> Self {
659        self.advice_map.extend(advice_map);
660        self.commitment = self.compute_mast_forest_commitment();
661        self
662    }
663
664    // SERIALIZATION
665    // --------------------------------------------------------------------------------------------
666
667    /// Serializes this MastForest with the HASHLESS flag set.
668    ///
669    /// Hashless forest bytes omit rebuildable internal node hashes. External node digests stay on
670    /// the wire because they cannot be rebuilt from local structure. Trusted deserialization
671    /// rejects this flag.
672    ///
673    /// Use this when producing data for untrusted validation.
674    pub fn write_hashless<W: ByteWriter>(&self, target: &mut W) {
675        serialization::write_hashless_into(self, target);
676    }
677
678    /// Returns the exact size in bytes produced by [`Self::write_hashless`] without allocating
679    /// or serializing the forest.
680    ///
681    /// This includes external node digests and omits rebuildable internal node hashes.
682    ///
683    /// # Panics
684    ///
685    /// Panics if the serialized size exceeds [`usize::MAX`].
686    pub fn hashless_size_hint(&self) -> usize {
687        self.serialized_size_hint(true)
688    }
689}
690
691/// Validation methods
692impl MastForest {
693    pub(in crate::mast) fn validate_dense_node_order(&self) -> Result<(), MastForestError> {
694        validate_dense_node_order(&self.nodes)
695    }
696
697    fn validate_basic_block_invariants(&self) -> Result<(), MastForestError> {
698        for (node_id_idx, node) in self.nodes.iter().enumerate() {
699            let node_id =
700                MastNodeId::new_unchecked(node_id_idx.try_into().expect("too many nodes"));
701            if let MastNode::Block(basic_block) = node {
702                basic_block.validate_batch_invariants().map_err(|error_msg| {
703                    MastForestError::InvalidBatchPadding(node_id, error_msg)
704                })?;
705            }
706        }
707
708        Ok(())
709    }
710
711    /// Validates that all BasicBlockNodes in this forest satisfy the core invariants:
712    /// 1. Power-of-two number of groups in each batch
713    /// 2. No operation group ends with an operation requiring an immediate value
714    /// 3. The last operation group in a batch cannot contain operations requiring immediate values
715    /// 4. OpBatch structural consistency (num_groups <= BATCH_SIZE, group size <= GROUP_SIZE,
716    ///    indptr integrity, bounds checking)
717    ///
718    /// This addresses the gap created by PR 2094, where padding NOOPs are now inserted
719    /// at assembly time rather than dynamically during execution, and adds comprehensive
720    /// structural validation to prevent deserialization-time panics.
721    pub fn validate(&self) -> Result<(), MastForestError> {
722        self.validate_basic_block_invariants()?;
723        Ok(())
724    }
725
726    /// Validates that stored node digests match the hashes implied by local structure.
727    ///
728    /// For `External` nodes the digest is accepted as-is because it is externally provided and
729    /// cannot be reconstructed from local structure alone.
730    fn validate_node_hashes(&self) -> Result<(), MastForestError> {
731        let computed_hashes = self.compute_node_hashes()?;
732        for (node_idx, (node, computed_digest)) in
733            self.nodes.iter().zip(computed_hashes).enumerate()
734        {
735            let expected_digest = node.digest();
736            if expected_digest != computed_digest {
737                return Err(MastForestError::HashMismatch {
738                    node_id: MastNodeId::new_unchecked(node_idx as u32),
739                    expected: expected_digest,
740                    computed: computed_digest,
741                });
742            }
743        }
744
745        Ok(())
746    }
747
748    /// Computes node hashes in topological order.
749    ///
750    /// The returned vector is aligned with node indices, so `digests[node_id as usize]` is the
751    /// digest of that node.
752    ///
753    /// For `External` nodes, the existing digest is returned unchanged.
754    ///
755    /// Returns [`MastForestError::ForwardReference`] if nodes are not in topological order.
756    fn compute_node_hashes(&self) -> Result<Vec<Word>, MastForestError> {
757        let mut computed_hashes = Vec::with_capacity(self.nodes.len());
758        for (node_idx, node) in self.nodes.iter().enumerate() {
759            let node_id = MastNodeId::new_unchecked(node_idx as u32);
760            let digest = node.compute_digest(|child_id| {
761                if child_id >= node_id {
762                    return Err(MastForestError::ForwardReference(node_id, child_id));
763                }
764                Ok(computed_hashes[child_id.0 as usize])
765            })?;
766            computed_hashes.push(digest);
767        }
768
769        Ok(computed_hashes)
770    }
771}
772
773// MAST FOREST INDEXING
774// ------------------------------------------------------------------------------------------------
775
776impl Index<MastNodeId> for MastForest {
777    type Output = MastNode;
778
779    #[inline(always)]
780    fn index(&self, node_id: MastNodeId) -> &Self::Output {
781        &self.nodes[node_id]
782    }
783}
784
785// EXECUTABLE MAST FOREST
786// ================================================================================================
787
788/// A MAST forest that can be used as the source of nodes during program execution.
789///
790/// Implemented by both [`MastForest`] (a dense forest containing all nodes) and
791/// [`SparseMastForest`] (a sparse subset of a forest containing only the nodes visited during
792/// some prior execution). The latter preserves the original [`MastNodeId`]s of its source forest,
793/// which allows it to stand in for the dense forest during re-execution.
794pub trait ExecutableMastForest {
795    /// Returns the [`MastNode`] associated with the provided [`MastNodeId`] if present, or else
796    /// `None`.
797    fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode>;
798
799    /// Returns the digest of the node associated with the provided [`MastNodeId`] if present, or
800    /// else `None`.
801    ///
802    /// For dense forests this is equivalent to `get_node_by_id(id).map(|n| n.digest())`. For
803    /// [`SparseMastForest`], it additionally consults the digest-only entries — nodes that were
804    /// referenced (but not entered) during execution and which were therefore stored as digest
805    /// only. Use this method whenever only the digest of a referenced node is needed (e.g. when
806    /// populating the hasher state of a parent's trace row).
807    fn get_digest_by_id(&self, node_id: MastNodeId) -> Option<Word>;
808
809    /// Returns the [`MastNodeId`] of the procedure associated with a given digest, if any.
810    fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId>;
811
812    /// Returns the advice map associated with this forest.
813    fn advice_map(&self) -> &AdviceMap;
814}
815
816impl ExecutableMastForest for MastForest {
817    #[inline(always)]
818    fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
819        MastForest::get_node_by_id(self, node_id)
820    }
821
822    #[inline(always)]
823    fn get_digest_by_id(&self, node_id: MastNodeId) -> Option<Word> {
824        MastForest::get_node_by_id(self, node_id).map(MastNodeExt::digest)
825    }
826
827    #[inline(always)]
828    fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
829        MastForest::find_procedure_root(self, digest)
830    }
831
832    #[inline(always)]
833    fn advice_map(&self) -> &AdviceMap {
834        MastForest::advice_map(self)
835    }
836}
837
838// Blanket impl: an `Arc<T>` is an `ExecutableMastForest` whenever the underlying `T` is, which
839// allows the executor and tracer plumbing to be generic over a forest type while the live
840// (`Arc<MastForest>`) and replay (`Arc<SparseMastForest>`) paths each pick a concrete instance.
841impl<T> Index<MastNodeId> for Arc<T>
842where
843    T: Index<MastNodeId, Output = MastNode> + ?Sized,
844{
845    type Output = MastNode;
846
847    #[inline(always)]
848    fn index(&self, node_id: MastNodeId) -> &Self::Output {
849        &(**self)[node_id]
850    }
851}
852
853impl<T: ExecutableMastForest + ?Sized> ExecutableMastForest for Arc<T> {
854    #[inline(always)]
855    fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
856        T::get_node_by_id(self, node_id)
857    }
858
859    #[inline(always)]
860    fn get_digest_by_id(&self, node_id: MastNodeId) -> Option<Word> {
861        T::get_digest_by_id(self, node_id)
862    }
863
864    #[inline(always)]
865    fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
866        T::find_procedure_root(self, digest)
867    }
868
869    #[inline(always)]
870    fn advice_map(&self) -> &AdviceMap {
871        T::advice_map(self)
872    }
873}
874
875// MAST NODE ID
876// ================================================================================================
877
878/// An opaque handle to a [`MastNode`] in some [`MastForest`]. It is the responsibility of the user
879/// to use a given [`MastNodeId`] with the corresponding [`MastForest`].
880///
881/// Note that the [`MastForest`] does *not* ensure that equal [`MastNode`]s have equal
882/// [`MastNodeId`] handles. Hence, [`MastNodeId`] equality must not be used to test for equality of
883/// the underlying [`MastNode`].
884#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
885#[cfg_attr(
886    all(feature = "arbitrary", test),
887    miden_test_serialization_macros::serialization_test
888)]
889pub struct MastNodeId(u32);
890
891/// Operations that mutate a MAST often produce this mapping between old and new NodeIds.
892pub type Remapping = BTreeMap<MastNodeId, MastNodeId>;
893
894impl MastNodeId {
895    /// Returns a new `MastNodeId` with the provided inner value, or an error if the provided
896    /// `value` is greater than the number of nodes in the forest.
897    ///
898    /// For use in deserialization.
899    pub fn from_u32_safe(
900        value: u32,
901        mast_forest: &MastForest,
902    ) -> Result<Self, DeserializationError> {
903        Self::from_u32_with_node_count(value, mast_forest.nodes.len())
904    }
905
906    /// Returns a new [`MastNodeId`] from the given `value` without checking its validity.
907    pub fn new_unchecked(value: u32) -> Self {
908        Self(value)
909    }
910
911    /// Returns a new [`MastNodeId`] with the provided `id`, or an error if `id` is greater or equal
912    /// to `node_count`. The `node_count` is the total number of nodes in the [`MastForest`] for
913    /// which this ID is being constructed.
914    ///
915    /// This function can be used when deserializing an id whose corresponding node is not yet in
916    /// the forest and [`Self::from_u32_safe`] would fail. For instance, when deserializing the ids
917    /// referenced by the Join node in this forest:
918    ///
919    /// ```text
920    /// [Join(1, 2), Block(foo), Block(bar)]
921    /// ```
922    ///
923    /// Since it is less safe than [`Self::from_u32_safe`] and usually not needed it is not public.
924    pub(super) fn from_u32_with_node_count(
925        id: u32,
926        node_count: usize,
927    ) -> Result<Self, DeserializationError> {
928        if (id as usize) < node_count {
929            Ok(Self(id))
930        } else {
931            Err(DeserializationError::InvalidValue(format!(
932                "Invalid deserialized MAST node ID '{id}', but {node_count} is the number of nodes in the forest",
933            )))
934        }
935    }
936
937    /// Remap the NodeId to its new position using the given [`Remapping`].
938    pub fn remap(&self, remapping: &Remapping) -> Self {
939        *remapping.get(self).unwrap_or(self)
940    }
941}
942
943impl From<u32> for MastNodeId {
944    fn from(value: u32) -> Self {
945        MastNodeId::new_unchecked(value)
946    }
947}
948
949impl Idx for MastNodeId {}
950
951impl From<MastNodeId> for u32 {
952    fn from(value: MastNodeId) -> Self {
953        value.0
954    }
955}
956
957impl Serializable for MastNodeId {
958    fn write_into<W: ByteWriter>(&self, target: &mut W) {
959        Serializable::write_into(&self.0, target);
960    }
961}
962
963impl Deserializable for MastNodeId {
964    fn read_from<R: crate::serde::ByteReader>(
965        source: &mut R,
966    ) -> Result<Self, DeserializationError> {
967        Ok(Self(<u32 as Deserializable>::read_from(source)?))
968    }
969
970    fn min_serialized_size() -> usize {
971        <u32 as Deserializable>::min_serialized_size()
972    }
973}
974
975impl fmt::Display for MastNodeId {
976    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977        write!(f, "MastNodeId({})", self.0)
978    }
979}
980
981#[cfg(any(test, feature = "arbitrary"))]
982impl Arbitrary for MastNodeId {
983    type Parameters = ();
984
985    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
986        use proptest::prelude::*;
987        any::<u32>().prop_map(MastNodeId).boxed()
988    }
989
990    type Strategy = BoxedStrategy<Self>;
991}
992
993// ITERATOR
994
995/// Iterates over all the nodes a root depends on, in pre-order. The iteration can include other
996/// roots in the same forest.
997pub struct SubtreeIterator<'a> {
998    forest: &'a MastForest,
999    discovered: Vec<MastNodeId>,
1000    unvisited: Vec<MastNodeId>,
1001}
1002impl<'a> SubtreeIterator<'a> {
1003    pub fn new(root: &MastNodeId, forest: &'a MastForest) -> Self {
1004        let discovered = vec![];
1005        let unvisited = vec![*root];
1006        SubtreeIterator { forest, discovered, unvisited }
1007    }
1008}
1009impl Iterator for SubtreeIterator<'_> {
1010    type Item = MastNodeId;
1011    fn next(&mut self) -> Option<MastNodeId> {
1012        while let Some(id) = self.unvisited.pop() {
1013            let node = &self.forest[id];
1014            if !node.has_children() {
1015                return Some(id);
1016            } else {
1017                self.discovered.push(id);
1018                node.append_children_to(&mut self.unvisited);
1019            }
1020        }
1021        self.discovered.pop()
1022    }
1023}
1024
1025/// Derives an error code from an error message by hashing the message and returning the 0th element
1026/// of the resulting [`Word`].
1027pub fn error_code_from_msg(msg: impl AsRef<str>) -> Felt {
1028    // hash the message and return 0th felt of the resulting Word
1029    hash_string_to_word(msg.as_ref())[0]
1030}
1031
1032// MAST FOREST ERROR
1033// ================================================================================================
1034
1035/// Represents the types of errors that can occur when dealing with MAST forest.
1036#[derive(Debug, thiserror::Error, PartialEq, Eq)]
1037pub enum MastForestError {
1038    #[error("MAST forest node count exceeds the maximum of {} nodes", MastForest::MAX_NODES)]
1039    TooManyNodes,
1040    #[error("node id {0} is greater than or equal to forest length {1}")]
1041    NodeIdOverflow(MastNodeId, usize),
1042    #[error("basic block cannot be created from an empty list of operations")]
1043    EmptyBasicBlock,
1044    #[error("advice map key {0} already exists when merging forests")]
1045    AdviceMapKeyCollisionOnMerge(Word),
1046    #[error("sparse MAST merge cannot retain advice map entries")]
1047    AdviceMapNotSupportedInSparseMerge,
1048    #[error("dense MAST merge requires full node data for {0:?}")]
1049    MissingNodeOnDenseMerge(MastNodeId),
1050    #[error("MAST merge requires node data or a digest for procedure root {0:?}")]
1051    MissingRootOnMerge(MastNodeId),
1052    #[error("node {0:?} is not a procedure root in the source MAST forest")]
1053    NotAProcedureRoot(MastNodeId),
1054    #[error("external node digest {0} resolves to conflicting full nodes")]
1055    ConflictingNodeDigestOnMerge(Word),
1056    #[error("cyclic dependency encountered while merging node {0:?}")]
1057    CyclicDependencyOnMerge(MastNodeId),
1058    #[error("digest is required for deserialization")]
1059    DigestRequiredForDeserialization,
1060    #[error("invalid batch in basic block node {0:?}: {1}")]
1061    InvalidBatchPadding(MastNodeId, String),
1062    #[error("invalid node order at {node_id:?}: {reason}")]
1063    InvalidNodeOrder { node_id: MastNodeId, reason: String },
1064    #[error(
1065        "node {0:?} references child {1:?} which comes after it in the forest (forward reference)"
1066    )]
1067    ForwardReference(MastNodeId, MastNodeId),
1068    #[error("hash mismatch for node {node_id:?}: expected {expected:?}, computed {computed:?}")]
1069    HashMismatch {
1070        node_id: MastNodeId,
1071        expected: Word,
1072        computed: Word,
1073    },
1074    #[error("deserialization failed: {0}")]
1075    Deserialization(DeserializationError),
1076}
1077
1078// Custom serde implementation for MastForest delegates to the binary serialization format.