Skip to main content

openvm_circuit/system/program/
trace.rs

1use std::borrow::BorrowMut;
2
3use itertools::Itertools;
4use openvm_circuit::{arch::hasher::poseidon2::Poseidon2Hasher, primitives::Chip};
5use openvm_cpu_backend::CpuBackend;
6use openvm_instructions::{
7    exe::VmExe,
8    program::{Program, DEFAULT_PC_STEP},
9    LocalOpcode, SystemOpcode,
10};
11use openvm_stark_backend::{
12    p3_field::{Field, PrimeCharacteristicRing, PrimeField32},
13    p3_matrix::dense::RowMajorMatrix,
14    p3_maybe_rayon::prelude::*,
15    prover::AirProvingContext,
16    StarkProtocolConfig, Val,
17};
18
19use super::{Instruction, ProgramCachedCols, ProgramExecutionCols, EXIT_CODE_FAIL};
20use crate::{
21    arch::{
22        hasher::{poseidon2::vm_poseidon2_hasher, Hasher},
23        MemoryConfig,
24    },
25    system::{
26        memory::{merkle::MerkleTree, AddressMap, CHUNK},
27        program::ProgramChip,
28    },
29};
30
31impl<SC: StarkProtocolConfig> Chip<(), CpuBackend<SC>> for ProgramChip<SC> {
32    /// The cached program trace is cloned and left for future use. The clone is cheap because the
33    /// cached trace is behind smart pointers. The execution frequencies are left unchanged.
34    fn generate_proving_ctx(&self, _: ()) -> AirProvingContext<CpuBackend<SC>> {
35        let cached = self
36            .cached
37            .clone()
38            .expect("cached program trace must be loaded");
39        assert!(self.filtered_exec_frequencies.len() <= cached.height());
40        let mut freqs = Val::<SC>::zero_vec(cached.height());
41        freqs
42            .par_iter_mut()
43            .zip(self.filtered_exec_frequencies.par_iter())
44            .for_each(|(f, x)| *f = Val::<SC>::from_u32(*x));
45        let common_trace = RowMajorMatrix::new(freqs, 1);
46        AirProvingContext {
47            cached_mains: vec![cached],
48            common_main: common_trace,
49            public_values: vec![],
50        }
51    }
52}
53
54/// Computes a commitment to a VM executable. This is a Merklelized hash of:
55/// - Program code commitment (commitment of the cached trace)
56/// - Merkle root of the initial memory
57/// - Starting program counter (`pc_start`)
58///
59/// The program code commitment is itself a commitment (via the proof system PCS) to
60/// the program code.
61///
62/// The Merklelization uses Poseidon2 as a cryptographic hash function (for the leaves)
63/// and a cryptographic compression function (for internal nodes).
64///
65/// **Note**: This function recomputes the Merkle tree for the initial memory image.
66pub fn compute_exe_commit_from_mem_config<F: PrimeField32>(
67    program_commitment: &[F; CHUNK],
68    exe: &VmExe<F>,
69    memory_config: &MemoryConfig,
70) -> [F; CHUNK] {
71    let hasher = vm_poseidon2_hasher();
72    compute_exe_commit(
73        &hasher,
74        program_commitment,
75        &compute_initial_memory_commit(&hasher, exe, memory_config),
76        F::from_u32(exe.pc_start),
77    )
78}
79
80/// Computes the Merkle root of an executable's initial memory using the VM memory configuration.
81/// This rebuilds the Merkle tree from the executable's initial memory image.
82pub fn compute_initial_memory_commit<F: PrimeField32>(
83    hasher: &Poseidon2Hasher<F>,
84    exe: &VmExe<F>,
85    memory_config: &MemoryConfig,
86) -> [F; CHUNK] {
87    let mut memory_image = AddressMap::new(memory_config.addr_spaces.clone());
88    memory_image.set_from_sparse(&exe.init_memory);
89    MerkleTree::from_memory(&memory_image, &memory_config.memory_dimensions(), hasher).root()
90}
91
92/// Computes a Merklelized hash of:
93/// - Program code commitment (commitment of the cached trace)
94/// - Merkle root of the initial memory
95/// - Starting program counter (`pc_start`)
96///
97/// The Merklelization uses [Poseidon2Hasher] as a cryptographic hash function (for the leaves)
98/// and a cryptographic compression function (for internal nodes).
99pub fn compute_exe_commit<F: PrimeField32>(
100    hasher: &Poseidon2Hasher<F>,
101    program_commit: &[F; CHUNK],
102    init_memory_root: &[F; CHUNK],
103    pc_start: F,
104) -> [F; CHUNK] {
105    let mut padded_pc_start = [F::ZERO; CHUNK];
106    padded_pc_start[0] = pc_start;
107    let program_hash = hasher.hash(program_commit);
108    let memory_hash = hasher.hash(init_memory_root);
109    let pc_hash = hasher.hash(&padded_pc_start);
110    hasher.compress(&hasher.compress(&program_hash, &memory_hash), &pc_hash)
111}
112
113pub(crate) fn generate_cached_trace<F: Field>(program: &Program<F>) -> RowMajorMatrix<F> {
114    let width = ProgramCachedCols::<F>::width();
115    let mut instructions = program
116        .enumerate_by_pc()
117        .into_iter()
118        .map(|(pc, instruction, _)| (pc, instruction))
119        .collect_vec();
120
121    // `instructions` is packed, so its length is not a PC index when the program has holes.
122    // Start padding after the original slot range so those PCs stay unique.
123    let padding = padding_instruction();
124    let mut padding_index = program.len();
125    while !instructions.len().is_power_of_two() {
126        let padding_pc = program.pc_base + padding_index as u32 * DEFAULT_PC_STEP;
127        instructions.push((padding_pc, padding.clone()));
128        padding_index += 1;
129    }
130
131    let height = instructions.len();
132    let mut rows = F::zero_vec(height * width);
133    rows.par_chunks_mut(width)
134        .zip(instructions)
135        .enumerate()
136        .for_each(|(idx, (row, (pc, instruction)))| {
137            let row: &mut ProgramCachedCols<F> = row.borrow_mut();
138            row.exec_end = F::ONE + F::from_bool(idx == height - 1);
139            row.exec_start = F::from_bool(idx == 0);
140            row.exec = ProgramExecutionCols {
141                pc: F::from_u32(pc),
142                opcode: instruction.opcode.to_field(),
143                a: instruction.a,
144                b: instruction.b,
145                c: instruction.c,
146                d: instruction.d,
147                e: instruction.e,
148                f: instruction.f,
149                g: instruction.g,
150            };
151        });
152
153    RowMajorMatrix::new(rows, width)
154}
155
156pub(super) fn padding_instruction<F: Field>() -> Instruction<F> {
157    Instruction::from_usize(
158        SystemOpcode::TERMINATE.global_opcode(),
159        [0, 0, EXIT_CODE_FAIL],
160    )
161}