acir/circuit/
mod.rs

1//! Native structures for representing ACIR
2
3pub 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/// A program represented by multiple ACIR [circuit][Circuit]'s. The execution trace of these
29/// circuits is dictated by construction of the [crate::native_types::WitnessStack].
30#[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/// Representation of a single ACIR circuit. The execution trace of this structure
41/// is dictated by the construction of a [crate::native_types::WitnessMap]
42#[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    /// Name of the function represented by this circuit.
47    #[tag(0)]
48    pub function_name: String,
49    /// The circuit opcodes representing the relationship between witness values.
50    ///
51    /// The opcodes should be further converted into a backend-specific circuit representation.
52    /// When initial witness inputs are provided, these opcodes can also be used for generating an execution trace.
53    #[tag(1)]
54    pub opcodes: Vec<Opcode<F>>,
55    /// The set of private inputs to the circuit.
56    #[tag(2)]
57    pub private_parameters: BTreeSet<Witness>,
58    // ACIR distinguishes between the public inputs which are provided externally or calculated within the circuit and returned.
59    // The elements of these sets may not be mutually exclusive, i.e. a parameter may be returned from the circuit.
60    // All public inputs (parameters and return values) must be provided to the verifier at verification time.
61    /// The set of public inputs provided by the prover.
62    #[tag(3)]
63    pub public_parameters: PublicInputs,
64    /// The set of public inputs calculated within the circuit.
65    #[tag(4)]
66    pub return_values: PublicInputs,
67    /// Maps opcode locations to failed assertion payloads.
68    /// The data in the payload is embedded in the circuit to provide useful feedback to users
69    /// when a constraint in the circuit is not satisfied.
70    ///
71    // Note: This should be a BTreeMap, but serde-reflect is creating invalid
72    // c++ code at the moment when it is, due to OpcodeLocation needing a comparison
73    // implementation which is never generated.
74    #[tag(5)]
75    pub assert_messages: Vec<(OpcodeLocation, AssertionPayload<F>)>,
76}
77
78/// Enumeration of either an [expression][Expression] or a [memory identifier][BlockId].
79#[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/// Payload tied to an assertion failure.
90/// This data allows users to specify feedback upon a constraint not being satisfied in the circuit.
91#[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    /// Selector that maps a hash of either a constant string or an internal compiler error type
96    /// to an ABI type. The ABI type should then be used to appropriately resolve the payload data.
97    #[tag(0)]
98    pub error_selector: u64,
99    /// The dynamic payload data.
100    ///
101    /// Upon fetching the appropriate ABI type from the `error_selector`, the values
102    /// in this payload can be decoded into the given ABI type.
103    /// The payload is expected to be empty in the case of a constant string
104    /// as the string can be contained entirely within the error type and ABI type.
105    #[tag(1)]
106    pub payload: Vec<ExpressionOrMemory<F>>,
107}
108
109/// Value for differentiating error types. Used internally by an [AssertionPayload].
110#[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))]
146/// Opcodes are locatable so that callers can
147/// map opcodes to debug information related to their context.
148pub enum OpcodeLocation {
149    #[tag(0)]
150    Acir(usize),
151    // TODO(https://github.com/noir-lang/noir/issues/5792): We can not get rid of this enum field entirely just yet as this format is still
152    // used for resolving assert messages which is a breaking serialization change.
153    #[tag(1)]
154    Brillig {
155        #[tag(0)]
156        acir_index: usize,
157        #[tag(1)]
158        brillig_index: usize,
159    },
160}
161
162/// Opcodes are locatable so that callers can
163/// map opcodes to debug information related to their context.
164#[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/// Index of Brillig opcode within a list of Brillig opcodes.
181/// To be used by callers for resolving debug information.
182#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
183pub struct BrilligOpcodeLocation(pub usize);
184
185impl OpcodeLocation {
186    // Utility method to allow easily comparing a resolved Brillig location and a debug Brillig location.
187    // This method is useful when fetching Brillig debug locations as this does not need an ACIR index,
188    // and just need the Brillig index.
189    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
216/// The implementation of display and FromStr allows serializing and deserializing a OpcodeLocation to a string.
217/// This is useful when used as key in a map that has to be serialized to JSON/TOML, for example when mapping an opcode to its metadata.
218impl 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    /// Returns all witnesses which are required to execute the circuit successfully.
256    pub fn circuit_arguments(&self) -> BTreeSet<Witness> {
257        self.private_parameters.union(&self.public_parameters.0).copied().collect()
258    }
259
260    /// Returns all public inputs. This includes those provided as parameters to the circuit and those
261    /// computed as return values.
262    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    /// Compress a serialized [Program].
271    fn compress(buf: Vec<u8>) -> std::io::Result<Vec<u8>> {
272        let mut compressed: Vec<u8> = Vec::new();
273        // Compress the data, which should help with formats that uses field names.
274        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    /// Serialize and compress a [Program] into bytes, using the given format.
281    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    /// Serialize and compress a [Program] into bytes, using the format from the environment, or the default format.
288    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    /// Serialize, compress then base64 encode a [Program], using the format from the environment, or the default format,
294    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    /// Decompress and deserialize bytes into a [Program].
306    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    /// Deserialize bytecode.
315    pub fn deserialize_program(serialized_circuit: &[u8]) -> std::io::Result<Self> {
316        Program::read(serialized_circuit)
317    }
318
319    /// Deserialize and base64 decode program
320    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    /// Returns the witness index of each public input
445    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        // We expect to load circuits as compressed artifacts so we compress the junk circuit.
513        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        // All witnesses are expected to be formatted as `w{witness_index}`.
538        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    /// This test is a reminder that when we slap `#[derive(MsgpackTagged)]` on type,
553    /// we only get immediate compilation errors for non-generic fields that
554    /// don't implement `MsgpackTagged`; for generic types like `Circuit<F>`
555    /// in `Program<F>`, we may or may not have an implementation, depending on `F`.
556    ///
557    /// A test like this brings out all the concrete missing implementations by
558    /// choosing a particular `F`.
559    #[test]
560    fn ensure_program_is_msgpack_tagged() {
561        fn assert_impl<T: MsgpackTagged>() {}
562        assert_impl::<Program<FieldElement>>();
563    }
564
565    /// Property based testing for serialization
566    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        // It's not possible to set the maximum size of collections via `ProptestConfig`, only an env var,
577        // because e.g. the `VecStrategy` uses `Config::default().max_default_size_range`. On top of that,
578        // `Config::default()` reads a static `DEFAULT_CONFIG`, which gets the env vars only once at the
579        // beginning, so we can't override this on a test-by-test basis, unless we use `fork`,
580        // which is a feature that is currently disabled, because it doesn't work with Wasm.
581        // We could add it as a `dev-dependency` just for this crate, but when I tried it just crashed.
582        // For now using a const so it's obvious we can't set it to different values for different tests.
583        const MAX_SIZE_RANGE: usize = 5;
584        const SIZE_RANGE_KEY: &str = "PROPTEST_MAX_DEFAULT_SIZE_RANGE";
585
586        // Define a wrapper around field so we can implement `Arbitrary`.
587        // NB there are other methods like `arbitrary_field_elements` around the codebase,
588        // but for `proptest_derive::Arbitrary` we need `F: AcirField + Arbitrary`.
589        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        /// Override the maximum size of collections created by `proptest`.
606        #[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            // The defaults are only read once. If they are already set, leave them be.
614            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            // Restore the original.
624            unsafe {
625                std::env::set_var(SIZE_RANGE_KEY, orig_size_range.unwrap_or_default());
626            }
627
628            result.unwrap();
629        }
630
631        /// Round-trip a `Program` through each `Format` variant chosen
632        /// arbitrarily. Uses `serialize_with_format` + `deserialize_any_format`
633        /// so the framing-byte dispatch is exercised too — picks the right
634        /// encoder/decoder pair per format under one test name.
635        #[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}