arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/folding-schemes/src/folding/nova/decider_eth_circuit.rs
folding-schemes/src/folding/nova/decider_eth_circuit.rsRaw
  1/// This file implements the onchain (Ethereum's EVM) decider circuit. For non-ethereum use cases,
  2/// other more efficient approaches can be used.
  3/// More details can be found at the documentation page:
  4/// https://privacy-scaling-explorations.github.io/sonobe-docs/design/nova-decider-onchain.html
  5use ark_crypto_primitives::sponge::{
  6    constraints::CryptographicSpongeVar,
  7    poseidon::{constraints::PoseidonSpongeVar, PoseidonConfig, PoseidonSponge},
  8    Absorb, CryptographicSponge,
  9};
 10use ark_ec::{CurveGroup, Group};
 11use ark_ff::{BigInteger, PrimeField};
 12use ark_poly::Polynomial;
 13use ark_r1cs_std::{
 14    alloc::{AllocVar, AllocationMode},
 15    boolean::Boolean,
 16    eq::EqGadget,
 17    fields::{fp::FpVar, FieldVar},
 18    groups::GroupOpsBounds,
 19    poly::{domain::Radix2DomainVar, evaluations::univariate::EvaluationsVar},
 20    prelude::CurveVar,
 21    ToConstraintFieldGadget,
 22};
 23use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, Namespace, SynthesisError};
 24use ark_std::{log2, Zero};
 25use core::{borrow::Borrow, marker::PhantomData};
 26
 27use super::{
 28    circuits::{ChallengeGadget, CommittedInstanceVar},
 29    nifs::{nova::NIFS, NIFSTrait},
 30    CommittedInstance, Nova, Witness,
 31};
 32use crate::commitment::{pedersen::Params as PedersenParams, CommitmentScheme};
 33use crate::folding::circuits::{
 34    cyclefold::{CycleFoldCommittedInstance, CycleFoldWitness},
 35    nonnative::{affine::NonNativeAffineVar, uint::NonNativeUintVar},
 36    CF1, CF2,
 37};
 38use crate::frontend::FCircuit;
 39use crate::transcript::{Transcript, TranscriptVar};
 40use crate::utils::{
 41    gadgets::{MatrixGadget, SparseMatrixVar, VectorGadget},
 42    vec::poly_from_vec,
 43};
 44use crate::Error;
 45use crate::{
 46    arith::r1cs::R1CS,
 47    folding::traits::{CommittedInstanceVarOps, Dummy, WitnessVarOps},
 48};
 49
 50#[derive(Debug, Clone)]
 51pub struct RelaxedR1CSGadget {}
 52impl RelaxedR1CSGadget {
 53    /// performs the RelaxedR1CS check for native variables (Az∘Bz==uCz+E)
 54    pub fn check_native<F: PrimeField>(
 55        r1cs: R1CSVar<F, F, FpVar<F>>,
 56        E: Vec<FpVar<F>>,
 57        u: FpVar<F>,
 58        z: Vec<FpVar<F>>,
 59    ) -> Result<(), SynthesisError> {
 60        let Az = r1cs.A.mul_vector(&z)?;
 61        let Bz = r1cs.B.mul_vector(&z)?;
 62        let Cz = r1cs.C.mul_vector(&z)?;
 63        let uCzE = Cz.mul_scalar(&u)?.add(&E)?;
 64        let AzBz = Az.hadamard(&Bz)?;
 65        AzBz.enforce_equal(&uCzE)?;
 66        Ok(())
 67    }
 68
 69    /// performs the RelaxedR1CS check for non-native variables (Az∘Bz==uCz+E)
 70    pub fn check_nonnative<F: PrimeField, CF: PrimeField>(
 71        r1cs: R1CSVar<F, CF, NonNativeUintVar<CF>>,
 72        E: Vec<NonNativeUintVar<CF>>,
 73        u: NonNativeUintVar<CF>,
 74        z: Vec<NonNativeUintVar<CF>>,
 75    ) -> Result<(), SynthesisError> {
 76        // First we do addition and multiplication without mod F's order
 77        let Az = r1cs.A.mul_vector(&z)?;
 78        let Bz = r1cs.B.mul_vector(&z)?;
 79        let Cz = r1cs.C.mul_vector(&z)?;
 80        let uCzE = Cz.mul_scalar(&u)?.add(&E)?;
 81        let AzBz = Az.hadamard(&Bz)?;
 82
 83        // Then we compare the results by checking if they are congruent
 84        // modulo the field order
 85        AzBz.into_iter()
 86            .zip(uCzE)
 87            .try_for_each(|(a, b)| a.enforce_congruent::<F>(&b))
 88    }
 89}
 90
 91#[derive(Debug, Clone)]
 92pub struct R1CSVar<F: PrimeField, CF: PrimeField, FV: AllocVar<F, CF>> {
 93    _f: PhantomData<F>,
 94    _cf: PhantomData<CF>,
 95    _fv: PhantomData<FV>,
 96    pub A: SparseMatrixVar<F, CF, FV>,
 97    pub B: SparseMatrixVar<F, CF, FV>,
 98    pub C: SparseMatrixVar<F, CF, FV>,
 99}
100
101impl<F, CF, FV> AllocVar<R1CS<F>, CF> for R1CSVar<F, CF, FV>
102where
103    F: PrimeField,
104    CF: PrimeField,
105    FV: AllocVar<F, CF>,
106{
107    fn new_variable<T: Borrow<R1CS<F>>>(
108        cs: impl Into<Namespace<CF>>,
109        f: impl FnOnce() -> Result<T, SynthesisError>,
110        _mode: AllocationMode,
111    ) -> Result<Self, SynthesisError> {
112        f().and_then(|val| {
113            let cs = cs.into();
114
115            let A = SparseMatrixVar::<F, CF, FV>::new_constant(cs.clone(), &val.borrow().A)?;
116            let B = SparseMatrixVar::<F, CF, FV>::new_constant(cs.clone(), &val.borrow().B)?;
117            let C = SparseMatrixVar::<F, CF, FV>::new_constant(cs.clone(), &val.borrow().C)?;
118
119            Ok(Self {
120                _f: PhantomData,
121                _cf: PhantomData,
122                _fv: PhantomData,
123                A,
124                B,
125                C,
126            })
127        })
128    }
129}
130
131/// In-circuit representation of the Witness associated to the CommittedInstance.
132#[derive(Debug, Clone)]
133pub struct WitnessVar<C: CurveGroup> {
134    pub E: Vec<FpVar<C::ScalarField>>,
135    pub rE: FpVar<C::ScalarField>,
136    pub W: Vec<FpVar<C::ScalarField>>,
137    pub rW: FpVar<C::ScalarField>,
138}
139
140impl<C> AllocVar<Witness<C>, CF1<C>> for WitnessVar<C>
141where
142    C: CurveGroup,
143{
144    fn new_variable<T: Borrow<Witness<C>>>(
145        cs: impl Into<Namespace<CF1<C>>>,
146        f: impl FnOnce() -> Result<T, SynthesisError>,
147        mode: AllocationMode,
148    ) -> Result<Self, SynthesisError> {
149        f().and_then(|val| {
150            let cs = cs.into();
151
152            let E: Vec<FpVar<C::ScalarField>> =
153                Vec::new_variable(cs.clone(), || Ok(val.borrow().E.clone()), mode)?;
154            let rE =
155                FpVar::<C::ScalarField>::new_variable(cs.clone(), || Ok(val.borrow().rE), mode)?;
156
157            let W: Vec<FpVar<C::ScalarField>> =
158                Vec::new_variable(cs.clone(), || Ok(val.borrow().W.clone()), mode)?;
159            let rW =
160                FpVar::<C::ScalarField>::new_variable(cs.clone(), || Ok(val.borrow().rW), mode)?;
161
162            Ok(Self { E, rE, W, rW })
163        })
164    }
165}
166
167impl<C: CurveGroup> WitnessVarOps<C::ScalarField> for WitnessVar<C> {
168    fn get_openings(&self) -> Vec<(&[FpVar<C::ScalarField>], FpVar<C::ScalarField>)> {
169        vec![(&self.E, self.rE.clone()), (&self.W, self.rW.clone())]
170    }
171}
172
173/// Circuit that implements the in-circuit checks needed for the onchain (Ethereum's EVM)
174/// verification.
175#[derive(Clone, Debug)]
176pub struct DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2, const H: bool = false>
177where
178    C1: CurveGroup,
179    GC1: CurveVar<C1, CF2<C1>>,
180    C2: CurveGroup,
181    GC2: CurveVar<C2, CF2<C2>>,
182    CS1: CommitmentScheme<C1, H>,
183    CS2: CommitmentScheme<C2, H>,
184{
185    _c1: PhantomData<C1>,
186    _gc1: PhantomData<GC1>,
187    _c2: PhantomData<C2>,
188    _gc2: PhantomData<GC2>,
189    _cs1: PhantomData<CS1>,
190    _cs2: PhantomData<CS2>,
191
192    /// E vector's length of the Nova instance witness
193    pub E_len: usize,
194    /// E vector's length of the CycleFold instance witness
195    pub cf_E_len: usize,
196    /// R1CS of the Augmented Function circuit
197    pub r1cs: R1CS<C1::ScalarField>,
198    /// R1CS of the CycleFold circuit
199    pub cf_r1cs: R1CS<C2::ScalarField>,
200    /// CycleFold PedersenParams over C2
201    pub cf_pedersen_params: PedersenParams<C2>,
202    pub poseidon_config: PoseidonConfig<CF1<C1>>,
203    /// public params hash
204    pub pp_hash: Option<C1::ScalarField>,
205    pub i: Option<CF1<C1>>,
206    /// initial state
207    pub z_0: Option<Vec<C1::ScalarField>>,
208    /// current i-th state
209    pub z_i: Option<Vec<C1::ScalarField>>,
210    /// Nova instances
211    pub u_i: Option<CommittedInstance<C1>>,
212    pub w_i: Option<Witness<C1>>,
213    pub U_i: Option<CommittedInstance<C1>>,
214    pub W_i: Option<Witness<C1>>,
215    pub U_i1: Option<CommittedInstance<C1>>,
216    pub W_i1: Option<Witness<C1>>,
217    pub cmT: Option<C1>,
218    pub r: Option<C1::ScalarField>,
219    /// CycleFold running instance
220    pub cf_U_i: Option<CycleFoldCommittedInstance<C2>>,
221    pub cf_W_i: Option<CycleFoldWitness<C2>>,
222
223    /// KZG challenges
224    pub kzg_c_W: Option<C1::ScalarField>,
225    pub kzg_c_E: Option<C1::ScalarField>,
226    pub eval_W: Option<C1::ScalarField>,
227    pub eval_E: Option<C1::ScalarField>,
228}
229impl<C1, GC1, C2, GC2, CS1, CS2, const H: bool> DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2, H>
230where
231    C1: CurveGroup,
232    C2: CurveGroup,
233    GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
234    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
235    CS1: CommitmentScheme<C1, H>,
236    // enforce that the CS2 is Pedersen commitment scheme, since we're at Ethereum's EVM decider
237    CS2: CommitmentScheme<C2, H, ProverParams = PedersenParams<C2>>,
238    <C1 as Group>::ScalarField: Absorb,
239    <C1 as CurveGroup>::BaseField: PrimeField,
240{
241    /// returns an instance of the DeciderEthCircuit from the given Nova struct
242    pub fn from_nova<FC: FCircuit<C1::ScalarField>>(
243        nova: Nova<C1, GC1, C2, GC2, FC, CS1, CS2, H>,
244    ) -> Result<Self, Error> {
245        let mut transcript = PoseidonSponge::<C1::ScalarField>::new(&nova.poseidon_config);
246
247        // compute the U_{i+1}, W_{i+1}
248        let (W_i1, U_i1, cmT, r_bits) = NIFS::<C1, CS1, PoseidonSponge<C1::ScalarField>, H>::prove(
249            &nova.cs_pp,
250            &nova.r1cs.clone(),
251            &mut transcript,
252            nova.pp_hash,
253            &nova.W_i,
254            &nova.U_i,
255            &nova.w_i,
256            &nova.u_i,
257        )?;
258        let r_Fr = C1::ScalarField::from_bigint(BigInteger::from_bits_le(&r_bits))
259            .ok_or(Error::OutOfBounds)?;
260
261        // compute the KZG challenges used as inputs in the circuit
262        let (kzg_challenge_W, kzg_challenge_E) =
263            KZGChallengesGadget::<C1>::get_challenges_native(&mut transcript, U_i1.clone());
264
265        // get KZG evals
266        let mut W = W_i1.W.clone();
267        W.extend(
268            std::iter::repeat(C1::ScalarField::zero())
269                .take(W_i1.W.len().next_power_of_two() - W_i1.W.len()),
270        );
271        let mut E = W_i1.E.clone();
272        E.extend(
273            std::iter::repeat(C1::ScalarField::zero())
274                .take(W_i1.E.len().next_power_of_two() - W_i1.E.len()),
275        );
276        let p_W = poly_from_vec(W.to_vec())?;
277        let eval_W = p_W.evaluate(&kzg_challenge_W);
278        let p_E = poly_from_vec(E.to_vec())?;
279        let eval_E = p_E.evaluate(&kzg_challenge_E);
280
281        Ok(Self {
282            _c1: PhantomData,
283            _gc1: PhantomData,
284            _c2: PhantomData,
285            _gc2: PhantomData,
286            _cs1: PhantomData,
287            _cs2: PhantomData,
288
289            E_len: nova.W_i.E.len(),
290            cf_E_len: nova.cf_W_i.E.len(),
291            r1cs: nova.r1cs,
292            cf_r1cs: nova.cf_r1cs,
293            cf_pedersen_params: nova.cf_cs_pp,
294            poseidon_config: nova.poseidon_config,
295            pp_hash: Some(nova.pp_hash),
296            i: Some(nova.i),
297            z_0: Some(nova.z_0),
298            z_i: Some(nova.z_i),
299            u_i: Some(nova.u_i),
300            w_i: Some(nova.w_i),
301            U_i: Some(nova.U_i),
302            W_i: Some(nova.W_i),
303            U_i1: Some(U_i1),
304            W_i1: Some(W_i1),
305            cmT: Some(cmT),
306            r: Some(r_Fr),
307            cf_U_i: Some(nova.cf_U_i),
308            cf_W_i: Some(nova.cf_W_i),
309            kzg_c_W: Some(kzg_challenge_W),
310            kzg_c_E: Some(kzg_challenge_E),
311            eval_W: Some(eval_W),
312            eval_E: Some(eval_E),
313        })
314    }
315}
316
317impl<C1, GC1, C2, GC2, CS1, CS2> ConstraintSynthesizer<CF1<C1>>
318    for DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
319where
320    C1: CurveGroup,
321    C2: CurveGroup,
322    GC1: CurveVar<C1, CF2<C1>>,
323    GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
324    CS1: CommitmentScheme<C1>,
325    CS2: CommitmentScheme<C2>,
326    <C1 as CurveGroup>::BaseField: PrimeField,
327    <C2 as CurveGroup>::BaseField: PrimeField,
328    <C1 as Group>::ScalarField: Absorb,
329    <C2 as Group>::ScalarField: Absorb,
330    C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
331    for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
332{
333    fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
334        let r1cs =
335            R1CSVar::<C1::ScalarField, CF1<C1>, FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
336                Ok(self.r1cs.clone())
337            })?;
338
339        let pp_hash = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
340            Ok(self.pp_hash.unwrap_or_else(CF1::<C1>::zero))
341        })?;
342        let i =
343            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.i.unwrap_or_else(CF1::<C1>::zero)))?;
344        let z_0 = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
345            Ok(self.z_0.unwrap_or(vec![CF1::<C1>::zero()]))
346        })?;
347        let z_i = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
348            Ok(self.z_i.unwrap_or(vec![CF1::<C1>::zero()]))
349        })?;
350
351        let u_dummy_native = CommittedInstance::<C1>::dummy(&self.r1cs);
352        let w_dummy_native = Witness::<C1>::dummy(&self.r1cs);
353
354        let u_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
355            Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
356        })?;
357        let U_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
358            Ok(self.U_i.unwrap_or(u_dummy_native.clone()))
359        })?;
360        // here (U_i1, W_i1) = NIFS.P( (U_i,W_i), (u_i,w_i))
361        let U_i1 = CommittedInstanceVar::<C1>::new_input(cs.clone(), || {
362            Ok(self.U_i1.unwrap_or(u_dummy_native.clone()))
363        })?;
364        let W_i1 = WitnessVar::<C1>::new_witness(cs.clone(), || {
365            Ok(self.W_i1.unwrap_or(w_dummy_native.clone()))
366        })?;
367
368        // allocate the inputs for the check 5.1
369        let kzg_c_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
370            Ok(self.kzg_c_W.unwrap_or_else(CF1::<C1>::zero))
371        })?;
372        let kzg_c_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
373            Ok(self.kzg_c_E.unwrap_or_else(CF1::<C1>::zero))
374        })?;
375        // allocate the inputs for the check 5.2
376        let eval_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
377            Ok(self.eval_W.unwrap_or_else(CF1::<C1>::zero))
378        })?;
379        let eval_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
380            Ok(self.eval_E.unwrap_or_else(CF1::<C1>::zero))
381        })?;
382
383        // `sponge` is for digest computation.
384        let sponge = PoseidonSpongeVar::<C1::ScalarField>::new(cs.clone(), &self.poseidon_config);
385        // `transcript` is for challenge generation.
386        let mut transcript = sponge.clone();
387
388        // The following enumeration of the steps matches the one used at the documentation page
389        // https://privacy-scaling-explorations.github.io/sonobe-docs/design/nova-decider-onchain.html
390
391        // 2. u_i.cmE==cm(0), u_i.u==1
392        // Here zero is the x & y coordinates of the zero point affine representation.
393        let zero = NonNativeUintVar::new_constant(cs.clone(), C1::BaseField::zero())?;
394        u_i.cmE.x.enforce_equal_unaligned(&zero)?;
395        u_i.cmE.y.enforce_equal_unaligned(&zero)?;
396        (u_i.u.is_one()?).enforce_equal(&Boolean::TRUE)?;
397
398        // 3.a u_i.x[0] == H(i, z_0, z_i, U_i)
399        let (u_i_x, U_i_vec) = U_i.clone().hash(&sponge, &pp_hash, &i, &z_0, &z_i)?;
400        (u_i.x[0]).enforce_equal(&u_i_x)?;
401
402        // 4. check RelaxedR1CS of U_{i+1}
403        let z_U1: Vec<FpVar<CF1<C1>>> =
404            [vec![U_i1.u.clone()], U_i1.x.to_vec(), W_i1.W.to_vec()].concat();
405        RelaxedR1CSGadget::check_native(r1cs, W_i1.E.clone(), U_i1.u.clone(), z_U1)?;
406
407        #[cfg(feature = "light-test")]
408        log::warn!("[WARNING]: Running with the 'light-test' feature, skipping the big part of the DeciderEthCircuit.\n           Only for testing purposes.");
409
410        // The following two checks (and their respective allocations) are disabled for normal
411        // tests since they take several millions of constraints and would take several minutes
412        // (and RAM) to run the test. It is active by default, and not active only when
413        // 'light-test' feature is used.
414        #[cfg(not(feature = "light-test"))]
415        {
416            // imports here instead of at the top of the file, so we avoid having multiple
417            // `#[cfg(not(test))]`
418            use crate::commitment::pedersen::PedersenGadget;
419            use crate::folding::{
420                circuits::cyclefold::{
421                    CycleFoldCommittedInstanceVar, CycleFoldConfig, CycleFoldWitnessVar,
422                },
423                nova::NovaCycleFoldConfig,
424            };
425            use ark_r1cs_std::ToBitsGadget;
426
427            let cf_u_dummy_native =
428                CycleFoldCommittedInstance::<C2>::dummy(NovaCycleFoldConfig::<C1>::IO_LEN);
429            let w_dummy_native = CycleFoldWitness::<C2>::dummy(&self.cf_r1cs);
430            let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
431                Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
432            })?;
433            let cf_W_i = CycleFoldWitnessVar::<C2>::new_witness(cs.clone(), || {
434                Ok(self.cf_W_i.unwrap_or(w_dummy_native.clone()))
435            })?;
436
437            // 3.b u_i.x[1] == H(cf_U_i)
438            let (cf_u_i_x, _) = cf_U_i.clone().hash(&sponge, pp_hash.clone())?;
439            (u_i.x[1]).enforce_equal(&cf_u_i_x)?;
440
441            // 7. check Pedersen commitments of cf_U_i.{cmE, cmW}
442            let H = GC2::new_constant(cs.clone(), self.cf_pedersen_params.h)?;
443            let G = Vec::<GC2>::new_constant(cs.clone(), self.cf_pedersen_params.generators)?;
444            let cf_W_i_E_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
445                cf_W_i.E.iter().map(|E_i| E_i.to_bits_le()).collect();
446            let cf_W_i_W_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
447                cf_W_i.W.iter().map(|W_i| W_i.to_bits_le()).collect();
448
449            let computed_cmE = PedersenGadget::<C2, GC2>::commit(
450                H.clone(),
451                G.clone(),
452                cf_W_i_E_bits?,
453                cf_W_i.rE.to_bits_le()?,
454            )?;
455            cf_U_i.cmE.enforce_equal(&computed_cmE)?;
456            let computed_cmW =
457                PedersenGadget::<C2, GC2>::commit(H, G, cf_W_i_W_bits?, cf_W_i.rW.to_bits_le()?)?;
458            cf_U_i.cmW.enforce_equal(&computed_cmW)?;
459
460            let cf_r1cs =
461                R1CSVar::<C1::BaseField, CF1<C1>, NonNativeUintVar<CF1<C1>>>::new_witness(
462                    cs.clone(),
463                    || Ok(self.cf_r1cs.clone()),
464                )?;
465
466            // 6. check RelaxedR1CS of cf_U_i (CycleFold instance)
467            let cf_z_U = [vec![cf_U_i.u.clone()], cf_U_i.x.to_vec(), cf_W_i.W.to_vec()].concat();
468            RelaxedR1CSGadget::check_nonnative(cf_r1cs, cf_W_i.E, cf_U_i.u.clone(), cf_z_U)?;
469        }
470
471        // 1.1.a, 5.1. compute NIFS.V and KZG challenges.
472        // We need to ensure the order of challenge generation is the same as
473        // the native counterpart, so we first compute the challenges here and
474        // do the actual checks later.
475        let cmT =
476            NonNativeAffineVar::new_input(cs.clone(), || Ok(self.cmT.unwrap_or_else(C1::zero)))?;
477        // 1.1.a
478        let r_bits = ChallengeGadget::<C1, CommittedInstance<C1>>::get_challenge_gadget(
479            &mut transcript,
480            pp_hash,
481            U_i_vec,
482            u_i.clone(),
483            Some(cmT),
484        )?;
485        // 5.1.
486        let (incircuit_c_W, incircuit_c_E) =
487            KZGChallengesGadget::<C1>::get_challenges_gadget(&mut transcript, U_i1.clone())?;
488        incircuit_c_W.enforce_equal(&kzg_c_W)?;
489        incircuit_c_E.enforce_equal(&kzg_c_E)?;
490
491        // 5.2. check eval_W==p_W(c_W) and eval_E==p_E(c_E)
492        let incircuit_eval_W = evaluate_gadget::<CF1<C1>>(W_i1.W, incircuit_c_W)?;
493        let incircuit_eval_E = evaluate_gadget::<CF1<C1>>(W_i1.E, incircuit_c_E)?;
494        incircuit_eval_W.enforce_equal(&eval_W)?;
495        incircuit_eval_E.enforce_equal(&eval_E)?;
496
497        // 1.1.b check that the NIFS.V challenge matches the one from the public input (so we avoid
498        //   the verifier computing it)
499        let r_Fr = Boolean::le_bits_to_fp_var(&r_bits)?;
500        // check that the in-circuit computed r is equal to the inputted r
501        let r =
502            FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.r.unwrap_or_else(CF1::<C1>::zero)))?;
503        r_Fr.enforce_equal(&r)?;
504
505        Ok(())
506    }
507}
508
509/// Interpolates the polynomial from the given vector, and then returns it's evaluation at the
510/// given point.
511#[allow(unused)] // unused while check 7 is disabled
512pub fn evaluate_gadget<F: PrimeField>(
513    mut v: Vec<FpVar<F>>,
514    point: FpVar<F>,
515) -> Result<FpVar<F>, SynthesisError> {
516    v.resize(v.len().next_power_of_two(), FpVar::zero());
517    let n = v.len() as u64;
518    let gen = F::get_root_of_unity(n).unwrap();
519    let domain = Radix2DomainVar::new(gen, log2(v.len()) as u64, FpVar::one()).unwrap();
520
521    let evaluations_var = EvaluationsVar::from_vec_and_domain(v, domain, true);
522    evaluations_var.interpolate_and_evaluate(&point)
523}
524
525/// Gadget that computes the KZG challenges, also offers the rust native implementation compatible
526/// with the gadget.
527pub struct KZGChallengesGadget<C: CurveGroup> {
528    _c: PhantomData<C>,
529}
530#[allow(clippy::type_complexity)]
531impl<C> KZGChallengesGadget<C>
532where
533    C: CurveGroup,
534    C::ScalarField: PrimeField,
535    <C as CurveGroup>::BaseField: PrimeField,
536    C::ScalarField: Absorb,
537{
538    pub fn get_challenges_native<T: Transcript<C::ScalarField>>(
539        transcript: &mut T,
540        U_i: CommittedInstance<C>,
541    ) -> (C::ScalarField, C::ScalarField) {
542        // compute the KZG challenges, which are computed in-circuit and checked that it matches
543        // the inputted one
544        transcript.absorb_nonnative(&U_i.cmW);
545        let challenge_W = transcript.get_challenge();
546        transcript.absorb_nonnative(&U_i.cmE);
547        let challenge_E = transcript.get_challenge();
548
549        (challenge_W, challenge_E)
550    }
551    // compatible with the native get_challenges_native
552    pub fn get_challenges_gadget<S: CryptographicSponge, T: TranscriptVar<CF1<C>, S>>(
553        transcript: &mut T,
554        U_i: CommittedInstanceVar<C>,
555    ) -> Result<(FpVar<C::ScalarField>, FpVar<C::ScalarField>), SynthesisError> {
556        transcript.absorb(&U_i.cmW.to_constraint_field()?)?;
557        let challenge_W = transcript.get_challenge()?;
558
559        transcript.absorb(&U_i.cmE.to_constraint_field()?)?;
560        let challenge_E = transcript.get_challenge()?;
561
562        Ok((challenge_W, challenge_E))
563    }
564}
565
566#[cfg(test)]
567pub mod tests {
568    use std::cmp::max;
569
570    use ark_crypto_primitives::crh::{
571        sha256::{
572            constraints::{Sha256Gadget, UnitVar},
573            Sha256,
574        },
575        CRHScheme, CRHSchemeGadget,
576    };
577    use ark_pallas::{constraints::GVar, Fq, Fr, Projective};
578    use ark_r1cs_std::bits::uint8::UInt8;
579    use ark_relations::r1cs::ConstraintSystem;
580    use ark_std::{
581        rand::{thread_rng, Rng},
582        UniformRand,
583    };
584    use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
585
586    use super::*;
587    use crate::arith::{
588        r1cs::{
589            extract_r1cs, extract_w_x,
590            tests::{get_test_r1cs, get_test_z},
591        },
592        Arith,
593    };
594    use crate::commitment::pedersen::Pedersen;
595    use crate::folding::nova::PreprocessorParam;
596    use crate::frontend::utils::{CubicFCircuit, CustomFCircuit, WrapperCircuit};
597    use crate::transcript::poseidon::poseidon_canonical_config;
598    use crate::FoldingScheme;
599
600    // Convert `z` to a witness-instance pair for the relaxed R1CS
601    fn prepare_relaxed_witness_instance<C: CurveGroup, CS: CommitmentScheme<C>, R: Rng>(
602        mut rng: R,
603        r1cs: &R1CS<C::ScalarField>,
604        z: &[C::ScalarField],
605    ) -> (Witness<C>, CommittedInstance<C>) {
606        let (w, x) = r1cs.split_z(z);
607
608        let (cs_pp, _) = CS::setup(&mut rng, max(w.len(), r1cs.A.n_rows)).unwrap();
609
610        let mut w = Witness::new::<false>(w, r1cs.A.n_rows, &mut rng);
611        w.E = r1cs.eval_at_z(z).unwrap();
612        let mut u = w.commit::<CS, false>(&cs_pp, x).unwrap();
613        u.u = z[0];
614
615        (w, u)
616    }
617
618    #[test]
619    fn test_relaxed_r1cs_small_gadget_handcrafted() {
620        let rng = &mut thread_rng();
621
622        let r1cs: R1CS<Fr> = get_test_r1cs();
623
624        let mut z = get_test_z(3);
625        z[0] = Fr::rand(rng); // Randomize `z[0]` (i.e. `u.u`) to test the relaxed R1CS
626        let (w, u) = prepare_relaxed_witness_instance::<_, Pedersen<Projective>, _>(rng, &r1cs, &z);
627
628        let cs = ConstraintSystem::<Fr>::new_ref();
629
630        let zVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z)).unwrap();
631        let EVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(w.E)).unwrap();
632        let uVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
633        let r1csVar = R1CSVar::<Fr, Fr, FpVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
634
635        RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
636        assert!(cs.is_satisfied().unwrap());
637    }
638
639    // gets as input a circuit that implements the ConstraintSynthesizer trait, and that has been
640    // initialized.
641    fn test_relaxed_r1cs_gadget<CS: ConstraintSynthesizer<Fr>>(circuit: CS) {
642        let rng = &mut thread_rng();
643
644        let cs = ConstraintSystem::<Fr>::new_ref();
645
646        circuit.generate_constraints(cs.clone()).unwrap();
647        cs.finalize();
648        assert!(cs.is_satisfied().unwrap());
649
650        let cs = cs.into_inner().unwrap();
651
652        let r1cs = extract_r1cs::<Fr>(&cs);
653        let (w, x) = extract_w_x::<Fr>(&cs);
654        r1cs.check_relation(&w, &x).unwrap();
655
656        let z = [vec![Fr::rand(rng)], x, w].concat();
657        let (w, u) = prepare_relaxed_witness_instance::<_, Pedersen<Projective>, _>(rng, &r1cs, &z);
658        r1cs.check_relation(&w, &u).unwrap();
659
660        // set new CS for the circuit that checks the RelaxedR1CS of our original circuit
661        let cs = ConstraintSystem::<Fr>::new_ref();
662        // prepare the inputs for our circuit
663        let zVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z)).unwrap();
664        let EVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(w.E)).unwrap();
665        let uVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
666        let r1csVar = R1CSVar::<Fr, Fr, FpVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
667
668        RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
669        assert!(cs.is_satisfied().unwrap());
670    }
671
672    #[test]
673    fn test_relaxed_r1cs_small_gadget_arkworks() {
674        let z_i = vec![Fr::from(3_u32)];
675        let cubic_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
676        let circuit = WrapperCircuit::<Fr, CubicFCircuit<Fr>> {
677            FC: cubic_circuit,
678            z_i: Some(z_i.clone()),
679            z_i1: Some(cubic_circuit.step_native(0, z_i, vec![]).unwrap()),
680        };
681
682        test_relaxed_r1cs_gadget(circuit);
683    }
684
685    struct Sha256TestCircuit<F: PrimeField> {
686        _f: PhantomData<F>,
687        pub x: Vec<u8>,
688        pub y: Vec<u8>,
689    }
690    impl<F: PrimeField> ConstraintSynthesizer<F> for Sha256TestCircuit<F> {
691        fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
692            let x = Vec::<UInt8<F>>::new_witness(cs.clone(), || Ok(self.x))?;
693            let y = Vec::<UInt8<F>>::new_input(cs.clone(), || Ok(self.y))?;
694
695            let unitVar = UnitVar::default();
696            let comp_y = <Sha256Gadget<F> as CRHSchemeGadget<Sha256, F>>::evaluate(&unitVar, &x)?;
697            comp_y.0.enforce_equal(&y)?;
698            Ok(())
699        }
700    }
701    #[test]
702    fn test_relaxed_r1cs_medium_gadget_arkworks() {
703        let x = Fr::from(5_u32).into_bigint().to_bytes_le();
704        let y = <Sha256 as CRHScheme>::evaluate(&(), x.clone()).unwrap();
705
706        let circuit = Sha256TestCircuit::<Fr> {
707            _f: PhantomData,
708            x,
709            y,
710        };
711        test_relaxed_r1cs_gadget(circuit);
712    }
713
714    #[test]
715    fn test_relaxed_r1cs_custom_circuit() {
716        let n_constraints = 10_000;
717        let custom_circuit = CustomFCircuit::<Fr>::new(n_constraints).unwrap();
718        let z_i = vec![Fr::from(5_u32)];
719        let circuit = WrapperCircuit::<Fr, CustomFCircuit<Fr>> {
720            FC: custom_circuit,
721            z_i: Some(z_i.clone()),
722            z_i1: Some(custom_circuit.step_native(0, z_i, vec![]).unwrap()),
723        };
724        test_relaxed_r1cs_gadget(circuit);
725    }
726
727    #[test]
728    fn test_relaxed_r1cs_nonnative_circuit() {
729        let rng = &mut thread_rng();
730
731        let cs = ConstraintSystem::<Fq>::new_ref();
732        // in practice we would use CycleFoldCircuit, but is a very big circuit (when computed
733        // non-natively inside the RelaxedR1CS circuit), so in order to have a short test we use a
734        // custom circuit.
735        let custom_circuit = CustomFCircuit::<Fq>::new(10).unwrap();
736        let z_i = vec![Fq::from(5_u32)];
737        let circuit = WrapperCircuit::<Fq, CustomFCircuit<Fq>> {
738            FC: custom_circuit,
739            z_i: Some(z_i.clone()),
740            z_i1: Some(custom_circuit.step_native(0, z_i, vec![]).unwrap()),
741        };
742        circuit.generate_constraints(cs.clone()).unwrap();
743        cs.finalize();
744        let cs = cs.into_inner().unwrap();
745        let r1cs = extract_r1cs::<Fq>(&cs);
746        let (w, x) = extract_w_x::<Fq>(&cs);
747
748        let z = [vec![Fq::rand(rng)], x, w].concat();
749        let (w, u) =
750            prepare_relaxed_witness_instance::<_, Pedersen<Projective2>, _>(rng, &r1cs, &z);
751
752        // natively
753        let cs = ConstraintSystem::<Fq>::new_ref();
754        let zVar = Vec::<FpVar<Fq>>::new_witness(cs.clone(), || Ok(z.clone())).unwrap();
755        let EVar = Vec::<FpVar<Fq>>::new_witness(cs.clone(), || Ok(w.E.clone())).unwrap();
756        let uVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
757        let r1csVar =
758            R1CSVar::<Fq, Fq, FpVar<Fq>>::new_witness(cs.clone(), || Ok(r1cs.clone())).unwrap();
759        RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
760
761        // non-natively
762        let cs = ConstraintSystem::<Fr>::new_ref();
763        let zVar = Vec::new_witness(cs.clone(), || Ok(z)).unwrap();
764        let EVar = Vec::new_witness(cs.clone(), || Ok(w.E)).unwrap();
765        let uVar = NonNativeUintVar::<Fr>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
766        let r1csVar =
767            R1CSVar::<Fq, Fr, NonNativeUintVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
768        RelaxedR1CSGadget::check_nonnative(r1csVar, EVar, uVar, zVar).unwrap();
769    }
770
771    #[test]
772    fn test_decider_eth_circuit() {
773        let mut rng = ark_std::test_rng();
774        let poseidon_config = poseidon_canonical_config::<Fr>();
775
776        let F_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
777        let z_0 = vec![Fr::from(3_u32)];
778
779        type N = Nova<
780            Projective,
781            GVar,
782            Projective2,
783            GVar2,
784            CubicFCircuit<Fr>,
785            Pedersen<Projective>,
786            Pedersen<Projective2>,
787            false,
788        >;
789
790        let prep_param = PreprocessorParam::<
791            Projective,
792            Projective2,
793            CubicFCircuit<Fr>,
794            Pedersen<Projective>,
795            Pedersen<Projective2>,
796            false,
797        >::new(poseidon_config, F_circuit);
798        let nova_params = N::preprocess(&mut rng, &prep_param).unwrap();
799
800        // generate a Nova instance and do a step of it
801        let mut nova = N::init(&nova_params, F_circuit, z_0.clone()).unwrap();
802        nova.prove_step(&mut rng, vec![], None).unwrap();
803        let ivc_proof = nova.ivc_proof();
804        N::verify(nova_params.1, ivc_proof).unwrap();
805
806        // load the DeciderEthCircuit from the Nova instance
807        let decider_eth_circuit = DeciderEthCircuit::<
808            Projective,
809            GVar,
810            Projective2,
811            GVar2,
812            Pedersen<Projective>,
813            Pedersen<Projective2>,
814        >::from_nova(nova)
815        .unwrap();
816
817        let cs = ConstraintSystem::<Fr>::new_ref();
818
819        // generate the constraints and check that are satisfied by the inputs
820        decider_eth_circuit
821            .generate_constraints(cs.clone())
822            .unwrap();
823        assert!(cs.is_satisfied().unwrap());
824    }
825
826    // checks that the gadget and native implementations of the challenge computation match
827    #[test]
828    fn test_kzg_challenge_gadget() {
829        let mut rng = ark_std::test_rng();
830        let poseidon_config = poseidon_canonical_config::<Fr>();
831        let mut transcript = PoseidonSponge::<Fr>::new(&poseidon_config);
832
833        let U_i = CommittedInstance::<Projective> {
834            cmE: Projective::rand(&mut rng),
835            u: Fr::rand(&mut rng),
836            cmW: Projective::rand(&mut rng),
837            x: vec![Fr::rand(&mut rng); 1],
838        };
839
840        // compute the challenge natively
841        let (challenge_W, challenge_E) =
842            KZGChallengesGadget::<Projective>::get_challenges_native(&mut transcript, U_i.clone());
843
844        let cs = ConstraintSystem::<Fr>::new_ref();
845        let U_iVar =
846            CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(U_i.clone()))
847                .unwrap();
848        let mut transcript_var = PoseidonSpongeVar::<Fr>::new(cs.clone(), &poseidon_config);
849
850        let (challenge_W_Var, challenge_E_Var) =
851            KZGChallengesGadget::<Projective>::get_challenges_gadget(&mut transcript_var, U_iVar)
852                .unwrap();
853        assert!(cs.is_satisfied().unwrap());
854
855        // check that the natively computed and in-circuit computed hashes match
856        use ark_r1cs_std::R1CSVar;
857        assert_eq!(challenge_W_Var.value().unwrap(), challenge_W);
858        assert_eq!(challenge_E_Var.value().unwrap(), challenge_E);
859    }
860
861    #[test]
862    fn test_polynomial_interpolation() {
863        let mut rng = ark_std::test_rng();
864        let n = 12;
865        let l = 1 << n;
866
867        let v: Vec<Fr> = std::iter::repeat_with(|| Fr::rand(&mut rng))
868            .take(l)
869            .collect();
870        let challenge = Fr::rand(&mut rng);
871
872        use ark_poly::Polynomial;
873        let polynomial = poly_from_vec(v.to_vec()).unwrap();
874        let eval = polynomial.evaluate(&challenge);
875
876        let cs = ConstraintSystem::<Fr>::new_ref();
877        let vVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(v)).unwrap();
878        let challengeVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(challenge)).unwrap();
879
880        let evalVar = evaluate_gadget::<Fr>(vVar, challengeVar).unwrap();
881
882        use ark_r1cs_std::R1CSVar;
883        assert_eq!(evalVar.value().unwrap(), eval);
884        assert!(cs.is_satisfied().unwrap());
885    }
886}