kimchi/
prover_index.rs

1//! This module implements the prover index as [`ProverIndex`].
2
3use crate::{
4    alphas::Alphas,
5    circuits::{
6        berkeley_columns::{BerkeleyChallengeTerm, Column},
7        constraints::{ColumnEvaluations, ConstraintSystem},
8        expr::{Linearization, PolishToken},
9    },
10    curve::KimchiCurve,
11    linearization::expr_linearization,
12    o1_utils::lazy_cache::LazyCache,
13    verifier_index::VerifierIndex,
14};
15use ark_ff::PrimeField;
16use mina_poseidon::FqSponge;
17use poly_commitment::{OpenProof, SRS as _};
18use serde::{de::DeserializeOwned, Deserialize, Serialize};
19use serde_with::serde_as;
20use std::sync::Arc;
21
22/// The index used by the prover
23#[serde_as]
24#[derive(Serialize, Deserialize, Clone, Debug)]
25//~spec:startcode
26pub struct ProverIndex<G: KimchiCurve, OpeningProof: OpenProof<G>> {
27    /// constraints system polynomials
28    #[serde(bound = "ConstraintSystem<G::ScalarField>: Serialize + DeserializeOwned")]
29    pub cs: Arc<ConstraintSystem<G::ScalarField>>,
30
31    /// The symbolic linearization of our circuit, which can compile to concrete types once certain values are learned in the protocol.
32    #[serde(skip)]
33    pub linearization:
34        Linearization<Vec<PolishToken<G::ScalarField, Column, BerkeleyChallengeTerm>>, Column>,
35
36    /// The mapping between powers of alpha and constraints
37    #[serde(skip)]
38    pub powers_of_alpha: Alphas<G::ScalarField>,
39
40    /// polynomial commitment keys
41    #[serde(skip)]
42    #[serde(bound(deserialize = "OpeningProof::SRS: Default"))]
43    pub srs: Arc<OpeningProof::SRS>,
44
45    /// maximal size of polynomial section
46    pub max_poly_size: usize,
47
48    #[serde(bound = "ColumnEvaluations<G::ScalarField>: Serialize + DeserializeOwned")]
49    pub column_evaluations: Arc<LazyCache<ColumnEvaluations<G::ScalarField>>>,
50
51    /// The verifier index corresponding to this prover index
52    #[serde(skip)]
53    pub verifier_index: Option<VerifierIndex<G, OpeningProof>>,
54
55    /// The verifier index digest corresponding to this prover index
56    #[serde_as(as = "Option<o1_utils::serialization::SerdeAs>")]
57    pub verifier_index_digest: Option<G::BaseField>,
58}
59//~spec:endcode
60
61impl<G: KimchiCurve, OpeningProof: OpenProof<G>> ProverIndex<G, OpeningProof>
62where
63    G::BaseField: PrimeField,
64{
65    /// this function compiles the index from constraints
66    pub fn create(
67        mut cs: ConstraintSystem<G::ScalarField>,
68        endo_q: G::ScalarField,
69        srs: Arc<OpeningProof::SRS>,
70        lazy_mode: bool,
71    ) -> Self {
72        let max_poly_size = srs.max_poly_size();
73        cs.endo = endo_q;
74
75        // pre-compute the linearization
76        let (linearization, powers_of_alpha) = expr_linearization(Some(&cs.feature_flags), true);
77
78        let evaluated_column_coefficients = cs.evaluated_column_coefficients();
79
80        let cs = Arc::new(cs);
81        let cs_clone = Arc::clone(&cs);
82        let column_evaluations =
83            LazyCache::new(move || cs_clone.column_evaluations(&evaluated_column_coefficients));
84        if !lazy_mode {
85            // precompute the values
86            column_evaluations.get();
87        };
88
89        ProverIndex {
90            cs,
91            linearization,
92            powers_of_alpha,
93            srs,
94            max_poly_size,
95            column_evaluations: Arc::new(column_evaluations),
96            verifier_index: None,
97            verifier_index_digest: None,
98        }
99    }
100
101    /// Retrieve or compute the digest for the corresponding verifier index.
102    /// If the digest is not already cached inside the index, store it.
103    pub fn compute_verifier_index_digest<
104        EFqSponge: Clone + FqSponge<G::BaseField, G, G::ScalarField>,
105    >(
106        &mut self,
107    ) -> G::BaseField
108    where
109        VerifierIndex<G, OpeningProof>: Clone,
110    {
111        if let Some(verifier_index_digest) = self.verifier_index_digest {
112            return verifier_index_digest;
113        }
114
115        if self.verifier_index.is_none() {
116            self.verifier_index = Some(self.verifier_index());
117        }
118
119        let verifier_index_digest = self.verifier_index_digest::<EFqSponge>();
120        self.verifier_index_digest = Some(verifier_index_digest);
121        verifier_index_digest
122    }
123
124    /// Retrieve or compute the digest for the corresponding verifier index.
125    pub fn verifier_index_digest<EFqSponge: Clone + FqSponge<G::BaseField, G, G::ScalarField>>(
126        &self,
127    ) -> G::BaseField
128    where
129        VerifierIndex<G, OpeningProof>: Clone,
130    {
131        if let Some(verifier_index_digest) = self.verifier_index_digest {
132            return verifier_index_digest;
133        }
134
135        match &self.verifier_index {
136            None => {
137                let verifier_index = self.verifier_index();
138                verifier_index.digest::<EFqSponge>()
139            }
140            Some(verifier_index) => verifier_index.digest::<EFqSponge>(),
141        }
142    }
143}
144
145pub mod testing {
146    use super::*;
147    use crate::circuits::{
148        gate::CircuitGate,
149        lookup::{runtime_tables::RuntimeTableCfg, tables::LookupTable},
150    };
151    use ark_ff::PrimeField;
152    use ark_poly::{EvaluationDomain, Radix2EvaluationDomain as D};
153    use poly_commitment::{
154        ipa::{OpeningProof, SRS},
155        precomputed_srs, OpenProof,
156    };
157
158    #[allow(clippy::too_many_arguments)]
159    pub fn new_index_for_test_with_lookups_and_custom_srs<
160        G: KimchiCurve,
161        OpeningProof: OpenProof<G>,
162        F: FnMut(D<G::ScalarField>, usize) -> OpeningProof::SRS,
163    >(
164        gates: Vec<CircuitGate<G::ScalarField>>,
165        public: usize,
166        prev_challenges: usize,
167        lookup_tables: Vec<LookupTable<G::ScalarField>>,
168        runtime_tables: Option<Vec<RuntimeTableCfg<G::ScalarField>>>,
169        disable_gates_checks: bool,
170        override_srs_size: Option<usize>,
171        mut get_srs: F,
172        lazy_mode: bool,
173    ) -> ProverIndex<G, OpeningProof>
174    where
175        G::BaseField: PrimeField,
176        G::ScalarField: PrimeField,
177    {
178        // not sure if theres a smarter way instead of the double unwrap, but should be fine in the test
179        let cs = ConstraintSystem::<G::ScalarField>::create(gates)
180            .lookup(lookup_tables)
181            .runtime(runtime_tables)
182            .public(public)
183            .prev_challenges(prev_challenges)
184            .disable_gates_checks(disable_gates_checks)
185            .max_poly_size(override_srs_size)
186            .lazy_mode(lazy_mode)
187            .build()
188            .unwrap();
189
190        let srs_size = override_srs_size.unwrap_or_else(|| cs.domain.d1.size());
191        let srs = get_srs(cs.domain.d1, srs_size);
192        let srs = Arc::new(srs);
193
194        let &endo_q = G::other_curve_endo();
195        ProverIndex::create(cs, endo_q, srs, lazy_mode)
196    }
197
198    /// Create new index for lookups.
199    ///
200    /// # Panics
201    ///
202    /// Will panic if `constraint system` is not built with `gates` input.
203    pub fn new_index_for_test_with_lookups<G: KimchiCurve>(
204        gates: Vec<CircuitGate<G::ScalarField>>,
205        public: usize,
206        prev_challenges: usize,
207        lookup_tables: Vec<LookupTable<G::ScalarField>>,
208        runtime_tables: Option<Vec<RuntimeTableCfg<G::ScalarField>>>,
209        disable_gates_checks: bool,
210        override_srs_size: Option<usize>,
211        lazy_mode: bool,
212    ) -> ProverIndex<G, OpeningProof<G>>
213    where
214        G::BaseField: PrimeField,
215        G::ScalarField: PrimeField,
216    {
217        new_index_for_test_with_lookups_and_custom_srs(
218            gates,
219            public,
220            prev_challenges,
221            lookup_tables,
222            runtime_tables,
223            disable_gates_checks,
224            override_srs_size,
225            |d1: D<G::ScalarField>, size: usize| {
226                let log2_size = size.ilog2();
227                let srs = if log2_size <= precomputed_srs::SERIALIZED_SRS_SIZE {
228                    // TODO: we should trim it if it's smaller
229                    precomputed_srs::get_srs_test()
230                } else {
231                    // TODO: we should resume the SRS generation starting from the serialized one
232                    SRS::<G>::create(size)
233                };
234
235                srs.get_lagrange_basis(d1);
236                srs
237            },
238            lazy_mode,
239        )
240    }
241
242    pub fn new_index_for_test<G: KimchiCurve>(
243        gates: Vec<CircuitGate<G::ScalarField>>,
244        public: usize,
245    ) -> ProverIndex<G, OpeningProof<G>>
246    where
247        G::BaseField: PrimeField,
248        G::ScalarField: PrimeField,
249    {
250        new_index_for_test_with_lookups::<G>(gates, public, 0, vec![], None, false, None, false)
251    }
252}