sonobe/examples/sha256.rs
examples/sha256.rsRaw
1#![allow(non_snake_case)]
2#![allow(non_upper_case_globals)]
3#![allow(non_camel_case_types)]
4#![allow(clippy::upper_case_acronyms)]
5
6use ark_crypto_primitives::crh::{
7 sha256::{
8 constraints::{Sha256Gadget, UnitVar},
9 Sha256,
10 },
11 CRHScheme, CRHSchemeGadget,
12};
13use ark_ff::{BigInteger, PrimeField, ToConstraintField};
14use ark_r1cs_std::{fields::fp::FpVar, ToBytesGadget, ToConstraintFieldGadget};
15use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
16use core::marker::PhantomData;
17use std::time::Instant;
18
19use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as Projective};
20use ark_grumpkin::{constraints::GVar as GVar2, Projective as Projective2};
21
22use folding_schemes::commitment::{kzg::KZG, pedersen::Pedersen};
23use folding_schemes::folding::nova::{Nova, PreprocessorParam};
24use folding_schemes::frontend::FCircuit;
25use folding_schemes::transcript::poseidon::poseidon_canonical_config;
26use folding_schemes::{Error, FoldingScheme};
27
28/// This is the circuit that we want to fold, it implements the FCircuit trait.
29/// The parameter z_i denotes the current state, and z_{i+1} denotes the next state which we get by
30/// applying the step.
31/// In this example we set z_i and z_{i+1} to be a single value, but the trait is made to support
32/// arrays, so our state could be an array with different values.
33#[derive(Clone, Copy, Debug)]
34pub struct Sha256FCircuit<F: PrimeField> {
35 _f: PhantomData<F>,
36}
37impl<F: PrimeField> FCircuit<F> for Sha256FCircuit<F> {
38 type Params = ();
39
40 fn new(_params: Self::Params) -> Result<Self, Error> {
41 Ok(Self { _f: PhantomData })
42 }
43 fn state_len(&self) -> usize {
44 1
45 }
46 fn external_inputs_len(&self) -> usize {
47 0
48 }
49
50 /// computes the next state values in place, assigning z_{i+1} into z_i, and computing the new
51 /// z_{i+1}
52 fn step_native(
53 &self,
54 _i: usize,
55 z_i: Vec<F>,
56 _external_inputs: Vec<F>,
57 ) -> Result<Vec<F>, Error> {
58 let out_bytes = Sha256::evaluate(&(), z_i[0].into_bigint().to_bytes_le()).unwrap();
59 let out: Vec<F> = out_bytes.to_field_elements().unwrap();
60
61 Ok(vec![out[0]])
62 }
63
64 /// generates the constraints for the step of F for the given z_i
65 fn generate_step_constraints(
66 &self,
67 _cs: ConstraintSystemRef<F>,
68 _i: usize,
69 z_i: Vec<FpVar<F>>,
70 _external_inputs: Vec<FpVar<F>>,
71 ) -> Result<Vec<FpVar<F>>, SynthesisError> {
72 let unit_var = UnitVar::default();
73 let out_bytes = Sha256Gadget::evaluate(&unit_var, &z_i[0].to_bytes()?)?;
74 let out = out_bytes.0.to_constraint_field()?;
75 Ok(vec![out[0].clone()])
76 }
77}
78
79/// cargo test --example sha256
80#[cfg(test)]
81pub mod tests {
82 use super::*;
83 use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
84 use ark_relations::r1cs::ConstraintSystem;
85
86 // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
87 #[test]
88 fn test_f_circuit() {
89 let cs = ConstraintSystem::<Fr>::new_ref();
90
91 let circuit = Sha256FCircuit::<Fr>::new(()).unwrap();
92 let z_i = vec![Fr::from(1_u32)];
93
94 let z_i1 = circuit.step_native(0, z_i.clone(), vec![]).unwrap();
95
96 let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
97 let computed_z_i1Var = circuit
98 .generate_step_constraints(cs.clone(), 0, z_iVar.clone(), vec![])
99 .unwrap();
100 assert_eq!(computed_z_i1Var.value().unwrap(), z_i1);
101 }
102}
103
104/// cargo run --release --example sha256
105fn main() {
106 let num_steps = 10;
107 let initial_state = vec![Fr::from(1_u32)];
108
109 let F_circuit = Sha256FCircuit::<Fr>::new(()).unwrap();
110
111 /// The idea here is that eventually we could replace the next line chunk that defines the
112 /// `type N = Nova<...>` by using another folding scheme that fulfills the `FoldingScheme`
113 /// trait, and the rest of our code would be working without needing to be updated.
114 type N = Nova<
115 Projective,
116 GVar,
117 Projective2,
118 GVar2,
119 Sha256FCircuit<Fr>,
120 KZG<'static, Bn254>,
121 Pedersen<Projective2>,
122 >;
123
124 let poseidon_config = poseidon_canonical_config::<Fr>();
125 let mut rng = rand::rngs::OsRng;
126
127 println!("Prepare Nova ProverParams & VerifierParams");
128 let nova_preprocess_params = PreprocessorParam::new(poseidon_config, F_circuit);
129 let nova_params = N::preprocess(&mut rng, &nova_preprocess_params).unwrap();
130
131 println!("Initialize FoldingScheme");
132 let mut folding_scheme = N::init(&nova_params, F_circuit, initial_state.clone()).unwrap();
133 // compute a step of the IVC
134 for i in 0..num_steps {
135 let start = Instant::now();
136 folding_scheme.prove_step(rng, vec![], None).unwrap();
137 println!("Nova::prove_step {}: {:?}", i, start.elapsed());
138 }
139
140 let (running_instance, incoming_instance, cyclefold_instance) = folding_scheme.instances();
141
142 println!("Run the Nova's IVC verifier");
143 N::verify(
144 nova_params.1,
145 initial_state,
146 folding_scheme.state(), // latest state
147 Fr::from(num_steps as u32),
148 running_instance,
149 incoming_instance,
150 cyclefold_instance,
151 )
152 .unwrap();
153}