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::NIFS,
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 (T, cmT) = NIFS::<C1, CS1, H>::compute_cmT(
249 &nova.cs_pp,
250 &nova.r1cs.clone(),
251 &nova.w_i.clone(),
252 &nova.u_i.clone(),
253 &nova.W_i.clone(),
254 &nova.U_i.clone(),
255 )?;
256 let r_bits = ChallengeGadget::<C1>::get_challenge_native(
257 &mut transcript,
258 nova.pp_hash,
259 nova.U_i.clone(),
260 nova.u_i.clone(),
261 cmT,
262 );
263 let r_Fr = C1::ScalarField::from_bigint(BigInteger::from_bits_le(&r_bits))
264 .ok_or(Error::OutOfBounds)?;
265 let (W_i1, U_i1) = NIFS::<C1, CS1, H>::fold_instances(
266 r_Fr, &nova.W_i, &nova.U_i, &nova.w_i, &nova.u_i, &T, cmT,
267 )?;
268
269 // compute the KZG challenges used as inputs in the circuit
270 let (kzg_challenge_W, kzg_challenge_E) =
271 KZGChallengesGadget::<C1>::get_challenges_native(&mut transcript, U_i1.clone());
272
273 // get KZG evals
274 let mut W = W_i1.W.clone();
275 W.extend(
276 std::iter::repeat(C1::ScalarField::zero())
277 .take(W_i1.W.len().next_power_of_two() - W_i1.W.len()),
278 );
279 let mut E = W_i1.E.clone();
280 E.extend(
281 std::iter::repeat(C1::ScalarField::zero())
282 .take(W_i1.E.len().next_power_of_two() - W_i1.E.len()),
283 );
284 let p_W = poly_from_vec(W.to_vec())?;
285 let eval_W = p_W.evaluate(&kzg_challenge_W);
286 let p_E = poly_from_vec(E.to_vec())?;
287 let eval_E = p_E.evaluate(&kzg_challenge_E);
288
289 Ok(Self {
290 _c1: PhantomData,
291 _gc1: PhantomData,
292 _c2: PhantomData,
293 _gc2: PhantomData,
294 _cs1: PhantomData,
295 _cs2: PhantomData,
296
297 E_len: nova.W_i.E.len(),
298 cf_E_len: nova.cf_W_i.E.len(),
299 r1cs: nova.r1cs,
300 cf_r1cs: nova.cf_r1cs,
301 cf_pedersen_params: nova.cf_cs_pp,
302 poseidon_config: nova.poseidon_config,
303 pp_hash: Some(nova.pp_hash),
304 i: Some(nova.i),
305 z_0: Some(nova.z_0),
306 z_i: Some(nova.z_i),
307 u_i: Some(nova.u_i),
308 w_i: Some(nova.w_i),
309 U_i: Some(nova.U_i),
310 W_i: Some(nova.W_i),
311 U_i1: Some(U_i1),
312 W_i1: Some(W_i1),
313 cmT: Some(cmT),
314 r: Some(r_Fr),
315 cf_U_i: Some(nova.cf_U_i),
316 cf_W_i: Some(nova.cf_W_i),
317 kzg_c_W: Some(kzg_challenge_W),
318 kzg_c_E: Some(kzg_challenge_E),
319 eval_W: Some(eval_W),
320 eval_E: Some(eval_E),
321 })
322 }
323}
324
325impl<C1, GC1, C2, GC2, CS1, CS2> ConstraintSynthesizer<CF1<C1>>
326 for DeciderEthCircuit<C1, GC1, C2, GC2, CS1, CS2>
327where
328 C1: CurveGroup,
329 C2: CurveGroup,
330 GC1: CurveVar<C1, CF2<C1>>,
331 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
332 CS1: CommitmentScheme<C1>,
333 CS2: CommitmentScheme<C2>,
334 <C1 as CurveGroup>::BaseField: PrimeField,
335 <C2 as CurveGroup>::BaseField: PrimeField,
336 <C1 as Group>::ScalarField: Absorb,
337 <C2 as Group>::ScalarField: Absorb,
338 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
339 for<'b> &'b GC2: GroupOpsBounds<'b, C2, GC2>,
340{
341 fn generate_constraints(self, cs: ConstraintSystemRef<CF1<C1>>) -> Result<(), SynthesisError> {
342 let r1cs =
343 R1CSVar::<C1::ScalarField, CF1<C1>, FpVar<CF1<C1>>>::new_witness(cs.clone(), || {
344 Ok(self.r1cs.clone())
345 })?;
346
347 let pp_hash = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
348 Ok(self.pp_hash.unwrap_or_else(CF1::<C1>::zero))
349 })?;
350 let i =
351 FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.i.unwrap_or_else(CF1::<C1>::zero)))?;
352 let z_0 = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
353 Ok(self.z_0.unwrap_or(vec![CF1::<C1>::zero()]))
354 })?;
355 let z_i = Vec::<FpVar<CF1<C1>>>::new_input(cs.clone(), || {
356 Ok(self.z_i.unwrap_or(vec![CF1::<C1>::zero()]))
357 })?;
358
359 let u_dummy_native = CommittedInstance::<C1>::dummy(&self.r1cs);
360 let w_dummy_native = Witness::<C1>::dummy(&self.r1cs);
361
362 let u_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
363 Ok(self.u_i.unwrap_or(u_dummy_native.clone()))
364 })?;
365 let U_i = CommittedInstanceVar::<C1>::new_witness(cs.clone(), || {
366 Ok(self.U_i.unwrap_or(u_dummy_native.clone()))
367 })?;
368 // here (U_i1, W_i1) = NIFS.P( (U_i,W_i), (u_i,w_i))
369 let U_i1 = CommittedInstanceVar::<C1>::new_input(cs.clone(), || {
370 Ok(self.U_i1.unwrap_or(u_dummy_native.clone()))
371 })?;
372 let W_i1 = WitnessVar::<C1>::new_witness(cs.clone(), || {
373 Ok(self.W_i1.unwrap_or(w_dummy_native.clone()))
374 })?;
375
376 // allocate the inputs for the check 5.1
377 let kzg_c_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
378 Ok(self.kzg_c_W.unwrap_or_else(CF1::<C1>::zero))
379 })?;
380 let kzg_c_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
381 Ok(self.kzg_c_E.unwrap_or_else(CF1::<C1>::zero))
382 })?;
383 // allocate the inputs for the check 5.2
384 let _eval_W = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
385 Ok(self.eval_W.unwrap_or_else(CF1::<C1>::zero))
386 })?;
387 let _eval_E = FpVar::<CF1<C1>>::new_input(cs.clone(), || {
388 Ok(self.eval_E.unwrap_or_else(CF1::<C1>::zero))
389 })?;
390
391 // `sponge` is for digest computation.
392 let sponge = PoseidonSpongeVar::<C1::ScalarField>::new(cs.clone(), &self.poseidon_config);
393 // `transcript` is for challenge generation.
394 let mut transcript = sponge.clone();
395
396 // The following enumeration of the steps matches the one used at the documentation page
397 // https://privacy-scaling-explorations.github.io/sonobe-docs/design/nova-decider-onchain.html
398
399 // 2. u_i.cmE==cm(0), u_i.u==1
400 // Here zero is the x & y coordinates of the zero point affine representation.
401 let zero = NonNativeUintVar::new_constant(cs.clone(), C1::BaseField::zero())?;
402 u_i.cmE.x.enforce_equal_unaligned(&zero)?;
403 u_i.cmE.y.enforce_equal_unaligned(&zero)?;
404 (u_i.u.is_one()?).enforce_equal(&Boolean::TRUE)?;
405
406 // 3.a u_i.x[0] == H(i, z_0, z_i, U_i)
407 let (u_i_x, U_i_vec) = U_i.clone().hash(&sponge, &pp_hash, &i, &z_0, &z_i)?;
408 (u_i.x[0]).enforce_equal(&u_i_x)?;
409
410 // 4. check RelaxedR1CS of U_{i+1}
411 let z_U1: Vec<FpVar<CF1<C1>>> =
412 [vec![U_i1.u.clone()], U_i1.x.to_vec(), W_i1.W.to_vec()].concat();
413 RelaxedR1CSGadget::check_native(r1cs, W_i1.E.clone(), U_i1.u.clone(), z_U1)?;
414
415 #[cfg(feature = "light-test")]
416 log::warn!("[WARNING]: Running with the 'light-test' feature, skipping the big part of the DeciderEthCircuit.\n Only for testing purposes.");
417
418 // The following two checks (and their respective allocations) are disabled for normal
419 // tests since they take several millions of constraints and would take several minutes
420 // (and RAM) to run the test. It is active by default, and not active only when
421 // 'light-test' feature is used.
422 #[cfg(not(feature = "light-test"))]
423 {
424 // imports here instead of at the top of the file, so we avoid having multiple
425 // `#[cfg(not(test))]`
426 use crate::commitment::pedersen::PedersenGadget;
427 use crate::folding::{
428 circuits::cyclefold::{
429 CycleFoldCommittedInstanceVar, CycleFoldConfig, CycleFoldWitnessVar,
430 },
431 nova::NovaCycleFoldConfig,
432 };
433 use ark_r1cs_std::ToBitsGadget;
434
435 let cf_u_dummy_native =
436 CycleFoldCommittedInstance::<C2>::dummy(NovaCycleFoldConfig::<C1>::IO_LEN);
437 let w_dummy_native = CycleFoldWitness::<C2>::dummy(&self.cf_r1cs);
438 let cf_U_i = CycleFoldCommittedInstanceVar::<C2, GC2>::new_witness(cs.clone(), || {
439 Ok(self.cf_U_i.unwrap_or_else(|| cf_u_dummy_native.clone()))
440 })?;
441 let cf_W_i = CycleFoldWitnessVar::<C2>::new_witness(cs.clone(), || {
442 Ok(self.cf_W_i.unwrap_or(w_dummy_native.clone()))
443 })?;
444
445 // 3.b u_i.x[1] == H(cf_U_i)
446 let (cf_u_i_x, _) = cf_U_i.clone().hash(&sponge, pp_hash.clone())?;
447 (u_i.x[1]).enforce_equal(&cf_u_i_x)?;
448
449 // 7. check Pedersen commitments of cf_U_i.{cmE, cmW}
450 let H = GC2::new_constant(cs.clone(), self.cf_pedersen_params.h)?;
451 let G = Vec::<GC2>::new_constant(cs.clone(), self.cf_pedersen_params.generators)?;
452 let cf_W_i_E_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
453 cf_W_i.E.iter().map(|E_i| E_i.to_bits_le()).collect();
454 let cf_W_i_W_bits: Result<Vec<Vec<Boolean<CF1<C1>>>>, SynthesisError> =
455 cf_W_i.W.iter().map(|W_i| W_i.to_bits_le()).collect();
456
457 let computed_cmE = PedersenGadget::<C2, GC2>::commit(
458 H.clone(),
459 G.clone(),
460 cf_W_i_E_bits?,
461 cf_W_i.rE.to_bits_le()?,
462 )?;
463 cf_U_i.cmE.enforce_equal(&computed_cmE)?;
464 let computed_cmW =
465 PedersenGadget::<C2, GC2>::commit(H, G, cf_W_i_W_bits?, cf_W_i.rW.to_bits_le()?)?;
466 cf_U_i.cmW.enforce_equal(&computed_cmW)?;
467
468 let cf_r1cs =
469 R1CSVar::<C1::BaseField, CF1<C1>, NonNativeUintVar<CF1<C1>>>::new_witness(
470 cs.clone(),
471 || Ok(self.cf_r1cs.clone()),
472 )?;
473
474 // 6. check RelaxedR1CS of cf_U_i (CycleFold instance)
475 let cf_z_U = [vec![cf_U_i.u.clone()], cf_U_i.x.to_vec(), cf_W_i.W.to_vec()].concat();
476 RelaxedR1CSGadget::check_nonnative(cf_r1cs, cf_W_i.E, cf_U_i.u.clone(), cf_z_U)?;
477 }
478
479 // 1.1.a, 5.1. compute NIFS.V and KZG challenges.
480 // We need to ensure the order of challenge generation is the same as
481 // the native counterpart, so we first compute the challenges here and
482 // do the actual checks later.
483 let cmT =
484 NonNativeAffineVar::new_input(cs.clone(), || Ok(self.cmT.unwrap_or_else(C1::zero)))?;
485 // 1.1.a
486 let r_bits = ChallengeGadget::<C1>::get_challenge_gadget(
487 &mut transcript,
488 pp_hash,
489 U_i_vec,
490 u_i.clone(),
491 cmT.clone(),
492 )?;
493 // 5.1.
494 let (incircuit_c_W, incircuit_c_E) =
495 KZGChallengesGadget::<C1>::get_challenges_gadget(&mut transcript, U_i1.clone())?;
496 incircuit_c_W.enforce_equal(&kzg_c_W)?;
497 incircuit_c_E.enforce_equal(&kzg_c_E)?;
498
499 // Check 5.2 is temporary disabled due
500 // https://github.com/privacy-scaling-explorations/sonobe/issues/80
501 log::warn!("[WARNING]: issue #80 (https://github.com/privacy-scaling-explorations/sonobe/issues/80) is not resolved yet.");
502 //
503 // 5.2. check eval_W==p_W(c_W) and eval_E==p_E(c_E)
504 // let incircuit_eval_W = evaluate_gadget::<CF1<C1>>(W_i1.W, incircuit_c_W)?;
505 // let incircuit_eval_E = evaluate_gadget::<CF1<C1>>(W_i1.E, incircuit_c_E)?;
506 // incircuit_eval_W.enforce_equal(&eval_W)?;
507 // incircuit_eval_E.enforce_equal(&eval_E)?;
508
509 // 1.1.b check that the NIFS.V challenge matches the one from the public input (so we avoid
510 // the verifier computing it)
511 let r_Fr = Boolean::le_bits_to_fp_var(&r_bits)?;
512 // check that the in-circuit computed r is equal to the inputted r
513 let r =
514 FpVar::<CF1<C1>>::new_input(cs.clone(), || Ok(self.r.unwrap_or_else(CF1::<C1>::zero)))?;
515 r_Fr.enforce_equal(&r)?;
516
517 Ok(())
518 }
519}
520
521/// Interpolates the polynomial from the given vector, and then returns it's evaluation at the
522/// given point.
523#[allow(unused)] // unused while check 7 is disabled
524fn evaluate_gadget<F: PrimeField>(
525 v: Vec<FpVar<F>>,
526 point: FpVar<F>,
527) -> Result<FpVar<F>, SynthesisError> {
528 if !v.len().is_power_of_two() {
529 return Err(SynthesisError::Unsatisfiable);
530 }
531 let n = v.len() as u64;
532 let gen = F::get_root_of_unity(n).unwrap();
533 let domain = Radix2DomainVar::new(gen, log2(v.len()) as u64, FpVar::one()).unwrap();
534
535 let evaluations_var = EvaluationsVar::from_vec_and_domain(v, domain, true);
536 evaluations_var.interpolate_and_evaluate(&point)
537}
538
539/// Gadget that computes the KZG challenges, also offers the rust native implementation compatible
540/// with the gadget.
541pub struct KZGChallengesGadget<C: CurveGroup> {
542 _c: PhantomData<C>,
543}
544#[allow(clippy::type_complexity)]
545impl<C> KZGChallengesGadget<C>
546where
547 C: CurveGroup,
548 C::ScalarField: PrimeField,
549 <C as CurveGroup>::BaseField: PrimeField,
550 C::ScalarField: Absorb,
551{
552 pub fn get_challenges_native<T: Transcript<C::ScalarField>>(
553 transcript: &mut T,
554 U_i: CommittedInstance<C>,
555 ) -> (C::ScalarField, C::ScalarField) {
556 // compute the KZG challenges, which are computed in-circuit and checked that it matches
557 // the inputted one
558 transcript.absorb_nonnative(&U_i.cmW);
559 let challenge_W = transcript.get_challenge();
560 transcript.absorb_nonnative(&U_i.cmE);
561 let challenge_E = transcript.get_challenge();
562
563 (challenge_W, challenge_E)
564 }
565 // compatible with the native get_challenges_native
566 pub fn get_challenges_gadget<S: CryptographicSponge, T: TranscriptVar<CF1<C>, S>>(
567 transcript: &mut T,
568 U_i: CommittedInstanceVar<C>,
569 ) -> Result<(FpVar<C::ScalarField>, FpVar<C::ScalarField>), SynthesisError> {
570 transcript.absorb(&U_i.cmW.to_constraint_field()?)?;
571 let challenge_W = transcript.get_challenge()?;
572
573 transcript.absorb(&U_i.cmE.to_constraint_field()?)?;
574 let challenge_E = transcript.get_challenge()?;
575
576 Ok((challenge_W, challenge_E))
577 }
578}
579
580#[cfg(test)]
581pub mod tests {
582 use std::cmp::max;
583
584 use ark_crypto_primitives::crh::{
585 sha256::{
586 constraints::{Sha256Gadget, UnitVar},
587 Sha256,
588 },
589 CRHScheme, CRHSchemeGadget,
590 };
591 use ark_pallas::{constraints::GVar, Fq, Fr, Projective};
592 use ark_r1cs_std::bits::uint8::UInt8;
593 use ark_relations::r1cs::ConstraintSystem;
594 use ark_std::{
595 rand::{thread_rng, Rng},
596 One, UniformRand,
597 };
598 use ark_vesta::{constraints::GVar as GVar2, Projective as Projective2};
599
600 use super::*;
601 use crate::arith::{
602 r1cs::{
603 extract_r1cs, extract_w_x,
604 tests::{get_test_r1cs, get_test_z},
605 },
606 Arith,
607 };
608 use crate::commitment::pedersen::Pedersen;
609 use crate::folding::nova::PreprocessorParam;
610 use crate::frontend::utils::{CubicFCircuit, CustomFCircuit, WrapperCircuit};
611 use crate::transcript::poseidon::poseidon_canonical_config;
612 use crate::FoldingScheme;
613
614 // Convert `z` to a witness-instance pair for the relaxed R1CS
615 fn prepare_relaxed_witness_instance<C: CurveGroup, CS: CommitmentScheme<C>, R: Rng>(
616 mut rng: R,
617 r1cs: &R1CS<C::ScalarField>,
618 z: &[C::ScalarField],
619 ) -> (Witness<C>, CommittedInstance<C>) {
620 let (w, x) = r1cs.split_z(z);
621
622 let (cs_pp, _) = CS::setup(&mut rng, max(w.len(), r1cs.A.n_rows)).unwrap();
623
624 let mut w = Witness::new::<false>(w, r1cs.A.n_rows, &mut rng);
625 w.E = r1cs.eval_at_z(z).unwrap();
626 let mut u = w.commit::<CS, false>(&cs_pp, x).unwrap();
627 u.u = z[0];
628
629 (w, u)
630 }
631
632 #[test]
633 fn test_relaxed_r1cs_small_gadget_handcrafted() {
634 let rng = &mut thread_rng();
635
636 let r1cs: R1CS<Fr> = get_test_r1cs();
637
638 let mut z = get_test_z(3);
639 z[0] = Fr::rand(rng); // Randomize `z[0]` (i.e. `u.u`) to test the relaxed R1CS
640 let (w, u) = prepare_relaxed_witness_instance::<_, Pedersen<Projective>, _>(rng, &r1cs, &z);
641
642 let cs = ConstraintSystem::<Fr>::new_ref();
643
644 let zVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z)).unwrap();
645 let EVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(w.E)).unwrap();
646 let uVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
647 let r1csVar = R1CSVar::<Fr, Fr, FpVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
648
649 RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
650 assert!(cs.is_satisfied().unwrap());
651 }
652
653 // gets as input a circuit that implements the ConstraintSynthesizer trait, and that has been
654 // initialized.
655 fn test_relaxed_r1cs_gadget<CS: ConstraintSynthesizer<Fr>>(circuit: CS) {
656 let rng = &mut thread_rng();
657
658 let cs = ConstraintSystem::<Fr>::new_ref();
659
660 circuit.generate_constraints(cs.clone()).unwrap();
661 cs.finalize();
662 assert!(cs.is_satisfied().unwrap());
663
664 let cs = cs.into_inner().unwrap();
665
666 let r1cs = extract_r1cs::<Fr>(&cs);
667 let (w, x) = extract_w_x::<Fr>(&cs);
668 r1cs.check_relation(&w, &x).unwrap();
669
670 let z = [vec![Fr::rand(rng)], x, w].concat();
671 let (w, u) = prepare_relaxed_witness_instance::<_, Pedersen<Projective>, _>(rng, &r1cs, &z);
672 r1cs.check_relation(&w, &u).unwrap();
673
674 // set new CS for the circuit that checks the RelaxedR1CS of our original circuit
675 let cs = ConstraintSystem::<Fr>::new_ref();
676 // prepare the inputs for our circuit
677 let zVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z)).unwrap();
678 let EVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(w.E)).unwrap();
679 let uVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
680 let r1csVar = R1CSVar::<Fr, Fr, FpVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
681
682 RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
683 assert!(cs.is_satisfied().unwrap());
684 }
685
686 #[test]
687 fn test_relaxed_r1cs_small_gadget_arkworks() {
688 let z_i = vec![Fr::from(3_u32)];
689 let cubic_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
690 let circuit = WrapperCircuit::<Fr, CubicFCircuit<Fr>> {
691 FC: cubic_circuit,
692 z_i: Some(z_i.clone()),
693 z_i1: Some(cubic_circuit.step_native(0, z_i, vec![]).unwrap()),
694 };
695
696 test_relaxed_r1cs_gadget(circuit);
697 }
698
699 struct Sha256TestCircuit<F: PrimeField> {
700 _f: PhantomData<F>,
701 pub x: Vec<u8>,
702 pub y: Vec<u8>,
703 }
704 impl<F: PrimeField> ConstraintSynthesizer<F> for Sha256TestCircuit<F> {
705 fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
706 let x = Vec::<UInt8<F>>::new_witness(cs.clone(), || Ok(self.x))?;
707 let y = Vec::<UInt8<F>>::new_input(cs.clone(), || Ok(self.y))?;
708
709 let unitVar = UnitVar::default();
710 let comp_y = <Sha256Gadget<F> as CRHSchemeGadget<Sha256, F>>::evaluate(&unitVar, &x)?;
711 comp_y.0.enforce_equal(&y)?;
712 Ok(())
713 }
714 }
715 #[test]
716 fn test_relaxed_r1cs_medium_gadget_arkworks() {
717 let x = Fr::from(5_u32).into_bigint().to_bytes_le();
718 let y = <Sha256 as CRHScheme>::evaluate(&(), x.clone()).unwrap();
719
720 let circuit = Sha256TestCircuit::<Fr> {
721 _f: PhantomData,
722 x,
723 y,
724 };
725 test_relaxed_r1cs_gadget(circuit);
726 }
727
728 #[test]
729 fn test_relaxed_r1cs_custom_circuit() {
730 let n_constraints = 10_000;
731 let custom_circuit = CustomFCircuit::<Fr>::new(n_constraints).unwrap();
732 let z_i = vec![Fr::from(5_u32)];
733 let circuit = WrapperCircuit::<Fr, CustomFCircuit<Fr>> {
734 FC: custom_circuit,
735 z_i: Some(z_i.clone()),
736 z_i1: Some(custom_circuit.step_native(0, z_i, vec![]).unwrap()),
737 };
738 test_relaxed_r1cs_gadget(circuit);
739 }
740
741 #[test]
742 fn test_relaxed_r1cs_nonnative_circuit() {
743 let rng = &mut thread_rng();
744
745 let cs = ConstraintSystem::<Fq>::new_ref();
746 // in practice we would use CycleFoldCircuit, but is a very big circuit (when computed
747 // non-natively inside the RelaxedR1CS circuit), so in order to have a short test we use a
748 // custom circuit.
749 let custom_circuit = CustomFCircuit::<Fq>::new(10).unwrap();
750 let z_i = vec![Fq::from(5_u32)];
751 let circuit = WrapperCircuit::<Fq, CustomFCircuit<Fq>> {
752 FC: custom_circuit,
753 z_i: Some(z_i.clone()),
754 z_i1: Some(custom_circuit.step_native(0, z_i, vec![]).unwrap()),
755 };
756 circuit.generate_constraints(cs.clone()).unwrap();
757 cs.finalize();
758 let cs = cs.into_inner().unwrap();
759 let r1cs = extract_r1cs::<Fq>(&cs);
760 let (w, x) = extract_w_x::<Fq>(&cs);
761
762 let z = [vec![Fq::rand(rng)], x, w].concat();
763 let (w, u) =
764 prepare_relaxed_witness_instance::<_, Pedersen<Projective2>, _>(rng, &r1cs, &z);
765
766 // natively
767 let cs = ConstraintSystem::<Fq>::new_ref();
768 let zVar = Vec::<FpVar<Fq>>::new_witness(cs.clone(), || Ok(z.clone())).unwrap();
769 let EVar = Vec::<FpVar<Fq>>::new_witness(cs.clone(), || Ok(w.E.clone())).unwrap();
770 let uVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
771 let r1csVar =
772 R1CSVar::<Fq, Fq, FpVar<Fq>>::new_witness(cs.clone(), || Ok(r1cs.clone())).unwrap();
773 RelaxedR1CSGadget::check_native(r1csVar, EVar, uVar, zVar).unwrap();
774
775 // non-natively
776 let cs = ConstraintSystem::<Fr>::new_ref();
777 let zVar = Vec::new_witness(cs.clone(), || Ok(z)).unwrap();
778 let EVar = Vec::new_witness(cs.clone(), || Ok(w.E)).unwrap();
779 let uVar = NonNativeUintVar::<Fr>::new_witness(cs.clone(), || Ok(u.u)).unwrap();
780 let r1csVar =
781 R1CSVar::<Fq, Fr, NonNativeUintVar<Fr>>::new_witness(cs.clone(), || Ok(r1cs)).unwrap();
782 RelaxedR1CSGadget::check_nonnative(r1csVar, EVar, uVar, zVar).unwrap();
783 }
784
785 #[test]
786 fn test_decider_eth_circuit() {
787 let mut rng = ark_std::test_rng();
788 let poseidon_config = poseidon_canonical_config::<Fr>();
789
790 let F_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
791 let z_0 = vec![Fr::from(3_u32)];
792
793 type N = Nova<
794 Projective,
795 GVar,
796 Projective2,
797 GVar2,
798 CubicFCircuit<Fr>,
799 Pedersen<Projective>,
800 Pedersen<Projective2>,
801 false,
802 >;
803
804 let prep_param = PreprocessorParam::<
805 Projective,
806 Projective2,
807 CubicFCircuit<Fr>,
808 Pedersen<Projective>,
809 Pedersen<Projective2>,
810 false,
811 >::new(poseidon_config, F_circuit);
812 let nova_params = N::preprocess(&mut rng, &prep_param).unwrap();
813
814 // generate a Nova instance and do a step of it
815 let mut nova = N::init(&nova_params, F_circuit, z_0.clone()).unwrap();
816 nova.prove_step(&mut rng, vec![], None).unwrap();
817 let ivc_v = nova.clone();
818 let (running_instance, incoming_instance, cyclefold_instance) = ivc_v.instances();
819 N::verify(
820 nova_params.1, // verifier_params
821 z_0,
822 ivc_v.z_i,
823 Fr::one(),
824 running_instance,
825 incoming_instance,
826 cyclefold_instance,
827 )
828 .unwrap();
829
830 // load the DeciderEthCircuit from the Nova instance
831 let decider_eth_circuit = DeciderEthCircuit::<
832 Projective,
833 GVar,
834 Projective2,
835 GVar2,
836 Pedersen<Projective>,
837 Pedersen<Projective2>,
838 >::from_nova(nova)
839 .unwrap();
840
841 let cs = ConstraintSystem::<Fr>::new_ref();
842
843 // generate the constraints and check that are satisfied by the inputs
844 decider_eth_circuit
845 .generate_constraints(cs.clone())
846 .unwrap();
847 assert!(cs.is_satisfied().unwrap());
848 }
849
850 // checks that the gadget and native implementations of the challenge computation match
851 #[test]
852 fn test_kzg_challenge_gadget() {
853 let mut rng = ark_std::test_rng();
854 let poseidon_config = poseidon_canonical_config::<Fr>();
855 let mut transcript = PoseidonSponge::<Fr>::new(&poseidon_config);
856
857 let U_i = CommittedInstance::<Projective> {
858 cmE: Projective::rand(&mut rng),
859 u: Fr::rand(&mut rng),
860 cmW: Projective::rand(&mut rng),
861 x: vec![Fr::rand(&mut rng); 1],
862 };
863
864 // compute the challenge natively
865 let (challenge_W, challenge_E) =
866 KZGChallengesGadget::<Projective>::get_challenges_native(&mut transcript, U_i.clone());
867
868 let cs = ConstraintSystem::<Fr>::new_ref();
869 let U_iVar =
870 CommittedInstanceVar::<Projective>::new_witness(cs.clone(), || Ok(U_i.clone()))
871 .unwrap();
872 let mut transcript_var = PoseidonSpongeVar::<Fr>::new(cs.clone(), &poseidon_config);
873
874 let (challenge_W_Var, challenge_E_Var) =
875 KZGChallengesGadget::<Projective>::get_challenges_gadget(&mut transcript_var, U_iVar)
876 .unwrap();
877 assert!(cs.is_satisfied().unwrap());
878
879 // check that the natively computed and in-circuit computed hashes match
880 use ark_r1cs_std::R1CSVar;
881 assert_eq!(challenge_W_Var.value().unwrap(), challenge_W);
882 assert_eq!(challenge_E_Var.value().unwrap(), challenge_E);
883 }
884
885 // The test test_polynomial_interpolation is temporary disabled due
886 // https://github.com/privacy-scaling-explorations/sonobe/issues/80
887 // for n<=11 it will work, but for n>11 it will fail with stack overflow.
888 #[ignore]
889 #[test]
890 fn test_polynomial_interpolation() {
891 let mut rng = ark_std::test_rng();
892 let n = 12;
893 let l = 1 << n;
894
895 let v: Vec<Fr> = std::iter::repeat_with(|| Fr::rand(&mut rng))
896 .take(l)
897 .collect();
898 let challenge = Fr::rand(&mut rng);
899
900 use ark_poly::Polynomial;
901 let polynomial = poly_from_vec(v.to_vec()).unwrap();
902 let eval = polynomial.evaluate(&challenge);
903
904 let cs = ConstraintSystem::<Fr>::new_ref();
905 let vVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(v)).unwrap();
906 let challengeVar = FpVar::<Fr>::new_witness(cs.clone(), || Ok(challenge)).unwrap();
907
908 let evalVar = evaluate_gadget::<Fr>(vVar, challengeVar).unwrap();
909
910 use ark_r1cs_std::R1CSVar;
911 assert_eq!(evalVar.value().unwrap(), eval);
912 assert!(cs.is_satisfied().unwrap());
913 }
914}