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