voting-circuits 0.7.0

Governance ZKP circuits (delegation, vote proof, share reveal) for the Zcash shielded-voting protocol.
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! Shared circuit gadget for the shares-hash computation used in ZKP #2 and ZKP #3.
//!
//! This module is the authoritative in-tree definition of the two-level
//! encrypted-share hash. Both the vote-proof circuit (ZKP #2, condition 10) and
//! the share-reveal circuit (ZKP #3, condition 3) call this implementation
//! rather than maintaining separate formula copies:
//!
//! ```text
//! share_comm_i = Poseidon(blind_i, c1_i_x, c2_i_x, c1_i_y, c2_i_y)   for i ∈ 0..16
//! shares_hash  = Poseidon(share_comm_0, …, share_comm_15)
//! ```
//!
//! The y-coordinates are included to bind each share commitment to the exact
//! curve point, preventing ciphertext sign-malleability attacks where an
//! adversary negates ElGamal ciphertext points without invalidating the ZKP.
//!
//! `shares_hash` is a reusable internal circuit value, not a public instance
//! by itself. ZKP #2 binds it to the verifier only by feeding it into the
//! public vote commitment, while ZKP #3 binds it transitively through the same
//! vote commitment tree path.
//!
//! This module extracts those constraints into a single, auditable gadget so
//! that both circuits provably execute the same hash logic.

use halo2_gadgets::poseidon::{
    primitives::{self as poseidon, ConstantLength},
    Hash as PoseidonHash, Pow5Chip as PoseidonChip,
};
use halo2_proofs::{
    circuit::{AssignedCell, Layouter},
    plonk,
};
use itertools::Itertools;
use pasta_curves::pallas;

/// Native per-share blinded commitment:
///
/// ```text
/// share_comm = Poseidon(blind, c1_x, c2_x, c1_y, c2_y)
/// ```
///
/// The y-coordinates bind the commitment to the exact curve point, preventing
/// ciphertext sign-malleability. The blind factor prevents anyone who sees the
/// encrypted shares on-chain from recomputing `shares_hash` and linking it to a
/// specific vote commitment.
pub fn share_commitment(
    blind: pallas::Base,
    c1_x: pallas::Base,
    c2_x: pallas::Base,
    c1_y: pallas::Base,
    c2_y: pallas::Base,
) -> pallas::Base {
    poseidon::Hash::<_, poseidon::P128Pow5T3, ConstantLength<5>, 3, 2>::init()
        .hash([blind, c1_x, c2_x, c1_y, c2_y])
}

/// Native full two-level shares hash:
///
/// ```text
/// share_comm_i = Poseidon(blind_i, c1_i_x, c2_i_x, c1_i_y, c2_i_y)   for i ∈ 0..16
/// shares_hash  = Poseidon(share_comm_0, …, share_comm_15)
/// ```
///
/// Native counterpart of [`compute_shares_hash_in_circuit`].
pub fn shares_hash(
    share_blinds: [pallas::Base; 16],
    enc_share_c1_x: [pallas::Base; 16],
    enc_share_c2_x: [pallas::Base; 16],
    enc_share_c1_y: [pallas::Base; 16],
    enc_share_c2_y: [pallas::Base; 16],
) -> pallas::Base {
    let comms: [pallas::Base; 16] = core::array::from_fn(|i| {
        share_commitment(
            share_blinds[i],
            enc_share_c1_x[i],
            enc_share_c2_x[i],
            enc_share_c1_y[i],
            enc_share_c2_y[i],
        )
    });
    shares_hash_from_comms(comms)
}

/// Computes a single blinded per-share commitment in-circuit:
///
/// ```text
/// share_comm = Poseidon(blind, c1_x, c2_x, c1_y, c2_y)
/// ```
///
/// The y-coordinates bind the commitment to the exact curve point, preventing
/// ciphertext sign-malleability. The `index` is used only for namespace labels
/// and has no effect on the constraint system.
pub(crate) fn hash_share_commitment_in_circuit(
    chip: PoseidonChip<pallas::Base, 3, 2>,
    mut layouter: impl Layouter<pallas::Base>,
    blind: AssignedCell<pallas::Base, pallas::Base>,
    enc_c1_x: AssignedCell<pallas::Base, pallas::Base>,
    enc_c2_x: AssignedCell<pallas::Base, pallas::Base>,
    enc_c1_y: AssignedCell<pallas::Base, pallas::Base>,
    enc_c2_y: AssignedCell<pallas::Base, pallas::Base>,
    index: usize,
) -> Result<AssignedCell<pallas::Base, pallas::Base>, plonk::Error> {
    let hasher =
        PoseidonHash::<pallas::Base, _, poseidon::P128Pow5T3, ConstantLength<5>, 3, 2>::init(
            chip,
            layouter.namespace(|| format!("share_comm_{index} Poseidon init")),
        )?;
    hasher.hash(
        layouter.namespace(|| {
            format!("share_comm_{index} = Poseidon(blind, c1_x, c2_x, c1_y, c2_y)[{index}]")
        }),
        [blind, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y],
    )
}

/// Computes the two-level shares hash in-circuit:
///
/// ```text
/// share_comm_i = Poseidon(blind_i, c1_i_x, c2_i_x, c1_i_y, c2_i_y)   for i ∈ 0..16
/// shares_hash  = Poseidon(share_comm_0, …, share_comm_15)
/// ```
///
/// # Arguments
///
/// * `poseidon_chip` — A closure that returns a fresh `PoseidonChip` each time
///   it is called. It is called 17 times: once per per-share hash and once for
///   the outer hash. Typically `|| config.poseidon_chip()`.
/// * `layouter` — The circuit layouter.
/// * `blinds` — The 16 per-share blind factors.
/// * `enc_c1_x` — The 16 El Gamal `C1` x-coordinates.
/// * `enc_c2_x` — The 16 El Gamal `C2` x-coordinates.
/// * `enc_c1_y` — The 16 El Gamal `C1` y-coordinates.
/// * `enc_c2_y` — The 16 El Gamal `C2` y-coordinates.
///
/// Returns the internal `shares_hash` cell. The caller is responsible for
/// consuming that cell in a public binding, such as the vote commitment hash;
/// this gadget does not constrain the result to an instance column.
pub(crate) fn compute_shares_hash_in_circuit(
    poseidon_chip: impl Fn() -> PoseidonChip<pallas::Base, 3, 2>,
    mut layouter: impl Layouter<pallas::Base>,
    blinds: [AssignedCell<pallas::Base, pallas::Base>; 16],
    enc_c1_x: [AssignedCell<pallas::Base, pallas::Base>; 16],
    enc_c2_x: [AssignedCell<pallas::Base, pallas::Base>; 16],
    enc_c1_y: [AssignedCell<pallas::Base, pallas::Base>; 16],
    enc_c2_y: [AssignedCell<pallas::Base, pallas::Base>; 16],
) -> Result<AssignedCell<pallas::Base, pallas::Base>, plonk::Error> {
    let share_comms: [_; 16] = IntoIterator::into_iter(blinds)
        .zip_eq(enc_c1_x)
        .zip_eq(enc_c2_x)
        .zip_eq(enc_c1_y)
        .zip_eq(enc_c2_y)
        .enumerate()
        .map(|(i, ((((blind, c1x), c2x), c1y), c2y))| {
            hash_share_commitment_in_circuit(
                poseidon_chip(),
                layouter.namespace(|| format!("share_comm_{i}")),
                blind,
                c1x,
                c2x,
                c1y,
                c2y,
                i,
            )
        })
        .collect::<Result<Vec<_>, _>>()?
        .try_into()
        .expect("always 16 elements");

    // Outer hash: shares_hash = Poseidon(share_comm_0, …, share_comm_15)
    let hasher = PoseidonHash::<
        pallas::Base,
        _,
        poseidon::P128Pow5T3,
        ConstantLength<16>,
        3, // WIDTH
        2, // RATE
    >::init(
        poseidon_chip(),
        layouter.namespace(|| "shares_hash Poseidon init"),
    )?;
    hasher.hash(
        layouter.namespace(|| "shares_hash = Poseidon(share_comms)"),
        share_comms,
    )
}

/// Computes the shares hash in-circuit from pre-computed share commitments:
///
/// ```text
/// shares_hash = Poseidon(share_comm_0, …, share_comm_15)
/// ```
///
/// Unlike [`compute_shares_hash_in_circuit`], this skips the per-share
/// blind hashing (level 1) because the caller already provides the 16
/// `share_comm` values — e.g. as private witness cells in ZKP #3.
///
/// Returns an internal cell; callers must bind it transitively through their
/// own public commitment path.
pub(crate) fn compute_shares_hash_from_comms_in_circuit(
    poseidon_chip: PoseidonChip<pallas::Base, 3, 2>,
    mut layouter: impl Layouter<pallas::Base>,
    share_comms: [AssignedCell<pallas::Base, pallas::Base>; 16],
) -> Result<AssignedCell<pallas::Base, pallas::Base>, plonk::Error> {
    let hasher = PoseidonHash::<
        pallas::Base,
        _,
        poseidon::P128Pow5T3,
        ConstantLength<16>,
        3, // WIDTH
        2, // RATE
    >::init(
        poseidon_chip,
        layouter.namespace(|| "shares_hash Poseidon init"),
    )?;
    hasher.hash(
        layouter.namespace(|| "shares_hash = Poseidon(share_comms)"),
        share_comms,
    )
}

/// Native counterpart of [`compute_shares_hash_from_comms_in_circuit`].
///
/// Computes `Poseidon(share_comm_0, …, share_comm_15)` outside the circuit.
pub fn shares_hash_from_comms(share_comms: [pallas::Base; 16]) -> pallas::Base {
    poseidon::Hash::<_, poseidon::P128Pow5T3, ConstantLength<16>, 3, 2>::init().hash(share_comms)
}

#[cfg(test)]
mod tests {
    use super::*;

    use ff::{Field, PrimeField};
    use halo2_gadgets::poseidon::Pow5Config as PoseidonConfig;
    use halo2_proofs::{
        circuit::{floor_planner, Value},
        dev::MockProver,
        plonk::{Advice, Column, ConstraintSystem, Fixed, Instance as InstanceColumn},
    };
    use rand::rngs::OsRng;

    // ---------------------------------------------------------------
    // Shared minimal circuit config (Poseidon only, no ECC).
    // ---------------------------------------------------------------

    #[derive(Clone)]
    struct TestConfig {
        primary: Column<InstanceColumn>,
        advice: Column<Advice>,
        poseidon_config: PoseidonConfig<pallas::Base, 3, 2>,
    }

    impl TestConfig {
        fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self {
            let primary = meta.instance_column();
            meta.enable_equality(primary);

            // 5 advice columns: [0] general witness, [1..4] Poseidon state.
            let advices: [Column<Advice>; 5] = core::array::from_fn(|_| meta.advice_column());
            for col in &advices {
                meta.enable_equality(*col);
            }

            let fixed: [Column<Fixed>; 6] = core::array::from_fn(|_| meta.fixed_column());
            // Dedicated constants column required by Poseidon strict range checks.
            let constants = meta.fixed_column();
            meta.enable_constant(constants);
            let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
                meta,
                advices[1..4].try_into().unwrap(),
                advices[4],
                fixed[0..3].try_into().unwrap(),
                fixed[3..6].try_into().unwrap(),
            );

            TestConfig {
                primary,
                advice: advices[0],
                poseidon_config,
            }
        }

        fn poseidon_chip(&self) -> PoseidonChip<pallas::Base, 3, 2> {
            PoseidonChip::construct(self.poseidon_config.clone())
        }
    }

    /// Witnesses a single field element into the advice column.
    fn witness(
        mut layouter: impl Layouter<pallas::Base>,
        col: Column<Advice>,
        val: Value<pallas::Base>,
    ) -> Result<AssignedCell<pallas::Base, pallas::Base>, plonk::Error> {
        layouter.assign_region(
            || "witness",
            |mut region| region.assign_advice(|| "val", col, 0, || val),
        )
    }

    // ================================================================
    // hash_share_commitment_in_circuit
    // ================================================================

    fn base_from_repr(bytes: [u8; 32]) -> pallas::Base {
        pallas::Base::from_repr(bytes).expect("frozen vector must be canonical")
    }

    #[test]
    fn share_commitment_frozen_vector() {
        let actual = share_commitment(
            pallas::Base::from(1u64),
            pallas::Base::from(2u64),
            pallas::Base::from(3u64),
            pallas::Base::from(4u64),
            pallas::Base::from(5u64),
        );

        assert_eq!(
            actual,
            base_from_repr([
                183, 66, 173, 64, 240, 83, 206, 161, 132, 211, 79, 38, 240, 12, 144, 142, 247, 139,
                173, 56, 54, 59, 51, 73, 42, 113, 240, 242, 21, 103, 150, 29,
            ])
        );
    }

    #[test]
    fn shares_hash_frozen_vector() {
        let blinds = core::array::from_fn(|i| pallas::Base::from((i + 1) as u64));
        let enc_c1_x = core::array::from_fn(|i| pallas::Base::from((i + 17) as u64));
        let enc_c2_x = core::array::from_fn(|i| pallas::Base::from((i + 33) as u64));
        let enc_c1_y = core::array::from_fn(|i| pallas::Base::from((i + 49) as u64));
        let enc_c2_y = core::array::from_fn(|i| pallas::Base::from((i + 65) as u64));

        assert_eq!(
            shares_hash(blinds, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y),
            base_from_repr([
                125, 88, 190, 64, 180, 158, 228, 46, 43, 173, 80, 255, 152, 160, 47, 234, 86, 36,
                157, 87, 187, 167, 86, 239, 58, 45, 222, 42, 111, 6, 63, 28,
            ])
        );
    }

    /// Minimal circuit: computes `hash_share_commitment_in_circuit` and
    /// constrains the result to instance row 0.
    #[derive(Clone, Default)]
    struct HashShareCommCircuit {
        blind: pallas::Base,
        c1_x: pallas::Base,
        c2_x: pallas::Base,
        c1_y: pallas::Base,
        c2_y: pallas::Base,
    }

    impl plonk::Circuit<pallas::Base> for HashShareCommCircuit {
        type Config = TestConfig;
        type FloorPlanner = floor_planner::V1;

        fn without_witnesses(&self) -> Self {
            Self::default()
        }

        fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
            TestConfig::configure(meta)
        }

        fn synthesize(
            &self,
            config: Self::Config,
            mut layouter: impl Layouter<pallas::Base>,
        ) -> Result<(), plonk::Error> {
            let blind = witness(
                layouter.namespace(|| "blind"),
                config.advice,
                Value::known(self.blind),
            )?;
            let c1x = witness(
                layouter.namespace(|| "c1_x"),
                config.advice,
                Value::known(self.c1_x),
            )?;
            let c2x = witness(
                layouter.namespace(|| "c2_x"),
                config.advice,
                Value::known(self.c2_x),
            )?;
            let c1y = witness(
                layouter.namespace(|| "c1_y"),
                config.advice,
                Value::known(self.c1_y),
            )?;
            let c2y = witness(
                layouter.namespace(|| "c2_y"),
                config.advice,
                Value::known(self.c2_y),
            )?;

            let result = hash_share_commitment_in_circuit(
                config.poseidon_chip(),
                layouter.namespace(|| "hash_share_comm"),
                blind,
                c1x,
                c2x,
                c1y,
                c2y,
                0,
            )?;
            layouter.constrain_instance(result.cell(), config.primary, 0)
        }
    }

    /// In-circuit result matches the native `share_commitment` helper.
    #[test]
    fn hash_share_commitment_matches_native() {
        let mut rng = OsRng;
        let blind = pallas::Base::random(&mut rng);
        let c1_x = pallas::Base::random(&mut rng);
        let c2_x = pallas::Base::random(&mut rng);
        let c1_y = pallas::Base::random(&mut rng);
        let c2_y = pallas::Base::random(&mut rng);

        let expected = share_commitment(blind, c1_x, c2_x, c1_y, c2_y);
        let circuit = HashShareCommCircuit {
            blind,
            c1_x,
            c2_x,
            c1_y,
            c2_y,
        };
        let prover =
            MockProver::run(10, &circuit, vec![vec![expected]]).expect("MockProver::run failed");
        assert_eq!(prover.verify(), Ok(()));
    }

    /// Swapping c1 and c2 produces a different hash (input order matters).
    #[test]
    fn hash_share_commitment_input_order_matters() {
        let mut rng = OsRng;
        let blind = pallas::Base::random(&mut rng);
        let c1_x = pallas::Base::random(&mut rng);
        let c2_x = pallas::Base::random(&mut rng);
        let c1_y = pallas::Base::random(&mut rng);
        let c2_y = pallas::Base::random(&mut rng);

        let wrong = share_commitment(blind, c2_x, c1_x, c2_y, c1_y);
        let circuit = HashShareCommCircuit {
            blind,
            c1_x,
            c2_x,
            c1_y,
            c2_y,
        };
        let prover =
            MockProver::run(10, &circuit, vec![vec![wrong]]).expect("MockProver::run failed");
        assert!(prover.verify().is_err());
    }

    /// Negating a y-coordinate (simulating sign-bit flip) changes the hash.
    #[test]
    fn hash_share_commitment_y_negate_changes_hash() {
        let mut rng = OsRng;
        let blind = pallas::Base::random(&mut rng);
        let c1_x = pallas::Base::random(&mut rng);
        let c2_x = pallas::Base::random(&mut rng);
        let c1_y = pallas::Base::random(&mut rng);
        let c2_y = pallas::Base::random(&mut rng);

        let correct = share_commitment(blind, c1_x, c2_x, c1_y, c2_y);
        let negated = share_commitment(blind, c1_x, c2_x, -c1_y, c2_y);
        assert_ne!(
            correct, negated,
            "negating c1_y must change the share commitment"
        );
    }

    // ================================================================
    // compute_shares_hash_in_circuit
    // ================================================================

    /// Minimal circuit: computes `compute_shares_hash_in_circuit` over 16
    /// shares and constrains the result to instance row 0.
    #[derive(Clone)]
    struct ComputeSharesHashCircuit {
        blinds: [pallas::Base; 16],
        enc_c1_x: [pallas::Base; 16],
        enc_c2_x: [pallas::Base; 16],
        enc_c1_y: [pallas::Base; 16],
        enc_c2_y: [pallas::Base; 16],
    }

    impl Default for ComputeSharesHashCircuit {
        fn default() -> Self {
            Self {
                blinds: [pallas::Base::zero(); 16],
                enc_c1_x: [pallas::Base::zero(); 16],
                enc_c2_x: [pallas::Base::zero(); 16],
                enc_c1_y: [pallas::Base::zero(); 16],
                enc_c2_y: [pallas::Base::zero(); 16],
            }
        }
    }

    impl plonk::Circuit<pallas::Base> for ComputeSharesHashCircuit {
        type Config = TestConfig;
        type FloorPlanner = floor_planner::V1;

        fn without_witnesses(&self) -> Self {
            Self::default()
        }

        fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
            TestConfig::configure(meta)
        }

        fn synthesize(
            &self,
            config: Self::Config,
            mut layouter: impl Layouter<pallas::Base>,
        ) -> Result<(), plonk::Error> {
            let mut blind_cells = Vec::with_capacity(16);
            let mut c1x_cells = Vec::with_capacity(16);
            let mut c2x_cells = Vec::with_capacity(16);
            let mut c1y_cells = Vec::with_capacity(16);
            let mut c2y_cells = Vec::with_capacity(16);
            for i in 0..16 {
                blind_cells.push(witness(
                    layouter.namespace(|| format!("blind_{i}")),
                    config.advice,
                    Value::known(self.blinds[i]),
                )?);
                c1x_cells.push(witness(
                    layouter.namespace(|| format!("c1x_{i}")),
                    config.advice,
                    Value::known(self.enc_c1_x[i]),
                )?);
                c2x_cells.push(witness(
                    layouter.namespace(|| format!("c2x_{i}")),
                    config.advice,
                    Value::known(self.enc_c2_x[i]),
                )?);
                c1y_cells.push(witness(
                    layouter.namespace(|| format!("c1y_{i}")),
                    config.advice,
                    Value::known(self.enc_c1_y[i]),
                )?);
                c2y_cells.push(witness(
                    layouter.namespace(|| format!("c2y_{i}")),
                    config.advice,
                    Value::known(self.enc_c2_y[i]),
                )?);
            }
            let blinds: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                blind_cells.try_into().unwrap();
            let enc_c1_x: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                c1x_cells.try_into().unwrap();
            let enc_c2_x: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                c2x_cells.try_into().unwrap();
            let enc_c1_y: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                c1y_cells.try_into().unwrap();
            let enc_c2_y: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                c2y_cells.try_into().unwrap();

            let result = compute_shares_hash_in_circuit(
                || config.poseidon_chip(),
                layouter.namespace(|| "compute_shares_hash"),
                blinds,
                enc_c1_x,
                enc_c2_x,
                enc_c1_y,
                enc_c2_y,
            )?;
            layouter.constrain_instance(result.cell(), config.primary, 0)
        }
    }

    /// In-circuit result matches the native `shares_hash` helper.
    #[test]
    fn compute_shares_hash_matches_native() {
        let mut rng = OsRng;
        let blinds: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));

        let expected = shares_hash(blinds, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y);
        let circuit = ComputeSharesHashCircuit {
            blinds,
            enc_c1_x,
            enc_c2_x,
            enc_c1_y,
            enc_c2_y,
        };
        // K=12 (4096 rows) comfortably fits 17 chained Poseidon(5) regions.
        let prover =
            MockProver::run(12, &circuit, vec![vec![expected]]).expect("MockProver::run failed");
        assert_eq!(prover.verify(), Ok(()));
    }

    /// Corrupting any single enc_c1_x value changes the output.
    #[test]
    fn compute_shares_hash_wrong_enc_c1_fails() {
        let mut rng = OsRng;
        let blinds: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));

        let correct = shares_hash(blinds, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y);

        let mut circuit = ComputeSharesHashCircuit {
            blinds,
            enc_c1_x,
            enc_c2_x,
            enc_c1_y,
            enc_c2_y,
        };
        circuit.enc_c1_x[2] = pallas::Base::random(&mut rng);

        let prover =
            MockProver::run(12, &circuit, vec![vec![correct]]).expect("MockProver::run failed");
        assert!(prover.verify().is_err());
    }

    /// Every one of the 16 share positions contributes to the native output hash.
    ///
    /// `compute_shares_hash_matches_native` covers the in-circuit/native
    /// equivalence once; this test keeps the per-position coverage without
    /// running a separate K=12 prover for every position.
    #[test]
    fn all_16_share_positions_are_hashed() {
        let mut rng = OsRng;
        let blinds: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));

        let correct = shares_hash(blinds, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y);

        for i in 0..16 {
            let mut perturbed_enc_c1_x = enc_c1_x;
            perturbed_enc_c1_x[i] += pallas::Base::one();

            assert_ne!(
                shares_hash(blinds, perturbed_enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y),
                correct,
                "perturbing enc_c1_x[{i}] did not change the shares_hash"
            );
        }
    }

    /// Corrupting a blind factor changes the output.
    #[test]
    fn compute_shares_hash_wrong_blind_fails() {
        let mut rng = OsRng;
        let blinds: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));

        let correct = shares_hash(blinds, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y);

        let mut circuit = ComputeSharesHashCircuit {
            blinds,
            enc_c1_x,
            enc_c2_x,
            enc_c1_y,
            enc_c2_y,
        };
        circuit.blinds[0] = pallas::Base::random(&mut rng);

        let prover =
            MockProver::run(12, &circuit, vec![vec![correct]]).expect("MockProver::run failed");
        assert!(prover.verify().is_err());
    }

    // ================================================================
    // compute_shares_hash_from_comms_in_circuit
    // ================================================================

    /// Minimal circuit: computes `compute_shares_hash_from_comms_in_circuit`
    /// from 16 pre-computed share_comms and constrains to instance row 0.
    #[derive(Clone)]
    struct ComputeSharesHashFromCommsCircuit {
        share_comms: [pallas::Base; 16],
    }

    impl Default for ComputeSharesHashFromCommsCircuit {
        fn default() -> Self {
            Self {
                share_comms: [pallas::Base::zero(); 16],
            }
        }
    }

    impl plonk::Circuit<pallas::Base> for ComputeSharesHashFromCommsCircuit {
        type Config = TestConfig;
        type FloorPlanner = floor_planner::V1;

        fn without_witnesses(&self) -> Self {
            Self::default()
        }

        fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
            TestConfig::configure(meta)
        }

        fn synthesize(
            &self,
            config: Self::Config,
            mut layouter: impl Layouter<pallas::Base>,
        ) -> Result<(), plonk::Error> {
            let mut comm_cells = Vec::with_capacity(16);
            for i in 0..16 {
                comm_cells.push(witness(
                    layouter.namespace(|| format!("comm_{i}")),
                    config.advice,
                    Value::known(self.share_comms[i]),
                )?);
            }
            let comms: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                comm_cells.try_into().unwrap();

            let result = super::compute_shares_hash_from_comms_in_circuit(
                config.poseidon_chip(),
                layouter.namespace(|| "hash_from_comms"),
                comms,
            )?;
            layouter.constrain_instance(result.cell(), config.primary, 0)
        }
    }

    /// Minimal circuit: computes both in-circuit `shares_hash` paths from the
    /// same witness and constrains their outputs equal without a native oracle.
    #[derive(Clone)]
    struct SharesHashInCircuitEquivalenceCircuit {
        blinds: [pallas::Base; 16],
        enc_c1_x: [pallas::Base; 16],
        enc_c2_x: [pallas::Base; 16],
        enc_c1_y: [pallas::Base; 16],
        enc_c2_y: [pallas::Base; 16],
    }

    impl Default for SharesHashInCircuitEquivalenceCircuit {
        fn default() -> Self {
            Self {
                blinds: [pallas::Base::zero(); 16],
                enc_c1_x: [pallas::Base::zero(); 16],
                enc_c2_x: [pallas::Base::zero(); 16],
                enc_c1_y: [pallas::Base::zero(); 16],
                enc_c2_y: [pallas::Base::zero(); 16],
            }
        }
    }

    impl plonk::Circuit<pallas::Base> for SharesHashInCircuitEquivalenceCircuit {
        type Config = TestConfig;
        type FloorPlanner = floor_planner::V1;

        fn without_witnesses(&self) -> Self {
            Self::default()
        }

        fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
            TestConfig::configure(meta)
        }

        fn synthesize(
            &self,
            config: Self::Config,
            mut layouter: impl Layouter<pallas::Base>,
        ) -> Result<(), plonk::Error> {
            let mut blind_cells = Vec::with_capacity(16);
            let mut c1x_cells = Vec::with_capacity(16);
            let mut c2x_cells = Vec::with_capacity(16);
            let mut c1y_cells = Vec::with_capacity(16);
            let mut c2y_cells = Vec::with_capacity(16);
            for i in 0..16 {
                blind_cells.push(witness(
                    layouter.namespace(|| format!("blind_{i}")),
                    config.advice,
                    Value::known(self.blinds[i]),
                )?);
                c1x_cells.push(witness(
                    layouter.namespace(|| format!("c1x_{i}")),
                    config.advice,
                    Value::known(self.enc_c1_x[i]),
                )?);
                c2x_cells.push(witness(
                    layouter.namespace(|| format!("c2x_{i}")),
                    config.advice,
                    Value::known(self.enc_c2_x[i]),
                )?);
                c1y_cells.push(witness(
                    layouter.namespace(|| format!("c1y_{i}")),
                    config.advice,
                    Value::known(self.enc_c1_y[i]),
                )?);
                c2y_cells.push(witness(
                    layouter.namespace(|| format!("c2y_{i}")),
                    config.advice,
                    Value::known(self.enc_c2_y[i]),
                )?);
            }

            let blinds_full: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                core::array::from_fn(|i| blind_cells[i].clone());
            let enc_c1_x_full: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                core::array::from_fn(|i| c1x_cells[i].clone());
            let enc_c2_x_full: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                core::array::from_fn(|i| c2x_cells[i].clone());
            let enc_c1_y_full: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                core::array::from_fn(|i| c1y_cells[i].clone());
            let enc_c2_y_full: [AssignedCell<pallas::Base, pallas::Base>; 16] =
                core::array::from_fn(|i| c2y_cells[i].clone());

            let full_hash = compute_shares_hash_in_circuit(
                || config.poseidon_chip(),
                layouter.namespace(|| "full shares_hash path"),
                blinds_full,
                enc_c1_x_full,
                enc_c2_x_full,
                enc_c1_y_full,
                enc_c2_y_full,
            )?;

            let share_comms: [AssignedCell<pallas::Base, pallas::Base>; 16] = (0..16)
                .map(|i| {
                    hash_share_commitment_in_circuit(
                        config.poseidon_chip(),
                        layouter.namespace(|| format!("from-comms share_comm_{i}")),
                        blind_cells[i].clone(),
                        c1x_cells[i].clone(),
                        c2x_cells[i].clone(),
                        c1y_cells[i].clone(),
                        c2y_cells[i].clone(),
                        i,
                    )
                })
                .collect::<Result<Vec<_>, _>>()?
                .try_into()
                .expect("always 16 elements");

            let from_comms_hash = super::compute_shares_hash_from_comms_in_circuit(
                config.poseidon_chip(),
                layouter.namespace(|| "from-comms shares_hash path"),
                share_comms,
            )?;

            layouter.assign_region(
                || "full shares_hash == from-comms shares_hash",
                |mut region| region.constrain_equal(full_hash.cell(), from_comms_hash.cell()),
            )
        }
    }

    /// The from-comms gadget matches the two-level native computation.
    #[test]
    fn shares_hash_from_comms_matches_native() {
        let mut rng = OsRng;
        let blinds: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_x: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c1_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let enc_c2_y: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));

        let comms: [pallas::Base; 16] = core::array::from_fn(|i| {
            share_commitment(
                blinds[i],
                enc_c1_x[i],
                enc_c2_x[i],
                enc_c1_y[i],
                enc_c2_y[i],
            )
        });
        let expected = super::shares_hash_from_comms(comms);

        assert_eq!(
            expected,
            shares_hash(blinds, enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y)
        );

        let circuit = ComputeSharesHashFromCommsCircuit { share_comms: comms };
        let prover =
            MockProver::run(12, &circuit, vec![vec![expected]]).expect("MockProver::run failed");
        assert_eq!(prover.verify(), Ok(()));
    }

    /// The full two-level in-circuit path and the from-comms in-circuit path
    /// agree on the same witnesses without relying on a native expected value.
    #[test]
    fn compute_shares_hash_in_circuit_matches_from_comms_in_circuit() {
        let mut rng = OsRng;
        let circuit = SharesHashInCircuitEquivalenceCircuit {
            blinds: core::array::from_fn(|_| pallas::Base::random(&mut rng)),
            enc_c1_x: core::array::from_fn(|_| pallas::Base::random(&mut rng)),
            enc_c2_x: core::array::from_fn(|_| pallas::Base::random(&mut rng)),
            enc_c1_y: core::array::from_fn(|_| pallas::Base::random(&mut rng)),
            enc_c2_y: core::array::from_fn(|_| pallas::Base::random(&mut rng)),
        };

        // K=13 fits the two complete 17-Poseidon paths used by this equivalence test.
        let prover = MockProver::run(13, &circuit, vec![vec![]]).expect("MockProver::run failed");
        assert_eq!(prover.verify(), Ok(()));
    }

    /// Corrupting any single share_comm changes the output.
    #[test]
    fn shares_hash_from_comms_wrong_comm_fails() {
        let mut rng = OsRng;
        let comms: [pallas::Base; 16] = core::array::from_fn(|_| pallas::Base::random(&mut rng));
        let expected = super::shares_hash_from_comms(comms);

        let mut bad_comms = comms;
        bad_comms[7] = pallas::Base::random(&mut rng);
        let circuit = ComputeSharesHashFromCommsCircuit {
            share_comms: bad_comms,
        };
        let prover =
            MockProver::run(12, &circuit, vec![vec![expected]]).expect("MockProver::run failed");
        assert!(prover.verify().is_err());
    }
}