-
Notifications
You must be signed in to change notification settings - Fork 19
/
separately.rs
242 lines (210 loc) · 8.02 KB
/
separately.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
230
231
232
233
234
235
236
237
238
239
240
241
242
use application::StandardPlonk;
use prelude::*;
use halo2_solidity_verifier::{
compile_solidity, encode_calldata, BatchOpenScheme::Bdfg21, Evm, Keccak256Transcript,
SolidityGenerator,
};
const K_RANGE: Range<u32> = 10..17;
fn main() {
let mut rng = seeded_std_rng();
let params = setup(K_RANGE, &mut rng);
let vk = keygen_vk(¶ms[&K_RANGE.start], &StandardPlonk::default()).unwrap();
let generator = SolidityGenerator::new(¶ms[&K_RANGE.start], &vk, Bdfg21, 0);
let (verifier_solidity, _) = generator.render_separately().unwrap();
save_solidity("Halo2Verifier.sol", &verifier_solidity);
let verifier_creation_code = compile_solidity(&verifier_solidity);
let verifier_creation_code_size = verifier_creation_code.len();
println!("Verifier creation code size: {verifier_creation_code_size}");
let mut evm = Evm::default();
let verifier_address = evm.create(verifier_creation_code);
let deployed_verifier_solidity = verifier_solidity;
for k in K_RANGE {
let num_instances = k as usize;
let circuit = StandardPlonk::rand(num_instances, &mut rng);
let vk = keygen_vk(¶ms[&k], &circuit).unwrap();
let pk = keygen_pk(¶ms[&k], vk, &circuit).unwrap();
let generator = SolidityGenerator::new(¶ms[&k], pk.get_vk(), Bdfg21, num_instances);
let (verifier_solidity, vk_solidity) = generator.render_separately().unwrap();
save_solidity(format!("Halo2VerifyingKey-{k}.sol"), &vk_solidity);
assert_eq!(deployed_verifier_solidity, verifier_solidity);
let vk_creation_code = compile_solidity(&vk_solidity);
let vk_address = evm.create(vk_creation_code);
let calldata = {
let instances = circuit.instances();
let proof = create_proof_checked(¶ms[&k], &pk, circuit, &instances, &mut rng);
encode_calldata(Some(vk_address.into()), &proof, &instances)
};
let (gas_cost, output) = evm.call(verifier_address, calldata);
assert_eq!(output, [vec![0; 31], vec![1]].concat());
println!("Gas cost of verifying standard Plonk with 2^{k} rows: {gas_cost}");
}
}
fn save_solidity(name: impl AsRef<str>, solidity: &str) {
const DIR_GENERATED: &str = "./generated";
create_dir_all(DIR_GENERATED).unwrap();
File::create(format!("{DIR_GENERATED}/{}", name.as_ref()))
.unwrap()
.write_all(solidity.as_bytes())
.unwrap();
}
fn setup(k_range: Range<u32>, mut rng: impl RngCore) -> HashMap<u32, ParamsKZG<Bn256>> {
k_range
.clone()
.zip(k_range.map(|k| ParamsKZG::<Bn256>::setup(k, &mut rng)))
.collect()
}
fn create_proof_checked(
params: &ParamsKZG<Bn256>,
pk: &ProvingKey<G1Affine>,
circuit: impl Circuit<Fr>,
instances: &[Fr],
mut rng: impl RngCore,
) -> Vec<u8> {
use halo2_proofs::{
poly::kzg::{
multiopen::{ProverSHPLONK, VerifierSHPLONK},
strategy::SingleStrategy,
},
transcript::TranscriptWriterBuffer,
};
let proof = {
let mut transcript = Keccak256Transcript::new(Vec::new());
create_proof::<_, ProverSHPLONK<_>, _, _, _, _>(
params,
pk,
&[circuit],
&[&[instances]],
&mut rng,
&mut transcript,
)
.unwrap();
transcript.finalize()
};
let result = {
let mut transcript = Keccak256Transcript::new(proof.as_slice());
verify_proof::<_, VerifierSHPLONK<_>, _, _, SingleStrategy<_>>(
params,
pk.get_vk(),
SingleStrategy::new(params),
&[&[instances]],
&mut transcript,
)
};
assert!(result.is_ok());
proof
}
mod application {
use crate::prelude::*;
#[derive(Clone)]
pub struct StandardPlonkConfig {
selectors: [Column<Fixed>; 5],
wires: [Column<Advice>; 3],
}
impl StandardPlonkConfig {
fn configure(meta: &mut ConstraintSystem<impl PrimeField>) -> Self {
let [w_l, w_r, w_o] = [(); 3].map(|_| meta.advice_column());
let [q_l, q_r, q_o, q_m, q_c] = [(); 5].map(|_| meta.fixed_column());
let pi = meta.instance_column();
[w_l, w_r, w_o].map(|column| meta.enable_equality(column));
meta.create_gate(
"q_l·w_l + q_r·w_r + q_o·w_o + q_m·w_l·w_r + q_c + pi = 0",
|meta| {
let [w_l, w_r, w_o] =
[w_l, w_r, w_o].map(|column| meta.query_advice(column, Rotation::cur()));
let [q_l, q_r, q_o, q_m, q_c] = [q_l, q_r, q_o, q_m, q_c]
.map(|column| meta.query_fixed(column, Rotation::cur()));
let pi = meta.query_instance(pi, Rotation::cur());
Some(
q_l * w_l.clone()
+ q_r * w_r.clone()
+ q_o * w_o
+ q_m * w_l * w_r
+ q_c
+ pi,
)
},
);
StandardPlonkConfig {
selectors: [q_l, q_r, q_o, q_m, q_c],
wires: [w_l, w_r, w_o],
}
}
}
#[derive(Clone, Debug, Default)]
pub struct StandardPlonk<F>(Vec<F>);
impl<F: PrimeField> StandardPlonk<F> {
pub fn rand<R: RngCore>(num_instances: usize, mut rng: R) -> Self {
Self((0..num_instances).map(|_| F::random(&mut rng)).collect())
}
pub fn instances(&self) -> Vec<F> {
self.0.clone()
}
}
impl<F: PrimeField> Circuit<F> for StandardPlonk<F> {
type Config = StandardPlonkConfig;
type FloorPlanner = SimpleFloorPlanner;
fn without_witnesses(&self) -> Self {
unimplemented!()
}
fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
meta.set_minimum_degree(5);
StandardPlonkConfig::configure(meta)
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<F>,
) -> Result<(), Error> {
let [q_l, q_r, q_o, q_m, q_c] = config.selectors;
let [w_l, w_r, w_o] = config.wires;
layouter.assign_region(
|| "",
|mut region| {
for (offset, instance) in self.0.iter().enumerate() {
region.assign_advice(|| "", w_l, offset, || Value::known(*instance))?;
region.assign_fixed(|| "", q_l, offset, || Value::known(-F::ONE))?;
}
let offset = self.0.len();
let a = region.assign_advice(|| "", w_l, offset, || Value::known(F::ONE))?;
a.copy_advice(|| "", &mut region, w_r, offset)?;
a.copy_advice(|| "", &mut region, w_o, offset)?;
let offset = offset + 1;
region.assign_advice(|| "", w_l, offset, || Value::known(-F::from(5)))?;
for (column, idx) in [q_l, q_r, q_o, q_m, q_c].iter().zip(1..) {
region.assign_fixed(
|| "",
*column,
offset,
|| Value::known(F::from(idx)),
)?;
}
Ok(())
},
)
}
}
}
mod prelude {
pub use halo2_proofs::{
circuit::{Layouter, SimpleFloorPlanner, Value},
halo2curves::{
bn256::{Bn256, Fr, G1Affine},
ff::PrimeField,
},
plonk::*,
poly::{kzg::commitment::ParamsKZG, Rotation},
};
pub use rand::{
rngs::{OsRng, StdRng},
RngCore, SeedableRng,
};
pub use std::{
collections::HashMap,
fs::{create_dir_all, File},
io::Write,
ops::Range,
};
pub fn seeded_std_rng() -> impl RngCore {
StdRng::seed_from_u64(OsRng.next_u64())
}
}