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