arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/examples/full_flow.rs
examples/full_flow.rsRaw
  1#![allow(non_snake_case)]
  2#![allow(non_camel_case_types)]
  3#![allow(clippy::upper_case_acronyms)]
  4///
  5/// This example performs the full flow:
  6/// - define the circuit to be folded
  7/// - fold the circuit with Nova+CycleFold's IVC
  8/// - generate a DeciderEthCircuit final proof
  9/// - generate the Solidity contract that verifies the proof
 10/// - verify the proof in the EVM
 11///
 12use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as G1};
 13use ark_ff::PrimeField;
 14use ark_groth16::Groth16;
 15use ark_grumpkin::{constraints::GVar as GVar2, Projective as G2};
 16use ark_r1cs_std::alloc::AllocVar;
 17use ark_r1cs_std::fields::fp::FpVar;
 18use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
 19use std::marker::PhantomData;
 20use std::time::Instant;
 21
 22use folding_schemes::{
 23    commitment::{kzg::KZG, pedersen::Pedersen},
 24    folding::nova::{
 25        decider_eth::{prepare_calldata, Decider as DeciderEth},
 26        Nova, PreprocessorParam,
 27    },
 28    frontend::FCircuit,
 29    transcript::poseidon::poseidon_canonical_config,
 30    Decider, Error, FoldingScheme,
 31};
 32use solidity_verifiers::{
 33    evm::{compile_solidity, Evm},
 34    utils::get_function_selector_for_nova_cyclefold_verifier,
 35    verifiers::nova_cyclefold::get_decider_template_for_cyclefold_decider,
 36    NovaCycleFoldVerifierKey,
 37};
 38
 39/// Test circuit to be folded
 40#[derive(Clone, Copy, Debug)]
 41pub struct CubicFCircuit<F: PrimeField> {
 42    _f: PhantomData<F>,
 43}
 44impl<F: PrimeField> FCircuit<F> for CubicFCircuit<F> {
 45    type Params = ();
 46    fn new(_params: Self::Params) -> Result<Self, Error> {
 47        Ok(Self { _f: PhantomData })
 48    }
 49    fn state_len(&self) -> usize {
 50        1
 51    }
 52    fn external_inputs_len(&self) -> usize {
 53        0
 54    }
 55    fn step_native(
 56        &self,
 57        _i: usize,
 58        z_i: Vec<F>,
 59        _external_inputs: Vec<F>,
 60    ) -> Result<Vec<F>, Error> {
 61        Ok(vec![z_i[0] * z_i[0] * z_i[0] + z_i[0] + F::from(5_u32)])
 62    }
 63    fn generate_step_constraints(
 64        &self,
 65        cs: ConstraintSystemRef<F>,
 66        _i: usize,
 67        z_i: Vec<FpVar<F>>,
 68        _external_inputs: Vec<FpVar<F>>,
 69    ) -> Result<Vec<FpVar<F>>, SynthesisError> {
 70        let five = FpVar::<F>::new_constant(cs.clone(), F::from(5u32))?;
 71        let z_i = z_i[0].clone();
 72
 73        Ok(vec![&z_i * &z_i * &z_i + &z_i + &five])
 74    }
 75}
 76
 77fn main() {
 78    let n_steps = 10;
 79    // set the initial state
 80    let z_0 = vec![Fr::from(3_u32)];
 81
 82    let f_circuit = CubicFCircuit::<Fr>::new(()).unwrap();
 83
 84    pub type N = Nova<G1, GVar, G2, GVar2, CubicFCircuit<Fr>, KZG<'static, Bn254>, Pedersen<G2>>;
 85    pub type D = DeciderEth<
 86        G1,
 87        GVar,
 88        G2,
 89        GVar2,
 90        CubicFCircuit<Fr>,
 91        KZG<'static, Bn254>,
 92        Pedersen<G2>,
 93        Groth16<Bn254>,
 94        N,
 95    >;
 96
 97    let poseidon_config = poseidon_canonical_config::<Fr>();
 98    let mut rng = rand::rngs::OsRng;
 99
100    // prepare the Nova prover & verifier params
101    let nova_preprocess_params = PreprocessorParam::new(poseidon_config.clone(), f_circuit);
102    let (fs_pp, fs_vp) = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
103
104    // initialize the folding scheme engine, in our case we use Nova
105    let mut nova = N::init(&fs_pp, f_circuit, z_0).unwrap();
106
107    // prepare the Decider prover & verifier params
108    let (decider_pp, decider_vp) = D::preprocess(&mut rng, &(fs_pp, fs_vp), nova.clone()).unwrap();
109
110    // run n steps of the folding iteration
111    for i in 0..n_steps {
112        let start = Instant::now();
113        nova.prove_step(rng, vec![]).unwrap();
114        println!("Nova::prove_step {}: {:?}", i, start.elapsed());
115    }
116
117    let start = Instant::now();
118    let proof = D::prove(rng, decider_pp, nova.clone()).unwrap();
119    println!("generated Decider proof: {:?}", start.elapsed());
120
121    let verified = D::verify(
122        decider_vp.clone(),
123        nova.i,
124        nova.z_0.clone(),
125        nova.z_i.clone(),
126        &nova.U_i,
127        &nova.u_i,
128        &proof,
129    )
130    .unwrap();
131    assert!(verified);
132    println!("Decider proof verification: {}", verified);
133
134    // Now, let's generate the Solidity code that verifies this Decider final proof
135    let function_selector =
136        get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1);
137
138    let calldata: Vec<u8> = prepare_calldata(
139        function_selector,
140        nova.i,
141        nova.z_0,
142        nova.z_i,
143        &nova.U_i,
144        &nova.u_i,
145        proof,
146    )
147    .unwrap();
148
149    // prepare the setup params for the solidity verifier
150    let nova_cyclefold_vk = NovaCycleFoldVerifierKey::from((decider_vp, f_circuit.state_len()));
151
152    // generate the solidity code
153    let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk);
154
155    // verify the proof against the solidity code in the EVM
156    let nova_cyclefold_verifier_bytecode = compile_solidity(&decider_solidity_code, "NovaDecider");
157    let mut evm = Evm::default();
158    let verifier_address = evm.create(nova_cyclefold_verifier_bytecode);
159    let (_, output) = evm.call(verifier_address, calldata.clone());
160    assert_eq!(*output.last().unwrap(), 1);
161
162    // save smart contract and the calldata
163    println!("storing nova-verifier.sol and the calldata into files");
164    use std::fs;
165    fs::write(
166        "./examples/nova-verifier.sol",
167        decider_solidity_code.clone(),
168    )
169    .unwrap();
170    fs::write("./examples/solidity-calldata.calldata", calldata.clone()).unwrap();
171    let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone());
172    fs::write("./examples/solidity-calldata.inputs", s.join(",\n")).expect("");
173}