arnaucube
arnaucube/sonobePublic Self-hosted repository
sonobe/examples/circom_full_flow.rs
examples/circom_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};
 13
 14use ark_groth16::Groth16;
 15use ark_grumpkin::{constraints::GVar as GVar2, Projective as G2};
 16
 17use std::path::PathBuf;
 18use std::time::Instant;
 19
 20use folding_schemes::{
 21    commitment::{kzg::KZG, pedersen::Pedersen},
 22    folding::{
 23        nova::{
 24            decider_eth::{prepare_calldata, Decider as DeciderEth},
 25            Nova, PreprocessorParam,
 26        },
 27        traits::CommittedInstanceOps,
 28    },
 29    frontend::FCircuit,
 30    transcript::poseidon::poseidon_canonical_config,
 31    Decider, FoldingScheme,
 32};
 33use frontends::circom::CircomFCircuit;
 34use solidity_verifiers::{
 35    evm::{compile_solidity, Evm},
 36    utils::get_function_selector_for_nova_cyclefold_verifier,
 37    verifiers::nova_cyclefold::get_decider_template_for_cyclefold_decider,
 38    NovaCycleFoldVerifierKey,
 39};
 40
 41fn main() {
 42    // set the initial state
 43    let z_0 = vec![Fr::from(3_u32)];
 44
 45    // set the external inputs to be used at each step of the IVC, it has length of 10 since this
 46    // is the number of steps that we will do
 47    let external_inputs = vec![
 48        vec![Fr::from(6u32), Fr::from(7u32)],
 49        vec![Fr::from(8u32), Fr::from(9u32)],
 50        vec![Fr::from(10u32), Fr::from(11u32)],
 51        vec![Fr::from(12u32), Fr::from(13u32)],
 52        vec![Fr::from(14u32), Fr::from(15u32)],
 53        vec![Fr::from(6u32), Fr::from(7u32)],
 54        vec![Fr::from(8u32), Fr::from(9u32)],
 55        vec![Fr::from(10u32), Fr::from(11u32)],
 56        vec![Fr::from(12u32), Fr::from(13u32)],
 57        vec![Fr::from(14u32), Fr::from(15u32)],
 58    ];
 59
 60    // initialize the Circom circuit
 61    let r1cs_path = PathBuf::from("./frontends/src/circom/test_folder/with_external_inputs.r1cs");
 62    let wasm_path = PathBuf::from(
 63        "./frontends/src/circom/test_folder/with_external_inputs_js/with_external_inputs.wasm",
 64    );
 65
 66    let f_circuit_params = (r1cs_path.into(), wasm_path.into(), 1, 2);
 67    let f_circuit = CircomFCircuit::<Fr>::new(f_circuit_params).unwrap();
 68
 69    pub type N =
 70        Nova<G1, GVar, G2, GVar2, CircomFCircuit<Fr>, KZG<'static, Bn254>, Pedersen<G2>, false>;
 71    pub type D = DeciderEth<
 72        G1,
 73        GVar,
 74        G2,
 75        GVar2,
 76        CircomFCircuit<Fr>,
 77        KZG<'static, Bn254>,
 78        Pedersen<G2>,
 79        Groth16<Bn254>,
 80        N,
 81    >;
 82
 83    let poseidon_config = poseidon_canonical_config::<Fr>();
 84    let mut rng = rand::rngs::OsRng;
 85
 86    // prepare the Nova prover & verifier params
 87    let nova_preprocess_params = PreprocessorParam::new(poseidon_config, f_circuit.clone());
 88    let nova_params = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
 89
 90    // initialize the folding scheme engine, in our case we use Nova
 91    let mut nova = N::init(&nova_params, f_circuit.clone(), z_0).unwrap();
 92
 93    // prepare the Decider prover & verifier params
 94    let (decider_pp, decider_vp) =
 95        D::preprocess(&mut rng, nova_params.clone(), nova.clone()).unwrap();
 96
 97    // run n steps of the folding iteration
 98    for (i, external_inputs_at_step) in external_inputs.iter().enumerate() {
 99        let start = Instant::now();
100        nova.prove_step(rng, external_inputs_at_step.clone(), None)
101            .unwrap();
102        println!("Nova::prove_step {}: {:?}", i, start.elapsed());
103    }
104
105    // verify the last IVC proof
106    let ivc_proof = nova.ivc_proof();
107    N::verify(
108        nova_params.1, // Nova's verifier params
109        ivc_proof,
110    )
111    .unwrap();
112
113    let start = Instant::now();
114    let proof = D::prove(rng, decider_pp, nova.clone()).unwrap();
115    println!("generated Decider proof: {:?}", start.elapsed());
116
117    let verified = D::verify(
118        decider_vp.clone(),
119        nova.i,
120        nova.z_0.clone(),
121        nova.z_i.clone(),
122        &nova.U_i.get_commitments(),
123        &nova.u_i.get_commitments(),
124        &proof,
125    )
126    .unwrap();
127    assert!(verified);
128    println!("Decider proof verification: {}", verified);
129
130    // Now, let's generate the Solidity code that verifies this Decider final proof
131    let function_selector =
132        get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1);
133
134    let calldata: Vec<u8> = prepare_calldata(
135        function_selector,
136        nova.i,
137        nova.z_0,
138        nova.z_i,
139        &nova.U_i,
140        &nova.u_i,
141        proof,
142    )
143    .unwrap();
144
145    // prepare the setup params for the solidity verifier
146    let nova_cyclefold_vk = NovaCycleFoldVerifierKey::from((decider_vp, f_circuit.state_len()));
147
148    // generate the solidity code
149    let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk);
150
151    // verify the proof against the solidity code in the EVM
152    let nova_cyclefold_verifier_bytecode = compile_solidity(&decider_solidity_code, "NovaDecider");
153    let mut evm = Evm::default();
154    let verifier_address = evm.create(nova_cyclefold_verifier_bytecode);
155    let (_, output) = evm.call(verifier_address, calldata.clone());
156    assert_eq!(*output.last().unwrap(), 1);
157
158    // save smart contract and the calldata
159    println!("storing nova-verifier.sol and the calldata into files");
160    use std::fs;
161    fs::write(
162        "./examples/nova-verifier.sol",
163        decider_solidity_code.clone(),
164    )
165    .unwrap();
166    fs::write("./examples/solidity-calldata.calldata", calldata.clone()).unwrap();
167    let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone());
168    fs::write("./examples/solidity-calldata.inputs", s.join(",\n")).expect("");
169}