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