hash-chain-sonobe/src/naive_approach_sha_chain.rs
src/naive_approach_sha_chain.rsRaw
1/// This example does the hash chain but in the naive approach: instead of using folding, it does a
2/// big circuit containing n instantiations of the sha256 constraints.
3
4#[cfg(test)]
5mod tests {
6 use ark_bn254::{Bn254, Fr};
7
8 use ark_groth16::Groth16;
9 use ark_snark::SNARK;
10
11 use ark_ff::PrimeField;
12
13 use std::time::Instant;
14
15 use ark_crypto_primitives::crh::sha256::{constraints::Sha256Gadget, digest::Digest, Sha256};
16 use ark_r1cs_std::fields::fp::FpVar;
17 use ark_r1cs_std::{alloc::AllocVar, eq::EqGadget};
18 use ark_r1cs_std::{bits::uint8::UInt8, boolean::Boolean, ToBitsGadget, ToBytesGadget};
19 use ark_relations::r1cs::{
20 ConstraintSynthesizer, ConstraintSystem, ConstraintSystemRef, SynthesisError,
21 };
22
23 use crate::utils::tests::*;
24
25 /// Test circuit to be folded
26 #[derive(Clone, Debug)]
27 pub struct SHA256ChainCircuit<F: PrimeField, const N: usize, const HASHES_PER_STEP: usize> {
28 z_0: Option<Vec<F>>,
29 z_n: Option<Vec<F>>,
30 }
31 impl<F: PrimeField, const N: usize, const HASHES_PER_STEP: usize> ConstraintSynthesizer<F>
32 for SHA256ChainCircuit<F, N, HASHES_PER_STEP>
33 {
34 fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
35 let z_0 = Vec::<FpVar<F>>::new_witness(cs.clone(), || {
36 Ok(self.z_0.unwrap_or(vec![F::zero()]))
37 })?;
38 let z_n =
39 Vec::<FpVar<F>>::new_input(cs.clone(), || Ok(self.z_n.unwrap_or(vec![F::zero()])))?;
40 let mut z_i: Vec<FpVar<F>> = z_0.clone();
41 for _ in 0..N {
42 let mut b: Vec<UInt8<F>> = z_i
43 .iter()
44 .map(|f| UInt8::<F>::from_bits_le(&f.to_bits_le().unwrap()[..8]))
45 .collect::<Vec<_>>();
46
47 for _ in 0..HASHES_PER_STEP {
48 let mut sha256_var = Sha256Gadget::default();
49 sha256_var.update(&b).unwrap();
50 b = sha256_var.finalize()?.to_bytes()?;
51 }
52
53 // update z_i = z_{i+1}
54 z_i = b
55 .iter()
56 .map(|e| {
57 let bits = e.to_bits_le().unwrap();
58 Boolean::<F>::le_bits_to_fp_var(&bits).unwrap()
59 })
60 .collect();
61 }
62
63 z_i.enforce_equal(&z_n)?;
64 Ok(())
65 }
66 }
67 // compute natively in rust the expected result
68 fn rust_native_result(z_0: Vec<Fr>, n_steps: usize, hashes_per_step: usize) -> Vec<Fr> {
69 let mut z_i: Vec<Fr> = z_0.clone();
70 for _ in 0..n_steps {
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 z_i = bytes_to_f_vec(b.to_vec()).unwrap();
80 }
81 z_i.clone()
82 }
83
84 #[test]
85 fn full_flow() {
86 // set how many iterations of the SHA256ChainCircuit circuit internal loop we want to
87 // compute
88 const N_STEPS: usize = 100;
89 const HASHES_PER_STEP: usize = 10;
90 println!("running the 'naive' SHA256ChainCircuit, with N_STEPS={}, HASHES_PER_STEP={}. Total hashes = {}", N_STEPS, HASHES_PER_STEP, N_STEPS* HASHES_PER_STEP);
91
92 // set the initial state
93 // let z_0_aux: Vec<u32> = vec![0_u32; 32 * 8];
94 let z_0_aux: Vec<u8> = vec![0_u8; 32];
95 let z_0: Vec<Fr> = z_0_aux.iter().map(|v| Fr::from(*v)).collect::<Vec<Fr>>();
96
97 // run the N iterations 'natively' in rust to compute the expected `z_n`
98 let z_n = rust_native_result(z_0.clone(), N_STEPS, HASHES_PER_STEP);
99
100 let circuit = SHA256ChainCircuit::<Fr, N_STEPS, HASHES_PER_STEP> {
101 z_0: Some(z_0),
102 z_n: Some(z_n.clone()),
103 };
104
105 let cs = ConstraintSystem::<Fr>::new_ref();
106 circuit.clone().generate_constraints(cs.clone()).unwrap();
107 println!(
108 "number of constraints of the (naive) SHA256ChainCircuit with N_STEPS*HASHES_PER_STEP={} sha256 hashes in total: {}",
109 N_STEPS * HASHES_PER_STEP,
110 cs.num_constraints()
111 );
112
113 // now let's generate an actual Groth16 proof
114 let mut rng = rand::rngs::OsRng;
115 let (g16_pk, g16_vk) =
116 Groth16::<Bn254>::circuit_specific_setup(circuit.clone(), &mut rng).unwrap();
117
118 let start = Instant::now();
119 let proof = Groth16::<Bn254>::prove(&g16_pk, circuit.clone(), &mut rng).unwrap();
120 println!(
121 "Groth16 proof generation (for the naive SHA256ChainCircuit): {:?}",
122 start.elapsed()
123 );
124
125 let public_inputs = z_n;
126 let valid_proof = Groth16::<Bn254>::verify(&g16_vk, &public_inputs, &proof).unwrap();
127
128 assert!(valid_proof);
129
130 println!("finished running the 'naive' SHA256ChainCircuit, with N_STEPS={}, HASHES_PER_STEP={}. Total hashes = {}", N_STEPS, HASHES_PER_STEP, N_STEPS* HASHES_PER_STEP);
131 }
132}