Skip to main content

miden_core/mast/node/
dyn_node.rs

1use alloc::{boxed::Box, vec::Vec};
2use core::fmt;
3
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7use super::{MastForestContributor, MastNodeExt};
8#[cfg(debug_assertions)]
9use crate::mast::MastNode;
10use crate::{
11    Felt, Word,
12    mast::{
13        DecoratorId, DecoratorStore, MastForest, MastForestError, MastNodeFingerprint, MastNodeId,
14    },
15    operations::opcodes,
16    prettier::{Document, PrettyPrint, const_text, nl},
17    utils::LookupByIdx,
18};
19
20// DYN NODE
21// ================================================================================================
22
23/// A Dyn node specifies that the node to be executed next is defined dynamically via the stack.
24#[derive(Debug, Clone, PartialEq, Eq)]
25#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
26#[cfg_attr(all(feature = "arbitrary", test), miden_test_serde_macros::serde_test)]
27pub struct DynNode {
28    is_dyncall: bool,
29    digest: Word,
30    decorator_store: DecoratorStore,
31}
32
33/// Constants
34impl DynNode {
35    /// The domain of the Dyn block (used for control block hashing).
36    pub const DYN_DOMAIN: Felt = Felt::new(opcodes::DYN as u64);
37
38    /// The domain of the Dyncall block (used for control block hashing).
39    pub const DYNCALL_DOMAIN: Felt = Felt::new(opcodes::DYNCALL as u64);
40}
41
42/// Default digest constants
43impl DynNode {
44    /// The default digest for a DynNode representing a dyncall operation.
45    pub const DYNCALL_DEFAULT_DIGEST: Word = Word::new([
46        Felt::new(14319792288905293245),
47        Felt::new(11465345153771181037),
48        Felt::new(16104169334207009019),
49        Felt::new(2750797734633655770),
50    ]);
51
52    /// The default digest for a DynNode representing a dynexec operation.
53    pub const DYN_DEFAULT_DIGEST: Word = Word::new([
54        Felt::new(13210061556570014836),
55        Felt::new(16003296542960478536),
56        Felt::new(6732564319544917702),
57        Felt::new(16687523027086140644),
58    ]);
59}
60
61/// Public accessors
62impl DynNode {
63    /// Returns true if the [`DynNode`] represents a dyncall operation, and false for dynexec.
64    pub fn is_dyncall(&self) -> bool {
65        self.is_dyncall
66    }
67
68    /// Returns the domain of this dyn node.
69    pub fn domain(&self) -> Felt {
70        if self.is_dyncall() {
71            Self::DYNCALL_DOMAIN
72        } else {
73            Self::DYN_DOMAIN
74        }
75    }
76}
77
78// PRETTY PRINTING
79// ================================================================================================
80
81impl DynNode {
82    pub(super) fn to_display<'a>(&'a self, mast_forest: &'a MastForest) -> impl fmt::Display + 'a {
83        DynNodePrettyPrint { node: self, mast_forest }
84    }
85
86    pub(super) fn to_pretty_print<'a>(
87        &'a self,
88        mast_forest: &'a MastForest,
89    ) -> impl PrettyPrint + 'a {
90        DynNodePrettyPrint { node: self, mast_forest }
91    }
92}
93
94struct DynNodePrettyPrint<'a> {
95    node: &'a DynNode,
96    mast_forest: &'a MastForest,
97}
98
99impl DynNodePrettyPrint<'_> {
100    /// Concatenates the provided decorators in a single line. If the list of decorators is not
101    /// empty, prepends `prepend` and appends `append` to the decorator document.
102    fn concatenate_decorators(
103        &self,
104        decorator_ids: &[DecoratorId],
105        prepend: Document,
106        append: Document,
107    ) -> Document {
108        let decorators = decorator_ids
109            .iter()
110            .map(|&decorator_id| self.mast_forest[decorator_id].render())
111            .reduce(|acc, doc| acc + const_text(" ") + doc)
112            .unwrap_or_default();
113
114        if decorators.is_empty() {
115            decorators
116        } else {
117            prepend + decorators + append
118        }
119    }
120
121    fn single_line_pre_decorators(&self) -> Document {
122        self.concatenate_decorators(
123            self.node.before_enter(self.mast_forest),
124            Document::Empty,
125            const_text(" "),
126        )
127    }
128
129    fn single_line_post_decorators(&self) -> Document {
130        self.concatenate_decorators(
131            self.node.after_exit(self.mast_forest),
132            const_text(" "),
133            Document::Empty,
134        )
135    }
136
137    fn multi_line_pre_decorators(&self) -> Document {
138        self.concatenate_decorators(self.node.before_enter(self.mast_forest), Document::Empty, nl())
139    }
140
141    fn multi_line_post_decorators(&self) -> Document {
142        self.concatenate_decorators(self.node.after_exit(self.mast_forest), nl(), Document::Empty)
143    }
144}
145
146impl crate::prettier::PrettyPrint for DynNodePrettyPrint<'_> {
147    fn render(&self) -> crate::prettier::Document {
148        let dyn_text = if self.node.is_dyncall() {
149            const_text("dyncall")
150        } else {
151            const_text("dyn")
152        };
153
154        let single_line = self.single_line_pre_decorators()
155            + dyn_text.clone()
156            + self.single_line_post_decorators();
157        let multi_line =
158            self.multi_line_pre_decorators() + dyn_text + self.multi_line_post_decorators();
159
160        single_line | multi_line
161    }
162}
163
164impl fmt::Display for DynNodePrettyPrint<'_> {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        self.pretty_print(f)
167    }
168}
169
170// MAST NODE TRAIT IMPLEMENTATION
171// ================================================================================================
172
173impl MastNodeExt for DynNode {
174    /// Returns a commitment to a Dyn node.
175    fn digest(&self) -> Word {
176        self.digest
177    }
178
179    /// Returns the decorators to be executed before this node is executed.
180    fn before_enter<'a>(&'a self, forest: &'a MastForest) -> &'a [DecoratorId] {
181        #[cfg(debug_assertions)]
182        self.verify_node_in_forest(forest);
183        self.decorator_store.before_enter(forest)
184    }
185
186    /// Returns the decorators to be executed after this node is executed.
187    fn after_exit<'a>(&'a self, forest: &'a MastForest) -> &'a [DecoratorId] {
188        #[cfg(debug_assertions)]
189        self.verify_node_in_forest(forest);
190        self.decorator_store.after_exit(forest)
191    }
192
193    fn to_display<'a>(&'a self, mast_forest: &'a MastForest) -> Box<dyn fmt::Display + 'a> {
194        Box::new(DynNode::to_display(self, mast_forest))
195    }
196
197    fn to_pretty_print<'a>(&'a self, mast_forest: &'a MastForest) -> Box<dyn PrettyPrint + 'a> {
198        Box::new(DynNode::to_pretty_print(self, mast_forest))
199    }
200
201    fn has_children(&self) -> bool {
202        false
203    }
204
205    fn append_children_to(&self, _target: &mut Vec<MastNodeId>) {
206        // No children for dyn nodes
207    }
208
209    fn for_each_child<F>(&self, _f: F)
210    where
211        F: FnMut(MastNodeId),
212    {
213        // DynNode has no children
214    }
215
216    fn domain(&self) -> Felt {
217        self.domain()
218    }
219
220    type Builder = DynNodeBuilder;
221
222    fn to_builder(self, forest: &MastForest) -> Self::Builder {
223        // Extract decorators from decorator_store if in Owned state
224        match self.decorator_store {
225            DecoratorStore::Owned { before_enter, after_exit, .. } => {
226                let mut builder = if self.is_dyncall {
227                    DynNodeBuilder::new_dyncall()
228                } else {
229                    DynNodeBuilder::new_dyn()
230                };
231                builder = builder.with_before_enter(before_enter).with_after_exit(after_exit);
232                builder
233            },
234            DecoratorStore::Linked { id } => {
235                // Extract decorators from forest storage when in Linked state
236                let before_enter = forest.before_enter_decorators(id).to_vec();
237                let after_exit = forest.after_exit_decorators(id).to_vec();
238                let mut builder = if self.is_dyncall {
239                    DynNodeBuilder::new_dyncall()
240                } else {
241                    DynNodeBuilder::new_dyn()
242                };
243                builder = builder.with_before_enter(before_enter).with_after_exit(after_exit);
244                builder
245            },
246        }
247    }
248
249    #[cfg(debug_assertions)]
250    fn verify_node_in_forest(&self, forest: &MastForest) {
251        if let Some(id) = self.decorator_store.linked_id() {
252            // Verify that this node is the one stored at the given ID in the forest
253            let self_ptr = self as *const Self;
254            let forest_node = &forest.nodes[id];
255            let forest_node_ptr = match forest_node {
256                MastNode::Dyn(dyn_node) => dyn_node as *const DynNode as *const (),
257                _ => panic!("Node type mismatch at {:?}", id),
258            };
259            let self_as_void = self_ptr as *const ();
260            debug_assert_eq!(
261                self_as_void, forest_node_ptr,
262                "Node pointer mismatch: expected node at {:?} to be self",
263                id
264            );
265        }
266    }
267}
268
269// ARBITRARY IMPLEMENTATION
270// ================================================================================================
271
272#[cfg(all(feature = "arbitrary", test))]
273impl proptest::prelude::Arbitrary for DynNode {
274    type Parameters = ();
275
276    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
277        use proptest::prelude::*;
278
279        // Generate whether it's a dyncall or dynexec
280        any::<bool>()
281            .prop_map(|is_dyncall| {
282                if is_dyncall {
283                    DynNodeBuilder::new_dyncall().build()
284                } else {
285                    DynNodeBuilder::new_dyn().build()
286                }
287            })
288            .no_shrink()  // Pure random values, no meaningful shrinking pattern
289            .boxed()
290    }
291
292    type Strategy = proptest::prelude::BoxedStrategy<Self>;
293}
294
295// ------------------------------------------------------------------------------------------------
296/// Builder for creating [`DynNode`] instances with decorators.
297#[derive(Debug)]
298pub struct DynNodeBuilder {
299    is_dyncall: bool,
300    before_enter: Vec<DecoratorId>,
301    after_exit: Vec<DecoratorId>,
302    digest: Option<Word>,
303}
304
305impl DynNodeBuilder {
306    /// Creates a new builder for a DynNode representing a dynexec operation.
307    pub fn new_dyn() -> Self {
308        Self {
309            is_dyncall: false,
310            before_enter: Vec::new(),
311            after_exit: Vec::new(),
312            digest: None,
313        }
314    }
315
316    /// Creates a new builder for a DynNode representing a dyncall operation.
317    pub fn new_dyncall() -> Self {
318        Self {
319            is_dyncall: true,
320            before_enter: Vec::new(),
321            after_exit: Vec::new(),
322            digest: None,
323        }
324    }
325
326    /// Builds the DynNode with the specified decorators.
327    pub fn build(self) -> DynNode {
328        // Use the forced digest if provided, otherwise use the default digest
329        let digest = if let Some(forced_digest) = self.digest {
330            forced_digest
331        } else if self.is_dyncall {
332            DynNode::DYNCALL_DEFAULT_DIGEST
333        } else {
334            DynNode::DYN_DEFAULT_DIGEST
335        };
336
337        DynNode {
338            is_dyncall: self.is_dyncall,
339            digest,
340            decorator_store: DecoratorStore::new_owned_with_decorators(
341                self.before_enter,
342                self.after_exit,
343            ),
344        }
345    }
346}
347
348impl MastForestContributor for DynNodeBuilder {
349    fn add_to_forest(self, forest: &mut MastForest) -> Result<MastNodeId, MastForestError> {
350        // Use the forced digest if provided, otherwise use the default digest
351        let digest = if let Some(forced_digest) = self.digest {
352            forced_digest
353        } else if self.is_dyncall {
354            DynNode::DYNCALL_DEFAULT_DIGEST
355        } else {
356            DynNode::DYN_DEFAULT_DIGEST
357        };
358
359        // Determine the node ID that will be assigned
360        let future_node_id = MastNodeId::new_unchecked(forest.nodes.len() as u32);
361
362        // Store node-level decorators in the centralized NodeToDecoratorIds for efficient access
363        forest.register_node_decorators(future_node_id, &self.before_enter, &self.after_exit);
364
365        // Create the node in the forest with Linked variant from the start
366        // Move the data directly without intermediate cloning
367        let node_id = forest
368            .nodes
369            .push(
370                DynNode {
371                    is_dyncall: self.is_dyncall,
372                    digest,
373                    decorator_store: DecoratorStore::Linked { id: future_node_id },
374                }
375                .into(),
376            )
377            .map_err(|_| MastForestError::TooManyNodes)?;
378
379        Ok(node_id)
380    }
381
382    fn fingerprint_for_node(
383        &self,
384        forest: &MastForest,
385        _hash_by_node_id: &impl LookupByIdx<MastNodeId, MastNodeFingerprint>,
386    ) -> Result<MastNodeFingerprint, MastForestError> {
387        // DynNode has no children, so we don't need hash_by_node_id
388        // Use the fingerprint_from_parts helper function with empty children array
389        crate::mast::node_fingerprint::fingerprint_from_parts(
390            forest,
391            _hash_by_node_id,
392            &self.before_enter,
393            &self.after_exit,
394            &[], // DynNode has no children
395            // Use the forced digest if available, otherwise use the default digest values
396            if let Some(forced_digest) = self.digest {
397                forced_digest
398            } else if self.is_dyncall {
399                DynNode::DYNCALL_DEFAULT_DIGEST
400            } else {
401                DynNode::DYN_DEFAULT_DIGEST
402            },
403        )
404    }
405
406    fn remap_children(self, _remapping: &impl LookupByIdx<MastNodeId, MastNodeId>) -> Self {
407        // DynNode has no children to remap, but preserve the digest
408        self
409    }
410
411    fn with_before_enter(mut self, decorators: impl Into<Vec<DecoratorId>>) -> Self {
412        self.before_enter = decorators.into();
413        self
414    }
415
416    fn with_after_exit(mut self, decorators: impl Into<Vec<DecoratorId>>) -> Self {
417        self.after_exit = decorators.into();
418        self
419    }
420
421    fn append_before_enter(&mut self, decorators: impl IntoIterator<Item = DecoratorId>) {
422        self.before_enter.extend(decorators);
423    }
424
425    fn append_after_exit(&mut self, decorators: impl IntoIterator<Item = DecoratorId>) {
426        self.after_exit.extend(decorators);
427    }
428
429    fn with_digest(mut self, digest: crate::Word) -> Self {
430        self.digest = Some(digest);
431        self
432    }
433}
434
435impl DynNodeBuilder {
436    /// Add this node to a forest using relaxed validation.
437    ///
438    /// This method is used during deserialization where nodes may reference child nodes
439    /// that haven't been added to the forest yet. The child node IDs have already been
440    /// validated against the expected final node count during the `try_into_mast_node_builder`
441    /// step, so we can safely skip validation here.
442    ///
443    /// Note: This is not part of the `MastForestContributor` trait because it's only
444    /// intended for internal use during deserialization.
445    pub(in crate::mast) fn add_to_forest_relaxed(
446        self,
447        forest: &mut MastForest,
448    ) -> Result<MastNodeId, MastForestError> {
449        // Use the forced digest if provided, otherwise use the default digest
450        let digest = if let Some(forced_digest) = self.digest {
451            forced_digest
452        } else if self.is_dyncall {
453            DynNode::DYNCALL_DEFAULT_DIGEST
454        } else {
455            DynNode::DYN_DEFAULT_DIGEST
456        };
457
458        // Determine the node ID that will be assigned
459        let future_node_id = MastNodeId::new_unchecked(forest.nodes.len() as u32);
460
461        // Create the node in the forest with Linked variant from the start
462        // Note: Decorators are already in forest.debug_info from deserialization
463        // Move the data directly without intermediate cloning
464        let node_id = forest
465            .nodes
466            .push(
467                DynNode {
468                    is_dyncall: self.is_dyncall,
469                    digest,
470                    decorator_store: DecoratorStore::Linked { id: future_node_id },
471                }
472                .into(),
473            )
474            .map_err(|_| MastForestError::TooManyNodes)?;
475
476        Ok(node_id)
477    }
478}
479
480#[cfg(any(test, feature = "arbitrary"))]
481impl proptest::prelude::Arbitrary for DynNodeBuilder {
482    type Parameters = DynNodeBuilderParams;
483    type Strategy = proptest::strategy::BoxedStrategy<Self>;
484
485    fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
486        use proptest::prelude::*;
487
488        (
489            any::<bool>(),
490            proptest::collection::vec(
491                super::arbitrary::decorator_id_strategy(params.max_decorator_id_u32),
492                0..=params.max_decorators,
493            ),
494            proptest::collection::vec(
495                super::arbitrary::decorator_id_strategy(params.max_decorator_id_u32),
496                0..=params.max_decorators,
497            ),
498        )
499            .prop_map(|(is_dyncall, before_enter, after_exit)| {
500                let builder = if is_dyncall {
501                    Self::new_dyncall()
502                } else {
503                    Self::new_dyn()
504                };
505                builder.with_before_enter(before_enter).with_after_exit(after_exit)
506            })
507            .boxed()
508    }
509}
510
511/// Parameters for generating DynNodeBuilder instances
512#[cfg(any(test, feature = "arbitrary"))]
513#[derive(Clone, Debug)]
514pub struct DynNodeBuilderParams {
515    pub max_decorators: usize,
516    pub max_decorator_id_u32: u32,
517}
518
519#[cfg(any(test, feature = "arbitrary"))]
520impl Default for DynNodeBuilderParams {
521    fn default() -> Self {
522        Self {
523            max_decorators: 4,
524            max_decorator_id_u32: 10,
525        }
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use miden_crypto::hash::poseidon2::Poseidon2;
532
533    use super::*;
534
535    /// Ensures that the hash of `DynNode` is indeed the hash of 2 empty words, in the `DynNode`
536    /// domain.
537    #[test]
538    pub fn test_dyn_node_digest() {
539        let mut forest = MastForest::new();
540        let dyn_node_id = DynNodeBuilder::new_dyn().add_to_forest(&mut forest).unwrap();
541        let dyn_node = forest.get_node_by_id(dyn_node_id).unwrap().unwrap_dyn();
542        assert_eq!(
543            dyn_node.digest(),
544            Poseidon2::merge_in_domain(&[Word::default(), Word::default()], DynNode::DYN_DOMAIN)
545        );
546
547        let dyncall_node_id = DynNodeBuilder::new_dyncall().add_to_forest(&mut forest).unwrap();
548        let dyncall_node = forest.get_node_by_id(dyncall_node_id).unwrap().unwrap_dyn();
549        assert_eq!(
550            dyncall_node.digest(),
551            Poseidon2::merge_in_domain(
552                &[Word::default(), Word::default()],
553                DynNode::DYNCALL_DOMAIN
554            )
555        );
556    }
557}