voting_circuits/vote_proof/circuit.rs
1//! The Vote Proof circuit implementation (ZKP #2).
2//!
3//! Proves that a registered voter is casting a valid vote, without
4//! revealing which VAN they hold. Currently implements:
5//!
6//! - **Condition 1**: VAN Membership (Poseidon Merkle path, `constrain_instance`).
7//! - **Condition 2**: VAN Integrity (Poseidon hash).
8//! - **Condition 3**: Diversified Address Integrity (`vpk_pk_d = [ivk_v] * vpk_g_d` via CommitIvk).
9//! - **Condition 4**: Spend Authority — `r_vpk = vsk.ak + [alpha_v] * G` (fixed-base mul + point add, `constrain_instance`).
10//! - **Condition 5**: VAN Nullifier Integrity (nested Poseidon, `constrain_instance`).
11//! - **Condition 6**: Proposal Authority Decrement (AddChip + range check).
12//! - **Condition 7**: New VAN Integrity (Poseidon hash, `constrain_instance`).
13//! - **Condition 8**: Shares Sum Correctness (AddChip, `constrain_equal`).
14//! - **Condition 9**: Shares Range (LookupRangeCheck, `[0, 2^30)`).
15//! - **Condition 10**: Shares Hash Integrity (Poseidon `ConstantLength<16>` over 16 blinded share commitments; output flows to condition 12).
16//! - **Condition 11**: Encryption Integrity (ECC variable-base mul, `constrain_equal`).
17//! - **Condition 12**: Vote Commitment Integrity (Poseidon `ConstantLength<5>`, `constrain_instance`).
18//!
19//! Conditions 1–4 and 5–12 are fully constrained in-circuit.
20//!
21//! ## Conditions overview
22//!
23//! VAN ownership and spending:
24//! - **Condition 1**: VAN Membership — Merkle path from `vote_authority_note_old`
25//! to `vote_comm_tree_root`.
26//! - **Condition 2**: VAN Integrity — `vote_authority_note_old` is the two-layer
27//! Poseidon hash (ZKP 1–compatible: core then finalize with rand). *(implemented)*
28//! - **Condition 3**: Diversified Address Integrity — `vpk_pk_d = [ivk_v] * vpk_g_d`
29//! where `ivk_v = CommitIvk(ExtractP([vsk]*SpendAuthG), vsk.nk)`. *(implemented)*
30//! - **Condition 4**: Spend Authority — `r_vpk = vsk.ak + [alpha_v] * G`; enforced in-circuit (fixed-base mul + point add, `constrain_instance`).
31//! - **Condition 5**: VAN Nullifier Integrity — `van_nullifier` is correctly
32//! derived from `vsk.nk`. *(implemented)*
33//!
34//! New VAN construction:
35//! - **Condition 6**: Proposal Authority Decrement — `proposal_authority_new =
36//! proposal_authority_old - (1 << proposal_id)`, with bitmask range [0, 2^16). *(implemented)*
37//! - **Condition 7**: New VAN Integrity — same two-layer structure as condition 2
38//! but with decremented authority. *(implemented)*
39//!
40//! Vote commitment construction:
41//! - **Condition 8**: Shares Sum Correctness — `sum(shares_1..16) = total_note_value`.
42//! *(implemented)*
43//! - **Condition 9**: Shares Range — each `shares_j` in `[0, 2^30)`.
44//! *(implemented)*
45//! - **Condition 10**: Shares Hash Integrity — `shares_hash = H(enc_share_1..16)`.
46//! *(implemented)*
47//! - **Condition 11**: Encryption Integrity — each `enc_share_i = ElGamal(shares_i, r_i, ea_pk)`.
48//! *(implemented)*
49//! - **Condition 12**: Vote Commitment Integrity — `vote_commitment = H(DOMAIN_VC, voting_round_id,
50//! shares_hash, proposal_id, vote_decision)`. *(implemented)*
51
52use alloc::vec::Vec;
53
54
55use halo2_proofs::{
56 circuit::{AssignedCell, Layouter, Value, floor_planner},
57 plonk::{self, Advice, Column, ConstraintSystem, Fixed, Instance as InstanceColumn},
58};
59use pasta_curves::{pallas, vesta};
60
61use halo2_gadgets::{
62 ecc::{
63 chip::{EccChip, EccConfig},
64 NonIdentityPoint, ScalarFixed,
65 },
66 poseidon::{
67 primitives::{self as poseidon, ConstantLength},
68 Hash as PoseidonHash, Pow5Chip as PoseidonChip, Pow5Config as PoseidonConfig,
69 },
70 sinsemilla::chip::{SinsemillaChip, SinsemillaConfig},
71 utilities::lookup_range_check::LookupRangeCheckConfig,
72};
73use crate::circuit::address_ownership::{prove_address_ownership, spend_auth_g_mul};
74use crate::circuit::elgamal::{EaPkInstanceLoc, prove_elgamal_encryptions};
75use crate::circuit::poseidon_merkle::{MerkleSwapGate, synthesize_poseidon_merkle_path};
76use orchard::circuit::commit_ivk::{CommitIvkChip, CommitIvkConfig};
77use orchard::circuit::gadget::{add_chip::{AddChip, AddConfig}, assign_free_advice, AddInstruction};
78use orchard::constants::{
79 OrchardCommitDomains, OrchardFixedBases, OrchardHashDomains,
80};
81use crate::circuit::van_integrity;
82use crate::circuit::vote_commitment;
83use crate::shares_hash::compute_shares_hash_in_circuit;
84#[cfg(test)]
85use crate::shares_hash::hash_share_commitment_in_circuit;
86use super::authority_decrement::{AuthorityDecrementChip, AuthorityDecrementConfig};
87
88// ================================================================
89// Constants
90// ================================================================
91
92/// Depth of the Poseidon-based vote commitment tree.
93///
94/// Reduced from Zcash's depth 32 (~4.3B) because governance voting
95/// produces far fewer leaves than a full shielded pool. Each voter
96/// generates 1 leaf per delegation + 2 per vote, so even 10K voters
97/// × 50 proposals ≈ 1M leaves — well within 2^24 ≈ 16.7M capacity.
98///
99/// Must match `vote_commitment_tree::TREE_DEPTH`.
100pub const VOTE_COMM_TREE_DEPTH: usize = 24;
101
102/// Circuit size (2^K rows).
103///
104/// K=14 (16,384 rows). `CircuitCost::measure` reports a floor-planner
105/// high-water mark of **3,512 rows** (21% of 16,384). The `V1` floor planner
106/// packs non-overlapping regions into the same row range across different
107/// columns, so the high-water mark is much lower than a naive sum-of-heights
108/// estimate.
109///
110/// Key contributors (rough per-region heights, not per-column sums):
111/// - 24-level Merkle path: 24 Poseidon regions stacked sequentially — the
112/// tallest single stack in the circuit.
113/// - ECC fixed- and variable-base multiplications packed alongside the
114/// Poseidon regions in non-overlapping columns.
115/// - 10-bit Sinsemilla/range-check lookup table: 1,024 fixed rows.
116///
117/// The `[v_i]*G` term uses `FixedPointShort` (22-window short-scalar path)
118/// rather than `FixedPointBaseField` (85-window full-scalar path), saving
119/// 315 rows (3,827 → 3,512 measured). Run the `row_budget` benchmark to
120/// re-measure after circuit changes:
121/// `cargo test --features vote-proof row_budget -- --nocapture --ignored`
122pub const K: u32 = 13;
123
124pub use van_integrity::DOMAIN_VAN;
125pub use vote_commitment::DOMAIN_VC;
126
127/// Maximum proposal_id bit index (exclusive upper bound). `proposal_id` is in `[1, MAX_PROPOSAL_ID)`,
128/// i.e. valid values are 1–15. Bit 0 is permanently reserved as the sentinel/unset value and is
129/// rejected by the non-zero gate in `AuthorityDecrementChip` (`q_cond_6`). This means a voting
130/// round supports at most 15 proposals, not 16.
131/// Spec: "The number of proposals for a polling session must be <= 16."
132///
133/// # Indexing Convention
134///
135/// `proposal_id` is **1-indexed** throughout the entire stack:
136///
137/// - **On-chain (`MsgCreateVotingSession`)**: proposals carry `Id = 1, 2, …, N`.
138/// - **On-chain (`ValidateProposalId`)**: rejects `proposal_id < 1`.
139/// - **Circuit (this file)**: `proposal_id` serves as the bit-position in the
140/// 16-bit `proposal_authority` bitmask. The `proposal_id != 0` gate ensures
141/// bit 0 is never selected, so the effective bit range is `[1, 15]`.
142/// - **Client (`zcash_voting::zkp2`)**: validates `proposal_id` in `[1, 15]`
143/// before building the proof.
144///
145/// Bit 0 of `proposal_authority` is always set (initial value `0xFFFF`) and
146/// never decremented, acting as a structural invariant rather than a usable slot.
147pub const MAX_PROPOSAL_ID: usize = 16;
148
149// ================================================================
150// Public input offsets (11 field elements).
151// ================================================================
152
153/// Public input offset for the VAN nullifier (prevents double-vote).
154const VAN_NULLIFIER: usize = 0;
155/// Public input offset for the randomized voting public key (condition 4: Spend Authority).
156/// x-coordinate of r_vpk = vsk.ak + [alpha_v] * G.
157const R_VPK_X: usize = 1;
158/// Public input offset for r_vpk y-coordinate.
159const R_VPK_Y: usize = 2;
160/// Public input offset for the new VAN commitment (with decremented authority).
161const VOTE_AUTHORITY_NOTE_NEW: usize = 3;
162/// Public input offset for the vote commitment hash.
163const VOTE_COMMITMENT: usize = 4;
164/// Public input offset for the vote commitment tree root.
165const VOTE_COMM_TREE_ROOT: usize = 5;
166/// Public input offset for the tree anchor height.
167const VOTE_COMM_TREE_ANCHOR_HEIGHT: usize = 6;
168/// Public input offset for the proposal identifier.
169const PROPOSAL_ID: usize = 7;
170/// Public input offset for the voting round identifier.
171const VOTING_ROUND_ID: usize = 8;
172/// Public input offset for the election authority public key x-coordinate.
173const EA_PK_X: usize = 9;
174/// Public input offset for the election authority public key y-coordinate.
175const EA_PK_Y: usize = 10;
176
177// Suppress dead-code warnings for public input offsets that are
178// defined but not yet used by any condition's constraint logic.
179// VOTE_COMM_TREE_ANCHOR_HEIGHT is validated out-of-circuit by the chain's
180// ante handler: sdk/x/vote/ante/validate.go calls GetCommitmentRootAtHeight
181// with msg.VoteCommTreeAnchorHeight and rejects the transaction if no root
182// exists at that height (ErrInvalidAnchorHeight). The retrieved root is then
183// passed as the VoteCommTreeRoot public input to the ZKP verifier, which the
184// circuit constrains via constrain_instance. This binds the anchor height to
185// the in-circuit tree root, mirroring Zcash's out-of-circuit anchor design.
186const _: usize = VOTE_COMM_TREE_ANCHOR_HEIGHT;
187
188// ================================================================
189// Out-of-circuit helpers
190// ================================================================
191
192pub use van_integrity::van_integrity_hash;
193pub use vote_commitment::vote_commitment_hash;
194
195/// Returns the domain separator for the VAN nullifier inner hash.
196///
197/// Encodes `"vote authority spend"` as a Pallas base field element
198/// by interpreting the UTF-8 bytes as a little-endian 256-bit integer.
199/// This domain tag differentiates VAN nullifier derivation from other
200/// Poseidon uses in the protocol.
201pub fn domain_van_nullifier() -> pallas::Base {
202 // "vote authority spend" (20 bytes) zero-padded to 32, as LE u64 words.
203 pallas::Base::from_raw([
204 0x7475_6120_6574_6f76, // b"vote aut" LE
205 0x7320_7974_6972_6f68, // b"hority s" LE
206 0x0000_0000_646e_6570, // b"pend\0\0\0\0" LE
207 0,
208 ])
209}
210
211/// Out-of-circuit VAN nullifier hash (condition 5).
212///
213/// ```text
214/// van_nullifier = Poseidon(vsk_nk, domain_tag, voting_round_id, vote_authority_note_old)
215/// ```
216///
217/// Single `ConstantLength<4>` call (2 permutations at rate=2).
218/// Used by the builder and tests to compute the expected VAN nullifier.
219pub fn van_nullifier_hash(
220 vsk_nk: pallas::Base,
221 voting_round_id: pallas::Base,
222 vote_authority_note_old: pallas::Base,
223) -> pallas::Base {
224 poseidon::Hash::<_, poseidon::P128Pow5T3, ConstantLength<4>, 3, 2>::init().hash([
225 vsk_nk,
226 domain_van_nullifier(),
227 voting_round_id,
228 vote_authority_note_old,
229 ])
230}
231
232/// Out-of-circuit Poseidon hash of two field elements.
233///
234/// `Poseidon(a, b)` with P128Pow5T3, ConstantLength<2>, width 3, rate 2.
235/// Used for Merkle path computation (condition 1) and tests. This is the
236/// same hash function used by `vote_commitment_tree::MerkleHashVote::combine`.
237pub fn poseidon_hash_2(a: pallas::Base, b: pallas::Base) -> pallas::Base {
238 poseidon::Hash::<_, poseidon::P128Pow5T3, ConstantLength<2>, 3, 2>::init().hash([a, b])
239}
240
241/// Out-of-circuit per-share blinded commitment (condition 10).
242///
243/// Computes `Poseidon(blind, c1_x, c2_x, c1_y, c2_y)` for a single share.
244///
245/// The y-coordinates bind the commitment to the exact curve point, not just
246/// the x-coordinate. Without them, an attacker can negate the ElGamal
247/// ciphertext (flip sign bits) without invalidating the ZKP — corrupting
248/// the homomorphic tally. See: ciphertext sign-malleability fix.
249///
250/// The blind factor prevents anyone who sees the encrypted shares on-chain
251/// from recomputing shares_hash and linking it to a specific vote commitment.
252pub fn share_commitment(
253 blind: pallas::Base,
254 c1_x: pallas::Base,
255 c2_x: pallas::Base,
256 c1_y: pallas::Base,
257 c2_y: pallas::Base,
258) -> pallas::Base {
259 poseidon::Hash::<_, poseidon::P128Pow5T3, ConstantLength<5>, 3, 2>::init()
260 .hash([blind, c1_x, c2_x, c1_y, c2_y])
261}
262
263/// Out-of-circuit shares hash (condition 10).
264///
265/// Computes blinded per-share commitments and hashes them together:
266/// ```text
267/// share_comm_i = Poseidon(blind_i, c1_i_x, c2_i_x, c1_i_y, c2_i_y) for i in 0..16
268/// shares_hash = Poseidon(share_comm_0, ..., share_comm_15)
269/// ```
270///
271/// The blind factors prevent anyone who sees the encrypted shares on-chain
272/// from recomputing shares_hash and linking it to a specific vote commitment.
273///
274/// Used by the builder and tests to compute the expected shares hash.
275pub fn shares_hash(
276 share_blinds: [pallas::Base; 16],
277 enc_share_c1_x: [pallas::Base; 16],
278 enc_share_c2_x: [pallas::Base; 16],
279 enc_share_c1_y: [pallas::Base; 16],
280 enc_share_c2_y: [pallas::Base; 16],
281) -> pallas::Base {
282 let comms: [pallas::Base; 16] = core::array::from_fn(|i| {
283 share_commitment(
284 share_blinds[i],
285 enc_share_c1_x[i],
286 enc_share_c2_x[i],
287 enc_share_c1_y[i],
288 enc_share_c2_y[i],
289 )
290 });
291 poseidon::Hash::<_, poseidon::P128Pow5T3, ConstantLength<16>, 3, 2>::init().hash(comms)
292}
293
294// ================================================================
295// Config
296// ================================================================
297
298/// Configuration for the Vote Proof circuit.
299///
300/// Holds chip configs for Poseidon (conditions 1, 2, 5, 7, 10), AddChip
301/// (conditions 6, 8), LookupRangeCheck (conditions 6, 9), ECC
302/// (conditions 3, 11), and the Merkle swap gate (condition 1).
303#[derive(Clone, Debug)]
304pub struct Config {
305 /// Public input column (9 field elements).
306 primary: Column<InstanceColumn>,
307 /// 10 advice columns for private witness data.
308 ///
309 /// Column layout follows the delegation circuit for consistency:
310 /// - `advices[0..5]`: general witness assignment + Merkle swap gate.
311 /// - `advices[5]`: Poseidon partial S-box column.
312 /// - `advices[6..9]`: Poseidon state columns + AddChip output.
313 /// - `advices[9]`: range check running sum.
314 advices: [Column<Advice>; 10],
315 /// Poseidon hash chip configuration.
316 ///
317 /// P128Pow5T3 with width 3, rate 2. Used for VAN integrity (condition 2),
318 /// VAN nullifier (condition 5), new VAN integrity (condition 7),
319 /// vote commitment Merkle path (condition 1), and vote commitment
320 /// integrity (conditions 10, 12).
321 poseidon_config: PoseidonConfig<pallas::Base, 3, 2>,
322 /// AddChip: constrains `a + b = c` on a single row.
323 ///
324 /// Uses advices[7] (a), advices[8] (b), advices[6] (c), matching
325 /// the delegation circuit's column assignment.
326 /// Used in conditions 6 (proposal authority decrement) and 8 (shares
327 /// sum correctness).
328 add_config: AddConfig,
329 /// ECC chip configuration (condition 3: diversified address integrity, condition 11: El Gamal).
330 ///
331 /// Condition 3 proves `vpk_pk_d = [ivk_v] * vpk_g_d` via the CommitIvk chain:
332 /// `[vsk] * SpendAuthG → ak → CommitIvk(ExtractP(ak), nk, rivk_v) → ivk_v → [ivk_v] * vpk_g_d`.
333 /// Shares advice and fixed columns with Poseidon per delegation layout.
334 ecc_config: EccConfig<OrchardFixedBases>,
335 /// Sinsemilla chip configuration (condition 3: CommitIvk requires Sinsemilla).
336 ///
337 /// Uses advices[0..5] for Sinsemilla message hashing, advices[6] for
338 /// witnessing message pieces, and lagrange_coeffs[0] for the fixed y_Q column.
339 /// Also loads the 10-bit lookup table used by LookupRangeCheckConfig.
340 sinsemilla_config:
341 SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
342 /// CommitIvk chip configuration (condition 3: canonicity checks on ak || nk).
343 ///
344 /// Provides the custom gate and decomposition logic for the
345 /// Sinsemilla-based `CommitIvk` commitment.
346 commit_ivk_config: CommitIvkConfig,
347 /// 10-bit lookup range check configuration.
348 ///
349 /// Uses advices[9] as the running-sum column. Each word is 10 bits,
350 /// so `num_words` × 10 gives the total bit-width checked.
351 /// Used in condition 6 to ensure authority values and diff are in [0, 2^16)
352 /// (16-bit bitmask), and condition 9 to ensure each share is in `[0, 2^30)`.
353 range_check: LookupRangeCheckConfig<pallas::Base, 10>,
354 /// Merkle conditional swap gate (condition 1).
355 ///
356 /// At each of the 24 Merkle tree levels, conditionally swaps
357 /// (current, sibling) into (left, right) based on the position bit.
358 /// Uses advices[0..5]: pos_bit, current, sibling, left, right.
359 merkle_swap: MerkleSwapGate,
360 /// Configuration for condition 6 (Proposal Authority Decrement).
361 authority_decrement: AuthorityDecrementConfig,
362}
363
364impl Config {
365 /// Constructs a Poseidon chip from this configuration.
366 ///
367 /// Width 3 (P128Pow5T3 state size), rate 2 (absorbs 2 field elements
368 /// per permutation — halves the number of rounds vs rate 1).
369 pub(crate) fn poseidon_chip(&self) -> PoseidonChip<pallas::Base, 3, 2> {
370 PoseidonChip::construct(self.poseidon_config.clone())
371 }
372
373 /// Constructs an AddChip for field element addition (`c = a + b`).
374 fn add_chip(&self) -> AddChip {
375 AddChip::construct(self.add_config.clone())
376 }
377
378 /// Constructs an ECC chip for curve operations (conditions 3, 11).
379 fn ecc_chip(&self) -> EccChip<OrchardFixedBases> {
380 EccChip::construct(self.ecc_config.clone())
381 }
382
383 /// Constructs a Sinsemilla chip (condition 3: CommitIvk).
384 fn sinsemilla_chip(
385 &self,
386 ) -> SinsemillaChip<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases> {
387 SinsemillaChip::construct(self.sinsemilla_config.clone())
388 }
389
390 /// Constructs a CommitIvk chip for canonicity checks (condition 3).
391 fn commit_ivk_chip(&self) -> CommitIvkChip {
392 CommitIvkChip::construct(self.commit_ivk_config.clone())
393 }
394
395 /// Returns the range check configuration (10-bit words).
396 fn range_check_config(&self) -> LookupRangeCheckConfig<pallas::Base, 10> {
397 self.range_check
398 }
399}
400
401// ================================================================
402// Circuit
403// ================================================================
404
405/// The Vote Proof circuit (ZKP #2).
406///
407/// Proves that a registered voter is casting a valid vote, without
408/// revealing which VAN they hold. Contains witness fields for all
409/// 12 conditions (condition 4 enforced out-of-circuit); constraint logic is added incrementally.
410///
411/// Conditions 1–3 and 5–12 are fully constrained in-circuit; condition 4 (Spend Authority) is
412/// enforced out-of-circuit via signature verification.
413#[derive(Clone, Debug, Default)]
414pub struct Circuit {
415 // === VAN ownership and spending (conditions 1–5; condition 4 out-of-circuit) ===
416
417 // Condition 1 (VAN Membership): Poseidon-based Merkle path from
418 // vote_authority_note_old to vote_comm_tree_root.
419 /// Merkle authentication path (sibling hashes at each tree level).
420 pub(crate) vote_comm_tree_path: Value<[pallas::Base; VOTE_COMM_TREE_DEPTH]>,
421 /// Leaf position in the vote commitment tree.
422 pub(crate) vote_comm_tree_position: Value<u32>,
423
424 // Condition 2 (VAN Integrity): two-layer hash matching ZKP 1 (delegation):
425 // van_comm_core = Poseidon(DOMAIN_VAN, vpk_g_d.x, vpk_pk_d.x, total_note_value,
426 // voting_round_id, proposal_authority_old);
427 // vote_authority_note_old = Poseidon(van_comm_core, van_comm_rand).
428 //
429 // Condition 3 (Diversified Address Integrity): vpk_pk_d = [ivk_v] * vpk_g_d
430 // where ivk_v = CommitIvk(ExtractP([vsk]*SpendAuthG), vsk.nk, rivk_v).
431 // Full affine points are needed for condition 3's ECC operations;
432 // x-coordinates are extracted in-circuit for Poseidon hashing (conditions 2, 7).
433 /// Voting public key — diversified base point (from DiversifyHash(d)).
434 /// This is the vpk_g_d component of the voting hotkey address.
435 /// Condition 3 performs `[ivk_v] * vpk_g_d` to derive vpk_pk_d.
436 pub(crate) vpk_g_d: Value<pallas::Affine>,
437 /// Voting public key — diversified transmission key (pk_d = [ivk_v] * g_d).
438 /// This is the vpk_pk_d component of the voting hotkey address.
439 /// Condition 3 (Diversified Address Integrity) constrains this to equal `[ivk_v] * vpk_g_d`.
440 pub(crate) vpk_pk_d: Value<pallas::Affine>,
441 /// The voter's total delegated weight, denominated in ballots
442 /// (1 ballot = 0.125 ZEC; converted from zatoshi by ZKP #1 condition 8).
443 pub(crate) total_note_value: Value<pallas::Base>,
444 // Condition 6:
445 /// Remaining proposal authority bitmask in the old VAN.
446 pub(crate) proposal_authority_old: Value<pallas::Base>,
447 /// Blinding randomness for the VAN commitment.
448 pub(crate) van_comm_rand: Value<pallas::Base>,
449 /// The old VAN commitment (Poseidon hash output). Used as the Merkle
450 /// leaf in condition 1 and constrained to equal the derived hash here.
451 pub(crate) vote_authority_note_old: Value<pallas::Base>,
452
453 // Condition 3 (Diversified Address Integrity): prover controls the VAN address.
454 // vpk_pk_d = [ivk_v] * vpk_g_d
455 // where ivk_v = CommitIvk_rivk_v(ExtractP([vsk]*SpendAuthG), vsk.nk)
456 /// Voting spending key (scalar for ECC multiplication).
457 /// Used in condition 3 for `[vsk] * SpendAuthG`.
458 pub(crate) vsk: Value<pallas::Scalar>,
459 /// CommitIvk randomness for the ivk_v derivation (condition 3).
460 /// Used as the blinding scalar in `CommitIvk(ak, nk, rivk_v)`.
461 pub(crate) rivk_v: Value<pallas::Scalar>,
462 /// Spend auth randomizer for condition 4: r_vpk = vsk.ak + [alpha_v] * G.
463 pub(crate) alpha_v: Value<pallas::Scalar>,
464
465 // Condition 5 (VAN Nullifier Integrity): nullifier deriving key.
466 // Also used in condition 3 as the nk input to CommitIvk.
467 /// Nullifier deriving key derived from vsk.
468 pub(crate) vsk_nk: Value<pallas::Base>,
469
470 // Condition 6 (Proposal Authority Decrement): one_shifted = 2^proposal_id.
471 /// `2^proposal_id`, supplied as a private witness and constrained by a lookup.
472 ///
473 /// Field arithmetic cannot express variable-exponent exponentiation as a
474 /// polynomial gate, so the prover witnesses `one_shifted` directly. The lookup
475 /// table `(0,1), (1,2), ..., (15,32768)` then proves `one_shifted == 2^proposal_id`.
476 /// The bit-decomposition region uses this value to compute
477 /// `proposal_authority_new = proposal_authority_old - one_shifted`.
478 pub(crate) one_shifted: Value<pallas::Base>,
479
480 // === Vote commitment construction (conditions 8–12) ===
481
482 // Condition 8 (Shares Sum): sum(shares_1..16) = total_note_value.
483 // Condition 9 (Shares Range): each share in [0, 2^30).
484 /// Voting share vector (16 random shares that sum to total_note_value).
485 /// The decomposition is chosen by the prover for amount privacy: the
486 /// on-chain El Gamal ciphertexts reveal no weight fingerprint.
487 pub(crate) shares: [Value<pallas::Base>; 16],
488
489 // Condition 10 (Shares Hash Integrity): El Gamal ciphertext coordinates.
490 // These are the coordinates of the curve points comprising each
491 // El Gamal ciphertext. Condition 11 constrains these to be correct
492 // encryptions; condition 10 hashes them (including y-coordinates to
493 // prevent ciphertext sign-malleability).
494 /// X-coordinates of C1_i = r_i * G for each share (via ExtractP).
495 pub(crate) enc_share_c1_x: [Value<pallas::Base>; 16],
496 /// X-coordinates of C2_i = shares_i * G + r_i * ea_pk for each share (via ExtractP).
497 pub(crate) enc_share_c2_x: [Value<pallas::Base>; 16],
498 /// Y-coordinates of C1_i (bound to the exact curve point, preventing sign-malleability).
499 pub(crate) enc_share_c1_y: [Value<pallas::Base>; 16],
500 /// Y-coordinates of C2_i (bound to the exact curve point, preventing sign-malleability).
501 pub(crate) enc_share_c2_y: [Value<pallas::Base>; 16],
502
503 // Condition 10 (Shares Hash Integrity): per-share blind factors for blinded commitments.
504 /// Random blind factors: share_comm_i = Poseidon(blind_i, c1_i_x, c2_i_x, c1_i_y, c2_i_y).
505 pub(crate) share_blinds: [Value<pallas::Base>; 16],
506
507 // Condition 11 (Encryption Integrity): El Gamal randomness and public key.
508 /// El Gamal encryption randomness for each share (base field element,
509 /// converted to scalar via ScalarVar::from_base in-circuit).
510 pub(crate) share_randomness: [Value<pallas::Base>; 16],
511 /// Election authority public key (Pallas curve point).
512 /// The El Gamal encryption key — published as a round parameter.
513 /// Both coordinates are public inputs (EA_PK_X, EA_PK_Y).
514 pub(crate) ea_pk: Value<pallas::Affine>,
515
516 // Condition 12 (Vote Commitment Integrity): vote decision.
517 /// The voter's choice (hidden inside the vote commitment).
518 pub(crate) vote_decision: Value<pallas::Base>,
519}
520
521impl Circuit {
522 /// Creates a circuit with conditions 1–3 and 5–7 witnesses populated.
523 ///
524 /// All other witness fields are set to `Value::unknown()`.
525 /// - Condition 1 uses `vote_authority_note_old` as the Merkle leaf,
526 /// with `vote_comm_tree_path` and `vote_comm_tree_position` for
527 /// the authentication path.
528 /// - Condition 2 binds `vote_authority_note_old` to the Poseidon hash
529 /// of its components (using x-coordinates extracted from vpk_g_d, vpk_pk_d).
530 /// - Condition 3 proves diversified address integrity via CommitIvk chain:
531 /// `[vsk] * SpendAuthG → ak → CommitIvk(ak, nk, rivk_v) → ivk_v → [ivk_v] * vpk_g_d = vpk_pk_d`.
532 /// - Condition 5 reuses `vote_authority_note_old` and `voting_round_id`.
533 /// - Condition 6 derives `proposal_authority_new` from
534 /// `proposal_authority_old`.
535 /// - Condition 7 reuses all condition 2 witnesses except
536 /// `proposal_authority_old`, which is replaced by the
537 /// in-circuit `proposal_authority_new` from condition 6.
538 pub fn with_van_witnesses(
539 vote_comm_tree_path: Value<[pallas::Base; VOTE_COMM_TREE_DEPTH]>,
540 vote_comm_tree_position: Value<u32>,
541 vpk_g_d: Value<pallas::Affine>,
542 vpk_pk_d: Value<pallas::Affine>,
543 total_note_value: Value<pallas::Base>,
544 proposal_authority_old: Value<pallas::Base>,
545 van_comm_rand: Value<pallas::Base>,
546 vote_authority_note_old: Value<pallas::Base>,
547 vsk: Value<pallas::Scalar>,
548 rivk_v: Value<pallas::Scalar>,
549 vsk_nk: Value<pallas::Base>,
550 alpha_v: Value<pallas::Scalar>,
551 ) -> Self {
552 Circuit {
553 vote_comm_tree_path,
554 vote_comm_tree_position,
555 vpk_g_d,
556 vpk_pk_d,
557 total_note_value,
558 proposal_authority_old,
559 van_comm_rand,
560 vote_authority_note_old,
561 vsk,
562 rivk_v,
563 alpha_v,
564 vsk_nk,
565 ..Default::default()
566 }
567 }
568}
569
570/// In-circuit Poseidon hash for one share commitment: `Poseidon(blind, c1_x, c2_x, c1_y, c2_y)`.
571///
572/// Uses the same parameters as the out-of-circuit [`share_commitment`] (P128Pow5T3,
573/// ConstantLength<5>, width 3, rate 2) so that native and in-circuit hashes match.
574
575impl plonk::Circuit<pallas::Base> for Circuit {
576 type Config = Config;
577 type FloorPlanner = floor_planner::V1;
578
579 fn without_witnesses(&self) -> Self {
580 Self::default()
581 }
582
583 fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
584 // 10 advice columns, matching the delegation circuit layout so the two
585 // circuits share the same column assignment and chip configurations.
586 // The count is driven by the ECC chip, which is the largest consumer
587 // and requires all 10 columns for its internal scalar-multiplication
588 // gates. The remaining chips tile within that same 10-column window:
589 //
590 // advices[0..5] — general witness assignment, Sinsemilla pair 1
591 // message columns, and the Merkle swap gate
592 // (pos_bit / current / sibling / left / right).
593 // advices[5] — Poseidon partial S-box column; also the start of
594 // Sinsemilla pair 2 main columns (advices[5..10]).
595 // advices[6..9] — Poseidon width-3 state columns; AddChip uses these
596 // same three columns (a=advices[7], b=advices[8],
597 // c=advices[6]).
598 // advices[9] — LookupRangeCheck running-sum column.
599 let advices: [Column<Advice>; 10] = core::array::from_fn(|_| meta.advice_column());
600 for col in &advices {
601 meta.enable_equality(*col);
602 }
603
604 // Instance column for public inputs.
605 let primary = meta.instance_column();
606 meta.enable_equality(primary);
607
608 // 8 fixed columns shared between ECC and Poseidon chips.
609 // Indices 0–1: Lagrange coefficients (ECC chip only).
610 // Indices 2–4: Poseidon round constants A (rc_a).
611 // Indices 5–7: Poseidon round constants B (rc_b).
612 let lagrange_coeffs: [Column<Fixed>; 8] =
613 core::array::from_fn(|_| meta.fixed_column());
614 let rc_a = lagrange_coeffs[2..5].try_into().unwrap();
615 let rc_b = lagrange_coeffs[5..8].try_into().unwrap();
616
617 // Dedicated constants column, separate from the Lagrange coefficient
618 // columns used by the ECC chip. This prevents collisions between
619 // the ECC chip's fixed-base scalar multiplication tables and the
620 // constant-zero cells created by strict range checks.
621 let constants = meta.fixed_column();
622 meta.enable_constant(constants);
623
624 // AddChip: constrains `a + b = c` in a single row.
625 // Column assignment matches the delegation circuit:
626 // a = advices[7], b = advices[8], c = advices[6].
627 let add_config = AddChip::configure(meta, advices[7], advices[8], advices[6]);
628
629 // Lookup table columns for Sinsemilla (3 columns) and range checks.
630 // The first column (table_idx) is shared between Sinsemilla and
631 // LookupRangeCheckConfig. SinsemillaChip::load populates all three
632 // during synthesis (replacing the manual table loading).
633 let table_idx = meta.lookup_table_column();
634 let lookup = (
635 table_idx,
636 meta.lookup_table_column(),
637 meta.lookup_table_column(),
638 );
639
640 // Range check configuration: 10-bit lookup words in advices[9].
641 let range_check = LookupRangeCheckConfig::configure(meta, advices[9], table_idx);
642
643 // ECC chip: fixed- and variable-base scalar multiplication for
644 // condition 3 (diversified address integrity via CommitIvk chain) and condition 11
645 // (El Gamal encryption integrity).
646 // Shares columns with Poseidon per delegation circuit layout.
647 let ecc_config =
648 EccChip::<OrchardFixedBases>::configure(meta, advices, lagrange_coeffs, range_check);
649
650 // Sinsemilla chip: required by CommitIvk for condition 3.
651 // Uses advices[0..5] for Sinsemilla message hashing, advices[6] for
652 // witnessing message pieces, and lagrange_coeffs[0] for the fixed
653 // y_Q column. Shares the lookup table with LookupRangeCheckConfig.
654 let sinsemilla_config = SinsemillaChip::configure(
655 meta,
656 advices[..5].try_into().unwrap(),
657 advices[6],
658 lagrange_coeffs[0],
659 lookup,
660 range_check,
661 );
662
663 // CommitIvk chip: canonicity checks on the ak || nk decomposition
664 // inside the CommitIvk Sinsemilla commitment (condition 3).
665 let commit_ivk_config = CommitIvkChip::configure(meta, advices);
666
667 // Poseidon chip: P128Pow5T3 with width 3, rate 2.
668 // State columns: advices[6..9] (3 columns for the width-3 state).
669 // Partial S-box column: advices[5].
670 // Round constants: lagrange_coeffs[2..5] (rc_a), [5..8] (rc_b).
671 let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
672 meta,
673 advices[6..9].try_into().unwrap(),
674 advices[5],
675 rc_a,
676 rc_b,
677 );
678
679 // Merkle conditional swap gate (condition 1).
680 let merkle_swap = MerkleSwapGate::configure(
681 meta,
682 [advices[0], advices[1], advices[2], advices[3], advices[4]],
683 );
684
685 // Condition 6: Proposal Authority Decrement.
686 let authority_decrement = AuthorityDecrementChip::configure(meta, advices);
687
688 Config {
689 primary,
690 advices,
691 poseidon_config,
692 add_config,
693 ecc_config,
694 sinsemilla_config,
695 commit_ivk_config,
696 range_check,
697 merkle_swap,
698 authority_decrement,
699 }
700 }
701
702 #[allow(non_snake_case)]
703 fn synthesize(
704 &self,
705 config: Self::Config,
706 mut layouter: impl Layouter<pallas::Base>,
707 ) -> Result<(), plonk::Error> {
708 // ---------------------------------------------------------------
709 // Load the Sinsemilla generator lookup table.
710 //
711 // Populates the 10-bit lookup table and Sinsemilla generator
712 // points. Required by CommitIvk (condition 3), and also provides
713 // the range check table used by conditions 5 and 8.
714 // ---------------------------------------------------------------
715 SinsemillaChip::load(config.sinsemilla_config.clone(), &mut layouter)?;
716
717 // Load (proposal_id, 2^proposal_id) lookup table for condition 6.
718 AuthorityDecrementChip::load_table(&config.authority_decrement, &mut layouter)?;
719
720
721 // Construct the ECC chip (used in conditions 3 and 10).
722 let ecc_chip = config.ecc_chip();
723
724 // ---------------------------------------------------------------
725 // Witness assignment for condition 2.
726 // ---------------------------------------------------------------
727
728 // Copy voting_round_id from the instance column into an advice cell.
729 // This creates an equality constraint between the advice cell and the
730 // instance at offset VOTING_ROUND_ID, ensuring the in-circuit value
731 // matches the public input.
732 let voting_round_id = layouter.assign_region(
733 || "copy voting_round_id from instance",
734 |mut region| {
735 region.assign_advice_from_instance(
736 || "voting_round_id",
737 config.primary,
738 VOTING_ROUND_ID,
739 config.advices[0],
740 0,
741 )
742 },
743 )?;
744 // Clone for condition 12 (vote commitment integrity) before
745 // condition 2 consumes the original via van_integrity_poseidon.
746 let voting_round_id_cond12 = voting_round_id.clone();
747
748 // Witness vpk_g_d as a full non-identity curve point (condition 3 needs
749 // the point for variable-base ECC mul; conditions 2/6 need the x-coordinate
750 // for Poseidon hashing).
751 let vpk_g_d_point = NonIdentityPoint::new(
752 ecc_chip.clone(),
753 layouter.namespace(|| "witness vpk_g_d"),
754 self.vpk_g_d.map(|p| p),
755 )?;
756 let vpk_g_d = vpk_g_d_point.extract_p().inner().clone();
757
758 // Witness vpk_pk_d as a full non-identity curve point (condition 3
759 // constrains the derived point to equal this; conditions 2/6 use x-coordinate).
760 let vpk_pk_d_point = NonIdentityPoint::new(
761 ecc_chip.clone(),
762 layouter.namespace(|| "witness vpk_pk_d"),
763 self.vpk_pk_d.map(|p| p),
764 )?;
765 let vpk_pk_d = vpk_pk_d_point.extract_p().inner().clone();
766
767 let total_note_value = assign_free_advice(
768 layouter.namespace(|| "witness total_note_value"),
769 config.advices[0],
770 self.total_note_value,
771 )?;
772
773 let proposal_authority_old = assign_free_advice(
774 layouter.namespace(|| "witness proposal_authority_old"),
775 config.advices[0],
776 self.proposal_authority_old,
777 )?;
778
779 let van_comm_rand = assign_free_advice(
780 layouter.namespace(|| "witness van_comm_rand"),
781 config.advices[0],
782 self.van_comm_rand,
783 )?;
784
785 let vote_authority_note_old = assign_free_advice(
786 layouter.namespace(|| "witness vote_authority_note_old"),
787 config.advices[0],
788 self.vote_authority_note_old,
789 )?;
790
791 // DOMAIN_VAN — constant-constrained so the value is baked into the
792 // verification key and cannot be altered by a malicious prover.
793 let domain_van = layouter.assign_region(
794 || "DOMAIN_VAN constant",
795 |mut region| {
796 region.assign_advice_from_constant(
797 || "domain_van",
798 config.advices[0],
799 0,
800 pallas::Base::from(DOMAIN_VAN),
801 )
802 },
803 )?;
804
805 // ---------------------------------------------------------------
806 // Witness assignment for conditions 3 and 4.
807 //
808 // vsk_nk is shared between condition 3 (CommitIvk input) and
809 // condition 5 (VAN nullifier). Witnessed here so it's available
810 // for condition 3 which runs before condition 5.
811 // ---------------------------------------------------------------
812
813 // Private witness: nullifier deriving key (shared by conditions 3, 4).
814 let vsk_nk = assign_free_advice(
815 layouter.namespace(|| "witness vsk_nk"),
816 config.advices[0],
817 self.vsk_nk,
818 )?;
819
820 // Clone cells that are consumed by condition 2's Poseidon hash but
821 // reused in later conditions:
822 // - vote_authority_note_old: also used in condition 1 (Merkle leaf).
823 // - voting_round_id: also used in condition 5 (VAN nullifier).
824 // - vpk_g_d, vpk_pk_d, total_note_value, voting_round_id,
825 // van_comm_rand, domain_van: also used in condition 7 (new VAN integrity).
826 // - total_note_value: also used in condition 8 (shares sum check).
827 // - vsk_nk: also used in condition 5 (VAN nullifier).
828 let vote_authority_note_old_cond1 = vote_authority_note_old.clone();
829 let voting_round_id_cond4 = voting_round_id.clone();
830 let domain_van_cond6 = domain_van.clone();
831 let vpk_g_d_cond6 = vpk_g_d.clone();
832 let vpk_pk_d_cond6 = vpk_pk_d.clone();
833 let total_note_value_cond6 = total_note_value.clone();
834 let total_note_value_cond8 = total_note_value.clone();
835 let voting_round_id_cond6 = voting_round_id.clone();
836 let van_comm_rand_cond6 = van_comm_rand.clone();
837 let vsk_nk_cond4 = vsk_nk.clone();
838
839 // ---------------------------------------------------------------
840 // Condition 2: VAN Integrity (ZKP 1–compatible two-layer hash).
841 // van_comm_core = Poseidon(DOMAIN_VAN, vpk_g_d, vpk_pk_d, total_note_value,
842 // voting_round_id, proposal_authority_old)
843 // vote_authority_note_old = Poseidon(van_comm_core, van_comm_rand)
844 // ---------------------------------------------------------------
845
846 let derived_van = van_integrity::van_integrity_poseidon(
847 &config.poseidon_config,
848 &mut layouter,
849 "Old VAN integrity",
850 domain_van,
851 vpk_g_d,
852 vpk_pk_d,
853 total_note_value,
854 voting_round_id,
855 proposal_authority_old.clone(),
856 van_comm_rand,
857 )?;
858
859 // Constrain: derived VAN hash == witnessed vote_authority_note_old.
860 layouter.assign_region(
861 || "VAN integrity check",
862 |mut region| region.constrain_equal(derived_van.cell(), vote_authority_note_old.cell()),
863 )?;
864
865 // ---------------------------------------------------------------
866 // Condition 3: Diversified Address Integrity.
867 //
868 // vpk_pk_d = [ivk_v] * vpk_g_d where ivk_v = CommitIvk(ExtractP([vsk]*SpendAuthG), vsk_nk, rivk_v).
869 // ---------------------------------------------------------------
870 let vsk_scalar = ScalarFixed::new(
871 ecc_chip.clone(),
872 layouter.namespace(|| "cond3 vsk"),
873 self.vsk,
874 )?;
875 let vsk_ak_point = spend_auth_g_mul(
876 ecc_chip.clone(),
877 layouter.namespace(|| "cond3 [vsk]G"),
878 "cond3: [vsk] SpendAuthG",
879 vsk_scalar,
880 )?;
881 let ak = vsk_ak_point.extract_p().inner().clone();
882 let rivk_v_scalar = ScalarFixed::new(
883 ecc_chip.clone(),
884 layouter.namespace(|| "cond3 rivk_v"),
885 self.rivk_v,
886 )?;
887 prove_address_ownership(
888 config.sinsemilla_chip(),
889 ecc_chip.clone(),
890 config.commit_ivk_chip(),
891 layouter.namespace(|| "cond3 address"),
892 "cond3",
893 ak,
894 vsk_nk.clone(),
895 rivk_v_scalar,
896 &vpk_g_d_point,
897 &vpk_pk_d_point,
898 )?;
899
900 // ---------------------------------------------------------------
901 // Condition 4: Spend authority.
902 // r_vpk = [alpha_v] * SpendAuthG + vsk_ak_point
903 // ---------------------------------------------------------------
904 // Spend authority: proves that the public r_vpk is a valid rerandomization of the prover's ak.
905 // The out-of-circuit verifier checks that the vote signature is valid under r_vpk,
906 // so this links the ZKP to the signature without revealing ak.
907 //
908 // Uses the shared gadget from crate::circuit::spend_authority – a 1:1 copy of
909 // the upstream Orchard spend authority check:
910 // https://github.com/zcash/orchard/blob/main/src/circuit.rs#L542-L558
911 crate::circuit::spend_authority::prove_spend_authority(
912 ecc_chip.clone(),
913 layouter.namespace(|| "cond4 spend authority"),
914 self.alpha_v,
915 &vsk_ak_point,
916 config.primary,
917 R_VPK_X,
918 R_VPK_Y,
919 )?;
920
921 // ---------------------------------------------------------------
922 // Condition 1: VAN Membership.
923 //
924 // MerklePath(vote_authority_note_old, position, path) = vote_comm_tree_root
925 //
926 // Poseidon-based Merkle path verification (24 levels). At each
927 // level, the position bit determines child ordering: if bit=0,
928 // current is the left child; if bit=1, current is the right child.
929 //
930 // The leaf is vote_authority_note_old, which is already constrained
931 // to be a correct Poseidon hash by condition 2. This creates a
932 // binding: the VAN integrity check and the Merkle membership proof
933 // are tied to the same commitment.
934 //
935 // The hash function is Poseidon(left, right) with no level tag,
936 // matching vote_commitment_tree::MerkleHashVote::combine.
937 // ---------------------------------------------------------------
938 {
939 let root = synthesize_poseidon_merkle_path::<VOTE_COMM_TREE_DEPTH>(
940 &config.merkle_swap,
941 &config.poseidon_config,
942 &mut layouter,
943 config.advices[0],
944 vote_authority_note_old_cond1,
945 self.vote_comm_tree_position,
946 self.vote_comm_tree_path,
947 "cond1: merkle",
948 )?;
949
950 // Bind the computed Merkle root to the VOTE_COMM_TREE_ROOT
951 // public input. The verifier checks that the voter's VAN is
952 // a leaf in the published vote commitment tree.
953 layouter.constrain_instance(
954 root.cell(),
955 config.primary,
956 VOTE_COMM_TREE_ROOT,
957 )?;
958 }
959
960 // ---------------------------------------------------------------
961 // Witness assignment for condition 5.
962 //
963 // vsk_nk was already witnessed before condition 3 (shared between
964 // conditions 3 and 5). The vsk_nk_cond4 clone is used here.
965 // ---------------------------------------------------------------
966
967 // "vote authority spend" domain tag — constant-constrained so the
968 // value is baked into the verification key.
969 let domain_van_nf = layouter.assign_region(
970 || "DOMAIN_VAN_NULLIFIER constant",
971 |mut region| {
972 region.assign_advice_from_constant(
973 || "domain_van_nullifier",
974 config.advices[0],
975 0,
976 domain_van_nullifier(),
977 )
978 },
979 )?;
980
981 // ---------------------------------------------------------------
982 // Condition 5: VAN Nullifier Integrity.
983 // van_nullifier = Poseidon(vsk_nk, domain_tag, voting_round_id, vote_authority_note_old)
984 //
985 // Single ConstantLength<4> Poseidon hash (2 permutations at rate=2).
986 //
987 // voting_round_id and vote_authority_note_old are reused from
988 // condition 2 via cell equality — these cells flow directly into
989 // the Poseidon state without being re-witnessed.
990 // ---------------------------------------------------------------
991
992 let van_nullifier = {
993 let hasher = PoseidonHash::<
994 pallas::Base,
995 _,
996 poseidon::P128Pow5T3,
997 ConstantLength<4>,
998 3, // WIDTH
999 2, // RATE
1000 >::init(
1001 config.poseidon_chip(),
1002 layouter.namespace(|| "VAN nullifier Poseidon init"),
1003 )?;
1004 hasher.hash(
1005 layouter.namespace(|| "Poseidon(vsk_nk, domain, round_id, van_old)"),
1006 [vsk_nk_cond4, domain_van_nf, voting_round_id_cond4, vote_authority_note_old],
1007 )?
1008 };
1009
1010 // Bind the derived nullifier to the VAN_NULLIFIER public input.
1011 // The verifier checks that the prover's computed nullifier matches
1012 // the publicly posted value, preventing double-voting.
1013 layouter.constrain_instance(van_nullifier.cell(), config.primary, VAN_NULLIFIER)?;
1014
1015 // ---------------------------------------------------------------
1016 // Condition 6: Proposal Authority Decrement (bit decomposition).
1017 //
1018 // Step 1: Decompose proposal_authority_old into 16 bits b_i (boolean).
1019 // Step 2: Selector sel_i = 1 iff proposal_id == i; exactly one active;
1020 // selected bit = sum(sel_i * b_i) = 1 (voter has authority).
1021 // Step 3: b_new_i = b_i*(1-sel_i); recompose to proposal_authority_new.
1022 // No diff/gap range check; decomposition proves [0, 2^16).
1023 // ---------------------------------------------------------------
1024
1025 // Copy proposal_id from the public instance into an advice cell.
1026 let proposal_id = layouter.assign_region(
1027 || "copy proposal_id from instance",
1028 |mut region| {
1029 region.assign_advice_from_instance(
1030 || "proposal_id",
1031 config.primary,
1032 PROPOSAL_ID,
1033 config.advices[0],
1034 0,
1035 )
1036 },
1037 )?;
1038
1039 let proposal_authority_new = AuthorityDecrementChip::assign(
1040 &config.authority_decrement,
1041 &mut layouter,
1042 proposal_id.clone(),
1043 proposal_authority_old,
1044 self.one_shifted,
1045 )?;
1046
1047 // ---------------------------------------------------------------
1048 // Condition 7: New VAN Integrity (ZKP 1–compatible two-layer hash).
1049 //
1050 // Same structure as condition 2; proposal_authority_new (from
1051 // condition 6) replaces proposal_authority_old. vpk_g_d and vpk_pk_d
1052 // are unchanged (same diversified address).
1053 // ---------------------------------------------------------------
1054
1055 let derived_van_new = van_integrity::van_integrity_poseidon(
1056 &config.poseidon_config,
1057 &mut layouter,
1058 "New VAN integrity",
1059 domain_van_cond6,
1060 vpk_g_d_cond6,
1061 vpk_pk_d_cond6,
1062 total_note_value_cond6,
1063 voting_round_id_cond6,
1064 proposal_authority_new,
1065 van_comm_rand_cond6,
1066 )?;
1067
1068 // Bind the derived new VAN to the VOTE_AUTHORITY_NOTE_NEW public input.
1069 // The verifier checks that the new VAN commitment posted on-chain is
1070 // correctly formed with decremented proposal authority.
1071 layouter.constrain_instance(
1072 derived_van_new.cell(),
1073 config.primary,
1074 VOTE_AUTHORITY_NOTE_NEW,
1075 )?;
1076
1077 // ---------------------------------------------------------------
1078 // Condition 8: Shares Sum Correctness.
1079 //
1080 // sum(share_0, ..., share_15) = total_note_value
1081 //
1082 // Proves the voting share decomposition is consistent with the
1083 // total delegated weight (in ballots). Uses 15 chained AddChip additions:
1084 // partial_1 = share_0 + share_1
1085 // partial_2 = partial_1 + share_2
1086 // ...
1087 // shares_sum = partial_14 + share_15
1088 // Then constrains shares_sum == total_note_value (from condition 2).
1089 // ---------------------------------------------------------------
1090
1091 // Witness the 16 plaintext shares. These cells are also used
1092 // by condition 9 (range check) and condition 11 (El Gamal
1093 // encryption inputs).
1094 let share_cells: [_; 16] = (0..16usize)
1095 .map(|i| assign_free_advice(
1096 layouter.namespace(|| alloc::format!("witness share_{i}")),
1097 config.advices[0],
1098 self.shares[i],
1099 ))
1100 .collect::<Result<Vec<_>, _>>()?
1101 .try_into()
1102 .expect("always 16 elements");
1103
1104 // Chain 15 additions: share_0 + share_1 + ... + share_15.
1105 let shares_sum = share_cells[1..].iter().enumerate().try_fold(
1106 share_cells[0].clone(),
1107 |acc, (i, share)| {
1108 config.add_chip().add(
1109 layouter.namespace(|| alloc::format!("shares sum step {}", i + 1)),
1110 &acc,
1111 share,
1112 )
1113 },
1114 )?;
1115
1116 // Constrain: shares_sum == total_note_value.
1117 // This ensures the 16 shares decompose the voter's total delegated
1118 // weight without creating or destroying value.
1119 layouter.assign_region(
1120 || "shares sum == total_note_value",
1121 |mut region| {
1122 region.constrain_equal(shares_sum.cell(), total_note_value_cond8.cell())
1123 },
1124 )?;
1125
1126 // ---------------------------------------------------------------
1127 // Condition 9: Shares Range.
1128 //
1129 // Each share_i in [0, 2^30)
1130 //
1131 // Motivation: the sum constraint (condition 8) holds in the
1132 // base field F_p, but El Gamal encryption operates in the
1133 // scalar field F_q via `share_i * G`. For Pallas, p ≠ q, so a
1134 // large base-field element (e.g. p − 50) reduces to a different
1135 // value mod q, breaking the correspondence between the
1136 // constrained sum and the encrypted values. Bounding each share
1137 // to [0, 2^30) guarantees both representations agree (no
1138 // modular reduction in either field), so the homomorphic tally
1139 // faithfully reflects condition 8's sum.
1140 //
1141 // Secondary benefit: after accumulation the EA decrypts to
1142 // `total_value * G` and must solve a bounded DLOG (BSGS) to
1143 // recover `total_value`. Bounded shares keep the per-decision
1144 // aggregate small enough for efficient recovery.
1145 //
1146 // Shares are denominated in ballots (1 ballot = 0.125 ZEC),
1147 // converted from zatoshi in ZKP #1's condition 8 (ballot
1148 // scaling). Uses 3 × 10-bit lookup words with strict mode,
1149 // giving [0, 2^30). halo2_gadgets v0.3's `short_range_check`
1150 // is private, so exact non-10-bit-aligned bounds (e.g. 24-bit)
1151 // are unavailable. 2^30 ballots ≈ 134M ZEC — well above the
1152 // 21M ZEC supply — so the bound is never binding in practice.
1153 //
1154 // If a share exceeds 2^30 (or wraps around the field, e.g.
1155 // from underflow), the 3-word decomposition produces a non-zero
1156 // z_3 running sum, which fails the strict check.
1157 // ---------------------------------------------------------------
1158
1159 // Share cells are cloned because copy_check takes ownership;
1160 // the originals remain available for condition 11 (El Gamal).
1161 for (i, cell) in share_cells.iter().enumerate() {
1162 config.range_check_config().copy_check(
1163 layouter.namespace(|| alloc::format!("share_{i} < 2^30")),
1164 cell.clone(),
1165 3, // num_words: 3 × 10 = 30 bits
1166 true, // strict: running sum terminates at 0
1167 )?;
1168 }
1169
1170 // ---------------------------------------------------------------
1171 // Condition 10: Shares Hash Integrity (blinded commitments).
1172 //
1173 // share_comm_i = Poseidon(blind_i, c1_i_x, c2_i_x, c1_i_y, c2_i_y)
1174 // shares_hash = Poseidon(share_comm_0, ..., share_comm_15)
1175 //
1176 // The y-coordinates bind each share commitment to the exact curve
1177 // point, preventing ciphertext sign-malleability attacks.
1178 // The blind factors prevent on-chain observers from recomputing
1179 // shares_hash. shares_hash is an internal wire; it is not bound to
1180 // the instance column. Condition 11 constrains that each
1181 // (c1_i_x, c2_i_x, c1_i_y, c2_i_y) is a valid El Gamal encryption
1182 // of shares_i. Condition 12 computes the full vote commitment
1183 // H(DOMAIN_VC, voting_round_id, shares_hash, proposal_id, vote_decision)
1184 // and binds that value to the VOTE_COMMITMENT public input.
1185 // ---------------------------------------------------------------
1186
1187 let blinds: [AssignedCell<pallas::Base, pallas::Base>; 16] = (0..16)
1188 .map(|i| {
1189 assign_free_advice(
1190 layouter.namespace(|| alloc::format!("witness share_blind[{i}]")),
1191 config.advices[0],
1192 self.share_blinds[i],
1193 )
1194 })
1195 .collect::<Result<Vec<_>, _>>()?
1196 .try_into()
1197 .expect("always 16 elements");
1198
1199 let enc_c1: [AssignedCell<pallas::Base, pallas::Base>; 16] = (0..16)
1200 .map(|i| assign_free_advice(
1201 layouter.namespace(|| alloc::format!("witness enc_c1_x[{i}]")),
1202 config.advices[0],
1203 self.enc_share_c1_x[i],
1204 ))
1205 .collect::<Result<Vec<_>, _>>()?
1206 .try_into()
1207 .expect("always 16 elements");
1208
1209 let enc_c2: [AssignedCell<pallas::Base, pallas::Base>; 16] = (0..16)
1210 .map(|i| assign_free_advice(
1211 layouter.namespace(|| alloc::format!("witness enc_c2_x[{i}]")),
1212 config.advices[0],
1213 self.enc_share_c2_x[i],
1214 ))
1215 .collect::<Result<Vec<_>, _>>()?
1216 .try_into()
1217 .expect("always 16 elements");
1218
1219 let enc_c1_y: [AssignedCell<pallas::Base, pallas::Base>; 16] = (0..16)
1220 .map(|i| assign_free_advice(
1221 layouter.namespace(|| alloc::format!("witness enc_c1_y[{i}]")),
1222 config.advices[0],
1223 self.enc_share_c1_y[i],
1224 ))
1225 .collect::<Result<Vec<_>, _>>()?
1226 .try_into()
1227 .expect("always 16 elements");
1228
1229 let enc_c2_y: [AssignedCell<pallas::Base, pallas::Base>; 16] = (0..16)
1230 .map(|i| assign_free_advice(
1231 layouter.namespace(|| alloc::format!("witness enc_c2_y[{i}]")),
1232 config.advices[0],
1233 self.enc_share_c2_y[i],
1234 ))
1235 .collect::<Result<Vec<_>, _>>()?
1236 .try_into()
1237 .expect("always 16 elements");
1238
1239 // Clone for Condition 11 before compute_shares_hash_in_circuit takes ownership.
1240 let enc_c1_cond11: [AssignedCell<pallas::Base, pallas::Base>; 16] =
1241 core::array::from_fn(|i| enc_c1[i].clone());
1242 let enc_c2_cond11: [AssignedCell<pallas::Base, pallas::Base>; 16] =
1243 core::array::from_fn(|i| enc_c2[i].clone());
1244 let enc_c1_y_cond11: [AssignedCell<pallas::Base, pallas::Base>; 16] =
1245 core::array::from_fn(|i| enc_c1_y[i].clone());
1246 let enc_c2_y_cond11: [AssignedCell<pallas::Base, pallas::Base>; 16] =
1247 core::array::from_fn(|i| enc_c2_y[i].clone());
1248
1249 let shares_hash = compute_shares_hash_in_circuit(
1250 || config.poseidon_chip(),
1251 layouter.namespace(|| "cond10: shares hash"),
1252 blinds,
1253 enc_c1,
1254 enc_c2,
1255 enc_c1_y,
1256 enc_c2_y,
1257 )?;
1258
1259 // ---------------------------------------------------------------
1260 // Condition 11: Encryption Integrity.
1261 //
1262 // For each share i: C1_i = [r_i]*G, C2_i = [v_i]*G + [r_i]*ea_pk;
1263 // Both coordinates of C1_i and C2_i are constrained to the
1264 // witnessed enc_share cells. Implemented by the shared
1265 // circuit::elgamal::prove_elgamal_encryptions gadget.
1266 // ---------------------------------------------------------------
1267 {
1268 let r_cells: [_; 16] = (0..16usize)
1269 .map(|i| assign_free_advice(
1270 layouter.namespace(|| alloc::format!("witness r[{i}]")),
1271 config.advices[0],
1272 self.share_randomness[i],
1273 ))
1274 .collect::<Result<Vec<_>, _>>()?
1275 .try_into()
1276 .expect("always 16 elements");
1277
1278 prove_elgamal_encryptions(
1279 ecc_chip.clone(),
1280 layouter.namespace(|| "cond11 El Gamal"),
1281 "cond11",
1282 self.ea_pk,
1283 EaPkInstanceLoc {
1284 instance: config.primary,
1285 x_row: EA_PK_X,
1286 y_row: EA_PK_Y,
1287 },
1288 config.advices[0],
1289 share_cells,
1290 r_cells,
1291 enc_c1_cond11,
1292 enc_c2_cond11,
1293 enc_c1_y_cond11,
1294 enc_c2_y_cond11,
1295 )?;
1296 }
1297
1298 // ---------------------------------------------------------------
1299 // Condition 12: Vote Commitment Integrity.
1300 //
1301 // vote_commitment = Poseidon(DOMAIN_VC, voting_round_id,
1302 // shares_hash, proposal_id, vote_decision)
1303 //
1304 // Binds the voting round, encrypted shares (via shares_hash from
1305 // condition 10), the proposal choice, and the vote decision into a
1306 // single commitment with domain separation from VANs (DOMAIN_VC = 1).
1307 //
1308 // This is the value posted on-chain and later inserted into the
1309 // vote commitment tree. ZKP #3 (vote reveal) will open individual
1310 // shares from this commitment.
1311 // ---------------------------------------------------------------
1312
1313 // DOMAIN_VC — constant-constrained so the value is baked into the
1314 // verification key and cannot be altered by a malicious prover.
1315 let domain_vc = layouter.assign_region(
1316 || "DOMAIN_VC constant",
1317 |mut region| {
1318 region.assign_advice_from_constant(
1319 || "domain_vc",
1320 config.advices[0],
1321 0,
1322 pallas::Base::from(DOMAIN_VC),
1323 )
1324 },
1325 )?;
1326
1327 // proposal_id was already copied from instance in condition 6; reuse that cell.
1328
1329 // Private witness: vote decision.
1330 let vote_decision = assign_free_advice(
1331 layouter.namespace(|| "witness vote_decision"),
1332 config.advices[0],
1333 self.vote_decision,
1334 )?;
1335
1336 // Compute vote_commitment = Poseidon(DOMAIN_VC, voting_round_id,
1337 // shares_hash, proposal_id, vote_decision).
1338 let vote_commitment = vote_commitment::vote_commitment_poseidon(
1339 &config.poseidon_config,
1340 &mut layouter,
1341 "cond12",
1342 domain_vc,
1343 voting_round_id_cond12,
1344 shares_hash,
1345 proposal_id,
1346 vote_decision,
1347 )?;
1348
1349 // Bind the derived vote commitment to the VOTE_COMMITMENT public input.
1350 layouter.constrain_instance(
1351 vote_commitment.cell(),
1352 config.primary,
1353 VOTE_COMMITMENT,
1354 )?;
1355
1356 Ok(())
1357 }
1358}
1359
1360// ================================================================
1361// Instance (public inputs)
1362// ================================================================
1363
1364/// Public inputs to the Vote Proof circuit (11 field elements).
1365///
1366/// These are the values posted to the vote chain that both the prover
1367/// and verifier agree on. The verifier checks the proof against these
1368/// values without seeing any private witnesses.
1369#[derive(Clone, Debug)]
1370pub struct Instance {
1371 /// The nullifier of the old VAN being spent (prevents double-vote).
1372 pub van_nullifier: pallas::Base,
1373 /// Randomized voting public key (condition 4): x-coordinate of r_vpk = vsk.ak + [alpha_v] * G.
1374 pub r_vpk_x: pallas::Base,
1375 /// Randomized voting public key: y-coordinate.
1376 pub r_vpk_y: pallas::Base,
1377 /// The new VAN commitment (with decremented proposal authority).
1378 pub vote_authority_note_new: pallas::Base,
1379 /// The vote commitment hash.
1380 pub vote_commitment: pallas::Base,
1381 /// Root of the vote commitment tree at anchor height.
1382 pub vote_comm_tree_root: pallas::Base,
1383 /// The vote-chain height at which the tree is snapshotted.
1384 pub vote_comm_tree_anchor_height: pallas::Base,
1385 /// Which proposal this vote is for.
1386 pub proposal_id: pallas::Base,
1387 /// The voting round identifier.
1388 pub voting_round_id: pallas::Base,
1389 /// Election authority public key x-coordinate.
1390 pub ea_pk_x: pallas::Base,
1391 /// Election authority public key y-coordinate.
1392 pub ea_pk_y: pallas::Base,
1393}
1394
1395impl Instance {
1396 /// Constructs an [`Instance`] from its constituent parts.
1397 pub fn from_parts(
1398 van_nullifier: pallas::Base,
1399 r_vpk_x: pallas::Base,
1400 r_vpk_y: pallas::Base,
1401 vote_authority_note_new: pallas::Base,
1402 vote_commitment: pallas::Base,
1403 vote_comm_tree_root: pallas::Base,
1404 vote_comm_tree_anchor_height: pallas::Base,
1405 proposal_id: pallas::Base,
1406 voting_round_id: pallas::Base,
1407 ea_pk_x: pallas::Base,
1408 ea_pk_y: pallas::Base,
1409 ) -> Self {
1410 Instance {
1411 van_nullifier,
1412 r_vpk_x,
1413 r_vpk_y,
1414 vote_authority_note_new,
1415 vote_commitment,
1416 vote_comm_tree_root,
1417 vote_comm_tree_anchor_height,
1418 proposal_id,
1419 voting_round_id,
1420 ea_pk_x,
1421 ea_pk_y,
1422 }
1423 }
1424
1425 /// Serializes public inputs for halo2 proof creation/verification.
1426 ///
1427 /// The order must match the instance column offsets defined at the
1428 /// top of this file (`VAN_NULLIFIER`, `R_VPK_X`, `R_VPK_Y`, etc.).
1429 pub fn to_halo2_instance(&self) -> Vec<vesta::Scalar> {
1430 alloc::vec![
1431 self.van_nullifier,
1432 self.r_vpk_x,
1433 self.r_vpk_y,
1434 self.vote_authority_note_new,
1435 self.vote_commitment,
1436 self.vote_comm_tree_root,
1437 self.vote_comm_tree_anchor_height,
1438 self.proposal_id,
1439 self.voting_round_id,
1440 self.ea_pk_x,
1441 self.ea_pk_y,
1442 ]
1443 }
1444}
1445
1446// ================================================================
1447// Tests
1448// ================================================================
1449
1450#[cfg(test)]
1451mod tests {
1452 use super::*;
1453 use crate::circuit::elgamal::{base_to_scalar, elgamal_encrypt, spend_auth_g_affine};
1454 use core::iter;
1455 use ff::Field;
1456 use group::ff::PrimeFieldBits;
1457 use group::{Curve, Group};
1458 use halo2_gadgets::sinsemilla::primitives::CommitDomain;
1459 use halo2_proofs::dev::MockProver;
1460 use pasta_curves::arithmetic::CurveAffine;
1461 use pasta_curves::pallas;
1462 use rand::rngs::OsRng;
1463
1464 use orchard::constants::{
1465 fixed_bases::COMMIT_IVK_PERSONALIZATION,
1466 L_ORCHARD_BASE,
1467 };
1468
1469 /// Generates an El Gamal keypair for testing.
1470 /// Returns `(ea_sk, ea_pk_point, ea_pk_affine)`.
1471 fn generate_ea_keypair() -> (pallas::Scalar, pallas::Point, pallas::Affine) {
1472 let ea_sk = pallas::Scalar::from(42u64);
1473 let g = pallas::Point::from(spend_auth_g_affine());
1474 let ea_pk = g * ea_sk;
1475 let ea_pk_affine = ea_pk.to_affine();
1476 (ea_sk, ea_pk, ea_pk_affine)
1477 }
1478
1479 /// Computes real El Gamal encryptions for 16 shares.
1480 ///
1481 /// Returns `(c1_x, c2_x, c1_y, c2_y, randomness, share_blinds, shares_hash_value)` where:
1482 /// - `c1_x[i]` and `c2_x[i]` are correct ciphertext x-coordinates
1483 /// - `c1_y[i]` and `c2_y[i]` are correct ciphertext y-coordinates
1484 /// - `randomness[i]` is the base field randomness used for each share
1485 /// - `share_blinds[i]` is the blind factor for each share commitment
1486 /// - `shares_hash_value` is the blinded Poseidon hash of all shares
1487 fn encrypt_shares(
1488 shares: [u64; 16],
1489 ea_pk: pallas::Point,
1490 ) -> (
1491 [pallas::Base; 16],
1492 [pallas::Base; 16],
1493 [pallas::Base; 16],
1494 [pallas::Base; 16],
1495 [pallas::Base; 16],
1496 [pallas::Base; 16],
1497 pallas::Base,
1498 ) {
1499 let mut c1_x = [pallas::Base::zero(); 16];
1500 let mut c2_x = [pallas::Base::zero(); 16];
1501 let mut c1_y = [pallas::Base::zero(); 16];
1502 let mut c2_y = [pallas::Base::zero(); 16];
1503 // Use small deterministic randomness (fits in both Base and Scalar).
1504 let randomness: [pallas::Base; 16] = core::array::from_fn(|i| {
1505 pallas::Base::from((i as u64 + 1) * 101)
1506 });
1507 // Deterministic blind factors for tests.
1508 let share_blinds: [pallas::Base; 16] = core::array::from_fn(|i| {
1509 pallas::Base::from(1001u64 + i as u64)
1510 });
1511 for i in 0..16 {
1512 let (cx1, cx2, cy1, cy2) = elgamal_encrypt(
1513 pallas::Base::from(shares[i]),
1514 randomness[i],
1515 ea_pk,
1516 );
1517 c1_x[i] = cx1;
1518 c2_x[i] = cx2;
1519 c1_y[i] = cy1;
1520 c2_y[i] = cy2;
1521 }
1522 let hash = shares_hash(share_blinds, c1_x, c2_x, c1_y, c2_y);
1523 (c1_x, c2_x, c1_y, c2_y, randomness, share_blinds, hash)
1524 }
1525
1526 /// Out-of-circuit voting key derivation for tests.
1527 ///
1528 /// Given a voting spending key (vsk), nullifier key (nk), and CommitIvk
1529 /// randomness (rivk_v), derives the full voting address:
1530 ///
1531 /// 1. `ak = [vsk] * SpendAuthG` (spend validating key)
1532 /// 2. `ak_x = ExtractP(ak)` (x-coordinate)
1533 /// 3. `ivk_v = CommitIvk(ak_x, nk, rivk_v)` (incoming viewing key)
1534 /// 4. `g_d = random non-identity point` (diversified base)
1535 /// 5. `pk_d = [ivk_v] * g_d` (diversified transmission key)
1536 ///
1537 /// Returns `(g_d_affine, pk_d_affine, ak_x)` for use as circuit witnesses.
1538 fn derive_voting_address(
1539 vsk: pallas::Scalar,
1540 nk: pallas::Base,
1541 rivk_v: pallas::Scalar,
1542 ) -> (pallas::Affine, pallas::Affine) {
1543 // Step 1: ak = [vsk] * SpendAuthG
1544 let g = pallas::Point::from(spend_auth_g_affine());
1545 let ak_point = g * vsk;
1546 let ak_x = *ak_point.to_affine().coordinates().unwrap().x();
1547
1548 // Step 2: ivk_v = CommitIvk(ak_x, nk, rivk_v)
1549 let domain = CommitDomain::new(COMMIT_IVK_PERSONALIZATION);
1550 let ivk_v = domain
1551 .short_commit(
1552 iter::empty()
1553 .chain(ak_x.to_le_bits().iter().by_vals().take(L_ORCHARD_BASE))
1554 .chain(nk.to_le_bits().iter().by_vals().take(L_ORCHARD_BASE)),
1555 &rivk_v,
1556 )
1557 .expect("CommitIvk should not produce ⊥ for random inputs");
1558
1559 // Step 3: g_d = random non-identity point
1560 // Using a deterministic point derived from a fixed seed ensures
1561 // reproducibility while avoiding the identity point.
1562 let g_d = pallas::Point::generator() * pallas::Scalar::from(12345u64);
1563 let g_d_affine = g_d.to_affine();
1564
1565 // Step 4: pk_d = [ivk_v] * g_d
1566 let ivk_v_scalar =
1567 base_to_scalar(ivk_v).expect("ivk_v must be < scalar field modulus");
1568 let pk_d = g_d * ivk_v_scalar;
1569 let pk_d_affine = pk_d.to_affine();
1570
1571 (g_d_affine, pk_d_affine)
1572 }
1573
1574 /// Default proposal_id and vote_decision for tests.
1575 const TEST_PROPOSAL_ID: u64 = 3;
1576 const TEST_VOTE_DECISION: u64 = 1;
1577
1578 /// Sets condition 12 fields on a circuit and returns the vote_commitment.
1579 ///
1580 /// Computes `H(DOMAIN_VC, voting_round_id, shares_hash, proposal_id, vote_decision)`
1581 /// and sets `circuit.vote_decision`. Returns the vote_commitment
1582 /// for use in the Instance. The `proposal_id` must match the
1583 /// instance's proposal_id so the circuit's condition 12 (which
1584 /// copies proposal_id from the instance) agrees with the instance.
1585 fn set_condition_11(
1586 circuit: &mut Circuit,
1587 shares_hash_val: pallas::Base,
1588 proposal_id: u64,
1589 voting_round_id: pallas::Base,
1590 ) -> pallas::Base {
1591 let proposal_id_base = pallas::Base::from(proposal_id);
1592 let vote_decision = pallas::Base::from(TEST_VOTE_DECISION);
1593 circuit.vote_decision = Value::known(vote_decision);
1594 vote_commitment_hash(voting_round_id, shares_hash_val, proposal_id_base, vote_decision)
1595 }
1596
1597 /// Build valid test data for all 11 conditions.
1598 ///
1599 /// Returns a circuit with correctly-hashed VAN witnesses, valid
1600 /// shares, real El Gamal ciphertexts, and a matching instance.
1601 fn build_single_leaf_merkle_path(
1602 leaf: pallas::Base,
1603 ) -> ([pallas::Base; VOTE_COMM_TREE_DEPTH], u32, pallas::Base) {
1604 let mut empty_roots = [pallas::Base::zero(); VOTE_COMM_TREE_DEPTH];
1605 empty_roots[0] = poseidon_hash_2(pallas::Base::zero(), pallas::Base::zero());
1606 for i in 1..VOTE_COMM_TREE_DEPTH {
1607 empty_roots[i] = poseidon_hash_2(empty_roots[i - 1], empty_roots[i - 1]);
1608 }
1609 let auth_path = empty_roots;
1610 let mut current = leaf;
1611 for i in 0..VOTE_COMM_TREE_DEPTH {
1612 current = poseidon_hash_2(current, auth_path[i]);
1613 }
1614 (auth_path, 0, current)
1615 }
1616
1617 /// Build test (circuit, instance) with given proposal_authority_old and proposal_id.
1618 /// proposal_authority_old must have the proposal_id-th bit set (spec bitmask).
1619 fn make_test_data_with_authority_and_proposal(
1620 proposal_authority_old: pallas::Base,
1621 proposal_id: u64,
1622 ) -> (Circuit, Instance) {
1623 let mut rng = OsRng;
1624
1625 // Condition 3 (spend authority): derive proper voting key hierarchy.
1626 // vsk → ak → ivk_v → (vpk_g_d, vpk_pk_d) through CommitIvk chain.
1627 let vsk = pallas::Scalar::random(&mut rng);
1628 let vsk_nk = pallas::Base::random(&mut rng);
1629 let rivk_v = pallas::Scalar::random(&mut rng);
1630 let alpha_v = pallas::Scalar::random(&mut rng);
1631
1632 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
1633
1634 // Condition 4: r_vpk = ak + [alpha_v] * G
1635 let g = pallas::Point::from(spend_auth_g_affine());
1636 let ak_point = g * vsk;
1637 let r_vpk = (ak_point + g * alpha_v).to_affine();
1638 let r_vpk_x = *r_vpk.coordinates().unwrap().x();
1639 let r_vpk_y = *r_vpk.coordinates().unwrap().y();
1640
1641 // Extract x-coordinates for Poseidon hashing (conditions 2, 6).
1642 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
1643 let vpk_pk_d_x = *vpk_pk_d_affine.coordinates().unwrap().x();
1644
1645 // total_note_value must be small enough that all 16 shares
1646 // fit in [0, 2^30) for condition 9's range check.
1647 let total_note_value = pallas::Base::from(10_000u64);
1648 let voting_round_id = pallas::Base::random(&mut rng);
1649 let van_comm_rand = pallas::Base::random(&mut rng);
1650
1651 let vote_authority_note_old = van_integrity_hash(
1652 vpk_g_d_x,
1653 vpk_pk_d_x,
1654 total_note_value,
1655 voting_round_id,
1656 proposal_authority_old,
1657 van_comm_rand,
1658 );
1659 let (auth_path, position, vote_comm_tree_root) =
1660 build_single_leaf_merkle_path(vote_authority_note_old);
1661 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
1662 // Spec: proposal_authority_new = proposal_authority_old - (1 << proposal_id).
1663 let one_shifted = pallas::Base::from(1u64 << proposal_id);
1664 let proposal_authority_new = proposal_authority_old - one_shifted;
1665 let vote_authority_note_new = van_integrity_hash(
1666 vpk_g_d_x,
1667 vpk_pk_d_x,
1668 total_note_value,
1669 voting_round_id,
1670 proposal_authority_new,
1671 van_comm_rand,
1672 );
1673
1674 // Create shares that sum to total_note_value (conditions 8 + 9).
1675 // Each share must be in [0, 2^30) for condition 9's range check.
1676 let shares_u64: [u64; 16] = [625; 16]; // sum = 10000
1677
1678 // Condition 11: El Gamal encryption of shares under ea_pk.
1679 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
1680 let ea_pk_x = *ea_pk_affine.coordinates().unwrap().x();
1681 let ea_pk_y = *ea_pk_affine.coordinates().unwrap().y();
1682 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
1683 encrypt_shares(shares_u64, ea_pk_point);
1684
1685 let mut circuit = Circuit::with_van_witnesses(
1686 Value::known(auth_path),
1687 Value::known(position),
1688 Value::known(vpk_g_d_affine),
1689 Value::known(vpk_pk_d_affine),
1690 Value::known(total_note_value),
1691 Value::known(proposal_authority_old),
1692 Value::known(van_comm_rand),
1693 Value::known(vote_authority_note_old),
1694 Value::known(vsk),
1695 Value::known(rivk_v),
1696 Value::known(vsk_nk),
1697 Value::known(alpha_v),
1698 );
1699 circuit.one_shifted = Value::known(one_shifted);
1700 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
1701 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
1702 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
1703 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
1704 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
1705 circuit.share_blinds = share_blinds.map(Value::known);
1706 circuit.share_randomness = randomness.map(Value::known);
1707 circuit.ea_pk = Value::known(ea_pk_affine);
1708
1709 // Condition 12: vote commitment from shares_hash + proposal + decision.
1710 let vote_commitment = set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
1711
1712 let instance = Instance::from_parts(
1713 van_nullifier,
1714 r_vpk_x,
1715 r_vpk_y,
1716 vote_authority_note_new,
1717 vote_commitment,
1718 vote_comm_tree_root,
1719 pallas::Base::zero(),
1720 pallas::Base::from(proposal_id),
1721 voting_round_id,
1722 ea_pk_x,
1723 ea_pk_y,
1724 );
1725
1726 (circuit, instance)
1727 }
1728
1729 fn make_test_data_with_authority(proposal_authority_old: pallas::Base) -> (Circuit, Instance) {
1730 make_test_data_with_authority_and_proposal(proposal_authority_old, TEST_PROPOSAL_ID)
1731 }
1732
1733 fn make_test_data() -> (Circuit, Instance) {
1734 // proposal_authority_old must have bit TEST_PROPOSAL_ID set (spec bitmask).
1735 // 5 | (1 << 3) = 13 so we can vote on proposal 3 and get new = 5.
1736 make_test_data_with_authority(pallas::Base::from(13u64))
1737 }
1738
1739 // ================================================================
1740 // Condition 2 (VAN Integrity) tests
1741 // ================================================================
1742
1743 #[test]
1744 fn van_integrity_valid_proof() {
1745 let (circuit, instance) = make_test_data();
1746
1747 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
1748
1749 assert_eq!(prover.verify(), Ok(()));
1750 }
1751
1752 #[test]
1753 fn van_integrity_wrong_hash_fails() {
1754 let mut rng = OsRng;
1755 let (_, mut instance) = make_test_data();
1756
1757 // Deliberately wrong VAN value — condition 2 constrain_equal will fail.
1758 let wrong_van = pallas::Base::random(&mut rng);
1759 let (auth_path, position, root) = build_single_leaf_merkle_path(wrong_van);
1760 instance.vote_comm_tree_root = root;
1761
1762 // Use properly derived keys (condition 3 would pass) but the VAN
1763 // hash won't match wrong_van, so condition 2 fails.
1764 let vsk = pallas::Scalar::random(&mut rng);
1765 let vsk_nk = pallas::Base::random(&mut rng);
1766 let rivk_v = pallas::Scalar::random(&mut rng);
1767 let alpha_v = pallas::Scalar::random(&mut rng);
1768 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
1769 let g = pallas::Point::from(spend_auth_g_affine());
1770 let r_vpk = (g * vsk + g * alpha_v).to_affine();
1771 instance.r_vpk_x = *r_vpk.coordinates().unwrap().x();
1772 instance.r_vpk_y = *r_vpk.coordinates().unwrap().y();
1773
1774 let shares_u64: [u64; 16] = [625; 16];
1775 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
1776 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
1777 encrypt_shares(shares_u64, ea_pk_point);
1778
1779 // Use authority 13 (bit 3 set) and one_shifted = 8 so condition 6 is consistent;
1780 // only condition 2 (VAN hash) should fail due to wrong_van.
1781 let proposal_authority_old = pallas::Base::from(13u64);
1782 let van_comm_rand = pallas::Base::random(&mut rng);
1783 let mut circuit = Circuit::with_van_witnesses(
1784 Value::known(auth_path),
1785 Value::known(position),
1786 Value::known(vpk_g_d_affine),
1787 Value::known(vpk_pk_d_affine),
1788 Value::known(pallas::Base::from(10_000u64)),
1789 Value::known(proposal_authority_old),
1790 Value::known(van_comm_rand),
1791 Value::known(wrong_van),
1792 Value::known(vsk),
1793 Value::known(rivk_v),
1794 Value::known(vsk_nk),
1795 Value::known(alpha_v),
1796 );
1797 circuit.one_shifted = Value::known(pallas::Base::from(1u64 << TEST_PROPOSAL_ID));
1798 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
1799 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
1800 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
1801 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
1802 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
1803 circuit.share_blinds = share_blinds.map(Value::known);
1804 circuit.share_randomness = randomness.map(Value::known);
1805 circuit.ea_pk = Value::known(ea_pk_affine);
1806 let vc = set_condition_11(&mut circuit, shares_hash_val, TEST_PROPOSAL_ID, instance.voting_round_id);
1807 instance.vote_commitment = vc;
1808 instance.proposal_id = pallas::Base::from(TEST_PROPOSAL_ID);
1809 instance.ea_pk_x = *ea_pk_affine.coordinates().unwrap().x();
1810 instance.ea_pk_y = *ea_pk_affine.coordinates().unwrap().y();
1811
1812 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
1813 // Should fail: derived hash ≠ witnessed vote_authority_note_old.
1814 assert!(prover.verify().is_err());
1815 }
1816
1817 #[test]
1818 fn van_integrity_wrong_round_id_fails() {
1819 let (circuit, mut instance) = make_test_data();
1820
1821 // Supply a DIFFERENT voting_round_id in the instance.
1822 instance.voting_round_id = pallas::Base::random(&mut OsRng);
1823
1824 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
1825 // Should fail: the voting_round_id from the instance doesn't match
1826 // the one hashed into the VAN (condition 2).
1827 assert!(prover.verify().is_err());
1828 }
1829
1830 /// Verifies the out-of-circuit helper produces deterministic results.
1831 #[test]
1832 fn van_integrity_hash_deterministic() {
1833 let mut rng = OsRng;
1834
1835 let vpk_g_d = pallas::Base::random(&mut rng);
1836 let vpk_pk_d = pallas::Base::random(&mut rng);
1837 let val = pallas::Base::random(&mut rng);
1838 let round = pallas::Base::random(&mut rng);
1839 let auth = pallas::Base::random(&mut rng);
1840 let rand = pallas::Base::random(&mut rng);
1841
1842 let h1 = van_integrity_hash(vpk_g_d, vpk_pk_d, val, round, auth, rand);
1843 let h2 = van_integrity_hash(vpk_g_d, vpk_pk_d, val, round, auth, rand);
1844 assert_eq!(h1, h2);
1845
1846 // Changing any input changes the hash.
1847 let h3 = van_integrity_hash(
1848 pallas::Base::random(&mut rng),
1849 vpk_pk_d,
1850 val,
1851 round,
1852 auth,
1853 rand,
1854 );
1855 assert_ne!(h1, h3);
1856 }
1857
1858 // ================================================================
1859 // Condition 3 (Diversified Address Integrity / Address Ownership) tests
1860 //
1861 // These tests ensure the circuit rejects witnesses that violate
1862 // vpk_pk_d = [ivk_v] * vpk_g_d. Without condition 3 enabled, they
1863 // would pass (invalid address ownership would not be detected).
1864 // ================================================================
1865
1866 /// Using a different vsk in the circuit than was used to derive
1867 /// (vpk_g_d, vpk_pk_d) should fail condition 3 only: in-circuit
1868 /// [ivk']*vpk_g_d ≠ vpk_pk_d while VAN hash and nullifier stay valid.
1869 #[test]
1870 fn condition_3_wrong_vsk_fails() {
1871 let mut rng = OsRng;
1872
1873 let vsk = pallas::Scalar::random(&mut rng);
1874 let vsk_nk = pallas::Base::random(&mut rng);
1875 let rivk_v = pallas::Scalar::random(&mut rng);
1876 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
1877 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
1878 let vpk_pk_d_x = *vpk_pk_d_affine.coordinates().unwrap().x();
1879
1880 let total_note_value = pallas::Base::from(10_000u64);
1881 let voting_round_id = pallas::Base::random(&mut rng);
1882 let proposal_authority_old = pallas::Base::from(13u64);
1883 let proposal_id = 3u64;
1884 let van_comm_rand = pallas::Base::random(&mut rng);
1885
1886 let vote_authority_note_old = van_integrity_hash(
1887 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
1888 proposal_authority_old, van_comm_rand,
1889 );
1890 let (auth_path, position, vote_comm_tree_root) =
1891 build_single_leaf_merkle_path(vote_authority_note_old);
1892 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
1893 let one_shifted = pallas::Base::from(1u64 << proposal_id);
1894 let proposal_authority_new = proposal_authority_old - one_shifted;
1895 let vote_authority_note_new = van_integrity_hash(
1896 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
1897 proposal_authority_new, van_comm_rand,
1898 );
1899
1900 let shares_u64: [u64; 16] = [625; 16];
1901 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
1902 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
1903 encrypt_shares(shares_u64, ea_pk_point);
1904
1905 let wrong_vsk = pallas::Scalar::random(&mut rng);
1906 assert_ne!(wrong_vsk, vsk, "test assumes distinct vsk with high probability");
1907 let alpha_v = pallas::Scalar::random(&mut rng);
1908 let g = pallas::Point::from(spend_auth_g_affine());
1909 let r_vpk = (g * vsk + g * alpha_v).to_affine();
1910 let r_vpk_x = *r_vpk.coordinates().unwrap().x();
1911 let r_vpk_y = *r_vpk.coordinates().unwrap().y();
1912
1913 let mut circuit = Circuit::with_van_witnesses(
1914 Value::known(auth_path),
1915 Value::known(position),
1916 Value::known(vpk_g_d_affine),
1917 Value::known(vpk_pk_d_affine),
1918 Value::known(total_note_value),
1919 Value::known(proposal_authority_old),
1920 Value::known(van_comm_rand),
1921 Value::known(vote_authority_note_old),
1922 Value::known(wrong_vsk),
1923 Value::known(rivk_v),
1924 Value::known(vsk_nk),
1925 Value::known(alpha_v),
1926 );
1927 circuit.one_shifted = Value::known(one_shifted);
1928 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
1929 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
1930 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
1931 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
1932 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
1933 circuit.share_blinds = share_blinds.map(Value::known);
1934 circuit.share_randomness = randomness.map(Value::known);
1935 circuit.ea_pk = Value::known(ea_pk_affine);
1936 let vc = set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
1937
1938 let instance = Instance::from_parts(
1939 van_nullifier,
1940 r_vpk_x,
1941 r_vpk_y,
1942 vote_authority_note_new,
1943 vc,
1944 vote_comm_tree_root,
1945 pallas::Base::zero(),
1946 pallas::Base::from(proposal_id),
1947 voting_round_id,
1948 *ea_pk_affine.coordinates().unwrap().x(),
1949 *ea_pk_affine.coordinates().unwrap().y(),
1950 );
1951
1952 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
1953 assert!(prover.verify().is_err(), "condition 3 must reject wrong vsk");
1954 }
1955
1956 /// Using a vpk_pk_d that does not equal [ivk_v]*vpk_g_d should fail
1957 /// condition 3. Instance is built with a wrong vpk_pk_d for the VAN
1958 /// hash so condition 2 still passes; only condition 3 fails.
1959 #[test]
1960 fn condition_3_wrong_vpk_pk_d_fails() {
1961 let mut rng = OsRng;
1962
1963 let vsk = pallas::Scalar::random(&mut rng);
1964 let vsk_nk = pallas::Base::random(&mut rng);
1965 let rivk_v = pallas::Scalar::random(&mut rng);
1966 let (vpk_g_d_affine, _vpk_pk_d_correct) = derive_voting_address(vsk, vsk_nk, rivk_v);
1967 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
1968
1969 let wrong_vpk_pk_d_affine = (pallas::Point::generator() * pallas::Scalar::from(99999u64))
1970 .to_affine();
1971 let wrong_vpk_pk_d_x = *wrong_vpk_pk_d_affine.coordinates().unwrap().x();
1972
1973 let total_note_value = pallas::Base::from(10_000u64);
1974 let voting_round_id = pallas::Base::random(&mut rng);
1975 let proposal_authority_old = pallas::Base::from(13u64);
1976 let proposal_id = 3u64;
1977 let van_comm_rand = pallas::Base::random(&mut rng);
1978
1979 let vote_authority_note_old = van_integrity_hash(
1980 vpk_g_d_x,
1981 wrong_vpk_pk_d_x,
1982 total_note_value,
1983 voting_round_id,
1984 proposal_authority_old,
1985 van_comm_rand,
1986 );
1987 let (auth_path, position, vote_comm_tree_root) =
1988 build_single_leaf_merkle_path(vote_authority_note_old);
1989 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
1990 let one_shifted = pallas::Base::from(1u64 << proposal_id);
1991 let proposal_authority_new = proposal_authority_old - one_shifted;
1992 let vote_authority_note_new = van_integrity_hash(
1993 vpk_g_d_x,
1994 wrong_vpk_pk_d_x,
1995 total_note_value,
1996 voting_round_id,
1997 proposal_authority_new,
1998 van_comm_rand,
1999 );
2000
2001 let shares_u64: [u64; 16] = [625; 16];
2002 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
2003 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
2004 encrypt_shares(shares_u64, ea_pk_point);
2005
2006 let alpha_v = pallas::Scalar::random(&mut rng);
2007 let g = pallas::Point::from(spend_auth_g_affine());
2008 let r_vpk = (g * vsk + g * alpha_v).to_affine();
2009 let r_vpk_x = *r_vpk.coordinates().unwrap().x();
2010 let r_vpk_y = *r_vpk.coordinates().unwrap().y();
2011
2012 let mut circuit = Circuit::with_van_witnesses(
2013 Value::known(auth_path),
2014 Value::known(position),
2015 Value::known(vpk_g_d_affine),
2016 Value::known(wrong_vpk_pk_d_affine),
2017 Value::known(total_note_value),
2018 Value::known(proposal_authority_old),
2019 Value::known(van_comm_rand),
2020 Value::known(vote_authority_note_old),
2021 Value::known(vsk),
2022 Value::known(rivk_v),
2023 Value::known(vsk_nk),
2024 Value::known(alpha_v),
2025 );
2026 circuit.one_shifted = Value::known(one_shifted);
2027 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
2028 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
2029 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
2030 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
2031 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
2032 circuit.share_blinds = share_blinds.map(Value::known);
2033 circuit.share_randomness = randomness.map(Value::known);
2034 circuit.ea_pk = Value::known(ea_pk_affine);
2035 let vc = set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
2036
2037 let instance = Instance::from_parts(
2038 van_nullifier,
2039 r_vpk_x,
2040 r_vpk_y,
2041 vote_authority_note_new,
2042 vc,
2043 vote_comm_tree_root,
2044 pallas::Base::zero(),
2045 pallas::Base::from(proposal_id),
2046 voting_round_id,
2047 *ea_pk_affine.coordinates().unwrap().x(),
2048 *ea_pk_affine.coordinates().unwrap().y(),
2049 );
2050
2051 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2052 assert!(prover.verify().is_err(), "condition 3 must reject wrong vpk_pk_d");
2053 }
2054
2055 // ================================================================
2056 // Condition 4 (Spend Authority) tests
2057 // ================================================================
2058
2059 /// Wrong r_vpk public input should fail condition 4.
2060 #[test]
2061 fn condition_4_wrong_r_vpk_fails() {
2062 let (circuit, mut instance) = make_test_data();
2063
2064 instance.r_vpk_x = pallas::Base::random(&mut OsRng);
2065
2066 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2067 assert!(prover.verify().is_err(), "condition 4 must reject wrong r_vpk");
2068 }
2069
2070 // ================================================================
2071 // Condition 5 (VAN Nullifier Integrity) tests
2072 // ================================================================
2073
2074 /// Wrong VAN_NULLIFIER public input should fail condition 5.
2075 #[test]
2076 fn van_nullifier_wrong_public_input_fails() {
2077 let (circuit, mut instance) = make_test_data();
2078
2079 // Corrupt the VAN nullifier public input.
2080 instance.van_nullifier = pallas::Base::random(&mut OsRng);
2081
2082 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2083
2084 // Should fail: circuit-derived nullifier ≠ corrupted instance value.
2085 assert!(prover.verify().is_err());
2086 }
2087
2088 /// Using a different vsk_nk in the circuit than was used to compute
2089 /// the instance nullifier should fail condition 5.
2090 /// Note: since vsk_nk is also used in CommitIvk (condition 3), the
2091 /// wrong value also breaks condition 3 — but the test still verifies
2092 /// that the proof fails as expected.
2093 #[test]
2094 fn van_nullifier_wrong_vsk_nk_fails() {
2095 let mut rng = OsRng;
2096
2097 // Derive proper keys with the CORRECT vsk_nk.
2098 let vsk = pallas::Scalar::random(&mut rng);
2099 let vsk_nk = pallas::Base::random(&mut rng);
2100 let rivk_v = pallas::Scalar::random(&mut rng);
2101 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
2102 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
2103 let vpk_pk_d_x = *vpk_pk_d_affine.coordinates().unwrap().x();
2104
2105 let total_note_value = pallas::Base::from(10_000u64);
2106 let voting_round_id = pallas::Base::random(&mut rng);
2107 let proposal_authority_old = pallas::Base::from(5u64); // bits 0 and 2 set
2108 let van_comm_rand = pallas::Base::random(&mut rng);
2109 let proposal_id = 0u64; // vote on proposal 0 so one_shifted = 1, new = 4
2110
2111 let vote_authority_note_old = van_integrity_hash(
2112 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
2113 proposal_authority_old, van_comm_rand,
2114 );
2115 let (auth_path, position, vote_comm_tree_root) =
2116 build_single_leaf_merkle_path(vote_authority_note_old);
2117 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
2118 let one_shifted = pallas::Base::from(1u64 << proposal_id);
2119 let proposal_authority_new = proposal_authority_old - one_shifted;
2120 let vote_authority_note_new = van_integrity_hash(
2121 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
2122 proposal_authority_new, van_comm_rand,
2123 );
2124
2125 // Use a DIFFERENT vsk_nk in the circuit.
2126 let wrong_vsk_nk = pallas::Base::random(&mut rng);
2127 let alpha_v = pallas::Scalar::random(&mut rng);
2128 let g = pallas::Point::from(spend_auth_g_affine());
2129 let r_vpk = (g * vsk + g * alpha_v).to_affine();
2130 let r_vpk_x = *r_vpk.coordinates().unwrap().x();
2131 let r_vpk_y = *r_vpk.coordinates().unwrap().y();
2132
2133 // Shares that sum to total_note_value (conditions 8 + 9).
2134 let shares_u64: [u64; 16] = [625; 16];
2135
2136 // Condition 11: real El Gamal encryption.
2137 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
2138 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
2139 encrypt_shares(shares_u64, ea_pk_point);
2140
2141 let mut circuit = Circuit::with_van_witnesses(
2142 Value::known(auth_path),
2143 Value::known(position),
2144 Value::known(vpk_g_d_affine),
2145 Value::known(vpk_pk_d_affine),
2146 Value::known(total_note_value),
2147 Value::known(proposal_authority_old),
2148 Value::known(van_comm_rand),
2149 Value::known(vote_authority_note_old),
2150 Value::known(vsk),
2151 Value::known(rivk_v),
2152 Value::known(wrong_vsk_nk),
2153 Value::known(alpha_v),
2154 );
2155 circuit.one_shifted = Value::known(one_shifted);
2156 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
2157 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
2158 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
2159 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
2160 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
2161 circuit.share_blinds = share_blinds.map(Value::known);
2162 circuit.share_randomness = randomness.map(Value::known);
2163 circuit.ea_pk = Value::known(ea_pk_affine);
2164 let vc = set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
2165
2166 let instance = Instance::from_parts(
2167 van_nullifier,
2168 r_vpk_x,
2169 r_vpk_y,
2170 vote_authority_note_new,
2171 vc,
2172 vote_comm_tree_root,
2173 pallas::Base::zero(),
2174 pallas::Base::from(proposal_id),
2175 voting_round_id,
2176 *ea_pk_affine.coordinates().unwrap().x(),
2177 *ea_pk_affine.coordinates().unwrap().y(),
2178 );
2179
2180 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2181 // Should fail: circuit computes Poseidon(wrong_vsk_nk, inner_hash)
2182 // which ≠ the instance van_nullifier (computed with correct vsk_nk).
2183 // Also fails condition 3 since wrong_vsk_nk breaks CommitIvk derivation.
2184 assert!(prover.verify().is_err());
2185 }
2186
2187 /// Verifies the out-of-circuit nullifier helper produces deterministic results.
2188 #[test]
2189 fn van_nullifier_hash_deterministic() {
2190 let mut rng = OsRng;
2191
2192 let nk = pallas::Base::random(&mut rng);
2193 let round = pallas::Base::random(&mut rng);
2194 let van = pallas::Base::random(&mut rng);
2195
2196 let h1 = van_nullifier_hash(nk, round, van);
2197 let h2 = van_nullifier_hash(nk, round, van);
2198 assert_eq!(h1, h2);
2199
2200 // Changing any input changes the hash.
2201 let h3 = van_nullifier_hash(pallas::Base::random(&mut rng), round, van);
2202 assert_ne!(h1, h3);
2203 }
2204
2205 /// Verifies the domain tag is non-zero and deterministic.
2206 #[test]
2207 fn domain_van_nullifier_deterministic() {
2208 let d1 = domain_van_nullifier();
2209 let d2 = domain_van_nullifier();
2210 assert_eq!(d1, d2);
2211
2212 // Must differ from DOMAIN_VAN (which is 0).
2213 assert_ne!(d1, pallas::Base::zero());
2214 }
2215
2216 // ================================================================
2217 // Condition 6 (Proposal Authority Decrement) tests
2218 // ================================================================
2219
2220 /// Proposal authority with only bit 0 set (value 1): vote on proposal 0, new = 0.
2221 #[test]
2222 fn proposal_authority_decrement_minimum_valid() {
2223 // proposal_id = 0 is now forbidden (sentinel value); use the next smallest valid id.
2224 // Authority = 2 = 0b0010 has exactly bit 1 set, so proposal_id = 1 is valid.
2225 // After decrement: proposal_authority_new = 0 (minimum possible outcome).
2226 let (circuit, instance) =
2227 make_test_data_with_authority_and_proposal(pallas::Base::from(2u64), 1);
2228
2229 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2230 assert_eq!(prover.verify(), Ok(()));
2231 }
2232
2233 /// With proposal_authority_old = 0, the selected bit is 0 so the
2234 /// "run_selected = 1" constraint (selected bit was set) fails.
2235 #[test]
2236 fn proposal_authority_zero_fails() {
2237 let (circuit, instance) = make_test_data_with_authority(pallas::Base::zero());
2238
2239 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2240
2241 assert!(prover.verify().is_err());
2242 }
2243
2244 /// proposal_id = 0 is the dummy sentinel value and must be rejected (Cond 6, gate).
2245 #[test]
2246 fn proposal_id_zero_fails() {
2247 // Authority = 1 = 0b0001 has bit 0 set, so this is otherwise a structurally
2248 // valid decrement — the only reason it must fail is the non-zero gate.
2249 let (circuit, instance) =
2250 make_test_data_with_authority_and_proposal(pallas::Base::one(), 0);
2251
2252 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2253 assert!(prover.verify().is_err(), "proposal_id = 0 must be rejected");
2254 }
2255
2256 /// Full authority (65535), proposal_id 1 → new = 65533 (e2e scenario).
2257 #[test]
2258 fn proposal_authority_full_authority_proposal_1_passes() {
2259 const MAX_PROPOSAL_AUTHORITY: u64 = 65535;
2260 let (circuit, instance) = make_test_data_with_authority_and_proposal(
2261 pallas::Base::from(MAX_PROPOSAL_AUTHORITY),
2262 1,
2263 );
2264
2265 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2266 assert_eq!(prover.verify(), Ok(()));
2267 }
2268
2269 /// Wrong vote_authority_note_new (e.g. not clearing the bit) fails condition 6.
2270 #[test]
2271 fn proposal_authority_wrong_new_fails() {
2272 let (circuit, mut instance) =
2273 make_test_data_with_authority_and_proposal(pallas::Base::from(65535u64), 1);
2274
2275 instance.vote_authority_note_new = pallas::Base::random(&mut OsRng);
2276
2277 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2278 assert!(prover.verify().is_err());
2279 }
2280
2281 /// authority=4 (0b0100, bit 2 set only), proposal_id=1 (bit 1 absent) →
2282 /// run_selected=0 at the terminal row, so "run_selected = 1" fails.
2283 /// Uses proposal_id=1 (not 0) to isolate this constraint from the
2284 /// proposal_id != 0 sentinel gate.
2285 #[test]
2286 fn proposal_authority_bit_not_set_fails() {
2287 let (circuit, instance) =
2288 make_test_data_with_authority_and_proposal(pallas::Base::from(4u64), 1);
2289
2290 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2291 assert!(prover.verify().is_err());
2292 }
2293
2294 /// Condition 6 enforces run_sel = 1 (exactly one selector active) at the last bit row;
2295 /// see CONDITION_6_RUN_SEL_FIX.md. This test runs a valid proof (one selector) and
2296 /// verifies it passes; a zero-selector witness would be rejected by that gate.
2297 #[test]
2298 fn proposal_authority_condition6_run_sel_constraint() {
2299 let (circuit, instance) =
2300 make_test_data_with_authority_and_proposal(pallas::Base::from(3u64), 1);
2301
2302 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2303 assert_eq!(prover.verify(), Ok(()));
2304 }
2305
2306 /// proposal_authority_old = 65536 = 2^16 lies outside the valid 16-bit bitmask
2307 /// range [0, 65535]. The authority_decrement gadget decomposes the value into
2308 /// exactly 16 bits (positions 0–15); a value with bit 16 set cannot be represented
2309 /// in that decomposition and must be rejected by the range check.
2310 #[test]
2311 fn proposal_authority_exceeds_16_bits_fails() {
2312 // 65536 = 2^16 is the first value not representable as a 16-bit bitmask.
2313 let (circuit, instance) =
2314 make_test_data_with_authority(pallas::Base::from(65536u64));
2315 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2316 assert!(
2317 prover.verify().is_err(),
2318 "authority > 65535 must be rejected by the 16-bit bit decomposition"
2319 );
2320 }
2321
2322 // ================================================================
2323 // Condition 7 (New VAN Integrity) tests
2324 // ================================================================
2325
2326 /// Wrong vote_authority_note_new public input should fail condition 7.
2327 #[test]
2328 fn new_van_integrity_wrong_public_input_fails() {
2329 let (circuit, mut instance) = make_test_data();
2330
2331 // Corrupt the new VAN public input.
2332 instance.vote_authority_note_new = pallas::Base::random(&mut OsRng);
2333
2334 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2335
2336 // Should fail: circuit-derived new VAN ≠ corrupted instance value.
2337 assert!(prover.verify().is_err());
2338 }
2339
2340 /// New VAN integrity with a large (but valid) 16-bit proposal authority.
2341 /// Authority 0xFFF8 has bits 3..15 set; voting on proposal 3 gives new = 0xFFF0.
2342 #[test]
2343 fn new_van_integrity_large_authority() {
2344 let (circuit, instance) =
2345 make_test_data_with_authority(pallas::Base::from(0xFFF8u64));
2346
2347 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2348 assert_eq!(prover.verify(), Ok(()));
2349 }
2350
2351 // ================================================================
2352 // Condition 1 (VAN Membership) tests
2353 // ================================================================
2354
2355 /// Wrong vote_comm_tree_root in the instance should fail condition 1.
2356 #[test]
2357 fn van_membership_wrong_root_fails() {
2358 let (circuit, mut instance) = make_test_data();
2359
2360 // Corrupt the tree root.
2361 instance.vote_comm_tree_root = pallas::Base::random(&mut OsRng);
2362
2363 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2364 assert!(prover.verify().is_err());
2365 }
2366
2367 /// A VAN at a non-zero position in the tree should verify.
2368 #[test]
2369 fn van_membership_nonzero_position() {
2370 let mut rng = OsRng;
2371
2372 // Derive proper voting key hierarchy.
2373 let vsk = pallas::Scalar::random(&mut rng);
2374 let vsk_nk = pallas::Base::random(&mut rng);
2375 let rivk_v = pallas::Scalar::random(&mut rng);
2376 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
2377 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
2378 let vpk_pk_d_x = *vpk_pk_d_affine.coordinates().unwrap().x();
2379
2380 let total_note_value = pallas::Base::from(10_000u64);
2381 let voting_round_id = pallas::Base::random(&mut rng);
2382 let proposal_authority_old = pallas::Base::from(5u64); // bits 0 and 2 set
2383 // proposal_id = 0 is now forbidden (sentinel); use proposal_id = 2 (bit 2 is set in 5).
2384 let proposal_id = 2u64;
2385 let van_comm_rand = pallas::Base::random(&mut rng);
2386
2387 let vote_authority_note_old = van_integrity_hash(
2388 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
2389 proposal_authority_old, van_comm_rand,
2390 );
2391
2392 // Place the leaf at position 7 (binary: ...0111).
2393 let position: u32 = 7;
2394 let mut empty_roots = [pallas::Base::zero(); VOTE_COMM_TREE_DEPTH];
2395 empty_roots[0] = poseidon_hash_2(pallas::Base::zero(), pallas::Base::zero());
2396 for i in 1..VOTE_COMM_TREE_DEPTH {
2397 empty_roots[i] = poseidon_hash_2(empty_roots[i - 1], empty_roots[i - 1]);
2398 }
2399 let auth_path = empty_roots;
2400 let mut current = vote_authority_note_old;
2401 for i in 0..VOTE_COMM_TREE_DEPTH {
2402 if (position >> i) & 1 == 0 {
2403 current = poseidon_hash_2(current, auth_path[i]);
2404 } else {
2405 current = poseidon_hash_2(auth_path[i], current);
2406 }
2407 }
2408 let vote_comm_tree_root = current;
2409
2410 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
2411 let one_shifted = pallas::Base::from(1u64 << proposal_id);
2412 let proposal_authority_new = proposal_authority_old - one_shifted;
2413 let vote_authority_note_new = van_integrity_hash(
2414 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
2415 proposal_authority_new, van_comm_rand,
2416 );
2417
2418 let alpha_v = pallas::Scalar::random(&mut rng);
2419 let g = pallas::Point::from(spend_auth_g_affine());
2420 let r_vpk = (g * vsk + g * alpha_v).to_affine();
2421 let r_vpk_x = *r_vpk.coordinates().unwrap().x();
2422 let r_vpk_y = *r_vpk.coordinates().unwrap().y();
2423
2424 // Shares that sum to total_note_value (conditions 8 + 9).
2425 let shares_u64: [u64; 16] = [625; 16];
2426
2427 // Condition 11: real El Gamal encryption.
2428 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
2429 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
2430 encrypt_shares(shares_u64, ea_pk_point);
2431
2432 let mut circuit = Circuit::with_van_witnesses(
2433 Value::known(auth_path),
2434 Value::known(position),
2435 Value::known(vpk_g_d_affine),
2436 Value::known(vpk_pk_d_affine),
2437 Value::known(total_note_value),
2438 Value::known(proposal_authority_old),
2439 Value::known(van_comm_rand),
2440 Value::known(vote_authority_note_old),
2441 Value::known(vsk),
2442 Value::known(rivk_v),
2443 Value::known(vsk_nk),
2444 Value::known(alpha_v),
2445 );
2446 circuit.one_shifted = Value::known(one_shifted);
2447 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
2448 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
2449 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
2450 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
2451 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
2452 circuit.share_blinds = share_blinds.map(Value::known);
2453 circuit.share_randomness = randomness.map(Value::known);
2454 circuit.ea_pk = Value::known(ea_pk_affine);
2455 let vc = set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
2456
2457 let instance = Instance::from_parts(
2458 van_nullifier,
2459 r_vpk_x,
2460 r_vpk_y,
2461 vote_authority_note_new,
2462 vc,
2463 vote_comm_tree_root,
2464 pallas::Base::zero(),
2465 pallas::Base::from(proposal_id),
2466 voting_round_id,
2467 *ea_pk_affine.coordinates().unwrap().x(),
2468 *ea_pk_affine.coordinates().unwrap().y(),
2469 );
2470
2471 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2472 assert_eq!(prover.verify(), Ok(()));
2473 }
2474
2475 /// Poseidon hash-2 helper is deterministic.
2476 #[test]
2477 fn poseidon_hash_2_deterministic() {
2478 let mut rng = OsRng;
2479 let a = pallas::Base::random(&mut rng);
2480 let b = pallas::Base::random(&mut rng);
2481
2482 assert_eq!(poseidon_hash_2(a, b), poseidon_hash_2(a, b));
2483 // Non-commutative.
2484 assert_ne!(poseidon_hash_2(a, b), poseidon_hash_2(b, a));
2485 }
2486
2487 // ================================================================
2488 // Condition 8 (Shares Sum Correctness) tests
2489 // ================================================================
2490
2491 /// Shares that do NOT sum to total_note_value should fail condition 8.
2492 #[test]
2493 fn shares_sum_wrong_total_fails() {
2494 let (mut circuit, instance) = make_test_data();
2495
2496 // Corrupt shares[3] so the sum no longer equals total_note_value.
2497 // Use a small value that still passes condition 9's range check,
2498 // isolating the condition 8 failure.
2499 circuit.shares[3] = Value::known(pallas::Base::from(999u64));
2500
2501 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2502 // Should fail: shares sum ≠ total_note_value.
2503 assert!(prover.verify().is_err());
2504 }
2505
2506 // ================================================================
2507 // Condition 9 (Shares Range) tests
2508 // ================================================================
2509
2510 /// A share at the maximum valid value (2^30 - 1) should pass.
2511 #[test]
2512 fn shares_range_max_valid() {
2513 let max_share = pallas::Base::from((1u64 << 30) - 1); // 1,073,741,823
2514 let total = (0..16).fold(pallas::Base::zero(), |acc, _| acc + max_share);
2515
2516 let mut rng = OsRng;
2517 // Derive proper voting key hierarchy.
2518 let vsk = pallas::Scalar::random(&mut rng);
2519 let vsk_nk = pallas::Base::random(&mut rng);
2520 let rivk_v = pallas::Scalar::random(&mut rng);
2521 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
2522 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
2523 let vpk_pk_d_x = *vpk_pk_d_affine.coordinates().unwrap().x();
2524
2525 let voting_round_id = pallas::Base::random(&mut rng);
2526 let proposal_authority_old = pallas::Base::from(5u64); // bits 0 and 2 set
2527 // proposal_id = 0 is now forbidden (sentinel); use proposal_id = 2 (bit 2 is set in 5).
2528 let proposal_id = 2u64;
2529 let van_comm_rand = pallas::Base::random(&mut rng);
2530
2531 let vote_authority_note_old = van_integrity_hash(
2532 vpk_g_d_x, vpk_pk_d_x, total, voting_round_id,
2533 proposal_authority_old, van_comm_rand,
2534 );
2535 let (auth_path, position, vote_comm_tree_root) =
2536 build_single_leaf_merkle_path(vote_authority_note_old);
2537 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
2538 let one_shifted = pallas::Base::from(1u64 << proposal_id);
2539 let proposal_authority_new = proposal_authority_old - one_shifted;
2540 let vote_authority_note_new = van_integrity_hash(
2541 vpk_g_d_x, vpk_pk_d_x, total, voting_round_id,
2542 proposal_authority_new, van_comm_rand,
2543 );
2544
2545 // Condition 11: real El Gamal encryption with max-value shares.
2546 let max_share_u64 = (1u64 << 30) - 1;
2547 let shares_u64: [u64; 16] = [max_share_u64; 16];
2548 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
2549 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
2550 encrypt_shares(shares_u64, ea_pk_point);
2551
2552 let alpha_v = pallas::Scalar::random(&mut rng);
2553 let g = pallas::Point::from(spend_auth_g_affine());
2554 let r_vpk = (g * vsk + g * alpha_v).to_affine();
2555 let r_vpk_x = *r_vpk.coordinates().unwrap().x();
2556 let r_vpk_y = *r_vpk.coordinates().unwrap().y();
2557
2558 let mut circuit = Circuit::with_van_witnesses(
2559 Value::known(auth_path),
2560 Value::known(position),
2561 Value::known(vpk_g_d_affine),
2562 Value::known(vpk_pk_d_affine),
2563 Value::known(total),
2564 Value::known(proposal_authority_old),
2565 Value::known(van_comm_rand),
2566 Value::known(vote_authority_note_old),
2567 Value::known(vsk),
2568 Value::known(rivk_v),
2569 Value::known(vsk_nk),
2570 Value::known(alpha_v),
2571 );
2572 circuit.one_shifted = Value::known(one_shifted);
2573 circuit.shares = [Value::known(max_share); 16];
2574 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
2575 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
2576 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
2577 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
2578 circuit.share_blinds = share_blinds.map(Value::known);
2579 circuit.share_randomness = randomness.map(Value::known);
2580 circuit.ea_pk = Value::known(ea_pk_affine);
2581 let vc = set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
2582
2583 let instance = Instance::from_parts(
2584 van_nullifier,
2585 r_vpk_x,
2586 r_vpk_y,
2587 vote_authority_note_new,
2588 vc,
2589 vote_comm_tree_root,
2590 pallas::Base::zero(),
2591 pallas::Base::from(proposal_id),
2592 voting_round_id,
2593 *ea_pk_affine.coordinates().unwrap().x(),
2594 *ea_pk_affine.coordinates().unwrap().y(),
2595 );
2596
2597 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2598 assert_eq!(prover.verify(), Ok(()));
2599 }
2600
2601 /// A share at exactly 2^30 should fail the range check.
2602 #[test]
2603 fn shares_range_overflow_fails() {
2604 let (mut circuit, instance) = make_test_data();
2605
2606 // Set share_0 to 2^30 (one above the max valid value).
2607 // This will fail condition 9 AND condition 8 (sum mismatch),
2608 // but the important thing is the circuit rejects it.
2609 circuit.shares[0] = Value::known(pallas::Base::from(1u64 << 30));
2610
2611 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2612 assert!(prover.verify().is_err());
2613 }
2614
2615 /// A share that is a large field element (simulating underflow
2616 /// from subtraction) should fail the range check.
2617 #[test]
2618 fn shares_range_field_wrap_fails() {
2619 let (mut circuit, instance) = make_test_data();
2620
2621 // Set share_0 to p - 1 (a wrapped negative value).
2622 // The 10-bit decomposition will produce a huge residual.
2623 circuit.shares[0] = Value::known(-pallas::Base::one());
2624
2625 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2626 assert!(prover.verify().is_err());
2627 }
2628
2629 /// Shares that sum correctly to total_note_value but with shares[0] = 2^30
2630 /// (one above the per-share maximum). Condition 8 (sum check) passes because
2631 /// total_note_value is set to match the sum. Condition 9 (range check) must
2632 /// still reject the individual overflow, confirming it checks each share
2633 /// independently — a correct sum does not bypass the per-share range gate.
2634 #[test]
2635 fn shares_range_single_overflow_correct_sum_fails() {
2636 let mut rng = OsRng;
2637
2638 let overflow_share = pallas::Base::from(1u64 << 30); // 2^30 — just above [0, 2^30)
2639 let normal_share_u64 = 625u64;
2640 // total_note_value = 2^30 + 15 * 625 so sum(shares) == total_note_value.
2641 let total_note_value = overflow_share + pallas::Base::from(15u64 * normal_share_u64);
2642
2643 let vsk = pallas::Scalar::random(&mut rng);
2644 let vsk_nk = pallas::Base::random(&mut rng);
2645 let rivk_v = pallas::Scalar::random(&mut rng);
2646 let alpha_v = pallas::Scalar::random(&mut rng);
2647 let (vpk_g_d_affine, vpk_pk_d_affine) = derive_voting_address(vsk, vsk_nk, rivk_v);
2648 let vpk_g_d_x = *vpk_g_d_affine.coordinates().unwrap().x();
2649 let vpk_pk_d_x = *vpk_pk_d_affine.coordinates().unwrap().x();
2650
2651 let voting_round_id = pallas::Base::random(&mut rng);
2652 let proposal_authority_old = pallas::Base::from(13u64); // bit 3 set
2653 let proposal_id = TEST_PROPOSAL_ID;
2654 let van_comm_rand = pallas::Base::random(&mut rng);
2655
2656 let vote_authority_note_old = van_integrity_hash(
2657 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
2658 proposal_authority_old, van_comm_rand,
2659 );
2660 let (auth_path, position, vote_comm_tree_root) =
2661 build_single_leaf_merkle_path(vote_authority_note_old);
2662 let van_nullifier = van_nullifier_hash(vsk_nk, voting_round_id, vote_authority_note_old);
2663 let one_shifted = pallas::Base::from(1u64 << proposal_id);
2664 let proposal_authority_new = proposal_authority_old - one_shifted;
2665 let vote_authority_note_new = van_integrity_hash(
2666 vpk_g_d_x, vpk_pk_d_x, total_note_value, voting_round_id,
2667 proposal_authority_new, van_comm_rand,
2668 );
2669
2670 // shares[0] overflows (2^30); shares[1..16] are valid (625 each).
2671 // The encryption is computed with these exact values so condition 11 is consistent.
2672 let shares_u64: [u64; 16] = {
2673 let mut arr = [normal_share_u64; 16];
2674 arr[0] = 1u64 << 30;
2675 arr
2676 };
2677 let (_ea_sk, ea_pk_point, ea_pk_affine) = generate_ea_keypair();
2678 let (enc_c1_x, enc_c2_x, enc_c1_y, enc_c2_y, randomness, share_blinds, shares_hash_val) =
2679 encrypt_shares(shares_u64, ea_pk_point);
2680
2681 let g = pallas::Point::from(spend_auth_g_affine());
2682 let r_vpk = (g * vsk + g * alpha_v).to_affine();
2683
2684 let mut circuit = Circuit::with_van_witnesses(
2685 Value::known(auth_path),
2686 Value::known(position),
2687 Value::known(vpk_g_d_affine),
2688 Value::known(vpk_pk_d_affine),
2689 Value::known(total_note_value),
2690 Value::known(proposal_authority_old),
2691 Value::known(van_comm_rand),
2692 Value::known(vote_authority_note_old),
2693 Value::known(vsk),
2694 Value::known(rivk_v),
2695 Value::known(vsk_nk),
2696 Value::known(alpha_v),
2697 );
2698 circuit.one_shifted = Value::known(one_shifted);
2699 circuit.shares = shares_u64.map(|s| Value::known(pallas::Base::from(s)));
2700 circuit.enc_share_c1_x = enc_c1_x.map(Value::known);
2701 circuit.enc_share_c2_x = enc_c2_x.map(Value::known);
2702 circuit.enc_share_c1_y = enc_c1_y.map(Value::known);
2703 circuit.enc_share_c2_y = enc_c2_y.map(Value::known);
2704 circuit.share_blinds = share_blinds.map(Value::known);
2705 circuit.share_randomness = randomness.map(Value::known);
2706 circuit.ea_pk = Value::known(ea_pk_affine);
2707
2708 let vote_commitment =
2709 set_condition_11(&mut circuit, shares_hash_val, proposal_id, voting_round_id);
2710
2711 let instance = Instance::from_parts(
2712 van_nullifier,
2713 *r_vpk.coordinates().unwrap().x(),
2714 *r_vpk.coordinates().unwrap().y(),
2715 vote_authority_note_new,
2716 vote_commitment,
2717 vote_comm_tree_root,
2718 pallas::Base::zero(),
2719 pallas::Base::from(proposal_id),
2720 voting_round_id,
2721 *ea_pk_affine.coordinates().unwrap().x(),
2722 *ea_pk_affine.coordinates().unwrap().y(),
2723 );
2724
2725 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2726 // Condition 8 (sum check) passes: shares sum to total_note_value.
2727 // Condition 9 (range check) must reject shares[0] = 2^30 regardless.
2728 assert!(
2729 prover.verify().is_err(),
2730 "range check must reject a share equal to 2^30 even when the total sum is correct"
2731 );
2732 }
2733
2734 // ================================================================
2735 // Condition 10 (Shares Hash Integrity) tests
2736 // ================================================================
2737
2738 /// Valid enc_share witnesses with matching shares_hash should pass.
2739 #[test]
2740 fn shares_hash_valid_proof() {
2741 let (circuit, instance) = make_test_data();
2742
2743 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2744 assert_eq!(prover.verify(), Ok(()));
2745 }
2746
2747 /// A corrupted enc_share_c1_x[0] should cause condition 10 failure:
2748 /// the in-circuit hash won't match the VOTE_COMMITMENT instance.
2749 #[test]
2750 fn shares_hash_wrong_enc_share_fails() {
2751 let (mut circuit, instance) = make_test_data();
2752
2753 // Corrupt one enc_share component — the Poseidon hash will
2754 // change, so it won't match the instance's vote_commitment.
2755 circuit.enc_share_c1_x[0] = Value::known(pallas::Base::random(&mut OsRng));
2756
2757 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2758 assert!(prover.verify().is_err());
2759 }
2760
2761 /// A wrong vote_commitment instance value (shares_hash mismatch)
2762 /// should fail, even with correct enc_share witnesses.
2763 #[test]
2764 fn shares_hash_wrong_instance_fails() {
2765 let (circuit, mut instance) = make_test_data();
2766
2767 // Supply a random (wrong) vote_commitment in the instance.
2768 instance.vote_commitment = pallas::Base::random(&mut OsRng);
2769
2770 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2771 assert!(prover.verify().is_err());
2772 }
2773
2774 /// Verifies the out-of-circuit shares_hash helper is deterministic.
2775 #[test]
2776 fn shares_hash_deterministic() {
2777 let mut rng = OsRng;
2778
2779 let blinds: [pallas::Base; 16] =
2780 core::array::from_fn(|_| pallas::Base::random(&mut rng));
2781 let c1_x: [pallas::Base; 16] =
2782 core::array::from_fn(|_| pallas::Base::random(&mut rng));
2783 let c2_x: [pallas::Base; 16] =
2784 core::array::from_fn(|_| pallas::Base::random(&mut rng));
2785 let c1_y: [pallas::Base; 16] =
2786 core::array::from_fn(|_| pallas::Base::random(&mut rng));
2787 let c2_y: [pallas::Base; 16] =
2788 core::array::from_fn(|_| pallas::Base::random(&mut rng));
2789
2790 let h1 = shares_hash(blinds, c1_x, c2_x, c1_y, c2_y);
2791 let h2 = shares_hash(blinds, c1_x, c2_x, c1_y, c2_y);
2792 assert_eq!(h1, h2);
2793
2794 // Changing any component changes the hash.
2795 let mut c1_x_alt = c1_x;
2796 c1_x_alt[2] = pallas::Base::random(&mut rng);
2797 let h3 = shares_hash(blinds, c1_x_alt, c2_x, c1_y, c2_y);
2798 assert_ne!(h1, h3);
2799
2800 // Swapping c1 and c2 also changes the hash.
2801 let h4 = shares_hash(blinds, c2_x, c1_x, c2_y, c1_y);
2802 assert_ne!(h1, h4);
2803
2804 // Different blinds produce different hash.
2805 let blinds_alt: [pallas::Base; 16] =
2806 core::array::from_fn(|_| pallas::Base::random(&mut rng));
2807 let h5 = shares_hash(blinds_alt, c1_x, c2_x, c1_y, c2_y);
2808 assert_ne!(h1, h5);
2809 }
2810
2811 /// Verifies the out-of-circuit share_commitment helper is deterministic
2812 /// and that input order matters (Poseidon(blind, c1_x, c2_x, c1_y, c2_y) ≠
2813 /// Poseidon(blind, c2_x, c1_x, c2_y, c1_y)).
2814 #[test]
2815 fn share_commitment_deterministic() {
2816 let mut rng = OsRng;
2817 let blind = pallas::Base::random(&mut rng);
2818 let c1_x = pallas::Base::random(&mut rng);
2819 let c2_x = pallas::Base::random(&mut rng);
2820 let c1_y = pallas::Base::random(&mut rng);
2821 let c2_y = pallas::Base::random(&mut rng);
2822
2823 let h1 = share_commitment(blind, c1_x, c2_x, c1_y, c2_y);
2824 let h2 = share_commitment(blind, c1_x, c2_x, c1_y, c2_y);
2825 assert_eq!(h1, h2);
2826
2827 // Swapping c1 and c2 changes the hash.
2828 let h3 = share_commitment(blind, c2_x, c1_x, c2_y, c1_y);
2829 assert_ne!(h1, h3);
2830
2831 // Different blind changes the hash.
2832 let blind_alt = pallas::Base::random(&mut rng);
2833 let h4 = share_commitment(blind_alt, c1_x, c2_x, c1_y, c2_y);
2834 assert_ne!(h1, h4);
2835 }
2836
2837 /// Minimal circuit that computes one share commitment in-circuit and constrains
2838 /// the result to the instance column. Used to verify the in-circuit hash matches
2839 /// the native share_commitment.
2840 #[derive(Clone, Default)]
2841 struct ShareCommitmentTestCircuit {
2842 blind: pallas::Base,
2843 c1_x: pallas::Base,
2844 c2_x: pallas::Base,
2845 c1_y: pallas::Base,
2846 c2_y: pallas::Base,
2847 }
2848
2849 #[derive(Clone)]
2850 struct ShareCommitmentTestConfig {
2851 primary: Column<InstanceColumn>,
2852 advices: [Column<Advice>; 5],
2853 poseidon_config: PoseidonConfig<pallas::Base, 3, 2>,
2854 }
2855
2856 impl plonk::Circuit<pallas::Base> for ShareCommitmentTestCircuit {
2857 type Config = ShareCommitmentTestConfig;
2858 type FloorPlanner = floor_planner::V1;
2859
2860 fn without_witnesses(&self) -> Self {
2861 Self::default()
2862 }
2863
2864 fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
2865 let primary = meta.instance_column();
2866 meta.enable_equality(primary);
2867 let advices: [Column<Advice>; 5] = core::array::from_fn(|_| meta.advice_column());
2868 for col in &advices {
2869 meta.enable_equality(*col);
2870 }
2871 let fixed: [Column<Fixed>; 6] = core::array::from_fn(|_| meta.fixed_column());
2872 let constants = meta.fixed_column();
2873 meta.enable_constant(constants);
2874 let rc_a = fixed[0..3].try_into().unwrap();
2875 let rc_b = fixed[3..6].try_into().unwrap();
2876 let poseidon_config = PoseidonChip::configure::<poseidon::P128Pow5T3>(
2877 meta,
2878 advices[1..4].try_into().unwrap(),
2879 advices[4],
2880 rc_a,
2881 rc_b,
2882 );
2883 ShareCommitmentTestConfig {
2884 primary,
2885 advices,
2886 poseidon_config,
2887 }
2888 }
2889
2890 fn synthesize(
2891 &self,
2892 config: Self::Config,
2893 mut layouter: impl Layouter<pallas::Base>,
2894 ) -> Result<(), plonk::Error> {
2895 let blind_cell = assign_free_advice(
2896 layouter.namespace(|| "blind"),
2897 config.advices[0],
2898 Value::known(self.blind),
2899 )?;
2900 let c1_x_cell = assign_free_advice(
2901 layouter.namespace(|| "c1_x"),
2902 config.advices[0],
2903 Value::known(self.c1_x),
2904 )?;
2905 let c2_x_cell = assign_free_advice(
2906 layouter.namespace(|| "c2_x"),
2907 config.advices[0],
2908 Value::known(self.c2_x),
2909 )?;
2910 let c1_y_cell = assign_free_advice(
2911 layouter.namespace(|| "c1_y"),
2912 config.advices[0],
2913 Value::known(self.c1_y),
2914 )?;
2915 let c2_y_cell = assign_free_advice(
2916 layouter.namespace(|| "c2_y"),
2917 config.advices[0],
2918 Value::known(self.c2_y),
2919 )?;
2920 let chip = PoseidonChip::construct(config.poseidon_config.clone());
2921 let result = hash_share_commitment_in_circuit(
2922 chip,
2923 layouter.namespace(|| "share_comm"),
2924 blind_cell,
2925 c1_x_cell,
2926 c2_x_cell,
2927 c1_y_cell,
2928 c2_y_cell,
2929 0,
2930 )?;
2931 layouter.constrain_instance(result.cell(), config.primary, 0)?;
2932 Ok(())
2933 }
2934 }
2935
2936 /// Verifies that the in-circuit share commitment hash matches the native
2937 /// share_commitment(blind, c1_x, c2_x, c1_y, c2_y). The test builds a minimal circuit
2938 /// that computes the hash and constrains it to the instance column, then
2939 /// runs MockProver with the native hash as the public input.
2940 #[test]
2941 fn hash_share_commitment_in_circuit_matches_native() {
2942 let mut rng = OsRng;
2943 let blind = pallas::Base::random(&mut rng);
2944 let c1_x = pallas::Base::random(&mut rng);
2945 let c2_x = pallas::Base::random(&mut rng);
2946 let c1_y = pallas::Base::random(&mut rng);
2947 let c2_y = pallas::Base::random(&mut rng);
2948
2949 let expected = share_commitment(blind, c1_x, c2_x, c1_y, c2_y);
2950 let circuit = ShareCommitmentTestCircuit {
2951 blind,
2952 c1_x,
2953 c2_x,
2954 c1_y,
2955 c2_y,
2956 };
2957 let instance = vec![vec![expected]];
2958 // K=10 (1024 rows) is enough for one Poseidon(3) region.
2959 const TEST_K: u32 = 10;
2960 let prover =
2961 MockProver::run(TEST_K, &circuit, instance).expect("MockProver::run failed");
2962 assert_eq!(prover.verify(), Ok(()));
2963 }
2964
2965 // ================================================================
2966 // Condition 11 (Encryption Integrity) tests
2967 // ================================================================
2968
2969 /// Valid El Gamal encryptions should produce a valid proof.
2970 #[test]
2971 fn encryption_integrity_valid_proof() {
2972 let (circuit, instance) = make_test_data();
2973
2974 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2975 assert_eq!(prover.verify(), Ok(()));
2976 }
2977
2978 /// A corrupted share_randomness[0] should fail condition 11:
2979 /// the computed C1[0] won't match enc_share_c1_x[0].
2980 #[test]
2981 fn encryption_integrity_wrong_randomness_fails() {
2982 let (mut circuit, instance) = make_test_data();
2983
2984 // Corrupt the randomness for share 0 — C1 will change.
2985 circuit.share_randomness[0] = Value::known(pallas::Base::from(9999u64));
2986
2987 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
2988 assert!(prover.verify().is_err());
2989 }
2990
2991 /// A wrong ea_pk in the instance should fail condition 11:
2992 /// the computed r * ea_pk won't match the ciphertexts.
2993 #[test]
2994 fn encryption_integrity_wrong_ea_pk_instance_fails() {
2995 let (circuit, mut instance) = make_test_data();
2996
2997 // Corrupt ea_pk_x in the instance — the constraint linking
2998 // the witnessed ea_pk to the public input will fail.
2999 instance.ea_pk_x = pallas::Base::from(12345u64);
3000
3001 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3002 assert!(prover.verify().is_err());
3003 }
3004
3005 /// A corrupted share value (plaintext) should fail condition 11:
3006 /// C2_i = [v_i]*G + [r_i]*ea_pk will not match enc_share_c2_x[i].
3007 #[test]
3008 fn encryption_integrity_wrong_share_fails() {
3009 let (mut circuit, instance) = make_test_data();
3010
3011 // Corrupt share 0 — enc_share and randomness are unchanged (from
3012 // make_test_data), so the in-circuit C2_0 will not match enc_c2_x[0].
3013 circuit.shares[0] = Value::known(pallas::Base::from(9999u64));
3014
3015 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3016 assert!(prover.verify().is_err());
3017 }
3018
3019 /// A corrupted enc_share_c2_x witness should cause verification to fail:
3020 /// condition 11 constrains ExtractP(C2_i) == enc_c2_x[i].
3021 #[test]
3022 fn encryption_integrity_wrong_enc_c2_x_fails() {
3023 let (mut circuit, instance) = make_test_data();
3024
3025 // Corrupt one C2 x-coordinate — the ECC will compute the real C2_0
3026 // from share_0 and r_0; constrain_equal will fail (or the resulting
3027 // shares_hash will not match the instance vote_commitment).
3028 circuit.enc_share_c2_x[0] = Value::known(pallas::Base::random(&mut OsRng));
3029
3030 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3031 assert!(prover.verify().is_err());
3032 }
3033
3034 /// The out-of-circuit elgamal_encrypt helper is deterministic.
3035 #[test]
3036 fn elgamal_encrypt_deterministic() {
3037 let (_ea_sk, ea_pk_point, _ea_pk_affine) = generate_ea_keypair();
3038
3039 let v = pallas::Base::from(1000u64);
3040 let r = pallas::Base::from(42u64);
3041
3042 let (c1_a, c2_a, _, _) = elgamal_encrypt(v, r, ea_pk_point);
3043 let (c1_b, c2_b, _, _) = elgamal_encrypt(v, r, ea_pk_point);
3044 assert_eq!(c1_a, c1_b);
3045 assert_eq!(c2_a, c2_b);
3046
3047 // Different randomness → different C1.
3048 let (c1_c, _, _, _) = elgamal_encrypt(v, pallas::Base::from(99u64), ea_pk_point);
3049 assert_ne!(c1_a, c1_c);
3050 }
3051
3052 /// base_to_scalar (used by El Gamal) accepts share-sized values and
3053 /// the fixed randomness used in encrypt_shares.
3054 #[test]
3055 fn base_to_scalar_accepts_elgamal_inputs() {
3056 // Share-sized values (condition 9: [0, 2^30)) must convert.
3057 assert!(base_to_scalar(pallas::Base::zero()).is_some());
3058 assert!(base_to_scalar(pallas::Base::from(1u64)).is_some());
3059 assert!(base_to_scalar(pallas::Base::from(1_000u64)).is_some());
3060 assert!(base_to_scalar(pallas::Base::from(404u64)).is_some()); // encrypt_shares randomness
3061
3062 // encrypt_shares uses (i+1)*101 for i in 0..16 → 101, 202, ..., 1616.
3063 for r in (1u64..=16).map(|i| i * 101) {
3064 assert!(
3065 base_to_scalar(pallas::Base::from(r)).is_some(),
3066 "r = {} must convert for El Gamal",
3067 r
3068 );
3069 }
3070 }
3071
3072 // ================================================================
3073 // Condition 12 (Vote Commitment Integrity) tests
3074 // ================================================================
3075
3076 /// Valid vote commitment (full Poseidon chain) should pass.
3077 #[test]
3078 fn vote_commitment_integrity_valid_proof() {
3079 let (circuit, instance) = make_test_data();
3080
3081 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3082 assert_eq!(prover.verify(), Ok(()));
3083 }
3084
3085 /// A wrong vote_decision in the circuit should fail condition 12:
3086 /// the derived vote_commitment won't match the instance.
3087 #[test]
3088 fn vote_commitment_wrong_decision_fails() {
3089 let (mut circuit, instance) = make_test_data();
3090
3091 // Corrupt the vote decision — the Poseidon hash will change.
3092 circuit.vote_decision = Value::known(pallas::Base::from(99u64));
3093
3094 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3095 assert!(prover.verify().is_err());
3096 }
3097
3098 /// A wrong proposal_id in the instance should fail condition 12:
3099 /// the in-circuit proposal_id (copied from instance) will produce
3100 /// a different vote_commitment.
3101 #[test]
3102 fn vote_commitment_wrong_proposal_id_fails() {
3103 let (circuit, mut instance) = make_test_data();
3104
3105 // Corrupt the proposal_id in the instance.
3106 instance.proposal_id = pallas::Base::from(999u64);
3107
3108 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3109 assert!(prover.verify().is_err());
3110 }
3111
3112 /// A wrong vote_commitment in the instance should fail.
3113 #[test]
3114 fn vote_commitment_wrong_instance_fails() {
3115 let (circuit, mut instance) = make_test_data();
3116
3117 // Corrupt the vote_commitment public input.
3118 instance.vote_commitment = pallas::Base::random(&mut OsRng);
3119
3120 let prover = MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]).unwrap();
3121 assert!(prover.verify().is_err());
3122 }
3123
3124 /// The out-of-circuit vote_commitment_hash helper is deterministic.
3125 #[test]
3126 fn vote_commitment_hash_deterministic() {
3127 let mut rng = OsRng;
3128
3129 let rid = pallas::Base::random(&mut rng);
3130 let sh = pallas::Base::random(&mut rng);
3131 let pid = pallas::Base::from(5u64);
3132 let dec = pallas::Base::from(1u64);
3133
3134 let h1 = vote_commitment_hash(rid, sh, pid, dec);
3135 let h2 = vote_commitment_hash(rid, sh, pid, dec);
3136 assert_eq!(h1, h2);
3137
3138 // Changing any input changes the hash.
3139 let h3 = vote_commitment_hash(rid, sh, pallas::Base::from(6u64), dec);
3140 assert_ne!(h1, h3);
3141
3142 // Changing voting_round_id changes the hash.
3143 let h4 = vote_commitment_hash(pallas::Base::from(999u64), sh, pid, dec);
3144 assert_ne!(h1, h4);
3145
3146 // DOMAIN_VC ensures separation from VAN hashes.
3147 // (Different arity prevents confusion, but domain tag adds defense-in-depth.)
3148 assert_ne!(h1, pallas::Base::zero());
3149 }
3150
3151 // ================================================================
3152 // Instance and circuit sanity
3153 // ================================================================
3154
3155 /// Instance must serialize to exactly 9 public inputs.
3156 #[test]
3157 fn instance_has_eleven_public_inputs() {
3158 let (_, instance) = make_test_data();
3159 assert_eq!(instance.to_halo2_instance().len(), 11);
3160 }
3161
3162 /// Default circuit (all witnesses unknown) must not produce a valid proof.
3163 #[test]
3164 fn default_circuit_with_valid_instance_fails() {
3165 let (_, instance) = make_test_data();
3166 let circuit = Circuit::default();
3167
3168 match MockProver::run(K, &circuit, vec![instance.to_halo2_instance()]) {
3169 Ok(prover) => assert!(prover.verify().is_err()),
3170 Err(_) => {} // Synthesis failed — acceptable.
3171 }
3172 }
3173
3174 /// Measures actual rows used by the vote-proof circuit via `CircuitCost::measure`.
3175 ///
3176 /// `CircuitCost` runs the floor planner against the circuit and tracks the
3177 /// highest row offset assigned in any column, giving the real "rows consumed"
3178 /// number rather than the theoretical 2^K capacity.
3179 ///
3180 /// Run with:
3181 /// cargo test --features vote-proof row_budget -- --nocapture --ignored
3182 #[test]
3183 #[ignore]
3184 fn row_budget() {
3185 use std::println;
3186 use halo2_proofs::dev::CircuitCost;
3187 use pasta_curves::vesta;
3188
3189 let (circuit, _) = make_test_data();
3190
3191 // CircuitCost::measure runs the floor planner and returns layout statistics.
3192 // Fields are private, so extract them from the Debug representation.
3193 let cost = CircuitCost::<vesta::Point, _>::measure(K, &circuit);
3194 let debug = alloc::format!("{cost:?}");
3195
3196 // Parse max_rows, max_advice_rows, max_fixed_rows from Debug string.
3197 let extract = |field: &str| -> usize {
3198 let prefix = alloc::format!("{field}: ");
3199 debug.split(&prefix)
3200 .nth(1)
3201 .and_then(|s| s.split([',', ' ', '}']).next())
3202 .and_then(|n| n.parse().ok())
3203 .unwrap_or(0)
3204 };
3205
3206 let max_rows = extract("max_rows");
3207 let max_advice_rows = extract("max_advice_rows");
3208 let max_fixed_rows = extract("max_fixed_rows");
3209 let total_available = 1usize << K;
3210
3211 println!("=== vote-proof circuit row budget (K={K}) ===");
3212 println!(" max_rows (floor-planner high-water mark): {max_rows}");
3213 println!(" max_advice_rows: {max_advice_rows}");
3214 println!(" max_fixed_rows: {max_fixed_rows}");
3215 println!(" 2^K (total available rows): {total_available}");
3216 println!(" headroom: {}", total_available.saturating_sub(max_rows));
3217 println!(" utilisation: {:.1}%",
3218 100.0 * max_rows as f64 / total_available as f64);
3219 println!();
3220 println!(" Full debug: {debug}");
3221
3222 // ---------------------------------------------------------------
3223 // Witness-independence check: Circuit::default() (all unknowns)
3224 // must produce exactly the same layout as the filled circuit.
3225 // If these differ, the row count depends on witness values and
3226 // the measurement above cannot be trusted as a production bound.
3227 // ---------------------------------------------------------------
3228 let cost_default = CircuitCost::<vesta::Point, _>::measure(K, &Circuit::default());
3229 let debug_default = alloc::format!("{cost_default:?}");
3230 let max_rows_default = debug_default
3231 .split("max_rows: ").nth(1)
3232 .and_then(|s| s.split([',', ' ', '}']).next())
3233 .and_then(|n| n.parse::<usize>().ok())
3234 .unwrap_or(0);
3235 if max_rows_default == max_rows {
3236 println!(" Witness-independence: PASS \
3237 (Circuit::default() max_rows={max_rows_default} == filled max_rows={max_rows})");
3238 } else {
3239 println!(" Witness-independence: FAIL \
3240 (Circuit::default() max_rows={max_rows_default} != filled max_rows={max_rows}) \
3241 — row count depends on witness values!");
3242 }
3243
3244 // ---------------------------------------------------------------
3245 // VOTE_COMM_TREE_DEPTH sanity check: confirm the circuit constant
3246 // matches the canonical value in vote_commitment_tree::TREE_DEPTH
3247 // (24 as of this writing). A mismatch would mean test data uses a
3248 // shallower tree than production.
3249 // ---------------------------------------------------------------
3250 println!(" VOTE_COMM_TREE_DEPTH (circuit constant): {VOTE_COMM_TREE_DEPTH}");
3251
3252 // ---------------------------------------------------------------
3253 // Minimum-K probe: find the smallest K at which MockProver passes.
3254 // Useful for evaluating whether K can be reduced.
3255 // ---------------------------------------------------------------
3256 for probe_k in 11u32..=K {
3257 let (c, inst) = make_test_data();
3258 match MockProver::run(probe_k, &c, vec![inst.to_halo2_instance()]) {
3259 Err(_) => {
3260 println!(" K={probe_k}: not enough rows (synthesizer rejected)");
3261 continue;
3262 }
3263 Ok(p) => match p.verify() {
3264 Ok(()) => {
3265 println!(" Minimum viable K: {probe_k} (2^{probe_k} = {} rows, {:.1}% headroom)",
3266 1usize << probe_k,
3267 100.0 * (1.0 - max_rows as f64 / (1usize << probe_k) as f64));
3268 break;
3269 }
3270 Err(_) => println!(" K={probe_k}: too small"),
3271 },
3272 }
3273 }
3274 }
3275}