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
use super::{
commitments::Commitment,
constants::{NUM_FE_WITHOUT_IO_FOR_CRHF, NUM_HASH_BITS},
gadgets::{
ecc::AllocatedPoint,
r1cs::{AllocatedR1CSInstance, AllocatedRelaxedR1CSInstance},
utils::{
alloc_num_equals, alloc_scalar_as_base, alloc_zero, conditionally_select_vec, le_bits_to_num,
},
},
r1cs::{R1CSInstance, RelaxedR1CSInstance},
traits::{circuit::StepCircuit, Group, ROCircuitTrait, ROConstantsCircuit},
};
use bellperson::{
gadgets::{
boolean::{AllocatedBit, Boolean},
num::AllocatedNum,
Assignment,
},
Circuit, ConstraintSystem, SynthesisError,
};
use ff::Field;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NovaAugmentedCircuitParams {
limb_width: usize,
n_limbs: usize,
is_primary_circuit: bool, }
impl NovaAugmentedCircuitParams {
pub fn new(limb_width: usize, n_limbs: usize, is_primary_circuit: bool) -> Self {
Self {
limb_width,
n_limbs,
is_primary_circuit,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct NovaAugmentedCircuitInputs<G: Group> {
params: G::Scalar, i: G::Base,
z0: Vec<G::Base>,
zi: Option<Vec<G::Base>>,
U: Option<RelaxedR1CSInstance<G>>,
u: Option<R1CSInstance<G>>,
T: Option<Commitment<G>>,
}
impl<G> NovaAugmentedCircuitInputs<G>
where
G: Group,
{
#[allow(clippy::too_many_arguments)]
pub fn new(
params: G::Scalar,
i: G::Base,
z0: Vec<G::Base>,
zi: Option<Vec<G::Base>>,
U: Option<RelaxedR1CSInstance<G>>,
u: Option<R1CSInstance<G>>,
T: Option<Commitment<G>>,
) -> Self {
Self {
params,
i,
z0,
zi,
U,
u,
T,
}
}
}
pub struct NovaAugmentedCircuit<G, SC>
where
G: Group,
SC: StepCircuit<G::Base>,
{
params: NovaAugmentedCircuitParams,
ro_consts: ROConstantsCircuit<G>,
inputs: Option<NovaAugmentedCircuitInputs<G>>,
step_circuit: SC, }
impl<G, SC> NovaAugmentedCircuit<G, SC>
where
G: Group,
SC: StepCircuit<G::Base>,
{
pub fn new(
params: NovaAugmentedCircuitParams,
inputs: Option<NovaAugmentedCircuitInputs<G>>,
step_circuit: SC,
ro_consts: ROConstantsCircuit<G>,
) -> Self {
Self {
params,
inputs,
step_circuit,
ro_consts,
}
}
fn alloc_witness<CS: ConstraintSystem<<G as Group>::Base>>(
&self,
mut cs: CS,
arity: usize,
) -> Result<
(
AllocatedNum<G::Base>,
AllocatedNum<G::Base>,
Vec<AllocatedNum<G::Base>>,
Vec<AllocatedNum<G::Base>>,
AllocatedRelaxedR1CSInstance<G>,
AllocatedR1CSInstance<G>,
AllocatedPoint<G>,
),
SynthesisError,
> {
let params = alloc_scalar_as_base::<G, _>(
cs.namespace(|| "params"),
self.inputs.get().map_or(None, |inputs| Some(inputs.params)),
)?;
let i = AllocatedNum::alloc(cs.namespace(|| "i"), || Ok(self.inputs.get()?.i))?;
let z_0 = (0..arity)
.map(|i| {
AllocatedNum::alloc(cs.namespace(|| format!("z0_{i}")), || {
Ok(self.inputs.get()?.z0[i])
})
})
.collect::<Result<Vec<AllocatedNum<G::Base>>, _>>()?;
let zero = vec![G::Base::zero(); arity];
let z_i = (0..arity)
.map(|i| {
AllocatedNum::alloc(cs.namespace(|| format!("zi_{i}")), || {
Ok(self.inputs.get()?.zi.as_ref().unwrap_or(&zero)[i])
})
})
.collect::<Result<Vec<AllocatedNum<G::Base>>, _>>()?;
let U: AllocatedRelaxedR1CSInstance<G> = AllocatedRelaxedR1CSInstance::alloc(
cs.namespace(|| "Allocate U"),
self.inputs.get().map_or(None, |inputs| {
inputs.U.get().map_or(None, |U| Some(U.clone()))
}),
self.params.limb_width,
self.params.n_limbs,
)?;
let u = AllocatedR1CSInstance::alloc(
cs.namespace(|| "allocate instance u to fold"),
self.inputs.get().map_or(None, |inputs| {
inputs.u.get().map_or(None, |u| Some(u.clone()))
}),
)?;
let T = AllocatedPoint::alloc(
cs.namespace(|| "allocate T"),
self.inputs.get().map_or(None, |inputs| {
inputs
.T
.get()
.map_or(None, |T| Some(T.comm.to_coordinates()))
}),
)?;
Ok((params, i, z_0, z_i, U, u, T))
}
fn synthesize_base_case<CS: ConstraintSystem<<G as Group>::Base>>(
&self,
mut cs: CS,
u: AllocatedR1CSInstance<G>,
) -> Result<AllocatedRelaxedR1CSInstance<G>, SynthesisError> {
let U_default: AllocatedRelaxedR1CSInstance<G> = if self.params.is_primary_circuit {
AllocatedRelaxedR1CSInstance::default(
cs.namespace(|| "Allocate U_default"),
self.params.limb_width,
self.params.n_limbs,
)?
} else {
AllocatedRelaxedR1CSInstance::from_r1cs_instance(
cs.namespace(|| "Allocate U_default"),
u,
self.params.limb_width,
self.params.n_limbs,
)?
};
Ok(U_default)
}
#[allow(clippy::too_many_arguments)]
fn synthesize_non_base_case<CS: ConstraintSystem<<G as Group>::Base>>(
&self,
mut cs: CS,
params: AllocatedNum<G::Base>,
i: AllocatedNum<G::Base>,
z_0: Vec<AllocatedNum<G::Base>>,
z_i: Vec<AllocatedNum<G::Base>>,
U: AllocatedRelaxedR1CSInstance<G>,
u: AllocatedR1CSInstance<G>,
T: AllocatedPoint<G>,
arity: usize,
) -> Result<(AllocatedRelaxedR1CSInstance<G>, AllocatedBit), SynthesisError> {
let mut ro = G::ROCircuit::new(
self.ro_consts.clone(),
NUM_FE_WITHOUT_IO_FOR_CRHF + 2 * arity,
);
ro.absorb(params.clone());
ro.absorb(i);
for e in z_0 {
ro.absorb(e);
}
for e in z_i {
ro.absorb(e);
}
U.absorb_in_ro(cs.namespace(|| "absorb U"), &mut ro)?;
let hash_bits = ro.squeeze(cs.namespace(|| "Input hash"), NUM_HASH_BITS)?;
let hash = le_bits_to_num(cs.namespace(|| "bits to hash"), hash_bits)?;
let check_pass = alloc_num_equals(
cs.namespace(|| "check consistency of u.X[0] with H(params, U, i, z0, zi)"),
&u.X0,
&hash,
)?;
let U_fold = U.fold_with_r1cs(
cs.namespace(|| "compute fold of U and u"),
params,
u,
T,
self.ro_consts.clone(),
self.params.limb_width,
self.params.n_limbs,
)?;
Ok((U_fold, check_pass))
}
}
impl<G, SC> Circuit<<G as Group>::Base> for NovaAugmentedCircuit<G, SC>
where
G: Group,
SC: StepCircuit<G::Base>,
{
fn synthesize<CS: ConstraintSystem<<G as Group>::Base>>(
self,
cs: &mut CS,
) -> Result<(), SynthesisError> {
let arity = self.step_circuit.arity();
let (params, i, z_0, z_i, U, u, T) =
self.alloc_witness(cs.namespace(|| "allocate the circuit witness"), arity)?;
let zero = alloc_zero(cs.namespace(|| "zero"))?;
let is_base_case = alloc_num_equals(cs.namespace(|| "Check if base case"), &i.clone(), &zero)?;
let Unew_base = self.synthesize_base_case(cs.namespace(|| "base case"), u.clone())?;
let (Unew_non_base, check_non_base_pass) = self.synthesize_non_base_case(
cs.namespace(|| "synthesize non base case"),
params.clone(),
i.clone(),
z_0.clone(),
z_i.clone(),
U,
u.clone(),
T,
arity,
)?;
let should_be_false = AllocatedBit::nor(
cs.namespace(|| "check_non_base_pass nor base_case"),
&check_non_base_pass,
&is_base_case,
)?;
cs.enforce(
|| "check_non_base_pass nor base_case = false",
|lc| lc + should_be_false.get_variable(),
|lc| lc + CS::one(),
|lc| lc,
);
let Unew = Unew_base.conditionally_select(
cs.namespace(|| "compute U_new"),
Unew_non_base,
&Boolean::from(is_base_case.clone()),
)?;
let i_new = AllocatedNum::alloc(cs.namespace(|| "i + 1"), || {
Ok(*i.get_value().get()? + G::Base::one())
})?;
cs.enforce(
|| "check i + 1",
|lc| lc,
|lc| lc,
|lc| lc + i_new.get_variable() - CS::one() - i.get_variable(),
);
let z_input = conditionally_select_vec(
cs.namespace(|| "select input to F"),
&z_0,
&z_i,
&Boolean::from(is_base_case),
)?;
let z_next = self
.step_circuit
.synthesize(&mut cs.namespace(|| "F"), &z_input)?;
if z_next.len() != arity {
return Err(SynthesisError::IncompatibleLengthVector(
"z_next".to_string(),
));
}
let mut ro = G::ROCircuit::new(self.ro_consts, NUM_FE_WITHOUT_IO_FOR_CRHF + 2 * arity);
ro.absorb(params);
ro.absorb(i_new.clone());
for e in z_0 {
ro.absorb(e);
}
for e in z_next {
ro.absorb(e);
}
Unew.absorb_in_ro(cs.namespace(|| "absorb U_new"), &mut ro)?;
let hash_bits = ro.squeeze(cs.namespace(|| "output hash bits"), NUM_HASH_BITS)?;
let hash = le_bits_to_num(cs.namespace(|| "convert hash to num"), hash_bits)?;
u.X1
.inputize(cs.namespace(|| "Output unmodified hash of the other circuit"))?;
hash.inputize(cs.namespace(|| "output new hash of this circuit"))?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bellperson::{shape_cs::ShapeCS, solver::SatisfyingAssignment};
type G1 = pasta_curves::pallas::Point;
type G2 = pasta_curves::vesta::Point;
use crate::constants::{BN_LIMB_WIDTH, BN_N_LIMBS};
use crate::{
bellperson::r1cs::{NovaShape, NovaWitness},
poseidon::PoseidonConstantsCircuit,
traits::{circuit::TrivialTestCircuit, ROConstantsTrait},
};
#[test]
fn test_recursive_circuit() {
let params1 = NovaAugmentedCircuitParams::new(BN_LIMB_WIDTH, BN_N_LIMBS, true);
let params2 = NovaAugmentedCircuitParams::new(BN_LIMB_WIDTH, BN_N_LIMBS, false);
let ro_consts1: ROConstantsCircuit<G2> = PoseidonConstantsCircuit::new();
let ro_consts2: ROConstantsCircuit<G1> = PoseidonConstantsCircuit::new();
let circuit1: NovaAugmentedCircuit<G2, TrivialTestCircuit<<G2 as Group>::Base>> =
NovaAugmentedCircuit::new(
params1.clone(),
None,
TrivialTestCircuit::default(),
ro_consts1.clone(),
);
let mut cs: ShapeCS<G1> = ShapeCS::new();
let _ = circuit1.synthesize(&mut cs);
let (shape1, gens1) = (cs.r1cs_shape(), cs.r1cs_gens());
assert_eq!(cs.num_constraints(), 9815);
let circuit2: NovaAugmentedCircuit<G1, TrivialTestCircuit<<G1 as Group>::Base>> =
NovaAugmentedCircuit::new(
params2.clone(),
None,
TrivialTestCircuit::default(),
ro_consts2.clone(),
);
let mut cs: ShapeCS<G2> = ShapeCS::new();
let _ = circuit2.synthesize(&mut cs);
let (shape2, gens2) = (cs.r1cs_shape(), cs.r1cs_gens());
assert_eq!(cs.num_constraints(), 10347);
let zero1 = <<G2 as Group>::Base as Field>::zero();
let mut cs1: SatisfyingAssignment<G1> = SatisfyingAssignment::new();
let inputs1: NovaAugmentedCircuitInputs<G2> = NovaAugmentedCircuitInputs::new(
shape2.get_digest(),
zero1,
vec![zero1],
None,
None,
None,
None,
);
let circuit1: NovaAugmentedCircuit<G2, TrivialTestCircuit<<G2 as Group>::Base>> =
NovaAugmentedCircuit::new(
params1,
Some(inputs1),
TrivialTestCircuit::default(),
ro_consts1,
);
let _ = circuit1.synthesize(&mut cs1);
let (inst1, witness1) = cs1.r1cs_instance_and_witness(&shape1, &gens1).unwrap();
assert!(shape1.is_sat(&gens1, &inst1, &witness1).is_ok());
let zero2 = <<G1 as Group>::Base as Field>::zero();
let mut cs2: SatisfyingAssignment<G2> = SatisfyingAssignment::new();
let inputs2: NovaAugmentedCircuitInputs<G1> = NovaAugmentedCircuitInputs::new(
shape1.get_digest(),
zero2,
vec![zero2],
None,
None,
Some(inst1),
None,
);
let circuit: NovaAugmentedCircuit<G1, TrivialTestCircuit<<G1 as Group>::Base>> =
NovaAugmentedCircuit::new(
params2,
Some(inputs2),
TrivialTestCircuit::default(),
ro_consts2,
);
let _ = circuit.synthesize(&mut cs2);
let (inst2, witness2) = cs2.r1cs_instance_and_witness(&shape2, &gens2).unwrap();
assert!(shape2.is_sat(&gens2, &inst2, &witness2).is_ok());
}
}