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, FieldAlgebra, 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.row_slice(0);
160        let (begin, end) = (main.row_slice(0), main.row_slice(1));
161
162        let begin: &ConnectorCols<AB::Var> = (*begin).borrow();
163        let end: &ConnectorCols<AB::Var> = (*end).borrow();
164
165        let &VmConnectorPvs {
166            initial_pc,
167            final_pc,
168            exit_code,
169            is_terminate,
170        } = builder.public_values().borrow();
171
172        builder.when_transition().assert_eq(begin.pc, initial_pc);
173        builder.when_transition().assert_eq(end.pc, final_pc);
174        builder
175            .when_transition()
176            .when(end.is_terminate)
177            .assert_eq(end.exit_code, exit_code);
178        builder
179            .when_transition()
180            .assert_eq(end.is_terminate, is_terminate);
181
182        builder.when_transition().assert_one(begin.timestamp);
183
184        self.execution_bus.execute(
185            builder,
186            AB::Expr::ONE - prep_local[0], // 1 only if these are [0th, 1st] and not [1st, 0th]
187            ExecutionState::new(end.pc, end.timestamp),
188            ExecutionState::new(begin.pc, begin.timestamp),
189        );
190        self.program_bus.lookup_instruction(
191            builder,
192            end.pc,
193            AB::Expr::from_canonical_usize(TERMINATE.global_opcode().as_usize()),
194            [AB::Expr::ZERO, AB::Expr::ZERO, end.exit_code.into()],
195            (AB::Expr::ONE - prep_local[0]) * end.is_terminate,
196        );
197
198        // The following constraints hold on every row, so we rename `begin` to `local` to avoid
199        // confusion.
200        let local = begin;
201        // We decompose and range check `local.timestamp` as `timestamp_low_limb,
202        // timestamp_high_limb` where `timestamp = timestamp_low_limb + timestamp_high_limb
203        // * 2^range_max_bits`.
204        let (low_bits, high_bits) = self.timestamp_limb_bits();
205        let high_limb = (local.timestamp - local.timestamp_low_limb)
206            * AB::F::ONE.div_2exp_u64(self.range_bus.range_max_bits as u64);
207        self.range_bus
208            .range_check(local.timestamp_low_limb, low_bits)
209            .eval(builder, AB::Expr::ONE);
210        self.range_bus
211            .range_check(high_limb, high_bits)
212            .eval(builder, AB::Expr::ONE);
213    }
214}
215
216pub struct VmConnectorChip<F> {
217    pub range_checker: SharedVariableRangeCheckerChip,
218    pub boundary_states: [Option<ConnectorCols<u32>>; 2],
219    timestamp_max_bits: usize,
220    _marker: PhantomData<F>,
221}
222
223impl<F> VmConnectorChip<F> {
224    pub fn new(range_checker: SharedVariableRangeCheckerChip, timestamp_max_bits: usize) -> Self {
225        let range_bus = range_checker.bus();
226        assert!(
227            range_bus.range_max_bits * 2 >= timestamp_max_bits,
228            "Range checker not large enough: range_max_bits={}, timestamp_max_bits={}",
229            range_bus.range_max_bits,
230            timestamp_max_bits
231        );
232        Self {
233            range_checker,
234            boundary_states: [None, None],
235            timestamp_max_bits,
236            _marker: PhantomData,
237        }
238    }
239
240    pub fn begin(&mut self, state: ExecutionState<u32>) {
241        self.boundary_states[0] = Some(ConnectorCols {
242            pc: state.pc,
243            timestamp: state.timestamp,
244            is_terminate: 0,
245            exit_code: 0,
246            timestamp_low_limb: 0, // will be computed during tracegen
247        });
248    }
249
250    pub fn end(&mut self, state: ExecutionState<u32>, exit_code: Option<u32>) {
251        self.boundary_states[1] = Some(ConnectorCols {
252            pc: state.pc,
253            timestamp: state.timestamp,
254            is_terminate: exit_code.is_some() as u32,
255            exit_code: exit_code.unwrap_or(DEFAULT_SUSPEND_EXIT_CODE),
256            timestamp_low_limb: 0, // will be computed during tracegen
257        });
258    }
259
260    fn timestamp_limb_bits(&self) -> (usize, usize) {
261        let range_max_bits = self.range_checker.bus().range_max_bits;
262        if self.timestamp_max_bits <= range_max_bits {
263            (self.timestamp_max_bits, 0)
264        } else {
265            (range_max_bits, self.timestamp_max_bits - range_max_bits)
266        }
267    }
268}
269
270impl<RA, SC> Chip<RA, CpuBackend<SC>> for VmConnectorChip<Val<SC>>
271where
272    SC: StarkGenericConfig,
273    Val<SC>: PrimeField32,
274{
275    fn generate_proving_ctx(&self, _: RA) -> AirProvingContext<CpuBackend<SC>> {
276        let [initial_state, final_state] = self.boundary_states.map(|state| {
277            let mut state = state.unwrap();
278            // Decompose and range check timestamp
279            let range_max_bits = self.range_checker.range_max_bits();
280            let timestamp_low_limb = state.timestamp & ((1u32 << range_max_bits) - 1);
281            state.timestamp_low_limb = timestamp_low_limb;
282            let (low_bits, high_bits) = self.timestamp_limb_bits();
283            self.range_checker.add_count(timestamp_low_limb, low_bits);
284            self.range_checker
285                .add_count(state.timestamp >> range_max_bits, high_bits);
286
287            state.map(Val::<SC>::from_canonical_u32)
288        });
289
290        let trace = Arc::new(RowMajorMatrix::new(
291            [initial_state.flatten(), final_state.flatten()].concat(),
292            self.trace_width(),
293        ));
294
295        let mut public_values = Val::<SC>::zero_vec(VmConnectorPvs::<Val<SC>>::width());
296        *public_values.as_mut_slice().borrow_mut() = VmConnectorPvs {
297            initial_pc: initial_state.pc,
298            final_pc: final_state.pc,
299            exit_code: final_state.exit_code,
300            is_terminate: final_state.is_terminate,
301        };
302        AirProvingContext::simple(trace, public_values)
303    }
304}
305
306impl<F: PrimeField32> ChipUsageGetter for VmConnectorChip<F> {
307    fn air_name(&self) -> String {
308        "VmConnectorAir".to_string()
309    }
310
311    fn constant_trace_height(&self) -> Option<usize> {
312        Some(2)
313    }
314
315    fn current_trace_height(&self) -> usize {
316        2
317    }
318
319    fn trace_width(&self) -> usize {
320        5
321    }
322}