#![deny(
+ warnings,
+ unused,
+ future_incompatible,
+ nonstandard_style,
+ rust_2018_idioms,
+ missing_docs
+)]
+#![allow(non_snake_case)]
+mod bellpepper;
+mod circuit;
+mod digest;
+mod nifs;
+
+pub mod constants;
+pub mod errors;
+pub mod gadgets;
+pub mod provider;
+pub mod r1cs;
+pub mod spartan;
+pub mod traits;
+
+pub mod supernova;
+
+use once_cell::sync::OnceCell;
+
+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 core::marker::PhantomData;
+use errors::NovaError;
+use ff::{Field, PrimeField};
+use gadgets::utils::scalar_as_base;
+use nifs::NIFS;
+use r1cs::{
+ CommitmentKeyHint, R1CSInstance, R1CSShape, R1CSWitness, RelaxedR1CSInstance, RelaxedR1CSWitness,
+};
+use serde::{Deserialize, Serialize};
+use traits::{
+ circuit::StepCircuit,
+ commitment::{CommitmentEngineTrait, CommitmentTrait},
+ snark::RelaxedR1CSSNARKTrait,
+ AbsorbInROTrait, Engine, ROConstants, ROConstantsCircuit, ROTrait,
+};
+
+#[derive(Clone, 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> {
+ pub fn new(r1cs_shape: R1CSShape<E>, F_arity: usize) -> Self {
+ Self {
+ F_arity,
+ r1cs_shape,
+ }
+ }
+
+ pub fn digest(&self) -> E::Scalar {
+ let dc: DigestComputer<'_, <E as Engine>::Scalar, Self> = DigestComputer::new(self);
+ dc.digest().expect("Failure in computing digest")
+ }
+}
+
+#[derive(Clone, PartialEq, Serialize, Deserialize, Abomonation)]
+#[serde(bound = "")]
+#[abomonation_bounds(
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+ <E1::Scalar as PrimeField>::Repr: Abomonation,
+ <E2::Scalar as PrimeField>::Repr: Abomonation,
+)]
+pub struct PublicParams<E1, E2, C1, C2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+{
+ F_arity_primary: usize,
+ F_arity_secondary: usize,
+ ro_consts_primary: ROConstants<E1>,
+ ro_consts_circuit_primary: ROConstantsCircuit<E2>,
+ ck_primary: CommitmentKey<E1>,
+ circuit_shape_primary: R1CSWithArity<E1>,
+ ro_consts_secondary: ROConstants<E2>,
+ ro_consts_circuit_secondary: ROConstantsCircuit<E1>,
+ ck_secondary: CommitmentKey<E2>,
+ circuit_shape_secondary: R1CSWithArity<E2>,
+ augmented_circuit_params_primary: NovaAugmentedCircuitParams,
+ augmented_circuit_params_secondary: NovaAugmentedCircuitParams,
+ #[abomonation_skip]
+ #[serde(skip, default = "OnceCell::new")]
+ digest: OnceCell<E1::Scalar>,
+ _p: PhantomData<(C1, C2)>,
+}
+
+impl<E1, E2, C1, C2> SimpleDigestible for PublicParams<E1, E2, C1, C2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+{
+}
+
+impl<E1, E2, C1, C2> PublicParams<E1, E2, C1, C2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+{
+ pub fn setup(
+ c_primary: &C1,
+ c_secondary: &C2,
+ ck_hint1: &CommitmentKeyHint<E1>,
+ ck_hint2: &CommitmentKeyHint<E2>,
+ ) -> Self {
+ 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<E2> = ROConstants::<E2>::default();
+
+ let F_arity_primary = c_primary.arity();
+ let F_arity_secondary = c_secondary.arity();
+
+ let ro_consts_circuit_primary: ROConstantsCircuit<E2> = ROConstantsCircuit::<E2>::default();
+ let ro_consts_circuit_secondary: ROConstantsCircuit<E1> = ROConstantsCircuit::<E1>::default();
+
+ let circuit_primary: NovaAugmentedCircuit<'_, E2, 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 circuit_shape_primary = R1CSWithArity::new(r1cs_shape_primary, F_arity_primary);
+
+ let circuit_secondary: NovaAugmentedCircuit<'_, E1, C2> = NovaAugmentedCircuit::new(
+ &augmented_circuit_params_secondary,
+ None,
+ c_secondary,
+ ro_consts_circuit_secondary.clone(),
+ );
+ let mut cs: ShapeCS<E2> = ShapeCS::new();
+ let _ = circuit_secondary.synthesize(&mut cs);
+ let (r1cs_shape_secondary, ck_secondary) = cs.r1cs_shape_and_key(ck_hint2);
+ let circuit_shape_secondary = R1CSWithArity::new(r1cs_shape_secondary, F_arity_secondary);
+
+ 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(),
+ _p: Default::default(),
+ }
+ }
+
+ pub fn digest(&self) -> E1::Scalar {
+ self
+ .digest
+ .get_or_try_init(|| DigestComputer::new(self).digest())
+ .cloned()
+ .expect("Failure in retrieving digest")
+ }
+
+ pub const fn num_constraints(&self) -> (usize, usize) {
+ (
+ self.circuit_shape_primary.r1cs_shape.num_cons,
+ self.circuit_shape_secondary.r1cs_shape.num_cons,
+ )
+ }
+
+ pub const fn num_variables(&self) -> (usize, usize) {
+ (
+ self.circuit_shape_primary.r1cs_shape.num_vars,
+ self.circuit_shape_secondary.r1cs_shape.num_vars,
+ )
+ }
+}
+
+#[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>,
+
+ T: Vec<E::Scalar>,
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(bound = "")]
+pub struct RecursiveSNARK<E1, E2, C1, C2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+{
+ z0_primary: Vec<E1::Scalar>,
+ z0_secondary: Vec<E2::Scalar>,
+ r_W_primary: RelaxedR1CSWitness<E1>,
+ r_U_primary: RelaxedR1CSInstance<E1>,
+ r_W_secondary: RelaxedR1CSWitness<E2>,
+ r_U_secondary: RelaxedR1CSInstance<E2>,
+ l_w_secondary: R1CSWitness<E2>,
+ l_u_secondary: R1CSInstance<E2>,
+
+ buffer_primary: ResourceBuffer<E1>,
+ buffer_secondary: ResourceBuffer<E2>,
+
+ i: usize,
+ zi_primary: Vec<E1::Scalar>,
+ zi_secondary: Vec<E2::Scalar>,
+ _p: PhantomData<(C1, C2)>,
+}
+
+impl<E1, E2, C1, C2> RecursiveSNARK<E1, E2, C1, C2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+{
+ pub fn new(
+ pp: &PublicParams<E1, E2, C1, C2>,
+ c_primary: &C1,
+ c_secondary: &C2,
+ z0_primary: &[E1::Scalar],
+ z0_secondary: &[E2::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;
+
+ let mut cs_primary = SatisfyingAssignment::<E1>::new();
+ let inputs_primary: NovaAugmentedCircuitInputs<E2> = NovaAugmentedCircuitInputs::new(
+ scalar_as_base::<E1>(pp.digest()),
+ E1::Scalar::ZERO,
+ z0_primary.to_vec(),
+ None,
+ None,
+ None,
+ None,
+ );
+
+ let circuit_primary: NovaAugmentedCircuit<'_, E2, 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)?;
+
+ let mut cs_secondary = SatisfyingAssignment::<E2>::new();
+ let inputs_secondary: NovaAugmentedCircuitInputs<E1> = NovaAugmentedCircuitInputs::new(
+ pp.digest(),
+ E2::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)?;
+
+ 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,
+ );
+
+ let l_w_secondary = w_secondary;
+ let l_u_secondary = u_secondary;
+ let r_W_secondary = RelaxedR1CSWitness::<E2>::default(r1cs_secondary);
+ let r_U_secondary = RelaxedR1CSInstance::<E2>::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<<E2 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::<E2>(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,
+ _p: Default::default(),
+ })
+ }
+
+ #[tracing::instrument(skip_all, name = "nova::RecursiveSNARK::prove_step")]
+ pub fn prove_step(
+ &mut self,
+ pp: &PublicParams<E1, E2, C1, C2>,
+ c_primary: &C1,
+ c_secondary: &C2,
+ ) -> Result<(), NovaError> {
+ if self.i == 0 {
+ self.i = 1;
+ return Ok(());
+ }
+
+ 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();
+
+ 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<E2> = 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::<E2>::decompress(&nifs_secondary.comm_T)?),
+ );
+
+ let circuit_primary: NovaAugmentedCircuit<'_, E2, 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)?;
+
+ 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::<E2>::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(),
+ E2::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)?;
+
+ 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<<E2 as Engine>::Scalar>, _>>()?;
+
+ self.l_u_secondary = l_u_secondary;
+ self.l_w_secondary = l_w_secondary;
+
+ self.i += 1;
+
+ Ok(())
+ }
+
+ pub fn verify(
+ &self,
+ pp: &PublicParams<E1, E2, C1, C2>,
+ num_steps: usize,
+ z0_primary: &[E1::Scalar],
+ z0_secondary: &[E2::Scalar],
+ ) -> Result<(Vec<E1::Scalar>, Vec<E2::Scalar>), NovaError> {
+ let is_num_steps_zero = num_steps == 0;
+
+ let is_num_steps_not_match = self.i != num_steps;
+
+ let is_inputs_not_match = self.z0_primary != z0_primary || self.z0_secondary != z0_secondary;
+
+ let is_instance_has_two_outpus = 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_outpus
+ {
+ return Err(NovaError::ProofVerifyError);
+ }
+
+ let (hash_primary, hash_secondary) = {
+ let mut hasher = <E2 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(E2::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::<E2>(self.l_u_secondary.X[1])
+ {
+ return Err(NovaError::ProofVerifyError);
+ }
+
+ 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,
+ )
+ },
+ )
+ },
+ );
+
+ res_r_primary?;
+ res_r_secondary?;
+ res_l_secondary?;
+
+ Ok((self.zi_primary.clone(), self.zi_secondary.clone()))
+ }
+
+ pub fn outputs(&self) -> (&[E1::Scalar], &[E2::Scalar]) {
+ (&self.zi_primary, &self.zi_secondary)
+ }
+
+ pub fn num_steps(&self) -> usize {
+ self.i
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, Abomonation)]
+#[serde(bound = "")]
+#[abomonation_omit_bounds]
+pub struct ProverKey<E1, E2, C1, C2, S1, S2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+ S1: RelaxedR1CSSNARKTrait<E1>,
+ S2: RelaxedR1CSSNARKTrait<E2>,
+{
+ pk_primary: S1::ProverKey,
+ pk_secondary: S2::ProverKey,
+ _p: PhantomData<(C1, C2)>,
+}
+
+#[derive(Clone, Serialize, Deserialize, Abomonation)]
+#[serde(bound = "")]
+#[abomonation_bounds(
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+ S1: RelaxedR1CSSNARKTrait<E1>,
+ S2: RelaxedR1CSSNARKTrait<E2>,
+ <E1::Scalar as PrimeField>::Repr: Abomonation,
+ )]
+pub struct VerifierKey<E1, E2, C1, C2, S1, S2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+ S1: RelaxedR1CSSNARKTrait<E1>,
+ S2: RelaxedR1CSSNARKTrait<E2>,
+{
+ F_arity_primary: usize,
+ F_arity_secondary: usize,
+ ro_consts_primary: ROConstants<E1>,
+ ro_consts_secondary: ROConstants<E2>,
+ #[abomonate_with(<E1::Scalar as PrimeField>::Repr)]
+ pp_digest: E1::Scalar,
+ vk_primary: S1::VerifierKey,
+ vk_secondary: S2::VerifierKey,
+ _p: PhantomData<(C1, C2)>,
+}
+
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(bound = "")]
+pub struct CompressedSNARK<E1, E2, C1, C2, S1, S2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+ S1: RelaxedR1CSSNARKTrait<E1>,
+ S2: RelaxedR1CSSNARKTrait<E2>,
+{
+ r_U_primary: RelaxedR1CSInstance<E1>,
+ r_W_snark_primary: S1,
+
+ r_U_secondary: RelaxedR1CSInstance<E2>,
+ l_u_secondary: R1CSInstance<E2>,
+ nifs_secondary: NIFS<E2>,
+ f_W_snark_secondary: S2,
+
+ zn_primary: Vec<E1::Scalar>,
+ zn_secondary: Vec<E2::Scalar>,
+
+ _p: PhantomData<(C1, C2)>,
+}
+
+impl<E1, E2, C1, C2, S1, S2> CompressedSNARK<E1, E2, C1, C2, S1, S2>
+where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C1: StepCircuit<E1::Scalar>,
+ C2: StepCircuit<E2::Scalar>,
+ S1: RelaxedR1CSSNARKTrait<E1>,
+ S2: RelaxedR1CSSNARKTrait<E2>,
+{
+ pub fn setup(
+ pp: &PublicParams<E1, E2, C1, C2>,
+ ) -> Result<
+ (
+ ProverKey<E1, E2, C1, C2, S1, S2>,
+ VerifierKey<E1, E2, C1, C2, S1, S2>,
+ ),
+ NovaError,
+ > {
+ let (pk_primary, vk_primary) = S1::setup(&pp.ck_primary, &pp.circuit_shape_primary.r1cs_shape)?;
+ let (pk_secondary, vk_secondary) =
+ S2::setup(&pp.ck_secondary, &pp.circuit_shape_secondary.r1cs_shape)?;
+
+ let pk = ProverKey {
+ pk_primary,
+ pk_secondary,
+ _p: Default::default(),
+ };
+
+ 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,
+ _p: Default::default(),
+ };
+
+ Ok((pk, vk))
+ }
+
+ pub fn prove(
+ pp: &PublicParams<E1, E2, C1, C2>,
+ pk: &ProverKey<E1, E2, C1, C2, S1, S2>,
+ recursive_snark: &RecursiveSNARK<E1, E2, C1, C2>,
+ ) -> Result<Self, NovaError> {
+ 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,
+ )?;
+
+ 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(),
+
+ _p: Default::default(),
+ })
+ }
+
+ pub fn verify(
+ &self,
+ vk: &VerifierKey<E1, E2, C1, C2, S1, S2>,
+ num_steps: usize,
+ z0_primary: &[E1::Scalar],
+ z0_secondary: &[E2::Scalar],
+ ) -> Result<(Vec<E1::Scalar>, Vec<E2::Scalar>), NovaError> {
+ if num_steps == 0 {
+ return Err(NovaError::ProofVerifyError);
+ }
+
+ 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);
+ }
+
+ let (hash_primary, hash_secondary) = {
+ let mut hasher = <E2 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(E2::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::<E2>(self.l_u_secondary.X[1])
+ {
+ return Err(NovaError::ProofVerifyError);
+ }
+
+ 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,
+ )?;
+
+ 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()))
+ }
+}
+
+pub fn circuit_digest<
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ C: StepCircuit<E1::Scalar>,
+>(
+ circuit: &C,
+) -> E1::Scalar {
+ let augmented_circuit_params = NovaAugmentedCircuitParams::new(BN_LIMB_WIDTH, BN_N_LIMBS, true);
+
+ let ro_consts_circuit: ROConstantsCircuit<E2> = ROConstantsCircuit::<E2>::default();
+
+ let augmented_circuit: NovaAugmentedCircuit<'_, E2, C> =
+ NovaAugmentedCircuit::new(&augmented_circuit_params, None, circuit, ro_consts_circuit);
+ let mut cs: ShapeCS<E1> = ShapeCS::new();
+ let _ = augmented_circuit.synthesize(&mut cs);
+ cs.r1cs_shape().digest()
+}
+
+type CommitmentKey<E> = <<E as Engine>::CE as CommitmentEngineTrait<E>>::CommitmentKey;
+type Commitment<E> = <<E as Engine>::CE as CommitmentEngineTrait<E>>::Commitment;
+type CompressedCommitment<E> = <<<E as Engine>::CE as CommitmentEngineTrait<E>>::Commitment as CommitmentTrait<E>>::CompressedCommitment;
+type CE<E> = <E as Engine>::CE;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{
+ provider::{
+ non_hiding_zeromorph::ZMPCS, traits::DlogGroup, Bn256Engine, Bn256EngineKZG, Bn256EngineZM,
+ GrumpkinEngine, PallasEngine, Secp256k1Engine, Secq256k1Engine, VestaEngine,
+ },
+ traits::{evaluation::EvaluationEngineTrait, snark::default_ck_hint},
+ };
+ use ::bellpepper_core::{num::AllocatedNum, ConstraintSystem, SynthesisError};
+ use core::{fmt::Write, marker::PhantomData};
+ use expect_test::{expect, Expect};
+ use ff::PrimeField;
+ use halo2curves::bn256::Bn256;
+ use traits::circuit::TrivialCircuit;
+
+ type EE<E> = provider::ipa_pc::EvaluationEngine<E>;
+ type S<E, EE> = spartan::snark::RelaxedR1CSSNARK<E, EE>;
+ type SPrime<E, EE> = spartan::ppsnark::RelaxedR1CSSNARK<E, EE>;
+
+ #[derive(Clone, Debug, Default)]
+ struct CubicCircuit<F> {
+ _p: PhantomData<F>,
+ }
+
+ impl<F: PrimeField> StepCircuit<F> for CubicCircuit<F> {
+ fn arity(&self) -> usize {
+ 1
+ }
+
+ fn synthesize<CS: ConstraintSystem<F>>(
+ &self,
+ cs: &mut CS,
+ z: &[AllocatedNum<F>],
+ ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
+ let x = &z[0];
+ let x_sq = x.square(cs.namespace(|| "x_sq"))?;
+ let x_cu = x_sq.mul(cs.namespace(|| "x_cu"), x)?;
+ let y = AllocatedNum::alloc(cs.namespace(|| "y"), || {
+ Ok(x_cu.get_value().unwrap() + x.get_value().unwrap() + F::from(5u64))
+ })?;
+
+ cs.enforce(
+ || "y = x^3 + x + 5",
+ |lc| {
+ lc + x_cu.get_variable()
+ + x.get_variable()
+ + CS::one()
+ + CS::one()
+ + CS::one()
+ + CS::one()
+ + CS::one()
+ },
+ |lc| lc + CS::one(),
+ |lc| lc + y.get_variable(),
+ );
+
+ Ok(vec![y])
+ }
+ }
+
+ impl<F: PrimeField> CubicCircuit<F> {
+ fn output(&self, z: &[F]) -> Vec<F> {
+ vec![z[0] * z[0] * z[0] + z[0] + F::from(5u64)]
+ }
+ }
+
+ fn test_pp_digest_with<E1, E2, T1, T2, EE1, EE2>(circuit1: &T1, circuit2: &T2, expected: &Expect)
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ E1::GE: DlogGroup,
+ E2::GE: DlogGroup,
+ T1: StepCircuit<E1::Scalar>,
+ T2: StepCircuit<E2::Scalar>,
+ EE1: EvaluationEngineTrait<E1>,
+ EE2: EvaluationEngineTrait<E2>,
+ <E1::Scalar as PrimeField>::Repr: Abomonation,
+ <E2::Scalar as PrimeField>::Repr: Abomonation,
+ {
+ let ck_hint1 = &*SPrime::<E1, EE1>::ck_floor();
+ let ck_hint2 = &*SPrime::<E2, EE2>::ck_floor();
+ let pp = PublicParams::<E1, E2, T1, T2>::setup(circuit1, circuit2, ck_hint1, ck_hint2);
+
+ let digest_str = pp
+ .digest()
+ .to_repr()
+ .as_ref()
+ .iter()
+ .fold(String::new(), |mut output, b| {
+ let _ = write!(output, "{b:02x}");
+ output
+ });
+
+ expected.assert_eq(&digest_str);
+ }
+
+ #[test]
+ fn test_pp_digest() {
+ let trivial_circuit1 = TrivialCircuit::<<PallasEngine as Engine>::Scalar>::default();
+ let trivial_circuit2 = TrivialCircuit::<<VestaEngine as Engine>::Scalar>::default();
+ let cubic_circuit1 = CubicCircuit::<<PallasEngine as Engine>::Scalar>::default();
+
+ test_pp_digest_with::<PallasEngine, VestaEngine, _, _, EE<_>, EE<_>>(
+ &trivial_circuit1,
+ &trivial_circuit2,
+ &expect!["f4a04841515b4721519e2671b7ee11e58e2d4a30bb183ded963b71ad2ec80d00"],
+ );
+
+ test_pp_digest_with::<PallasEngine, VestaEngine, _, _, EE<_>, EE<_>>(
+ &cubic_circuit1,
+ &trivial_circuit2,
+ &expect!["dc1b7c40ab50c5c6877ad027769452870cc28f1d13f140de7ca3a00138c58502"],
+ );
+
+ let trivial_circuit1_grumpkin = TrivialCircuit::<<Bn256Engine as Engine>::Scalar>::default();
+ let trivial_circuit2_grumpkin = TrivialCircuit::<<GrumpkinEngine as Engine>::Scalar>::default();
+ let cubic_circuit1_grumpkin = CubicCircuit::<<Bn256Engine as Engine>::Scalar>::default();
+
+ test_pp_digest_with::<Bn256Engine, GrumpkinEngine, _, _, EE<_>, EE<_>>(
+ &trivial_circuit1_grumpkin,
+ &trivial_circuit2_grumpkin,
+ &expect!["2af2a80ea8a0c21cfc4096e9b2d4822344a29174d88cd86239a99a363efe8702"],
+ );
+ test_pp_digest_with::<Bn256Engine, GrumpkinEngine, _, _, EE<_>, EE<_>>(
+ &cubic_circuit1_grumpkin,
+ &trivial_circuit2_grumpkin,
+ &expect!["9273fd39ed6220ea28e60abca8bdb3180f90e37e6aaf3031e6d670d073e8a002"],
+ );
+ test_pp_digest_with::<Bn256EngineZM, GrumpkinEngine, _, _, ZMPCS<Bn256, _>, EE<_>>(
+ &trivial_circuit1_grumpkin,
+ &trivial_circuit2_grumpkin,
+ &expect!["eac63861dcbaa924a1bd9721f01528271385dd6ff182c77bc62e03448adc1902"],
+ );
+ test_pp_digest_with::<Bn256EngineZM, GrumpkinEngine, _, _, ZMPCS<Bn256, _>, EE<_>>(
+ &cubic_circuit1_grumpkin,
+ &trivial_circuit2_grumpkin,
+ &expect!["21bd7e07175b23e3bd2bbc6a0c3b9efd8603815609dbe93f8df9c174e132de03"],
+ );
+
+ let trivial_circuit1_secp = TrivialCircuit::<<Secp256k1Engine as Engine>::Scalar>::default();
+ let trivial_circuit2_secp = TrivialCircuit::<<Secq256k1Engine as Engine>::Scalar>::default();
+ let cubic_circuit1_secp = CubicCircuit::<<Secp256k1Engine as Engine>::Scalar>::default();
+
+ test_pp_digest_with::<Secp256k1Engine, Secq256k1Engine, _, _, EE<_>, EE<_>>(
+ &trivial_circuit1_secp,
+ &trivial_circuit2_secp,
+ &expect!["7652ef8326b01e784eaac7b44bd0bc2f27af3904c96ef2bf7ab1b923b8aae701"],
+ );
+ test_pp_digest_with::<Secp256k1Engine, Secq256k1Engine, _, _, EE<_>, EE<_>>(
+ &cubic_circuit1_secp,
+ &trivial_circuit2_secp,
+ &expect!["da51e6bac881c054c4ed08320ce42d8a0e61a22fbd70bbbbf05384ec4adeb201"],
+ );
+ }
+
+ fn test_ivc_trivial_with<E1, E2>()
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ {
+ let test_circuit1 = TrivialCircuit::<<E1 as Engine>::Scalar>::default();
+ let test_circuit2 = TrivialCircuit::<<E2 as Engine>::Scalar>::default();
+
+ let pp = PublicParams::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ TrivialCircuit<<E2 as Engine>::Scalar>,
+ >::setup(
+ &test_circuit1,
+ &test_circuit2,
+ &*default_ck_hint(),
+ &*default_ck_hint(),
+ );
+ let num_steps = 1;
+
+ let mut recursive_snark = RecursiveSNARK::new(
+ &pp,
+ &test_circuit1,
+ &test_circuit2,
+ &[<E1 as Engine>::Scalar::ZERO],
+ &[<E2 as Engine>::Scalar::ZERO],
+ )
+ .unwrap();
+
+ let res = recursive_snark.prove_step(&pp, &test_circuit1, &test_circuit2);
+
+ assert!(res.is_ok());
+
+ let res = recursive_snark.verify(
+ &pp,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ZERO],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+ }
+
+ #[test]
+ fn test_ivc_trivial() {
+ test_ivc_trivial_with::<PallasEngine, VestaEngine>();
+ test_ivc_trivial_with::<Bn256Engine, GrumpkinEngine>();
+ test_ivc_trivial_with::<Secp256k1Engine, Secq256k1Engine>();
+ }
+
+ fn test_ivc_nontrivial_with<E1, E2>()
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ {
+ let circuit_primary = TrivialCircuit::default();
+ let circuit_secondary = CubicCircuit::default();
+
+ let pp = PublicParams::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::setup(
+ &circuit_primary,
+ &circuit_secondary,
+ &*default_ck_hint(),
+ &*default_ck_hint(),
+ );
+
+ let num_steps = 3;
+
+ let mut recursive_snark = RecursiveSNARK::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::new(
+ &pp,
+ &circuit_primary,
+ &circuit_secondary,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ )
+ .unwrap();
+
+ for i in 0..num_steps {
+ let res = recursive_snark.prove_step(&pp, &circuit_primary, &circuit_secondary);
+ assert!(res.is_ok());
+
+ let res = recursive_snark.verify(
+ &pp,
+ i + 1,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+ }
+
+ let res = recursive_snark.verify(
+ &pp,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+
+ let (zn_primary, zn_secondary) = res.unwrap();
+
+ assert_eq!(zn_primary, vec![<E1 as Engine>::Scalar::ONE]);
+ let mut zn_secondary_direct = vec![<E2 as Engine>::Scalar::ZERO];
+ for _i in 0..num_steps {
+ zn_secondary_direct = circuit_secondary.clone().output(&zn_secondary_direct);
+ }
+ assert_eq!(zn_secondary, zn_secondary_direct);
+ assert_eq!(zn_secondary, vec![<E2 as Engine>::Scalar::from(2460515u64)]);
+ }
+
+ #[test]
+ fn test_ivc_nontrivial() {
+ test_ivc_nontrivial_with::<PallasEngine, VestaEngine>();
+ test_ivc_nontrivial_with::<Bn256Engine, GrumpkinEngine>();
+ test_ivc_nontrivial_with::<Secp256k1Engine, Secq256k1Engine>();
+ }
+
+ fn test_ivc_nontrivial_with_compression_with<E1, E2, EE1, EE2>()
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ EE1: EvaluationEngineTrait<E1>,
+ EE2: EvaluationEngineTrait<E2>,
+ <E1::Scalar as PrimeField>::Repr: Abomonation,
+ <E2::Scalar as PrimeField>::Repr: Abomonation,
+ {
+ let circuit_primary = TrivialCircuit::default();
+ let circuit_secondary = CubicCircuit::default();
+
+ let pp = PublicParams::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::setup(
+ &circuit_primary,
+ &circuit_secondary,
+ &*default_ck_hint(),
+ &*default_ck_hint(),
+ );
+
+ let num_steps = 3;
+
+ let mut recursive_snark = RecursiveSNARK::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::new(
+ &pp,
+ &circuit_primary,
+ &circuit_secondary,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ )
+ .unwrap();
+
+ for _i in 0..num_steps {
+ let res = recursive_snark.prove_step(&pp, &circuit_primary, &circuit_secondary);
+ assert!(res.is_ok());
+ }
+
+ let res = recursive_snark.verify(
+ &pp,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+
+ let (zn_primary, zn_secondary) = res.unwrap();
+
+ assert_eq!(zn_primary, vec![<E1 as Engine>::Scalar::ONE]);
+ let mut zn_secondary_direct = vec![<E2 as Engine>::Scalar::ZERO];
+ for _i in 0..num_steps {
+ zn_secondary_direct = circuit_secondary.clone().output(&zn_secondary_direct);
+ }
+ assert_eq!(zn_secondary, zn_secondary_direct);
+ assert_eq!(zn_secondary, vec![<E2 as Engine>::Scalar::from(2460515u64)]);
+
+ let (pk, vk) = CompressedSNARK::<_, _, _, _, S<E1, EE1>, S<E2, EE2>>::setup(&pp).unwrap();
+
+ let res =
+ CompressedSNARK::<_, _, _, _, S<E1, EE1>, S<E2, EE2>>::prove(&pp, &pk, &recursive_snark);
+ assert!(res.is_ok());
+ let compressed_snark = res.unwrap();
+
+ let res = compressed_snark.verify(
+ &vk,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+ }
+
+ #[test]
+ fn test_ivc_nontrivial_with_compression() {
+ test_ivc_nontrivial_with_compression_with::<PallasEngine, VestaEngine, EE<_>, EE<_>>();
+ test_ivc_nontrivial_with_compression_with::<Bn256Engine, GrumpkinEngine, EE<_>, EE<_>>();
+ test_ivc_nontrivial_with_compression_with::<Secp256k1Engine, Secq256k1Engine, EE<_>, EE<_>>();
+ test_ivc_nontrivial_with_compression_with::<
+ Bn256EngineZM,
+ GrumpkinEngine,
+ ZMPCS<Bn256, _>,
+ EE<_>,
+ >();
+
+ test_ivc_nontrivial_with_spark_compression_with::<
+ Bn256EngineKZG,
+ GrumpkinEngine,
+ provider::mlkzg::EvaluationEngine<Bn256, _>,
+ EE<_>,
+ >();
+ }
+
+ fn test_ivc_nontrivial_with_spark_compression_with<E1, E2, EE1, EE2>()
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ EE1: EvaluationEngineTrait<E1>,
+ EE2: EvaluationEngineTrait<E2>,
+ <E1::Scalar as PrimeField>::Repr: Abomonation,
+ <E2::Scalar as PrimeField>::Repr: Abomonation,
+ {
+ let circuit_primary = TrivialCircuit::default();
+ let circuit_secondary = CubicCircuit::default();
+
+ let pp = PublicParams::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::setup(
+ &circuit_primary,
+ &circuit_secondary,
+ &*SPrime::<E1, EE1>::ck_floor(),
+ &*SPrime::<E2, EE2>::ck_floor(),
+ );
+
+ let num_steps = 3;
+
+ let mut recursive_snark = RecursiveSNARK::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::new(
+ &pp,
+ &circuit_primary,
+ &circuit_secondary,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ )
+ .unwrap();
+
+ for _i in 0..num_steps {
+ let res = recursive_snark.prove_step(&pp, &circuit_primary, &circuit_secondary);
+ assert!(res.is_ok());
+ }
+
+ let res = recursive_snark.verify(
+ &pp,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+
+ let (zn_primary, zn_secondary) = res.unwrap();
+
+ assert_eq!(zn_primary, vec![<E1 as Engine>::Scalar::ONE]);
+ let mut zn_secondary_direct = vec![<E2 as Engine>::Scalar::ZERO];
+ for _i in 0..num_steps {
+ zn_secondary_direct = CubicCircuit::default().output(&zn_secondary_direct);
+ }
+ assert_eq!(zn_secondary, zn_secondary_direct);
+ assert_eq!(zn_secondary, vec![<E2 as Engine>::Scalar::from(2460515u64)]);
+
+ let (pk, vk) =
+ CompressedSNARK::<_, _, _, _, SPrime<E1, EE1>, SPrime<E2, EE2>>::setup(&pp).unwrap();
+
+ let res = CompressedSNARK::<_, _, _, _, SPrime<E1, EE1>, SPrime<E2, EE2>>::prove(
+ &pp,
+ &pk,
+ &recursive_snark,
+ );
+ assert!(res.is_ok());
+ let compressed_snark = res.unwrap();
+
+ let res = compressed_snark.verify(
+ &vk,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+ }
+
+ #[test]
+ fn test_ivc_nontrivial_with_spark_compression() {
+ test_ivc_nontrivial_with_spark_compression_with::<PallasEngine, VestaEngine, EE<_>, EE<_>>();
+ test_ivc_nontrivial_with_spark_compression_with::<Bn256Engine, GrumpkinEngine, EE<_>, EE<_>>();
+ test_ivc_nontrivial_with_spark_compression_with::<Secp256k1Engine, Secq256k1Engine, EE<_>, EE<_>>(
+ );
+ test_ivc_nontrivial_with_spark_compression_with::<
+ Bn256EngineZM,
+ GrumpkinEngine,
+ ZMPCS<Bn256, _>,
+ EE<_>,
+ >();
+ }
+
+ fn test_ivc_nondet_with_compression_with<E1, E2, EE1, EE2>()
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ EE1: EvaluationEngineTrait<E1>,
+ EE2: EvaluationEngineTrait<E2>,
+ <E1::Scalar as PrimeField>::Repr: Abomonation,
+ <E2::Scalar as PrimeField>::Repr: Abomonation,
+ {
+ #[derive(Clone, Debug)]
+ struct FifthRootCheckingCircuit<F> {
+ y: F,
+ }
+
+ impl<F: PrimeField> FifthRootCheckingCircuit<F> {
+ fn new(num_steps: usize) -> (Vec<F>, Vec<Self>) {
+ let mut powers = Vec::new();
+ let rng = &mut rand::rngs::OsRng;
+ let mut seed = F::random(rng);
+ for _i in 0..num_steps + 1 {
+ seed *= seed.clone().square().square();
+
+ powers.push(Self { y: seed });
+ }
+
+ let roots = powers.into_iter().rev().collect::<Vec<Self>>();
+ (vec![roots[0].y], roots[1..].to_vec())
+ }
+ }
+
+ impl<F> StepCircuit<F> for FifthRootCheckingCircuit<F>
+ where
+ F: PrimeField,
+ {
+ fn arity(&self) -> usize {
+ 1
+ }
+
+ fn synthesize<CS: ConstraintSystem<F>>(
+ &self,
+ cs: &mut CS,
+ z: &[AllocatedNum<F>],
+ ) -> Result<Vec<AllocatedNum<F>>, SynthesisError> {
+ let x = &z[0];
+
+ let y = AllocatedNum::alloc_infallible(cs.namespace(|| "y"), || self.y);
+
+ let y_sq = y.square(cs.namespace(|| "y_sq"))?;
+ let y_quad = y_sq.square(cs.namespace(|| "y_quad"))?;
+ let y_pow_5 = y_quad.mul(cs.namespace(|| "y_fifth"), &y)?;
+
+ cs.enforce(
+ || "y^5 = x",
+ |lc| lc + y_pow_5.get_variable(),
+ |lc| lc + CS::one(),
+ |lc| lc + x.get_variable(),
+ );
+
+ Ok(vec![y])
+ }
+ }
+
+ let circuit_primary = FifthRootCheckingCircuit {
+ y: <E1 as Engine>::Scalar::ZERO,
+ };
+
+ let circuit_secondary = TrivialCircuit::default();
+
+ let pp = PublicParams::<
+ E1,
+ E2,
+ FifthRootCheckingCircuit<<E1 as Engine>::Scalar>,
+ TrivialCircuit<<E2 as Engine>::Scalar>,
+ >::setup(
+ &circuit_primary,
+ &circuit_secondary,
+ &*default_ck_hint(),
+ &*default_ck_hint(),
+ );
+
+ let num_steps = 3;
+
+ let (z0_primary, roots) = FifthRootCheckingCircuit::new(num_steps);
+ let z0_secondary = vec![<E2 as Engine>::Scalar::ZERO];
+
+ let mut recursive_snark: RecursiveSNARK<
+ E1,
+ E2,
+ FifthRootCheckingCircuit<<E1 as Engine>::Scalar>,
+ TrivialCircuit<<E2 as Engine>::Scalar>,
+ > = RecursiveSNARK::<
+ E1,
+ E2,
+ FifthRootCheckingCircuit<<E1 as Engine>::Scalar>,
+ TrivialCircuit<<E2 as Engine>::Scalar>,
+ >::new(
+ &pp,
+ &roots[0],
+ &circuit_secondary,
+ &z0_primary,
+ &z0_secondary,
+ )
+ .unwrap();
+
+ for circuit_primary in roots.iter().take(num_steps) {
+ let res = recursive_snark.prove_step(&pp, circuit_primary, &circuit_secondary);
+ assert!(res.is_ok());
+ }
+
+ let res = recursive_snark.verify(&pp, num_steps, &z0_primary, &z0_secondary);
+ assert!(res.is_ok());
+
+ let (pk, vk) = CompressedSNARK::<_, _, _, _, S<E1, EE1>, S<E2, EE2>>::setup(&pp).unwrap();
+
+ let res =
+ CompressedSNARK::<_, _, _, _, S<E1, EE1>, S<E2, EE2>>::prove(&pp, &pk, &recursive_snark);
+ assert!(res.is_ok());
+ let compressed_snark = res.unwrap();
+
+ let res = compressed_snark.verify(&vk, num_steps, &z0_primary, &z0_secondary);
+ assert!(res.is_ok());
+ }
+
+ #[test]
+ fn test_ivc_nondet_with_compression() {
+ test_ivc_nondet_with_compression_with::<PallasEngine, VestaEngine, EE<_>, EE<_>>();
+ test_ivc_nondet_with_compression_with::<Bn256Engine, GrumpkinEngine, EE<_>, EE<_>>();
+ test_ivc_nondet_with_compression_with::<Secp256k1Engine, Secq256k1Engine, EE<_>, EE<_>>();
+ test_ivc_nondet_with_compression_with::<Bn256EngineZM, GrumpkinEngine, ZMPCS<Bn256, _>, EE<_>>(
+ );
+ }
+
+ fn test_ivc_base_with<E1, E2>()
+ where
+ E1: Engine<Base = <E2 as Engine>::Scalar>,
+ E2: Engine<Base = <E1 as Engine>::Scalar>,
+ {
+ let test_circuit1 = TrivialCircuit::<<E1 as Engine>::Scalar>::default();
+ let test_circuit2 = CubicCircuit::<<E2 as Engine>::Scalar>::default();
+
+ let pp = PublicParams::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::setup(
+ &test_circuit1,
+ &test_circuit2,
+ &*default_ck_hint(),
+ &*default_ck_hint(),
+ );
+
+ let num_steps = 1;
+
+ let mut recursive_snark = RecursiveSNARK::<
+ E1,
+ E2,
+ TrivialCircuit<<E1 as Engine>::Scalar>,
+ CubicCircuit<<E2 as Engine>::Scalar>,
+ >::new(
+ &pp,
+ &test_circuit1,
+ &test_circuit2,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ )
+ .unwrap();
+
+ let res = recursive_snark.prove_step(&pp, &test_circuit1, &test_circuit2);
+
+ assert!(res.is_ok());
+
+ let res = recursive_snark.verify(
+ &pp,
+ num_steps,
+ &[<E1 as Engine>::Scalar::ONE],
+ &[<E2 as Engine>::Scalar::ZERO],
+ );
+ assert!(res.is_ok());
+
+ let (zn_primary, zn_secondary) = res.unwrap();
+
+ assert_eq!(zn_primary, vec![<E1 as Engine>::Scalar::ONE]);
+ assert_eq!(zn_secondary, vec![<E2 as Engine>::Scalar::from(5u64)]);
+ }
+
+ #[test]
+ fn test_ivc_base() {
+ test_ivc_base_with::<PallasEngine, VestaEngine>();
+ test_ivc_base_with::<Bn256Engine, GrumpkinEngine>();
+ test_ivc_base_with::<Secp256k1Engine, Secq256k1Engine>();
+ }
+}
+