kimchi_stubs/
pasta_fq_plonk_index.rs

1use crate::{
2    arkworks::CamlFq, gate_vector::fq::CamlPastaFqPlonkGateVectorPtr, srs::fq::CamlFqSrs,
3    WithLagrangeBasis,
4};
5use ark_poly::EvaluationDomain;
6use kimchi::{
7    circuits::{
8        constraints::ConstraintSystem,
9        gate::CircuitGate,
10        lookup::{
11            runtime_tables::{caml::CamlRuntimeTableCfg, RuntimeTableCfg},
12            tables::{caml::CamlLookupTable, LookupTable},
13        },
14    },
15    linearization::expr_linearization,
16    prover_index::ProverIndex,
17};
18use mina_curves::pasta::{Fq, Pallas, PallasParameters, Vesta};
19use mina_poseidon::{constants::PlonkSpongeConstantsKimchi, sponge::DefaultFqSponge};
20use poly_commitment::{ipa::OpeningProof, SRS as _};
21use serde::{Deserialize, Serialize};
22use std::{
23    fs::{File, OpenOptions},
24    io::{BufReader, BufWriter, Seek, SeekFrom::Start},
25};
26
27/// Boxed so that we don't store large proving indexes in the OCaml heap.
28#[derive(ocaml_gen::CustomType)]
29pub struct CamlPastaFqPlonkIndex(pub Box<ProverIndex<Pallas, OpeningProof<Pallas>>>);
30pub type CamlPastaFqPlonkIndexPtr<'a> = ocaml::Pointer<'a, CamlPastaFqPlonkIndex>;
31
32extern "C" fn caml_pasta_fq_plonk_index_finalize(v: ocaml::Raw) {
33    unsafe {
34        let mut v: CamlPastaFqPlonkIndexPtr = v.as_pointer();
35        v.as_mut_ptr().drop_in_place();
36    }
37}
38
39impl ocaml::custom::Custom for CamlPastaFqPlonkIndex {
40    const NAME: &'static str = "CamlPastaFqPlonkIndex\0";
41    const USED: usize = 1;
42    /// Encourage the GC to free when there are > 12 in memory
43    const MAX: usize = 12;
44    const OPS: ocaml::custom::CustomOps = ocaml::custom::CustomOps {
45        identifier: Self::NAME.as_ptr() as *const ocaml::sys::Char,
46        finalize: Some(caml_pasta_fq_plonk_index_finalize),
47        ..ocaml::custom::DEFAULT_CUSTOM_OPS
48    };
49}
50
51#[ocaml_gen::func]
52#[ocaml::func]
53pub fn caml_pasta_fq_plonk_index_create(
54    gates: CamlPastaFqPlonkGateVectorPtr,
55    public: ocaml::Int,
56    lookup_tables: Vec<CamlLookupTable<CamlFq>>,
57    runtime_tables: Vec<CamlRuntimeTableCfg<CamlFq>>,
58    prev_challenges: ocaml::Int,
59    srs: CamlFqSrs,
60    lazy_mode: bool,
61) -> Result<CamlPastaFqPlonkIndex, ocaml::Error> {
62    let gates: Vec<_> = gates
63        .as_ref()
64        .0
65        .iter()
66        .map(|gate| CircuitGate::<Fq> {
67            typ: gate.typ,
68            wires: gate.wires,
69            coeffs: gate.coeffs.clone(),
70        })
71        .collect();
72
73    let runtime_tables: Vec<RuntimeTableCfg<Fq>> =
74        runtime_tables.into_iter().map(Into::into).collect();
75
76    let lookup_tables: Vec<LookupTable<Fq>> = lookup_tables.into_iter().map(Into::into).collect();
77
78    // create constraint system
79    let cs = match ConstraintSystem::<Fq>::create(gates)
80        .public(public as usize)
81        .prev_challenges(prev_challenges as usize)
82        .lookup(lookup_tables)
83        .runtime(if runtime_tables.is_empty() {
84            None
85        } else {
86            Some(runtime_tables)
87        })
88        .lazy_mode(lazy_mode)
89        .build()
90    {
91        Err(e) => return Err(e.into()),
92        Ok(cs) => cs,
93    };
94
95    // endo
96    let (endo_q, _endo_r) = poly_commitment::ipa::endos::<Vesta>();
97
98    srs.0.with_lagrange_basis(cs.domain.d1);
99
100    // create index
101    let mut index =
102        ProverIndex::<Pallas, OpeningProof<Pallas>>::create(cs, endo_q, srs.clone(), lazy_mode);
103    // Compute and cache the verifier index digest
104    index.compute_verifier_index_digest::<DefaultFqSponge<PallasParameters, PlonkSpongeConstantsKimchi>>();
105
106    Ok(CamlPastaFqPlonkIndex(Box::new(index)))
107}
108
109#[ocaml_gen::func]
110#[ocaml::func]
111pub fn caml_pasta_fq_plonk_index_max_degree(index: CamlPastaFqPlonkIndexPtr) -> ocaml::Int {
112    index.as_ref().0.srs.max_poly_size() as isize
113}
114
115#[ocaml_gen::func]
116#[ocaml::func]
117pub fn caml_pasta_fq_plonk_index_public_inputs(index: CamlPastaFqPlonkIndexPtr) -> ocaml::Int {
118    index.as_ref().0.cs.public as isize
119}
120
121#[ocaml_gen::func]
122#[ocaml::func]
123pub fn caml_pasta_fq_plonk_index_domain_d1_size(index: CamlPastaFqPlonkIndexPtr) -> ocaml::Int {
124    index.as_ref().0.cs.domain.d1.size() as isize
125}
126
127#[ocaml_gen::func]
128#[ocaml::func]
129pub fn caml_pasta_fq_plonk_index_domain_d4_size(index: CamlPastaFqPlonkIndexPtr) -> ocaml::Int {
130    index.as_ref().0.cs.domain.d4.size() as isize
131}
132
133#[ocaml_gen::func]
134#[ocaml::func]
135pub fn caml_pasta_fq_plonk_index_domain_d8_size(index: CamlPastaFqPlonkIndexPtr) -> ocaml::Int {
136    index.as_ref().0.cs.domain.d8.size() as isize
137}
138
139#[ocaml_gen::func]
140#[ocaml::func]
141pub fn caml_pasta_fq_plonk_index_read(
142    offset: Option<ocaml::Int>,
143    srs: CamlFqSrs,
144    path: String,
145) -> Result<CamlPastaFqPlonkIndex, ocaml::Error> {
146    // open the file for reading
147    let file = match File::open(path) {
148        Err(_) => {
149            return Err(
150                ocaml::Error::invalid_argument("caml_pasta_fp_plonk_index_read")
151                    .err()
152                    .unwrap(),
153            )
154        }
155        Ok(file) => file,
156    };
157    let mut r = BufReader::new(file);
158
159    // optional offset in file
160    if let Some(offset) = offset {
161        r.seek(Start(offset as u64))?;
162    }
163
164    // deserialize the index
165    let mut t = ProverIndex::<Pallas, OpeningProof<Pallas>>::deserialize(
166        &mut rmp_serde::Deserializer::new(r),
167    )?;
168    t.srs = srs.clone();
169
170    let (linearization, powers_of_alpha) = expr_linearization(Some(&t.cs.feature_flags), true);
171    t.linearization = linearization;
172    t.powers_of_alpha = powers_of_alpha;
173
174    Ok(CamlPastaFqPlonkIndex(Box::new(t)))
175}
176
177#[ocaml_gen::func]
178#[ocaml::func]
179pub fn caml_pasta_fq_plonk_index_write(
180    append: Option<bool>,
181    index: CamlPastaFqPlonkIndexPtr<'static>,
182    path: String,
183) -> Result<(), ocaml::Error> {
184    let file = OpenOptions::new()
185        .append(append.unwrap_or(true))
186        .open(path)
187        .map_err(|_| {
188            ocaml::Error::invalid_argument("caml_pasta_fq_plonk_index_write")
189                .err()
190                .unwrap()
191        })?;
192    let w = BufWriter::new(file);
193    index
194        .as_ref()
195        .0
196        .serialize(&mut rmp_serde::Serializer::new(w))
197        .map_err(|e| e.into())
198}