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 super::{
4 commitments::{CommitGens, CommitTrait, Commitment, CompressedCommitment},
5 constants::NUM_HASH_BITS,
6 errors::NovaError,
7 traits::{AppendToTranscriptTrait, Group},
8};
9use ff::{Field, PrimeField};
10use flate2::{write::ZlibEncoder, Compression};
11use itertools::concat;
12use merlin::Transcript;
13use rayon::prelude::*;
14use serde::{Deserialize, Serialize};
15use sha3::{Digest, Sha3_256};
16
17/// Public parameters for a given R1CS
18pub struct R1CSGens<G: Group> {
19 pub(crate) gens_W: CommitGens<G>, // TODO: avoid pub(crate)
20 pub(crate) gens_E: CommitGens<G>,
21}
22
23/// A type that holds the shape of the R1CS matrices
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct R1CSShape<G: Group> {
26 num_cons: usize,
27 num_vars: usize,
28 num_io: usize,
29 A: Vec<(usize, usize, G::Scalar)>,
30 B: Vec<(usize, usize, G::Scalar)>,
31 C: Vec<(usize, usize, G::Scalar)>,
32}
33
34/// A type that holds a witness for a given R1CS instance
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct R1CSWitness<G: Group> {
37 W: Vec<G::Scalar>,
38}
39
40/// A type that holds an R1CS instance
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub struct R1CSInstance<G: Group> {
43 pub(crate) comm_W: Commitment<G>,
44 pub(crate) X: Vec<G::Scalar>,
45}
46
47/// A type that holds a witness for a given Relaxed R1CS instance
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct RelaxedR1CSWitness<G: Group> {
50 W: Vec<G::Scalar>,
51 E: Vec<G::Scalar>,
52}
53
54/// A type that holds a Relaxed R1CS instance
55#[derive(Clone, Debug, PartialEq, Eq)]
56pub struct RelaxedR1CSInstance<G: Group> {
57 pub(crate) comm_W: Commitment<G>,
58 pub(crate) comm_E: Commitment<G>,
59 pub(crate) X: Vec<G::Scalar>,
60 pub(crate) u: G::Scalar,
61 Y_last: Vec<G::Scalar>, // output of the last instance that was folded
62 counter: usize, // the number of folds thus far
63}
64
65impl<G: Group> R1CSGens<G> {
66 /// Samples public parameters for the specified number of constraints and variables in an R1CS
67 pub fn new(num_cons: usize, num_vars: usize) -> R1CSGens<G> {
68 // generators to commit to witness vector `W`
69 let gens_W = CommitGens::new(b"gens_W", num_vars);
70
71 // generators to commit to the error/slack vector `E`
72 let gens_E = CommitGens::new(b"gens_E", num_cons);
73
74 R1CSGens { gens_E, gens_W }
75 }
76}
77
78impl<G: Group> R1CSShape<G> {
79 /// Create an object of type `R1CSShape` from the explicitly specified R1CS matrices
80 pub fn new(
81 num_cons: usize,
82 num_vars: usize,
83 num_io: usize,
84 A: &[(usize, usize, G::Scalar)],
85 B: &[(usize, usize, G::Scalar)],
86 C: &[(usize, usize, G::Scalar)],
87 ) -> Result<R1CSShape<G>, NovaError> {
88 let is_valid = |num_cons: usize,
89 num_vars: usize,
90 num_io: usize,
91 M: &[(usize, usize, G::Scalar)]|
92 -> Result<(), NovaError> {
93 let res = (0..M.len())
94 .map(|i| {
95 let (row, col, _val) = M[i];
96 if row >= num_cons || col > num_io + num_vars {
97 Err(NovaError::InvalidIndex)
98 } else {
99 Ok(())
100 }
101 })
102 .collect::<Result<Vec<()>, NovaError>>();
103
104 if res.is_err() {
105 Err(NovaError::InvalidIndex)
106 } else {
107 Ok(())
108 }
109 };
110
111 let res_A = is_valid(num_cons, num_vars, num_io, A);
112 let res_B = is_valid(num_cons, num_vars, num_io, B);
113 let res_C = is_valid(num_cons, num_vars, num_io, C);
114
115 if res_A.is_err() || res_B.is_err() || res_C.is_err() {
116 return Err(NovaError::InvalidIndex);
117 }
118
119 // We require the number of public inputs/outputs to be even
120 if num_io % 2 != 0 {
121 return Err(NovaError::OddInputLength);
122 }
123
124 let shape = R1CSShape {
125 num_cons,
126 num_vars,
127 num_io,
128 A: A.to_owned(),
129 B: B.to_owned(),
130 C: C.to_owned(),
131 };
132
133 Ok(shape)
134 }
135
136 fn multiply_vec(
137 &self,
138 z: &[G::Scalar],
139 ) -> Result<(Vec<G::Scalar>, Vec<G::Scalar>, Vec<G::Scalar>), NovaError> {
140 if z.len() != self.num_io + self.num_vars + 1 {
141 return Err(NovaError::InvalidWitnessLength);
142 }
143
144 // computes a product between a sparse matrix `M` and a vector `z`
145 // This does not perform any validation of entries in M (e.g., if entries in `M` reference indexes outside the range of `z`)
146 // This is safe since we know that `M` is valid
147 let sparse_matrix_vec_product =
148 |M: &Vec<(usize, usize, G::Scalar)>, num_rows: usize, z: &[G::Scalar]| -> Vec<G::Scalar> {
149 (0..M.len())
150 .map(|i| {
151 let (row, col, val) = M[i];
152 (row, val * z[col])
153 })
154 .fold(vec![G::Scalar::zero(); num_rows], |mut Mz, (r, v)| {
155 Mz[r] += v;
156 Mz
157 })
158 };
159
160 let Az = sparse_matrix_vec_product(&self.A, self.num_cons, z);
161 let Bz = sparse_matrix_vec_product(&self.B, self.num_cons, z);
162 let Cz = sparse_matrix_vec_product(&self.C, self.num_cons, z);
163
164 Ok((Az, Bz, Cz))
165 }
166
167 /// Checks if the Relaxed R1CS instance is satisfiable given a witness and its shape
168 pub fn is_sat_relaxed(
169 &self,
170 gens: &R1CSGens<G>,
171 U: &RelaxedR1CSInstance<G>,
172 W: &RelaxedR1CSWitness<G>,
173 ) -> Result<(), NovaError> {
174 assert_eq!(W.W.len(), self.num_vars);
175 assert_eq!(W.E.len(), self.num_cons);
176 assert_eq!(U.X.len(), self.num_io);
177
178 // verify if Az * Bz = u*Cz + E
179 let res_eq: bool = {
180 let z = concat(vec![W.W.clone(), vec![U.u], U.X.clone()]);
181 let (Az, Bz, Cz) = self.multiply_vec(&z)?;
182 assert_eq!(Az.len(), self.num_cons);
183 assert_eq!(Bz.len(), self.num_cons);
184 assert_eq!(Cz.len(), self.num_cons);
185
186 let res: usize = (0..self.num_cons)
187 .map(|i| {
188 if Az[i] * Bz[i] == U.u * Cz[i] + W.E[i] {
189 0
190 } else {
191 1
192 }
193 })
194 .sum();
195
196 res == 0
197 };
198
199 // verify if comm_E and comm_W are commitments to E and W
200 let res_comm: bool = {
201 let comm_W = W.W.commit(&gens.gens_W);
202 let comm_E = W.E.commit(&gens.gens_E);
203
204 U.comm_W == comm_W && U.comm_E == comm_E
205 };
206
207 if res_eq && res_comm {
208 Ok(())
209 } else {
210 Err(NovaError::UnSat)
211 }
212 }
213
214 /// Checks if the R1CS instance is satisfiable given a witness and its shape
215 pub fn is_sat(
216 &self,
217 gens: &R1CSGens<G>,
218 U: &R1CSInstance<G>,
219 W: &R1CSWitness<G>,
220 ) -> Result<(), NovaError> {
221 assert_eq!(W.W.len(), self.num_vars);
222 assert_eq!(U.X.len(), self.num_io);
223
224 // verify if Az * Bz = u*Cz
225 let res_eq: bool = {
226 let z = concat(vec![W.W.clone(), vec![G::Scalar::one()], U.X.clone()]);
227 let (Az, Bz, Cz) = self.multiply_vec(&z)?;
228 assert_eq!(Az.len(), self.num_cons);
229 assert_eq!(Bz.len(), self.num_cons);
230 assert_eq!(Cz.len(), self.num_cons);
231
232 let res: usize = (0..self.num_cons)
233 .map(|i| if Az[i] * Bz[i] == Cz[i] { 0 } else { 1 })
234 .sum();
235
236 res == 0
237 };
238
239 // verify if comm_W is a commitment to W
240 let res_comm: bool = U.comm_W == W.W.commit(&gens.gens_W);
241
242 if res_eq && res_comm {
243 Ok(())
244 } else {
245 Err(NovaError::UnSat)
246 }
247 }
248
249 /// A method to compute a commitment to the cross-term `T` given a
250 /// Relaxed R1CS instance-witness pair and an R1CS instance-witness pair
251 pub fn commit_T(
252 &self,
253 gens: &R1CSGens<G>,
254 U1: &RelaxedR1CSInstance<G>,
255 W1: &RelaxedR1CSWitness<G>,
256 U2: &R1CSInstance<G>,
257 W2: &R1CSWitness<G>,
258 ) -> Result<
259 (
260 Vec<G::Scalar>,
261 CompressedCommitment<G::CompressedGroupElement>,
262 ),
263 NovaError,
264 > {
265 let (AZ_1, BZ_1, CZ_1) = {
266 let Z1 = concat(vec![W1.W.clone(), vec![U1.u], U1.X.clone()]);
267 self.multiply_vec(&Z1)?
268 };
269
270 let (AZ_2, BZ_2, CZ_2) = {
271 let Z2 = concat(vec![W2.W.clone(), vec![G::Scalar::one()], U2.X.clone()]);
272 self.multiply_vec(&Z2)?
273 };
274
275 let AZ_1_circ_BZ_2 = (0..AZ_1.len())
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 .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 .map(|i| U1.u * CZ_2[i])
283 .collect::<Vec<G::Scalar>>();
284 let u_2_cdot_CZ_1 = (0..CZ_1.len()).map(|i| CZ_1[i]).collect::<Vec<G::Scalar>>();
285
286 let T = AZ_1_circ_BZ_2
287 .par_iter()
288 .zip(&AZ_2_circ_BZ_1)
289 .zip(&u_1_cdot_CZ_2)
290 .zip(&u_2_cdot_CZ_1)
291 .map(|(((a, b), c), d)| *a + *b - *c - *d)
292 .collect::<Vec<G::Scalar>>();
293
294 let comm_T = T.commit(&gens.gens_E).compress();
295
296 Ok((T, comm_T))
297 }
298}
299
300#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
301struct R1CSShapeSerialized {
302 num_cons: usize,
303 num_vars: usize,
304 num_io: usize,
305 A: Vec<(usize, usize, Vec<u8>)>,
306 B: Vec<(usize, usize, Vec<u8>)>,
307 C: Vec<(usize, usize, Vec<u8>)>,
308}
309
310impl<G: Group> AppendToTranscriptTrait for R1CSShape<G> {
311 fn append_to_transcript(&self, _label: &'static [u8], transcript: &mut Transcript) {
312 let shape_serialized = R1CSShapeSerialized {
313 num_cons: self.num_cons,
314 num_vars: self.num_vars,
315 num_io: self.num_io,
316 A: self
317 .A
318 .iter()
319 .map(|(i, j, v)| (*i, *j, v.to_repr().as_ref().to_vec()))
320 .collect(),
321 B: self
322 .B
323 .iter()
324 .map(|(i, j, v)| (*i, *j, v.to_repr().as_ref().to_vec()))
325 .collect(),
326 C: self
327 .C
328 .iter()
329 .map(|(i, j, v)| (*i, *j, v.to_repr().as_ref().to_vec()))
330 .collect(),
331 };
332
333 // obtain a vector of bytes representing the R1CS shape
334 let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
335 bincode::serialize_into(&mut encoder, &shape_serialized).unwrap();
336 let shape_bytes = encoder.finish().unwrap();
337
338 // convert shape_bytes into a short digest
339 let mut hasher = Sha3_256::new();
340 hasher.input(&shape_bytes);
341 let shape_digest = hasher.result();
342
343 let shape_digest_trun = {
344 // truncate the digest to 250 bits
345 let bv = (0..NUM_HASH_BITS).map(|i| {
346 let (byte_pos, bit_pos) = (i / 8, i % 8);
347 let bit = (shape_digest[byte_pos] >> bit_pos) & 1;
348 bit == 1
349 });
350
351 // turn the bit vector into a scalar
352 let mut res = G::Scalar::zero();
353 let mut coeff = G::Scalar::one();
354 for bit in bv {
355 if bit {
356 res += coeff;
357 }
358 coeff += coeff;
359 }
360 res
361 };
362
363 shape_digest_trun.append_to_transcript(b"R1CSShape", transcript);
364 }
365}
366
367impl<G: Group> R1CSWitness<G> {
368 /// A method to create a witness object using a vector of scalars
369 pub fn new(S: &R1CSShape<G>, W: &[G::Scalar]) -> Result<R1CSWitness<G>, NovaError> {
370 if S.num_vars != W.len() {
371 Err(NovaError::InvalidWitnessLength)
372 } else {
373 Ok(R1CSWitness { W: W.to_owned() })
374 }
375 }
376
377 /// Commits to the witness using the supplied generators
378 pub fn commit(&self, gens: &R1CSGens<G>) -> Commitment<G> {
379 self.W.commit(&gens.gens_W)
380 }
381}
382
383impl<G: Group> R1CSInstance<G> {
384 /// A method to create an instance object using consitituent elements
385 pub fn new(
386 S: &R1CSShape<G>,
387 comm_W: &Commitment<G>,
388 X: &[G::Scalar],
389 ) -> Result<R1CSInstance<G>, NovaError> {
390 if S.num_io != X.len() {
391 Err(NovaError::InvalidInputLength)
392 } else {
393 Ok(R1CSInstance {
394 comm_W: *comm_W,
395 X: X.to_owned(),
396 })
397 }
398 }
399}
400
401impl<G: Group> AppendToTranscriptTrait for R1CSInstance<G> {
402 fn append_to_transcript(&self, _label: &'static [u8], transcript: &mut Transcript) {
403 self.comm_W.append_to_transcript(b"comm_W", transcript);
404 self.X.append_to_transcript(b"X", transcript);
405 }
406}
407
408impl<G: Group> RelaxedR1CSWitness<G> {
409 /// Produces a default RelaxedR1CSWitness given an R1CSShape
410 pub fn default(S: &R1CSShape<G>) -> RelaxedR1CSWitness<G> {
411 RelaxedR1CSWitness {
412 W: vec![G::Scalar::zero(); S.num_vars],
413 E: vec![G::Scalar::zero(); S.num_cons],
414 }
415 }
416
417 /// Commits to the witness using the supplied generators
418 pub fn commit(&self, gens: &R1CSGens<G>) -> (Commitment<G>, Commitment<G>) {
419 (self.W.commit(&gens.gens_W), self.E.commit(&gens.gens_E))
420 }
421
422 /// Folds an incoming R1CSWitness into the current one
423 pub fn fold(
424 &self,
425 W2: &R1CSWitness<G>,
426 T: &[G::Scalar],
427 r: &G::Scalar,
428 ) -> Result<RelaxedR1CSWitness<G>, NovaError> {
429 let (W1, E1) = (&self.W, &self.E);
430 let W2 = &W2.W;
431
432 if W1.len() != W2.len() {
433 return Err(NovaError::InvalidWitnessLength);
434 }
435
436 let W = W1
437 .par_iter()
438 .zip(W2)
439 .map(|(a, b)| *a + *r * *b)
440 .collect::<Vec<G::Scalar>>();
441 let E = E1
442 .par_iter()
443 .zip(T)
444 .map(|(a, b)| *a + *r * *b)
445 .collect::<Vec<G::Scalar>>();
446 Ok(RelaxedR1CSWitness { W, E })
447 }
448}
449
450impl<G: Group> RelaxedR1CSInstance<G> {
451 /// Produces a default RelaxedR1CSInstance given R1CSGens and R1CSShape
452 pub fn default(gens: &R1CSGens<G>, S: &R1CSShape<G>) -> RelaxedR1CSInstance<G> {
453 let (comm_W, comm_E) = RelaxedR1CSWitness::default(S).commit(gens);
454 RelaxedR1CSInstance {
455 comm_W,
456 comm_E,
457 u: G::Scalar::zero(),
458 X: vec![G::Scalar::zero(); S.num_io],
459 Y_last: vec![G::Scalar::zero(); S.num_io / 2],
460 counter: 0,
461 }
462 }
463
464 /// Folds an incoming RelaxedR1CSInstance into the current one
465 pub fn fold(
466 &self,
467 U2: &R1CSInstance<G>,
468 comm_T: &CompressedCommitment<G::CompressedGroupElement>,
469 r: &G::Scalar,
470 ) -> Result<RelaxedR1CSInstance<G>, NovaError> {
471 let comm_T_unwrapped = comm_T.decompress()?;
472 let (X1, u1, comm_W_1, comm_E_1) =
473 (&self.X, &self.u, &self.comm_W.clone(), &self.comm_E.clone());
474 let (X2, comm_W_2) = (&U2.X, &U2.comm_W);
475
476 // check if the input of the incoming instance matches the output
477 // of the incremental computation thus far if counter > 0
478 if self.counter > 0 {
479 if self.Y_last.len() != U2.X.len() / 2 {
480 return Err(NovaError::InvalidInputLength);
481 }
482 for i in 0..self.Y_last.len() {
483 if self.Y_last[i] != U2.X[i] {
484 return Err(NovaError::InputOutputMismatch);
485 }
486 }
487 }
488
489 // weighted sum of X, comm_W, comm_E, and u
490 let X = X1
491 .par_iter()
492 .zip(X2)
493 .map(|(a, b)| *a + *r * *b)
494 .collect::<Vec<G::Scalar>>();
495 let comm_W = comm_W_1 + comm_W_2 * r;
496 let comm_E = *comm_E_1 + comm_T_unwrapped * *r;
497 let u = *u1 + *r;
498
499 Ok(RelaxedR1CSInstance {
500 comm_W,
501 comm_E,
502 X,
503 u,
504 Y_last: U2.X[U2.X.len() / 2..].to_owned(),
505 counter: self.counter + 1,
506 })
507 }
508}
509
510impl<G: Group> AppendToTranscriptTrait for RelaxedR1CSInstance<G> {
511 fn append_to_transcript(&self, _label: &'static [u8], transcript: &mut Transcript) {
512 self.comm_W.append_to_transcript(b"comm_W", transcript);
513 self.comm_E.append_to_transcript(b"comm_E", transcript);
514 self.X.append_to_transcript(b"X", transcript);
515 self.u.append_to_transcript(b"u", transcript);
516 }
517}