arcium-core-utils 0.8.6

Arcium core utils
Documentation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! `testdata/circuit.bin` is the `bincode` encoding of `(sample_circuit(), all_gates())`, and
//! records what this format version encodes.
//!
//! `bincode` encodes enum discriminants by declaration order. Reordering or inserting a
//! [`Gate`]/op variant, or any [`Circuit`] field, changes what a previously serialized circuit
//! decodes to.
//!
//! The fixture MUST stay current: `fixture_is_current` rewrites it in place whenever it drifts
//! from `all_gates()`/`sample_circuit()`, then fails so the regenerated file cannot go
//! uncommitted. That keeps it a faithful record of what this format encodes.
//!
//! Compatibility is therefore judged against the *base branch's* fixture, not this one: CI hands
//! `base_fixture_still_decodes` those bytes, and today's code MUST decode them to a prefix of
//! `all_gates()`. Appending a [`Gate`] variant preserves that, since existing discriminants keep
//! their index; a reorder, insert, removal or field change does not. Gates MUST therefore only
//! ever be appended to `all_gates()`, matching the rule on the enum itself, and `sample_circuit()`
//! MUST NOT change without a bump. Regenerating the fixture cannot hide a break -- the reference
//! bytes live in the base branch's history.
//!
//! On an intentional format bump, where N is today's `CIRCUIT_FORMAT_VERSION`:
//! 1. Copy the base branch's `testdata/circuit.bin` verbatim into `old/vN/testdata/`.
//! 2. Copy this module's builders into `old/vN/` (see `old::v2::format_guard` for the recipe).
//! 3. Make the format change and bump `CIRCUIT_FORMAT_VERSION` in `compressed_circuit.rs` to N+1.
//! 4. Run the tests: `fixture_is_current` rewrites `testdata/circuit.bin` for the new format.
//!
//! `.github/scripts/circuit_format_guard.sh` enforces these steps in CI.

use std::collections::{BTreeMap, BTreeSet};

use primitives::{
    algebra::{
        elliptic_curve::{BaseFieldElement, Curve25519Ristretto as EC, Point, Scalar},
        field::Bit,
        BoxedUint,
    },
    utils::codec::bincode_io,
};
use strum::VariantNames;

use crate::{
    circuit::latest::{
        AlgebraicType,
        BitPlaintextBinaryOp,
        BitPlaintextUnaryOp,
        BitShareBinaryOp,
        BitShareUnaryOp,
        Circuit,
        Constant,
        ConstraintClause,
        ConstraintExpr,
        DigestAlgorithm,
        Encoding,
        FieldPlaintextBinaryOp,
        FieldPlaintextUnaryOp,
        FieldShareBinaryOp,
        FieldShareUnaryOp,
        FieldType,
        Gate,
        Input,
        OnAmbiguity,
        PlaintextBitConstraint,
        PointPlaintextBinaryOp,
        PointPlaintextUnaryOp,
        PointShareBinaryOp,
        PointShareUnaryOp,
        Relation,
        SignatureScheme,
        Slice,
        SliceEnum,
    },
    config::{DefaultConfig as C, MpcFieldElement},
};

/// One instance of every [`Gate`] variant, and every op variant for op-carrying gates.
fn all_gates() -> Vec<Gate<C>> {
    let scalar = || Scalar::<EC>::from(1u64);
    let base_field = || BaseFieldElement::<EC>::from(1u64);
    let mpc_field = || MpcFieldElement::<C>::from(1u64);
    let bit = || Bit::from(false);
    let point = || Point::<EC>::identity();
    let exp = || BoxedUint::from(vec![1u64]);

    vec![
        // Input
        Gate::Input(Input::Plaintext {
            algebraic_type: AlgebraicType::BaseField,
            batch_size: 1,
        }),
        Gate::Input(Input::SecretPlaintext {
            inputer: 0,
            algebraic_type: AlgebraicType::ScalarField,
            batch_size: 1,
        }),
        Gate::Input(Input::Share {
            algebraic_type: AlgebraicType::Point,
            batch_size: 1,
        }),
        // Constant
        Gate::Constant(Constant::Scalar(scalar())),
        Gate::Constant(Constant::ScalarBatch(vec![scalar()])),
        Gate::Constant(Constant::BaseField(base_field())),
        Gate::Constant(Constant::BaseFieldBatch(vec![base_field()])),
        Gate::Constant(Constant::MpcField(mpc_field())),
        Gate::Constant(Constant::MpcFieldBatch(vec![mpc_field()])),
        Gate::Constant(Constant::Bit(bit())),
        Gate::Constant(Constant::BitBatch(vec![bit()])),
        Gate::Constant(Constant::Point(Box::new(point()))),
        Gate::Constant(Constant::PointBatch(vec![point()])),
        // Random
        Gate::Random {
            algebraic_type: AlgebraicType::BaseField,
            batch_size: 1,
        },
        Gate::Random {
            algebraic_type: AlgebraicType::ScalarField,
            batch_size: 1,
        },
        Gate::Random {
            algebraic_type: AlgebraicType::Point,
            batch_size: 1,
        },
        Gate::Random {
            algebraic_type: AlgebraicType::Bit,
            batch_size: 1,
        },
        Gate::Random {
            algebraic_type: AlgebraicType::MpcField,
            batch_size: 1,
        },
        // FieldShareUnaryOp
        Gate::FieldShareUnaryOp {
            x: 0,
            op: FieldShareUnaryOp::Neg,
        },
        Gate::FieldShareUnaryOp {
            x: 0,
            op: FieldShareUnaryOp::MulInverse,
        },
        Gate::FieldShareUnaryOp {
            x: 0,
            op: FieldShareUnaryOp::Open,
        },
        Gate::FieldShareUnaryOp {
            x: 0,
            op: FieldShareUnaryOp::IsZero,
        },
        // FieldShareBinaryOp
        Gate::FieldShareBinaryOp {
            x: 0,
            y: 1,
            op: FieldShareBinaryOp::Add,
        },
        Gate::FieldShareBinaryOp {
            x: 0,
            y: 1,
            op: FieldShareBinaryOp::Mul,
        },
        // BatchSummation
        Gate::BatchSummation { x: 0 },
        // BitShareUnaryOp
        Gate::BitShareUnaryOp {
            x: 0,
            op: BitShareUnaryOp::Not,
        },
        Gate::BitShareUnaryOp {
            x: 0,
            op: BitShareUnaryOp::Open,
        },
        // BitShareBinaryOp
        Gate::BitShareBinaryOp {
            x: 0,
            y: 1,
            op: BitShareBinaryOp::Xor,
        },
        Gate::BitShareBinaryOp {
            x: 0,
            y: 1,
            op: BitShareBinaryOp::Or,
        },
        Gate::BitShareBinaryOp {
            x: 0,
            y: 1,
            op: BitShareBinaryOp::And,
        },
        // PointShareUnaryOp
        Gate::PointShareUnaryOp {
            p: 0,
            op: PointShareUnaryOp::Neg,
        },
        Gate::PointShareUnaryOp {
            p: 0,
            op: PointShareUnaryOp::Open,
        },
        Gate::PointShareUnaryOp {
            p: 0,
            op: PointShareUnaryOp::IsZero,
        },
        // PointShareBinaryOp
        Gate::PointShareBinaryOp {
            p: 0,
            y: 1,
            op: PointShareBinaryOp::Add,
        },
        Gate::PointShareBinaryOp {
            p: 0,
            y: 1,
            op: PointShareBinaryOp::ScalarMul,
        },
        // FieldPlaintextUnaryOp
        Gate::FieldPlaintextUnaryOp {
            x: 0,
            op: FieldPlaintextUnaryOp::Neg,
        },
        Gate::FieldPlaintextUnaryOp {
            x: 0,
            op: FieldPlaintextUnaryOp::MulInverse,
        },
        Gate::FieldPlaintextUnaryOp {
            x: 0,
            op: FieldPlaintextUnaryOp::BitExtract {
                little_endian_bit_idx: 0,
                signed: false,
            },
        },
        Gate::FieldPlaintextUnaryOp {
            x: 0,
            op: FieldPlaintextUnaryOp::Sqrt,
        },
        Gate::FieldPlaintextUnaryOp {
            x: 0,
            op: FieldPlaintextUnaryOp::Pow { exp: exp() },
        },
        // FieldPlaintextBinaryOp
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Add,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Mul,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::EuclDiv,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Mod,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Gt,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Ge,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Eq,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Xor,
        },
        Gate::FieldPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: FieldPlaintextBinaryOp::Or,
        },
        // BitPlaintextUnaryOp
        Gate::BitPlaintextUnaryOp {
            x: 0,
            op: BitPlaintextUnaryOp::Not,
        },
        // BitPlaintextBinaryOp
        Gate::BitPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: BitPlaintextBinaryOp::Xor,
        },
        Gate::BitPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: BitPlaintextBinaryOp::Or,
        },
        Gate::BitPlaintextBinaryOp {
            x: 0,
            y: 1,
            op: BitPlaintextBinaryOp::And,
        },
        // PointPlaintextUnaryOp
        Gate::PointPlaintextUnaryOp {
            p: 0,
            op: PointPlaintextUnaryOp::Neg,
        },
        // PointPlaintextBinaryOp
        Gate::PointPlaintextBinaryOp {
            p: 0,
            y: 1,
            op: PointPlaintextBinaryOp::Add,
        },
        Gate::PointPlaintextBinaryOp {
            p: 0,
            y: 1,
            op: PointPlaintextBinaryOp::ScalarMul,
        },
        // DaBit
        Gate::DaBit {
            field_type: FieldType::BaseField,
            batch_size: 1,
        },
        Gate::DaBit {
            field_type: FieldType::ScalarField,
            batch_size: 1,
        },
        Gate::DaBit {
            field_type: FieldType::MpcField,
            batch_size: 1,
        },
        Gate::GetDaBitFieldShare { x: 0 },
        Gate::GetDaBitSharedBit { x: 0 },
        Gate::BaseFieldPow { x: 0, exp: exp() },
        Gate::BitPlaintextToField {
            x: 0,
            field_type: FieldType::BaseField,
        },
        Gate::BitPlaintextToField {
            x: 0,
            field_type: FieldType::ScalarField,
        },
        Gate::BitPlaintextToField {
            x: 0,
            field_type: FieldType::MpcField,
        },
        Gate::FieldPlaintextToBit { x: 0 },
        // One per `SliceEnum` variant.
        Gate::ExtractFromBatch {
            x: 0,
            slice: Slice::single(0),
        },
        Gate::ExtractFromBatch {
            x: 0,
            slice: Slice::range(0, 2, 1).expect("valid slice"),
        },
        Gate::ExtractFromBatch {
            x: 0,
            slice: Slice::range2d(0, 2, 2, 1, 1).expect("valid slice"),
        },
        Gate::ExtractFromBatch {
            x: 0,
            slice: {
                let mut s = Slice::empty();
                s.append(Slice::single(0));
                s
            },
        },
        Gate::CollectToBatch { wires: vec![0, 1] },
        Gate::PointFromPlaintextCoordinates { wires: vec![0, 1] },
        Gate::PlaintextPointToCoordinates { point: 0 },
        Gate::PlaintextKeccakF1600 { x: 0 },
        Gate::CompressPlaintextPoint { point: 0 },
        Gate::KeyRecoveryPlaintextComputeErrors {
            d_minus_one: 0,
            syndromes: 1,
        },
        Gate::AesGcmKeyStream {
            round_keys: 0,
            iv: 1,
            n_ciphertext_blocks: 1,
        },
        Gate::GhashPowersOfH {
            h: 0,
            n_ciphertext_blocks: 1,
        },
        Gate::Ghash {
            x: 0,
            powers_of_h: 1,
        },
        Gate::AesKeySchedule { key: 0 },
        // One per `PlaintextBitConstraint` variant and one per `ConstraintExpr` variant, across
        // two clauses so a multi-clause disjunction is pinned too. The gate below covers
        // the other `OnAmbiguity` variant, so reordering that enum is caught as well.
        Gate::ConstrainPlaintextBits {
            x: 0,
            on_ambiguity: OnAmbiguity::Fail,
            clauses: vec![
                ConstraintClause::new(vec![
                    PlaintextBitConstraint::Signature {
                        scheme: SignatureScheme::Ed25519,
                        signature: ConstraintExpr::Slice(
                            Slice::range(0, 512, 1).expect("valid slice"),
                        ),
                        message: ConstraintExpr::Concat(vec![
                            ConstraintExpr::Constant(vec![0x31]),
                            ConstraintExpr::Slice(Slice::range(512, 8, 1).expect("valid slice")),
                            ConstraintExpr::Digest {
                                algorithm: DigestAlgorithm::Sha256,
                                of: Box::new(ConstraintExpr::Wire(1)),
                            },
                        ]),
                        public_key: ConstraintExpr::Wire(1),
                    },
                    PlaintextBitConstraint::Equality {
                        bits: ConstraintExpr::Slice(Slice::range(0, 2, 1).expect("valid slice")),
                        expected: ConstraintExpr::Constant(vec![0xff]),
                    },
                ]),
                ConstraintClause::new(vec![
                    PlaintextBitConstraint::Comparison {
                        relation: Relation::AtMost,
                        lhs: ConstraintExpr::Slice(Slice::range(0, 8, 1).expect("valid slice")),
                        rhs: ConstraintExpr::Decode {
                            encoding: Encoding::Base64UrlNoPad,
                            of: Box::new(ConstraintExpr::Wire(1)),
                        },
                    },
                    PlaintextBitConstraint::Comparison {
                        relation: Relation::AtLeast,
                        lhs: ConstraintExpr::Slice(Slice::range(0, 8, 1).expect("valid slice")),
                        rhs: ConstraintExpr::Constant(vec![0x01]),
                    },
                ]),
            ],
        },
        Gate::ConstrainPlaintextBits {
            x: 0,
            on_ambiguity: OnAmbiguity::TakeSmallestBits,
            clauses: vec![ConstraintClause::new(vec![
                PlaintextBitConstraint::Equality {
                    bits: ConstraintExpr::Slice(Slice::range(0, 2, 1).expect("valid slice")),
                    expected: ConstraintExpr::Constant(vec![0xff]),
                },
            ])],
        },
        Gate::GatherFromBatches {
            parts: vec![(0, Slice::single(0)), (1, Slice::range(0, 2, 1).unwrap())],
        },
    ]
}

/// A small valid circuit (two inputs, one add, one output), built via the public `Circuit` API.
/// Exercises the real `CompressedCircuit` envelope.
fn sample_circuit() -> Circuit<C> {
    let mut circuit = Circuit::new();
    let x = circuit
        .add_gate(Gate::Input(Input::SecretPlaintext {
            inputer: 0,
            algebraic_type: AlgebraicType::ScalarField,
            batch_size: 1,
        }))
        .expect("valid gate");
    let y = circuit
        .add_gate(Gate::Input(Input::SecretPlaintext {
            inputer: 1,
            algebraic_type: AlgebraicType::ScalarField,
            batch_size: 1,
        }))
        .expect("valid gate");
    let z = circuit
        .add_gate(Gate::FieldShareBinaryOp {
            x,
            y,
            op: FieldShareBinaryOp::Add,
        })
        .expect("valid gate");
    circuit.add_output(z).expect("valid output");
    circuit
}

/// Asserts every `T` variant appears among `covered`. A variant with no instance in `all_gates()`
/// never reaches the fixture, so its `bincode` discriminant is unpinned and a later reorder of it
/// goes undetected.
fn assert_covered<T: VariantNames>(ty: &str, covered: &BTreeSet<&str>) {
    let missing: Vec<&str> = T::VARIANTS
        .iter()
        .copied()
        .filter(|name| !covered.contains(name))
        .collect();

    assert!(
        missing.is_empty(),
        "\n\n`all_gates()` has no instance of {ty} variant(s) {missing:?}. Every variant MUST \
         appear in `all_gates()`, otherwise it is never encoded into `testdata/circuit.bin` and a \
         later reorder of it is invisible. Append one instance per variant, then regenerate the \
         fixture by re-running the tests.\n"
    );
}

/// `all_gates()` MUST instantiate every [`Gate`] variant and every op variant. Appending a variant
/// to an enum is wire-compatible, so nothing else here fails when one is forgotten -- the fixture
/// simply never covers it.
#[test]
fn all_gates_covers_every_variant() {
    let gates = all_gates();

    assert_covered::<Gate<C>>("Gate", &gates.iter().map(AsRef::as_ref).collect());

    macro_rules! assert_op_covered {
        ($ty:ty, $pattern:pat => $op:expr) => {
            assert_covered::<$ty>(
                stringify!($ty),
                &gates
                    .iter()
                    .filter_map(|gate| match gate {
                        $pattern => Some($op),
                        _ => None,
                    })
                    .collect(),
            );
        };
    }

    assert_op_covered!(Input, Gate::Input(input) => input.as_ref());
    assert_op_covered!(Constant<C>, Gate::Constant(constant) => constant.as_ref());
    assert_op_covered!(FieldShareUnaryOp, Gate::FieldShareUnaryOp { op, .. } => op.as_ref());
    assert_op_covered!(FieldShareBinaryOp, Gate::FieldShareBinaryOp { op, .. } => op.as_ref());
    assert_op_covered!(BitShareUnaryOp, Gate::BitShareUnaryOp { op, .. } => op.as_ref());
    assert_op_covered!(BitShareBinaryOp, Gate::BitShareBinaryOp { op, .. } => op.as_ref());
    assert_op_covered!(PointShareUnaryOp, Gate::PointShareUnaryOp { op, .. } => op.as_ref());
    assert_op_covered!(PointShareBinaryOp, Gate::PointShareBinaryOp { op, .. } => op.as_ref());
    assert_op_covered!(FieldPlaintextUnaryOp, Gate::FieldPlaintextUnaryOp { op, .. } => op.as_ref());
    assert_op_covered!(FieldPlaintextBinaryOp, Gate::FieldPlaintextBinaryOp { op, .. } => op.as_ref());
    assert_op_covered!(BitPlaintextUnaryOp, Gate::BitPlaintextUnaryOp { op, .. } => op.as_ref());
    assert_op_covered!(BitPlaintextBinaryOp, Gate::BitPlaintextBinaryOp { op, .. } => op.as_ref());
    assert_op_covered!(PointPlaintextUnaryOp, Gate::PointPlaintextUnaryOp { op, .. } => op.as_ref());
    assert_op_covered!(PointPlaintextBinaryOp, Gate::PointPlaintextBinaryOp { op, .. } => op.as_ref());

    // `AlgebraicType`/`FieldType` are covered at the gate that carries the widest set, not
    // globally: `Gate::Input` deliberately instantiates only three of the five `AlgebraicType`s.
    assert_op_covered!(AlgebraicType, Gate::Random { algebraic_type, .. } => algebraic_type.as_ref());
    assert_op_covered!(FieldType, Gate::DaBit { field_type, .. } => field_type.as_ref());

    assert_op_covered!(SliceEnum, Gate::ExtractFromBatch { slice, .. } => slice.inner().as_ref());
    assert_op_covered!(OnAmbiguity, Gate::ConstrainPlaintextBits { on_ambiguity, .. } => on_ambiguity.as_ref());

    // The constraint enums nest inside `ConstrainPlaintextBits`'s clauses, so they are gathered by
    // walking the expression tree rather than read off the gate.
    let mut found: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
    for gate in &gates {
        let Gate::ConstrainPlaintextBits { clauses, .. } = gate else {
            continue;
        };
        for constraint in clauses.iter().flat_map(ConstraintClause::constraints) {
            found
                .entry("constraint")
                .or_default()
                .insert(constraint.as_ref());
            match constraint {
                PlaintextBitConstraint::Signature { scheme, .. } => {
                    found.entry("scheme").or_default().insert(scheme.as_ref());
                }
                PlaintextBitConstraint::Comparison { relation, .. } => {
                    found
                        .entry("relation")
                        .or_default()
                        .insert(relation.as_ref());
                }
                PlaintextBitConstraint::Equality { .. } => {}
            }
            for operand in constraint.operands() {
                collect_exprs(operand, &mut found);
            }
        }
    }

    let empty = BTreeSet::new();
    let of = |key| found.get(key).unwrap_or(&empty).clone();
    assert_covered::<PlaintextBitConstraint>("PlaintextBitConstraint", &of("constraint"));
    assert_covered::<ConstraintExpr>("ConstraintExpr", &of("expr"));
    assert_covered::<DigestAlgorithm>("DigestAlgorithm", &of("digest"));
    assert_covered::<SignatureScheme>("SignatureScheme", &of("scheme"));
    assert_covered::<Relation>("Relation", &of("relation"));
    assert_covered::<Encoding>("Encoding", &of("encoding"));
}

/// Walks a [`ConstraintExpr`] tree, recording every variant and nested enum it reaches.
fn collect_exprs<'a>(expr: &'a ConstraintExpr, found: &mut BTreeMap<&str, BTreeSet<&'a str>>) {
    found.entry("expr").or_default().insert(expr.as_ref());
    match expr {
        ConstraintExpr::Concat(parts) => {
            for part in parts {
                collect_exprs(part, found);
            }
        }
        ConstraintExpr::Digest { algorithm, of } => {
            found
                .entry("digest")
                .or_default()
                .insert(algorithm.as_ref());
            collect_exprs(of, found);
        }
        ConstraintExpr::Decode { encoding, of } => {
            found
                .entry("encoding")
                .or_default()
                .insert(encoding.as_ref());
            collect_exprs(of, found);
        }
        ConstraintExpr::Slice(_) | ConstraintExpr::Constant(_) | ConstraintExpr::Wire(_) => {}
    }
}

/// `testdata/circuit.bin` MUST equal today's encoding: kept current, a bump can freeze it with a
/// plain copy and the next branch gets a faithful compat reference. Rewrites it on mismatch, then
/// fails so the regenerated file cannot go uncommitted.
#[test]
fn fixture_is_current() {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/src/circuit/latest/testdata/circuit.bin"
    );
    let bytes = bincode_io::serialize(&(sample_circuit(), all_gates()))
        .expect("circuit/gate bincode serialization");

    if std::fs::read(path).unwrap_or_default() != bytes {
        std::fs::write(path, &bytes).unwrap_or_else(|e| panic!("write {path}: {e}"));
        panic!(
            "\n\n`testdata/circuit.bin` was stale and has been regenerated -- commit it. This is \
             not by itself a wire-format break: appending a gate is compatible. \
             `base_fixture_still_decodes` decides that, and CI runs it against the base branch's \
             fixture.\n"
        );
    }
}

/// Decodes the base branch's fixture -- real bytes written by the previous code -- with today's
/// code. Its gate list MUST be a prefix of `all_gates()`: appending a variant preserves that,
/// while a reorder, insert, removal or field change breaks it.
///
/// CI supplies the path via `CIRCUIT_BASE_FIXTURE` (see
/// `.github/scripts/circuit_format_guard.sh`); without it this is a no-op, since the check needs
/// two revisions. Unlike [`fixture_is_current`], it CANNOT be silenced by regenerating: the bytes
/// live in the base branch's history.
#[test]
fn base_fixture_still_decodes() {
    let Ok(path) = std::env::var("CIRCUIT_BASE_FIXTURE") else {
        return;
    };
    let fixture = std::fs::read(&path).unwrap_or_else(|e| panic!("read base fixture {path}: {e}"));

    let (circuit, gates): (Circuit<C>, Vec<Gate<C>>) = bincode_io::deserialize(&fixture)
        .unwrap_or_else(|e| {
            panic!(
                "\n\nThe base branch's circuit fixture no longer deserializes with today's code \
                 ({e}), so the wire format broke. See this module's docs for the bump steps.\n"
            )
        });

    assert_eq!(
        circuit,
        sample_circuit(),
        "\n\nThe base branch's fixture no longer decodes to `sample_circuit()`. Either a \
         `latest::Circuit` field changed -- a wire-format break, see the module docs for the bump \
         steps -- or `sample_circuit()` was edited, which MUST NOT happen without a bump.\n"
    );

    let current = all_gates();
    assert!(
        gates.len() <= current.len(),
        "\n\nThe base branch's fixture holds {} gates but `all_gates()` now has only {}. Gates \
         MUST only ever be appended to `all_gates()`, never removed or replaced.\n",
        gates.len(),
        current.len()
    );

    if let Some((index, (before, now))) = gates
        .iter()
        .zip(current.iter())
        .enumerate()
        .find(|(_, (before, now))| before != now)
    {
        panic!(
            "\n\nGate {index} of the base branch's fixture decodes to a different value than \
             `all_gates()[{index}]`, so the wire format changed:\n  base: {before:?}\n  now:  \
             {now:?}\nA `Gate`/op variant was reordered, inserted or had a field changed. New \
             variants MUST be appended, never inserted. If the change is intentional, see the \
             module docs for the bump steps.\n"
        );
    }
}