forked from arkworks-rs/groth16
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mimc.rs
229 lines (188 loc) · 6.96 KB
/
mimc.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#![warn(unused)]
#![deny(
trivial_casts,
trivial_numeric_casts,
variant_size_differences,
stable_features,
non_shorthand_field_patterns,
renamed_and_removed_lints,
unsafe_code
)]
use ark_crypto_primitives::snark::{CircuitSpecificSetupSNARK, SNARK};
// For randomness (during paramgen and proof generation)
use ark_std::rand::{Rng, RngCore, SeedableRng};
// For benchmarking
use std::time::{Duration, Instant};
// Bring in some tools for using pairing-friendly curves
// We're going to use the BLS12-377 pairing-friendly elliptic curve.
use ark_bls12_377::{Bls12_377, Fr};
use ark_ff::Field;
use ark_std::test_rng;
// We'll use these interfaces to construct our circuit.
use ark_relations::{
lc, ns,
r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError, Variable},
};
const MIMC_ROUNDS: usize = 322;
/// This is an implementation of MiMC, specifically a
/// variant named `LongsightF322p3` for BLS12-377.
/// See http://eprint.iacr.org/2016/492 for more
/// information about this construction.
///
/// ```
/// function LongsightF322p3(xL ⦂ Fp, xR ⦂ Fp) {
/// for i from 0 up to 321 {
/// xL, xR := xR + (xL + Ci)^3, xL
/// }
/// return xL
/// }
/// ```
fn mimc<F: Field>(mut xl: F, mut xr: F, constants: &[F]) -> F {
assert_eq!(constants.len(), MIMC_ROUNDS);
for i in 0..MIMC_ROUNDS {
let mut tmp1 = xl;
tmp1.add_assign(&constants[i]);
let mut tmp2 = tmp1;
tmp2.square_in_place();
tmp2.mul_assign(&tmp1);
tmp2.add_assign(&xr);
xr = xl;
xl = tmp2;
}
xl
}
/// This is our demo circuit for proving knowledge of the
/// preimage of a MiMC hash invocation.
struct MiMCDemo<'a, F: Field> {
xl: Option<F>,
xr: Option<F>,
constants: &'a [F],
}
/// Our demo circuit implements this `Circuit` trait which
/// is used during paramgen and proving in order to
/// synthesize the constraint system.
impl<'a, F: Field> ConstraintSynthesizer<F> for MiMCDemo<'a, F> {
fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
assert_eq!(self.constants.len(), MIMC_ROUNDS);
// Allocate the first component of the preimage.
let mut xl_value = self.xl;
let mut xl =
cs.new_witness_variable(|| xl_value.ok_or(SynthesisError::AssignmentMissing))?;
// Allocate the second component of the preimage.
let mut xr_value = self.xr;
let mut xr =
cs.new_witness_variable(|| xr_value.ok_or(SynthesisError::AssignmentMissing))?;
for i in 0..MIMC_ROUNDS {
// xL, xR := xR + (xL + Ci)^3, xL
let ns = ns!(cs, "round");
let cs = ns.cs();
// tmp = (xL + Ci)^2
let tmp_value = xl_value.map(|mut e| {
e.add_assign(&self.constants[i]);
e.square_in_place();
e
});
let tmp =
cs.new_witness_variable(|| tmp_value.ok_or(SynthesisError::AssignmentMissing))?;
cs.enforce_constraint(
lc!() + xl + (self.constants[i], Variable::One),
lc!() + xl + (self.constants[i], Variable::One),
lc!() + tmp,
)?;
// new_xL = xR + (xL + Ci)^3
// new_xL = xR + tmp * (xL + Ci)
// new_xL - xR = tmp * (xL + Ci)
let new_xl_value = xl_value.map(|mut e| {
e.add_assign(&self.constants[i]);
e.mul_assign(&tmp_value.unwrap());
e.add_assign(&xr_value.unwrap());
e
});
let new_xl = if i == (MIMC_ROUNDS - 1) {
// This is the last round, xL is our image and so
// we allocate a public input.
cs.new_input_variable(|| new_xl_value.ok_or(SynthesisError::AssignmentMissing))?
} else {
cs.new_witness_variable(|| new_xl_value.ok_or(SynthesisError::AssignmentMissing))?
};
cs.enforce_constraint(
lc!() + tmp,
lc!() + xl + (self.constants[i], Variable::One),
lc!() + new_xl - xr,
)?;
// xR = xL
xr = xl;
xr_value = xl_value;
// xL = new_xL
xl = new_xl;
xl_value = new_xl_value;
}
Ok(())
}
}
#[test]
fn test_mimc_groth16() {
// We're going to use the Groth16 proving system.
use ark_groth16::Groth16;
// This may not be cryptographically safe, use
// `OsRng` (for example) in production software.
let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());
// Generate the MiMC round constants
let constants = (0..MIMC_ROUNDS).map(|_| rng.gen()).collect::<Vec<_>>();
println!("Creating parameters...");
// Create parameters for our circuit
let (pk, vk) = {
let c = MiMCDemo::<Fr> {
xl: None,
xr: None,
constants: &constants,
};
Groth16::<Bls12_377>::setup(c, &mut rng).unwrap()
};
// Prepare the verification key (for proof verification)
let pvk = Groth16::<Bls12_377>::process_vk(&vk).unwrap();
println!("Creating proofs...");
// Let's benchmark stuff!
const SAMPLES: u32 = 50;
let mut total_proving = Duration::new(0, 0);
let mut total_verifying = Duration::new(0, 0);
// Just a place to put the proof data, so we can
// benchmark deserialization.
// let mut proof_vec = vec![];
for _ in 0..SAMPLES {
// Generate a random preimage and compute the image
let xl = rng.gen();
let xr = rng.gen();
let image = mimc(xl, xr, &constants);
// proof_vec.truncate(0);
let start = Instant::now();
{
// Create an instance of our circuit (with the
// witness)
let c = MiMCDemo {
xl: Some(xl),
xr: Some(xr),
constants: &constants,
};
// Create a groth16 proof with our parameters.
let proof = Groth16::<Bls12_377>::prove(&pk, c, &mut rng).unwrap();
assert!(
Groth16::<Bls12_377>::verify_with_processed_vk(&pvk, &[image], &proof).unwrap()
);
// proof.write(&mut proof_vec).unwrap();
}
total_proving += start.elapsed();
let start = Instant::now();
// let proof = Proof::read(&proof_vec[..]).unwrap();
// Check the proof
total_verifying += start.elapsed();
}
let proving_avg = total_proving / SAMPLES;
let proving_avg =
proving_avg.subsec_nanos() as f64 / 1_000_000_000f64 + (proving_avg.as_secs() as f64);
let verifying_avg = total_verifying / SAMPLES;
let verifying_avg =
verifying_avg.subsec_nanos() as f64 / 1_000_000_000f64 + (verifying_avg.as_secs() as f64);
println!("Average proving time: {:?} seconds", proving_avg);
println!("Average verifying time: {:?} seconds", verifying_avg);
}