sonobe/folding-schemes/src/folding/circuits/cyclefold.rs
folding-schemes/src/folding/circuits/cyclefold.rsRaw
1/// Contains [CycleFold](https://eprint.iacr.org/2023/1192.pdf) related circuits and functions that
2/// are shared across the different folding schemes
3use ark_crypto_primitives::sponge::{Absorb, CryptographicSponge};
4use ark_ec::{AffineRepr, CurveGroup, Group};
5use ark_ff::{BigInteger, Field, PrimeField};
6use ark_r1cs_std::{
7 alloc::{AllocVar, AllocationMode},
8 boolean::Boolean,
9 eq::EqGadget,
10 fields::fp::FpVar,
11 groups::GroupOpsBounds,
12 prelude::CurveVar,
13 ToConstraintFieldGadget,
14};
15use ark_relations::r1cs::{
16 ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, Namespace, SynthesisError,
17};
18use ark_std::fmt::Debug;
19use ark_std::rand::RngCore;
20use ark_std::Zero;
21use core::{borrow::Borrow, marker::PhantomData};
22
23use super::{nonnative::uint::NonNativeUintVar, CF1, CF2};
24use crate::arith::r1cs::{extract_w_x, R1CS};
25use crate::commitment::CommitmentScheme;
26use crate::constants::NOVA_N_BITS_RO;
27use crate::folding::nova::nifs::NIFS;
28use crate::transcript::{AbsorbNonNative, AbsorbNonNativeGadget, Transcript, TranscriptVar};
29use crate::Error;
30
31/// Re-export the Nova committed instance as `CycleFoldCommittedInstance` and
32/// witness as `CycleFoldWitness`, for clarity and consistency
33pub use crate::folding::nova::{
34 CommittedInstance as CycleFoldCommittedInstance, Witness as CycleFoldWitness,
35};
36
37/// CycleFoldCommittedInstanceVar is the CycleFold CommittedInstance represented
38/// in folding verifier circuit
39#[derive(Debug, Clone)]
40pub struct CycleFoldCommittedInstanceVar<C: CurveGroup, GC: CurveVar<C, CF2<C>>>
41where
42 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
43{
44 pub cmE: GC,
45 pub u: NonNativeUintVar<CF2<C>>,
46 pub cmW: GC,
47 pub x: Vec<NonNativeUintVar<CF2<C>>>,
48}
49impl<C, GC> AllocVar<CycleFoldCommittedInstance<C>, CF2<C>> for CycleFoldCommittedInstanceVar<C, GC>
50where
51 C: CurveGroup,
52 GC: CurveVar<C, CF2<C>>,
53 <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
54 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
55{
56 fn new_variable<T: Borrow<CycleFoldCommittedInstance<C>>>(
57 cs: impl Into<Namespace<CF2<C>>>,
58 f: impl FnOnce() -> Result<T, SynthesisError>,
59 mode: AllocationMode,
60 ) -> Result<Self, SynthesisError> {
61 f().and_then(|val| {
62 let cs = cs.into();
63
64 let cmE = GC::new_variable(cs.clone(), || Ok(val.borrow().cmE), mode)?;
65 let cmW = GC::new_variable(cs.clone(), || Ok(val.borrow().cmW), mode)?;
66 let u = NonNativeUintVar::new_variable(cs.clone(), || Ok(val.borrow().u), mode)?;
67 let x = Vec::new_variable(cs.clone(), || Ok(val.borrow().x.clone()), mode)?;
68
69 Ok(Self { cmE, u, cmW, x })
70 })
71 }
72}
73
74impl<C: CurveGroup> AbsorbNonNative<C::BaseField> for CycleFoldCommittedInstance<C>
75where
76 C::BaseField: PrimeField + Absorb,
77{
78 // Compatible with the in-circuit `CycleFoldCommittedInstanceVar::to_native_sponge_field_elements`
79 fn to_native_sponge_field_elements(&self, dest: &mut Vec<C::BaseField>) {
80 [self.u].to_native_sponge_field_elements(dest);
81 self.x.to_native_sponge_field_elements(dest);
82 let (cmE_x, cmE_y) = match self.cmE.into_affine().xy() {
83 Some((&x, &y)) => (x, y),
84 None => (C::BaseField::zero(), C::BaseField::zero()),
85 };
86 let (cmW_x, cmW_y) = match self.cmW.into_affine().xy() {
87 Some((&x, &y)) => (x, y),
88 None => (C::BaseField::zero(), C::BaseField::zero()),
89 };
90 cmE_x.to_sponge_field_elements(dest);
91 cmE_y.to_sponge_field_elements(dest);
92 cmW_x.to_sponge_field_elements(dest);
93 cmW_y.to_sponge_field_elements(dest);
94 }
95}
96
97impl<C, GC> AbsorbNonNativeGadget<C::BaseField> for CycleFoldCommittedInstanceVar<C, GC>
98where
99 C: CurveGroup,
100 GC: CurveVar<C, CF2<C>> + ToConstraintFieldGadget<CF2<C>>,
101 <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField + Absorb,
102 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
103{
104 /// Extracts the underlying field elements from `CycleFoldCommittedInstanceVar`, in the order
105 /// of `u`, `x`, `cmE.x`, `cmE.y`, `cmW.x`, `cmW.y`, `cmE.is_inf || cmW.is_inf` (|| is for
106 /// concat).
107 fn to_native_sponge_field_elements(&self) -> Result<Vec<FpVar<CF2<C>>>, SynthesisError> {
108 let mut cmE_elems = self.cmE.to_constraint_field()?;
109 let mut cmW_elems = self.cmW.to_constraint_field()?;
110
111 // See `transcript/poseidon.rs: TranscriptVar::absorb_point` for details
112 // why the last element is unnecessary.
113 cmE_elems.pop();
114 cmW_elems.pop();
115
116 Ok([
117 self.u.to_native_sponge_field_elements()?,
118 self.x
119 .iter()
120 .map(|i| i.to_native_sponge_field_elements())
121 .collect::<Result<Vec<_>, _>>()?
122 .concat(),
123 cmE_elems,
124 cmW_elems,
125 ]
126 .concat())
127 }
128}
129
130impl<C: CurveGroup> CycleFoldCommittedInstance<C>
131where
132 <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField + Absorb,
133{
134 /// hash_cyclefold implements the committed instance hash compatible with the
135 /// in-circuit implementation `CycleFoldCommittedInstanceVar::hash`.
136 /// Returns `H(U_i)`, where `U_i` is a `CycleFoldCommittedInstance`.
137 pub fn hash_cyclefold<T: Transcript<C::BaseField>>(
138 &self,
139 sponge: &T,
140 pp_hash: C::BaseField, // public params hash
141 ) -> C::BaseField {
142 let mut sponge = sponge.clone();
143 sponge.absorb(&pp_hash);
144 sponge.absorb_nonnative(self);
145 sponge.squeeze_field_elements(1)[0]
146 }
147}
148
149impl<C, GC> CycleFoldCommittedInstanceVar<C, GC>
150where
151 C: CurveGroup,
152 GC: CurveVar<C, CF2<C>> + ToConstraintFieldGadget<CF2<C>>,
153 <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField + Absorb,
154 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
155{
156 /// hash implements the committed instance hash compatible with the native
157 /// implementation `CycleFoldCommittedInstance::hash_cyclefold`.
158 /// Returns `H(U_i)`, where `U` is a `CycleFoldCommittedInstanceVar`.
159 ///
160 /// Additionally it returns the vector of the field elements from the self
161 /// parameters, so they can be reused in other gadgets without recalculating
162 /// (reconstraining) them.
163 #[allow(clippy::type_complexity)]
164 pub fn hash<S: CryptographicSponge, T: TranscriptVar<CF2<C>, S>>(
165 self,
166 sponge: &T,
167 pp_hash: FpVar<CF2<C>>, // public params hash
168 ) -> Result<(FpVar<CF2<C>>, Vec<FpVar<CF2<C>>>), SynthesisError> {
169 let mut sponge = sponge.clone();
170 let U_vec = self.to_native_sponge_field_elements()?;
171 sponge.absorb(&pp_hash)?;
172 sponge.absorb(&U_vec)?;
173 Ok((sponge.squeeze_field_elements(1)?.pop().unwrap(), U_vec))
174 }
175}
176
177/// CommittedInstanceInCycleFoldVar represents the Nova CommittedInstance in the CycleFold circuit,
178/// where the commitments to E and W (cmW and cmW) from the CommittedInstance on the E2,
179/// represented as native points, which are folded on the auxiliary curve constraints field (E2::Fr
180/// = E1::Fq).
181#[derive(Debug, Clone)]
182pub struct CommittedInstanceInCycleFoldVar<C: CurveGroup, GC: CurveVar<C, CF2<C>>>
183where
184 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
185{
186 _c: PhantomData<C>,
187 pub cmE: GC,
188 pub cmW: GC,
189}
190
191impl<C, GC> AllocVar<CycleFoldCommittedInstance<C>, CF2<C>>
192 for CommittedInstanceInCycleFoldVar<C, GC>
193where
194 C: CurveGroup,
195 GC: CurveVar<C, CF2<C>>,
196 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
197{
198 fn new_variable<T: Borrow<CycleFoldCommittedInstance<C>>>(
199 cs: impl Into<Namespace<CF2<C>>>,
200 f: impl FnOnce() -> Result<T, SynthesisError>,
201 mode: AllocationMode,
202 ) -> Result<Self, SynthesisError> {
203 f().and_then(|val| {
204 let cs = cs.into();
205
206 let cmE = GC::new_variable(cs.clone(), || Ok(val.borrow().cmE), mode)?;
207 let cmW = GC::new_variable(cs.clone(), || Ok(val.borrow().cmW), mode)?;
208
209 Ok(Self {
210 _c: PhantomData,
211 cmE,
212 cmW,
213 })
214 })
215 }
216}
217
218/// This is the gadget used in the AugmentedFCircuit to verify the CycleFold instances folding,
219/// which checks the correct RLC of u,x,cmE,cmW (hence the name containing 'Full', since it checks
220/// all the RLC values, not only the native ones). It assumes that ci2.cmE=0, ci2.u=1.
221pub struct NIFSFullGadget<C: CurveGroup, GC: CurveVar<C, CF2<C>>> {
222 _c: PhantomData<C>,
223 _gc: PhantomData<GC>,
224}
225
226impl<C: CurveGroup, GC: CurveVar<C, CF2<C>>> NIFSFullGadget<C, GC>
227where
228 C: CurveGroup,
229 GC: CurveVar<C, CF2<C>>,
230 <C as ark_ec::CurveGroup>::BaseField: ark_ff::PrimeField,
231 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
232{
233 pub fn fold_committed_instance(
234 r_bits: Vec<Boolean<CF2<C>>>,
235 cmT: GC,
236 ci1: CycleFoldCommittedInstanceVar<C, GC>,
237 // ci2 is assumed to be always with cmE=0, u=1 (checks done previous to this method)
238 ci2: CycleFoldCommittedInstanceVar<C, GC>,
239 ) -> Result<CycleFoldCommittedInstanceVar<C, GC>, SynthesisError> {
240 // r_nonnat is equal to r_bits just that in a different format
241 let r_nonnat = {
242 let mut bits = r_bits.clone();
243 bits.resize(CF1::<C>::MODULUS_BIT_SIZE as usize, Boolean::FALSE);
244 NonNativeUintVar::from(&bits)
245 };
246 Ok(CycleFoldCommittedInstanceVar {
247 cmE: cmT.scalar_mul_le(r_bits.iter())? + ci1.cmE,
248 cmW: ci1.cmW + ci2.cmW.scalar_mul_le(r_bits.iter())?,
249 u: ci1.u.add_no_align(&r_nonnat).modulo::<CF1<C>>()?,
250 x: ci1
251 .x
252 .iter()
253 .zip(ci2.x)
254 .map(|(a, b)| {
255 a.add_no_align(&r_nonnat.mul_no_align(&b)?)
256 .modulo::<CF1<C>>()
257 })
258 .collect::<Result<Vec<_>, _>>()?,
259 })
260 }
261
262 pub fn verify(
263 // assumes that r_bits is equal to r_nonnat just that in a different format
264 r_bits: Vec<Boolean<CF2<C>>>,
265 cmT: GC,
266 ci1: CycleFoldCommittedInstanceVar<C, GC>,
267 // ci2 is assumed to be always with cmE=0, u=1 (checks done previous to this method)
268 ci2: CycleFoldCommittedInstanceVar<C, GC>,
269 ci3: CycleFoldCommittedInstanceVar<C, GC>,
270 ) -> Result<(), SynthesisError> {
271 let ci = Self::fold_committed_instance(r_bits, cmT, ci1, ci2)?;
272
273 ci.cmE.enforce_equal(&ci3.cmE)?;
274 ci.u.enforce_equal_unaligned(&ci3.u)?;
275 ci.cmW.enforce_equal(&ci3.cmW)?;
276 for (x, y) in ci.x.iter().zip(ci3.x.iter()) {
277 x.enforce_equal_unaligned(y)?;
278 }
279
280 Ok(())
281 }
282}
283
284/// CycleFoldChallengeGadget computes the RO challenge used for the CycleFold instances NIFS, it contains a
285/// rust-native and a in-circuit compatible versions.
286pub struct CycleFoldChallengeGadget<C: CurveGroup, GC: CurveVar<C, CF2<C>>> {
287 _c: PhantomData<C>, // Nova's Curve2, the one used for the CycleFold circuit
288 _gc: PhantomData<GC>,
289}
290impl<C, GC> CycleFoldChallengeGadget<C, GC>
291where
292 C: CurveGroup,
293 GC: CurveVar<C, CF2<C>> + ToConstraintFieldGadget<CF2<C>>,
294 <C as CurveGroup>::BaseField: PrimeField,
295 <C as CurveGroup>::BaseField: Absorb,
296 for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
297{
298 pub fn get_challenge_native<T: Transcript<C::BaseField>>(
299 transcript: &mut T,
300 pp_hash: C::BaseField, // public params hash
301 U_i: CycleFoldCommittedInstance<C>,
302 u_i: CycleFoldCommittedInstance<C>,
303 cmT: C,
304 ) -> Vec<bool> {
305 transcript.absorb(&pp_hash);
306 transcript.absorb_nonnative(&U_i);
307 transcript.absorb_nonnative(&u_i);
308 transcript.absorb_point(&cmT);
309 transcript.squeeze_bits(NOVA_N_BITS_RO)
310 }
311
312 // compatible with the native get_challenge_native
313 pub fn get_challenge_gadget<S: CryptographicSponge, T: TranscriptVar<C::BaseField, S>>(
314 transcript: &mut T,
315 pp_hash: FpVar<C::BaseField>, // public params hash
316 U_i_vec: Vec<FpVar<C::BaseField>>,
317 u_i: CycleFoldCommittedInstanceVar<C, GC>,
318 cmT: GC,
319 ) -> Result<Vec<Boolean<C::BaseField>>, SynthesisError> {
320 transcript.absorb(&pp_hash)?;
321 transcript.absorb(&U_i_vec)?;
322 transcript.absorb_nonnative(&u_i)?;
323 transcript.absorb_point(&cmT)?;
324 transcript.squeeze_bits(NOVA_N_BITS_RO)
325 }
326}
327
328pub trait CycleFoldConfig {
329 /// `N_INPUT_POINTS` specifies the number of input points that are folded in
330 /// [`CycleFoldCircuit`] via random linear combinations.
331 const N_INPUT_POINTS: usize;
332 /// `RANDOMNESS_BIT_LENGTH` is the (maximum) bit length of randomness `r`.
333 const RANDOMNESS_BIT_LENGTH: usize;
334 /// `FIELD_CAPACITY` is the maximum number of bits that can be stored in a
335 /// field element.
336 ///
337 /// E.g., given a randomness `r` with `RANDOMNESS_BIT_LENGTH` bits, we need
338 /// `RANDOMNESS_BIT_LENGTH / FIELD_CAPACITY` field elements to represent `r`
339 /// compactly in-circuit.
340 const FIELD_CAPACITY: usize = CF2::<Self::C>::MODULUS_BIT_SIZE as usize - 1;
341
342 /// Public inputs length for the CycleFoldCircuit.
343 /// * For Nova this is: `|[r, p1.x,y, p2.x,y, p3.x,y]|`
344 /// * In general, `|[r * (n_points-1), (p_i.x,y)*n_points, p_folded.x,y]|`.
345 ///
346 /// Thus, `IO_LEN` is:
347 /// `RANDOMNESS_BIT_LENGTH / FIELD_CAPACITY * (N_INPUT_POINTS - 1) + 2 * N_INPUT_POINTS + 2`
348 const IO_LEN: usize = {
349 Self::RANDOMNESS_BIT_LENGTH.div_ceil(Self::FIELD_CAPACITY) * (Self::N_INPUT_POINTS - 1)
350 + 2 * Self::N_INPUT_POINTS
351 + 2
352 };
353
354 type F: Field;
355 type C: CurveGroup<BaseField = Self::F>;
356}
357
358/// CycleFoldCircuit contains the constraints that check the correct fold of the committed
359/// instances from Curve1. Namely, it checks the random linear combinations of the elliptic curve
360/// (Curve1) points of u_i, U_i leading to U_{i+1}
361#[derive(Debug, Clone)]
362pub struct CycleFoldCircuit<CFG: CycleFoldConfig, GC: CurveVar<CFG::C, CFG::F>> {
363 pub _gc: PhantomData<GC>,
364 /// r_bits is a vector containing the r_bits, one for each point except for the first one. They
365 /// are used for the scalar multiplication of the points. The r_bits are the bit
366 /// representation of each power of r (in Fr, while the CycleFoldCircuit is in Fq).
367 pub r_bits: Option<Vec<Vec<bool>>>,
368 /// points to be folded in the CycleFoldCircuit
369 pub points: Option<Vec<CFG::C>>,
370 /// public inputs (cf_u_{i+1}.x)
371 pub x: Option<Vec<CFG::F>>,
372}
373
374impl<CFG: CycleFoldConfig, GC: CurveVar<CFG::C, CFG::F>> CycleFoldCircuit<CFG, GC> {
375 /// n_points indicates the number of points being folded in the CycleFoldCircuit
376 pub fn empty() -> Self {
377 Self {
378 _gc: PhantomData,
379 r_bits: None,
380 points: None,
381 x: None,
382 }
383 }
384}
385
386impl<CFG: CycleFoldConfig, GC: CurveVar<CFG::C, CFG::F>> ConstraintSynthesizer<CFG::F>
387 for CycleFoldCircuit<CFG, GC>
388where
389 GC: ToConstraintFieldGadget<CFG::F>,
390 CFG::F: PrimeField,
391 for<'a> &'a GC: GroupOpsBounds<'a, CFG::C, GC>,
392{
393 fn generate_constraints(self, cs: ConstraintSystemRef<CFG::F>) -> Result<(), SynthesisError> {
394 let r_bits: Vec<Vec<Boolean<CFG::F>>> = self
395 .r_bits
396 // n_points-1, bcs is one for each point except for the first one
397 .unwrap_or(vec![
398 vec![false; CFG::RANDOMNESS_BIT_LENGTH];
399 CFG::N_INPUT_POINTS - 1
400 ])
401 .iter()
402 .map(|r_bits_i| {
403 Vec::<Boolean<CFG::F>>::new_witness(cs.clone(), || Ok(r_bits_i.clone()))
404 })
405 .collect::<Result<_, _>>()?;
406 let points = Vec::<GC>::new_witness(cs.clone(), || {
407 Ok(self
408 .points
409 .unwrap_or(vec![CFG::C::zero(); CFG::N_INPUT_POINTS]))
410 })?;
411
412 #[cfg(test)]
413 {
414 assert_eq!(CFG::N_INPUT_POINTS, points.len());
415 assert_eq!(CFG::N_INPUT_POINTS - 1, r_bits.len());
416 for r_bits_i in &r_bits {
417 assert_eq!(r_bits_i.len(), CFG::RANDOMNESS_BIT_LENGTH);
418 }
419 }
420
421 // Fold the original points of the instances natively in CycleFold.
422 // In Nova,
423 // - for the cmW we're computing: U_i1.cmW = U_i.cmW + r * u_i.cmW
424 // - for the cmE we're computing: U_i1.cmE = U_i.cmE + r * cmT + r^2 * u_i.cmE, where u_i.cmE
425 // is assumed to be 0, so, U_i1.cmE = U_i.cmE + r * cmT
426 let mut p_folded: GC = points[0].clone();
427 // iter over n_points-1 because the first point is not multiplied by r^i (it is multiplied
428 // by r^0=1)
429 for i in 0..CFG::N_INPUT_POINTS - 1 {
430 p_folded += points[i + 1].scalar_mul_le(r_bits[i].iter())?;
431 }
432
433 let x = Vec::<FpVar<CFG::F>>::new_input(cs.clone(), || {
434 Ok(self.x.unwrap_or(vec![CFG::F::zero(); CFG::IO_LEN]))
435 })?;
436 #[cfg(test)]
437 assert_eq!(x.len(), CFG::IO_LEN); // non-constrained sanity check
438
439 // Check that the points coordinates are placed as the public input x:
440 // In Nova, this is: x == [r, p1, p2, p3] (wheere p3 is the p_folded).
441 // In multifolding schemes such as HyperNova, this is:
442 // computed_x = [r_0, r_1, r_2, ..., r_n, p_0, p_1, p_2, ..., p_n, p_folded],
443 // where each p_i is in fact p_i.to_constraint_field()
444 let computed_x: Vec<FpVar<CFG::F>> = r_bits
445 .iter()
446 .map(|r_bits_i| {
447 r_bits_i
448 .chunks(CFG::FIELD_CAPACITY)
449 .map(Boolean::le_bits_to_fp_var)
450 .collect::<Result<Vec<_>, _>>()
451 })
452 .chain(
453 points
454 .iter()
455 .chain(&[p_folded])
456 .map(|p_i| Ok(p_i.to_constraint_field()?[..2].to_vec())),
457 )
458 .collect::<Result<Vec<_>, _>>()?
459 .concat();
460 computed_x.enforce_equal(&x)?;
461
462 Ok(())
463 }
464}
465
466/// Folds the given cyclefold circuit and its instances. This method is abstracted from any folding
467/// scheme struct because it is used both by Nova & HyperNova's CycleFold.
468#[allow(clippy::type_complexity)]
469#[allow(clippy::too_many_arguments)]
470pub fn fold_cyclefold_circuit<CFG, C1, GC1, C2, GC2, CS2, const H: bool>(
471 transcript: &mut impl Transcript<C1::ScalarField>,
472 cf_r1cs: R1CS<C2::ScalarField>,
473 cf_cs_params: CS2::ProverParams,
474 pp_hash: C1::ScalarField, // public params hash
475 cf_W_i: CycleFoldWitness<C2>, // witness of the running instance
476 cf_U_i: CycleFoldCommittedInstance<C2>, // running instance
477 cf_u_i_x: Vec<C2::ScalarField>,
478 cf_circuit: CycleFoldCircuit<CFG, GC1>,
479 mut rng: impl RngCore,
480) -> Result<
481 (
482 CycleFoldWitness<C2>,
483 CycleFoldCommittedInstance<C2>, // u_i
484 CycleFoldWitness<C2>, // W_i1
485 CycleFoldCommittedInstance<C2>, // U_i1
486 C2, // cmT
487 C2::ScalarField, // r_Fq
488 ),
489 Error,
490>
491where
492 CFG: CycleFoldConfig<C = C1, F = CF2<C1>>,
493 C1: CurveGroup,
494 GC1: CurveVar<C1, CF2<C1>> + ToConstraintFieldGadget<CF2<C1>>,
495 C2: CurveGroup,
496 GC2: CurveVar<C2, CF2<C2>> + ToConstraintFieldGadget<CF2<C2>>,
497 CS2: CommitmentScheme<C2, H>,
498 <C1 as CurveGroup>::BaseField: PrimeField,
499 <C2 as CurveGroup>::BaseField: PrimeField,
500 <C1 as Group>::ScalarField: Absorb,
501 <C2 as Group>::ScalarField: Absorb,
502 C1: CurveGroup<BaseField = C2::ScalarField, ScalarField = C2::BaseField>,
503 for<'a> &'a GC1: GroupOpsBounds<'a, C1, GC1>,
504 for<'a> &'a GC2: GroupOpsBounds<'a, C2, GC2>,
505{
506 let cs2 = ConstraintSystem::<C1::BaseField>::new_ref();
507 cf_circuit.generate_constraints(cs2.clone())?;
508
509 let cs2 = cs2.into_inner().ok_or(Error::NoInnerConstraintSystem)?;
510 let (cf_w_i, cf_x_i) = extract_w_x::<C1::BaseField>(&cs2);
511 if cf_x_i != cf_u_i_x {
512 return Err(Error::NotEqual);
513 }
514
515 #[cfg(test)]
516 assert_eq!(cf_x_i.len(), CFG::IO_LEN);
517
518 // fold cyclefold instances
519 let cf_w_i = CycleFoldWitness::<C2>::new::<H>(cf_w_i.clone(), cf_r1cs.A.n_rows, &mut rng);
520 let cf_u_i: CycleFoldCommittedInstance<C2> =
521 cf_w_i.commit::<CS2, H>(&cf_cs_params, cf_x_i.clone())?;
522
523 // compute T* and cmT* for CycleFoldCircuit
524 let (cf_T, cf_cmT) = NIFS::<C2, CS2, H>::compute_cyclefold_cmT(
525 &cf_cs_params,
526 &cf_r1cs,
527 &cf_w_i,
528 &cf_u_i,
529 &cf_W_i,
530 &cf_U_i,
531 )?;
532
533 let cf_r_bits = CycleFoldChallengeGadget::<C2, GC2>::get_challenge_native(
534 transcript,
535 pp_hash,
536 cf_U_i.clone(),
537 cf_u_i.clone(),
538 cf_cmT,
539 );
540 let cf_r_Fq = C1::BaseField::from_bigint(BigInteger::from_bits_le(&cf_r_bits))
541 .expect("cf_r_bits out of bounds");
542
543 let (cf_W_i1, cf_U_i1) = NIFS::<C2, CS2, H>::fold_instances(
544 cf_r_Fq, &cf_W_i, &cf_U_i, &cf_w_i, &cf_u_i, &cf_T, cf_cmT,
545 )?;
546 Ok((cf_w_i, cf_u_i, cf_W_i1, cf_U_i1, cf_cmT, cf_r_Fq))
547}
548
549#[cfg(test)]
550pub mod tests {
551 use ark_bn254::{constraints::GVar, Fq, Fr, G1Projective as Projective};
552 use ark_crypto_primitives::sponge::{
553 constraints::CryptographicSpongeVar,
554 poseidon::{constraints::PoseidonSpongeVar, PoseidonSponge},
555 };
556 use ark_r1cs_std::R1CSVar;
557 use ark_std::UniformRand;
558
559 use super::*;
560 use crate::folding::nova::nifs::tests::prepare_simple_fold_inputs;
561 use crate::transcript::poseidon::poseidon_canonical_config;
562 use crate::utils::get_cm_coordinates;
563
564 struct TestCycleFoldConfig<C: CurveGroup> {
565 _c: PhantomData<C>,
566 }
567
568 impl<C: CurveGroup> CycleFoldConfig for TestCycleFoldConfig<C> {
569 const RANDOMNESS_BIT_LENGTH: usize = NOVA_N_BITS_RO;
570 const N_INPUT_POINTS: usize = 2;
571 type C = C;
572 type F = C::BaseField;
573 }
574
575 #[test]
576 fn test_committed_instance_cyclefold_var() {
577 let mut rng = ark_std::test_rng();
578
579 let ci = CycleFoldCommittedInstance::<Projective> {
580 cmE: Projective::rand(&mut rng),
581 u: Fr::rand(&mut rng),
582 cmW: Projective::rand(&mut rng),
583 x: vec![Fr::rand(&mut rng); 1],
584 };
585
586 // check the instantiation of the CycleFold side:
587 let cs = ConstraintSystem::<Fq>::new_ref();
588 let ciVar =
589 CommittedInstanceInCycleFoldVar::<Projective, GVar>::new_witness(cs.clone(), || {
590 Ok(ci.clone())
591 })
592 .unwrap();
593 assert_eq!(ciVar.cmE.value().unwrap(), ci.cmE);
594 assert_eq!(ciVar.cmW.value().unwrap(), ci.cmW);
595 }
596
597 #[test]
598 fn test_CycleFoldCircuit_constraints() {
599 let (_, _, _, _, ci1, _, ci2, _, ci3, _, cmT, r_bits, _) = prepare_simple_fold_inputs();
600 let r_Fq = Fq::from_bigint(BigInteger::from_bits_le(&r_bits)).unwrap();
601
602 // cs is the Constraint System on the Curve Cycle auxiliary curve constraints field
603 // (E1::Fq=E2::Fr)
604 let cs = ConstraintSystem::<Fq>::new_ref();
605
606 let cfW_u_i_x: Vec<Fq> = [
607 vec![r_Fq],
608 get_cm_coordinates(&ci1.cmW),
609 get_cm_coordinates(&ci2.cmW),
610 get_cm_coordinates(&ci3.cmW),
611 ]
612 .concat();
613 let cfW_circuit = CycleFoldCircuit::<TestCycleFoldConfig<Projective>, GVar> {
614 _gc: PhantomData,
615 r_bits: Some(vec![r_bits.clone()]),
616 points: Some(vec![ci1.clone().cmW, ci2.clone().cmW]),
617 x: Some(cfW_u_i_x.clone()),
618 };
619 cfW_circuit.generate_constraints(cs.clone()).unwrap();
620 assert!(cs.is_satisfied().unwrap());
621
622 // same for E:
623 let cs = ConstraintSystem::<Fq>::new_ref();
624 let cfE_u_i_x = [
625 vec![r_Fq],
626 get_cm_coordinates(&ci1.cmE),
627 get_cm_coordinates(&cmT),
628 get_cm_coordinates(&ci3.cmE),
629 ]
630 .concat();
631 let cfE_circuit = CycleFoldCircuit::<TestCycleFoldConfig<Projective>, GVar> {
632 _gc: PhantomData,
633 r_bits: Some(vec![r_bits.clone()]),
634 points: Some(vec![ci1.clone().cmE, cmT]),
635 x: Some(cfE_u_i_x.clone()),
636 };
637 cfE_circuit.generate_constraints(cs.clone()).unwrap();
638 assert!(cs.is_satisfied().unwrap());
639 }
640
641 #[test]
642 fn test_nifs_full_gadget() {
643 let (_, _, _, _, ci1, _, ci2, _, ci3, _, cmT, r_bits, _) = prepare_simple_fold_inputs();
644
645 let cs = ConstraintSystem::<Fq>::new_ref();
646
647 let r_bitsVar = Vec::<Boolean<Fq>>::new_witness(cs.clone(), || Ok(r_bits)).unwrap();
648
649 let ci1Var =
650 CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
651 Ok(ci1.clone())
652 })
653 .unwrap();
654 let ci2Var =
655 CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
656 Ok(ci2.clone())
657 })
658 .unwrap();
659 let ci3Var =
660 CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
661 Ok(ci3.clone())
662 })
663 .unwrap();
664 let cmTVar = GVar::new_witness(cs.clone(), || Ok(cmT)).unwrap();
665
666 NIFSFullGadget::<Projective, GVar>::verify(r_bitsVar, cmTVar, ci1Var, ci2Var, ci3Var)
667 .unwrap();
668 assert!(cs.is_satisfied().unwrap());
669 }
670
671 #[test]
672 fn test_cyclefold_challenge_gadget() {
673 let mut rng = ark_std::test_rng();
674 let poseidon_config = poseidon_canonical_config::<Fq>();
675 let mut transcript = PoseidonSponge::<Fq>::new(&poseidon_config);
676
677 let u_i = CycleFoldCommittedInstance::<Projective> {
678 cmE: Projective::zero(), // zero on purpose, so we test also the zero point case
679 u: Fr::zero(),
680 cmW: Projective::rand(&mut rng),
681 x: std::iter::repeat_with(|| Fr::rand(&mut rng))
682 .take(TestCycleFoldConfig::<Projective>::IO_LEN)
683 .collect(),
684 };
685 let U_i = CycleFoldCommittedInstance::<Projective> {
686 cmE: Projective::rand(&mut rng),
687 u: Fr::rand(&mut rng),
688 cmW: Projective::rand(&mut rng),
689 x: std::iter::repeat_with(|| Fr::rand(&mut rng))
690 .take(TestCycleFoldConfig::<Projective>::IO_LEN)
691 .collect(),
692 };
693 let cmT = Projective::rand(&mut rng);
694
695 // compute the challenge natively
696 let pp_hash = Fq::from(42u32); // only for test
697 let r_bits = CycleFoldChallengeGadget::<Projective, GVar>::get_challenge_native(
698 &mut transcript,
699 pp_hash,
700 U_i.clone(),
701 u_i.clone(),
702 cmT,
703 );
704
705 let cs = ConstraintSystem::<Fq>::new_ref();
706 let u_iVar =
707 CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
708 Ok(u_i.clone())
709 })
710 .unwrap();
711 let U_iVar =
712 CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
713 Ok(U_i.clone())
714 })
715 .unwrap();
716 let cmTVar = GVar::new_witness(cs.clone(), || Ok(cmT)).unwrap();
717 let mut transcript_var =
718 PoseidonSpongeVar::<Fq>::new(ConstraintSystem::<Fq>::new_ref(), &poseidon_config);
719
720 let pp_hashVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(pp_hash)).unwrap();
721 let r_bitsVar = CycleFoldChallengeGadget::<Projective, GVar>::get_challenge_gadget(
722 &mut transcript_var,
723 pp_hashVar,
724 U_iVar.to_native_sponge_field_elements().unwrap(),
725 u_iVar,
726 cmTVar,
727 )
728 .unwrap();
729 assert!(cs.is_satisfied().unwrap());
730
731 // check that the natively computed and in-circuit computed hashes match
732 let rVar = Boolean::le_bits_to_fp_var(&r_bitsVar).unwrap();
733 let r = Fq::from_bigint(BigInteger::from_bits_le(&r_bits)).unwrap();
734 assert_eq!(rVar.value().unwrap(), r);
735 assert_eq!(r_bitsVar.value().unwrap(), r_bits);
736 }
737
738 #[test]
739 fn test_cyclefold_hash_gadget() {
740 let mut rng = ark_std::test_rng();
741 let poseidon_config = poseidon_canonical_config::<Fq>();
742 let sponge = PoseidonSponge::<Fq>::new(&poseidon_config);
743
744 let U_i = CycleFoldCommittedInstance::<Projective> {
745 cmE: Projective::rand(&mut rng),
746 u: Fr::rand(&mut rng),
747 cmW: Projective::rand(&mut rng),
748 x: std::iter::repeat_with(|| Fr::rand(&mut rng))
749 .take(TestCycleFoldConfig::<Projective>::IO_LEN)
750 .collect(),
751 };
752 let pp_hash = Fq::from(42u32); // only for test
753 let h = U_i.hash_cyclefold(&sponge, pp_hash);
754
755 let cs = ConstraintSystem::<Fq>::new_ref();
756 let U_iVar =
757 CycleFoldCommittedInstanceVar::<Projective, GVar>::new_witness(cs.clone(), || {
758 Ok(U_i.clone())
759 })
760 .unwrap();
761 let pp_hashVar = FpVar::<Fq>::new_witness(cs.clone(), || Ok(pp_hash)).unwrap();
762 let (hVar, _) = U_iVar
763 .hash(
764 &PoseidonSpongeVar::new(cs.clone(), &poseidon_config),
765 pp_hashVar,
766 )
767 .unwrap();
768 hVar.enforce_equal(&FpVar::new_witness(cs.clone(), || Ok(h)).unwrap())
769 .unwrap();
770 assert!(cs.is_satisfied().unwrap());
771 }
772}