Skip to main content

miden_processor/trace/
mod.rs

1use alloc::{format, string::ToString};
2
3use miden_core::{
4    deferred::{Digest, TRUE_DIGEST},
5    program::ExecutionClaim,
6    serde::{
7        BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
8        SliceReader,
9    },
10};
11
12use crate::{AdviceProvider, ProgramInfo, StackInputs, StackOutputs, fast::ExecutionOutput};
13
14pub(crate) mod utils;
15use utils::ChipletTraceFragment;
16
17pub mod chiplets;
18pub(crate) mod execution_tracer;
19
20mod block_stack;
21mod parallel;
22mod range;
23mod stack;
24mod trace_state;
25
26#[cfg(test)]
27mod tests;
28
29// RE-EXPORTS
30// ================================================================================================
31
32pub(crate) use execution_tracer::TraceReplay;
33pub use miden_air_definitions::vm::{
34    ChipletsLengths, TraceLenSummary, TraceLenSummaryError, VmTrace, trace::RowIndex,
35};
36pub use miden_core::deferred::PrecompileWitness;
37pub use parallel::{CORE_TRACE_WIDTH, build_trace};
38// Re-exported for the streaming trace-build path
39// (`FastProcessor::execute_and_build_trace_sync`), which is std-only; the buffered path
40// uses `build_hasher_chiplet` and `MAX_TRACE_LEN` directly within `parallel`.
41#[cfg(feature = "std")]
42pub(crate) use parallel::{MAX_TRACE_LEN, build_hasher_chiplet, build_trace_with_prebuilt_hasher};
43#[cfg(feature = "std")]
44pub(crate) use trace_state::ResolvedHasherOp;
45
46/// Complete in-memory witness produced by a traced program execution.
47///
48/// The processor constructs its VM witness and optional singleton precompile witness from the same
49/// execution output, so they retain the same deferred root. The aggregate may contain private and
50/// potentially large prover data. Its binary form is trusted replay data: sparse MAST node and
51/// digest maps inside the trace replay are not checked against a source `MastForest` commitment;
52/// see <https://github.com/0xMiden/miden-vm/issues/3303>.
53#[derive(Debug)]
54pub struct ExecutionWitness {
55    vm: VmWitness,
56    precompile: Option<PrecompileWitness>,
57}
58
59impl ExecutionWitness {
60    pub(crate) fn from_execution(
61        program_info: ProgramInfo,
62        stack_inputs: StackInputs,
63        execution_output: ExecutionOutput,
64        trace: TraceReplay,
65    ) -> (Self, AdviceProvider) {
66        let ExecutionOutput {
67            stack: stack_outputs,
68            advice,
69            memory: _,
70            precompile_root,
71            precompile_witness: precompile,
72        } = execution_output;
73        let vm = VmWitness {
74            program_info,
75            stack_inputs,
76            stack_outputs,
77            trace,
78            precompile_root,
79        };
80
81        (Self { vm, precompile }, advice)
82    }
83
84    /// Returns the public claim associated with this witness.
85    pub fn claim(&self) -> ExecutionClaim {
86        self.vm.claim()
87    }
88
89    /// Returns whether this witness contains precompile work.
90    pub const fn has_precompiles(&self) -> bool {
91        self.precompile.is_some()
92    }
93
94    /// Consumes this witness and returns its supported low-level proving components.
95    ///
96    /// The [`VmWitness`] can be passed to [`build_trace`]. The optional [`PrecompileWitness`] is
97    /// present only when execution authenticated deferred precompile work.
98    pub fn into_parts(self) -> (VmWitness, Option<PrecompileWitness>) {
99        (self.vm, self.precompile)
100    }
101
102    /// Decodes one execution witness from a potentially adversarial byte slice.
103    ///
104    /// The reader applies an input-proportional limit to byte consumption and collection
105    /// preallocation, checks available sparse node hashes, and rejects trailing bytes.
106    /// They do not prove that the sparse MAST replay is a subset of a particular source forest
107    /// because the witness wire does not carry such a proof.
108    ///
109    /// Use [`Self::read_from_bytes_trusted`] for bytes retained inside a trusted prover system.
110    #[track_caller]
111    pub fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
112        let budget = bytes.len().saturating_mul(EXECUTION_WITNESS_BYTE_READ_BUDGET_MULTIPLIER);
113        let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
114        let witness = <Self as Deserializable>::read_from(&mut reader)?;
115
116        if reader.has_more_bytes() {
117            return Err(DeserializationError::InvalidValue(
118                "extra bytes after execution witness payload".into(),
119            ));
120        }
121        Ok(witness)
122    }
123
124    /// Decodes execution witness bytes retained inside a trusted prover system.
125    ///
126    /// This preserves the original permissive byte-slice behavior. It trusts sparse MAST replay
127    /// hashes, accepts trailing bytes, and uses a replay-sized byte budget. Use
128    /// [`Self::read_from_bytes`] for bytes received across a trust boundary.
129    #[track_caller]
130    pub fn read_from_bytes_trusted(bytes: &[u8]) -> Result<Self, DeserializationError> {
131        let budget = bytes.len().saturating_mul(EXECUTION_WITNESS_BYTE_READ_BUDGET_MULTIPLIER);
132        let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
133        Self::read_from_inner(&mut reader)
134    }
135}
136
137/// Covers nested replay length checks while keeping untrusted work proportional to input size.
138const EXECUTION_WITNESS_BYTE_READ_BUDGET_MULTIPLIER: usize = 4;
139
140/// Current wire format version for [`ExecutionWitness`] serialization.
141///
142/// The version is written as the first byte of every serialized witness. Deserialization only
143/// accepts this exact value; older formats are intentionally unsupported.
144const EXECUTION_WITNESS_WIRE_VERSION: u8 = 2;
145
146impl Serializable for ExecutionWitness {
147    fn write_into<W: ByteWriter>(&self, target: &mut W) {
148        EXECUTION_WITNESS_WIRE_VERSION.write_into(target);
149        self.vm.write_into(target);
150        match &self.precompile {
151            Some(precompile) => {
152                target.write_u8(1);
153                precompile.write_into(target);
154            },
155            None => target.write_u8(0),
156        }
157    }
158}
159
160impl Deserializable for ExecutionWitness {
161    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
162        let witness = Self::read_from_inner(source)?;
163        for forest in &witness.vm.trace.mast_forest_store {
164            forest
165                .validate()
166                .map_err(|error| DeserializationError::InvalidValue(error.to_string()))?;
167        }
168        Ok(witness)
169    }
170
171    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
172        ExecutionWitness::read_from_bytes(bytes)
173    }
174}
175
176impl ExecutionWitness {
177    fn read_from_inner<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
178        let version = u8::read_from(source)?;
179        if version != EXECUTION_WITNESS_WIRE_VERSION {
180            return Err(DeserializationError::InvalidValue(format!(
181                "unsupported execution witness wire version {version} (expected \
182                 {EXECUTION_WITNESS_WIRE_VERSION})"
183            )));
184        }
185        let vm = VmWitness::read_from(source)?;
186        let precompile = match source.read_u8()? {
187            0 => {
188                if vm.precompile_root != TRUE_DIGEST {
189                    return Err(DeserializationError::InvalidValue(
190                        "VM witness claims deferred work but no precompile witness is present"
191                            .into(),
192                    ));
193                }
194                None
195            },
196            1 => {
197                let witness = PrecompileWitness::read_from(source)?;
198                if vm.precompile_root == TRUE_DIGEST {
199                    return Err(DeserializationError::InvalidValue(
200                        "VM witness carries a precompile witness for an empty deferred root".into(),
201                    ));
202                }
203                Some(witness)
204            },
205            tag => {
206                return Err(DeserializationError::InvalidValue(format!(
207                    "invalid precompile witness option tag {tag}"
208                )));
209            },
210        };
211        Ok(Self { vm, precompile })
212    }
213}
214
215/// Witness required to materialize and prove a VM execution trace.
216///
217/// This potentially large value contains private replay data and is consumed by trace-building and
218/// proving operations. Its binary form is trusted replay data: sparse MAST node and digest maps
219/// inside the trace replay are not checked against a source `MastForest` commitment; see
220/// <https://github.com/0xMiden/miden-vm/issues/3303>.
221///
222/// Its direct [`Serializable`] encoding is an unversioned implementation detail. Use the
223/// versioned [`ExecutionWitness`] envelope for transport or persistence.
224#[derive(Debug)]
225pub struct VmWitness {
226    program_info: ProgramInfo,
227    stack_inputs: StackInputs,
228    stack_outputs: StackOutputs,
229    trace: TraceReplay,
230    precompile_root: Digest,
231}
232
233impl VmWitness {
234    /// Returns the public claim associated with this witness.
235    pub fn claim(&self) -> ExecutionClaim {
236        ExecutionClaim::from_program_info(
237            self.program_info.clone(),
238            self.stack_inputs,
239            self.stack_outputs,
240        )
241    }
242
243    /// Returns whether this witness authenticates deferred precompile work.
244    pub fn has_precompiles(&self) -> bool {
245        self.precompile_root != TRUE_DIGEST
246    }
247
248    /// Returns the deferred root authenticated by the replayed VM execution.
249    pub fn precompile_root(&self) -> Digest {
250        self.precompile_root
251    }
252
253    /// Takes the hasher replay out, leaving an empty buffered one.
254    ///
255    /// The streaming path uses this to drop the replay's channel sender once execution has
256    /// finished, so the concurrently running hasher builder sees its input stream end.
257    #[cfg(feature = "std")]
258    pub(crate) fn take_hasher_replay(&mut self) -> trace_state::HasherRequestReplay {
259        core::mem::take(&mut self.trace.hasher_for_chiplet)
260    }
261
262    /// Returns the replay data captured during execution.
263    #[cfg(any(test, feature = "testing"))]
264    #[cfg_attr(all(feature = "testing", not(test)), expect(dead_code))]
265    pub(crate) fn trace_replay(&self) -> &TraceReplay {
266        &self.trace
267    }
268
269    // Kept for tests that force invalid replay data without widening the public API.
270    #[cfg(any(test, feature = "testing"))]
271    #[cfg_attr(all(feature = "testing", not(test)), expect(dead_code))]
272    pub(crate) fn trace_replay_mut(&mut self) -> &mut TraceReplay {
273        &mut self.trace
274    }
275
276    /// Returns the number of sparse MAST forests captured in the replay.
277    ///
278    /// Available under the `testing` feature for external tests that check which replay data a
279    /// serialized witness preserves.
280    #[cfg(any(test, feature = "testing"))]
281    #[allow(dead_code)]
282    pub fn mast_forest_count(&self) -> usize {
283        self.trace.mast_forest_store.len()
284    }
285}
286
287impl Serializable for VmWitness {
288    fn write_into<W: ByteWriter>(&self, target: &mut W) {
289        self.program_info.write_into(target);
290        self.stack_inputs.write_into(target);
291        self.stack_outputs.write_into(target);
292        self.trace.write_into(target);
293        self.precompile_root.write_into(target);
294    }
295}
296
297impl Deserializable for VmWitness {
298    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
299        Ok(Self {
300            program_info: ProgramInfo::read_from(source)?,
301            stack_inputs: StackInputs::read_from(source)?,
302            stack_outputs: StackOutputs::read_from(source)?,
303            trace: TraceReplay::read_from(source)?,
304            precompile_root: Digest::read_from(source)?,
305        })
306    }
307}
308
309#[cfg(test)]
310mod wire_tests {
311    use miden_assembly::Assembler;
312    use miden_core::{
313        deferred::TRUE_DIGEST,
314        mast::{BasicBlockNodeBuilder, MastForest},
315        operations::Operation,
316        program::Program,
317    };
318    use rstest::rstest;
319
320    use super::{
321        ExecutionWitness, Serializable, build_trace,
322        trace_state::{AeadStreamReplayEntry, BitwiseOp, BitwiseReplayEntry},
323    };
324    use crate::{DefaultHost, ExecutionError, FastProcessor, Felt, StackInputs, mast::MastNodeId};
325
326    fn execution_witness(source: &str) -> ExecutionWitness {
327        let program = Assembler::default()
328            .assemble_program("program", source)
329            .expect("program should compile")
330            .unwrap_program();
331        let mut host = DefaultHost::default();
332        FastProcessor::new(StackInputs::default())
333            .execute_for_proving_sync(&program, &mut host)
334            .expect("execution should produce a witness")
335    }
336
337    fn deferred_witness() -> ExecutionWitness {
338        execution_witness("begin log_deferred end")
339    }
340
341    fn deferred_witness_bytes() -> alloc::vec::Vec<u8> {
342        deferred_witness().to_bytes()
343    }
344
345    #[test]
346    fn witness_reports_precompile_state() {
347        let plain = execution_witness("begin push.1 drop end");
348        assert!(!plain.has_precompiles());
349
350        let deferred = execution_witness("begin log_deferred end");
351        assert!(deferred.has_precompiles());
352    }
353
354    fn aead_stream_witness() -> ExecutionWitness {
355        let mut mast_forest = MastForest::new();
356        let basic_block_id = BasicBlockNodeBuilder::new(vec![Operation::CryptoStream])
357            .add_to_forest(&mut mast_forest)
358            .unwrap();
359        mast_forest.make_root(basic_block_id);
360        let program = Program::new(mast_forest.into(), basic_block_id);
361
362        let stack = [
363            1, 2, 3, 4, // K_CTR
364            0, // counter
365            0, // src_ptr
366            8, // dst_ptr
367            1, // remaining
368            0, 0, 0, 0, 0, 0, 0, 0, // tail
369        ]
370        .map(Felt::new_unchecked);
371        let mut host = DefaultHost::default();
372        FastProcessor::new(StackInputs::new(&stack).unwrap())
373            .execute_for_proving_sync(&program, &mut host)
374            .expect("AEAD stream execution should produce a witness")
375    }
376
377    #[test]
378    fn witness_wire_rejects_unsupported_version() {
379        let mut bytes = deferred_witness_bytes();
380        assert!(ExecutionWitness::read_from_bytes(&bytes).is_ok());
381        assert_eq!(bytes[0], 2, "Eidos witnesses must use wire version 2");
382
383        // Rejected versions are checked before decoding replay or witness payloads.
384        for version in [0, 1, super::EXECUTION_WITNESS_WIRE_VERSION + 1] {
385            bytes[0] = version;
386            let err = ExecutionWitness::read_from_bytes(&bytes)
387                .expect_err("unsupported witness format must be rejected");
388            assert!(format!("{err:?}").contains("unsupported execution witness wire version"));
389        }
390    }
391
392    #[test]
393    fn witness_wire_rejects_trailing_bytes() {
394        let mut bytes = deferred_witness_bytes();
395        bytes.push(0);
396
397        let err = ExecutionWitness::read_from_bytes(&bytes)
398            .expect_err("witness payload with trailing bytes should be rejected");
399        assert!(
400            format!("{err:?}").contains("extra bytes after execution witness payload"),
401            "unexpected error: {err:?}"
402        );
403
404        assert!(
405            ExecutionWitness::read_from_bytes_trusted(&bytes).is_ok(),
406            "the explicit trusted reader should preserve the old permissive behavior"
407        );
408    }
409
410    #[test]
411    fn witness_reader_checks_sparse_hashes_and_preserves_trusted_path() {
412        use miden_core::{Word, mast::SparseMastForest, serde::ByteReader};
413
414        let mut witness = execution_witness("begin push.1 drop end");
415        let forest = &mut witness.vm.trace.mast_forest_store[0];
416        let mut sparse_bytes = forest.to_bytes();
417        let mut reader = std::io::Cursor::new(sparse_bytes.as_slice());
418        let root_count = reader.read_usize().unwrap();
419        for _ in 0..root_count {
420            reader.read_u32().unwrap();
421        }
422        assert!(reader.read_usize().unwrap() > 0);
423        reader.read_u32().unwrap();
424        reader.read_u8().unwrap();
425        let hash_offset = reader.position() as usize;
426        sparse_bytes[hash_offset..hash_offset + Word::SERIALIZED_SIZE]
427            .copy_from_slice(&Word::default().to_bytes());
428        *forest = alloc::sync::Arc::new(
429            SparseMastForest::read_from_bytes_trusted(&sparse_bytes).unwrap(),
430        );
431
432        let bytes = witness.to_bytes();
433        assert!(ExecutionWitness::read_from_bytes(&bytes).is_err());
434        assert!(
435            <ExecutionWitness as super::Deserializable>::read_from(&mut std::io::Cursor::new(
436                &bytes
437            ),)
438            .is_err()
439        );
440        assert!(ExecutionWitness::read_from_bytes_trusted(&bytes).is_ok());
441    }
442
443    #[test]
444    fn witness_wire_accepts_large_minimally_encoded_continuation_stack() {
445        let mut witness = deferred_witness();
446        let continuation = &mut witness
447            .vm
448            .trace_replay_mut()
449            .core_trace_contexts
450            .first_mut()
451            .expect("witness should contain a trace fragment")
452            .continuation;
453        for _ in 0..4096 {
454            continuation.push_start_node(MastNodeId::from(0));
455        }
456
457        let bytes = witness.to_bytes();
458        let restored = ExecutionWitness::read_from_bytes(&bytes)
459            .expect("valid witness should fit its input-proportional allocation budget");
460
461        assert_eq!(restored.to_bytes(), bytes);
462    }
463
464    #[test]
465    fn aead_stream_witness_round_trip_rebuilds_the_same_trace() {
466        let witness = aead_stream_witness();
467        let bytes = witness.to_bytes();
468        let claim = witness.claim();
469        let (original_vm, original_precompile) = witness.into_parts();
470        assert!(original_precompile.is_none());
471        let original_trace = build_trace(original_vm, &miden_vm_stark::memory::default_budget())
472            .expect("original trace should build");
473
474        let restored =
475            ExecutionWitness::read_from_bytes(&bytes).expect("witness should round trip");
476        assert_eq!(restored.claim(), claim);
477        let (restored_vm, restored_precompile) = restored.into_parts();
478        assert!(restored_precompile.is_none());
479        let restored_trace = build_trace(restored_vm, &miden_vm_stark::memory::default_budget())
480            .expect("restored trace should build");
481
482        assert_eq!(restored_trace.public_inputs(), original_trace.public_inputs());
483        assert_eq!(restored_trace.trace_len_summary(), original_trace.trace_len_summary());
484        assert_eq!(restored_trace.into_air_matrices(), original_trace.into_air_matrices());
485    }
486
487    #[rstest]
488    #[case::keystream_not_u32(
489        |entry: &mut AeadStreamReplayEntry, lane: usize| {
490            entry.keystream[lane] = Felt::new_unchecked(1 << 32);
491        },
492        "operation expected u32 values"
493    )]
494    #[case::ciphertext_not_u32(
495        |entry: &mut AeadStreamReplayEntry, lane: usize| {
496            entry.ciphertext[lane] = Felt::new_unchecked(1 << 32);
497        },
498        "operation expected u32 values"
499    )]
500    #[case::ciphertext_mismatch(
501        |entry: &mut AeadStreamReplayEntry, lane: usize| {
502            entry.ciphertext[lane] =
503                Felt::new_unchecked(entry.ciphertext[lane].as_canonical_u64() ^ 1);
504        },
505        "AEAD stream ciphertext does not match plaintext XOR keystream"
506    )]
507    fn build_trace_rejects_inconsistent_aead_stream_replay(
508        #[case] tamper: fn(&mut AeadStreamReplayEntry, usize),
509        #[case] expected_error: &str,
510        #[values(0, 7)] lane: usize,
511    ) {
512        let mut witness = aead_stream_witness();
513        let replay = &mut witness.vm.trace_replay_mut().bitwise_replay;
514        let mut tampered = false;
515        for entry in core::mem::take(replay) {
516            match entry {
517                BitwiseReplayEntry::AeadStream(mut entry) => {
518                    if !tampered {
519                        tamper(&mut entry, lane);
520                        tampered = true;
521                    }
522                    replay.record_aead_stream(*entry);
523                },
524                BitwiseReplayEntry::U32(BitwiseOp::U32And, a, b) => replay.record_u32and(a, b),
525                BitwiseReplayEntry::U32(BitwiseOp::U32Xor, a, b) => replay.record_u32xor(a, b),
526            }
527        }
528        assert!(tampered, "the witness should contain an AEAD stream entry");
529
530        let witness = ExecutionWitness::read_from_bytes(&witness.to_bytes())
531            .expect("the wire reader accepts Felt-valued replay lanes");
532        let Err(error) =
533            build_trace(witness.into_parts().0, &miden_vm_stark::memory::default_budget())
534        else {
535            panic!("invalid AEAD stream replay must return an error");
536        };
537        assert!(matches!(error, ExecutionError::OperationError { .. }));
538        assert!(format!("{error}").contains(expected_error), "unexpected error: {error}");
539    }
540
541    #[test]
542    fn witness_wire_rejects_precompile_witness_with_true_root() {
543        let bytes = deferred_witness_bytes();
544        let restored = ExecutionWitness::read_from_bytes(&bytes).expect("witness round trip");
545        let (vm, precompile) = restored.into_parts();
546        let precompile = precompile.expect("deferred execution should carry a precompile witness");
547        assert_ne!(vm.precompile_root, TRUE_DIGEST);
548
549        // A carried witness with an explicitly empty VM-side root is not a valid transport shape.
550        let tampered = ExecutionWitness {
551            vm: super::VmWitness { precompile_root: TRUE_DIGEST, ..vm },
552            precompile: Some(precompile),
553        };
554        let err = ExecutionWitness::read_from_bytes(&tampered.to_bytes())
555            .expect_err("tampered witness should be rejected");
556        assert!(
557            format!("{err:?}")
558                .contains("VM witness carries a precompile witness for an empty deferred root"),
559            "unexpected error: {err:?}"
560        );
561
562        // Sanity: the untampered wire still round-trips.
563        assert!(ExecutionWitness::read_from_bytes(&bytes).is_ok());
564    }
565
566    #[test]
567    fn witness_wire_rejects_missing_precompile_witness() {
568        let bytes = deferred_witness_bytes();
569        let restored = ExecutionWitness::read_from_bytes(&bytes).expect("witness round trip");
570        let (vm, precompile) = restored.into_parts();
571        assert!(precompile.is_some(), "deferred execution should carry a precompile witness");
572
573        // Drop only the precompile witness while the VM side still claims deferred work: the
574        // wire must not validate as a complete execution.
575        let stripped = ExecutionWitness { vm, precompile: None };
576        let err = ExecutionWitness::read_from_bytes(&stripped.to_bytes())
577            .expect_err("witness without its precompile half should be rejected");
578        assert!(
579            format!("{err:?}")
580                .contains("VM witness claims deferred work but no precompile witness is present"),
581            "unexpected error: {err:?}"
582        );
583    }
584}