arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/folding-schemes/src/folding/hypernova/nimfs.rs
folding-schemes/src/folding/hypernova/nimfs.rsRaw
  1use ark_crypto_primitives::sponge::Absorb;
  2use ark_ec::{CurveGroup, Group};
  3use ark_ff::{Field, PrimeField};
  4use ark_poly::univariate::DensePolynomial;
  5use ark_poly::{DenseUVPolynomial, Polynomial};
  6use ark_std::{One, Zero};
  7
  8use super::cccs::{Witness, CCCS};
  9use super::lcccs::LCCCS;
 10use super::utils::{compute_c, compute_g, compute_sigmas_and_thetas};
 11use crate::ccs::CCS;
 12use crate::transcript::Transcript;
 13use crate::utils::hypercube::BooleanHypercube;
 14use crate::utils::sum_check::structs::IOPProof as SumCheckProof;
 15use crate::utils::sum_check::{IOPSumCheck, SumCheck};
 16use crate::utils::virtual_polynomial::VPAuxInfo;
 17use crate::Error;
 18
 19use std::fmt::Debug;
 20use std::marker::PhantomData;
 21
 22/// Proof defines a multifolding proof
 23#[derive(Clone, Debug)]
 24pub struct Proof<C: CurveGroup> {
 25    pub sc_proof: SumCheckProof<C::ScalarField>,
 26    pub sigmas_thetas: SigmasThetas<C::ScalarField>,
 27}
 28
 29#[derive(Clone, Debug)]
 30pub struct SigmasThetas<F: PrimeField>(pub Vec<Vec<F>>, pub Vec<Vec<F>>);
 31
 32#[derive(Debug)]
 33/// Implements the Non-Interactive Multi Folding Scheme described in section 5 of
 34/// [HyperNova](https://eprint.iacr.org/2023/573.pdf)
 35pub struct NIMFS<C: CurveGroup, T: Transcript<C>> {
 36    pub _c: PhantomData<C>,
 37    pub _t: PhantomData<T>,
 38}
 39
 40impl<C: CurveGroup, T: Transcript<C>> NIMFS<C, T>
 41where
 42    <C as Group>::ScalarField: Absorb,
 43{
 44    pub fn fold(
 45        lcccs: &[LCCCS<C>],
 46        cccs: &[CCCS<C>],
 47        sigmas_thetas: &SigmasThetas<C::ScalarField>,
 48        r_x_prime: Vec<C::ScalarField>,
 49        rho: C::ScalarField,
 50    ) -> LCCCS<C> {
 51        let (sigmas, thetas) = (sigmas_thetas.0.clone(), sigmas_thetas.1.clone());
 52        let mut C_folded = C::zero();
 53        let mut u_folded = C::ScalarField::zero();
 54        let mut x_folded: Vec<C::ScalarField> = vec![C::ScalarField::zero(); lcccs[0].x.len()];
 55        let mut v_folded: Vec<C::ScalarField> = vec![C::ScalarField::zero(); sigmas[0].len()];
 56
 57        let mut rho_i = C::ScalarField::one();
 58        for i in 0..(lcccs.len() + cccs.len()) {
 59            let c: C;
 60            let u: C::ScalarField;
 61            let x: Vec<C::ScalarField>;
 62            let v: Vec<C::ScalarField>;
 63            if i < lcccs.len() {
 64                c = lcccs[i].C;
 65                u = lcccs[i].u;
 66                x = lcccs[i].x.clone();
 67                v = sigmas[i].clone();
 68            } else {
 69                c = cccs[i - lcccs.len()].C;
 70                u = C::ScalarField::one();
 71                x = cccs[i - lcccs.len()].x.clone();
 72                v = thetas[i - lcccs.len()].clone();
 73            }
 74
 75            C_folded += c.mul(rho_i);
 76            u_folded += rho_i * u;
 77            x_folded = x_folded
 78                .iter()
 79                .zip(
 80                    x.iter()
 81                        .map(|x_i| *x_i * rho_i)
 82                        .collect::<Vec<C::ScalarField>>(),
 83                )
 84                .map(|(a_i, b_i)| *a_i + b_i)
 85                .collect();
 86
 87            v_folded = v_folded
 88                .iter()
 89                .zip(
 90                    v.iter()
 91                        .map(|x_i| *x_i * rho_i)
 92                        .collect::<Vec<C::ScalarField>>(),
 93                )
 94                .map(|(a_i, b_i)| *a_i + b_i)
 95                .collect();
 96
 97            rho_i *= rho;
 98        }
 99
100        LCCCS::<C> {
101            C: C_folded,
102            u: u_folded,
103            x: x_folded,
104            r_x: r_x_prime,
105            v: v_folded,
106        }
107    }
108
109    pub fn fold_witness(
110        w_lcccs: &[Witness<C::ScalarField>],
111        w_cccs: &[Witness<C::ScalarField>],
112        rho: C::ScalarField,
113    ) -> Witness<C::ScalarField> {
114        let mut w_folded: Vec<C::ScalarField> = vec![C::ScalarField::zero(); w_lcccs[0].w.len()];
115        let mut r_w_folded = C::ScalarField::zero();
116
117        for i in 0..(w_lcccs.len() + w_cccs.len()) {
118            let rho_i = rho.pow([i as u64]);
119            let w: Vec<C::ScalarField>;
120            let r_w: C::ScalarField;
121
122            if i < w_lcccs.len() {
123                w = w_lcccs[i].w.clone();
124                r_w = w_lcccs[i].r_w;
125            } else {
126                w = w_cccs[i - w_lcccs.len()].w.clone();
127                r_w = w_cccs[i - w_lcccs.len()].r_w;
128            }
129
130            w_folded = w_folded
131                .iter()
132                .zip(
133                    w.iter()
134                        .map(|x_i| *x_i * rho_i)
135                        .collect::<Vec<C::ScalarField>>(),
136                )
137                .map(|(a_i, b_i)| *a_i + b_i)
138                .collect();
139
140            r_w_folded += rho_i * r_w;
141        }
142        Witness {
143            w: w_folded,
144            r_w: r_w_folded,
145        }
146    }
147
148    /// Performs the multifolding prover. Given μ LCCCS instances and ν CCS instances, fold them
149    /// into a single LCCCS instance. Since this is the prover, also fold their witness.
150    /// Returns the final folded LCCCS, the folded witness, and the multifolding proof, which
151    /// contains the sumcheck proof and the helper sumcheck claim sigmas and thetas.
152    #[allow(clippy::type_complexity)]
153    pub fn prove(
154        transcript: &mut impl Transcript<C>,
155        ccs: &CCS<C::ScalarField>,
156        running_instances: &[LCCCS<C>],
157        new_instances: &[CCCS<C>],
158        w_lcccs: &[Witness<C::ScalarField>],
159        w_cccs: &[Witness<C::ScalarField>],
160    ) -> Result<(Proof<C>, LCCCS<C>, Witness<C::ScalarField>), Error> {
161        // TODO appends to transcript
162
163        if running_instances.is_empty() {
164            return Err(Error::Empty);
165        }
166        if new_instances.is_empty() {
167            return Err(Error::Empty);
168        }
169
170        // construct the LCCCS z vector from the relaxation factor, public IO and witness
171        // XXX this deserves its own function in LCCCS
172        let mut z_lcccs = Vec::new();
173        for (i, running_instance) in running_instances.iter().enumerate() {
174            let z_1: Vec<C::ScalarField> = [
175                vec![running_instance.u],
176                running_instance.x.clone(),
177                w_lcccs[i].w.to_vec(),
178            ]
179            .concat();
180            z_lcccs.push(z_1);
181        }
182        // construct the CCCS z vector from the public IO and witness
183        let mut z_cccs = Vec::new();
184        for (i, new_instance) in new_instances.iter().enumerate() {
185            let z_2: Vec<C::ScalarField> = [
186                vec![C::ScalarField::one()],
187                new_instance.x.clone(),
188                w_cccs[i].w.to_vec(),
189            ]
190            .concat();
191            z_cccs.push(z_2);
192        }
193
194        // Step 1: Get some challenges
195        let gamma_scalar = C::ScalarField::from_le_bytes_mod_order(b"gamma");
196        let beta_scalar = C::ScalarField::from_le_bytes_mod_order(b"beta");
197        transcript.absorb(&gamma_scalar);
198        let gamma: C::ScalarField = transcript.get_challenge();
199        transcript.absorb(&beta_scalar);
200        let beta: Vec<C::ScalarField> = transcript.get_challenges(ccs.s);
201
202        // Compute g(x)
203        let g = compute_g(ccs, running_instances, &z_lcccs, &z_cccs, gamma, &beta);
204
205        // Step 3: Run the sumcheck prover
206        let sumcheck_proof = IOPSumCheck::<C, T>::prove(&g, transcript)
207            .map_err(|err| Error::SumCheckProveError(err.to_string()))?;
208
209        // Note: The following two "sanity checks" are done for this prototype, in a final version
210        // they should be removed.
211        //
212        // Sanity check 1: evaluate g(x) over x \in {0,1} (the boolean hypercube), and check that
213        // its sum is equal to the extracted_sum from the SumCheck.
214        //////////////////////////////////////////////////////////////////////
215        let mut g_over_bhc = C::ScalarField::zero();
216        for x in BooleanHypercube::new(ccs.s) {
217            g_over_bhc += g.evaluate(&x)?;
218        }
219
220        // note: this is the sum of g(x) over the whole boolean hypercube
221        let extracted_sum = IOPSumCheck::<C, T>::extract_sum(&sumcheck_proof);
222
223        if extracted_sum != g_over_bhc {
224            return Err(Error::NotEqual);
225        }
226        // Sanity check 2: expect \sum v_j * gamma^j to be equal to the sum of g(x) over the
227        // boolean hypercube (and also equal to the extracted_sum from the SumCheck).
228        let mut sum_v_j_gamma = C::ScalarField::zero();
229        for (i, running_instance) in running_instances.iter().enumerate() {
230            for j in 0..running_instance.v.len() {
231                let gamma_j = gamma.pow([(i * ccs.t + j) as u64]);
232                sum_v_j_gamma += running_instance.v[j] * gamma_j;
233            }
234        }
235        if g_over_bhc != sum_v_j_gamma {
236            return Err(Error::NotEqual);
237        }
238        if extracted_sum != sum_v_j_gamma {
239            return Err(Error::NotEqual);
240        }
241        //////////////////////////////////////////////////////////////////////
242
243        // Step 2: dig into the sumcheck and extract r_x_prime
244        let r_x_prime = sumcheck_proof.point.clone();
245
246        // Step 4: compute sigmas and thetas
247        let sigmas_thetas = compute_sigmas_and_thetas(ccs, &z_lcccs, &z_cccs, &r_x_prime);
248
249        // Step 6: Get the folding challenge
250        let rho_scalar = C::ScalarField::from_le_bytes_mod_order(b"rho");
251        transcript.absorb(&rho_scalar);
252        let rho: C::ScalarField = transcript.get_challenge();
253
254        // Step 7: Create the folded instance
255        let folded_lcccs = Self::fold(
256            running_instances,
257            new_instances,
258            &sigmas_thetas,
259            r_x_prime,
260            rho,
261        );
262
263        // Step 8: Fold the witnesses
264        let folded_witness = Self::fold_witness(w_lcccs, w_cccs, rho);
265
266        Ok((
267            Proof::<C> {
268                sc_proof: sumcheck_proof,
269                sigmas_thetas,
270            },
271            folded_lcccs,
272            folded_witness,
273        ))
274    }
275
276    /// Performs the multifolding verifier. Given μ LCCCS instances and ν CCS instances, fold them
277    /// into a single LCCCS instance.
278    /// Returns the folded LCCCS instance.
279    pub fn verify(
280        transcript: &mut impl Transcript<C>,
281        ccs: &CCS<C::ScalarField>,
282        running_instances: &[LCCCS<C>],
283        new_instances: &[CCCS<C>],
284        proof: Proof<C>,
285    ) -> Result<LCCCS<C>, Error> {
286        // TODO appends to transcript
287
288        if running_instances.is_empty() {
289            return Err(Error::Empty);
290        }
291        if new_instances.is_empty() {
292            return Err(Error::Empty);
293        }
294
295        // Step 1: Get some challenges
296        let gamma_scalar = C::ScalarField::from_le_bytes_mod_order(b"gamma");
297        transcript.absorb(&gamma_scalar);
298        let gamma: C::ScalarField = transcript.get_challenge();
299
300        let beta_scalar = C::ScalarField::from_le_bytes_mod_order(b"beta");
301        transcript.absorb(&beta_scalar);
302        let beta: Vec<C::ScalarField> = transcript.get_challenges(ccs.s);
303
304        let vp_aux_info = VPAuxInfo::<C::ScalarField> {
305            max_degree: ccs.d + 1,
306            num_variables: ccs.s,
307            phantom: PhantomData::<C::ScalarField>,
308        };
309
310        // Step 3: Start verifying the sumcheck
311        // First, compute the expected sumcheck sum: \sum gamma^j v_j
312        let mut sum_v_j_gamma = C::ScalarField::zero();
313        for (i, running_instance) in running_instances.iter().enumerate() {
314            for j in 0..running_instance.v.len() {
315                let gamma_j = gamma.pow([(i * ccs.t + j) as u64]);
316                sum_v_j_gamma += running_instance.v[j] * gamma_j;
317            }
318        }
319
320        // Verify the interactive part of the sumcheck
321        let sumcheck_subclaim =
322            IOPSumCheck::<C, T>::verify(sum_v_j_gamma, &proof.sc_proof, &vp_aux_info, transcript)
323                .map_err(|err| Error::SumCheckVerifyError(err.to_string()))?;
324
325        // Step 2: Dig into the sumcheck claim and extract the randomness used
326        let r_x_prime = sumcheck_subclaim.point.clone();
327
328        // Step 5: Finish verifying sumcheck (verify the claim c)
329        let c = compute_c(
330            ccs,
331            &proof.sigmas_thetas,
332            gamma,
333            &beta,
334            &running_instances
335                .iter()
336                .map(|lcccs| lcccs.r_x.clone())
337                .collect(),
338            &r_x_prime,
339        );
340
341        // check that the g(r_x') from the sumcheck proof is equal to the computed c from sigmas&thetas
342        if c != sumcheck_subclaim.expected_evaluation {
343            return Err(Error::NotEqual);
344        }
345
346        // Sanity check: we can also compute g(r_x') from the proof last evaluation value, and
347        // should be equal to the previously obtained values.
348        let g_on_rxprime_from_sumcheck_last_eval =
349            DensePolynomial::from_coefficients_slice(&proof.sc_proof.proofs.last().unwrap().coeffs)
350                .evaluate(r_x_prime.last().unwrap());
351        if g_on_rxprime_from_sumcheck_last_eval != c {
352            return Err(Error::NotEqual);
353        }
354        if g_on_rxprime_from_sumcheck_last_eval != sumcheck_subclaim.expected_evaluation {
355            return Err(Error::NotEqual);
356        }
357
358        // Step 6: Get the folding challenge
359        let rho_scalar = C::ScalarField::from_le_bytes_mod_order(b"rho");
360        transcript.absorb(&rho_scalar);
361        let rho: C::ScalarField = transcript.get_challenge();
362
363        // Step 7: Compute the folded instance
364        Ok(Self::fold(
365            running_instances,
366            new_instances,
367            &proof.sigmas_thetas,
368            r_x_prime,
369            rho,
370        ))
371    }
372}
373
374#[cfg(test)]
375pub mod tests {
376    use super::*;
377    use crate::ccs::tests::{get_test_ccs, get_test_z};
378    use crate::transcript::poseidon::poseidon_canonical_config;
379    use crate::transcript::poseidon::PoseidonTranscript;
380    use ark_std::test_rng;
381    use ark_std::UniformRand;
382
383    use crate::commitment::{pedersen::Pedersen, CommitmentScheme};
384    use ark_pallas::{Fr, Projective};
385
386    #[test]
387    fn test_fold() {
388        let ccs = get_test_ccs();
389        let z1 = get_test_z::<Fr>(3);
390        let z2 = get_test_z::<Fr>(4);
391        ccs.check_relation(&z1).unwrap();
392        ccs.check_relation(&z2).unwrap();
393
394        let mut rng = test_rng();
395        let r_x_prime: Vec<Fr> = (0..ccs.s).map(|_| Fr::rand(&mut rng)).collect();
396
397        let sigmas_thetas =
398            compute_sigmas_and_thetas(&ccs, &[z1.clone()], &[z2.clone()], &r_x_prime);
399
400        let (pedersen_params, _) =
401            Pedersen::<Projective>::setup(&mut rng, ccs.n - ccs.l - 1).unwrap();
402
403        let (lcccs, w1) = ccs.to_lcccs(&mut rng, &pedersen_params, &z1).unwrap();
404        let (cccs, w2) = ccs.to_cccs(&mut rng, &pedersen_params, &z2).unwrap();
405
406        lcccs.check_relation(&pedersen_params, &ccs, &w1).unwrap();
407        cccs.check_relation(&pedersen_params, &ccs, &w2).unwrap();
408
409        let mut rng = test_rng();
410        let rho = Fr::rand(&mut rng);
411
412        let folded = NIMFS::<Projective, PoseidonTranscript<Projective>>::fold(
413            &[lcccs],
414            &[cccs],
415            &sigmas_thetas,
416            r_x_prime,
417            rho,
418        );
419
420        let w_folded =
421            NIMFS::<Projective, PoseidonTranscript<Projective>>::fold_witness(&[w1], &[w2], rho);
422
423        // check lcccs relation
424        folded
425            .check_relation(&pedersen_params, &ccs, &w_folded)
426            .unwrap();
427    }
428
429    /// Perform multifolding of an LCCCS instance with a CCCS instance (as described in the paper)
430    #[test]
431    pub fn test_basic_multifolding() {
432        let mut rng = test_rng();
433
434        // Create a basic CCS circuit
435        let ccs = get_test_ccs::<Fr>();
436        let (pedersen_params, _) =
437            Pedersen::<Projective>::setup(&mut rng, ccs.n - ccs.l - 1).unwrap();
438
439        // Generate a satisfying witness
440        let z_1 = get_test_z(3);
441        // Generate another satisfying witness
442        let z_2 = get_test_z(4);
443
444        // Create the LCCCS instance out of z_1
445        let (running_instance, w1) = ccs.to_lcccs(&mut rng, &pedersen_params, &z_1).unwrap();
446        // Create the CCCS instance out of z_2
447        let (new_instance, w2) = ccs.to_cccs(&mut rng, &pedersen_params, &z_2).unwrap();
448
449        // Prover's transcript
450        let poseidon_config = poseidon_canonical_config::<Fr>();
451        let mut transcript_p: PoseidonTranscript<Projective> =
452            PoseidonTranscript::<Projective>::new(&poseidon_config);
453        transcript_p.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
454
455        // Run the prover side of the multifolding
456        let (proof, folded_lcccs, folded_witness) =
457            NIMFS::<Projective, PoseidonTranscript<Projective>>::prove(
458                &mut transcript_p,
459                &ccs,
460                &[running_instance.clone()],
461                &[new_instance.clone()],
462                &[w1],
463                &[w2],
464            )
465            .unwrap();
466
467        // Verifier's transcript
468        let mut transcript_v: PoseidonTranscript<Projective> =
469            PoseidonTranscript::<Projective>::new(&poseidon_config);
470        transcript_v.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
471
472        // Run the verifier side of the multifolding
473        let folded_lcccs_v = NIMFS::<Projective, PoseidonTranscript<Projective>>::verify(
474            &mut transcript_v,
475            &ccs,
476            &[running_instance.clone()],
477            &[new_instance.clone()],
478            proof,
479        )
480        .unwrap();
481        assert_eq!(folded_lcccs, folded_lcccs_v);
482
483        // Check that the folded LCCCS instance is a valid instance with respect to the folded witness
484        folded_lcccs
485            .check_relation(&pedersen_params, &ccs, &folded_witness)
486            .unwrap();
487    }
488
489    /// Perform multiple steps of multifolding of an LCCCS instance with a CCCS instance
490    #[test]
491    pub fn test_multifolding_two_instances_multiple_steps() {
492        let mut rng = test_rng();
493
494        let ccs = get_test_ccs::<Fr>();
495
496        let (pedersen_params, _) =
497            Pedersen::<Projective>::setup(&mut rng, ccs.n - ccs.l - 1).unwrap();
498
499        // LCCCS witness
500        let z_1 = get_test_z(2);
501        let (mut running_instance, mut w1) =
502            ccs.to_lcccs(&mut rng, &pedersen_params, &z_1).unwrap();
503
504        let poseidon_config = poseidon_canonical_config::<Fr>();
505
506        let mut transcript_p: PoseidonTranscript<Projective> =
507            PoseidonTranscript::<Projective>::new(&poseidon_config);
508        transcript_p.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
509
510        let mut transcript_v: PoseidonTranscript<Projective> =
511            PoseidonTranscript::<Projective>::new(&poseidon_config);
512        transcript_v.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
513
514        let n: usize = 10;
515        for i in 3..n {
516            println!("\niteration: i {}", i); // DBG
517
518            // CCS witness
519            let z_2 = get_test_z(i);
520            println!("z_2 {:?}", z_2); // DBG
521
522            let (new_instance, w2) = ccs.to_cccs(&mut rng, &pedersen_params, &z_2).unwrap();
523
524            // run the prover side of the multifolding
525            let (proof, folded_lcccs, folded_witness) =
526                NIMFS::<Projective, PoseidonTranscript<Projective>>::prove(
527                    &mut transcript_p,
528                    &ccs,
529                    &[running_instance.clone()],
530                    &[new_instance.clone()],
531                    &[w1],
532                    &[w2],
533                )
534                .unwrap();
535
536            // run the verifier side of the multifolding
537            let folded_lcccs_v = NIMFS::<Projective, PoseidonTranscript<Projective>>::verify(
538                &mut transcript_v,
539                &ccs,
540                &[running_instance.clone()],
541                &[new_instance.clone()],
542                proof,
543            )
544            .unwrap();
545            assert_eq!(folded_lcccs, folded_lcccs_v);
546
547            // check that the folded instance with the folded witness holds the LCCCS relation
548            println!("check_relation {}", i);
549            folded_lcccs
550                .check_relation(&pedersen_params, &ccs, &folded_witness)
551                .unwrap();
552
553            running_instance = folded_lcccs;
554            w1 = folded_witness;
555        }
556    }
557
558    /// Test that generates mu>1 and nu>1 instances, and folds them in a single multifolding step.
559    #[test]
560    pub fn test_multifolding_mu_nu_instances() {
561        let mut rng = test_rng();
562
563        // Create a basic CCS circuit
564        let ccs = get_test_ccs::<Fr>();
565        let (pedersen_params, _) =
566            Pedersen::<Projective>::setup(&mut rng, ccs.n - ccs.l - 1).unwrap();
567
568        let mu = 10;
569        let nu = 15;
570
571        // Generate a mu LCCCS & nu CCCS satisfying witness
572        let mut z_lcccs = Vec::new();
573        for i in 0..mu {
574            let z = get_test_z(i + 3);
575            z_lcccs.push(z);
576        }
577        let mut z_cccs = Vec::new();
578        for i in 0..nu {
579            let z = get_test_z(nu + i + 3);
580            z_cccs.push(z);
581        }
582
583        // Create the LCCCS instances out of z_lcccs
584        let mut lcccs_instances = Vec::new();
585        let mut w_lcccs = Vec::new();
586        for z_i in z_lcccs.iter() {
587            let (running_instance, w) = ccs.to_lcccs(&mut rng, &pedersen_params, z_i).unwrap();
588            lcccs_instances.push(running_instance);
589            w_lcccs.push(w);
590        }
591        // Create the CCCS instance out of z_cccs
592        let mut cccs_instances = Vec::new();
593        let mut w_cccs = Vec::new();
594        for z_i in z_cccs.iter() {
595            let (new_instance, w) = ccs.to_cccs(&mut rng, &pedersen_params, z_i).unwrap();
596            cccs_instances.push(new_instance);
597            w_cccs.push(w);
598        }
599
600        // Prover's transcript
601        let poseidon_config = poseidon_canonical_config::<Fr>();
602        let mut transcript_p: PoseidonTranscript<Projective> =
603            PoseidonTranscript::<Projective>::new(&poseidon_config);
604        transcript_p.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
605
606        // Run the prover side of the multifolding
607        let (proof, folded_lcccs, folded_witness) =
608            NIMFS::<Projective, PoseidonTranscript<Projective>>::prove(
609                &mut transcript_p,
610                &ccs,
611                &lcccs_instances,
612                &cccs_instances,
613                &w_lcccs,
614                &w_cccs,
615            )
616            .unwrap();
617
618        // Verifier's transcript
619        let mut transcript_v: PoseidonTranscript<Projective> =
620            PoseidonTranscript::<Projective>::new(&poseidon_config);
621        transcript_v.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
622
623        // Run the verifier side of the multifolding
624        let folded_lcccs_v = NIMFS::<Projective, PoseidonTranscript<Projective>>::verify(
625            &mut transcript_v,
626            &ccs,
627            &lcccs_instances,
628            &cccs_instances,
629            proof,
630        )
631        .unwrap();
632        assert_eq!(folded_lcccs, folded_lcccs_v);
633
634        // Check that the folded LCCCS instance is a valid instance with respect to the folded witness
635        folded_lcccs
636            .check_relation(&pedersen_params, &ccs, &folded_witness)
637            .unwrap();
638    }
639
640    /// Test that generates mu>1 and nu>1 instances, and folds them in a single multifolding step
641    /// and repeats the process doing multiple steps.
642    #[test]
643    pub fn test_multifolding_mu_nu_instances_multiple_steps() {
644        let mut rng = test_rng();
645
646        // Create a basic CCS circuit
647        let ccs = get_test_ccs::<Fr>();
648        let (pedersen_params, _) =
649            Pedersen::<Projective>::setup(&mut rng, ccs.n - ccs.l - 1).unwrap();
650
651        let poseidon_config = poseidon_canonical_config::<Fr>();
652        // Prover's transcript
653        let mut transcript_p: PoseidonTranscript<Projective> =
654            PoseidonTranscript::<Projective>::new(&poseidon_config);
655        transcript_p.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
656
657        // Verifier's transcript
658        let mut transcript_v: PoseidonTranscript<Projective> =
659            PoseidonTranscript::<Projective>::new(&poseidon_config);
660        transcript_v.absorb(&Fr::from_le_bytes_mod_order(b"init init"));
661
662        let n_steps = 3;
663
664        // number of LCCCS & CCCS instances in each multifolding step
665        let mu = 10;
666        let nu = 15;
667
668        // Generate a mu LCCCS & nu CCCS satisfying witness, for each step
669        for step in 0..n_steps {
670            let mut z_lcccs = Vec::new();
671            for i in 0..mu {
672                let z = get_test_z(step + i + 3);
673                z_lcccs.push(z);
674            }
675            let mut z_cccs = Vec::new();
676            for i in 0..nu {
677                let z = get_test_z(nu + i + 3);
678                z_cccs.push(z);
679            }
680
681            // Create the LCCCS instances out of z_lcccs
682            let mut lcccs_instances = Vec::new();
683            let mut w_lcccs = Vec::new();
684            for z_i in z_lcccs.iter() {
685                let (running_instance, w) = ccs.to_lcccs(&mut rng, &pedersen_params, z_i).unwrap();
686                lcccs_instances.push(running_instance);
687                w_lcccs.push(w);
688            }
689            // Create the CCCS instance out of z_cccs
690            let mut cccs_instances = Vec::new();
691            let mut w_cccs = Vec::new();
692            for z_i in z_cccs.iter() {
693                let (new_instance, w) = ccs.to_cccs(&mut rng, &pedersen_params, z_i).unwrap();
694                cccs_instances.push(new_instance);
695                w_cccs.push(w);
696            }
697
698            // Run the prover side of the multifolding
699            let (proof, folded_lcccs, folded_witness) =
700                NIMFS::<Projective, PoseidonTranscript<Projective>>::prove(
701                    &mut transcript_p,
702                    &ccs,
703                    &lcccs_instances,
704                    &cccs_instances,
705                    &w_lcccs,
706                    &w_cccs,
707                )
708                .unwrap();
709
710            // Run the verifier side of the multifolding
711            let folded_lcccs_v = NIMFS::<Projective, PoseidonTranscript<Projective>>::verify(
712                &mut transcript_v,
713                &ccs,
714                &lcccs_instances,
715                &cccs_instances,
716                proof,
717            )
718            .unwrap();
719
720            assert_eq!(folded_lcccs, folded_lcccs_v);
721
722            // Check that the folded LCCCS instance is a valid instance with respect to the folded witness
723            folded_lcccs
724                .check_relation(&pedersen_params, &ccs, &folded_witness)
725                .unwrap();
726        }
727    }
728}