-
Notifications
You must be signed in to change notification settings - Fork 203
/
Copy pathsha256.rs
193 lines (168 loc) · 5.34 KB
/
sha256.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Benchmarks Nova's prover for proving SHA-256 with varying sized messages.
//! We run a single step with the step performing the entire computation.
//! This code invokes a hand-written SHA-256 gadget from bellman/bellperson.
//! It also uses code from bellman/bellperson to compare circuit-generated digest with sha2 crate's output
#![allow(non_snake_case)]
use core::{marker::PhantomData, time::Duration};
use criterion::*;
use ff::{PrimeField, PrimeFieldBits};
use nova_snark::{
frontend::{
num::{AllocatedNum, Num},
sha256, AllocatedBit, Assignment, Boolean, ConstraintSystem, SynthesisError,
},
nova::{PublicParams, RecursiveSNARK},
provider::{Bn256EngineKZG, GrumpkinEngine},
traits::{
circuit::{StepCircuit, TrivialCircuit},
snark::default_ck_hint,
Engine,
},
};
use sha2::{Digest, Sha256};
type E1 = Bn256EngineKZG;
type E2 = GrumpkinEngine;
#[derive(Clone, Debug)]
struct Sha256Circuit<Scalar: PrimeField> {
preimage: Vec<u8>,
_p: PhantomData<Scalar>,
}
impl<Scalar: PrimeField + PrimeFieldBits> Sha256Circuit<Scalar> {
pub fn new(preimage: Vec<u8>) -> Self {
Self {
preimage,
_p: PhantomData,
}
}
}
impl<Scalar: PrimeField + PrimeFieldBits> StepCircuit<Scalar> for Sha256Circuit<Scalar> {
fn arity(&self) -> usize {
1
}
fn synthesize<CS: ConstraintSystem<Scalar>>(
&self,
cs: &mut CS,
_z: &[AllocatedNum<Scalar>],
) -> Result<Vec<AllocatedNum<Scalar>>, SynthesisError> {
let mut z_out: Vec<AllocatedNum<Scalar>> = Vec::new();
let bit_values: Vec<_> = self
.preimage
.clone()
.into_iter()
.flat_map(|byte| (0..8).map(move |i| (byte >> i) & 1u8 == 1u8))
.map(Some)
.collect();
assert_eq!(bit_values.len(), self.preimage.len() * 8);
let preimage_bits = bit_values
.into_iter()
.enumerate()
.map(|(i, b)| AllocatedBit::alloc(cs.namespace(|| format!("preimage bit {i}")), b))
.map(|b| b.map(Boolean::from))
.collect::<Result<Vec<_>, _>>()?;
let hash_bits = sha256(cs.namespace(|| "sha256"), &preimage_bits)?;
for (i, hash_bits) in hash_bits.chunks(256_usize).enumerate() {
let mut num = Num::<Scalar>::zero();
let mut coeff = Scalar::ONE;
for bit in hash_bits {
num = num.add_bool_with_coeff(CS::one(), bit, coeff);
coeff = coeff.double();
}
let hash = AllocatedNum::alloc(cs.namespace(|| format!("input {i}")), || {
Ok(*num.get_value().get()?)
})?;
// num * 1 = hash
cs.enforce(
|| format!("packing constraint {i}"),
|_| num.lc(Scalar::ONE),
|lc| lc + CS::one(),
|lc| lc + hash.get_variable(),
);
z_out.push(hash);
}
// sanity check with the hasher
let mut hasher = Sha256::new();
hasher.update(&self.preimage);
let hash_result = hasher.finalize();
let mut s = hash_result
.iter()
.flat_map(|&byte| (0..8).rev().map(move |i| (byte >> i) & 1u8 == 1u8));
for b in hash_bits {
match b {
Boolean::Is(b) => {
assert!(s.next().unwrap() == b.get_value().unwrap());
}
Boolean::Not(b) => {
assert!(s.next().unwrap() != b.get_value().unwrap());
}
Boolean::Constant(_b) => {
panic!("Can't reach here")
}
}
}
Ok(z_out)
}
}
type C1 = Sha256Circuit<<E1 as Engine>::Scalar>;
type C2 = TrivialCircuit<<E2 as Engine>::Scalar>;
criterion_group! {
name = recursive_snark;
config = Criterion::default().warm_up_time(Duration::from_millis(3000));
targets = bench_recursive_snark
}
criterion_main!(recursive_snark);
fn bench_recursive_snark(c: &mut Criterion) {
// Test vectors
let circuits = vec![
Sha256Circuit::new(vec![0u8; 1 << 6]),
Sha256Circuit::new(vec![0u8; 1 << 7]),
Sha256Circuit::new(vec![0u8; 1 << 8]),
Sha256Circuit::new(vec![0u8; 1 << 9]),
Sha256Circuit::new(vec![0u8; 1 << 10]),
Sha256Circuit::new(vec![0u8; 1 << 11]),
Sha256Circuit::new(vec![0u8; 1 << 12]),
Sha256Circuit::new(vec![0u8; 1 << 13]),
Sha256Circuit::new(vec![0u8; 1 << 14]),
Sha256Circuit::new(vec![0u8; 1 << 15]),
Sha256Circuit::new(vec![0u8; 1 << 16]),
];
for circuit_primary in circuits {
let mut group = c.benchmark_group(format!(
"NovaProve-Sha256-message-len-{}",
circuit_primary.preimage.len()
));
group.sample_size(10);
// Produce public parameters
let ttc = TrivialCircuit::default();
let pp = PublicParams::<E1, E2, C1, C2>::setup(
&circuit_primary,
&ttc,
&*default_ck_hint(),
&*default_ck_hint(),
)
.unwrap();
let circuit_secondary = TrivialCircuit::default();
let z0_primary = vec![<E1 as Engine>::Scalar::from(2u64)];
let z0_secondary = vec![<E2 as Engine>::Scalar::from(2u64)];
group.bench_function("Prove", |b| {
b.iter(|| {
let mut recursive_snark = RecursiveSNARK::new(
black_box(&pp),
black_box(&circuit_primary),
black_box(&circuit_secondary),
black_box(&z0_primary),
black_box(&z0_secondary),
)
.unwrap();
// produce a recursive SNARK for a step of the recursion
assert!(recursive_snark
.prove_step(
black_box(&pp),
black_box(&circuit_primary),
black_box(&circuit_secondary),
)
.is_ok());
})
});
group.finish();
}
}