-
Notifications
You must be signed in to change notification settings - Fork 36
/
lib.rs
1709 lines (1515 loc) · 54.5 KB
/
lib.rs
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This library implements Nova, a high-speed recursive SNARK.
#![deny(
warnings,
unused,
future_incompatible,
nonstandard_style,
rust_2018_idioms,
missing_docs
)]
#![allow(non_snake_case)]
// #![forbid(unsafe_code)] // Commented for development with `Abomonation`
// private modules
mod bellpepper;
mod circuit;
mod digest;
mod nifs;
// public modules
pub mod constants;
pub mod errors;
pub mod gadgets;
pub mod provider;
pub mod r1cs;
pub mod spartan;
pub mod traits;
pub mod cyclefold;
pub mod supernova;
use once_cell::sync::OnceCell;
use traits::{CurveCycleEquipped, Dual};
use crate::digest::{DigestComputer, SimpleDigestible};
use crate::{
bellpepper::{
r1cs::{NovaShape, NovaWitness},
shape_cs::ShapeCS,
solver::SatisfyingAssignment,
},
r1cs::R1CSResult,
};
use abomonation::Abomonation;
use abomonation_derive::Abomonation;
use bellpepper_core::{ConstraintSystem, SynthesisError};
use circuit::{NovaAugmentedCircuit, NovaAugmentedCircuitInputs, NovaAugmentedCircuitParams};
use constants::{BN_LIMB_WIDTH, BN_N_LIMBS, NUM_FE_WITHOUT_IO_FOR_CRHF, NUM_HASH_BITS};
use errors::NovaError;
use ff::{Field, PrimeField};
use gadgets::scalar_as_base;
use nifs::NIFS;
use r1cs::{
CommitmentKeyHint, R1CSInstance, R1CSShape, R1CSWitness, RelaxedR1CSInstance, RelaxedR1CSWitness,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use traits::{
circuit::StepCircuit,
commitment::{CommitmentEngineTrait, CommitmentTrait},
snark::RelaxedR1CSSNARKTrait,
AbsorbInROTrait, Engine, ROConstants, ROConstantsCircuit, ROTrait,
};
/// A type that holds parameters for the primary and secondary circuits of Nova and SuperNova
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Abomonation)]
#[serde(bound = "")]
#[abomonation_bounds(where <E::Scalar as PrimeField>::Repr: Abomonation)]
pub struct R1CSWithArity<E: Engine> {
F_arity: usize,
r1cs_shape: R1CSShape<E>,
}
impl<E: Engine> SimpleDigestible for R1CSWithArity<E> {}
impl<E: Engine> R1CSWithArity<E> {
/// Create a new `R1CSWithArity`
pub fn new(r1cs_shape: R1CSShape<E>, F_arity: usize) -> Self {
Self {
F_arity,
r1cs_shape,
}
}
/// Return the [`R1CSWithArity`]' digest.
pub fn digest(&self) -> E::Scalar {
let dc: DigestComputer<'_, <E as Engine>::Scalar, Self> = DigestComputer::new(self);
dc.digest().expect("Failure in computing digest")
}
}
/// A type that holds public parameters of Nova
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct PublicParams<E>
where
E: CurveCycleEquipped,
{
F_arity_primary: usize,
F_arity_secondary: usize,
ro_consts_primary: ROConstants<E>,
ro_consts_circuit_primary: ROConstantsCircuit<Dual<E>>,
ck_primary: Arc<CommitmentKey<E>>,
circuit_shape_primary: R1CSWithArity<E>,
ro_consts_secondary: ROConstants<Dual<E>>,
ro_consts_circuit_secondary: ROConstantsCircuit<E>,
ck_secondary: Arc<CommitmentKey<Dual<E>>>,
circuit_shape_secondary: R1CSWithArity<Dual<E>>,
augmented_circuit_params_primary: NovaAugmentedCircuitParams,
augmented_circuit_params_secondary: NovaAugmentedCircuitParams,
#[serde(skip, default = "OnceCell::new")]
digest: OnceCell<E::Scalar>,
}
// Ensure to include necessary crates and features in your Cargo.toml
// e.g., abomonation, serde, etc., with the appropriate feature flags.
/// A version of [`crate::PublicParams`] that is amenable to fast ser/de using Abomonation
#[cfg(feature = "abomonate")]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Abomonation)]
#[serde(bound = "")]
#[abomonation_bounds(
where
E1: CurveCycleEquipped,
<E1::Scalar as PrimeField>::Repr: Abomonation,
<<Dual<E1> as Engine>::Scalar as PrimeField>::Repr: Abomonation,
)]
pub struct FlatPublicParams<E1>
where
E1: CurveCycleEquipped,
{
F_arity_primary: usize,
F_arity_secondary: usize,
ro_consts_primary: ROConstants<E1>,
ro_consts_circuit_primary: ROConstantsCircuit<Dual<E1>>,
ck_primary: CommitmentKey<E1>,
circuit_shape_primary: R1CSWithArity<E1>,
ro_consts_secondary: ROConstants<Dual<E1>>,
ro_consts_circuit_secondary: ROConstantsCircuit<E1>,
ck_secondary: CommitmentKey<Dual<E1>>,
circuit_shape_secondary: R1CSWithArity<Dual<E1>>,
augmented_circuit_params_primary: NovaAugmentedCircuitParams,
augmented_circuit_params_secondary: NovaAugmentedCircuitParams,
}
#[cfg(feature = "abomonate")]
impl<E1> TryFrom<PublicParams<E1>> for FlatPublicParams<E1>
where
E1: CurveCycleEquipped,
{
type Error = &'static str;
fn try_from(value: PublicParams<E1>) -> Result<Self, Self::Error> {
let ck_primary =
Arc::try_unwrap(value.ck_primary).map_err(|_| "Failed to unwrap Arc for ck_primary")?;
let ck_secondary =
Arc::try_unwrap(value.ck_secondary).map_err(|_| "Failed to unwrap Arc for ck_secondary")?;
Ok(Self {
F_arity_primary: value.F_arity_primary,
F_arity_secondary: value.F_arity_secondary,
ro_consts_primary: value.ro_consts_primary,
ro_consts_circuit_primary: value.ro_consts_circuit_primary,
ck_primary,
circuit_shape_primary: value.circuit_shape_primary,
ro_consts_secondary: value.ro_consts_secondary,
ro_consts_circuit_secondary: value.ro_consts_circuit_secondary,
ck_secondary,
circuit_shape_secondary: value.circuit_shape_secondary,
augmented_circuit_params_primary: value.augmented_circuit_params_primary,
augmented_circuit_params_secondary: value.augmented_circuit_params_secondary,
})
}
}
#[cfg(feature = "abomonate")]
impl<E1> From<FlatPublicParams<E1>> for PublicParams<E1>
where
E1: CurveCycleEquipped,
{
fn from(value: FlatPublicParams<E1>) -> Self {
Self {
F_arity_primary: value.F_arity_primary,
F_arity_secondary: value.F_arity_secondary,
ro_consts_primary: value.ro_consts_primary,
ro_consts_circuit_primary: value.ro_consts_circuit_primary,
ck_primary: Arc::new(value.ck_primary),
circuit_shape_primary: value.circuit_shape_primary,
ro_consts_secondary: value.ro_consts_secondary,
ro_consts_circuit_secondary: value.ro_consts_circuit_secondary,
ck_secondary: Arc::new(value.ck_secondary),
circuit_shape_secondary: value.circuit_shape_secondary,
augmented_circuit_params_primary: value.augmented_circuit_params_primary,
augmented_circuit_params_secondary: value.augmented_circuit_params_secondary,
digest: OnceCell::new(),
}
}
}
impl<E1> SimpleDigestible for PublicParams<E1> where E1: CurveCycleEquipped {}
impl<E1> PublicParams<E1>
where
E1: CurveCycleEquipped,
{
/// Set up builder to create `PublicParams` for a pair of circuits `C1` and `C2`.
///
/// # Note
///
/// Public parameters set up a number of bases for the homomorphic commitment scheme of Nova.
///
/// Some final compressing SNARKs, like variants of Spartan, use computation commitments that require
/// larger sizes for these parameters. These SNARKs provide a hint for these values by
/// implementing `RelaxedR1CSSNARKTrait::ck_floor()`, which can be passed to this function.
///
/// If you're not using such a SNARK, pass `arecibo::traits::snark::default_ck_hint()` instead.
///
/// # Arguments
///
/// * `c_primary`: The primary circuit of type `C1`.
/// * `c_secondary`: The secondary circuit of type `C2`.
/// * `ck_hint1`: A `CommitmentKeyHint` for `G1`, which is a function that provides a hint
/// for the number of generators required in the commitment scheme for the primary circuit.
/// * `ck_hint2`: A `CommitmentKeyHint` for `G2`, similar to `ck_hint1`, but for the secondary circuit.
///
/// # Example
///
/// ```rust
/// # use arecibo::spartan::ppsnark::RelaxedR1CSSNARK;
/// # use arecibo::provider::ipa_pc::EvaluationEngine;
/// # use arecibo::provider::{PallasEngine, VestaEngine};
/// # use arecibo::traits::{circuit::TrivialCircuit, Engine, snark::RelaxedR1CSSNARKTrait};
/// use arecibo::PublicParams;
///
/// type E1 = PallasEngine;
/// type E2 = VestaEngine;
/// type EE<E> = EvaluationEngine<E>;
/// type SPrime<E> = RelaxedR1CSSNARK<E, EE<E>>;
///
/// let circuit1 = TrivialCircuit::<<E1 as Engine>::Scalar>::default();
/// let circuit2 = TrivialCircuit::<<E2 as Engine>::Scalar>::default();
/// // Only relevant for a SNARK using computation commitmnets, pass &(|_| 0)
/// // or &*nova_snark::traits::snark::default_ck_hint() otherwise.
/// let ck_hint1 = &*SPrime::<E1>::ck_floor();
/// let ck_hint2 = &*SPrime::<E2>::ck_floor();
///
/// let pp = PublicParams::setup(&circuit1, &circuit2, ck_hint1, ck_hint2).unwrap();
/// ```
pub fn setup<C1: StepCircuit<E1::Scalar>, C2: StepCircuit<<Dual<E1> as Engine>::Scalar>>(
c_primary: &C1,
c_secondary: &C2,
ck_hint1: &CommitmentKeyHint<E1>,
ck_hint2: &CommitmentKeyHint<Dual<E1>>,
) -> Result<Self, NovaError> {
let augmented_circuit_params_primary =
NovaAugmentedCircuitParams::new(BN_LIMB_WIDTH, BN_N_LIMBS, true);
let augmented_circuit_params_secondary =
NovaAugmentedCircuitParams::new(BN_LIMB_WIDTH, BN_N_LIMBS, false);
let ro_consts_primary: ROConstants<E1> = ROConstants::<E1>::default();
let ro_consts_secondary: ROConstants<Dual<E1>> = ROConstants::<Dual<E1>>::default();
let F_arity_primary = c_primary.arity();
let F_arity_secondary = c_secondary.arity();
// ro_consts_circuit_primary are parameterized by E2 because the type alias uses E2::Base = E1::Scalar
let ro_consts_circuit_primary: ROConstantsCircuit<Dual<E1>> =
ROConstantsCircuit::<Dual<E1>>::default();
let ro_consts_circuit_secondary: ROConstantsCircuit<E1> = ROConstantsCircuit::<E1>::default();
// Initialize ck for the primary
let circuit_primary: NovaAugmentedCircuit<'_, Dual<E1>, C1> = NovaAugmentedCircuit::new(
&augmented_circuit_params_primary,
None,
c_primary,
ro_consts_circuit_primary.clone(),
);
let mut cs: ShapeCS<E1> = ShapeCS::new();
let _ = circuit_primary.synthesize(&mut cs);
let (r1cs_shape_primary, ck_primary) = cs.r1cs_shape_and_key(ck_hint1);
let ck_primary = Arc::new(ck_primary);
// Initialize ck for the secondary
let circuit_secondary: NovaAugmentedCircuit<'_, E1, C2> = NovaAugmentedCircuit::new(
&augmented_circuit_params_secondary,
None,
c_secondary,
ro_consts_circuit_secondary.clone(),
);
let mut cs: ShapeCS<Dual<E1>> = ShapeCS::new();
let _ = circuit_secondary.synthesize(&mut cs);
let (r1cs_shape_secondary, ck_secondary) = cs.r1cs_shape_and_key(ck_hint2);
let ck_secondary = Arc::new(ck_secondary);
if r1cs_shape_primary.num_io != 2 || r1cs_shape_secondary.num_io != 2 {
return Err(NovaError::InvalidStepCircuitIO);
}
let circuit_shape_primary = R1CSWithArity::new(r1cs_shape_primary, F_arity_primary);
let circuit_shape_secondary = R1CSWithArity::new(r1cs_shape_secondary, F_arity_secondary);
Ok(Self {
F_arity_primary,
F_arity_secondary,
ro_consts_primary,
ro_consts_circuit_primary,
ck_primary,
circuit_shape_primary,
ro_consts_secondary,
ro_consts_circuit_secondary,
ck_secondary,
circuit_shape_secondary,
augmented_circuit_params_primary,
augmented_circuit_params_secondary,
digest: OnceCell::new(),
})
}
/// Retrieve the digest of the public parameters.
pub fn digest(&self) -> E1::Scalar {
self
.digest
.get_or_try_init(|| DigestComputer::new(self).digest())
.cloned()
.expect("Failure in retrieving digest")
}
/// Returns the number of constraints in the primary and secondary circuits
pub const fn num_constraints(&self) -> (usize, usize) {
(
self.circuit_shape_primary.r1cs_shape.num_cons,
self.circuit_shape_secondary.r1cs_shape.num_cons,
)
}
/// Returns the number of variables in the primary and secondary circuits
pub const fn num_variables(&self) -> (usize, usize) {
(
self.circuit_shape_primary.r1cs_shape.num_vars,
self.circuit_shape_secondary.r1cs_shape.num_vars,
)
}
}
/// A resource buffer for [`RecursiveSNARK`] for storing scratch values that are computed by `prove_step`,
/// which allows the reuse of memory allocations and avoids unnecessary new allocations in the critical section.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct ResourceBuffer<E: Engine> {
l_w: Option<R1CSWitness<E>>,
l_u: Option<R1CSInstance<E>>,
ABC_Z_1: R1CSResult<E>,
ABC_Z_2: R1CSResult<E>,
/// buffer for `commit_T`
T: Vec<E::Scalar>,
}
/// A SNARK that proves the correct execution of an incremental computation
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct RecursiveSNARK<E1>
where
E1: CurveCycleEquipped,
{
z0_primary: Vec<E1::Scalar>,
z0_secondary: Vec<<Dual<E1> as Engine>::Scalar>,
r_W_primary: RelaxedR1CSWitness<E1>,
r_U_primary: RelaxedR1CSInstance<E1>,
r_W_secondary: RelaxedR1CSWitness<Dual<E1>>,
r_U_secondary: RelaxedR1CSInstance<Dual<E1>>,
l_w_secondary: R1CSWitness<Dual<E1>>,
l_u_secondary: R1CSInstance<Dual<E1>>,
/// Buffer for memory needed by the primary fold-step
buffer_primary: ResourceBuffer<E1>,
/// Buffer for memory needed by the secondary fold-step
buffer_secondary: ResourceBuffer<Dual<E1>>,
i: usize,
zi_primary: Vec<E1::Scalar>,
zi_secondary: Vec<<Dual<E1> as Engine>::Scalar>,
}
impl<E1> RecursiveSNARK<E1>
where
E1: CurveCycleEquipped,
{
/// Create new instance of recursive SNARK
pub fn new<C1: StepCircuit<E1::Scalar>, C2: StepCircuit<<Dual<E1> as Engine>::Scalar>>(
pp: &PublicParams<E1>,
c_primary: &C1,
c_secondary: &C2,
z0_primary: &[E1::Scalar],
z0_secondary: &[<Dual<E1> as Engine>::Scalar],
) -> Result<Self, NovaError> {
if z0_primary.len() != pp.F_arity_primary || z0_secondary.len() != pp.F_arity_secondary {
return Err(NovaError::InvalidInitialInputLength);
}
let r1cs_primary = &pp.circuit_shape_primary.r1cs_shape;
let r1cs_secondary = &pp.circuit_shape_secondary.r1cs_shape;
// base case for the primary
let mut cs_primary = SatisfyingAssignment::<E1>::new();
let inputs_primary: NovaAugmentedCircuitInputs<Dual<E1>> = NovaAugmentedCircuitInputs::new(
scalar_as_base::<E1>(pp.digest()),
E1::Scalar::ZERO,
z0_primary.to_vec(),
None,
None,
None,
None,
);
let circuit_primary: NovaAugmentedCircuit<'_, Dual<E1>, C1> = NovaAugmentedCircuit::new(
&pp.augmented_circuit_params_primary,
Some(inputs_primary),
c_primary,
pp.ro_consts_circuit_primary.clone(),
);
let zi_primary = circuit_primary.synthesize(&mut cs_primary)?;
let (u_primary, w_primary) =
cs_primary.r1cs_instance_and_witness(r1cs_primary, &pp.ck_primary)?;
// base case for the secondary
let mut cs_secondary = SatisfyingAssignment::<Dual<E1>>::new();
let inputs_secondary: NovaAugmentedCircuitInputs<E1> = NovaAugmentedCircuitInputs::new(
pp.digest(),
<Dual<E1> as Engine>::Scalar::ZERO,
z0_secondary.to_vec(),
None,
None,
Some(u_primary.clone()),
None,
);
let circuit_secondary: NovaAugmentedCircuit<'_, E1, C2> = NovaAugmentedCircuit::new(
&pp.augmented_circuit_params_secondary,
Some(inputs_secondary),
c_secondary,
pp.ro_consts_circuit_secondary.clone(),
);
let zi_secondary = circuit_secondary.synthesize(&mut cs_secondary)?;
let (u_secondary, w_secondary) = cs_secondary
.r1cs_instance_and_witness(&pp.circuit_shape_secondary.r1cs_shape, &pp.ck_secondary)?;
// IVC proof for the primary circuit
let l_w_primary = w_primary;
let l_u_primary = u_primary;
let r_W_primary = RelaxedR1CSWitness::from_r1cs_witness(r1cs_primary, l_w_primary);
let r_U_primary = RelaxedR1CSInstance::from_r1cs_instance(
&*pp.ck_primary,
&pp.circuit_shape_primary.r1cs_shape,
l_u_primary,
);
// IVC proof for the secondary circuit
let l_w_secondary = w_secondary;
let l_u_secondary = u_secondary;
let r_W_secondary = RelaxedR1CSWitness::<Dual<E1>>::default(r1cs_secondary);
let r_U_secondary = RelaxedR1CSInstance::<Dual<E1>>::default(&pp.ck_secondary, r1cs_secondary);
assert!(
!(zi_primary.len() != pp.F_arity_primary || zi_secondary.len() != pp.F_arity_secondary),
"Invalid step length"
);
let zi_primary = zi_primary
.iter()
.map(|v| v.get_value().ok_or(SynthesisError::AssignmentMissing))
.collect::<Result<Vec<<E1 as Engine>::Scalar>, _>>()?;
let zi_secondary = zi_secondary
.iter()
.map(|v| v.get_value().ok_or(SynthesisError::AssignmentMissing))
.collect::<Result<Vec<<Dual<E1> as Engine>::Scalar>, _>>()?;
let buffer_primary = ResourceBuffer {
l_w: None,
l_u: None,
ABC_Z_1: R1CSResult::default(r1cs_primary.num_cons),
ABC_Z_2: R1CSResult::default(r1cs_primary.num_cons),
T: r1cs::default_T::<E1>(r1cs_primary.num_cons),
};
let buffer_secondary = ResourceBuffer {
l_w: None,
l_u: None,
ABC_Z_1: R1CSResult::default(r1cs_secondary.num_cons),
ABC_Z_2: R1CSResult::default(r1cs_secondary.num_cons),
T: r1cs::default_T::<Dual<E1>>(r1cs_secondary.num_cons),
};
Ok(Self {
z0_primary: z0_primary.to_vec(),
z0_secondary: z0_secondary.to_vec(),
r_W_primary,
r_U_primary,
r_W_secondary,
r_U_secondary,
l_w_secondary,
l_u_secondary,
buffer_primary,
buffer_secondary,
i: 0,
zi_primary,
zi_secondary,
})
}
/// Inputs of the primary circuits
pub fn z0_primary(&self) -> &Vec<E1::Scalar> {
&self.z0_primary
}
/// Outputs of the primary circuits
pub fn zi_primary(&self) -> &Vec<E1::Scalar> {
&self.zi_primary
}
/// Create a new `RecursiveSNARK` (or updates the provided `RecursiveSNARK`)
/// by executing a step of the incremental computation
#[tracing::instrument(skip_all, name = "nova::RecursiveSNARK::prove_step")]
pub fn prove_step<C1: StepCircuit<E1::Scalar>, C2: StepCircuit<<Dual<E1> as Engine>::Scalar>>(
&mut self,
pp: &PublicParams<E1>,
c_primary: &C1,
c_secondary: &C2,
) -> Result<(), NovaError> {
// first step was already done in the constructor
if self.i == 0 {
self.i = 1;
return Ok(());
}
// save the inputs before proceeding to the `i+1`th step
let r_U_primary_i = self.r_U_primary.clone();
let r_U_secondary_i = self.r_U_secondary.clone();
let l_u_secondary_i = self.l_u_secondary.clone();
// fold the secondary circuit's instance
let (nifs_secondary, _) = NIFS::prove_mut(
&*pp.ck_secondary,
&pp.ro_consts_secondary,
&scalar_as_base::<E1>(pp.digest()),
&pp.circuit_shape_secondary.r1cs_shape,
&mut self.r_U_secondary,
&mut self.r_W_secondary,
&self.l_u_secondary,
&self.l_w_secondary,
&mut self.buffer_secondary.T,
&mut self.buffer_secondary.ABC_Z_1,
&mut self.buffer_secondary.ABC_Z_2,
)?;
let mut cs_primary = SatisfyingAssignment::<E1>::with_capacity(
pp.circuit_shape_primary.r1cs_shape.num_io + 1,
pp.circuit_shape_primary.r1cs_shape.num_vars,
);
let inputs_primary: NovaAugmentedCircuitInputs<Dual<E1>> = NovaAugmentedCircuitInputs::new(
scalar_as_base::<E1>(pp.digest()),
E1::Scalar::from(self.i as u64),
self.z0_primary.to_vec(),
Some(self.zi_primary.clone()),
Some(r_U_secondary_i),
Some(l_u_secondary_i),
Some(Commitment::<Dual<E1>>::decompress(&nifs_secondary.comm_T)?),
);
let circuit_primary: NovaAugmentedCircuit<'_, Dual<E1>, C1> = NovaAugmentedCircuit::new(
&pp.augmented_circuit_params_primary,
Some(inputs_primary),
c_primary,
pp.ro_consts_circuit_primary.clone(),
);
let zi_primary = circuit_primary.synthesize(&mut cs_primary)?;
let (l_u_primary, l_w_primary) =
cs_primary.r1cs_instance_and_witness(&pp.circuit_shape_primary.r1cs_shape, &pp.ck_primary)?;
// fold the primary circuit's instance
let (nifs_primary, _) = NIFS::prove_mut(
&*pp.ck_primary,
&pp.ro_consts_primary,
&pp.digest(),
&pp.circuit_shape_primary.r1cs_shape,
&mut self.r_U_primary,
&mut self.r_W_primary,
&l_u_primary,
&l_w_primary,
&mut self.buffer_primary.T,
&mut self.buffer_primary.ABC_Z_1,
&mut self.buffer_primary.ABC_Z_2,
)?;
let mut cs_secondary = SatisfyingAssignment::<Dual<E1>>::with_capacity(
pp.circuit_shape_secondary.r1cs_shape.num_io + 1,
pp.circuit_shape_secondary.r1cs_shape.num_vars,
);
let inputs_secondary: NovaAugmentedCircuitInputs<E1> = NovaAugmentedCircuitInputs::new(
pp.digest(),
<Dual<E1> as Engine>::Scalar::from(self.i as u64),
self.z0_secondary.to_vec(),
Some(self.zi_secondary.clone()),
Some(r_U_primary_i),
Some(l_u_primary),
Some(Commitment::<E1>::decompress(&nifs_primary.comm_T)?),
);
let circuit_secondary: NovaAugmentedCircuit<'_, E1, C2> = NovaAugmentedCircuit::new(
&pp.augmented_circuit_params_secondary,
Some(inputs_secondary),
c_secondary,
pp.ro_consts_circuit_secondary.clone(),
);
let zi_secondary = circuit_secondary.synthesize(&mut cs_secondary)?;
let (l_u_secondary, l_w_secondary) = cs_secondary
.r1cs_instance_and_witness(&pp.circuit_shape_secondary.r1cs_shape, &pp.ck_secondary)
.map_err(|_e| NovaError::UnSat)?;
// update the running instances and witnesses
self.zi_primary = zi_primary
.iter()
.map(|v| v.get_value().ok_or(SynthesisError::AssignmentMissing))
.collect::<Result<Vec<<E1 as Engine>::Scalar>, _>>()?;
self.zi_secondary = zi_secondary
.iter()
.map(|v| v.get_value().ok_or(SynthesisError::AssignmentMissing))
.collect::<Result<Vec<<Dual<E1> as Engine>::Scalar>, _>>()?;
self.l_u_secondary = l_u_secondary;
self.l_w_secondary = l_w_secondary;
self.i += 1;
Ok(())
}
/// Verify the correctness of the `RecursiveSNARK`
pub fn verify(
&self,
pp: &PublicParams<E1>,
num_steps: usize,
z0_primary: &[E1::Scalar],
z0_secondary: &[<Dual<E1> as Engine>::Scalar],
) -> Result<(Vec<E1::Scalar>, Vec<<Dual<E1> as Engine>::Scalar>), NovaError> {
// number of steps cannot be zero
let is_num_steps_zero = num_steps == 0;
// check if the provided proof has executed num_steps
let is_num_steps_not_match = self.i != num_steps;
// check if the initial inputs match
let is_inputs_not_match = self.z0_primary != z0_primary || self.z0_secondary != z0_secondary;
// check if the (relaxed) R1CS instances have two public outputs
let is_instance_has_two_outputs = self.l_u_secondary.X.len() != 2
|| self.r_U_primary.X.len() != 2
|| self.r_U_secondary.X.len() != 2;
if is_num_steps_zero
|| is_num_steps_not_match
|| is_inputs_not_match
|| is_instance_has_two_outputs
{
return Err(NovaError::ProofVerifyError);
}
// check if the output hashes in R1CS instances point to the right running instances
let (hash_primary, hash_secondary) = {
let mut hasher = <Dual<E1> as Engine>::RO::new(
pp.ro_consts_secondary.clone(),
NUM_FE_WITHOUT_IO_FOR_CRHF + 2 * pp.F_arity_primary,
);
hasher.absorb(pp.digest());
hasher.absorb(E1::Scalar::from(num_steps as u64));
for e in z0_primary {
hasher.absorb(*e);
}
for e in &self.zi_primary {
hasher.absorb(*e);
}
self.r_U_secondary.absorb_in_ro(&mut hasher);
let mut hasher2 = <E1 as Engine>::RO::new(
pp.ro_consts_primary.clone(),
NUM_FE_WITHOUT_IO_FOR_CRHF + 2 * pp.F_arity_secondary,
);
hasher2.absorb(scalar_as_base::<E1>(pp.digest()));
hasher2.absorb(<Dual<E1> as Engine>::Scalar::from(num_steps as u64));
for e in z0_secondary {
hasher2.absorb(*e);
}
for e in &self.zi_secondary {
hasher2.absorb(*e);
}
self.r_U_primary.absorb_in_ro(&mut hasher2);
(
hasher.squeeze(NUM_HASH_BITS),
hasher2.squeeze(NUM_HASH_BITS),
)
};
if hash_primary != self.l_u_secondary.X[0]
|| hash_secondary != scalar_as_base::<Dual<E1>>(self.l_u_secondary.X[1])
{
return Err(NovaError::ProofVerifyError);
}
// check the satisfiability of the provided instances
let (res_r_primary, (res_r_secondary, res_l_secondary)) = rayon::join(
|| {
pp.circuit_shape_primary.r1cs_shape.is_sat_relaxed(
&pp.ck_primary,
&self.r_U_primary,
&self.r_W_primary,
)
},
|| {
rayon::join(
|| {
pp.circuit_shape_secondary.r1cs_shape.is_sat_relaxed(
&pp.ck_secondary,
&self.r_U_secondary,
&self.r_W_secondary,
)
},
|| {
pp.circuit_shape_secondary.r1cs_shape.is_sat(
&pp.ck_secondary,
&self.l_u_secondary,
&self.l_w_secondary,
)
},
)
},
);
// check the returned res objects
res_r_primary?;
res_r_secondary?;
res_l_secondary?;
Ok((self.zi_primary.clone(), self.zi_secondary.clone()))
}
/// Get the outputs after the last step of computation.
pub fn outputs(&self) -> (&[E1::Scalar], &[<Dual<E1> as Engine>::Scalar]) {
(&self.zi_primary, &self.zi_secondary)
}
/// The number of steps which have been executed thus far.
pub fn num_steps(&self) -> usize {
self.i
}
}
/// A type that holds the prover key for `CompressedSNARK`
#[derive(Clone, Debug)]
pub struct ProverKey<E1, S1, S2>
where
E1: CurveCycleEquipped,
S1: RelaxedR1CSSNARKTrait<E1>,
S2: RelaxedR1CSSNARKTrait<Dual<E1>>,
{
pk_primary: S1::ProverKey,
pk_secondary: S2::ProverKey,
}
/// A type that holds the verifier key for `CompressedSNARK`
#[derive(Debug, Clone, Serialize)]
#[serde(bound = "")]
pub struct VerifierKey<E1, S1, S2>
where
E1: CurveCycleEquipped,
S1: RelaxedR1CSSNARKTrait<E1>,
S2: RelaxedR1CSSNARKTrait<Dual<E1>>,
{
F_arity_primary: usize,
F_arity_secondary: usize,
ro_consts_primary: ROConstants<E1>,
ro_consts_secondary: ROConstants<Dual<E1>>,
pp_digest: E1::Scalar,
vk_primary: S1::VerifierKey,
vk_secondary: S2::VerifierKey,
}
/// A SNARK that proves the knowledge of a valid `RecursiveSNARK`
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(bound = "")]
pub struct CompressedSNARK<E1, S1, S2>
where
E1: CurveCycleEquipped,
S1: RelaxedR1CSSNARKTrait<E1>,
S2: RelaxedR1CSSNARKTrait<Dual<E1>>,
{
r_U_primary: RelaxedR1CSInstance<E1>,
r_W_snark_primary: S1,
r_U_secondary: RelaxedR1CSInstance<Dual<E1>>,
l_u_secondary: R1CSInstance<Dual<E1>>,
nifs_secondary: NIFS<Dual<E1>>,
f_W_snark_secondary: S2,
zn_primary: Vec<E1::Scalar>,
zn_secondary: Vec<<Dual<E1> as Engine>::Scalar>,
}
impl<E1, S1, S2> CompressedSNARK<E1, S1, S2>
where
E1: CurveCycleEquipped,
S1: RelaxedR1CSSNARKTrait<E1>,
S2: RelaxedR1CSSNARKTrait<Dual<E1>>,
{
/// Creates prover and verifier keys for `CompressedSNARK`
pub fn setup(
pp: &PublicParams<E1>,
) -> Result<(ProverKey<E1, S1, S2>, VerifierKey<E1, S1, S2>), NovaError> {
let (pk_primary, vk_primary) =
S1::setup(pp.ck_primary.clone(), &pp.circuit_shape_primary.r1cs_shape)?;
let (pk_secondary, vk_secondary) = S2::setup(
pp.ck_secondary.clone(),
&pp.circuit_shape_secondary.r1cs_shape,
)?;
let pk = ProverKey {
pk_primary,
pk_secondary,
};
let vk = VerifierKey {
F_arity_primary: pp.F_arity_primary,
F_arity_secondary: pp.F_arity_secondary,
ro_consts_primary: pp.ro_consts_primary.clone(),
ro_consts_secondary: pp.ro_consts_secondary.clone(),
pp_digest: pp.digest(),
vk_primary,
vk_secondary,
};
Ok((pk, vk))
}
/// Create a new `CompressedSNARK`
pub fn prove(
pp: &PublicParams<E1>,
pk: &ProverKey<E1, S1, S2>,
recursive_snark: &RecursiveSNARK<E1>,
) -> Result<Self, NovaError> {
// fold the secondary circuit's instance with its running instance
let (nifs_secondary, (f_U_secondary, f_W_secondary), _) = NIFS::prove(
&*pp.ck_secondary,
&pp.ro_consts_secondary,
&scalar_as_base::<E1>(pp.digest()),
&pp.circuit_shape_secondary.r1cs_shape,
&recursive_snark.r_U_secondary,
&recursive_snark.r_W_secondary,
&recursive_snark.l_u_secondary,
&recursive_snark.l_w_secondary,
)?;
// create SNARKs proving the knowledge of f_W_primary and f_W_secondary
let (r_W_snark_primary, f_W_snark_secondary) = rayon::join(
|| {
S1::prove(
&pp.ck_primary,
&pk.pk_primary,
&pp.circuit_shape_primary.r1cs_shape,
&recursive_snark.r_U_primary,
&recursive_snark.r_W_primary,
)
},
|| {
S2::prove(
&pp.ck_secondary,
&pk.pk_secondary,
&pp.circuit_shape_secondary.r1cs_shape,
&f_U_secondary,
&f_W_secondary,
)
},
);
Ok(Self {
r_U_primary: recursive_snark.r_U_primary.clone(),
r_W_snark_primary: r_W_snark_primary?,
r_U_secondary: recursive_snark.r_U_secondary.clone(),
l_u_secondary: recursive_snark.l_u_secondary.clone(),
nifs_secondary,
f_W_snark_secondary: f_W_snark_secondary?,
zn_primary: recursive_snark.zi_primary.clone(),
zn_secondary: recursive_snark.zi_secondary.clone(),
})
}
/// Verify the correctness of the `CompressedSNARK`
pub fn verify(
&self,
vk: &VerifierKey<E1, S1, S2>,
num_steps: usize,
z0_primary: &[E1::Scalar],
z0_secondary: &[<Dual<E1> as Engine>::Scalar],
) -> Result<(Vec<E1::Scalar>, Vec<<Dual<E1> as Engine>::Scalar>), NovaError> {
// the number of steps cannot be zero
if num_steps == 0 {
return Err(NovaError::ProofVerifyError);
}
// check if the (relaxed) R1CS instances have two public outputs
if self.l_u_secondary.X.len() != 2
|| self.r_U_primary.X.len() != 2
|| self.r_U_secondary.X.len() != 2
{
return Err(NovaError::ProofVerifyError);
}
// check if the output hashes in R1CS instances point to the right running instances
let (hash_primary, hash_secondary) = {
let mut hasher = <Dual<E1> as Engine>::RO::new(
vk.ro_consts_secondary.clone(),
NUM_FE_WITHOUT_IO_FOR_CRHF + 2 * vk.F_arity_primary,
);
hasher.absorb(vk.pp_digest);
hasher.absorb(E1::Scalar::from(num_steps as u64));
for e in z0_primary {
hasher.absorb(*e);
}
for e in &self.zn_primary {
hasher.absorb(*e);
}
self.r_U_secondary.absorb_in_ro(&mut hasher);
let mut hasher2 = <E1 as Engine>::RO::new(
vk.ro_consts_primary.clone(),
NUM_FE_WITHOUT_IO_FOR_CRHF + 2 * vk.F_arity_secondary,
);
hasher2.absorb(scalar_as_base::<E1>(vk.pp_digest));
hasher2.absorb(<Dual<E1> as Engine>::Scalar::from(num_steps as u64));
for e in z0_secondary {
hasher2.absorb(*e);
}
for e in &self.zn_secondary {
hasher2.absorb(*e);
}
self.r_U_primary.absorb_in_ro(&mut hasher2);
(
hasher.squeeze(NUM_HASH_BITS),
hasher2.squeeze(NUM_HASH_BITS),
)
};
if hash_primary != self.l_u_secondary.X[0]
|| hash_secondary != scalar_as_base::<Dual<E1>>(self.l_u_secondary.X[1])
{
return Err(NovaError::ProofVerifyError);
}
// fold the secondary's running instance with the last instance to get a folded instance
let f_U_secondary = self.nifs_secondary.verify(
&vk.ro_consts_secondary,
&scalar_as_base::<E1>(vk.pp_digest),
&self.r_U_secondary,
&self.l_u_secondary,
)?;
// check the satisfiability of the folded instances using
// SNARKs proving the knowledge of their satisfying witnesses
let (res_primary, res_secondary) = rayon::join(
|| {
self
.r_W_snark_primary
.verify(&vk.vk_primary, &self.r_U_primary)
},
|| {
self
.f_W_snark_secondary
.verify(&vk.vk_secondary, &f_U_secondary)
},
);
res_primary?;
res_secondary?;
Ok((self.zn_primary.clone(), self.zn_secondary.clone()))
}
}
/// Compute the circuit digest of a [`StepCircuit`].
///
/// Note for callers: This function should be called with its performance characteristics in mind.
/// It will synthesize and digest the full `circuit` given.
pub fn circuit_digest<E1: CurveCycleEquipped, C: StepCircuit<E1::Scalar>>(
circuit: &C,
) -> E1::Scalar {