p3-miden-prover 0.4.2

Miden-specific STARK prover built on Plonky3.
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
use alloc::vec;
use alloc::vec::Vec;

use p3_field::{ExtensionField, Field};
use p3_miden_air::{MidenAir, MidenAirBuilder, RowMajorMatrix};
use p3_util::log2_ceil_usize;
use tracing::instrument;

use crate::{Entry, SymbolicExpression, SymbolicVariable};

#[instrument(name = "infer log of constraint degree", skip_all)]
pub fn get_log_quotient_degree<F, EF, A>(
    air: &A,
    preprocessed_width: usize,
    num_public_values: usize,
    is_zk: usize,
    aux_width: usize,
    num_randomness: usize,
) -> usize
where
    F: Field,
    EF: ExtensionField<F>,
    A: MidenAir<F, EF>,
{
    assert!(is_zk <= 1, "is_zk must be either 0 or 1");
    // We pad to at least degree 2, since a quotient argument doesn't make sense with smaller degrees.
    let constraint_degree = (get_max_constraint_degree::<F, EF, A>(
        air,
        preprocessed_width,
        num_public_values,
        aux_width,
        num_randomness,
    ) + is_zk)
        .max(2);

    // The quotient's actual degree is approximately (max_constraint_degree - 1) n,
    // where subtracting 1 comes from division by the vanishing polynomial.
    // But we pad it to a power of two so that we can efficiently decompose the quotient.
    log2_ceil_usize(constraint_degree - 1)
}

#[instrument(name = "infer constraint degree", skip_all, level = "debug")]
pub fn get_max_constraint_degree<F, EF, A>(
    air: &A,
    preprocessed_width: usize,
    num_public_values: usize,
    aux_width: usize,
    num_randomness: usize,
) -> usize
where
    F: Field,
    EF: ExtensionField<F>,
    A: MidenAir<F, EF>,
{
    get_symbolic_constraints::<F, EF, A>(
        air,
        preprocessed_width,
        num_public_values,
        aux_width,
        num_randomness,
    )
    .iter()
    .map(|c| c.degree_multiple())
    .max()
    .unwrap_or(0)
}

#[instrument(name = "evaluate constraints symbolically", skip_all, level = "debug")]
pub fn get_symbolic_constraints<F, EF, A>(
    air: &A,
    preprocessed_width: usize,
    num_public_values: usize,
    aux_width: usize,
    num_randomness: usize,
) -> Vec<SymbolicExpression<F>>
where
    F: Field,
    EF: ExtensionField<F>,
    A: MidenAir<F, EF>,
{
    let num_periodic_values = air.periodic_table().len();
    let mut builder = SymbolicAirBuilder::<F>::new_with_periodic(
        preprocessed_width,
        air.width(),
        aux_width,
        num_randomness,
        num_public_values,
        num_periodic_values,
    );
    air.eval(&mut builder);
    builder.constraints()
}

/// An `AirBuilder` for evaluating constraints symbolically, and recording them for later use.
#[derive(Debug)]
pub struct SymbolicAirBuilder<F: Field> {
    preprocessed: RowMajorMatrix<SymbolicVariable<F>>,
    main: RowMajorMatrix<SymbolicVariable<F>>,
    aux: RowMajorMatrix<SymbolicVariable<F>>,
    aux_randomness: Vec<SymbolicVariable<F>>,
    aux_bus_boundary_values: Vec<SymbolicVariable<F>>,
    public_values: Vec<SymbolicVariable<F>>,
    periodic_values: Vec<SymbolicVariable<F>>,
    constraints: Vec<SymbolicExpression<F>>,
}

impl<F: Field> SymbolicAirBuilder<F> {
    pub fn new(
        preprocessed_width: usize,
        width: usize,
        aux_width: usize,
        num_randomness: usize,
        num_public_values: usize,
    ) -> Self {
        Self::new_with_periodic(
            preprocessed_width,
            width,
            aux_width,
            num_randomness,
            num_public_values,
            0,
        )
    }

    pub fn new_with_periodic(
        preprocessed_width: usize,
        width: usize,
        aux_width: usize,
        num_randomness: usize,
        num_public_values: usize,
        num_periodic_values: usize,
    ) -> Self {
        let prep_values = [0, 1]
            .into_iter()
            .flat_map(|offset| {
                (0..preprocessed_width)
                    .map(move |index| SymbolicVariable::new(Entry::Preprocessed { offset }, index))
            })
            .collect();
        let main_values = [0, 1]
            .into_iter()
            .flat_map(|offset| {
                (0..width).map(move |index| SymbolicVariable::new(Entry::Main { offset }, index))
            })
            .collect();
        let aux_values = [0, 1] // Aux trace also use consecutive rows for LogUp based permutation check
            .into_iter()
            .flat_map(|offset| {
                (0..aux_width).map(move |index| SymbolicVariable::new(Entry::Aux { offset }, index))
            })
            .collect();
        let aux = RowMajorMatrix::new(aux_values, aux_width);
        let randomness = Self::sample_randomness(num_randomness);
        let aux_bus_boundary_values = (0..aux_width)
            .map(move |index| SymbolicVariable::new(Entry::AuxBusBoundary, index))
            .collect();
        let public_values = (0..num_public_values)
            .map(move |index| SymbolicVariable::new(Entry::Public, index))
            .collect();
        let periodic_values = (0..num_periodic_values)
            .map(move |index| SymbolicVariable::new(Entry::Periodic, index))
            .collect();
        Self {
            preprocessed: RowMajorMatrix::new(prep_values, preprocessed_width),
            main: RowMajorMatrix::new(main_values, width),
            aux,
            aux_randomness: randomness,
            aux_bus_boundary_values,
            public_values,
            periodic_values,
            constraints: vec![],
        }
    }

    pub fn constraints(self) -> Vec<SymbolicExpression<F>> {
        self.constraints
    }

    pub(crate) fn sample_randomness(num_randomness: usize) -> Vec<SymbolicVariable<F>> {
        (0..num_randomness)
            .map(|index| SymbolicVariable::new(Entry::Challenge, index))
            .collect()
    }
}

impl<F: Field> MidenAirBuilder for SymbolicAirBuilder<F> {
    type F = F;
    type Expr = SymbolicExpression<F>;
    type Var = SymbolicVariable<F>;
    type M = RowMajorMatrix<Self::Var>;
    type EF = F;
    type ExprEF = SymbolicExpression<F>;
    type VarEF = SymbolicVariable<F>;
    type PeriodicVal = SymbolicVariable<F>;

    type PublicVar = SymbolicVariable<F>;

    type MP = RowMajorMatrix<SymbolicVariable<F>>;
    type RandomVar = SymbolicVariable<F>;

    fn main(&self) -> Self::M {
        self.main.clone()
    }

    fn is_first_row(&self) -> Self::Expr {
        SymbolicExpression::IsFirstRow
    }

    fn is_last_row(&self) -> Self::Expr {
        SymbolicExpression::IsLastRow
    }

    /// # Panics
    /// This function panics if `size` is not `2`.
    fn is_transition_window(&self, size: usize) -> Self::Expr {
        if size == 2 {
            SymbolicExpression::IsTransition
        } else {
            panic!("uni-stark only supports a window size of 2")
        }
    }

    fn assert_zero<I: Into<Self::Expr>>(&mut self, x: I) {
        self.constraints.push(x.into());
    }

    fn permutation(&self) -> Self::MP {
        self.aux.clone()
    }

    fn permutation_randomness(&self) -> &[Self::RandomVar] {
        &self.aux_randomness
    }

    fn aux_bus_boundary_values(&self) -> &[Self::VarEF] {
        &self.aux_bus_boundary_values
    }

    fn public_values(&self) -> &[Self::PublicVar] {
        &self.public_values
    }

    fn assert_zero_ext<I>(&mut self, x: I)
    where
        I: Into<Self::ExprEF>,
    {
        self.constraints.push(x.into());
    }

    fn preprocessed(&self) -> Self::M {
        self.preprocessed.clone()
    }

    fn periodic_evals(&self) -> &[<Self as MidenAirBuilder>::PeriodicVal] {
        &self.periodic_values
    }
}

#[cfg(test)]
mod tests {
    use p3_field::PrimeCharacteristicRing;
    use p3_goldilocks::Goldilocks;
    use p3_matrix::Matrix;
    use p3_miden_air::MidenAir;

    use super::*;

    #[derive(Debug)]
    struct MockAir {
        // Store (entry_type, index) pairs instead of SymbolicVariables
        constraint_specs: Vec<(Entry, usize)>,
        width: usize,
    }

    impl MidenAir<Goldilocks, Goldilocks> for MockAir {
        fn width(&self) -> usize {
            self.width
        }

        fn eval<AB: MidenAirBuilder<F = Goldilocks>>(&self, builder: &mut AB) {
            let main = builder.main();

            for (entry, index) in &self.constraint_specs {
                match entry {
                    Entry::Main { offset } => {
                        builder.assert_zero(main.row_slice(*offset).unwrap()[*index].clone());
                    }
                    _ => panic!("Test only supports Main entry"),
                }
            }
        }
    }

    #[test]
    fn test_get_log_quotient_degree_no_constraints() {
        let air = MockAir {
            constraint_specs: vec![],
            width: 4,
        };
        let log_degree = get_log_quotient_degree::<Goldilocks, Goldilocks, _>(&air, 3, 2, 0, 0, 0);
        assert_eq!(log_degree, 0);
    }

    #[test]
    fn test_get_log_quotient_degree_single_constraint() {
        let air = MockAir {
            constraint_specs: vec![(Entry::Main { offset: 0 }, 0)],
            width: 4,
        };
        let log_degree = get_log_quotient_degree::<Goldilocks, Goldilocks, _>(&air, 3, 2, 0, 0, 0);
        assert_eq!(log_degree, log2_ceil_usize(1));
    }

    #[test]
    fn test_get_log_quotient_degree_multiple_constraints() {
        let air = MockAir {
            constraint_specs: vec![
                (Entry::Main { offset: 0 }, 0),
                (Entry::Main { offset: 1 }, 1),
                (Entry::Main { offset: 0 }, 2),
            ],
            width: 4,
        };
        let log_degree = get_log_quotient_degree::<Goldilocks, Goldilocks, _>(&air, 3, 2, 0, 0, 0);
        assert_eq!(log_degree, log2_ceil_usize(1));
    }

    #[test]
    fn test_get_max_constraint_degree_no_constraints() {
        let air = MockAir {
            constraint_specs: vec![],
            width: 4,
        };
        let max_degree = get_max_constraint_degree::<Goldilocks, Goldilocks, _>(&air, 3, 2, 0, 0);
        assert_eq!(
            max_degree, 0,
            "No constraints should result in a degree of 0"
        );
    }

    #[test]
    fn test_get_max_constraint_degree_multiple_constraints() {
        let air = MockAir {
            constraint_specs: vec![
                (Entry::Main { offset: 0 }, 0),
                (Entry::Main { offset: 1 }, 1),
                (Entry::Main { offset: 0 }, 2),
            ],
            width: 4,
        };
        let max_degree = get_max_constraint_degree::<Goldilocks, Goldilocks, _>(&air, 3, 2, 0, 0);
        assert_eq!(max_degree, 1, "Max constraint degree should be 1");
    }

    #[test]
    fn test_get_symbolic_constraints() {
        let c1: SymbolicVariable<Goldilocks> = SymbolicVariable::new(Entry::Main { offset: 0 }, 0);
        let c2: SymbolicVariable<Goldilocks> = SymbolicVariable::new(Entry::Main { offset: 1 }, 1);

        let air = MockAir {
            constraint_specs: vec![
                (Entry::Main { offset: 0 }, 0),
                (Entry::Main { offset: 1 }, 1),
            ],
            width: 4,
        };

        let constraints = get_symbolic_constraints::<Goldilocks, Goldilocks, _>(&air, 3, 2, 0, 0);

        assert_eq!(constraints.len(), 2, "Should return exactly 2 constraints");

        assert!(
            constraints.iter().any(|x| matches!(x, SymbolicExpression::Variable(v) if v.index == c1.index && v.entry == c1.entry)),
            "Expected constraint {c1:?} was not found"
        );

        assert!(
            constraints.iter().any(|x| matches!(x, SymbolicExpression::Variable(v) if v.index == c2.index && v.entry == c2.entry)),
            "Expected constraint {c2:?} was not found"
        );
    }

    #[test]
    fn test_symbolic_air_builder_initialization() {
        let builder = SymbolicAirBuilder::<Goldilocks>::new(2, 4, 0, 0, 3);

        let expected_main = [
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 0 }, 0),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 0 }, 1),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 0 }, 2),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 0 }, 3),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 1 }, 0),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 1 }, 1),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 1 }, 2),
            SymbolicVariable::<Goldilocks>::new(Entry::Main { offset: 1 }, 3),
        ];

        let builder_main = builder.main.values;

        assert_eq!(
            builder_main.len(),
            expected_main.len(),
            "Main matrix should have the expected length"
        );

        for (expected, actual) in expected_main.iter().zip(builder_main.iter()) {
            assert_eq!(expected.index, actual.index, "Index mismatch");
            assert_eq!(expected.entry, actual.entry, "Entry mismatch");
        }
    }

    #[test]
    fn test_symbolic_air_builder_is_first_last_row() {
        let builder = SymbolicAirBuilder::<Goldilocks>::new(2, 4, 0, 0, 3);

        assert!(
            matches!(builder.is_first_row(), SymbolicExpression::IsFirstRow),
            "First row condition did not match"
        );

        assert!(
            matches!(builder.is_last_row(), SymbolicExpression::IsLastRow),
            "Last row condition did not match"
        );
    }

    #[test]
    fn test_symbolic_air_builder_assert_zero() {
        let mut builder = SymbolicAirBuilder::<Goldilocks>::new(2, 4, 0, 0, 3);
        let expr = SymbolicExpression::Constant(Goldilocks::from_u64(5));
        builder.assert_zero(expr);

        let constraints = builder.constraints();
        assert_eq!(constraints.len(), 1, "One constraint should be recorded");

        assert!(
            constraints.iter().any(
                |x| matches!(x, SymbolicExpression::Constant(val) if *val == Goldilocks::from_u64(5))
            ),
            "Constraint should match the asserted one"
        );
    }
}