miden-processor 1.0.0-rc.1

Miden VM processor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
use alloc::{format, string::ToString};

use miden_core::{
    deferred::{Digest, TRUE_DIGEST},
    program::ExecutionClaim,
    serde::{
        BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
        SliceReader,
    },
};

use crate::{AdviceProvider, ProgramInfo, StackInputs, StackOutputs, fast::ExecutionOutput};

pub(crate) mod utils;
use utils::ChipletTraceFragment;

pub mod chiplets;
pub(crate) mod execution_tracer;

mod block_stack;
mod parallel;
mod range;
mod stack;
mod trace_state;

#[cfg(test)]
mod tests;

// RE-EXPORTS
// ================================================================================================

pub(crate) use execution_tracer::TraceReplay;
pub use miden_air_definitions::vm::{
    ChipletsLengths, TraceLenSummary, TraceLenSummaryError, VmTrace, trace::RowIndex,
};
pub use miden_core::deferred::PrecompileWitness;
pub use parallel::{CORE_TRACE_WIDTH, build_trace};
// Re-exported for the streaming trace-build path
// (`FastProcessor::execute_and_build_trace_sync`), which is std-only; the buffered path
// uses `build_hasher_chiplet` and `MAX_TRACE_LEN` directly within `parallel`.
#[cfg(feature = "std")]
pub(crate) use parallel::{MAX_TRACE_LEN, build_hasher_chiplet, build_trace_with_prebuilt_hasher};
#[cfg(feature = "std")]
pub(crate) use trace_state::ResolvedHasherOp;

/// Complete in-memory witness produced by a traced program execution.
///
/// The processor constructs its VM witness and optional singleton precompile witness from the same
/// execution output, so they retain the same deferred root. The aggregate may contain private and
/// potentially large prover data. Its binary form is trusted replay data: sparse MAST node and
/// digest maps inside the trace replay are not checked against a source `MastForest` commitment;
/// see <https://github.com/0xMiden/miden-vm/issues/3303>.
#[derive(Debug)]
pub struct ExecutionWitness {
    vm: VmWitness,
    precompile: Option<PrecompileWitness>,
}

impl ExecutionWitness {
    pub(crate) fn from_execution(
        program_info: ProgramInfo,
        stack_inputs: StackInputs,
        execution_output: ExecutionOutput,
        trace: TraceReplay,
    ) -> (Self, AdviceProvider) {
        let ExecutionOutput {
            stack: stack_outputs,
            advice,
            memory: _,
            precompile_root,
            precompile_witness: precompile,
        } = execution_output;
        let vm = VmWitness {
            program_info,
            stack_inputs,
            stack_outputs,
            trace,
            precompile_root,
        };

        (Self { vm, precompile }, advice)
    }

    /// Returns the public claim associated with this witness.
    pub fn claim(&self) -> ExecutionClaim {
        self.vm.claim()
    }

    /// Returns whether this witness contains precompile work.
    pub const fn has_precompiles(&self) -> bool {
        self.precompile.is_some()
    }

    /// Consumes this witness and returns its supported low-level proving components.
    ///
    /// The [`VmWitness`] can be passed to [`build_trace`]. The optional [`PrecompileWitness`] is
    /// present only when execution authenticated deferred precompile work.
    pub fn into_parts(self) -> (VmWitness, Option<PrecompileWitness>) {
        (self.vm, self.precompile)
    }

    /// Decodes one execution witness from a potentially adversarial byte slice.
    ///
    /// The reader applies an input-proportional limit to byte consumption and collection
    /// preallocation, checks available sparse node hashes, and rejects trailing bytes.
    /// They do not prove that the sparse MAST replay is a subset of a particular source forest
    /// because the witness wire does not carry such a proof.
    ///
    /// Use [`Self::read_from_bytes_trusted`] for bytes retained inside a trusted prover system.
    #[track_caller]
    pub fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
        let budget = bytes.len().saturating_mul(EXECUTION_WITNESS_BYTE_READ_BUDGET_MULTIPLIER);
        let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
        let witness = <Self as Deserializable>::read_from(&mut reader)?;

        if reader.has_more_bytes() {
            return Err(DeserializationError::InvalidValue(
                "extra bytes after execution witness payload".into(),
            ));
        }
        Ok(witness)
    }

    /// Decodes execution witness bytes retained inside a trusted prover system.
    ///
    /// This preserves the original permissive byte-slice behavior. It trusts sparse MAST replay
    /// hashes, accepts trailing bytes, and uses a replay-sized byte budget. Use
    /// [`Self::read_from_bytes`] for bytes received across a trust boundary.
    #[track_caller]
    pub fn read_from_bytes_trusted(bytes: &[u8]) -> Result<Self, DeserializationError> {
        let budget = bytes.len().saturating_mul(EXECUTION_WITNESS_BYTE_READ_BUDGET_MULTIPLIER);
        let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
        Self::read_from_inner(&mut reader)
    }
}

/// Covers nested replay length checks while keeping untrusted work proportional to input size.
const EXECUTION_WITNESS_BYTE_READ_BUDGET_MULTIPLIER: usize = 4;

/// Current wire format version for [`ExecutionWitness`] serialization.
///
/// The version is written as the first byte of every serialized witness. Deserialization only
/// accepts this exact value; older formats are intentionally unsupported.
const EXECUTION_WITNESS_WIRE_VERSION: u8 = 2;

impl Serializable for ExecutionWitness {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        EXECUTION_WITNESS_WIRE_VERSION.write_into(target);
        self.vm.write_into(target);
        match &self.precompile {
            Some(precompile) => {
                target.write_u8(1);
                precompile.write_into(target);
            },
            None => target.write_u8(0),
        }
    }
}

impl Deserializable for ExecutionWitness {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let witness = Self::read_from_inner(source)?;
        for forest in &witness.vm.trace.mast_forest_store {
            forest
                .validate()
                .map_err(|error| DeserializationError::InvalidValue(error.to_string()))?;
        }
        Ok(witness)
    }

    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
        ExecutionWitness::read_from_bytes(bytes)
    }
}

impl ExecutionWitness {
    fn read_from_inner<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let version = u8::read_from(source)?;
        if version != EXECUTION_WITNESS_WIRE_VERSION {
            return Err(DeserializationError::InvalidValue(format!(
                "unsupported execution witness wire version {version} (expected \
                 {EXECUTION_WITNESS_WIRE_VERSION})"
            )));
        }
        let vm = VmWitness::read_from(source)?;
        let precompile = match source.read_u8()? {
            0 => {
                if vm.precompile_root != TRUE_DIGEST {
                    return Err(DeserializationError::InvalidValue(
                        "VM witness claims deferred work but no precompile witness is present"
                            .into(),
                    ));
                }
                None
            },
            1 => {
                let witness = PrecompileWitness::read_from(source)?;
                if vm.precompile_root == TRUE_DIGEST {
                    return Err(DeserializationError::InvalidValue(
                        "VM witness carries a precompile witness for an empty deferred root".into(),
                    ));
                }
                Some(witness)
            },
            tag => {
                return Err(DeserializationError::InvalidValue(format!(
                    "invalid precompile witness option tag {tag}"
                )));
            },
        };
        Ok(Self { vm, precompile })
    }
}

/// Witness required to materialize and prove a VM execution trace.
///
/// This potentially large value contains private replay data and is consumed by trace-building and
/// proving operations. Its binary form is trusted replay data: sparse MAST node and digest maps
/// inside the trace replay are not checked against a source `MastForest` commitment; see
/// <https://github.com/0xMiden/miden-vm/issues/3303>.
///
/// Its direct [`Serializable`] encoding is an unversioned implementation detail. Use the
/// versioned [`ExecutionWitness`] envelope for transport or persistence.
#[derive(Debug)]
pub struct VmWitness {
    program_info: ProgramInfo,
    stack_inputs: StackInputs,
    stack_outputs: StackOutputs,
    trace: TraceReplay,
    precompile_root: Digest,
}

impl VmWitness {
    /// Returns the public claim associated with this witness.
    pub fn claim(&self) -> ExecutionClaim {
        ExecutionClaim::from_program_info(
            self.program_info.clone(),
            self.stack_inputs,
            self.stack_outputs,
        )
    }

    /// Returns whether this witness authenticates deferred precompile work.
    pub fn has_precompiles(&self) -> bool {
        self.precompile_root != TRUE_DIGEST
    }

    /// Returns the deferred root authenticated by the replayed VM execution.
    pub fn precompile_root(&self) -> Digest {
        self.precompile_root
    }

    /// Takes the hasher replay out, leaving an empty buffered one.
    ///
    /// The streaming path uses this to drop the replay's channel sender once execution has
    /// finished, so the concurrently running hasher builder sees its input stream end.
    #[cfg(feature = "std")]
    pub(crate) fn take_hasher_replay(&mut self) -> trace_state::HasherRequestReplay {
        core::mem::take(&mut self.trace.hasher_for_chiplet)
    }

    /// Returns the replay data captured during execution.
    #[cfg(any(test, feature = "testing"))]
    #[cfg_attr(all(feature = "testing", not(test)), expect(dead_code))]
    pub(crate) fn trace_replay(&self) -> &TraceReplay {
        &self.trace
    }

    // Kept for tests that force invalid replay data without widening the public API.
    #[cfg(any(test, feature = "testing"))]
    #[cfg_attr(all(feature = "testing", not(test)), expect(dead_code))]
    pub(crate) fn trace_replay_mut(&mut self) -> &mut TraceReplay {
        &mut self.trace
    }

    /// Returns the number of sparse MAST forests captured in the replay.
    ///
    /// Available under the `testing` feature for external tests that check which replay data a
    /// serialized witness preserves.
    #[cfg(any(test, feature = "testing"))]
    #[allow(dead_code)]
    pub fn mast_forest_count(&self) -> usize {
        self.trace.mast_forest_store.len()
    }
}

impl Serializable for VmWitness {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        self.program_info.write_into(target);
        self.stack_inputs.write_into(target);
        self.stack_outputs.write_into(target);
        self.trace.write_into(target);
        self.precompile_root.write_into(target);
    }
}

impl Deserializable for VmWitness {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        Ok(Self {
            program_info: ProgramInfo::read_from(source)?,
            stack_inputs: StackInputs::read_from(source)?,
            stack_outputs: StackOutputs::read_from(source)?,
            trace: TraceReplay::read_from(source)?,
            precompile_root: Digest::read_from(source)?,
        })
    }
}

#[cfg(test)]
mod wire_tests {
    use miden_assembly::Assembler;
    use miden_core::{
        deferred::TRUE_DIGEST,
        mast::{BasicBlockNodeBuilder, MastForest},
        operations::Operation,
        program::Program,
    };
    use rstest::rstest;

    use super::{
        ExecutionWitness, Serializable, build_trace,
        trace_state::{AeadStreamReplayEntry, BitwiseOp, BitwiseReplayEntry},
    };
    use crate::{DefaultHost, ExecutionError, FastProcessor, Felt, StackInputs, mast::MastNodeId};

    fn execution_witness(source: &str) -> ExecutionWitness {
        let program = Assembler::default()
            .assemble_program("program", source)
            .expect("program should compile")
            .unwrap_program();
        let mut host = DefaultHost::default();
        FastProcessor::new(StackInputs::default())
            .execute_for_proving_sync(&program, &mut host)
            .expect("execution should produce a witness")
    }

    fn deferred_witness() -> ExecutionWitness {
        execution_witness("begin log_deferred end")
    }

    fn deferred_witness_bytes() -> alloc::vec::Vec<u8> {
        deferred_witness().to_bytes()
    }

    #[test]
    fn witness_reports_precompile_state() {
        let plain = execution_witness("begin push.1 drop end");
        assert!(!plain.has_precompiles());

        let deferred = execution_witness("begin log_deferred end");
        assert!(deferred.has_precompiles());
    }

    fn aead_stream_witness() -> ExecutionWitness {
        let mut mast_forest = MastForest::new();
        let basic_block_id = BasicBlockNodeBuilder::new(vec![Operation::CryptoStream])
            .add_to_forest(&mut mast_forest)
            .unwrap();
        mast_forest.make_root(basic_block_id);
        let program = Program::new(mast_forest.into(), basic_block_id);

        let stack = [
            1, 2, 3, 4, // K_CTR
            0, // counter
            0, // src_ptr
            8, // dst_ptr
            1, // remaining
            0, 0, 0, 0, 0, 0, 0, 0, // tail
        ]
        .map(Felt::new_unchecked);
        let mut host = DefaultHost::default();
        FastProcessor::new(StackInputs::new(&stack).unwrap())
            .execute_for_proving_sync(&program, &mut host)
            .expect("AEAD stream execution should produce a witness")
    }

    #[test]
    fn witness_wire_rejects_unsupported_version() {
        let mut bytes = deferred_witness_bytes();
        assert!(ExecutionWitness::read_from_bytes(&bytes).is_ok());
        assert_eq!(bytes[0], 2, "Eidos witnesses must use wire version 2");

        // Rejected versions are checked before decoding replay or witness payloads.
        for version in [0, 1, super::EXECUTION_WITNESS_WIRE_VERSION + 1] {
            bytes[0] = version;
            let err = ExecutionWitness::read_from_bytes(&bytes)
                .expect_err("unsupported witness format must be rejected");
            assert!(format!("{err:?}").contains("unsupported execution witness wire version"));
        }
    }

    #[test]
    fn witness_wire_rejects_trailing_bytes() {
        let mut bytes = deferred_witness_bytes();
        bytes.push(0);

        let err = ExecutionWitness::read_from_bytes(&bytes)
            .expect_err("witness payload with trailing bytes should be rejected");
        assert!(
            format!("{err:?}").contains("extra bytes after execution witness payload"),
            "unexpected error: {err:?}"
        );

        assert!(
            ExecutionWitness::read_from_bytes_trusted(&bytes).is_ok(),
            "the explicit trusted reader should preserve the old permissive behavior"
        );
    }

    #[test]
    fn witness_reader_checks_sparse_hashes_and_preserves_trusted_path() {
        use miden_core::{Word, mast::SparseMastForest, serde::ByteReader};

        let mut witness = execution_witness("begin push.1 drop end");
        let forest = &mut witness.vm.trace.mast_forest_store[0];
        let mut sparse_bytes = forest.to_bytes();
        let mut reader = std::io::Cursor::new(sparse_bytes.as_slice());
        let root_count = reader.read_usize().unwrap();
        for _ in 0..root_count {
            reader.read_u32().unwrap();
        }
        assert!(reader.read_usize().unwrap() > 0);
        reader.read_u32().unwrap();
        reader.read_u8().unwrap();
        let hash_offset = reader.position() as usize;
        sparse_bytes[hash_offset..hash_offset + Word::SERIALIZED_SIZE]
            .copy_from_slice(&Word::default().to_bytes());
        *forest = alloc::sync::Arc::new(
            SparseMastForest::read_from_bytes_trusted(&sparse_bytes).unwrap(),
        );

        let bytes = witness.to_bytes();
        assert!(ExecutionWitness::read_from_bytes(&bytes).is_err());
        assert!(
            <ExecutionWitness as super::Deserializable>::read_from(&mut std::io::Cursor::new(
                &bytes
            ),)
            .is_err()
        );
        assert!(ExecutionWitness::read_from_bytes_trusted(&bytes).is_ok());
    }

    #[test]
    fn witness_wire_accepts_large_minimally_encoded_continuation_stack() {
        let mut witness = deferred_witness();
        let continuation = &mut witness
            .vm
            .trace_replay_mut()
            .core_trace_contexts
            .first_mut()
            .expect("witness should contain a trace fragment")
            .continuation;
        for _ in 0..4096 {
            continuation.push_start_node(MastNodeId::from(0));
        }

        let bytes = witness.to_bytes();
        let restored = ExecutionWitness::read_from_bytes(&bytes)
            .expect("valid witness should fit its input-proportional allocation budget");

        assert_eq!(restored.to_bytes(), bytes);
    }

    #[test]
    fn aead_stream_witness_round_trip_rebuilds_the_same_trace() {
        let witness = aead_stream_witness();
        let bytes = witness.to_bytes();
        let claim = witness.claim();
        let (original_vm, original_precompile) = witness.into_parts();
        assert!(original_precompile.is_none());
        let original_trace = build_trace(original_vm, &miden_vm_stark::memory::default_budget())
            .expect("original trace should build");

        let restored =
            ExecutionWitness::read_from_bytes(&bytes).expect("witness should round trip");
        assert_eq!(restored.claim(), claim);
        let (restored_vm, restored_precompile) = restored.into_parts();
        assert!(restored_precompile.is_none());
        let restored_trace = build_trace(restored_vm, &miden_vm_stark::memory::default_budget())
            .expect("restored trace should build");

        assert_eq!(restored_trace.public_inputs(), original_trace.public_inputs());
        assert_eq!(restored_trace.trace_len_summary(), original_trace.trace_len_summary());
        assert_eq!(restored_trace.into_air_matrices(), original_trace.into_air_matrices());
    }

    #[rstest]
    #[case::keystream_not_u32(
        |entry: &mut AeadStreamReplayEntry, lane: usize| {
            entry.keystream[lane] = Felt::new_unchecked(1 << 32);
        },
        "operation expected u32 values"
    )]
    #[case::ciphertext_not_u32(
        |entry: &mut AeadStreamReplayEntry, lane: usize| {
            entry.ciphertext[lane] = Felt::new_unchecked(1 << 32);
        },
        "operation expected u32 values"
    )]
    #[case::ciphertext_mismatch(
        |entry: &mut AeadStreamReplayEntry, lane: usize| {
            entry.ciphertext[lane] =
                Felt::new_unchecked(entry.ciphertext[lane].as_canonical_u64() ^ 1);
        },
        "AEAD stream ciphertext does not match plaintext XOR keystream"
    )]
    fn build_trace_rejects_inconsistent_aead_stream_replay(
        #[case] tamper: fn(&mut AeadStreamReplayEntry, usize),
        #[case] expected_error: &str,
        #[values(0, 7)] lane: usize,
    ) {
        let mut witness = aead_stream_witness();
        let replay = &mut witness.vm.trace_replay_mut().bitwise_replay;
        let mut tampered = false;
        for entry in core::mem::take(replay) {
            match entry {
                BitwiseReplayEntry::AeadStream(mut entry) => {
                    if !tampered {
                        tamper(&mut entry, lane);
                        tampered = true;
                    }
                    replay.record_aead_stream(*entry);
                },
                BitwiseReplayEntry::U32(BitwiseOp::U32And, a, b) => replay.record_u32and(a, b),
                BitwiseReplayEntry::U32(BitwiseOp::U32Xor, a, b) => replay.record_u32xor(a, b),
            }
        }
        assert!(tampered, "the witness should contain an AEAD stream entry");

        let witness = ExecutionWitness::read_from_bytes(&witness.to_bytes())
            .expect("the wire reader accepts Felt-valued replay lanes");
        let Err(error) =
            build_trace(witness.into_parts().0, &miden_vm_stark::memory::default_budget())
        else {
            panic!("invalid AEAD stream replay must return an error");
        };
        assert!(matches!(error, ExecutionError::OperationError { .. }));
        assert!(format!("{error}").contains(expected_error), "unexpected error: {error}");
    }

    #[test]
    fn witness_wire_rejects_precompile_witness_with_true_root() {
        let bytes = deferred_witness_bytes();
        let restored = ExecutionWitness::read_from_bytes(&bytes).expect("witness round trip");
        let (vm, precompile) = restored.into_parts();
        let precompile = precompile.expect("deferred execution should carry a precompile witness");
        assert_ne!(vm.precompile_root, TRUE_DIGEST);

        // A carried witness with an explicitly empty VM-side root is not a valid transport shape.
        let tampered = ExecutionWitness {
            vm: super::VmWitness { precompile_root: TRUE_DIGEST, ..vm },
            precompile: Some(precompile),
        };
        let err = ExecutionWitness::read_from_bytes(&tampered.to_bytes())
            .expect_err("tampered witness should be rejected");
        assert!(
            format!("{err:?}")
                .contains("VM witness carries a precompile witness for an empty deferred root"),
            "unexpected error: {err:?}"
        );

        // Sanity: the untampered wire still round-trips.
        assert!(ExecutionWitness::read_from_bytes(&bytes).is_ok());
    }

    #[test]
    fn witness_wire_rejects_missing_precompile_witness() {
        let bytes = deferred_witness_bytes();
        let restored = ExecutionWitness::read_from_bytes(&bytes).expect("witness round trip");
        let (vm, precompile) = restored.into_parts();
        assert!(precompile.is_some(), "deferred execution should carry a precompile witness");

        // Drop only the precompile witness while the VM side still claims deferred work: the
        // wire must not validate as a complete execution.
        let stripped = ExecutionWitness { vm, precompile: None };
        let err = ExecutionWitness::read_from_bytes(&stripped.to_bytes())
            .expect_err("witness without its precompile half should be rejected");
        assert!(
            format!("{err:?}")
                .contains("VM witness claims deferred work but no precompile witness is present"),
            "unexpected error: {err:?}"
        );
    }
}