1pub mod black_box_functions;
4pub mod brillig;
5pub mod opcodes;
6
7use crate::{
8 SerializationFormat,
9 circuit::opcodes::display_opcode,
10 native_types::{Expression, Witness},
11 serialization::{self, deserialize_any_format, serialize_with_format},
12};
13use acir_field::AcirField;
14use msgpack_tagged::MsgpackTagged;
15pub use opcodes::Opcode;
16use thiserror::Error;
17
18use std::{collections::HashMap, io::prelude::*, num::ParseIntError, str::FromStr};
19
20use base64::Engine;
21use flate2::Compression;
22use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeserializationError};
23
24use std::collections::BTreeSet;
25
26use self::{brillig::BrilligBytecode, opcodes::BlockId};
27
28#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default, Hash, MsgpackTagged)]
31#[cfg_attr(feature = "arb", derive(proptest_derive::Arbitrary))]
32#[tagged(allow_unknown_tags)]
33pub struct Program<F: AcirField> {
34 #[tag(0)]
35 pub functions: Vec<Circuit<F>>,
36 #[tag(1)]
37 pub unconstrained_functions: Vec<BrilligBytecode<F>>,
38}
39
40#[derive(Clone, PartialEq, Eq, Default, Hash, Serialize, Deserialize, MsgpackTagged)]
43#[cfg_attr(feature = "arb", derive(proptest_derive::Arbitrary))]
44#[tagged(allow_unknown_tags)]
45pub struct Circuit<F: AcirField> {
46 #[tag(0)]
48 pub function_name: String,
49 #[tag(1)]
54 pub opcodes: Vec<Opcode<F>>,
55 #[tag(2)]
57 pub private_parameters: BTreeSet<Witness>,
58 #[tag(3)]
63 pub public_parameters: PublicInputs,
64 #[tag(4)]
66 pub return_values: PublicInputs,
67 #[tag(5)]
75 pub assert_messages: Vec<(OpcodeLocation, AssertionPayload<F>)>,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, Hash)]
80#[derive(Serialize, Deserialize, MsgpackTagged)]
81#[cfg_attr(feature = "arb", derive(proptest_derive::Arbitrary))]
82pub enum ExpressionOrMemory<F> {
83 #[tag(0)]
84 Expression(Expression<F>),
85 #[tag(1)]
86 Memory(BlockId),
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Hash)]
92#[derive(Serialize, Deserialize, MsgpackTagged)]
93#[cfg_attr(feature = "arb", derive(proptest_derive::Arbitrary))]
94pub struct AssertionPayload<F> {
95 #[tag(0)]
98 pub error_selector: u64,
99 #[tag(1)]
106 pub payload: Vec<ExpressionOrMemory<F>>,
107}
108
109#[derive(Debug, Copy, PartialEq, Eq, Hash, Clone, PartialOrd, Ord)]
111pub struct ErrorSelector(u64);
112
113impl ErrorSelector {
114 pub fn new(integer: u64) -> Self {
115 ErrorSelector(integer)
116 }
117
118 pub fn as_u64(&self) -> u64 {
119 self.0
120 }
121}
122
123impl Serialize for ErrorSelector {
124 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
125 where
126 S: Serializer,
127 {
128 self.0.to_string().serialize(serializer)
129 }
130}
131
132impl<'de> Deserialize<'de> for ErrorSelector {
133 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
134 where
135 D: Deserializer<'de>,
136 {
137 let s: String = Deserialize::deserialize(deserializer)?;
138 let as_u64 = s.parse().map_err(serde::de::Error::custom)?;
139 Ok(ErrorSelector(as_u64))
140 }
141}
142
143#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
144#[derive(Serialize, Deserialize, MsgpackTagged)]
145#[cfg_attr(feature = "arb", derive(proptest_derive::Arbitrary))]
146pub enum OpcodeLocation {
149 #[tag(0)]
150 Acir(usize),
151 #[tag(1)]
154 Brillig {
155 #[tag(0)]
156 acir_index: usize,
157 #[tag(1)]
158 brillig_index: usize,
159 },
160}
161
162#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
165pub struct AcirOpcodeLocation(usize);
166impl std::fmt::Display for AcirOpcodeLocation {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 write!(f, "{}", self.0)
169 }
170}
171
172impl AcirOpcodeLocation {
173 pub fn new(index: usize) -> Self {
174 AcirOpcodeLocation(index)
175 }
176 pub fn index(&self) -> usize {
177 self.0
178 }
179}
180#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
183pub struct BrilligOpcodeLocation(pub usize);
184
185impl OpcodeLocation {
186 pub fn to_brillig_location(self) -> Option<BrilligOpcodeLocation> {
190 match self {
191 OpcodeLocation::Brillig { brillig_index, .. } => {
192 Some(BrilligOpcodeLocation(brillig_index))
193 }
194 OpcodeLocation::Acir(_) => None,
195 }
196 }
197}
198
199impl std::fmt::Display for OpcodeLocation {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 match self {
202 OpcodeLocation::Acir(index) => write!(f, "{index}"),
203 OpcodeLocation::Brillig { acir_index, brillig_index } => {
204 write!(f, "{acir_index}.{brillig_index}")
205 }
206 }
207 }
208}
209
210#[derive(Error, Debug)]
211pub enum OpcodeLocationFromStrError {
212 #[error("Invalid opcode location string: {0}")]
213 InvalidOpcodeLocationString(String),
214}
215
216impl FromStr for OpcodeLocation {
219 type Err = OpcodeLocationFromStrError;
220 fn from_str(s: &str) -> Result<Self, Self::Err> {
221 let parts: Vec<_> = s.split('.').collect();
222
223 if parts.is_empty() || parts.len() > 2 {
224 return Err(OpcodeLocationFromStrError::InvalidOpcodeLocationString(s.to_string()));
225 }
226
227 fn parse_components(parts: Vec<&str>) -> Result<OpcodeLocation, ParseIntError> {
228 match parts.len() {
229 1 => {
230 let index = parts[0].parse()?;
231 Ok(OpcodeLocation::Acir(index))
232 }
233 2 => {
234 let acir_index = parts[0].parse()?;
235 let brillig_index = parts[1].parse()?;
236 Ok(OpcodeLocation::Brillig { acir_index, brillig_index })
237 }
238 _ => unreachable!("`OpcodeLocation` has too many components"),
239 }
240 }
241
242 parse_components(parts)
243 .map_err(|_| OpcodeLocationFromStrError::InvalidOpcodeLocationString(s.to_string()))
244 }
245}
246
247impl std::fmt::Display for BrilligOpcodeLocation {
248 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 let index = self.0;
250 write!(f, "{index}")
251 }
252}
253
254impl<F: AcirField> Circuit<F> {
255 pub fn circuit_arguments(&self) -> BTreeSet<Witness> {
257 self.private_parameters.union(&self.public_parameters.0).copied().collect()
258 }
259
260 pub fn public_inputs(&self) -> PublicInputs {
263 let public_inputs =
264 self.public_parameters.0.union(&self.return_values.0).copied().collect();
265 PublicInputs(public_inputs)
266 }
267}
268
269impl<F: Serialize + AcirField + MsgpackTagged> Program<F> {
270 fn compress(buf: Vec<u8>) -> std::io::Result<Vec<u8>> {
272 let mut compressed: Vec<u8> = Vec::new();
273 let mut encoder = flate2::write::GzEncoder::new(&mut compressed, Compression::default());
275 encoder.write_all(&buf)?;
276 encoder.finish()?;
277 Ok(compressed)
278 }
279
280 pub fn serialize_program_with_format(program: &Self, format: serialization::Format) -> Vec<u8> {
282 let program_bytes =
283 serialize_with_format(program, format).expect("expected circuit to be serializable");
284 Self::compress(program_bytes).expect("expected circuit to compress")
285 }
286
287 pub fn serialize_program(program: &Self) -> Vec<u8> {
289 let format = SerializationFormat::from_env().expect("invalid format");
290 Self::serialize_program_with_format(program, format.unwrap_or_default())
291 }
292
293 pub fn serialize_program_base64<S>(program: &Self, s: S) -> Result<S::Ok, S::Error>
295 where
296 S: Serializer,
297 {
298 let program_bytes = Program::serialize_program(program);
299 let encoded_b64 = base64::engine::general_purpose::STANDARD.encode(program_bytes);
300 s.serialize_str(&encoded_b64)
301 }
302}
303
304impl<F: AcirField + for<'a> Deserialize<'a> + MsgpackTagged> Program<F> {
305 fn read<R: Read>(reader: R) -> std::io::Result<Self> {
307 let mut gz_decoder = flate2::read::GzDecoder::new(reader);
308 let mut buf = Vec::new();
309 gz_decoder.read_to_end(&mut buf)?;
310 let program = deserialize_any_format(&buf)?;
311 Ok(program)
312 }
313
314 pub fn deserialize_program(serialized_circuit: &[u8]) -> std::io::Result<Self> {
316 Program::read(serialized_circuit)
317 }
318
319 pub fn deserialize_program_base64<'de, D>(deserializer: D) -> Result<Self, D::Error>
321 where
322 D: Deserializer<'de>,
323 {
324 let bytecode_b64: String = Deserialize::deserialize(deserializer)?;
325 let program_bytes = base64::engine::general_purpose::STANDARD
326 .decode(bytecode_b64)
327 .map_err(D::Error::custom)?;
328 let circuit = Self::deserialize_program(&program_bytes).map_err(D::Error::custom)?;
329 Ok(circuit)
330 }
331}
332
333impl<F: AcirField> std::fmt::Display for Circuit<F> {
334 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335 display_circuit(self, None, f)
336 }
337}
338
339pub fn display_circuit<F: AcirField>(
340 circuit: &Circuit<F>,
341 error_types: Option<&HashMap<ErrorSelector, String>>,
342 f: &mut std::fmt::Formatter<'_>,
343) -> std::fmt::Result {
344 let write_witness_indices =
345 |f: &mut std::fmt::Formatter<'_>, indices: &[u32]| -> Result<(), std::fmt::Error> {
346 write!(f, "[")?;
347 for (index, witness_index) in indices.iter().enumerate() {
348 write!(f, "w{witness_index}")?;
349 if index != indices.len() - 1 {
350 write!(f, ", ")?;
351 }
352 }
353 writeln!(f, "]")
354 };
355
356 write!(f, "private parameters: ")?;
357 write_witness_indices(
358 f,
359 &circuit
360 .private_parameters
361 .iter()
362 .map(|witness| witness.witness_index())
363 .collect::<Vec<_>>(),
364 )?;
365
366 write!(f, "public parameters: ")?;
367 write_witness_indices(f, &circuit.public_parameters.indices())?;
368
369 write!(f, "return values: ")?;
370 write_witness_indices(f, &circuit.return_values.indices())?;
371
372 let assert_messages_by_opcode_location =
373 circuit.assert_messages.iter().cloned().collect::<HashMap<_, _>>();
374
375 for (index, opcode) in circuit.opcodes.iter().enumerate() {
376 display_opcode(opcode, Some(&circuit.return_values), f)?;
377
378 if let Some(error_types) = error_types {
379 let location = OpcodeLocation::Acir(index);
380 if let Some(payload) = assert_messages_by_opcode_location.get(&location)
381 && let Some(message) = error_types.get(&ErrorSelector::new(payload.error_selector))
382 {
383 write!(f, " // {message}")?;
384 }
385 }
386 writeln!(f)?;
387 }
388 Ok(())
389}
390
391impl<F: AcirField> std::fmt::Debug for Circuit<F> {
392 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393 std::fmt::Display::fmt(self, f)
394 }
395}
396
397impl<F: AcirField> std::fmt::Display for Program<F> {
398 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
399 display_program(self, None, f)
400 }
401}
402
403pub fn display_program<F: AcirField>(
404 program: &Program<F>,
405 error_types: Option<&HashMap<ErrorSelector, String>>,
406 f: &mut std::fmt::Formatter<'_>,
407) -> std::fmt::Result {
408 for (func_index, function) in program.functions.iter().enumerate() {
409 writeln!(f, "func {func_index}")?;
410 display_circuit(function, error_types, f)?;
411 writeln!(f)?;
412 }
413 for (func_index, function) in program.unconstrained_functions.iter().enumerate() {
414 writeln!(f, "unconstrained func {func_index}: {}", function.function_name)?;
415 let width = function.bytecode.len().to_string().len();
416 for (index, opcode) in function.bytecode.iter().enumerate() {
417 write!(f, "{index:>width$}: {opcode}")?;
418
419 if let ::brillig::Opcode::IndirectConst { value, .. } = opcode
420 && let Some(value) = value.try_to_u64()
421 && let Some(message) =
422 error_types.and_then(|error_types| error_types.get(&ErrorSelector::new(value)))
423 {
424 write!(f, " // {message:?}")?;
425 }
426
427 writeln!(f)?;
428 }
429 }
430 Ok(())
431}
432
433impl<F: AcirField> std::fmt::Debug for Program<F> {
434 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
435 std::fmt::Display::fmt(self, f)
436 }
437}
438
439#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default, Hash, MsgpackTagged)]
440#[cfg_attr(feature = "arb", derive(proptest_derive::Arbitrary))]
441pub struct PublicInputs(pub BTreeSet<Witness>);
442
443impl PublicInputs {
444 pub fn indices(&self) -> Vec<u32> {
446 self.0.iter().map(|witness| witness.witness_index()).collect()
447 }
448
449 pub fn contains(&self, index: usize) -> bool {
450 self.0.contains(&Witness(index as u32))
451 }
452}
453
454#[cfg(test)]
455mod tests {
456 use super::{Circuit, Compression};
457 use crate::circuit::Program;
458 use acir_field::{AcirField, FieldElement};
459 use msgpack_tagged::MsgpackTagged;
460 use serde::{Deserialize, Serialize};
461
462 #[test]
463 fn serialization_roundtrip() {
464 let src = "
465 private parameters: []
466 public parameters: [w2, w12]
467 return values: [w4, w12]
468 BLACKBOX::AND lhs: w1, rhs: w2, output: w3, bits: 4
469 BLACKBOX::RANGE input: w1, bits: 8
470 ";
471 let circuit = Circuit::from_str(src).unwrap();
472 let program = Program { functions: vec![circuit], unconstrained_functions: Vec::new() };
473
474 fn read_write<F: Serialize + for<'a> Deserialize<'a> + AcirField + MsgpackTagged>(
475 program: Program<F>,
476 ) -> (Program<F>, Program<F>) {
477 let bytes = Program::serialize_program(&program);
478 let got_program = Program::deserialize_program(&bytes).unwrap();
479 (program, got_program)
480 }
481
482 let (circ, got_circ) = read_write(program);
483 assert_eq!(circ, got_circ);
484 }
485
486 #[test]
487 fn test_serialize() {
488 let src = "
489 private parameters: []
490 public parameters: [w2]
491 return values: [w2]
492 ASSERT 0 = 8
493 BLACKBOX::RANGE input: w1, bits: 8
494 BLACKBOX::AND lhs: w1, rhs: w2, output: w3, bits: 4
495 BLACKBOX::KECCAKF1600 inputs: [w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, w16, w17, w18, w19, w20, w21, w22, w23, w24, w25], outputs: [w26, w27, w28, w29, w30, w31, w32, w33, w34, w35, w36, w37, w38, w39, w40, w41, w42, w43, w44, w45, w46, w47, w48, w49, w50]
496 ";
497 let circuit = Circuit::from_str(src).unwrap();
498 let program = Program { functions: vec![circuit], unconstrained_functions: Vec::new() };
499
500 let json = serde_json::to_string_pretty(&program).unwrap();
501
502 let deserialized = serde_json::from_str(&json).unwrap();
503 assert_eq!(program, deserialized);
504 }
505
506 #[test]
507 fn does_not_panic_on_invalid_circuit() {
508 use std::io::Write;
509
510 let bad_circuit = "I'm not an ACIR circuit".as_bytes();
511
512 let mut zipped_bad_circuit = Vec::new();
514 let mut encoder =
515 flate2::write::GzEncoder::new(&mut zipped_bad_circuit, Compression::default());
516 encoder.write_all(bad_circuit).unwrap();
517 encoder.finish().unwrap();
518
519 let deserialization_result: Result<Program<FieldElement>, _> =
520 Program::deserialize_program(&zipped_bad_circuit);
521 assert!(deserialization_result.is_err());
522 }
523
524 #[test]
525 fn circuit_display_snapshot() {
526 let src = "
527 private parameters: []
528 public parameters: [w2]
529 return values: [w2]
530 ASSERT 0 = 2*w1 + 8
531 BLACKBOX::RANGE input: w1, bits: 8
532 BLACKBOX::AND lhs: w1, rhs: w2, output: w3, bits: 4
533 BLACKBOX::KECCAKF1600 inputs: [w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, w16, w17, w18, w19, w20, w21, w22, w23, w24, w25], outputs: [w26, w27, w28, w29, w30, w31, w32, w33, w34, w35, w36, w37, w38, w39, w40, w41, w42, w43, w44, w45, w46, w47, w48, w49, w50]
534 ";
535 let circuit = Circuit::from_str(src).unwrap();
536
537 insta::assert_snapshot!(
539 circuit.to_string(),
540 @r"
541 private parameters: []
542 public parameters: [w2]
543 return values: [w2]
544 ASSERT 0 = 2*w1 + 8
545 BLACKBOX::RANGE input: w1, bits: 8
546 BLACKBOX::AND lhs: w1, rhs: w2, output: w3, bits: 4
547 BLACKBOX::KECCAKF1600 inputs: [w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15, w16, w17, w18, w19, w20, w21, w22, w23, w24, w25], outputs: [w26, w27, w28, w29, w30, w31, w32, w33, w34, w35, w36, w37, w38, w39, w40, w41, w42, w43, w44, w45, w46, w47, w48, w49, w50]
548 "
549 );
550 }
551
552 #[test]
560 fn ensure_program_is_msgpack_tagged() {
561 fn assert_impl<T: MsgpackTagged>() {}
562 assert_impl::<Program<FieldElement>>();
563 }
564
565 mod props {
567 use acir_field::FieldElement;
568 use msgpack_tagged::MsgpackTagged;
569 use proptest::prelude::*;
570 use proptest::test_runner::{TestCaseResult, TestRunner};
571
572 use crate::circuit::Program;
573 use crate::native_types::{WitnessMap, WitnessStack};
574 use crate::serialization::*;
575
576 const MAX_SIZE_RANGE: usize = 5;
584 const SIZE_RANGE_KEY: &str = "PROPTEST_MAX_DEFAULT_SIZE_RANGE";
585
586 acir_field::field_wrapper!(TestField, FieldElement);
590
591 impl Arbitrary for TestField {
592 type Parameters = ();
593 type Strategy = BoxedStrategy<Self>;
594
595 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
596 any::<u128>().prop_map(|v| Self(FieldElement::from(v))).boxed()
597 }
598 }
599
600 impl MsgpackTagged for TestField {
601 const TAGGED: msgpack_tagged::Tagged = msgpack_tagged::Tagged::empty_product();
602 fn register_into(_reg: &mut msgpack_tagged::TagRegistry) {}
603 }
604
605 #[allow(unsafe_code)]
607 fn run_with_max_size_range<T, F>(cases: u32, f: F)
608 where
609 T: Arbitrary,
610 F: Fn(T) -> TestCaseResult,
611 {
612 let orig_size_range = std::env::var(SIZE_RANGE_KEY).ok();
613 if orig_size_range.is_none() {
615 unsafe {
616 std::env::set_var(SIZE_RANGE_KEY, MAX_SIZE_RANGE.to_string());
617 }
618 }
619
620 let mut runner = TestRunner::new(ProptestConfig { cases, ..Default::default() });
621 let result = runner.run(&any::<T>(), f);
622
623 unsafe {
625 std::env::set_var(SIZE_RANGE_KEY, orig_size_range.unwrap_or_default());
626 }
627
628 result.unwrap();
629 }
630
631 #[test]
636 fn prop_program_arb_roundtrip() {
637 run_with_max_size_range(100, |(program, format): (Program<TestField>, Format)| {
638 let bz = serialize_with_format(&program, format)?;
639 let de = deserialize_any_format(&bz)?;
640 prop_assert_eq!(program, de);
641 Ok(())
642 });
643 }
644
645 #[test]
646 fn prop_program_roundtrip() {
647 run_with_max_size_range(10, |program: Program<TestField>| {
648 let bz = Program::serialize_program(&program);
649 let de = Program::deserialize_program(&bz)?;
650 prop_assert_eq!(program, de);
651 Ok(())
652 });
653 }
654
655 #[test]
656 fn prop_witness_stack_arb_roundtrip() {
657 run_with_max_size_range(10, |(witness, format): (WitnessStack<TestField>, Format)| {
658 let bz = serialize_with_format(&witness, format)?;
659 let de = deserialize_any_format(&bz)?;
660 prop_assert_eq!(witness, de);
661 Ok(())
662 });
663 }
664
665 #[test]
666 fn prop_witness_stack_roundtrip() {
667 run_with_max_size_range(10, |witness: WitnessStack<TestField>| {
668 let bz = witness.serialize()?;
669 let de = WitnessStack::deserialize(bz.as_slice())?;
670 prop_assert_eq!(witness, de);
671 Ok(())
672 });
673 }
674
675 #[test]
676 fn prop_witness_map_arb_roundtrip() {
677 run_with_max_size_range(10, |(witness, format): (WitnessMap<TestField>, Format)| {
678 let bz = serialize_with_format(&witness, format)?;
679 let de = deserialize_any_format(&bz)?;
680 prop_assert_eq!(witness, de);
681 Ok(())
682 });
683 }
684
685 #[test]
686 fn prop_witness_map_roundtrip() {
687 run_with_max_size_range(10, |witness: WitnessMap<TestField>| {
688 let bz = witness.serialize()?;
689 let de = WitnessMap::deserialize(bz.as_slice())?;
690 prop_assert_eq!(witness, de);
691 Ok(())
692 });
693 }
694 }
695}