openvm_circuit/system/connector/
mod.rs

1use std::{
2    borrow::{Borrow, BorrowMut},
3    marker::PhantomData,
4    sync::Arc,
5};
6
7use openvm_circuit_primitives::var_range::{
8    SharedVariableRangeCheckerChip, VariableRangeCheckerBus,
9};
10use openvm_circuit_primitives_derive::AlignedBorrow;
11use openvm_instructions::LocalOpcode;
12use openvm_stark_backend::{
13    config::{StarkGenericConfig, Val},
14    interaction::InteractionBuilder,
15    p3_air::{Air, AirBuilder, AirBuilderWithPublicValues, BaseAir, PairBuilder},
16    p3_field::{Field, PrimeCharacteristicRing, PrimeField32},
17    p3_matrix::{dense::RowMajorMatrix, Matrix},
18    prover::{cpu::CpuBackend, types::AirProvingContext},
19    rap::{BaseAirWithPublicValues, PartitionedBaseAir},
20    Chip, ChipUsageGetter,
21};
22use serde::{Deserialize, Serialize};
23
24use crate::{
25    arch::{instructions::SystemOpcode::TERMINATE, ExecutionBus, ExecutionState},
26    system::program::ProgramBus,
27};
28
29#[cfg(test)]
30mod tests;
31
32/// When a program hasn't terminated. There is no constraints on the exit code.
33/// But we will use this value when generating the proof.
34pub const DEFAULT_SUSPEND_EXIT_CODE: u32 = 42;
35
36#[derive(Debug, Clone, Copy)]
37pub struct VmConnectorAir {
38    pub execution_bus: ExecutionBus,
39    pub program_bus: ProgramBus,
40    pub range_bus: VariableRangeCheckerBus,
41    /// The final timestamp will be constrained to be in the range [0, 2^timestamp_max_bits).
42    timestamp_max_bits: usize,
43}
44
45#[derive(Debug, Clone, Copy, AlignedBorrow)]
46#[repr(C)]
47pub struct VmConnectorPvs<F> {
48    /// The initial PC of this segment.
49    pub initial_pc: F,
50    /// The final PC of this segment.
51    pub final_pc: F,
52    /// The exit code of the whole program. 0 means exited normally. This is only meaningful when
53    /// `is_terminate` is 1.
54    pub exit_code: F,
55    /// Whether the whole program is terminated. 0 means not terminated. 1 means terminated.
56    /// Only the last segment of an execution can have `is_terminate` = 1.
57    pub is_terminate: F,
58}
59
60impl<F: PrimeField32> VmConnectorPvs<F> {
61    pub fn is_terminate(&self) -> bool {
62        self.is_terminate == F::from_bool(true)
63    }
64
65    pub fn exit_code(&self) -> Option<u32> {
66        if self.is_terminate() && self.exit_code == F::ZERO {
67            Some(self.exit_code.as_canonical_u32())
68        } else {
69            None
70        }
71    }
72}
73
74impl<F: Field> BaseAirWithPublicValues<F> for VmConnectorAir {
75    fn num_public_values(&self) -> usize {
76        VmConnectorPvs::<F>::width()
77    }
78}
79impl<F: Field> PartitionedBaseAir<F> for VmConnectorAir {}
80impl<F: Field> BaseAir<F> for VmConnectorAir {
81    fn width(&self) -> usize {
82        5
83    }
84
85    fn preprocessed_trace(&self) -> Option<RowMajorMatrix<F>> {
86        Some(RowMajorMatrix::new_col(vec![F::ZERO, F::ONE]))
87    }
88}
89
90impl VmConnectorAir {
91    pub fn new(
92        execution_bus: ExecutionBus,
93        program_bus: ProgramBus,
94        range_bus: VariableRangeCheckerBus,
95        timestamp_max_bits: usize,
96    ) -> Self {
97        assert!(
98            range_bus.range_max_bits * 2 >= timestamp_max_bits,
99            "Range checker not large enough: range_max_bits={}, timestamp_max_bits={}",
100            range_bus.range_max_bits,
101            timestamp_max_bits
102        );
103        Self {
104            execution_bus,
105            program_bus,
106            range_bus,
107            timestamp_max_bits,
108        }
109    }
110
111    /// Returns (low_bits, high_bits) to range check.
112    fn timestamp_limb_bits(&self) -> (usize, usize) {
113        let range_max_bits = self.range_bus.range_max_bits;
114        if self.timestamp_max_bits <= range_max_bits {
115            (self.timestamp_max_bits, 0)
116        } else {
117            (range_max_bits, self.timestamp_max_bits - range_max_bits)
118        }
119    }
120}
121
122#[derive(Debug, Copy, Clone, AlignedBorrow, Serialize, Deserialize)]
123#[repr(C)]
124pub struct ConnectorCols<T> {
125    pub pc: T,
126    pub timestamp: T,
127    pub is_terminate: T,
128    pub exit_code: T,
129    /// Lowest `range_bus.range_max_bits` bits of the timestamp
130    timestamp_low_limb: T,
131}
132
133impl<T: Copy> ConnectorCols<T> {
134    fn map<F>(self, f: impl Fn(T) -> F) -> ConnectorCols<F> {
135        ConnectorCols {
136            pc: f(self.pc),
137            timestamp: f(self.timestamp),
138            is_terminate: f(self.is_terminate),
139            exit_code: f(self.exit_code),
140            timestamp_low_limb: f(self.timestamp_low_limb),
141        }
142    }
143
144    fn flatten(&self) -> [T; 5] {
145        [
146            self.pc,
147            self.timestamp,
148            self.is_terminate,
149            self.exit_code,
150            self.timestamp_low_limb,
151        ]
152    }
153}
154
155impl<AB: InteractionBuilder + PairBuilder + AirBuilderWithPublicValues> Air<AB> for VmConnectorAir {
156    fn eval(&self, builder: &mut AB) {
157        let main = builder.main();
158        let preprocessed = builder.preprocessed();
159        let prep_local = preprocessed
160            .row_slice(0)
161            .expect("window should have two elements");
162        let (begin, end) = (
163            main.row_slice(0).expect("window should have two elements"),
164            main.row_slice(1).expect("window should have two elements"),
165        );
166
167        let begin: &ConnectorCols<AB::Var> = (*begin).borrow();
168        let end: &ConnectorCols<AB::Var> = (*end).borrow();
169
170        let &VmConnectorPvs {
171            initial_pc,
172            final_pc,
173            exit_code,
174            is_terminate,
175        } = builder.public_values().borrow();
176
177        builder.when_transition().assert_eq(begin.pc, initial_pc);
178        builder.when_transition().assert_eq(end.pc, final_pc);
179        builder
180            .when_transition()
181            .when(end.is_terminate)
182            .assert_eq(end.exit_code, exit_code);
183        builder
184            .when_transition()
185            .assert_eq(end.is_terminate, is_terminate);
186
187        builder.when_transition().assert_one(begin.timestamp);
188
189        self.execution_bus.execute(
190            builder,
191            AB::Expr::ONE - prep_local[0], // 1 only if these are [0th, 1st] and not [1st, 0th]
192            ExecutionState::new(end.pc, end.timestamp),
193            ExecutionState::new(begin.pc, begin.timestamp),
194        );
195        self.program_bus.lookup_instruction(
196            builder,
197            end.pc,
198            AB::Expr::from_usize(TERMINATE.global_opcode().as_usize()),
199            [AB::Expr::ZERO, AB::Expr::ZERO, end.exit_code.into()],
200            (AB::Expr::ONE - prep_local[0]) * end.is_terminate,
201        );
202
203        // The following constraints hold on every row, so we rename `begin` to `local` to avoid
204        // confusion.
205        let local = begin;
206        // We decompose and range check `local.timestamp` as `timestamp_low_limb,
207        // timestamp_high_limb` where `timestamp = timestamp_low_limb + timestamp_high_limb
208        // * 2^range_max_bits`.
209        let (low_bits, high_bits) = self.timestamp_limb_bits();
210        let high_limb = (local.timestamp - local.timestamp_low_limb)
211            * AB::F::ONE.div_2exp_u64(self.range_bus.range_max_bits as u64);
212        self.range_bus
213            .range_check(local.timestamp_low_limb, low_bits)
214            .eval(builder, AB::Expr::ONE);
215        self.range_bus
216            .range_check(high_limb, high_bits)
217            .eval(builder, AB::Expr::ONE);
218    }
219}
220
221pub struct VmConnectorChip<F> {
222    pub range_checker: SharedVariableRangeCheckerChip,
223    pub boundary_states: [Option<ConnectorCols<u32>>; 2],
224    timestamp_max_bits: usize,
225    _marker: PhantomData<F>,
226}
227
228impl<F> VmConnectorChip<F> {
229    pub fn new(range_checker: SharedVariableRangeCheckerChip, timestamp_max_bits: usize) -> Self {
230        let range_bus = range_checker.bus();
231        assert!(
232            range_bus.range_max_bits * 2 >= timestamp_max_bits,
233            "Range checker not large enough: range_max_bits={}, timestamp_max_bits={}",
234            range_bus.range_max_bits,
235            timestamp_max_bits
236        );
237        Self {
238            range_checker,
239            boundary_states: [None, None],
240            timestamp_max_bits,
241            _marker: PhantomData,
242        }
243    }
244
245    pub fn begin(&mut self, state: ExecutionState<u32>) {
246        self.boundary_states[0] = Some(ConnectorCols {
247            pc: state.pc,
248            timestamp: state.timestamp,
249            is_terminate: 0,
250            exit_code: 0,
251            timestamp_low_limb: 0, // will be computed during tracegen
252        });
253    }
254
255    pub fn end(&mut self, state: ExecutionState<u32>, exit_code: Option<u32>) {
256        self.boundary_states[1] = Some(ConnectorCols {
257            pc: state.pc,
258            timestamp: state.timestamp,
259            is_terminate: exit_code.is_some() as u32,
260            exit_code: exit_code.unwrap_or(DEFAULT_SUSPEND_EXIT_CODE),
261            timestamp_low_limb: 0, // will be computed during tracegen
262        });
263    }
264
265    fn timestamp_limb_bits(&self) -> (usize, usize) {
266        let range_max_bits = self.range_checker.bus().range_max_bits;
267        if self.timestamp_max_bits <= range_max_bits {
268            (self.timestamp_max_bits, 0)
269        } else {
270            (range_max_bits, self.timestamp_max_bits - range_max_bits)
271        }
272    }
273}
274
275impl<RA, SC> Chip<RA, CpuBackend<SC>> for VmConnectorChip<Val<SC>>
276where
277    SC: StarkGenericConfig,
278    Val<SC>: PrimeField32,
279{
280    fn generate_proving_ctx(&self, _: RA) -> AirProvingContext<CpuBackend<SC>> {
281        let [initial_state, final_state] = self.boundary_states.map(|state| {
282            let mut state = state.unwrap();
283            // Decompose and range check timestamp
284            let range_max_bits = self.range_checker.range_max_bits();
285            let timestamp_low_limb = state.timestamp & ((1u32 << range_max_bits) - 1);
286            state.timestamp_low_limb = timestamp_low_limb;
287            let (low_bits, high_bits) = self.timestamp_limb_bits();
288            self.range_checker.add_count(timestamp_low_limb, low_bits);
289            self.range_checker
290                .add_count(state.timestamp >> range_max_bits, high_bits);
291
292            state.map(Val::<SC>::from_u32)
293        });
294
295        let trace = Arc::new(RowMajorMatrix::new(
296            [initial_state.flatten(), final_state.flatten()].concat(),
297            self.trace_width(),
298        ));
299
300        let mut public_values = Val::<SC>::zero_vec(VmConnectorPvs::<Val<SC>>::width());
301        *public_values.as_mut_slice().borrow_mut() = VmConnectorPvs {
302            initial_pc: initial_state.pc,
303            final_pc: final_state.pc,
304            exit_code: final_state.exit_code,
305            is_terminate: final_state.is_terminate,
306        };
307        AirProvingContext::simple(trace, public_values)
308    }
309}
310
311impl<F: PrimeField32> ChipUsageGetter for VmConnectorChip<F> {
312    fn air_name(&self) -> String {
313        "VmConnectorAir".to_string()
314    }
315
316    fn constant_trace_height(&self) -> Option<usize> {
317        Some(2)
318    }
319
320    fn current_trace_height(&self) -> usize {
321        2
322    }
323
324    fn trace_width(&self) -> usize {
325        5
326    }
327}