-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathmod.rs
403 lines (361 loc) · 14.2 KB
/
mod.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use num_bigint::{BigInt, BigUint};
use num_traits::{Num, Zero};
use std::collections::{BTreeMap, HashSet};
use thiserror::Error;
use acvm::{AcirField, FieldElement};
use serde::Serialize;
use crate::errors::InputParserError;
use crate::{Abi, AbiType};
pub mod json;
mod toml;
/// This is what all formats eventually transform into
/// For example, a toml file will parse into TomlTypes
/// and those TomlTypes will be mapped to Value
#[derive(Debug, Clone, Serialize, PartialEq)]
pub enum InputValue {
Field(FieldElement),
String(String),
Vec(Vec<InputValue>),
Struct(BTreeMap<String, InputValue>),
}
#[derive(Debug, Error)]
pub enum InputTypecheckingError {
#[error("Value {value:?} does not fall within range of allowable values for a {typ:?}")]
OutsideOfValidRange { path: String, typ: AbiType, value: InputValue },
#[error("Type {typ:?} is expected to have length {expected_length} but value {value:?} has length {actual_length}")]
LengthMismatch {
path: String,
typ: AbiType,
value: InputValue,
expected_length: usize,
actual_length: usize,
},
#[error("Could not find value for required field `{expected_field}`. Found values for fields {found_fields:?}")]
MissingField { path: String, expected_field: String, found_fields: Vec<String> },
#[error("Additional unexpected field was provided for type {typ:?}. Found field named `{extra_field}`")]
UnexpectedField { path: String, typ: AbiType, extra_field: String },
#[error("Type {typ:?} and value {value:?} do not match")]
IncompatibleTypes { path: String, typ: AbiType, value: InputValue },
}
impl InputTypecheckingError {
pub(crate) fn path(&self) -> &str {
match self {
InputTypecheckingError::OutsideOfValidRange { path, .. }
| InputTypecheckingError::LengthMismatch { path, .. }
| InputTypecheckingError::MissingField { path, .. }
| InputTypecheckingError::UnexpectedField { path, .. }
| InputTypecheckingError::IncompatibleTypes { path, .. } => path,
}
}
}
impl InputValue {
/// Checks whether the ABI type matches the InputValue type
pub(crate) fn find_type_mismatch(
&self,
abi_param: &AbiType,
path: String,
) -> Result<(), InputTypecheckingError> {
match (self, abi_param) {
(InputValue::Field(_), AbiType::Field) => Ok(()),
(InputValue::Field(field_element), AbiType::Integer { width, .. }) => {
if field_element.num_bits() <= *width {
Ok(())
} else {
Err(InputTypecheckingError::OutsideOfValidRange {
path,
typ: abi_param.clone(),
value: self.clone(),
})
}
}
(InputValue::Field(field_element), AbiType::Boolean) => {
if field_element.is_one() || field_element.is_zero() {
Ok(())
} else {
Err(InputTypecheckingError::OutsideOfValidRange {
path,
typ: abi_param.clone(),
value: self.clone(),
})
}
}
(InputValue::Vec(array_elements), AbiType::Array { length, typ, .. }) => {
if array_elements.len() != *length as usize {
return Err(InputTypecheckingError::LengthMismatch {
path,
typ: abi_param.clone(),
value: self.clone(),
expected_length: *length as usize,
actual_length: array_elements.len(),
});
}
// Check that all of the array's elements' values match the ABI as well.
for (i, element) in array_elements.iter().enumerate() {
let mut path = path.clone();
path.push_str(&format!("[{i}]"));
element.find_type_mismatch(typ, path)?;
}
Ok(())
}
(InputValue::String(string), AbiType::String { length }) => {
if string.len() == *length as usize {
Ok(())
} else {
Err(InputTypecheckingError::LengthMismatch {
path,
typ: abi_param.clone(),
value: self.clone(),
actual_length: string.len(),
expected_length: *length as usize,
})
}
}
(InputValue::Struct(map), AbiType::Struct { fields, .. }) => {
for (field_name, field_type) in fields {
if let Some(value) = map.get(field_name) {
let mut path = path.clone();
path.push_str(&format!(".{field_name}"));
value.find_type_mismatch(field_type, path)?;
} else {
return Err(InputTypecheckingError::MissingField {
path,
expected_field: field_name.to_string(),
found_fields: map.keys().cloned().collect(),
});
}
}
if map.len() > fields.len() {
let expected_fields: HashSet<String> =
fields.iter().map(|(field, _)| field.to_string()).collect();
let extra_field = map.keys().find(|&key| !expected_fields.contains(key)).cloned().expect("`map` is larger than the expected type's `fields` so it must contain an unexpected field");
return Err(InputTypecheckingError::UnexpectedField {
path,
typ: abi_param.clone(),
extra_field: extra_field.to_string(),
});
}
Ok(())
}
(InputValue::Vec(vec_elements), AbiType::Tuple { fields }) => {
if vec_elements.len() != fields.len() {
return Err(InputTypecheckingError::LengthMismatch {
path,
typ: abi_param.clone(),
value: self.clone(),
actual_length: vec_elements.len(),
expected_length: fields.len(),
});
}
// Check that all of the array's elements' values match the ABI as well.
for (i, (element, expected_typ)) in vec_elements.iter().zip(fields).enumerate() {
let mut path = path.clone();
path.push_str(&format!(".{i}"));
element.find_type_mismatch(expected_typ, path)?;
}
Ok(())
}
// All other InputValue-AbiType combinations are fundamentally incompatible.
_ => Err(InputTypecheckingError::IncompatibleTypes {
path,
typ: abi_param.clone(),
value: self.clone(),
}),
}
}
/// Checks whether the ABI type matches the InputValue type.
pub fn matches_abi(&self, abi_param: &AbiType) -> bool {
self.find_type_mismatch(abi_param, String::new()).is_ok()
}
}
/// The different formats that are supported when parsing
/// the initial witness values
#[cfg_attr(test, derive(strum_macros::EnumIter))]
pub enum Format {
Json,
Toml,
}
impl Format {
pub fn ext(&self) -> &'static str {
match self {
Format::Json => "json",
Format::Toml => "toml",
}
}
}
impl Format {
pub fn parse(
&self,
input_string: &str,
abi: &Abi,
) -> Result<BTreeMap<String, InputValue>, InputParserError> {
match self {
Format::Json => json::parse_json(input_string, abi),
Format::Toml => toml::parse_toml(input_string, abi),
}
}
pub fn serialize(
&self,
input_map: &BTreeMap<String, InputValue>,
abi: &Abi,
) -> Result<String, InputParserError> {
match self {
Format::Json => json::serialize_to_json(input_map, abi),
Format::Toml => toml::serialize_to_toml(input_map, abi),
}
}
}
#[cfg(test)]
mod serialization_tests {
use std::collections::BTreeMap;
use acvm::{AcirField, FieldElement};
use strum::IntoEnumIterator;
use crate::{
input_parser::InputValue, Abi, AbiParameter, AbiReturnType, AbiType, AbiVisibility, Sign,
MAIN_RETURN_NAME,
};
use super::Format;
#[test]
fn serialization_round_trip() {
let abi = Abi {
parameters: vec![
AbiParameter {
name: "foo".into(),
typ: AbiType::Field,
visibility: AbiVisibility::Private,
},
AbiParameter {
name: "bar".into(),
typ: AbiType::Struct {
path: "MyStruct".into(),
fields: vec![
("field1".into(), AbiType::Integer { sign: Sign::Unsigned, width: 8 }),
(
"field2".into(),
AbiType::Array { length: 2, typ: Box::new(AbiType::Boolean) },
),
],
},
visibility: AbiVisibility::Private,
},
],
return_type: Some(AbiReturnType {
abi_type: AbiType::String { length: 5 },
visibility: AbiVisibility::Public,
}),
error_types: Default::default(),
};
let input_map: BTreeMap<String, InputValue> = BTreeMap::from([
("foo".into(), InputValue::Field(FieldElement::one())),
(
"bar".into(),
InputValue::Struct(BTreeMap::from([
("field1".into(), InputValue::Field(255u128.into())),
(
"field2".into(),
InputValue::Vec(vec![
InputValue::Field(true.into()),
InputValue::Field(false.into()),
]),
),
])),
),
(MAIN_RETURN_NAME.into(), InputValue::String("hello".to_owned())),
]);
for format in Format::iter() {
let serialized_inputs = format.serialize(&input_map, &abi).unwrap();
let reconstructed_input_map = format.parse(&serialized_inputs, &abi).unwrap();
assert_eq!(input_map, reconstructed_input_map);
}
}
}
fn parse_str_to_field(value: &str) -> Result<FieldElement, InputParserError> {
let big_num = if let Some(hex) = value.strip_prefix("0x") {
BigUint::from_str_radix(hex, 16)
} else {
BigUint::from_str_radix(value, 10)
};
big_num.map_err(|err_msg| InputParserError::ParseStr(err_msg.to_string())).and_then(|bigint| {
if bigint < FieldElement::modulus() {
Ok(field_from_big_uint(bigint))
} else {
Err(InputParserError::ParseStr(format!(
"Input exceeds field modulus. Values must fall within [0, {})",
FieldElement::modulus(),
)))
}
})
}
fn parse_str_to_signed(value: &str, width: u32) -> Result<FieldElement, InputParserError> {
let big_num = if let Some(hex) = value.strip_prefix("0x") {
BigInt::from_str_radix(hex, 16)
} else {
BigInt::from_str_radix(value, 10)
};
big_num.map_err(|err_msg| InputParserError::ParseStr(err_msg.to_string())).and_then(|bigint| {
let modulus: BigInt = FieldElement::modulus().into();
let bigint = if bigint.sign() == num_bigint::Sign::Minus {
BigInt::from(2).pow(width) + bigint
} else {
bigint
};
if bigint.is_zero() || (bigint.sign() == num_bigint::Sign::Plus && bigint < modulus) {
Ok(field_from_big_int(bigint))
} else {
Err(InputParserError::ParseStr(format!(
"Input exceeds field modulus. Values must fall within [0, {})",
FieldElement::modulus(),
)))
}
})
}
fn field_from_big_uint(bigint: BigUint) -> FieldElement {
FieldElement::from_be_bytes_reduce(&bigint.to_bytes_be())
}
fn field_from_big_int(bigint: BigInt) -> FieldElement {
match bigint.sign() {
num_bigint::Sign::Minus => {
unreachable!(
"Unsupported negative value; it should only be called with a positive value"
)
}
num_bigint::Sign::NoSign => FieldElement::zero(),
num_bigint::Sign::Plus => FieldElement::from_be_bytes_reduce(&bigint.to_bytes_be().1),
}
}
#[cfg(test)]
mod test {
use acvm::{AcirField, FieldElement};
use num_bigint::BigUint;
use super::parse_str_to_field;
fn big_uint_from_field(field: FieldElement) -> BigUint {
BigUint::from_bytes_be(&field.to_be_bytes())
}
#[test]
fn parse_empty_str_fails() {
// Check that this fails appropriately rather than being treated as 0, etc.
assert!(parse_str_to_field("").is_err());
}
#[test]
fn parse_fields_from_strings() {
let fields = vec![
FieldElement::zero(),
FieldElement::one(),
FieldElement::from(u128::MAX) + FieldElement::one(),
// Equivalent to `FieldElement::modulus() - 1`
-FieldElement::one(),
];
for field in fields {
let hex_field = format!("0x{}", field.to_hex());
let field_from_hex = parse_str_to_field(&hex_field).unwrap();
assert_eq!(field_from_hex, field);
let dec_field = big_uint_from_field(field).to_string();
let field_from_dec = parse_str_to_field(&dec_field).unwrap();
assert_eq!(field_from_dec, field);
}
}
#[test]
fn rejects_noncanonical_fields() {
let noncanonical_field = FieldElement::modulus().to_string();
assert!(parse_str_to_field(&noncanonical_field).is_err());
}
}