-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathmod.rs
More file actions
695 lines (610 loc) · 20.2 KB
/
mod.rs
File metadata and controls
695 lines (610 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! This module defines R1CS related types and a folding scheme for Relaxed R1CS
pub mod sparse;
mod util;
use crate::{
constants::{BN_LIMB_WIDTH, BN_N_LIMBS},
digest::{DigestComputer, SimpleDigestible},
errors::NovaError,
gadgets::{
nonnative::{bignat::nat_to_limbs, util::f_to_nat},
utils::scalar_as_base,
},
traits::{
commitment::CommitmentEngineTrait, AbsorbInROTrait, Group, ROTrait, TranscriptReprTrait,
},
Commitment, CommitmentKey, CE,
};
use abomonation::Abomonation;
use abomonation_derive::Abomonation;
use core::cmp::max;
use ff::Field;
use once_cell::sync::OnceCell;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use self::sparse::SparseMatrix;
/// A type that holds the shape of the R1CS matrices
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Abomonation)]
#[abomonation_bounds(where <G::Scalar as ff::PrimeField>::Repr: Abomonation)]
pub struct R1CSShape<G: Group> {
pub(crate) num_cons: usize,
pub(crate) num_vars: usize,
pub(crate) num_io: usize,
pub(crate) A: SparseMatrix<G::Scalar>,
pub(crate) B: SparseMatrix<G::Scalar>,
pub(crate) C: SparseMatrix<G::Scalar>,
#[abomonation_skip]
#[serde(skip, default = "OnceCell::new")]
pub(crate) digest: OnceCell<G::Scalar>,
}
impl<G: Group> SimpleDigestible for R1CSShape<G> {}
/// A type that holds a witness for a given R1CS instance
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct R1CSWitness<G: Group> {
W: Vec<G::Scalar>,
}
/// A type that holds an R1CS instance
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct R1CSInstance<G: Group> {
pub(crate) comm_W: Commitment<G>,
pub(crate) X: Vec<G::Scalar>,
}
/// A type that holds a witness for a given Relaxed R1CS instance
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RelaxedR1CSWitness<G: Group> {
pub(crate) W: Vec<G::Scalar>,
pub(crate) E: Vec<G::Scalar>,
}
/// A type that holds a Relaxed R1CS instance
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct RelaxedR1CSInstance<G: Group> {
pub(crate) comm_W: Commitment<G>,
pub(crate) comm_E: Commitment<G>,
pub(crate) X: Vec<G::Scalar>,
pub(crate) u: G::Scalar,
}
/// A type for functions that hints commitment key sizing by returning the floor of the number of required generators.
pub type CommitmentKeyHint<G> = Box<dyn Fn(&R1CSShape<G>) -> usize>;
/// Generates public parameters for a Rank-1 Constraint System (R1CS).
///
/// This function takes into consideration the shape of the R1CS matrices and a hint function
/// for the number of generators. It returns a `CommitmentKey`.
///
/// # Arguments
///
/// * `S`: The shape of the R1CS matrices.
/// * `commitment_key_hint`: An optional function that provides a floor for the number of
/// generators. A good function to provide is the `commitment_key_floor` field in the trait `RelaxedR1CSSNARKTrait`.
/// If no floor function is provided, the default number of generators will be `max(S.num_cons`, `S.num_vars`).
///
pub fn commitment_key<G: Group>(
S: &R1CSShape<G>,
commitment_key_floor: Option<CommitmentKeyHint<G>>,
) -> CommitmentKey<G> {
let size = commitment_key_size(S, commitment_key_floor);
G::CE::setup(b"ck", size)
}
/// Computes the number of generators required for the commitment key corresponding to shape `S`.
pub fn commitment_key_size<G: Group>(
S: &R1CSShape<G>,
commitment_key_floor: Option<CommitmentKeyHint<G>>,
) -> usize {
let num_cons = S.num_cons;
let num_vars = S.num_vars;
let generators_hint = commitment_key_floor.map_or(0, |f| f(S));
max(max(num_cons, num_vars), generators_hint)
}
impl<G: Group> R1CSShape<G> {
/// Create an object of type `R1CSShape` from the explicitly specified R1CS matrices
pub fn new(
num_cons: usize,
num_vars: usize,
num_io: usize,
A: SparseMatrix<G::Scalar>,
B: SparseMatrix<G::Scalar>,
C: SparseMatrix<G::Scalar>,
) -> Result<R1CSShape<G>, NovaError> {
let is_valid = |num_cons: usize,
num_vars: usize,
num_io: usize,
M: &SparseMatrix<G::Scalar>|
-> Result<(), NovaError> {
let res = M
.iter()
.map(|(row, col, _val)| {
if row >= num_cons || col > num_io + num_vars {
Err(NovaError::InvalidIndex)
} else {
Ok(())
}
})
.collect::<Result<Vec<()>, NovaError>>();
if res.is_err() {
Err(NovaError::InvalidIndex)
} else {
Ok(())
}
};
let res_A = is_valid(num_cons, num_vars, num_io, &A);
let res_B = is_valid(num_cons, num_vars, num_io, &B);
let res_C = is_valid(num_cons, num_vars, num_io, &C);
if res_A.is_err() || res_B.is_err() || res_C.is_err() {
return Err(NovaError::InvalidIndex);
}
// We require the number of public inputs/outputs to be even
if num_io % 2 != 0 {
return Err(NovaError::OddInputLength);
}
Ok(R1CSShape {
num_cons,
num_vars,
num_io,
A,
B,
C,
digest: OnceCell::new(),
})
}
/// returnd the digest of the `R1CSShape`
pub fn digest(&self) -> G::Scalar {
self
.digest
.get_or_try_init(|| DigestComputer::new(self).digest())
.cloned()
.expect("Failure retrieving digest")
}
// Checks regularity conditions on the R1CSShape, required in Spartan-class SNARKs
// Panics if num_cons, num_vars, or num_io are not powers of two, or if num_io > num_vars
#[inline]
pub(crate) fn check_regular_shape(&self) {
assert_eq!(self.num_cons.next_power_of_two(), self.num_cons);
assert_eq!(self.num_vars.next_power_of_two(), self.num_vars);
assert_eq!(self.num_io.next_power_of_two(), self.num_io);
assert!(self.num_io < self.num_vars);
}
pub(crate) fn multiply_vec(
&self,
z: &[G::Scalar],
) -> Result<(Vec<G::Scalar>, Vec<G::Scalar>, Vec<G::Scalar>), NovaError> {
if z.len() != self.num_io + self.num_vars + 1 {
return Err(NovaError::InvalidWitnessLength);
}
let (Az, (Bz, Cz)) = rayon::join(
|| self.A.multiply_vec(z),
|| rayon::join(|| self.B.multiply_vec(z), || self.C.multiply_vec(z)),
);
Ok((Az, Bz, Cz))
}
/// Checks if the Relaxed R1CS instance is satisfiable given a witness and its shape
pub fn is_sat_relaxed(
&self,
ck: &CommitmentKey<G>,
U: &RelaxedR1CSInstance<G>,
W: &RelaxedR1CSWitness<G>,
) -> Result<(), NovaError> {
assert_eq!(W.W.len(), self.num_vars);
assert_eq!(W.E.len(), self.num_cons);
assert_eq!(U.X.len(), self.num_io);
// verify if Az * Bz = u*Cz + E
let res_eq: Result<(), NovaError> = {
let z = [W.W.clone(), vec![U.u], U.X.clone()].concat();
let (Az, Bz, Cz) = self.multiply_vec(&z)?;
assert_eq!(Az.len(), self.num_cons);
assert_eq!(Bz.len(), self.num_cons);
assert_eq!(Cz.len(), self.num_cons);
(0..self.num_cons).try_for_each(|i| {
if Az[i] * Bz[i] != U.u * Cz[i] + W.E[i] {
// constraint failed
Err(NovaError::UnSatIndex(i))
} else {
Ok(())
}
})
};
res_eq?;
// verify if comm_E and comm_W are commitments to E and W
let res_comm: bool = {
let (comm_W, comm_E) =
rayon::join(|| CE::<G>::commit(ck, &W.W), || CE::<G>::commit(ck, &W.E));
U.comm_W == comm_W && U.comm_E == comm_E
};
if !res_comm {
return Err(NovaError::UnSat);
}
Ok(())
}
/// Checks if the R1CS instance is satisfiable given a witness and its shape
pub fn is_sat(
&self,
ck: &CommitmentKey<G>,
U: &R1CSInstance<G>,
W: &R1CSWitness<G>,
) -> Result<(), NovaError> {
assert_eq!(W.W.len(), self.num_vars);
assert_eq!(U.X.len(), self.num_io);
// verify if Az * Bz = u*Cz
let res_eq: Result<(), NovaError> = {
let z = [W.W.clone(), vec![G::Scalar::ONE], U.X.clone()].concat();
let (Az, Bz, Cz) = self.multiply_vec(&z)?;
assert_eq!(Az.len(), self.num_cons);
assert_eq!(Bz.len(), self.num_cons);
assert_eq!(Cz.len(), self.num_cons);
(0..self.num_cons).try_for_each(|i| {
if Az[i] * Bz[i] != Cz[i] {
// constraint failed, retrieve constaint name
Err(NovaError::UnSatIndex(i))
} else {
Ok(())
}
})
};
res_eq?;
// verify if comm_W is a commitment to W
let res_comm: bool = U.comm_W == CE::<G>::commit(ck, &W.W);
if !res_comm {
return Err(NovaError::UnSat);
}
Ok(())
}
/// A method to compute a commitment to the cross-term `T` given a
/// Relaxed R1CS instance-witness pair and an R1CS instance-witness pair
pub fn commit_T(
&self,
ck: &CommitmentKey<G>,
U1: &RelaxedR1CSInstance<G>,
W1: &RelaxedR1CSWitness<G>,
U2: &R1CSInstance<G>,
W2: &R1CSWitness<G>,
) -> Result<(Vec<G::Scalar>, Commitment<G>), NovaError> {
let (AZ_1, BZ_1, CZ_1) = tracing::trace_span!("AZ_1, BZ_1, CZ_1").in_scope(|| {
let Z1 = [W1.W.clone(), vec![U1.u], U1.X.clone()].concat();
self.multiply_vec(&Z1)
})?;
let (AZ_2, BZ_2, CZ_2) = tracing::trace_span!("AZ_2, BZ_2, CZ_2").in_scope(|| {
let Z2 = [W2.W.clone(), vec![G::Scalar::ONE], U2.X.clone()].concat();
self.multiply_vec(&Z2)
})?;
let (AZ_1_circ_BZ_2, AZ_2_circ_BZ_1, u_1_cdot_CZ_2, u_2_cdot_CZ_1) =
tracing::trace_span!("cross terms").in_scope(|| {
let AZ_1_circ_BZ_2 = (0..AZ_1.len())
.into_par_iter()
.map(|i| AZ_1[i] * BZ_2[i])
.collect::<Vec<G::Scalar>>();
let AZ_2_circ_BZ_1 = (0..AZ_2.len())
.into_par_iter()
.map(|i| AZ_2[i] * BZ_1[i])
.collect::<Vec<G::Scalar>>();
let u_1_cdot_CZ_2 = (0..CZ_2.len())
.into_par_iter()
.map(|i| U1.u * CZ_2[i])
.collect::<Vec<G::Scalar>>();
let u_2_cdot_CZ_1 = (0..CZ_1.len())
.into_par_iter()
.map(|i| CZ_1[i])
.collect::<Vec<G::Scalar>>();
(AZ_1_circ_BZ_2, AZ_2_circ_BZ_1, u_1_cdot_CZ_2, u_2_cdot_CZ_1)
});
let T = tracing::trace_span!("T").in_scope(|| {
AZ_1_circ_BZ_2
.par_iter()
.zip(&AZ_2_circ_BZ_1)
.zip(&u_1_cdot_CZ_2)
.zip(&u_2_cdot_CZ_1)
.map(|(((a, b), c), d)| *a + *b - *c - *d)
.collect::<Vec<G::Scalar>>()
});
let comm_T = CE::<G>::commit(ck, &T);
Ok((T, comm_T))
}
/// Pads the `R1CSShape` so that the number of variables is a power of two
/// Renumbers variables to accomodate padded variables
pub fn pad(&self) -> Self {
// equalize the number of variables and constraints
let m = max(self.num_vars, self.num_cons).next_power_of_two();
// check if the provided R1CSShape is already as required
if self.num_vars == m && self.num_cons == m {
return self.clone();
}
// check if the number of variables are as expected, then
// we simply set the number of constraints to the next power of two
if self.num_vars == m {
return R1CSShape {
num_cons: m,
num_vars: m,
num_io: self.num_io,
A: self.A.clone(),
B: self.B.clone(),
C: self.C.clone(),
digest: OnceCell::new(),
};
}
// otherwise, we need to pad the number of variables and renumber variable accesses
let num_vars_padded = m;
let num_cons_padded = m;
let apply_pad = |mut M: SparseMatrix<G::Scalar>| -> SparseMatrix<G::Scalar> {
M.indices.par_iter_mut().for_each(|c| {
if *c >= self.num_vars {
*c += num_vars_padded - self.num_vars
}
});
M.cols += num_vars_padded - self.num_vars;
let ex = {
let nnz = M.indptr.last().unwrap();
vec![*nnz; num_cons_padded - self.num_cons]
};
M.indptr.extend(ex);
M
};
let A_padded = apply_pad(self.A.clone());
let B_padded = apply_pad(self.B.clone());
let C_padded = apply_pad(self.C.clone());
R1CSShape {
num_cons: num_cons_padded,
num_vars: num_vars_padded,
num_io: self.num_io,
A: A_padded,
B: B_padded,
C: C_padded,
digest: OnceCell::new(),
}
}
}
impl<G: Group> R1CSWitness<G> {
/// A method to create a witness object using a vector of scalars
pub fn new(S: &R1CSShape<G>, W: &[G::Scalar]) -> Result<R1CSWitness<G>, NovaError> {
if S.num_vars != W.len() {
Err(NovaError::InvalidWitnessLength)
} else {
Ok(R1CSWitness { W: W.to_owned() })
}
}
/// Commits to the witness using the supplied generators
pub fn commit(&self, ck: &CommitmentKey<G>) -> Commitment<G> {
CE::<G>::commit(ck, &self.W)
}
}
impl<G: Group> R1CSInstance<G> {
/// A method to create an instance object using consitituent elements
pub fn new(
S: &R1CSShape<G>,
comm_W: &Commitment<G>,
X: &[G::Scalar],
) -> Result<R1CSInstance<G>, NovaError> {
if S.num_io != X.len() {
Err(NovaError::InvalidInputLength)
} else {
Ok(R1CSInstance {
comm_W: *comm_W,
X: X.to_owned(),
})
}
}
}
impl<G: Group> AbsorbInROTrait<G> for R1CSInstance<G> {
fn absorb_in_ro(&self, ro: &mut G::RO) {
self.comm_W.absorb_in_ro(ro);
for x in &self.X {
ro.absorb(scalar_as_base::<G>(*x));
}
}
}
impl<G: Group> RelaxedR1CSWitness<G> {
/// Produces a default `RelaxedR1CSWitness` given an `R1CSShape`
pub fn default(S: &R1CSShape<G>) -> RelaxedR1CSWitness<G> {
RelaxedR1CSWitness {
W: vec![G::Scalar::ZERO; S.num_vars],
E: vec![G::Scalar::ZERO; S.num_cons],
}
}
/// Initializes a new `RelaxedR1CSWitness` from an `R1CSWitness`
pub fn from_r1cs_witness(S: &R1CSShape<G>, witness: &R1CSWitness<G>) -> RelaxedR1CSWitness<G> {
RelaxedR1CSWitness {
W: witness.W.clone(),
E: vec![G::Scalar::ZERO; S.num_cons],
}
}
/// Commits to the witness using the supplied generators
pub fn commit(&self, ck: &CommitmentKey<G>) -> (Commitment<G>, Commitment<G>) {
(CE::<G>::commit(ck, &self.W), CE::<G>::commit(ck, &self.E))
}
/// Folds an incoming `R1CSWitness` into the current one
pub fn fold(
&self,
W2: &R1CSWitness<G>,
T: &[G::Scalar],
r: &G::Scalar,
) -> Result<RelaxedR1CSWitness<G>, NovaError> {
let (W1, E1) = (&self.W, &self.E);
let W2 = &W2.W;
if W1.len() != W2.len() {
return Err(NovaError::InvalidWitnessLength);
}
let W = W1
.par_iter()
.zip(W2)
.map(|(a, b)| *a + *r * *b)
.collect::<Vec<G::Scalar>>();
let E = E1
.par_iter()
.zip(T)
.map(|(a, b)| *a + *r * *b)
.collect::<Vec<G::Scalar>>();
Ok(RelaxedR1CSWitness { W, E })
}
/// Pads the provided witness to the correct length
pub fn pad(&self, S: &R1CSShape<G>) -> RelaxedR1CSWitness<G> {
let W = {
let mut W = self.W.clone();
W.extend(vec![G::Scalar::ZERO; S.num_vars - W.len()]);
W
};
let E = {
let mut E = self.E.clone();
E.extend(vec![G::Scalar::ZERO; S.num_cons - E.len()]);
E
};
Self { W, E }
}
}
impl<G: Group> RelaxedR1CSInstance<G> {
/// Produces a default `RelaxedR1CSInstance` given `R1CSGens` and `R1CSShape`
pub fn default(_ck: &CommitmentKey<G>, S: &R1CSShape<G>) -> RelaxedR1CSInstance<G> {
let (comm_W, comm_E) = (Commitment::<G>::default(), Commitment::<G>::default());
RelaxedR1CSInstance {
comm_W,
comm_E,
u: G::Scalar::ZERO,
X: vec![G::Scalar::ZERO; S.num_io],
}
}
/// Initializes a new `RelaxedR1CSInstance` from an `R1CSInstance`
pub fn from_r1cs_instance(
ck: &CommitmentKey<G>,
S: &R1CSShape<G>,
instance: &R1CSInstance<G>,
) -> RelaxedR1CSInstance<G> {
let mut r_instance = RelaxedR1CSInstance::default(ck, S);
r_instance.comm_W = instance.comm_W;
r_instance.u = G::Scalar::ONE;
r_instance.X = instance.X.clone();
r_instance
}
/// Initializes a new `RelaxedR1CSInstance` from an `R1CSInstance`
pub fn from_r1cs_instance_unchecked(
comm_W: &Commitment<G>,
X: &[G::Scalar],
) -> RelaxedR1CSInstance<G> {
RelaxedR1CSInstance {
comm_W: *comm_W,
comm_E: Commitment::<G>::default(),
u: G::Scalar::ONE,
X: X.to_vec(),
}
}
/// Folds an incoming `RelaxedR1CSInstance` into the current one
pub fn fold(
&self,
U2: &R1CSInstance<G>,
comm_T: &Commitment<G>,
r: &G::Scalar,
) -> Result<RelaxedR1CSInstance<G>, NovaError> {
let (X1, u1, comm_W_1, comm_E_1) =
(&self.X, &self.u, &self.comm_W.clone(), &self.comm_E.clone());
let (X2, comm_W_2) = (&U2.X, &U2.comm_W);
// weighted sum of X, comm_W, comm_E, and u
let X = X1
.par_iter()
.zip(X2)
.map(|(a, b)| *a + *r * *b)
.collect::<Vec<G::Scalar>>();
let comm_W = *comm_W_1 + *comm_W_2 * *r;
let comm_E = *comm_E_1 + *comm_T * *r;
let u = *u1 + *r;
Ok(RelaxedR1CSInstance {
comm_W,
comm_E,
X,
u,
})
}
}
impl<G: Group> TranscriptReprTrait<G> for RelaxedR1CSInstance<G> {
fn to_transcript_bytes(&self) -> Vec<u8> {
[
self.comm_W.to_transcript_bytes(),
self.comm_E.to_transcript_bytes(),
self.u.to_transcript_bytes(),
self.X.as_slice().to_transcript_bytes(),
]
.concat()
}
}
impl<G: Group> AbsorbInROTrait<G> for RelaxedR1CSInstance<G> {
fn absorb_in_ro(&self, ro: &mut G::RO) {
self.comm_W.absorb_in_ro(ro);
self.comm_E.absorb_in_ro(ro);
ro.absorb(scalar_as_base::<G>(self.u));
// absorb each element of self.X in bignum format
for x in &self.X {
let limbs: Vec<G::Scalar> = nat_to_limbs(&f_to_nat(x), BN_LIMB_WIDTH, BN_N_LIMBS).unwrap();
for limb in limbs {
ro.absorb(scalar_as_base::<G>(limb));
}
}
}
}
#[cfg(test)]
mod tests {
use ff::Field;
use super::*;
use crate::{r1cs::sparse::SparseMatrix, traits::Group};
fn tiny_r1cs<G: Group>(num_vars: usize) -> R1CSShape<G> {
let one = <G::Scalar as Field>::ONE;
let (num_cons, num_vars, num_io, A, B, C) = {
let num_cons = 4;
let num_io = 2;
// Consider a cubic equation: `x^3 + x + 5 = y`, where `x` and `y` are respectively the input and output.
// The R1CS for this problem consists of the following constraints:
// `I0 * I0 - Z0 = 0`
// `Z0 * I0 - Z1 = 0`
// `(Z1 + I0) * 1 - Z2 = 0`
// `(Z2 + 5) * 1 - I1 = 0`
// Relaxed R1CS is a set of three sparse matrices (A B C), where there is a row for every
// constraint and a column for every entry in z = (vars, u, inputs)
// An R1CS instance is satisfiable iff:
// Az \circ Bz = u \cdot Cz + E, where z = (vars, 1, inputs)
let mut A: Vec<(usize, usize, G::Scalar)> = Vec::new();
let mut B: Vec<(usize, usize, G::Scalar)> = Vec::new();
let mut C: Vec<(usize, usize, G::Scalar)> = Vec::new();
// constraint 0 entries in (A,B,C)
// `I0 * I0 - Z0 = 0`
A.push((0, num_vars + 1, one));
B.push((0, num_vars + 1, one));
C.push((0, 0, one));
// constraint 1 entries in (A,B,C)
// `Z0 * I0 - Z1 = 0`
A.push((1, 0, one));
B.push((1, num_vars + 1, one));
C.push((1, 1, one));
// constraint 2 entries in (A,B,C)
// `(Z1 + I0) * 1 - Z2 = 0`
A.push((2, 1, one));
A.push((2, num_vars + 1, one));
B.push((2, num_vars, one));
C.push((2, 2, one));
// constraint 3 entries in (A,B,C)
// `(Z2 + 5) * 1 - I1 = 0`
A.push((3, 2, one));
A.push((3, num_vars, one + one + one + one + one));
B.push((3, num_vars, one));
C.push((3, num_vars + 2, one));
(num_cons, num_vars, num_io, A, B, C)
};
// create a shape object
let rows = num_cons;
let cols = num_vars + num_io + 1;
let res = R1CSShape::new(
num_cons,
num_vars,
num_io,
SparseMatrix::new(&A, rows, cols),
SparseMatrix::new(&B, rows, cols),
SparseMatrix::new(&C, rows, cols),
);
assert!(res.is_ok());
res.unwrap()
}
fn test_pad_tiny_r1cs_with<G: Group>() {
let padded_r1cs = tiny_r1cs::<G>(3).pad();
padded_r1cs.check_regular_shape();
let expected_r1cs = tiny_r1cs::<G>(4);
assert_eq!(padded_r1cs, expected_r1cs);
}
#[test]
fn test_pad_tiny_r1cs() {
test_pad_tiny_r1cs_with::<pasta_curves::pallas::Point>();
test_pad_tiny_r1cs_with::<crate::provider::bn256_grumpkin::bn256::Point>();
test_pad_tiny_r1cs_with::<crate::provider::secp_secq::secp256k1::Point>();
}
}