hash-chain-sonobe/src/sha_chain_onchain.rs
src/sha_chain_onchain.rsRaw
1///
2/// This example performs the full flow:
3/// - define the circuit to be folded
4/// - fold the circuit with Nova+CycleFold's IVC
5/// - verify the IVC proof
6/// - generate a DeciderEthCircuit final proof
7/// - generate the Solidity contract that verifies the proof
8/// - verify the proof in the EVM
9///
10
11#[cfg(test)]
12mod tests {
13 use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as G1};
14 use ark_grumpkin::{constraints::GVar as GVar2, Projective as G2};
15
16 use ark_groth16::Groth16;
17
18 use ark_ff::PrimeField;
19
20 use std::time::Instant;
21
22 use ark_crypto_primitives::crh::sha256::{constraints::Sha256Gadget, digest::Digest, Sha256};
23 use ark_r1cs_std::fields::fp::FpVar;
24 use ark_r1cs_std::{bits::uint8::UInt8, boolean::Boolean, ToBitsGadget, ToBytesGadget};
25 use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
26 use std::marker::PhantomData;
27
28 use folding_schemes::{
29 commitment::{kzg::KZG, pedersen::Pedersen},
30 folding::nova::{
31 decider_eth::{prepare_calldata, Decider as DeciderEth},
32 Nova, PreprocessorParam,
33 },
34 frontend::FCircuit,
35 transcript::poseidon::poseidon_canonical_config,
36 Decider, Error, FoldingScheme,
37 };
38 use solidity_verifiers::{
39 utils::get_function_selector_for_nova_cyclefold_verifier,
40 verifiers::nova_cyclefold::get_decider_template_for_cyclefold_decider,
41 NovaCycleFoldVerifierKey,
42 };
43
44 use crate::utils::tests::*;
45
46 /// Test circuit to be folded
47 #[derive(Clone, Copy, Debug)]
48 pub struct SHA256FoldStepCircuit<F: PrimeField, const HASHES_PER_STEP: usize> {
49 _f: PhantomData<F>,
50 }
51 impl<F: PrimeField, const HASHES_PER_STEP: usize> FCircuit<F>
52 for SHA256FoldStepCircuit<F, HASHES_PER_STEP>
53 {
54 type Params = ();
55 fn new(_params: Self::Params) -> Result<Self, Error> {
56 Ok(Self { _f: PhantomData })
57 }
58 fn state_len(&self) -> usize {
59 32
60 }
61 fn external_inputs_len(&self) -> usize {
62 0
63 }
64 fn step_native(
65 &self,
66 _i: usize,
67 z_i: Vec<F>,
68 _external_inputs: Vec<F>,
69 ) -> Result<Vec<F>, Error> {
70 let mut b = f_vec_to_bytes(z_i.to_vec());
71
72 for _ in 0..HASHES_PER_STEP {
73 let mut sha256 = Sha256::default();
74 sha256.update(b);
75 b = sha256.finalize().to_vec();
76 }
77
78 bytes_to_f_vec(b.to_vec()) // z_{i+1}
79 }
80 fn generate_step_constraints(
81 &self,
82 _cs: ConstraintSystemRef<F>,
83 _i: usize,
84 z_i: Vec<FpVar<F>>,
85 _external_inputs: Vec<FpVar<F>>,
86 ) -> Result<Vec<FpVar<F>>, SynthesisError> {
87 let mut b: Vec<UInt8<F>> = z_i
88 .iter()
89 .map(|f| UInt8::<F>::from_bits_le(&f.to_bits_le().unwrap()[..8]))
90 .collect::<Vec<_>>();
91
92 for _ in 0..HASHES_PER_STEP {
93 let mut sha256_var = Sha256Gadget::default();
94 sha256_var.update(&b).unwrap();
95 b = sha256_var.finalize()?.to_bytes()?;
96 }
97
98 let z_i1: Vec<FpVar<F>> = b
99 .iter()
100 .map(|e| {
101 let bits = e.to_bits_le().unwrap();
102 Boolean::<F>::le_bits_to_fp_var(&bits).unwrap()
103 })
104 .collect();
105
106 Ok(z_i1)
107 }
108 }
109
110 #[test]
111 fn full_flow() {
112 // set how many steps of folding we want to compute
113 const N_STEPS: usize = 100;
114 const HASHES_PER_STEP: usize = 10;
115 println!("running Nova folding scheme on SHA256FoldStepCircuit, with N_STEPS={}, HASHES_PER_STEP={}. Total hashes = {}", N_STEPS, HASHES_PER_STEP, N_STEPS* HASHES_PER_STEP);
116
117 // set the initial state
118 // let z_0_aux: Vec<u32> = vec![0_u32; 32 * 8];
119 let z_0_aux: Vec<u8> = vec![0_u8; 32];
120 let z_0: Vec<Fr> = z_0_aux.iter().map(|v| Fr::from(*v)).collect::<Vec<Fr>>();
121
122 let f_circuit = SHA256FoldStepCircuit::<Fr, HASHES_PER_STEP>::new(()).unwrap();
123
124 // ----------------
125 // Sanity check
126 // check that the f_circuit produces valid R1CS constraints
127 use ark_r1cs_std::alloc::AllocVar;
128 use ark_r1cs_std::fields::fp::FpVar;
129 use ark_r1cs_std::R1CSVar;
130 use ark_relations::r1cs::ConstraintSystem;
131 let cs = ConstraintSystem::<Fr>::new_ref();
132 let z_0_var = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_0.clone())).unwrap();
133 let z_1_var = f_circuit
134 .generate_step_constraints(cs.clone(), 1, z_0_var, vec![])
135 .unwrap();
136 // check z_1_var against the native z_1
137 let z_1_native = f_circuit.step_native(1, z_0.clone(), vec![]).unwrap();
138 assert_eq!(z_1_var.value().unwrap(), z_1_native);
139 // check that the constraint system is satisfied
140 assert!(cs.is_satisfied().unwrap());
141 println!(
142 "number of constraints of a single instantiation of the SHA256FoldStepCircuit: {}",
143 cs.num_constraints()
144 );
145 // ----------------
146
147 // define type aliases for the FoldingScheme (FS) and Decider (D), to avoid writting the
148 // whole type each time
149 pub type FS = Nova<
150 G1,
151 GVar,
152 G2,
153 GVar2,
154 SHA256FoldStepCircuit<Fr, HASHES_PER_STEP>,
155 KZG<'static, Bn254>,
156 Pedersen<G2>,
157 false,
158 >;
159 pub type D = DeciderEth<
160 G1,
161 GVar,
162 G2,
163 GVar2,
164 SHA256FoldStepCircuit<Fr, HASHES_PER_STEP>,
165 KZG<'static, Bn254>,
166 Pedersen<G2>,
167 Groth16<Bn254>,
168 FS,
169 >;
170
171 let poseidon_config = poseidon_canonical_config::<Fr>();
172 let mut rng = rand::rngs::OsRng;
173
174 // prepare the Nova prover & verifier params
175 let nova_preprocess_params = PreprocessorParam::new(poseidon_config, f_circuit);
176 let start = Instant::now();
177 let nova_params = FS::preprocess(&mut rng, &nova_preprocess_params).unwrap();
178 let pp_hash = nova_params.1.pp_hash().unwrap();
179 println!("Nova params generated: {:?}", start.elapsed());
180
181 // initialize the folding scheme engine, in our case we use Nova
182 let mut nova = FS::init(&nova_params, f_circuit, z_0.clone()).unwrap();
183
184 // run n steps of the folding iteration
185 let start_full = Instant::now();
186 for _ in 0..N_STEPS {
187 let start = Instant::now();
188 nova.prove_step(rng, vec![], None).unwrap();
189 println!(
190 "Nova::prove_step (sha256) {}: {:?}",
191 nova.i,
192 start.elapsed()
193 );
194 }
195 println!(
196 "Nova's all {} steps time: {:?}",
197 N_STEPS,
198 start_full.elapsed()
199 );
200
201 // ----------------
202 // Sanity check
203 // The following lines contain a sanity check that checks the IVC proof (before going into
204 // the zkSNARK proof)
205 let ivc_proof = nova.ivc_proof();
206 FS::verify(
207 nova_params.1.clone(), // Nova's verifier params
208 ivc_proof,
209 )
210 .unwrap();
211 // ----------------
212
213 // prepare the Decider prover & verifier params
214 let start = Instant::now();
215 let (decider_pp, decider_vp) = D::preprocess(&mut rng, nova_params, nova.clone()).unwrap();
216 println!("Decider params generated: {:?}", start.elapsed());
217
218 let rng = rand::rngs::OsRng;
219 let start = Instant::now();
220 let proof = D::prove(rng, decider_pp, nova.clone()).unwrap();
221 println!("generated Decider proof: {:?}", start.elapsed());
222
223 let verified = D::verify(
224 decider_vp.clone(),
225 nova.i,
226 nova.z_0.clone(),
227 nova.z_i.clone(),
228 &nova.U_i,
229 &nova.u_i,
230 &proof,
231 )
232 .unwrap();
233 assert!(verified);
234 println!("Decider proof verification: {}", verified);
235
236 // generate the Solidity code that verifies this Decider final proof
237 let function_selector =
238 get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1);
239
240 let calldata: Vec<u8> = prepare_calldata(
241 function_selector,
242 pp_hash,
243 nova.i,
244 nova.z_0,
245 nova.z_i,
246 &nova.U_i,
247 &nova.u_i,
248 proof,
249 )
250 .unwrap();
251
252 // prepare the setup params for the solidity verifier
253 let nova_cyclefold_vk = NovaCycleFoldVerifierKey::from((decider_vp, f_circuit.state_len()));
254
255 // generate the solidity code
256 let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk);
257
258 /*
259 * Note: since we're proving the SHA256 (ie. 32 byte size, 256 bits), the number of inputs
260 * is too big for the contract. In a real world use case we would convert the binary
261 * representation into a couple of field elements which would be inputs of the Decider
262 * circuit, and in-circuit we would obtain the binary representation to be used for the
263 * final proof check.
264 *
265 * The following code is commented out for that reason.
266 // verify the proof against the solidity code in the EVM
267 use solidity_verifiers::evm::{compile_solidity, Evm};
268 let nova_cyclefold_verifier_bytecode =
269 compile_solidity(&decider_solidity_code, "NovaDecider");
270 let mut evm = Evm::default();
271 let verifier_address = evm.create(nova_cyclefold_verifier_bytecode);
272 let (_, output) = evm.call(verifier_address, calldata.clone());
273 assert_eq!(*output.last().unwrap(), 1);
274 */
275
276 // save smart contract and the calldata
277 println!("storing nova-verifier.sol and the calldata into files");
278 use std::fs;
279 fs::create_dir_all("./solidity").unwrap();
280 fs::write(
281 "./solidity/nova-verifier.sol",
282 decider_solidity_code.clone(),
283 )
284 .unwrap();
285 fs::write("./solidity/solidity-calldata.calldata", calldata.clone()).unwrap();
286 let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone());
287 fs::write("./solidity/solidity-calldata.inputs", s.join(",\n")).expect("");
288 }
289}