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