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