This repository has been archived by the owner on Oct 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 106
/
solidity_seralizer.rs
366 lines (323 loc) · 12.6 KB
/
solidity_seralizer.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use crate::{
channel::{RandomGenerator, Replayable, VerifierChannel},
constraints::Constraints,
proof_of_work, Proof,
};
use hex::encode;
use std::{collections::BTreeMap, prelude::v1::*};
use zkp_hash::Hash;
use zkp_merkle_tree::{Commitment, Error as MerkleError};
use zkp_primefield::FieldElement;
use zkp_u256::U256;
// This trait is a simple json encoding trait which exports the values
// in the format expected by the ethereum call, the hand made version
// is used instead of serde because it differ in important ways
trait SoliditySeralize {
fn sol_encode(&self) -> String;
}
impl SoliditySeralize for FieldElement {
fn sol_encode(&self) -> String {
format!("\"0x{}\"", encode(self.as_montgomery().to_bytes_be()))
}
}
impl SoliditySeralize for Hash {
fn sol_encode(&self) -> String {
format!("\"0x{}\"", encode(self.as_bytes()))
}
}
impl SoliditySeralize for Commitment {
fn sol_encode(&self) -> String {
self.hash().sol_encode()
}
}
// This recursive call makes a javascript array, for any type which can be
// serialized
impl<T: SoliditySeralize> SoliditySeralize for Vec<T> {
fn sol_encode(&self) -> String {
let mut res: String = "".to_string();
if self.is_empty() {
return res;
}
let (last, rest) = self.split_last().unwrap();
res.push_str(&"[\n");
for data in rest.iter() {
res.push_str(&format!("{},\n", data.sol_encode()));
}
res.push_str(&format!("{}\n", last.sol_encode()));
res.push_str("]");
res
}
}
// TODO - Make this function smaller
#[allow(clippy::too_many_lines)]
pub fn proof_serialize(
constraints: &Constraints,
proof: &Proof,
result_string: &mut String,
) -> Result<(), MerkleError> {
let proof = proof.as_bytes();
let trace_length = constraints.trace_nrows();
let trace_cols = constraints.trace_ncolumns();
let eval_domain_size = trace_length * constraints.blowup;
let mut channel = VerifierChannel::new(proof.to_vec());
// TODO - Add method to seralize public input
channel.initialize(constraints.channel_seed());
// Get the low degree root commitment, and constraint root commitment
// TODO: Make it work as channel.read()
let low_degree_extension_root: Hash = channel.replay();
result_string.push_str(&format!(
"\"trace_commitment\": {}, \n",
low_degree_extension_root.sol_encode()
));
let lde_commitment = Commitment::from_size_hash(eval_domain_size, &low_degree_extension_root)?;
let _ = channel.get_coefficients(2 * constraints.len());
let constraint_evaluated_root: Hash = channel.replay();
result_string.push_str(&format!(
"\"constraint_commitment\": {}, \n",
constraint_evaluated_root.sol_encode()
));
let constraint_commitment =
Commitment::from_size_hash(eval_domain_size, &constraint_evaluated_root)?;
// Get the oods information from the proof and random
let _: FieldElement = channel.get_random();
// This hack around claim polynomials is awful and should be removed
let mut parseable_constraints = constraints.clone();
parseable_constraints.substitute();
let trace_arguments = parseable_constraints.trace_arguments();
let trace_values: Vec<FieldElement> = channel.replay_many(trace_arguments.len());
result_string.push_str(&format!(
"\"trace_oods_values\": {}, \n",
trace_values.sol_encode()
));
let claimed_trace_map: BTreeMap<(usize, isize), FieldElement> = trace_arguments
.into_iter()
.zip(trace_values.iter().cloned())
.collect();
let constraints_trace_degree = constraints.degree().next_power_of_two();
let claimed_constraint_values: Vec<FieldElement> =
channel.replay_many(constraints_trace_degree);
result_string.push_str(&format!(
"\"constraint_oods_values\": {}, \n",
claimed_constraint_values.sol_encode()
));
let _ = channel.get_coefficients(claimed_trace_map.len() + claimed_constraint_values.len());
let mut fri_commitments: Vec<Commitment> = Vec::with_capacity(constraints.fri_layout.len() + 1);
let mut eval_points: Vec<FieldElement> = Vec::with_capacity(constraints.fri_layout.len() + 1);
let mut fri_size = eval_domain_size;
// Get fri roots and eval points from the channel random
for &num_folds in &constraints.fri_layout {
fri_size >>= num_folds;
fri_commitments.push(Commitment::from_size_hash(fri_size, &channel.replay())?);
eval_points.push(channel.get_random());
}
result_string.push_str(&format!(
"\"fri_commitments\": {}, \n",
fri_commitments.sol_encode()
));
// Gets the last layer coeffiencts
let last_layer_coefficients = channel.replay_fri_layer(fri_size / constraints.blowup);
result_string.push_str(&format!(
"\"last_layer_coefficients\": {}, \n",
last_layer_coefficients.sol_encode()
));
// Gets the proof of work from the proof.
let pow_response: proof_of_work::Response = channel.replay();
result_string.push_str(&format!(
"\"pow_nonce\": \"0x{}\",",
encode(pow_response.nonce().to_be_bytes())
));
// Gets queries from channel
let queries = get_indices(
constraints.num_queries,
eval_domain_size.trailing_zeros(),
&mut channel,
);
// Get values and check decommitment of low degree extension
let lde_values: Vec<(usize, Vec<FieldElement>)> = queries
.iter()
.map(|&index| (index, channel.replay_fri_layer(trace_cols)))
.collect();
let flattened_trace_values: Vec<FieldElement> =
lde_values.iter().flat_map(|data| data.1.clone()).collect();
result_string.push_str(&format!(
"\"trace_values\": {}, \n",
flattened_trace_values.sol_encode()
));
let lde_proof_length = lde_commitment.proof_size(&queries)?;
let lde_hashes: Vec<Hash> = channel.replay_many(lde_proof_length);
result_string.push_str(&format!(
"\"trace_decommitment\": {}, \n",
lde_hashes.sol_encode()
));
// Gets the values and checks the constraint decommitment
let mut constraint_values = Vec::with_capacity(queries.len());
for query_index in &queries {
constraint_values.push((
*query_index,
channel.replay_fri_layer(constraints_trace_degree),
));
}
let flattened_constraint_values: Vec<FieldElement> = constraint_values
.iter()
.flat_map(|data| data.1.clone())
.collect();
result_string.push_str(&format!(
"\"constraint_values\": {}, \n",
flattened_constraint_values.sol_encode()
));
let constraint_proof_length = constraint_commitment.proof_size(&queries)?;
let constraint_hashes: Vec<Hash> = channel.replay_many(constraint_proof_length);
result_string.push_str(&format!(
"\"constraint_decommitment\": {}, \n",
constraint_hashes.sol_encode()
));
let coset_sizes = constraints
.fri_layout
.iter()
.map(|k| 1_usize << k)
.collect::<Vec<_>>();
let mut fri_indices: Vec<usize> = queries
.to_vec()
.iter()
.map(|x| x / coset_sizes[0])
.collect();
let mut previous_indices = queries.to_vec();
let mut fri_values: Vec<Vec<FieldElement>> = Vec::new();
let mut fri_decommitments: Vec<Vec<Hash>> = Vec::new();
for (k, commitment) in fri_commitments.iter().enumerate() {
fri_indices.dedup();
let mut proof_values = Vec::new();
for i in &fri_indices {
for j in 0..coset_sizes[k] {
let n = i * coset_sizes[k] + j;
if previous_indices.binary_search(&n).is_err() {
let held: FieldElement = channel.replay();
proof_values.push(held.clone());
}
}
}
fri_values.push(proof_values);
let merkle_proof_length = commitment.proof_size(&fri_indices)?;
let merkle_hashes: Vec<Hash> = channel.replay_many(merkle_proof_length);
fri_decommitments.push(merkle_hashes.clone());
previous_indices = fri_indices.clone();
if k + 1 < constraints.fri_layout.len() {
fri_indices = fri_indices
.iter()
.map(|ind| ind / coset_sizes[k + 1])
.collect();
}
}
result_string.push_str(&format!("\"fri_values\": {}, \n", fri_values.sol_encode()));
result_string.push_str(&format!(
"\"fri_decommitments\": {} \n",
fri_decommitments.sol_encode()
));
Ok(())
}
// TODO: Clean up
#[allow(clippy::cast_possible_truncation)]
fn get_indices(num: usize, bits: u32, proof: &mut VerifierChannel) -> Vec<usize> {
let mut query_indices = Vec::with_capacity(num + 3);
while query_indices.len() < num {
let val: U256 = proof.get_random();
query_indices
.push(((val.clone() >> (0x100 - 0x040)).limb(0) & (2_u64.pow(bits) - 1)) as usize);
query_indices
.push(((val.clone() >> (0x100 - 0x080)).limb(0) & (2_u64.pow(bits) - 1)) as usize);
query_indices
.push(((val.clone() >> (0x100 - 0x0C0)).limb(0) & (2_u64.pow(bits) - 1)) as usize);
query_indices.push((val.limb(0) & (2_u64.pow(bits) - 1)) as usize);
}
query_indices.truncate(num);
(&mut query_indices).sort_unstable();
query_indices
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{prove, traits::tests::Recurrance, Provable, Verifiable};
use zkp_macros_decl::field_element;
#[test]
fn seralize_recurrance() {
let r = Recurrance {
index: 150,
initial_value: field_element!(
"42f70183f3ed560b81c4cd49a8d5f27fdb747c17eaa93f41570b012649b5a47b"
),
exponent: 2,
};
let public = r.claim();
let private = r.witness();
let mut constraints = public.constraints();
constraints.num_queries = 20;
constraints.pow_bits = 10;
let trace = public.trace(&private);
let mut result_string = "".to_string();
proof_serialize(
&constraints,
&prove(&constraints, &trace).unwrap(),
&mut result_string,
)
.unwrap();
}
// Note this test is actually more like a binary which we want run so it
// commented out, The Recurrance struct can't be exported to a binary or
// example because it only lives in tests.
// use std::{fs::File, io::prelude::*, path::Path};
// #[test]
// fn output_recurrances() {
// let mut initial_value =
// field_element!("
// 42f70183f3ed560b81c4cd49a8d5f27fdb747c17eaa93f41570b012649b5a47b");
// let mut result_string = "[\n".to_string();
// let mut index = 150;
// for i in 0..15 {
// println!("{}", i);
// let r = Recurrance {
// index: index,
// initial_value: initial_value.clone(),
// exponent: 2,
// };
// let public = r.claim();
// // println!("{:?}", public.value.as_montgomery());
// let private = r.witness();
// let mut constraints = public.constraints();
// constraints.num_queries = 20;
// constraints.pow_bits = 10;
// let trace = public.trace(&private);
// result_string.push_str(&format!(
// "{{
// \"public_inputs\": {{
// \"index\" : {},
// \"value\" : \"0x{}\"
// }},",
// r.index,
// public.value.as_montgomery()
// ));
// let _ = proof_serialize(
// &constraints,
// &prove(&constraints, &trace).unwrap(),
// &mut result_string,
// )
// .unwrap();
// if i == 19 {
// result_string.push_str("}\n");
// } else {
// result_string.push_str("},\n");
// }
// // This changes around the value in a slightly unpredictable way
// initial_value *= initial_value.clone();
// index *= 2;
// }
// result_string.push_str("]");
// let path = Path::new("recurrence.json");
// let display = path.display();
// let mut file = match File::create(&path) {
// Err(why) => panic!("couldn't create {}: {}", display,
// why.to_string()), Ok(file) => file,
// };
// writeln!(&mut file, "{}", result_string).unwrap();
// // assert!(false);
// }
}