arnaucube
arnaucube/testudoPublic Self-hosted repository
testudo/src/constraints.rs
src/constraints.rsRaw
  1use std::{borrow::Borrow, vec};
  2
  3use super::scalar::Scalar;
  4use crate::{
  5  group::Fq,
  6  math::Math,
  7  sparse_mlpoly::{SparsePolyEntry, SparsePolynomial},
  8  unipoly::UniPoly,
  9};
 10use ark_bls12_377::{constraints::PairingVar as IV, Bls12_377 as I, Fr};
 11use ark_crypto_primitives::{
 12  snark::BooleanInputVar, CircuitSpecificSetupSNARK, SNARKGadget, SNARK,
 13};
 14
 15use ark_ff::{BitIteratorLE, PrimeField, Zero};
 16use ark_groth16::{
 17  constraints::{Groth16VerifierGadget, PreparedVerifyingKeyVar, ProofVar},
 18  Groth16, PreparedVerifyingKey, Proof as GrothProof,
 19};
 20
 21use ark_poly_commit::multilinear_pc::{
 22  data_structures::{Commitment, Proof, VerifierKey},
 23  MultilinearPC,
 24};
 25use ark_r1cs_std::{
 26  alloc::{AllocVar, AllocationMode},
 27  fields::fp::FpVar,
 28  prelude::{Boolean, EqGadget, FieldVar},
 29  R1CSVar,
 30};
 31use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError};
 32use ark_sponge::{
 33  constraints::CryptographicSpongeVar,
 34  poseidon::{constraints::PoseidonSpongeVar, PoseidonParameters},
 35};
 36use rand::{CryptoRng, Rng};
 37
 38pub struct PoseidonTranscripVar {
 39  pub cs: ConstraintSystemRef<Fr>,
 40  pub sponge: PoseidonSpongeVar<Fr>,
 41  pub params: PoseidonParameters<Fr>,
 42}
 43
 44impl PoseidonTranscripVar {
 45  fn new(
 46    cs: ConstraintSystemRef<Fr>,
 47    params: &PoseidonParameters<Fr>,
 48    challenge: Option<Fr>,
 49  ) -> Self {
 50    let mut sponge = PoseidonSpongeVar::new(cs.clone(), params);
 51
 52    if let Some(c) = challenge {
 53      let c_var = FpVar::<Fr>::new_witness(cs.clone(), || Ok(c)).unwrap();
 54      sponge.absorb(&c_var).unwrap();
 55    }
 56
 57    Self {
 58      cs,
 59      sponge,
 60      params: params.clone(),
 61    }
 62  }
 63
 64  fn append(&mut self, input: &FpVar<Fr>) -> Result<(), SynthesisError> {
 65    self.sponge.absorb(&input)
 66  }
 67
 68  fn append_vector(&mut self, input_vec: &[FpVar<Fr>]) -> Result<(), SynthesisError> {
 69    for input in input_vec.iter() {
 70      self.append(input)?;
 71    }
 72    Ok(())
 73  }
 74
 75  fn challenge(&mut self) -> Result<FpVar<Fr>, SynthesisError> {
 76    let c_var = self.sponge.squeeze_field_elements(1).unwrap().remove(0);
 77
 78    Ok(c_var)
 79  }
 80
 81  fn challenge_vector(&mut self, len: usize) -> Result<Vec<FpVar<Fr>>, SynthesisError> {
 82    let c_vars = self.sponge.squeeze_field_elements(len).unwrap();
 83
 84    Ok(c_vars)
 85  }
 86}
 87
 88#[derive(Clone)]
 89pub struct UniPolyVar {
 90  pub coeffs: Vec<FpVar<Fr>>,
 91}
 92
 93impl AllocVar<UniPoly, Fr> for UniPolyVar {
 94  fn new_variable<T: Borrow<UniPoly>>(
 95    cs: impl Into<Namespace<Fr>>,
 96    f: impl FnOnce() -> Result<T, SynthesisError>,
 97    mode: AllocationMode,
 98  ) -> Result<Self, SynthesisError> {
 99    f().and_then(|c| {
100      let cs = cs.into();
101      let cp: &UniPoly = c.borrow();
102      let mut coeffs_var = Vec::new();
103      for coeff in cp.coeffs.iter() {
104        let coeff_var = FpVar::<Fr>::new_variable(cs.clone(), || Ok(coeff), mode)?;
105        coeffs_var.push(coeff_var);
106      }
107      Ok(Self { coeffs: coeffs_var })
108    })
109  }
110}
111
112impl UniPolyVar {
113  pub fn eval_at_zero(&self) -> FpVar<Fr> {
114    self.coeffs[0].clone()
115  }
116
117  pub fn eval_at_one(&self) -> FpVar<Fr> {
118    let mut res = self.coeffs[0].clone();
119    for i in 1..self.coeffs.len() {
120      res = &res + &self.coeffs[i];
121    }
122    res
123  }
124
125  // mul without reduce
126  pub fn evaluate(&self, r: &FpVar<Fr>) -> FpVar<Fr> {
127    let mut eval = self.coeffs[0].clone();
128    let mut power = r.clone();
129
130    for i in 1..self.coeffs.len() {
131      eval += &power * &self.coeffs[i];
132      power *= r;
133    }
134    eval
135  }
136}
137
138#[derive(Clone)]
139pub struct SumcheckVerificationCircuit {
140  pub polys: Vec<UniPoly>,
141}
142
143impl SumcheckVerificationCircuit {
144  fn verifiy_sumcheck(
145    &self,
146    poly_vars: &[UniPolyVar],
147    claim_var: &FpVar<Fr>,
148    transcript_var: &mut PoseidonTranscripVar,
149  ) -> Result<(FpVar<Fr>, Vec<FpVar<Fr>>), SynthesisError> {
150    let mut e_var = claim_var.clone();
151    let mut r_vars: Vec<FpVar<Fr>> = Vec::new();
152
153    for (poly_var, _poly) in poly_vars.iter().zip(self.polys.iter()) {
154      let res = poly_var.eval_at_one() + poly_var.eval_at_zero();
155      res.enforce_equal(&e_var)?;
156      transcript_var.append_vector(&poly_var.coeffs)?;
157      let r_i_var = transcript_var.challenge()?;
158      r_vars.push(r_i_var.clone());
159      e_var = poly_var.evaluate(&r_i_var.clone());
160    }
161
162    Ok((e_var, r_vars))
163  }
164}
165
166#[derive(Clone)]
167pub struct SparsePolyEntryVar {
168  idx: usize,
169  val_var: FpVar<Fr>,
170}
171
172impl AllocVar<SparsePolyEntry, Fr> for SparsePolyEntryVar {
173  fn new_variable<T: Borrow<SparsePolyEntry>>(
174    cs: impl Into<Namespace<Fr>>,
175    f: impl FnOnce() -> Result<T, SynthesisError>,
176    _mode: AllocationMode,
177  ) -> Result<Self, SynthesisError> {
178    f().and_then(|s| {
179      let cs = cs.into();
180      let spe: &SparsePolyEntry = s.borrow();
181      let val_var = FpVar::<Fr>::new_witness(cs, || Ok(spe.val))?;
182      Ok(Self {
183        idx: spe.idx,
184        val_var,
185      })
186    })
187  }
188}
189
190#[derive(Clone)]
191pub struct SparsePolynomialVar {
192  num_vars: usize,
193  Z_var: Vec<SparsePolyEntryVar>,
194}
195
196impl AllocVar<SparsePolynomial, Fr> for SparsePolynomialVar {
197  fn new_variable<T: Borrow<SparsePolynomial>>(
198    cs: impl Into<Namespace<Fr>>,
199    f: impl FnOnce() -> Result<T, SynthesisError>,
200    mode: AllocationMode,
201  ) -> Result<Self, SynthesisError> {
202    f().and_then(|s| {
203      let cs = cs.into();
204      let sp: &SparsePolynomial = s.borrow();
205      let mut Z_var = Vec::new();
206      for spe in sp.Z.iter() {
207        let spe_var = SparsePolyEntryVar::new_variable(cs.clone(), || Ok(spe), mode)?;
208        Z_var.push(spe_var);
209      }
210      Ok(Self {
211        num_vars: sp.num_vars,
212        Z_var,
213      })
214    })
215  }
216}
217
218impl SparsePolynomialVar {
219  fn compute_chi(a: &[bool], r_vars: &[FpVar<Fr>]) -> FpVar<Fr> {
220    let mut chi_i_var = FpVar::<Fr>::one();
221    let one = FpVar::<Fr>::one();
222    for (i, r_var) in r_vars.iter().enumerate() {
223      if a[i] {
224        chi_i_var *= r_var;
225      } else {
226        chi_i_var *= &one - r_var;
227      }
228    }
229    chi_i_var
230  }
231
232  pub fn evaluate(&self, r_var: &[FpVar<Fr>]) -> FpVar<Fr> {
233    let mut sum = FpVar::<Fr>::zero();
234    for spe_var in self.Z_var.iter() {
235      // potential problem
236      let bits = &spe_var.idx.get_bits(r_var.len());
237      sum += SparsePolynomialVar::compute_chi(bits, r_var) * &spe_var.val_var;
238    }
239    sum
240  }
241}
242
243#[derive(Clone)]
244pub struct R1CSVerificationCircuit {
245  pub num_vars: usize,
246  pub num_cons: usize,
247  pub input: Vec<Fr>,
248  pub input_as_sparse_poly: SparsePolynomial,
249  pub evals: (Fr, Fr, Fr),
250  pub params: PoseidonParameters<Fr>,
251  pub prev_challenge: Fr,
252  pub claims_phase2: (Scalar, Scalar, Scalar, Scalar),
253  pub eval_vars_at_ry: Fr,
254  pub sc_phase1: SumcheckVerificationCircuit,
255  pub sc_phase2: SumcheckVerificationCircuit,
256  // The point on which the polynomial was evaluated by the prover.
257  pub claimed_ry: Vec<Scalar>,
258}
259
260impl R1CSVerificationCircuit {
261  fn new(config: &VerifierConfig) -> Self {
262    Self {
263      num_vars: config.num_vars,
264      num_cons: config.num_cons,
265      input: config.input.clone(),
266      input_as_sparse_poly: config.input_as_sparse_poly.clone(),
267      evals: config.evals,
268      params: config.params.clone(),
269      prev_challenge: config.prev_challenge,
270      claims_phase2: config.claims_phase2,
271      eval_vars_at_ry: config.eval_vars_at_ry,
272      sc_phase1: SumcheckVerificationCircuit {
273        polys: config.polys_sc1.clone(),
274      },
275      sc_phase2: SumcheckVerificationCircuit {
276        polys: config.polys_sc2.clone(),
277      },
278      claimed_ry: config.ry.clone(),
279    }
280  }
281}
282
283impl ConstraintSynthesizer<Fr> for R1CSVerificationCircuit {
284  fn generate_constraints(self, cs: ConstraintSystemRef<Fr>) -> ark_relations::r1cs::Result<()> {
285    let mut transcript_var =
286      PoseidonTranscripVar::new(cs.clone(), &self.params, Some(self.prev_challenge));
287
288    let poly_sc1_vars = self
289      .sc_phase1
290      .polys
291      .iter()
292      .map(|p| UniPolyVar::new_variable(cs.clone(), || Ok(p), AllocationMode::Witness).unwrap())
293      .collect::<Vec<UniPolyVar>>();
294
295    let poly_sc2_vars = self
296      .sc_phase2
297      .polys
298      .iter()
299      .map(|p| UniPolyVar::new_variable(cs.clone(), || Ok(p), AllocationMode::Witness).unwrap())
300      .collect::<Vec<UniPolyVar>>();
301
302    let input_vars = self
303      .input
304      .iter()
305      .map(|i| FpVar::<Fr>::new_variable(cs.clone(), || Ok(i), AllocationMode::Witness).unwrap())
306      .collect::<Vec<FpVar<Fr>>>();
307
308    let claimed_ry_vars = self
309      .claimed_ry
310      .iter()
311      .map(|r| FpVar::<Fr>::new_variable(cs.clone(), || Ok(r), AllocationMode::Input).unwrap())
312      .collect::<Vec<FpVar<Fr>>>();
313
314    transcript_var.append_vector(&input_vars)?;
315
316    let num_rounds_x = self.num_cons.log_2();
317    let _num_rounds_y = (2 * self.num_vars).log_2();
318
319    let tau_vars = transcript_var.challenge_vector(num_rounds_x)?;
320
321    let claim_phase1_var = FpVar::<Fr>::new_witness(cs.clone(), || Ok(Fr::zero()))?;
322
323    let (claim_post_phase1_var, rx_var) =
324      self
325        .sc_phase1
326        .verifiy_sumcheck(&poly_sc1_vars, &claim_phase1_var, &mut transcript_var)?;
327
328    let (Az_claim, Bz_claim, Cz_claim, prod_Az_Bz_claims) = &self.claims_phase2;
329
330    let Az_claim_var = FpVar::<Fr>::new_input(cs.clone(), || Ok(Az_claim))?;
331    let Bz_claim_var = FpVar::<Fr>::new_input(cs.clone(), || Ok(Bz_claim))?;
332    let Cz_claim_var = FpVar::<Fr>::new_input(cs.clone(), || Ok(Cz_claim))?;
333    let prod_Az_Bz_claim_var = FpVar::<Fr>::new_input(cs.clone(), || Ok(prod_Az_Bz_claims))?;
334    let one = FpVar::<Fr>::one();
335    let prod_vars: Vec<FpVar<Fr>> = (0..rx_var.len())
336      .map(|i| (&rx_var[i] * &tau_vars[i]) + (&one - &rx_var[i]) * (&one - &tau_vars[i]))
337      .collect();
338    let mut taus_bound_rx_var = FpVar::<Fr>::one();
339
340    for p_var in prod_vars.iter() {
341      taus_bound_rx_var *= p_var;
342    }
343
344    let expected_claim_post_phase1_var =
345      (&prod_Az_Bz_claim_var - &Cz_claim_var) * &taus_bound_rx_var;
346
347    claim_post_phase1_var.enforce_equal(&expected_claim_post_phase1_var)?;
348
349    let r_A_var = transcript_var.challenge()?;
350    let r_B_var = transcript_var.challenge()?;
351    let r_C_var = transcript_var.challenge()?;
352
353    let claim_phase2_var =
354      &r_A_var * &Az_claim_var + &r_B_var * &Bz_claim_var + &r_C_var * &Cz_claim_var;
355
356    let (claim_post_phase2_var, ry_var) =
357      self
358        .sc_phase2
359        .verifiy_sumcheck(&poly_sc2_vars, &claim_phase2_var, &mut transcript_var)?;
360
361    //  Because the verifier checks the commitment opening on point ry outside
362    //  the circuit, the prover needs to send ry to the verifier (making the
363    //  proof size O(log n)). As this point is normally obtained by the verifier
364    //  from the second round of sumcheck, the circuit needs to ensure the
365    //  claimed point, coming from the prover, is actually the point derived
366    //  inside the circuit. These additional checks will be removed
367    //  when the commitment verification is done inside the circuit.
368    for (i, r) in claimed_ry_vars.iter().enumerate() {
369      ry_var[i].enforce_equal(r)?;
370    }
371
372    let input_as_sparse_poly_var = SparsePolynomialVar::new_variable(
373      cs.clone(),
374      || Ok(&self.input_as_sparse_poly),
375      AllocationMode::Witness,
376    )?;
377
378    let poly_input_eval_var = input_as_sparse_poly_var.evaluate(&ry_var[1..]);
379
380    let eval_vars_at_ry_var = FpVar::<Fr>::new_input(cs.clone(), || Ok(&self.eval_vars_at_ry))?;
381
382    let eval_Z_at_ry_var =
383      (FpVar::<Fr>::one() - &ry_var[0]) * &eval_vars_at_ry_var + &ry_var[0] * &poly_input_eval_var;
384
385    let (eval_A_r, eval_B_r, eval_C_r) = self.evals;
386
387    let eval_A_r_var = FpVar::<Fr>::new_witness(cs.clone(), || Ok(eval_A_r))?;
388    let eval_B_r_var = FpVar::<Fr>::new_witness(cs.clone(), || Ok(eval_B_r))?;
389    let eval_C_r_var = FpVar::<Fr>::new_witness(cs, || Ok(eval_C_r))?;
390
391    let scalar_var = &r_A_var * &eval_A_r_var + &r_B_var * &eval_B_r_var + &r_C_var * &eval_C_r_var;
392
393    let expected_claim_post_phase2_var = eval_Z_at_ry_var * scalar_var;
394    claim_post_phase2_var.enforce_equal(&expected_claim_post_phase2_var)?;
395
396    Ok(())
397  }
398}
399
400#[derive(Clone)]
401pub struct VerifierConfig {
402  pub num_vars: usize,
403  pub num_cons: usize,
404  pub input: Vec<Fr>,
405  pub input_as_sparse_poly: SparsePolynomial,
406  pub evals: (Fr, Fr, Fr),
407  pub params: PoseidonParameters<Fr>,
408  pub prev_challenge: Fr,
409  pub claims_phase2: (Fr, Fr, Fr, Fr),
410  pub eval_vars_at_ry: Fr,
411  pub polys_sc1: Vec<UniPoly>,
412  pub polys_sc2: Vec<UniPoly>,
413  pub ry: Vec<Scalar>,
414}
415#[derive(Clone)]
416pub struct VerifierCircuit {
417  pub inner_circuit: R1CSVerificationCircuit,
418  pub inner_proof: GrothProof<I>,
419  pub inner_vk: PreparedVerifyingKey<I>,
420  pub eval_vars_at_ry: Fr,
421  pub claims_phase2: (Fr, Fr, Fr, Fr),
422  pub ry: Vec<Fr>,
423}
424
425impl VerifierCircuit {
426  pub fn new<R: Rng + CryptoRng>(
427    config: &VerifierConfig,
428    mut rng: &mut R,
429  ) -> Result<Self, SynthesisError> {
430    let inner_circuit = R1CSVerificationCircuit::new(config);
431    let (pk, vk) = Groth16::<I>::setup(inner_circuit.clone(), &mut rng).unwrap();
432    let proof = Groth16::<I>::prove(&pk, inner_circuit.clone(), &mut rng)?;
433    let pvk = Groth16::<I>::process_vk(&vk).unwrap();
434    Ok(Self {
435      inner_circuit,
436      inner_proof: proof,
437      inner_vk: pvk,
438      eval_vars_at_ry: config.eval_vars_at_ry,
439      claims_phase2: config.claims_phase2,
440      ry: config.ry.clone(),
441    })
442  }
443}
444
445impl ConstraintSynthesizer<Fq> for VerifierCircuit {
446  fn generate_constraints(self, cs: ConstraintSystemRef<Fq>) -> ark_relations::r1cs::Result<()> {
447    let proof_var = ProofVar::<I, IV>::new_witness(cs.clone(), || Ok(self.inner_proof.clone()))?;
448    let (v_A, v_B, v_C, v_AB) = self.claims_phase2;
449    let mut pubs = vec![];
450    pubs.extend(self.ry);
451    pubs.extend(vec![v_A, v_B, v_C, v_AB]);
452    pubs.extend(vec![self.eval_vars_at_ry]);
453    let bits = pubs
454      .iter()
455      .map(|c| {
456        let bits: Vec<bool> = BitIteratorLE::new(c.into_repr().as_ref().to_vec()).collect();
457        Vec::new_witness(cs.clone(), || Ok(bits))
458      })
459      .collect::<Result<Vec<_>, _>>()?;
460    let input_var = BooleanInputVar::<Fr, Fq>::new(bits);
461
462    let vk_var = PreparedVerifyingKeyVar::new_witness(cs, || Ok(self.inner_vk.clone()))?;
463    Groth16VerifierGadget::verify_with_processed_vk(&vk_var, &input_var, &proof_var)?
464      .enforce_equal(&Boolean::constant(true))?;
465    Ok(())
466  }
467}