p3_commit/
testing.rs

1use alloc::vec;
2use alloc::vec::Vec;
3use core::marker::PhantomData;
4
5use p3_challenger::CanSample;
6use p3_dft::TwoAdicSubgroupDft;
7use p3_field::coset::TwoAdicMultiplicativeCoset;
8use p3_field::{ExtensionField, Field, TwoAdicField};
9use p3_matrix::Matrix;
10use p3_matrix::dense::RowMajorMatrix;
11use p3_util::log2_strict_usize;
12use p3_util::zip_eq::zip_eq;
13use serde::{Deserialize, Serialize};
14
15use crate::{OpenedValues, Pcs};
16
17/// A trivial PCS: its commitment is simply the coefficients of each poly.
18#[derive(Debug)]
19pub struct TrivialPcs<Val: TwoAdicField, Dft: TwoAdicSubgroupDft<Val>> {
20    pub dft: Dft,
21    // degree bound
22    pub log_n: usize,
23    pub _phantom: PhantomData<Val>,
24}
25
26pub fn eval_coeffs_at_pt<F: Field, EF: ExtensionField<F>>(
27    coeffs: &RowMajorMatrix<F>,
28    x: EF,
29) -> Vec<EF> {
30    let mut acc = vec![EF::ZERO; coeffs.width()];
31    for r in (0..coeffs.height()).rev() {
32        let row = coeffs.row_slice(r).unwrap();
33        for (acc_c, row_c) in acc.iter_mut().zip(row.iter()) {
34            *acc_c *= x;
35            *acc_c += *row_c;
36        }
37    }
38    acc
39}
40
41impl<Val, Dft, Challenge, Challenger> Pcs<Challenge, Challenger> for TrivialPcs<Val, Dft>
42where
43    Val: TwoAdicField,
44    Challenge: ExtensionField<Val>,
45    Challenger: CanSample<Challenge>,
46    Dft: TwoAdicSubgroupDft<Val>,
47    Vec<Vec<Val>>: Serialize + for<'de> Deserialize<'de>,
48{
49    type Domain = TwoAdicMultiplicativeCoset<Val>;
50    type Commitment = Vec<Vec<Val>>;
51    type ProverData = Vec<RowMajorMatrix<Val>>;
52    type EvaluationsOnDomain<'a> = Dft::Evaluations;
53    type Proof = ();
54    type Error = ();
55    const ZK: bool = false;
56
57    fn natural_domain_for_degree(&self, degree: usize) -> Self::Domain {
58        // This panics if (and only if) `degree` is not a power of 2 or `degree`
59        // > `1 << Val::TWO_ADICITY`.
60        TwoAdicMultiplicativeCoset::new(Val::ONE, log2_strict_usize(degree)).unwrap()
61    }
62
63    fn commit(
64        &self,
65        evaluations: impl IntoIterator<Item = (Self::Domain, RowMajorMatrix<Val>)>,
66    ) -> (Self::Commitment, Self::ProverData) {
67        let coeffs: Vec<_> = evaluations
68            .into_iter()
69            .map(|(domain, evals)| {
70                let log_domain_size = log2_strict_usize(domain.size());
71                // for now, only commit on larger domain than natural
72                assert!(log_domain_size >= self.log_n);
73                assert_eq!(domain.size(), evals.height());
74                // coset_idft_batch
75                let mut coeffs = self.dft.idft_batch(evals);
76                coeffs
77                    .rows_mut()
78                    .zip(domain.shift_inverse().powers())
79                    .for_each(|(row, weight)| {
80                        row.iter_mut().for_each(|coeff| {
81                            *coeff *= weight;
82                        })
83                    });
84                coeffs
85            })
86            .collect();
87        (
88            coeffs.clone().into_iter().map(|m| m.values).collect(),
89            coeffs,
90        )
91    }
92
93    fn get_evaluations_on_domain<'a>(
94        &self,
95        prover_data: &'a Self::ProverData,
96        idx: usize,
97        domain: Self::Domain,
98    ) -> Self::EvaluationsOnDomain<'a> {
99        let mut coeffs = prover_data[idx].clone();
100        assert!(domain.log_size() >= self.log_n);
101        coeffs.values.resize(
102            coeffs.values.len() << (domain.log_size() - self.log_n),
103            Val::ZERO,
104        );
105        self.dft.coset_dft_batch(coeffs, domain.shift())
106    }
107
108    fn open(
109        &self,
110        // For each round,
111        rounds: Vec<(
112            &Self::ProverData,
113            // for each matrix,
114            Vec<
115                // points to open
116                Vec<Challenge>,
117            >,
118        )>,
119        _challenger: &mut Challenger,
120    ) -> (OpenedValues<Challenge>, Self::Proof) {
121        (
122            rounds
123                .into_iter()
124                .map(|(coeffs_for_round, points_for_round)| {
125                    // ensure that each matrix corresponds to a set of opening points
126                    debug_assert_eq!(coeffs_for_round.len(), points_for_round.len());
127                    coeffs_for_round
128                        .iter()
129                        .zip(points_for_round)
130                        .map(|(coeffs_for_mat, points_for_mat)| {
131                            points_for_mat
132                                .into_iter()
133                                .map(|pt| eval_coeffs_at_pt(coeffs_for_mat, pt))
134                                .collect()
135                        })
136                        .collect()
137                })
138                .collect(),
139            (),
140        )
141    }
142
143    // This is a testing function, so we allow panics for convenience.
144    #[allow(clippy::panic_in_result_fn)]
145    fn verify(
146        &self,
147        // For each round:
148        rounds: Vec<(
149            Self::Commitment,
150            // for each matrix:
151            Vec<(
152                // its domain,
153                Self::Domain,
154                // for each point:
155                Vec<(
156                    Challenge,
157                    // values at this point
158                    Vec<Challenge>,
159                )>,
160            )>,
161        )>,
162        _proof: &Self::Proof,
163        _challenger: &mut Challenger,
164    ) -> Result<(), Self::Error> {
165        for (comm, round_opening) in rounds {
166            for (coeff_vec, (domain, points_and_values)) in zip_eq(comm, round_opening, ())? {
167                let width = coeff_vec.len() / domain.size();
168                assert_eq!(width * domain.size(), coeff_vec.len());
169                let coeffs = RowMajorMatrix::new(coeff_vec, width);
170                for (pt, values) in points_and_values {
171                    assert_eq!(eval_coeffs_at_pt(&coeffs, pt), values);
172                }
173            }
174        }
175        Ok(())
176    }
177}