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 =
 85        Nova<G1, GVar, G2, GVar2, CubicFCircuit<Fr>, KZG<'static, Bn254>, Pedersen<G2>, false>;
 86    pub type D = DeciderEth<
 87        G1,
 88        GVar,
 89        G2,
 90        GVar2,
 91        CubicFCircuit<Fr>,
 92        KZG<'static, Bn254>,
 93        Pedersen<G2>,
 94        Groth16<Bn254>,
 95        N,
 96    >;
 97
 98    let poseidon_config = poseidon_canonical_config::<Fr>();
 99    let mut rng = rand::rngs::OsRng;
100
101    // prepare the Nova prover & verifier params
102    let nova_preprocess_params = PreprocessorParam::new(poseidon_config.clone(), f_circuit);
103    let nova_params = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
104
105    // initialize the folding scheme engine, in our case we use Nova
106    let mut nova = N::init(&nova_params, f_circuit, z_0).unwrap();
107
108    // prepare the Decider prover & verifier params
109    let (decider_pp, decider_vp) = D::preprocess(&mut rng, nova_params, nova.clone()).unwrap();
110
111    // run n steps of the folding iteration
112    for i in 0..n_steps {
113        let start = Instant::now();
114        nova.prove_step(rng, vec![], None).unwrap();
115        println!("Nova::prove_step {}: {:?}", i, start.elapsed());
116    }
117
118    let start = Instant::now();
119    let proof = D::prove(rng, decider_pp, nova.clone()).unwrap();
120    println!("generated Decider proof: {:?}", start.elapsed());
121
122    let verified = D::verify(
123        decider_vp.clone(),
124        nova.i,
125        nova.z_0.clone(),
126        nova.z_i.clone(),
127        &nova.U_i,
128        &nova.u_i,
129        &proof,
130    )
131    .unwrap();
132    assert!(verified);
133    println!("Decider proof verification: {}", verified);
134
135    // Now, let's generate the Solidity code that verifies this Decider final proof
136    let function_selector =
137        get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1);
138
139    let calldata: Vec<u8> = prepare_calldata(
140        function_selector,
141        nova.i,
142        nova.z_0,
143        nova.z_i,
144        &nova.U_i,
145        &nova.u_i,
146        proof,
147    )
148    .unwrap();
149
150    // prepare the setup params for the solidity verifier
151    let nova_cyclefold_vk = NovaCycleFoldVerifierKey::from((decider_vp, f_circuit.state_len()));
152
153    // generate the solidity code
154    let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk);
155
156    // verify the proof against the solidity code in the EVM
157    let nova_cyclefold_verifier_bytecode = compile_solidity(&decider_solidity_code, "NovaDecider");
158    let mut evm = Evm::default();
159    let verifier_address = evm.create(nova_cyclefold_verifier_bytecode);
160    let (_, output) = evm.call(verifier_address, calldata.clone());
161    assert_eq!(*output.last().unwrap(), 1);
162
163    // save smart contract and the calldata
164    println!("storing nova-verifier.sol and the calldata into files");
165    use std::fs;
166    fs::write(
167        "./examples/nova-verifier.sol",
168        decider_solidity_code.clone(),
169    )
170    .unwrap();
171    fs::write("./examples/solidity-calldata.calldata", calldata.clone()).unwrap();
172    let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone());
173    fs::write("./examples/solidity-calldata.inputs", s.join(",\n")).expect("");
174}