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