Skip to main content

miden_core/deferred/
wire.rs

1//! Portable singleton deferred witnesses and their versioned encoding.
2//!
3//! The versioned encoding stores data chunks, joins, and ordered child-reference pairs. Wire
4//! index zero is implicit TRUE; stored entries have indices starting at one. Canonical witnesses
5//! reference earlier entries and end with the selected root. Decoding checks bounded transport
6//! syntax; [`PrecompileWitness::prepare`] establishes graph integrity and admission.
7
8use alloc::{
9    collections::{BTreeMap, BTreeSet},
10    format,
11    sync::Arc,
12    vec::Vec,
13};
14
15use miden_crypto::hash::eidos::{EidosDomain, EidosFrame};
16
17use super::{
18    DEFERRED_AND_FRAME, DataChunk, DeferredError, DeferredState, Digest,
19    MAX_DEFERRED_WIRE_ELEMENTS, Node, NodeType, PrecompileError, PrecompileLimits,
20    PrecompileRegistry, PrecompileWork, TRUE_DIGEST,
21};
22use crate::{
23    Felt, Word, ZERO,
24    program::domain::DeferredChunksDomain,
25    serde::{
26        BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
27        SliceReader, validate_bounded_len,
28    },
29};
30
31// CONSTANTS
32// ================================================================================================
33
34/// Reserved index for the always-known [`super::TRUE_DIGEST`] / [`super::Node::TRUE`] node.
35const TRUE_INDEX: u32 = 0;
36
37const MAX_WIRE_ENTRIES: usize = MAX_DEFERRED_WIRE_ELEMENTS / EidosFrame::FELT_LEN;
38
39fn reserve_wire_elements(
40    remaining_elements: &mut usize,
41    requested_elements: usize,
42) -> Result<(), DeserializationError> {
43    *remaining_elements = remaining_elements.checked_sub(requested_elements).ok_or_else(|| {
44        DeserializationError::InvalidValue(format!(
45            "deferred wire exceeds the {MAX_DEFERRED_WIRE_ELEMENTS} element limit"
46        ))
47    })?;
48    Ok(())
49}
50
51fn reserve_wire_payload(
52    remaining_elements: &mut usize,
53    payload_count: usize,
54) -> Result<(), DeserializationError> {
55    let payload_elements =
56        payload_count.checked_mul(Node::DATA_CHUNK_FELT_LEN).ok_or_else(|| {
57            DeserializationError::InvalidValue("deferred wire element count overflow".into())
58        })?;
59    reserve_wire_elements(remaining_elements, payload_elements)
60}
61
62// WIRE ENTRY
63// ================================================================================================
64
65/// One untrusted deferred DAG wire entry.
66///
67/// Wire index 0 is implicit TRUE. `entries[i]` has wire index `i + 1`. Preparation requires
68/// structural children to reference `TRUE_INDEX` or an earlier entry. Pair-list pairs store
69/// structural child references in payload order.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum WireEntry {
72    /// Raw data payload interpreted by the frame's precompile.
73    ///
74    /// The payload requires at least one chunk. A frame's precompile may assign value semantics to
75    /// a one-chunk payload, but the wire shape itself does not.
76    Data {
77        frame: EidosFrame,
78        chunks: Vec<DataChunk>,
79    },
80    /// Two child references resolved against `TRUE_INDEX` or earlier wire indices.
81    Join { frame: EidosFrame, lhs: u32, rhs: u32 },
82    /// Raw structural child-reference pairs, with at least one pair.
83    PairList {
84        frame: EidosFrame,
85        pairs: Vec<(u32, u32)>,
86    },
87}
88
89impl WireEntry {
90    // An empty Data/PairList is transport-valid but rejected during preparation.
91    fn min_serialized_size() -> usize {
92        1 + Word::min_serialized_size() + usize::min_serialized_size()
93    }
94}
95
96// PORTABLE WITNESS
97// ================================================================================================
98
99/// Bounded, untrusted portable entries for one deferred execution obligation.
100///
101/// Construction and decoding check transport syntax and allocation bounds. Call [`Self::prepare`]
102/// before native or STARK-backed evaluation.
103#[derive(Debug, Clone, PartialEq, Eq)]
104#[cfg_attr(
105    all(feature = "arbitrary", test),
106    miden_test_serialization_macros::serialization_test
107)]
108pub struct PrecompileWitness {
109    entries: Vec<WireEntry>,
110}
111
112impl PrecompileWitness {
113    /// Version of the standalone singleton witness encoding. Other versions are rejected.
114    pub const WIRE_VERSION: u8 = 2;
115
116    /// Creates bounded portable entries without hashing or validating their graph.
117    pub fn from_entries(entries: Vec<WireEntry>) -> Result<Self, IntegrityError> {
118        let wire = Self { entries };
119        wire.validate_element_limit()?;
120        Ok(wire)
121    }
122
123    /// Validates and admits this graph under `registry` and `verification_limits`.
124    ///
125    /// Consumes the entries, checks registry tags, payload shapes, backward references, and
126    /// canonical child-first order, and rejects duplicate commitments and unreachable entries.
127    /// Each node's declared work is charged before computing its commitment, which is hashed once.
128    /// The final entry establishes the non-TRUE root exposed by [`PreparedWitness::root`]; callers
129    /// must bind that root to the authenticated execution root before accepting the result as
130    /// evidence for that execution.
131    /// Preparation does not evaluate precompile semantics or establish assertion truth.
132    ///
133    /// Callers retaining the portable witness must clone it explicitly.
134    pub fn prepare(
135        self,
136        registry: Arc<PrecompileRegistry>,
137        verification_limits: &PrecompileLimits,
138    ) -> Result<PreparedWitness, PreparationError> {
139        if self.entries.is_empty() {
140            return Err(IntegrityError::InvalidStructure.into());
141        }
142        let mut indices = BTreeMap::new();
143        let mut nodes: Vec<PreparedNode> = Vec::with_capacity(self.entries.len());
144        let mut work = PrecompileWork::default();
145        indices.insert(TRUE_DIGEST, 0);
146
147        for entry in self.entries {
148            let child = |index: u32| match index {
149                TRUE_INDEX => Ok(TRUE_DIGEST),
150                index => nodes
151                    .get(index as usize - 1)
152                    .map(PreparedNode::digest)
153                    .ok_or(IntegrityError::InvalidStructure),
154            };
155            let node = match entry {
156                WireEntry::Data { frame, chunks } => {
157                    if frame.domain() == DeferredChunksDomain::TAG {
158                        if Node::chunks_frame_for_len(chunks.len())
159                            .map_err(|_| IntegrityError::InvalidStructure)?
160                            != frame
161                        {
162                            return Err(IntegrityError::InvalidStructure.into());
163                        }
164                        Node::chunks(chunks)
165                    } else {
166                        Node::try_data(frame, chunks)
167                    }
168                },
169                WireEntry::Join { frame, lhs, rhs } => {
170                    let (lhs, rhs) = (child(lhs)?, child(rhs)?);
171                    if frame == DEFERRED_AND_FRAME {
172                        Ok(Node::and(lhs, rhs))
173                    } else {
174                        Node::join(frame, lhs, rhs)
175                    }
176                },
177                WireEntry::PairList { frame, pairs } => {
178                    let pairs = pairs
179                        .into_iter()
180                        .map(|(lhs, rhs)| Ok((child(lhs)?, child(rhs)?)))
181                        .collect::<Result<Vec<_>, IntegrityError>>()?;
182                    Node::try_pair_list(frame, pairs)
183                },
184            }
185            .map_err(|_| IntegrityError::InvalidStructure)?;
186
187            registry.validate_node(&node)?;
188            work.charge_node(&node, &registry, verification_limits)?;
189            let prepared = PreparedNode::new(node);
190            let digest = prepared.digest();
191            if indices.insert(digest, nodes.len() + 1).is_some() {
192                return Err(IntegrityError::InvalidStructure.into());
193            }
194            nodes.push(prepared);
195        }
196
197        Self::validate_canonical_order(&nodes, &indices)?;
198        let root = nodes.last().expect("the witness is nonempty").digest();
199        if root == TRUE_DIGEST {
200            return Err(IntegrityError::InvalidStructure.into());
201        }
202
203        Ok(PreparedWitness { registry, nodes, root, work })
204    }
205
206    /// Returns the bounded, untrusted wire entries.
207    ///
208    /// Slice entry `entries[i]` has wire index `i + 1`. Wire index zero denotes implicit TRUE
209    /// and has no entry in this slice.
210    pub fn entries(&self) -> &[WireEntry] {
211        &self.entries
212    }
213
214    fn validate_canonical_order(
215        nodes: &[PreparedNode],
216        indices: &BTreeMap<Digest, usize>,
217    ) -> Result<(), IntegrityError> {
218        // The same left-to-right DFS used by the exporter must emit exactly the supplied stream.
219        // Backward references make this iterative traversal acyclic, including for shared graphs.
220        // Wire index 0 denotes implicit TRUE; stored nodes have indices 1..=nodes.len().
221        // Track visits by wire index, leaving seen[0] unused.
222        let mut seen = alloc::vec![false; nodes.len() + 1];
223        let mut pending = alloc::vec![(nodes.len(), false)];
224        let mut next_index = 1;
225        while let Some((index, emit)) = pending.pop() {
226            if index == 0 {
227                continue;
228            }
229            if emit {
230                if index != next_index {
231                    return Err(IntegrityError::InvalidStructure);
232                }
233                next_index += 1;
234            } else if !core::mem::replace(&mut seen[index], true) {
235                pending.push((index, true));
236                pending.extend(
237                    nodes[index - 1].node().children().rev().map(|child| (indices[&child], false)),
238                );
239            }
240        }
241        if next_index != nodes.len() + 1 {
242            return Err(IntegrityError::InvalidStructure);
243        }
244        Ok(())
245    }
246
247    /// Exports and admits the graph reachable from `root` without serializing through bytes.
248    pub(crate) fn from_state(
249        state: &DeferredState,
250        root: Digest,
251        verification_limits: &PrecompileLimits,
252    ) -> Result<Self, PrecompileError> {
253        if root == TRUE_DIGEST {
254            return Err(PrecompileError::InvalidNode);
255        }
256        let mut build = WireEncoder::default();
257        build.visit_state_digest(state, root, verification_limits)?;
258        Ok(Self { entries: build.entries })
259    }
260
261    fn validate_element_limit(&self) -> Result<(), IntegrityError> {
262        let mut remaining_elements = MAX_DEFERRED_WIRE_ELEMENTS;
263        for entry in &self.entries {
264            let payload_count = match entry {
265                WireEntry::Data { chunks, .. } => chunks.len(),
266                WireEntry::Join { .. } => 1,
267                WireEntry::PairList { pairs, .. } => pairs.len(),
268            };
269            let payload_elements = payload_count
270                .checked_mul(Node::DATA_CHUNK_FELT_LEN)
271                .and_then(|elements| EidosFrame::FELT_LEN.checked_add(elements))
272                .ok_or(IntegrityError::InvalidStructure)?;
273            remaining_elements = remaining_elements.checked_sub(payload_elements).ok_or(
274                IntegrityError::DeferredStateTooLarge {
275                    num_elements: payload_elements,
276                    max: remaining_elements,
277                },
278            )?;
279        }
280        Ok(())
281    }
282}
283
284// PREPARED WITNESS
285// ================================================================================================
286
287/// A hydrated node and the commitment computed during preparation.
288///
289/// Obtained from [`PreparedWitness::into_nodes`]. Fields and construction remain private so
290/// consumers can inspect the checked definition without changing it or its commitment.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub struct PreparedNode {
293    node: Node,
294    digest: Digest,
295}
296
297impl PreparedNode {
298    pub(super) fn new(node: Node) -> Self {
299        let digest = node.digest();
300        Self { node, digest }
301    }
302
303    pub(super) fn into_parts(self) -> (Digest, Node) {
304        (self.digest, self.node)
305    }
306
307    /// Returns the hydrated node.
308    pub const fn node(&self) -> &Node {
309        &self.node
310    }
311
312    /// Returns the node's checked commitment.
313    pub const fn digest(&self) -> Digest {
314        self.digest
315    }
316}
317
318/// A structurally valid, admitted witness ready for native or recording evaluation.
319///
320/// Preparation establishes graph integrity, commitments, and declared work only. It does not
321/// establish semantic validity or assertion truth.
322#[derive(Debug, Clone)]
323pub struct PreparedWitness {
324    registry: Arc<PrecompileRegistry>,
325    nodes: Vec<PreparedNode>,
326    root: Digest,
327    work: PrecompileWork,
328}
329
330impl PreparedWitness {
331    /// Returns the root computed from the prepared graph.
332    pub const fn root(&self) -> Digest {
333        self.root
334    }
335
336    /// Returns the admitted verification workload summary.
337    pub const fn work(&self) -> &PrecompileWork {
338        &self.work
339    }
340
341    /// Consumes this witness and yields its checked nodes in canonical child-first order.
342    ///
343    /// The nodes establish structural validity and admission, not computational validity.
344    pub fn into_nodes(self) -> impl ExactSizeIterator<Item = PreparedNode> {
345        self.nodes.into_iter()
346    }
347
348    /// Consumes and evaluates this witness, succeeding only if its root resolves to
349    /// [`TRUE_DIGEST`].
350    pub fn evaluate(self) -> Result<(), PrecompileError> {
351        let Self { registry, nodes, root: _, work: _ } = self;
352        let mut evaluator = super::state::DeferredEvaluator::new(registry)?;
353        let mut digests = Vec::with_capacity(nodes.len());
354        for prepared in nodes {
355            digests.push(evaluator.insert_node(prepared)?);
356        }
357        let root_digest = digests.pop().ok_or(PrecompileError::MissingNode)?;
358        for digest in digests {
359            evaluator.evaluate_digest(digest)?;
360        }
361        if evaluator.evaluate_digest(root_digest)? != TRUE_DIGEST {
362            return Err(PrecompileError::AssertionFailed);
363        }
364        Ok(())
365    }
366}
367
368/// Failure while turning bounded wire material into a prepared witness.
369#[derive(Debug, Clone, thiserror::Error)]
370pub enum PreparationError {
371    #[error(transparent)]
372    Integrity(#[from] IntegrityError),
373    #[error(transparent)]
374    Precompile(#[from] PrecompileError),
375}
376
377// INTEGRITY ERROR
378// ================================================================================================
379
380/// A portable graph cannot be represented within the structural and resource constraints.
381#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
382pub enum IntegrityError {
383    /// Invalid framework shape, child reference, duplicate, orphan, or canonical entry order.
384    #[error("invalid or non-canonical precompile witness structure")]
385    InvalidStructure,
386    /// The portable entries exceed the hard wire-allocation ceiling.
387    #[error("deferred insertion requires {num_elements} elements but only {max} remain")]
388    DeferredStateTooLarge { num_elements: usize, max: usize },
389}
390
391// WIRE ENCODING
392// ================================================================================================
393
394/// Iterative exporter for the original, root-reachable execution graph.
395#[derive(Default)]
396struct WireEncoder {
397    seen: BTreeSet<Digest>,
398    by_digest: BTreeMap<Digest, u32>,
399    entries: Vec<WireEntry>,
400}
401
402impl WireEncoder {
403    fn visit_state_digest(
404        &mut self,
405        state: &DeferredState,
406        digest: Digest,
407        verification_limits: &PrecompileLimits,
408    ) -> Result<(), PrecompileError> {
409        let mut pending = Vec::new();
410        let mut work = PrecompileWork::default();
411        pending.push(WireEncodeStep::Visit(digest));
412
413        while let Some(step) = pending.pop() {
414            match step {
415                WireEncodeStep::Visit(digest) => self.schedule_digest(
416                    state,
417                    digest,
418                    &mut pending,
419                    &mut work,
420                    verification_limits,
421                )?,
422                WireEncodeStep::Emit(digest, node_type) => {
423                    let entry = self.entry_for_digest(state, digest, node_type)?;
424                    self.push_entry(digest, entry)?;
425                },
426            }
427        }
428
429        Ok(())
430    }
431
432    fn schedule_digest(
433        &mut self,
434        state: &DeferredState,
435        digest: Digest,
436        pending: &mut Vec<WireEncodeStep>,
437        work: &mut PrecompileWork,
438        verification_limits: &PrecompileLimits,
439    ) -> Result<(), PrecompileError> {
440        if digest == TRUE_DIGEST || self.seen.contains(&digest) {
441            return Ok(());
442        }
443
444        let (node_type, node) = self.validated_node(state, digest)?;
445        work.charge_node(node, state.registry(), verification_limits)?;
446        if work.elements() > MAX_DEFERRED_WIRE_ELEMENTS as u64 {
447            return Err(DeferredError::DeferredStateTooLarge {
448                num_elements: usize::try_from(work.elements()).unwrap_or(usize::MAX),
449                max: MAX_DEFERRED_WIRE_ELEMENTS,
450            }
451            .into());
452        }
453        self.seen.insert(digest);
454        pending.push(WireEncodeStep::Emit(digest, node_type));
455
456        match node_type {
457            NodeType::Data => {},
458            NodeType::Join => {
459                let (lhs, rhs) = node.payload().as_join()?;
460                pending.push(WireEncodeStep::Visit(rhs));
461                pending.push(WireEncodeStep::Visit(lhs));
462            },
463            NodeType::PairList => {
464                let pairs = node.payload().as_pair_list()?;
465                for (lhs, rhs) in pairs.iter().rev() {
466                    pending.push(WireEncodeStep::Visit(*rhs));
467                    pending.push(WireEncodeStep::Visit(*lhs));
468                }
469            },
470            NodeType::True => return Err(PrecompileError::InvalidNode),
471        };
472
473        Ok(())
474    }
475
476    fn entry_for_digest(
477        &self,
478        state: &DeferredState,
479        digest: Digest,
480        node_type: NodeType,
481    ) -> Result<WireEntry, PrecompileError> {
482        let node = state.get_node(&digest).ok_or(PrecompileError::MissingNode)?;
483
484        Ok(match node_type {
485            NodeType::Data => WireEntry::Data {
486                frame: node.frame().ok_or(PrecompileError::InvalidNode)?,
487                chunks: node.payload().as_data()?.to_vec(),
488            },
489            NodeType::Join => {
490                let (lhs, rhs) = node.payload().as_join()?;
491                let lhs = self.index_for(lhs)?;
492                let rhs = self.index_for(rhs)?;
493                WireEntry::Join {
494                    frame: node.frame().ok_or(PrecompileError::InvalidNode)?,
495                    lhs,
496                    rhs,
497                }
498            },
499            NodeType::PairList => {
500                let pairs = node.payload().as_pair_list()?;
501                let pairs = pairs
502                    .iter()
503                    .map(|(lhs, rhs)| Ok((self.index_for(*lhs)?, self.index_for(*rhs)?)))
504                    .collect::<Result<Vec<_>, PrecompileError>>()?;
505                WireEntry::PairList {
506                    frame: node.frame().ok_or(PrecompileError::InvalidNode)?,
507                    pairs,
508                }
509            },
510            NodeType::True => return Err(PrecompileError::InvalidNode),
511        })
512    }
513
514    fn validated_node<'a>(
515        &self,
516        state: &'a DeferredState,
517        digest: Digest,
518    ) -> Result<(NodeType, &'a Node), PrecompileError> {
519        let node = state.get_node(&digest).ok_or(PrecompileError::MissingNode)?;
520        let node_type = state.registry().validate_node(node)?;
521        Ok((node_type, node))
522    }
523
524    fn index_for(&self, digest: Digest) -> Result<u32, PrecompileError> {
525        if digest == TRUE_DIGEST {
526            return Ok(TRUE_INDEX);
527        }
528        self.by_digest.get(&digest).copied().ok_or(PrecompileError::MissingNode)
529    }
530
531    fn push_entry(&mut self, digest: Digest, entry: WireEntry) -> Result<(), PrecompileError> {
532        let next_index = self.entries.len().checked_add(1).ok_or(PrecompileError::InvalidNode)?;
533        let next_index = u32::try_from(next_index).map_err(|_| PrecompileError::InvalidNode)?;
534        self.entries.push(entry);
535        self.by_digest.insert(digest, next_index);
536        Ok(())
537    }
538}
539
540enum WireEncodeStep {
541    Visit(Digest),
542    Emit(Digest, NodeType),
543}
544
545// SERIALIZATION
546// ================================================================================================
547
548impl Serializable for WireEntry {
549    fn write_into<W: ByteWriter>(&self, target: &mut W) {
550        match self {
551            Self::Data { frame, chunks } => {
552                target.write_u8(0);
553                frame.as_word().write_into(target);
554                target.write_usize(chunks.len());
555                for chunk in chunks {
556                    for felt in chunk {
557                        felt.write_into(target);
558                    }
559                }
560            },
561            Self::Join { frame, lhs, rhs } => {
562                target.write_u8(1);
563                frame.as_word().write_into(target);
564                target.write_u32(*lhs);
565                target.write_u32(*rhs);
566            },
567            Self::PairList { frame, pairs } => {
568                target.write_u8(2);
569                frame.as_word().write_into(target);
570                target.write_usize(pairs.len());
571                for (lhs, rhs) in pairs {
572                    target.write_u32(*lhs);
573                    target.write_u32(*rhs);
574                }
575            },
576        }
577    }
578}
579
580struct WirePair((u32, u32));
581
582impl Deserializable for WirePair {
583    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
584        Ok(Self((source.read_u32()?, source.read_u32()?)))
585    }
586
587    fn min_serialized_size() -> usize {
588        u32::min_serialized_size() * 2
589    }
590}
591
592struct WireDataChunk(DataChunk);
593
594impl Deserializable for WireDataChunk {
595    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
596        let mut chunk = [ZERO; Node::DATA_CHUNK_FELT_LEN];
597        for felt in &mut chunk {
598            *felt = Felt::read_from(source)?;
599        }
600        Ok(Self(chunk))
601    }
602
603    fn min_serialized_size() -> usize {
604        Node::DATA_CHUNK_FELT_LEN * Felt::min_serialized_size()
605    }
606}
607
608impl Serializable for PrecompileWitness {
609    fn write_into<W: ByteWriter>(&self, target: &mut W) {
610        target.write_u8(Self::WIRE_VERSION);
611        target.write_usize(self.entries.len());
612        for entry in &self.entries {
613            entry.write_into(target);
614        }
615    }
616}
617
618impl Deserializable for PrecompileWitness {
619    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
620        let version = source.read_u8()?;
621        if version != Self::WIRE_VERSION {
622            return Err(DeserializationError::InvalidValue(format!(
623                "unsupported precompile witness version {version} (expected {})",
624                Self::WIRE_VERSION
625            )));
626        }
627        let entry_count =
628            read_len(source, "precompile witness entry", WireEntry::min_serialized_size())?;
629        if entry_count > MAX_WIRE_ENTRIES {
630            return Err(DeserializationError::InvalidValue(format!(
631                "precompile witness contains {entry_count} entries, maximum is {MAX_WIRE_ENTRIES}"
632            )));
633        }
634
635        let mut remaining_elements = MAX_DEFERRED_WIRE_ELEMENTS;
636        let mut entries = Vec::with_capacity(entry_count);
637        for _ in 0..entry_count {
638            entries.push(read_wire_entry(source, &mut remaining_elements)?);
639        }
640        Ok(Self { entries })
641    }
642
643    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
644        let mut reader = BudgetedReader::new(SliceReader::new(bytes), bytes.len());
645        let wire = Self::read_from(&mut reader)?;
646        if reader.has_more_bytes() {
647            return Err(DeserializationError::InvalidValue(
648                "trailing bytes after deferred witness".into(),
649            ));
650        }
651        Ok(wire)
652    }
653
654    fn min_serialized_size() -> usize {
655        1 + usize::min_serialized_size()
656    }
657}
658
659/// Retain the existing vint64 decoder and allocation checks, requiring its shortest encoding.
660fn read_len<R: ByteReader>(
661    source: &mut R,
662    label: &str,
663    min_element_size: usize,
664) -> Result<usize, DeserializationError> {
665    let encoded_len = source.peek_u8()?.trailing_zeros() as usize + 1;
666    let len = source.read_usize()?;
667    // The usize Serializable implementation computes the exact vint64 width without allocating.
668    if encoded_len != len.get_size_hint() {
669        return Err(DeserializationError::InvalidValue(format!("noncanonical {label} length")));
670    }
671    validate_bounded_len(source, label, len, min_element_size)?;
672    Ok(len)
673}
674
675fn read_wire_entry<R: ByteReader>(
676    source: &mut R,
677    remaining_elements: &mut usize,
678) -> Result<WireEntry, DeserializationError> {
679    let discriminant = source.read_u8()?;
680    match discriminant {
681        0 => {
682            reserve_wire_elements(remaining_elements, EidosFrame::FELT_LEN)?;
683            let frame = read_frame(source)?;
684            let chunk_count = read_len(source, "data chunk", WireDataChunk::min_serialized_size())?;
685            reserve_wire_payload(remaining_elements, chunk_count)?;
686            let chunks = source
687                .read_many_iter::<WireDataChunk>(chunk_count)?
688                .map(|chunk| chunk.map(|chunk| chunk.0))
689                .collect::<Result<_, _>>()?;
690            Ok(WireEntry::Data { frame, chunks })
691        },
692        1 => {
693            reserve_wire_elements(
694                remaining_elements,
695                EidosFrame::FELT_LEN + Node::DATA_CHUNK_FELT_LEN,
696            )?;
697            let frame = read_frame(source)?;
698            let lhs = source.read_u32()?;
699            let rhs = source.read_u32()?;
700            Ok(WireEntry::Join { frame, lhs, rhs })
701        },
702        2 => {
703            reserve_wire_elements(remaining_elements, EidosFrame::FELT_LEN)?;
704            let frame = read_frame(source)?;
705            let pair_count = read_len(source, "child pair", WirePair::min_serialized_size())?;
706            reserve_wire_payload(remaining_elements, pair_count)?;
707            let pairs = source
708                .read_many_iter::<WirePair>(pair_count)?
709                .map(|pair| pair.map(|pair| pair.0))
710                .collect::<Result<_, _>>()?;
711            Ok(WireEntry::PairList { frame, pairs })
712        },
713        other => Err(DeserializationError::InvalidValue(format!(
714            "invalid deferred wire entry discriminant: {other}"
715        ))),
716    }
717}
718
719fn read_frame<R: ByteReader>(source: &mut R) -> Result<EidosFrame, DeserializationError> {
720    EidosFrame::from_word(Word::read_from(source)?)
721        .ok_or_else(|| DeserializationError::InvalidValue("invalid deferred Eidos frame".into()))
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use crate::deferred::{
728        PrecompileLimitError, deferred_chunks_frame, precompile::test_precompile_domain_tag,
729    };
730
731    fn felts(seed: u64) -> DataChunk {
732        core::array::from_fn(|i| Felt::new_unchecked(seed + i as u64))
733    }
734
735    fn frame(seed: u8) -> EidosFrame {
736        EidosFrame::new(test_precompile_domain_tag(seed), [u32::from(seed), 0, 0])
737    }
738
739    fn encoded_entries(entries: &[WireEntry]) -> Vec<u8> {
740        let mut bytes = alloc::vec![PrecompileWitness::WIRE_VERSION];
741        bytes.write_usize(entries.len());
742        for entry in entries {
743            entry.write_into(&mut bytes);
744        }
745        bytes
746    }
747
748    fn framework_limits() -> PrecompileLimits {
749        PrecompileLimits::new(MAX_DEFERRED_WIRE_ELEMENTS as u64)
750    }
751
752    fn prepare_framework(witness: PrecompileWitness) -> Result<PreparedWitness, PreparationError> {
753        witness.prepare(Arc::new(PrecompileRegistry::new()), &framework_limits())
754    }
755
756    #[test]
757    fn portable_structure_is_independent_of_operation_support() {
758        let entries = alloc::vec![
759            WireEntry::Data {
760                frame: frame(1),
761                chunks: alloc::vec![felts(10)]
762            },
763            WireEntry::Data {
764                frame: frame(2),
765                chunks: alloc::vec![felts(20), felts(30)]
766            },
767            WireEntry::Join { frame: frame(3), lhs: 1, rhs: 1 },
768            WireEntry::PairList {
769                frame: frame(4),
770                pairs: alloc::vec![(1, 2), (3, 3)]
771            },
772        ];
773        let witness = PrecompileWitness::from_entries(entries).unwrap();
774        let left = Node::value(frame(1), felts(10)).unwrap().digest();
775        let right = Node::try_data(frame(2), alloc::vec![felts(20), felts(30)]).unwrap().digest();
776        let claim = Node::join(frame(3), left, left).unwrap().digest();
777        let expected = Node::try_pair_list(frame(4), alloc::vec![(left, right), (claim, claim)])
778            .unwrap()
779            .digest();
780        assert_ne!(expected, TRUE_DIGEST);
781        assert_eq!(PrecompileWitness::read_from_bytes(&witness.to_bytes()).unwrap(), witness);
782        assert!(matches!(
783            prepare_framework(witness),
784            Err(PreparationError::Precompile(PrecompileError::InvalidNode))
785        ));
786    }
787
788    #[test]
789    fn portable_decode_defers_graph_validation_until_preparation() {
790        let leaf = || WireEntry::Data {
791            frame: deferred_chunks_frame(1),
792            chunks: alloc::vec![felts(10)],
793        };
794        let other = || WireEntry::Data {
795            frame: deferred_chunks_frame(1),
796            chunks: alloc::vec![felts(20)],
797        };
798        let malformed_and = EidosFrame::new(DEFERRED_AND_FRAME.domain(), [1, 0, 0]);
799        let graph_invalid = [
800            Vec::new(),
801            alloc::vec![WireEntry::Data {
802                frame: deferred_chunks_frame(1),
803                chunks: Vec::new()
804            }],
805            alloc::vec![WireEntry::PairList { frame: frame(1), pairs: Vec::new() }],
806            alloc::vec![WireEntry::Data {
807                frame: DEFERRED_AND_FRAME,
808                chunks: alloc::vec![felts(10)]
809            }],
810            alloc::vec![WireEntry::Data {
811                frame: deferred_chunks_frame(2),
812                chunks: alloc::vec![felts(10)]
813            }],
814            alloc::vec![WireEntry::Join {
815                frame: deferred_chunks_frame(1),
816                lhs: 0,
817                rhs: 0
818            }],
819            alloc::vec![WireEntry::Join { frame: malformed_and, lhs: 0, rhs: 0 }],
820            alloc::vec![WireEntry::Join {
821                frame: DEFERRED_AND_FRAME,
822                lhs: 0,
823                rhs: 1
824            }],
825            alloc::vec![
826                leaf(),
827                leaf(),
828                WireEntry::Join {
829                    frame: DEFERRED_AND_FRAME,
830                    lhs: 1,
831                    rhs: 2
832                }
833            ],
834            alloc::vec![leaf(), other()],
835            alloc::vec![
836                leaf(),
837                other(),
838                WireEntry::Join {
839                    frame: DEFERRED_AND_FRAME,
840                    lhs: 2,
841                    rhs: 1
842                }
843            ],
844            alloc::vec![
845                WireEntry::Join {
846                    frame: DEFERRED_AND_FRAME,
847                    lhs: 0,
848                    rhs: 2
849                },
850                WireEntry::Join {
851                    frame: DEFERRED_AND_FRAME,
852                    lhs: 0,
853                    rhs: 0
854                },
855            ],
856            alloc::vec![WireEntry::PairList {
857                frame: frame(1),
858                pairs: alloc::vec![(0, 1)]
859            }],
860        ];
861        for entries in graph_invalid {
862            let bytes = encoded_entries(&entries);
863            let witness = PrecompileWitness::from_entries(entries).unwrap();
864            assert_eq!(PrecompileWitness::read_from_bytes(&bytes).unwrap(), witness);
865            assert!(matches!(
866                prepare_framework(witness),
867                Err(PreparationError::Integrity(IntegrityError::InvalidStructure))
868            ));
869        }
870    }
871
872    #[test]
873    fn export_omits_unreachable_state_and_retains_logged_true() {
874        let mut empty = DeferredState::default();
875        let value = empty.register(Node::chunks(alloc::vec![felts(10)]).unwrap()).unwrap();
876        // Borrowed export is structural and works even when the selected node is not a statement.
877        let witness = empty.witness_for(value, &framework_limits()).unwrap();
878        assert_eq!(
879            witness
880                .prepare(Arc::new(PrecompileRegistry::new()), &framework_limits())
881                .unwrap()
882                .root(),
883            value
884        );
885        assert!(matches!(
886            empty.witness_for(value, &PrecompileLimits::new(0)),
887            Err(PrecompileError::Limit(PrecompileLimitError::Elements { max: 0, .. }))
888        ));
889        assert_eq!(empty.root(), TRUE_DIGEST);
890        assert!(empty.get_node(&value).is_some());
891        for root in [TRUE_DIGEST, Word::new([Felt::from_u32(99); 4])] {
892            assert!(empty.witness_for(root, &framework_limits()).is_err());
893        }
894        assert!(empty.into_witness(&framework_limits()).unwrap().is_none());
895        let mut state = DeferredState::default();
896        state.register(Node::chunks(alloc::vec![felts(10)]).unwrap()).unwrap();
897        state.log_statement(TRUE_DIGEST).unwrap();
898        let root = state.root();
899        let expected_elements = Node::and(TRUE_DIGEST, TRUE_DIGEST).felt_len() as u64;
900        let verification_limits = PrecompileLimits::new(expected_elements);
901        let registry = Arc::new(PrecompileRegistry::new());
902        let witness = state.clone().into_witness(&verification_limits).unwrap().unwrap();
903        assert_eq!(
904            witness.entries(),
905            &[WireEntry::Join {
906                frame: DEFERRED_AND_FRAME,
907                lhs: 0,
908                rhs: 0
909            }]
910        );
911        let prepared = witness
912            .prepare(registry, &verification_limits)
913            .expect("exported work must prepare under the same verification policy");
914        assert_eq!(prepared.root(), root);
915        assert_eq!(prepared.work().nodes(), 1);
916        assert_eq!(prepared.work().elements(), expected_elements);
917        prepared.evaluate().expect("prepared evaluation is semantic only");
918
919        let too_small = verification_limits.with_max_elements(expected_elements - 1);
920        assert!(matches!(
921            state.into_witness(&too_small),
922            Err(PrecompileError::Limit(PrecompileLimitError::Elements {
923                actual,
924                max,
925            })) if actual == expected_elements && max == expected_elements - 1
926        ));
927    }
928
929    #[test]
930    fn deep_shared_graph_exports_and_decodes_without_expansion() {
931        let mut state = DeferredState::default();
932        let mut statement = TRUE_DIGEST;
933        for _ in 0..4_096 {
934            statement = state.register(Node::and(statement, statement)).unwrap();
935        }
936        state.log_statement(statement).unwrap();
937        let root = state.root();
938        let witness = state.into_witness(&framework_limits()).unwrap().unwrap();
939        assert_eq!(witness.entries().len(), 4_097);
940        assert_eq!(PrecompileWitness::from_entries(witness.entries().to_vec()).unwrap(), witness);
941        assert_eq!(PrecompileWitness::read_from_bytes(&witness.to_bytes()).unwrap(), witness);
942        assert_eq!(prepare_framework(witness).unwrap().root(), root);
943    }
944
945    #[test]
946    fn standalone_witness_rejects_legacy_tag_encoding_before_body() {
947        // Version-1 singleton Join with Tag::AND = [1, 0, 0, 0] and two TRUE children.
948        const LEGACY_WITNESS: &[u8] = &[
949            1, 3, 1, // Version, one entry (vint64), Join discriminant.
950            1, 0, 0, 0, 0, 0, 0, 0, // Tag id.
951            0, 0, 0, 0, 0, 0, 0, 0, // Tag arg0.
952            0, 0, 0, 0, 0, 0, 0, 0, // Tag arg1.
953            0, 0, 0, 0, 0, 0, 0, 0, // Tag arg2.
954            0, 0, 0, 0, 0, 0, 0, 0, // Two u32 child indices.
955        ];
956        let mut reader = SliceReader::new(LEGACY_WITNESS);
957        assert_eq!(
958            PrecompileWitness::read_from(&mut reader),
959            Err(DeserializationError::InvalidValue(
960                "unsupported precompile witness version 1 (expected 2)".into()
961            ))
962        );
963        assert_eq!(reader.read_slice(LEGACY_WITNESS.len() - 1).unwrap(), &LEGACY_WITNESS[1..]);
964    }
965
966    #[test]
967    fn standalone_witness_rejects_unsupported_versions_and_trailing_bytes() {
968        let witness = PrecompileWitness::from_entries(alloc::vec![WireEntry::Join {
969            frame: DEFERRED_AND_FRAME,
970            lhs: 0,
971            rhs: 0
972        }])
973        .unwrap();
974        let bytes = witness.to_bytes();
975        assert_eq!(bytes[0], 2);
976        for version in [0, 1, PrecompileWitness::WIRE_VERSION + 1] {
977            let mut unsupported = bytes.clone();
978            unsupported[0] = version;
979            assert_eq!(
980                PrecompileWitness::read_from_bytes(&unsupported),
981                Err(DeserializationError::InvalidValue(format!(
982                    "unsupported precompile witness version {version} (expected 2)"
983                )))
984            );
985        }
986        let mut trailing = bytes;
987        trailing.push(0);
988        assert!(PrecompileWitness::read_from_bytes(&trailing).is_err());
989    }
990
991    #[test]
992    fn decoder_rejects_malformed_frame_words_for_every_entry_shape() {
993        let entries = [
994            WireEntry::Data {
995                frame: frame(1),
996                chunks: alloc::vec![felts(10)],
997            },
998            WireEntry::Join { frame: frame(1), lhs: 0, rhs: 0 },
999            WireEntry::PairList {
1000                frame: frame(1),
1001                pairs: alloc::vec![(0, 0)],
1002            },
1003        ];
1004        let mut invalid_frames = alloc::vec![Word::default()];
1005        for index in 0..EidosFrame::FELT_LEN {
1006            let mut elements = frame(1).as_word().into_elements();
1007            elements[index] = Felt::new_unchecked(u32::MAX as u64 + 1);
1008            invalid_frames.push(Word::new(elements));
1009        }
1010        for entry in entries {
1011            let bytes = encoded_entries(&[entry]);
1012            for invalid_frame in &invalid_frames {
1013                let mut malformed = bytes.clone();
1014                // Version, singleton entry count, and variant precede the frame word.
1015                malformed[3..3 + Word::min_serialized_size()]
1016                    .copy_from_slice(&invalid_frame.to_bytes());
1017                assert_eq!(
1018                    PrecompileWitness::read_from_bytes(&malformed),
1019                    Err(DeserializationError::InvalidValue("invalid deferred Eidos frame".into()))
1020                );
1021            }
1022        }
1023    }
1024
1025    #[test]
1026    fn decoder_rejects_overlong_entry_and_payload_lengths() {
1027        let entries = [
1028            WireEntry::Data {
1029                frame: deferred_chunks_frame(1),
1030                chunks: alloc::vec![felts(10)],
1031            },
1032            WireEntry::PairList {
1033                frame: frame(1),
1034                pairs: alloc::vec![(0, 0)],
1035            },
1036        ];
1037        for entry in entries {
1038            let witness = PrecompileWitness::from_entries(alloc::vec![entry]).unwrap();
1039            let bytes = witness.to_bytes();
1040            // Version + entry count + variant precede the frame and payload count.
1041            for offset in [1, 3 + Word::min_serialized_size()] {
1042                assert_eq!(bytes[offset], 3, "one uses the one-byte vint64 encoding");
1043                let mut noncanonical = bytes[..offset].to_vec();
1044                noncanonical.extend_from_slice(&[6, 0]);
1045                noncanonical.extend_from_slice(&bytes[offset + 1..]);
1046                assert!(PrecompileWitness::read_from_bytes(&noncanonical).is_err());
1047            }
1048        }
1049    }
1050
1051    #[test]
1052    fn singleton_vector_decodes_with_exact_byte_budget() {
1053        let witness = PrecompileWitness::from_entries(alloc::vec![WireEntry::Join {
1054            frame: DEFERRED_AND_FRAME,
1055            lhs: 0,
1056            rhs: 0
1057        }])
1058        .unwrap();
1059        assert_eq!(PrecompileWitness::min_serialized_size(), 2);
1060        assert!(PrecompileWitness::min_serialized_size() <= witness.to_bytes().len());
1061        let witnesses = alloc::vec![witness.clone(), witness];
1062        let bytes = witnesses.to_bytes();
1063        assert_eq!(
1064            Vec::<PrecompileWitness>::read_from_bytes_with_budget(&bytes, bytes.len()).unwrap(),
1065            witnesses
1066        );
1067    }
1068
1069    #[test]
1070    fn wire_element_budget_accepts_exact_limit_and_rejects_one_more() {
1071        let mut remaining = MAX_DEFERRED_WIRE_ELEMENTS;
1072        reserve_wire_elements(&mut remaining, MAX_DEFERRED_WIRE_ELEMENTS).unwrap();
1073        assert_eq!(remaining, 0);
1074        assert!(reserve_wire_elements(&mut remaining, 1).is_err());
1075        let mut overflow_budget = MAX_DEFERRED_WIRE_ELEMENTS;
1076        assert!(reserve_wire_payload(&mut overflow_budget, usize::MAX).is_err());
1077    }
1078
1079    #[test]
1080    fn in_memory_entries_enforce_the_wire_element_limit() {
1081        let join = WireEntry::Join {
1082            frame: DEFERRED_AND_FRAME,
1083            lhs: 0,
1084            rhs: 0,
1085        };
1086        let mut entries = alloc::vec![join; MAX_DEFERRED_WIRE_ELEMENTS / (EidosFrame::FELT_LEN + Node::DATA_CHUNK_FELT_LEN)];
1087        // Budget validation runs before hashing, so a repeated-entry allocation cannot bypass it.
1088        entries.push(WireEntry::Data {
1089            frame: deferred_chunks_frame(1),
1090            chunks: alloc::vec![felts(10)],
1091        });
1092        assert!(matches!(
1093            PrecompileWitness::from_entries(entries),
1094            Err(IntegrityError::DeferredStateTooLarge { .. })
1095        ));
1096    }
1097
1098    #[test]
1099    fn decoder_rejects_oversized_and_truncated_lengths_before_payload_allocation() {
1100        for count in [MAX_WIRE_ENTRIES, MAX_WIRE_ENTRIES + 1, usize::MAX] {
1101            let mut bytes = alloc::vec![PrecompileWitness::WIRE_VERSION];
1102            bytes.write_usize(count);
1103            assert!(PrecompileWitness::read_from_bytes(&bytes).is_err());
1104        }
1105        for discriminant in [0, 2] {
1106            let mut bytes = alloc::vec![PrecompileWitness::WIRE_VERSION];
1107            bytes.write_usize(1);
1108            bytes.write_u8(discriminant);
1109            frame(1).as_word().write_into(&mut bytes);
1110            bytes.write_usize(usize::MAX);
1111            assert!(PrecompileWitness::read_from_bytes(&bytes).is_err());
1112        }
1113    }
1114}
1115
1116// ARBITRARY (proptest)
1117// ================================================================================================
1118
1119#[cfg(any(test, feature = "arbitrary"))]
1120mod wire_arbitrary {
1121    use alloc::vec::Vec;
1122
1123    use miden_crypto::hash::eidos::{EidosDomain, EidosFrame};
1124    use proptest::prelude::*;
1125
1126    use super::{PrecompileWitness, WireEntry};
1127    use crate::program::domain::{
1128        CurvePrecompileDomain, Keccak256PrecompileDomain, Sha256PrecompileDomain,
1129        Sha512PrecompileDomain, Uint256PrecompileDomain,
1130    };
1131
1132    impl Arbitrary for PrecompileWitness {
1133        type Parameters = ();
1134        type Strategy = BoxedStrategy<Self>;
1135
1136        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
1137            // Sound by construction: entry i (wire index i + 1) references earlier wire indices
1138            // such that every entry's flattened child list is ASCENDING and every entry is
1139            // reachable from the root (the LAST entry, which must be reference-bearing). Under
1140            // those two rules validate_structure's DFS emits entries in wire order, digests stay
1141            // unique (generated frames, differing fold structures), and the element limit holds. A
1142            // Data entry is allowed only at position 0 (it has no children, so it would orphan
1143            // its predecessors elsewhere); entry 1 references it. Five shapes are generated: the
1144            // linear Join chain (0, prev), the branching Join (prev - 1, prev) whose two
1145            // distinct children make the witness a non-linear DAG, the multi-pair PairList
1146            // [(0, prev), (prev, prev)], the single-pair PairList [(0, prev)], and the
1147            // position-0 Data entry. from_entries rejects the all-TRUE root, hence the witness
1148            // always has at least one reference-bearing entry.
1149            (1usize..=4)
1150                .prop_flat_map(|len| {
1151                    (
1152                        proptest::collection::vec(
1153                            (
1154                                prop_oneof![
1155                                    Just(Keccak256PrecompileDomain::TAG),
1156                                    Just(Uint256PrecompileDomain::TAG),
1157                                    Just(CurvePrecompileDomain::TAG),
1158                                    Just(Sha256PrecompileDomain::TAG),
1159                                    Just(Sha512PrecompileDomain::TAG),
1160                                ],
1161                                any::<[u32; 3]>(),
1162                            )
1163                                .prop_map(|(domain, params)| EidosFrame::new(domain, params)),
1164                            len,
1165                        ),
1166                        proptest::collection::vec(0u8..5, len),
1167                        proptest::collection::vec(
1168                            proptest::collection::vec(any::<crate::Felt>(), 8),
1169                            1..=3,
1170                        ),
1171                    )
1172                })
1173                .prop_map(|(frames, kinds, data_chunks)| {
1174                    // data_chunks is the (1..=3)-chunk payload of a position-0 Data entry; it is
1175                    // deliberately NOT zipped per entry so its length cannot truncate generation.
1176                    //
1177                    // Precompile domains accept every portable wire shape; the frame
1178                    // constructor guarantees canonical u32 parameters.
1179                    let n = frames.len();
1180                    let mut entries = Vec::with_capacity(n);
1181                    for (i, (frame, kind)) in frames.into_iter().zip(kinds).enumerate() {
1182                        if i == 0 && kind == 4 && n >= 2 {
1183                            let chunks = data_chunks
1184                                .iter()
1185                                .map(|chunk| chunk.clone().try_into().expect("8 felts per chunk"))
1186                                .collect();
1187                            entries.push(WireEntry::Data { frame, chunks });
1188                            continue;
1189                        }
1190                        let prev = i as u32; // the previous entry's wire index (TRUE for i = 0)
1191                        match kind % 4 {
1192                            0 => entries.push(WireEntry::Join { frame, lhs: 0, rhs: prev }),
1193                            // branching: two distinct earlier references (entries i - 2 and i - 1)
1194                            1 if i >= 2 => {
1195                                entries.push(WireEntry::Join { frame, lhs: prev - 1, rhs: prev });
1196                            },
1197                            1 => entries.push(WireEntry::Join { frame, lhs: 0, rhs: prev }),
1198                            // multi-pair: flattened children [0, prev, prev, prev] ascending
1199                            2 => entries.push(WireEntry::PairList {
1200                                frame,
1201                                pairs: alloc::vec![(0, prev), (prev, prev)],
1202                            }),
1203                            _ => {
1204                                entries.push(WireEntry::PairList {
1205                                    frame,
1206                                    pairs: alloc::vec![(0, prev)],
1207                                });
1208                            },
1209                        }
1210                    }
1211                    PrecompileWitness::from_entries(entries)
1212                        .expect("a mixed-kind witness DAG is canonical")
1213                })
1214                .boxed()
1215        }
1216    }
1217}