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