arnaucube
arnaucube/hash-chain-sonobePublic Self-hosted repository
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 for the FoldingScheme (FS) and Decider (D), to avoid writting the
149        // whole type each time
150        pub type FS = Nova<
151            G1,
152            GVar,
153            G2,
154            GVar2,
155            SHA256FoldStepCircuit<Fr, HASHES_PER_STEP>,
156            KZG<'static, Bn254>,
157            Pedersen<G2>,
158            false,
159        >;
160        pub type D = DeciderEth<
161            G1,
162            GVar,
163            G2,
164            GVar2,
165            SHA256FoldStepCircuit<Fr, HASHES_PER_STEP>,
166            KZG<'static, Bn254>,
167            Pedersen<G2>,
168            Groth16<Bn254>,
169            FS,
170        >;
171
172        let poseidon_config = poseidon_canonical_config::<Fr>();
173        let mut rng = rand::rngs::OsRng;
174
175        // prepare the Nova prover & verifier params
176        let nova_preprocess_params = PreprocessorParam::new(poseidon_config, f_circuit);
177        let start = Instant::now();
178        let nova_params = FS::preprocess(&mut rng, &nova_preprocess_params).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 (running_instance, incoming_instance, cyclefold_instance) = nova.instances();
206        FS::verify(
207            nova_params.1.clone(), // Nova's verifier params
208            z_0,
209            nova.z_i.clone(),
210            nova.i,
211            running_instance,
212            incoming_instance,
213            cyclefold_instance,
214        )
215        .unwrap();
216        // ----------------
217
218        // prepare the Decider prover & verifier params
219        let start = Instant::now();
220        let (decider_pp, decider_vp) = D::preprocess(&mut rng, &nova_params, nova.clone()).unwrap();
221        println!("Decider params generated: {:?}", start.elapsed());
222
223        let rng = rand::rngs::OsRng;
224        let start = Instant::now();
225        let proof = D::prove(rng, decider_pp, nova.clone()).unwrap();
226        println!("generated Decider proof: {:?}", start.elapsed());
227
228        let verified = D::verify(
229            decider_vp.clone(),
230            nova.i,
231            nova.z_0.clone(),
232            nova.z_i.clone(),
233            &nova.U_i,
234            &nova.u_i,
235            &proof,
236        )
237        .unwrap();
238        assert!(verified);
239        println!("Decider proof verification: {}", verified);
240
241        // generate the Solidity code that verifies this Decider final proof
242        let function_selector =
243            get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1);
244
245        let calldata: Vec<u8> = prepare_calldata(
246            function_selector,
247            nova.i,
248            nova.z_0,
249            nova.z_i,
250            &nova.U_i,
251            &nova.u_i,
252            proof,
253        )
254        .unwrap();
255
256        // prepare the setup params for the solidity verifier
257        let nova_cyclefold_vk = NovaCycleFoldVerifierKey::from((decider_vp, f_circuit.state_len()));
258
259        // generate the solidity code
260        let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk);
261
262        /*
263         * Note: since we're proving the SHA256 (ie. 32 byte size, 256 bits), the number of inputs
264         * is too big for the contract. In a real world use case we would convert the binary
265         * representation into a couple of field elements which would be inputs of the Decider
266         * circuit, and in-circuit we would obtain the binary representation to be used for the
267         * final proof check.
268         *
269         * The following code is commented out for that reason.
270        // verify the proof against the solidity code in the EVM
271        use solidity_verifiers::evm::{compile_solidity, Evm};
272        let nova_cyclefold_verifier_bytecode =
273            compile_solidity(&decider_solidity_code, "NovaDecider");
274        let mut evm = Evm::default();
275        let verifier_address = evm.create(nova_cyclefold_verifier_bytecode);
276        let (_, output) = evm.call(verifier_address, calldata.clone());
277        assert_eq!(*output.last().unwrap(), 1);
278         */
279
280        // save smart contract and the calldata
281        println!("storing nova-verifier.sol and the calldata into files");
282        use std::fs;
283        fs::create_dir_all("./solidity").unwrap();
284        fs::write(
285            "./solidity/nova-verifier.sol",
286            decider_solidity_code.clone(),
287        )
288        .unwrap();
289        fs::write("./solidity/solidity-calldata.calldata", calldata.clone()).unwrap();
290        let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone());
291        fs::write("./solidity/solidity-calldata.inputs", s.join(",\n")).expect("");
292    }
293}