arnaucube
arnaucube/NovaPublic Self-hosted repository
Nova/src/r1cs.rs
src/r1cs.rsRaw
  1//! This module defines R1CS related types and a folding scheme for Relaxed R1CS
  2#![allow(clippy::type_complexity)]
  3use crate::{
  4  constants::{BN_LIMB_WIDTH, BN_N_LIMBS, NUM_HASH_BITS},
  5  errors::NovaError,
  6  gadgets::{
  7    nonnative::{bignat::nat_to_limbs, util::f_to_nat},
  8    utils::scalar_as_base,
  9  },
 10  traits::{
 11    commitment::CommitmentEngineTrait, AbsorbInROTrait, Group, ROTrait, TranscriptReprTrait,
 12  },
 13  Commitment, CommitmentKey, CE,
 14};
 15use core::{cmp::max, marker::PhantomData};
 16use ff::Field;
 17use flate2::{write::ZlibEncoder, Compression};
 18use itertools::concat;
 19use rayon::prelude::*;
 20use serde::{Deserialize, Serialize};
 21use sha3::{Digest, Sha3_256};
 22
 23/// Public parameters for a given R1CS
 24#[derive(Clone, Serialize, Deserialize)]
 25#[serde(bound = "")]
 26pub struct R1CS<G: Group> {
 27  _p: PhantomData<G>,
 28}
 29
 30/// A type that holds the shape of the R1CS matrices
 31#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 32pub struct R1CSShape<G: Group> {
 33  pub(crate) num_cons: usize,
 34  pub(crate) num_vars: usize,
 35  pub(crate) num_io: usize,
 36  pub(crate) A: Vec<(usize, usize, G::Scalar)>,
 37  pub(crate) B: Vec<(usize, usize, G::Scalar)>,
 38  pub(crate) C: Vec<(usize, usize, G::Scalar)>,
 39  digest: G::Scalar, // digest of the rest of R1CSShape
 40}
 41
 42/// A type that holds a witness for a given R1CS instance
 43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 44pub struct R1CSWitness<G: Group> {
 45  W: Vec<G::Scalar>,
 46}
 47
 48/// A type that holds an R1CS instance
 49#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 50#[serde(bound = "")]
 51pub struct R1CSInstance<G: Group> {
 52  pub(crate) comm_W: Commitment<G>,
 53  pub(crate) X: Vec<G::Scalar>,
 54}
 55
 56/// A type that holds a witness for a given Relaxed R1CS instance
 57#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 58pub struct RelaxedR1CSWitness<G: Group> {
 59  pub(crate) W: Vec<G::Scalar>,
 60  pub(crate) E: Vec<G::Scalar>,
 61}
 62
 63/// A type that holds a Relaxed R1CS instance
 64#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
 65#[serde(bound = "")]
 66pub struct RelaxedR1CSInstance<G: Group> {
 67  pub(crate) comm_W: Commitment<G>,
 68  pub(crate) comm_E: Commitment<G>,
 69  pub(crate) X: Vec<G::Scalar>,
 70  pub(crate) u: G::Scalar,
 71}
 72
 73impl<G: Group> R1CS<G> {
 74  /// Samples public parameters for the specified number of constraints and variables in an R1CS
 75  pub fn commitment_key(num_cons: usize, num_vars: usize) -> CommitmentKey<G> {
 76    G::CE::setup(b"ck", max(num_vars, num_cons))
 77  }
 78}
 79
 80impl<G: Group> R1CSShape<G> {
 81  /// Create an object of type `R1CSShape` from the explicitly specified R1CS matrices
 82  pub fn new(
 83    num_cons: usize,
 84    num_vars: usize,
 85    num_io: usize,
 86    A: &[(usize, usize, G::Scalar)],
 87    B: &[(usize, usize, G::Scalar)],
 88    C: &[(usize, usize, G::Scalar)],
 89  ) -> Result<R1CSShape<G>, NovaError> {
 90    let is_valid = |num_cons: usize,
 91                    num_vars: usize,
 92                    num_io: usize,
 93                    M: &[(usize, usize, G::Scalar)]|
 94     -> Result<(), NovaError> {
 95      let res = (0..M.len())
 96        .map(|i| {
 97          let (row, col, _val) = M[i];
 98          if row >= num_cons || col > num_io + num_vars {
 99            Err(NovaError::InvalidIndex)
100          } else {
101            Ok(())
102          }
103        })
104        .collect::<Result<Vec<()>, NovaError>>();
105
106      if res.is_err() {
107        Err(NovaError::InvalidIndex)
108      } else {
109        Ok(())
110      }
111    };
112
113    let res_A = is_valid(num_cons, num_vars, num_io, A);
114    let res_B = is_valid(num_cons, num_vars, num_io, B);
115    let res_C = is_valid(num_cons, num_vars, num_io, C);
116
117    if res_A.is_err() || res_B.is_err() || res_C.is_err() {
118      return Err(NovaError::InvalidIndex);
119    }
120
121    // We require the number of public inputs/outputs to be even
122    if num_io % 2 != 0 {
123      return Err(NovaError::OddInputLength);
124    }
125
126    let digest = Self::compute_digest(num_cons, num_vars, num_io, A, B, C);
127
128    let shape = R1CSShape {
129      num_cons,
130      num_vars,
131      num_io,
132      A: A.to_owned(),
133      B: B.to_owned(),
134      C: C.to_owned(),
135      digest,
136    };
137
138    Ok(shape)
139  }
140
141  pub fn multiply_vec(
142    &self,
143    z: &[G::Scalar],
144  ) -> Result<(Vec<G::Scalar>, Vec<G::Scalar>, Vec<G::Scalar>), NovaError> {
145    if z.len() != self.num_io + self.num_vars + 1 {
146      return Err(NovaError::InvalidWitnessLength);
147    }
148
149    // computes a product between a sparse matrix `M` and a vector `z`
150    // This does not perform any validation of entries in M (e.g., if entries in `M` reference indexes outside the range of `z`)
151    // This is safe since we know that `M` is valid
152    let sparse_matrix_vec_product =
153      |M: &Vec<(usize, usize, G::Scalar)>, num_rows: usize, z: &[G::Scalar]| -> Vec<G::Scalar> {
154        (0..M.len())
155          .map(|i| {
156            let (row, col, val) = M[i];
157            (row, val * z[col])
158          })
159          .fold(vec![G::Scalar::zero(); num_rows], |mut Mz, (r, v)| {
160            Mz[r] += v;
161            Mz
162          })
163      };
164
165    let (Az, (Bz, Cz)) = rayon::join(
166      || sparse_matrix_vec_product(&self.A, self.num_cons, z),
167      || {
168        rayon::join(
169          || sparse_matrix_vec_product(&self.B, self.num_cons, z),
170          || sparse_matrix_vec_product(&self.C, self.num_cons, z),
171        )
172      },
173    );
174
175    Ok((Az, Bz, Cz))
176  }
177
178  /// Checks if the Relaxed R1CS instance is satisfiable given a witness and its shape
179  pub fn is_sat_relaxed(
180    &self,
181    ck: &CommitmentKey<G>,
182    U: &RelaxedR1CSInstance<G>,
183    W: &RelaxedR1CSWitness<G>,
184  ) -> Result<(), NovaError> {
185    assert_eq!(W.W.len(), self.num_vars);
186    assert_eq!(W.E.len(), self.num_cons);
187    assert_eq!(U.X.len(), self.num_io);
188
189    // verify if Az * Bz = u*Cz + E
190    let res_eq: bool = {
191      let z = concat(vec![W.W.clone(), vec![U.u], U.X.clone()]);
192      let (Az, Bz, Cz) = self.multiply_vec(&z)?;
193      assert_eq!(Az.len(), self.num_cons);
194      assert_eq!(Bz.len(), self.num_cons);
195      assert_eq!(Cz.len(), self.num_cons);
196
197      let res: usize = (0..self.num_cons)
198        .map(|i| usize::from(Az[i] * Bz[i] != U.u * Cz[i] + W.E[i]))
199        .sum();
200
201      res == 0
202    };
203
204    // verify if comm_E and comm_W are commitments to E and W
205    let res_comm: bool = {
206      let (comm_W, comm_E) =
207        rayon::join(|| CE::<G>::commit(ck, &W.W), || CE::<G>::commit(ck, &W.E));
208      U.comm_W == comm_W && U.comm_E == comm_E
209    };
210
211    if res_eq && res_comm {
212      Ok(())
213    } else {
214      Err(NovaError::UnSat)
215    }
216  }
217
218  /// Checks if the R1CS instance is satisfiable given a witness and its shape
219  pub fn is_sat(
220    &self,
221    ck: &CommitmentKey<G>,
222    U: &R1CSInstance<G>,
223    W: &R1CSWitness<G>,
224  ) -> Result<(), NovaError> {
225    assert_eq!(W.W.len(), self.num_vars);
226    assert_eq!(U.X.len(), self.num_io);
227
228    // verify if Az * Bz = u*Cz
229    let res_eq: bool = {
230      let z = concat(vec![W.W.clone(), vec![G::Scalar::one()], U.X.clone()]);
231      let (Az, Bz, Cz) = self.multiply_vec(&z)?;
232      assert_eq!(Az.len(), self.num_cons);
233      assert_eq!(Bz.len(), self.num_cons);
234      assert_eq!(Cz.len(), self.num_cons);
235
236      let res: usize = (0..self.num_cons)
237        .map(|i| usize::from(Az[i] * Bz[i] != Cz[i]))
238        .sum();
239
240      res == 0
241    };
242
243    // verify if comm_W is a commitment to W
244    let res_comm: bool = U.comm_W == CE::<G>::commit(ck, &W.W);
245
246    if res_eq && res_comm {
247      Ok(())
248    } else {
249      Err(NovaError::UnSat)
250    }
251  }
252
253  /// A method to compute a commitment to the cross-term `T` given a
254  /// Relaxed R1CS instance-witness pair and an R1CS instance-witness pair
255  pub fn commit_T(
256    &self,
257    ck: &CommitmentKey<G>,
258    U1: &RelaxedR1CSInstance<G>,
259    W1: &RelaxedR1CSWitness<G>,
260    U2: &R1CSInstance<G>,
261    W2: &R1CSWitness<G>,
262  ) -> Result<(Vec<G::Scalar>, Commitment<G>), NovaError> {
263    let (AZ_1, BZ_1, CZ_1) = {
264      let Z1 = concat(vec![W1.W.clone(), vec![U1.u], U1.X.clone()]);
265      self.multiply_vec(&Z1)?
266    };
267
268    let (AZ_2, BZ_2, CZ_2) = {
269      let Z2 = concat(vec![W2.W.clone(), vec![G::Scalar::one()], U2.X.clone()]);
270      self.multiply_vec(&Z2)?
271    };
272
273    let AZ_1_circ_BZ_2 = (0..AZ_1.len())
274      .into_par_iter()
275      .map(|i| AZ_1[i] * BZ_2[i])
276      .collect::<Vec<G::Scalar>>();
277    let AZ_2_circ_BZ_1 = (0..AZ_2.len())
278      .into_par_iter()
279      .map(|i| AZ_2[i] * BZ_1[i])
280      .collect::<Vec<G::Scalar>>();
281    let u_1_cdot_CZ_2 = (0..CZ_2.len())
282      .into_par_iter()
283      .map(|i| U1.u * CZ_2[i])
284      .collect::<Vec<G::Scalar>>();
285    let u_2_cdot_CZ_1 = (0..CZ_1.len())
286      .into_par_iter()
287      .map(|i| CZ_1[i])
288      .collect::<Vec<G::Scalar>>();
289
290    let T = AZ_1_circ_BZ_2
291      .par_iter()
292      .zip(&AZ_2_circ_BZ_1)
293      .zip(&u_1_cdot_CZ_2)
294      .zip(&u_2_cdot_CZ_1)
295      .map(|(((a, b), c), d)| *a + *b - *c - *d)
296      .collect::<Vec<G::Scalar>>();
297
298    let comm_T = CE::<G>::commit(ck, &T);
299
300    Ok((T, comm_T))
301  }
302
303  /// returns the digest of R1CSShape
304  pub fn get_digest(&self) -> G::Scalar {
305    self.digest
306  }
307
308  fn compute_digest(
309    num_cons: usize,
310    num_vars: usize,
311    num_io: usize,
312    A: &[(usize, usize, G::Scalar)],
313    B: &[(usize, usize, G::Scalar)],
314    C: &[(usize, usize, G::Scalar)],
315  ) -> G::Scalar {
316    #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
317    struct R1CSShapeWithoutDigest<G: Group> {
318      num_cons: usize,
319      num_vars: usize,
320      num_io: usize,
321      A: Vec<(usize, usize, G::Scalar)>,
322      B: Vec<(usize, usize, G::Scalar)>,
323      C: Vec<(usize, usize, G::Scalar)>,
324    }
325
326    let shape = R1CSShapeWithoutDigest::<G> {
327      num_cons,
328      num_vars,
329      num_io,
330      A: A.to_vec(),
331      B: B.to_vec(),
332      C: C.to_vec(),
333    };
334
335    // obtain a vector of bytes representing the R1CS shape
336    let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
337    bincode::serialize_into(&mut encoder, &shape).unwrap();
338    let shape_bytes = encoder.finish().unwrap();
339
340    // convert shape_bytes into a short digest
341    let mut hasher = Sha3_256::new();
342    hasher.input(&shape_bytes);
343    let digest = hasher.result();
344
345    // truncate the digest to 250 bits
346    let bv = (0..NUM_HASH_BITS).map(|i| {
347      let (byte_pos, bit_pos) = (i / 8, i % 8);
348      let bit = (digest[byte_pos] >> bit_pos) & 1;
349      bit == 1
350    });
351
352    // turn the bit vector into a scalar
353    let mut res = G::Scalar::zero();
354    let mut coeff = G::Scalar::one();
355    for bit in bv {
356      if bit {
357        res += coeff;
358      }
359      coeff += coeff;
360    }
361    res
362  }
363
364  /// Pads the R1CSShape so that the number of variables is a power of two
365  /// Renumbers variables to accomodate padded variables
366  pub fn pad(&self) -> Self {
367    // equalize the number of variables and constraints
368    let m = max(self.num_vars, self.num_cons).next_power_of_two();
369
370    // check if the provided R1CSShape is already as required
371    if self.num_vars == m && self.num_cons == m {
372      return self.clone();
373    }
374
375    // check if the number of variables are as expected, then
376    // we simply set the number of constraints to the next power of two
377    if self.num_vars == m {
378      let digest = Self::compute_digest(m, self.num_vars, self.num_io, &self.A, &self.B, &self.C);
379
380      return R1CSShape {
381        num_cons: m,
382        num_vars: m,
383        num_io: self.num_io,
384        A: self.A.clone(),
385        B: self.B.clone(),
386        C: self.C.clone(),
387        digest,
388      };
389    }
390
391    // otherwise, we need to pad the number of variables and renumber variable accesses
392    let num_vars_padded = m;
393    let num_cons_padded = m;
394    let apply_pad = |M: &[(usize, usize, G::Scalar)]| -> Vec<(usize, usize, G::Scalar)> {
395      M.par_iter()
396        .map(|(r, c, v)| {
397          if c >= &self.num_vars {
398            (*r, c + num_vars_padded - self.num_vars, *v)
399          } else {
400            (*r, *c, *v)
401          }
402        })
403        .collect::<Vec<_>>()
404    };
405
406    let A_padded = apply_pad(&self.A);
407    let B_padded = apply_pad(&self.B);
408    let C_padded = apply_pad(&self.C);
409
410    let digest = Self::compute_digest(
411      num_cons_padded,
412      num_vars_padded,
413      self.num_io,
414      &A_padded,
415      &B_padded,
416      &C_padded,
417    );
418
419    R1CSShape {
420      num_cons: num_cons_padded,
421      num_vars: num_vars_padded,
422      num_io: self.num_io,
423      A: A_padded,
424      B: B_padded,
425      C: C_padded,
426      digest,
427    }
428  }
429}
430
431impl<G: Group> TranscriptReprTrait<G> for R1CSShape<G> {
432  fn to_transcript_bytes(&self) -> Vec<u8> {
433    self.get_digest().to_transcript_bytes()
434  }
435}
436
437impl<G: Group> AbsorbInROTrait<G> for R1CSShape<G> {
438  fn absorb_in_ro(&self, ro: &mut G::RO) {
439    ro.absorb(scalar_as_base::<G>(self.get_digest()));
440  }
441}
442
443impl<G: Group> R1CSWitness<G> {
444  /// A method to create a witness object using a vector of scalars
445  pub fn new(S: &R1CSShape<G>, W: &[G::Scalar]) -> Result<R1CSWitness<G>, NovaError> {
446    if S.num_vars != W.len() {
447      Err(NovaError::InvalidWitnessLength)
448    } else {
449      Ok(R1CSWitness { W: W.to_owned() })
450    }
451  }
452
453  /// Commits to the witness using the supplied generators
454  pub fn commit(&self, ck: &CommitmentKey<G>) -> Commitment<G> {
455    CE::<G>::commit(ck, &self.W)
456  }
457}
458
459impl<G: Group> R1CSInstance<G> {
460  /// A method to create an instance object using consitituent elements
461  pub fn new(
462    S: &R1CSShape<G>,
463    comm_W: &Commitment<G>,
464    X: &[G::Scalar],
465  ) -> Result<R1CSInstance<G>, NovaError> {
466    if S.num_io != X.len() {
467      Err(NovaError::InvalidInputLength)
468    } else {
469      Ok(R1CSInstance {
470        comm_W: *comm_W,
471        X: X.to_owned(),
472      })
473    }
474  }
475}
476
477impl<G: Group> AbsorbInROTrait<G> for R1CSInstance<G> {
478  fn absorb_in_ro(&self, ro: &mut G::RO) {
479    self.comm_W.absorb_in_ro(ro);
480    for x in &self.X {
481      ro.absorb(scalar_as_base::<G>(*x));
482    }
483  }
484}
485
486impl<G: Group> RelaxedR1CSWitness<G> {
487  /// Produces a default RelaxedR1CSWitness given an R1CSShape
488  pub fn default(S: &R1CSShape<G>) -> RelaxedR1CSWitness<G> {
489    RelaxedR1CSWitness {
490      W: vec![G::Scalar::zero(); S.num_vars],
491      E: vec![G::Scalar::zero(); S.num_cons],
492    }
493  }
494
495  /// Initializes a new RelaxedR1CSWitness from an R1CSWitness
496  pub fn from_r1cs_witness(S: &R1CSShape<G>, witness: &R1CSWitness<G>) -> RelaxedR1CSWitness<G> {
497    RelaxedR1CSWitness {
498      W: witness.W.clone(),
499      E: vec![G::Scalar::zero(); S.num_cons],
500    }
501  }
502
503  /// Commits to the witness using the supplied generators
504  pub fn commit(&self, ck: &CommitmentKey<G>) -> (Commitment<G>, Commitment<G>) {
505    (CE::<G>::commit(ck, &self.W), CE::<G>::commit(ck, &self.E))
506  }
507
508  /// Folds an incoming R1CSWitness into the current one
509  pub fn fold(
510    &self,
511    W2: &R1CSWitness<G>,
512    T: &[G::Scalar],
513    r: &G::Scalar,
514  ) -> Result<RelaxedR1CSWitness<G>, NovaError> {
515    let (W1, E1) = (&self.W, &self.E);
516    let W2 = &W2.W;
517
518    if W1.len() != W2.len() {
519      return Err(NovaError::InvalidWitnessLength);
520    }
521
522    let W = W1
523      .par_iter()
524      .zip(W2)
525      .map(|(a, b)| *a + *r * *b)
526      .collect::<Vec<G::Scalar>>();
527    let E = E1
528      .par_iter()
529      .zip(T)
530      .map(|(a, b)| *a + *r * *b)
531      .collect::<Vec<G::Scalar>>();
532    Ok(RelaxedR1CSWitness { W, E })
533  }
534
535  /// Pads the provided witness to the correct length
536  pub fn pad(&self, S: &R1CSShape<G>) -> RelaxedR1CSWitness<G> {
537    let W = {
538      let mut W = self.W.clone();
539      W.extend(vec![G::Scalar::zero(); S.num_vars - W.len()]);
540      W
541    };
542
543    let E = {
544      let mut E = self.E.clone();
545      E.extend(vec![G::Scalar::zero(); S.num_cons - E.len()]);
546      E
547    };
548
549    Self { W, E }
550  }
551}
552
553impl<G: Group> RelaxedR1CSInstance<G> {
554  /// Produces a default RelaxedR1CSInstance given R1CSGens and R1CSShape
555  pub fn default(_ck: &CommitmentKey<G>, S: &R1CSShape<G>) -> RelaxedR1CSInstance<G> {
556    let (comm_W, comm_E) = (Commitment::<G>::default(), Commitment::<G>::default());
557    RelaxedR1CSInstance {
558      comm_W,
559      comm_E,
560      u: G::Scalar::zero(),
561      X: vec![G::Scalar::zero(); S.num_io],
562    }
563  }
564
565  /// Initializes a new RelaxedR1CSInstance from an R1CSInstance
566  pub fn from_r1cs_instance(
567    ck: &CommitmentKey<G>,
568    S: &R1CSShape<G>,
569    instance: &R1CSInstance<G>,
570  ) -> RelaxedR1CSInstance<G> {
571    let mut r_instance = RelaxedR1CSInstance::default(ck, S);
572    r_instance.comm_W = instance.comm_W;
573    r_instance.u = G::Scalar::one();
574    r_instance.X = instance.X.clone();
575    r_instance
576  }
577
578  /// Folds an incoming RelaxedR1CSInstance into the current one
579  pub fn fold(
580    &self,
581    U2: &R1CSInstance<G>,
582    comm_T: &Commitment<G>,
583    r: &G::Scalar,
584  ) -> Result<RelaxedR1CSInstance<G>, NovaError> {
585    let (X1, u1, comm_W_1, comm_E_1) =
586      (&self.X, &self.u, &self.comm_W.clone(), &self.comm_E.clone());
587    let (X2, comm_W_2) = (&U2.X, &U2.comm_W);
588
589    // weighted sum of X, comm_W, comm_E, and u
590    let X = X1
591      .par_iter()
592      .zip(X2)
593      .map(|(a, b)| *a + *r * *b)
594      .collect::<Vec<G::Scalar>>();
595    let comm_W = *comm_W_1 + *comm_W_2 * *r;
596    let comm_E = *comm_E_1 + *comm_T * *r;
597    let u = *u1 + *r;
598
599    Ok(RelaxedR1CSInstance {
600      comm_W,
601      comm_E,
602      X,
603      u,
604    })
605  }
606}
607
608impl<G: Group> TranscriptReprTrait<G> for RelaxedR1CSInstance<G> {
609  fn to_transcript_bytes(&self) -> Vec<u8> {
610    [
611      self.comm_W.to_transcript_bytes(),
612      self.comm_E.to_transcript_bytes(),
613      self.u.to_transcript_bytes(),
614      self.X.as_slice().to_transcript_bytes(),
615    ]
616    .concat()
617  }
618}
619
620impl<G: Group> AbsorbInROTrait<G> for RelaxedR1CSInstance<G> {
621  fn absorb_in_ro(&self, ro: &mut G::RO) {
622    self.comm_W.absorb_in_ro(ro);
623    self.comm_E.absorb_in_ro(ro);
624    ro.absorb(scalar_as_base::<G>(self.u));
625
626    // absorb each element of self.X in bignum format
627    for x in &self.X {
628      let limbs: Vec<G::Scalar> = nat_to_limbs(&f_to_nat(x), BN_LIMB_WIDTH, BN_N_LIMBS).unwrap();
629      for limb in limbs {
630        ro.absorb(scalar_as_base::<G>(limb));
631      }
632    }
633  }
634}