aethel-core 0.1.5

Post-Quantum Ephemeral Identifier Engine — Polymorphic Lattice Projection (PLP), SAAP, and 5D Hypercube HTSS routing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
//! # SAAP Selective Attribute Verification Engine
//!
//! This module implements the **Selective Attribute Attestation Protocol (SAAP)**
//! prove/verify engine for Aethel-ID. This is pre-release code with no formal
//! security audit (see the crate README's security notice) — not "production-grade."
//! It also covers a narrower surface than the full SAAP design: `saap_prove`
//! and `verify_saap_proof` operate over an already-parsed credential; issuing
//! one in the first place (BDLOP commitment issuance, an issuer signature) is
//! not implemented here.
//!
//! ## Purpose
//!
//! Verifies SAAP proof transcripts generated by credential holders performing
//! selective attribute disclosure. The verifier checks:
//!
//! 1. **Norm Bound**: Response vector `z` satisfies `∥z∥_∞ < (γ₁ - β)`.
//! 2. **Commitment Reconstruction**: Recomputes `w' = A · z - c · t_attr`.
//! 3. **Challenge Validation**: Verifies Fiat-Shamir challenge consistency.
//!
//! ## Key Structures
//!
//! - [`Polynomial`] — Ring element in R_q = Z_q[X]/(X^256 + 1)
//! - [`VectorK`] — k-dimensional module vector over R_q
//! - [`SaapProof`] — Complete SAAP proof transcript
//! - [`SaapValidationError`] — Typed verification failure reasons
//! - [`AttributePayload`] — Disclosed attribute values
//!
//! ## Domain Separators
//!
//! - Challenge hash: `"AETHEL_SAAP_CHALLENGE_V1"`

use core::sync::atomic::{compiler_fence, Ordering};
use sha3::{Shake256, digest::{Update, ExtendableOutput, XofReader}};
use zeroize::Zeroize;

pub const RING_N: usize = 256;
pub const MODULE_K: usize = 4;
pub const MAX_ATTRIBUTES: usize = 8;
pub const PARAM_Q: i32 = 8_380_417;
pub const PARAM_GAMMA1: i32 = 131_072;
pub const PARAM_BETA: i32 = 78;
pub const REJECTION_BOUND: i32 = PARAM_GAMMA1 - PARAM_BETA;

/// Ring element in R_q = Z_q[X]/(X^256 + 1).
///
/// Used both for public proof data (challenge, commitment) and, as a
/// component of [`VectorK`], for caller-supplied secret key material passed
/// into [`saap_prove`]. Because this crate's own `saap_prove` signature uses
/// `VectorK` to carry a raw secret, neither type derives `Debug`/`Display`
/// (P3-03) — see the `assert_not_impl_any!` checks in `tests/no_debug_leak.rs`.
#[derive(Copy, Clone, Zeroize)]
#[repr(align(64))]
pub struct Polynomial {
    pub coeffs: [i32; RING_N],
}

impl Polynomial {
    pub const fn zero() -> Self {
        Self { coeffs: [0; RING_N] }
    }
}

/// k-dimensional module vector over R_q. See [`Polynomial`] for why this
/// type has no `Debug`/`Display` impl: it is the type this crate's own API
/// uses to carry a raw SAAP secret key (`saap_prove`'s `secret_key` parameter).
#[derive(Copy, Clone, Zeroize)]
#[repr(align(64))]
pub struct VectorK {
    pub vec: [Polynomial; MODULE_K],
}

impl VectorK {
    pub const fn zero() -> Self {
        Self { vec: [Polynomial::zero(); MODULE_K] }
    }
}

/// Bitmask of disclosed attributes.
pub type AttributeMask = u64;

/// Disclosed attribute values.
///
/// Keeps its `Debug` derive: these are the attribute values the credential
/// holder has *chosen to disclose* — deliberately revealed by SAAP's own
/// selective-disclosure design, never the secret key itself. Safe to
/// format-print by construction (P3-03).
#[derive(Copy, Clone, Debug)]
pub struct AttributePayload {
    pub values: [u64; MAX_ATTRIBUTES],
}

impl AttributePayload {
    pub const fn zero() -> Self {
        Self { values: [0u64; MAX_ATTRIBUTES] }
    }
}

/// Complete SAAP proof transcript.
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SaapProof {
    /// Context tag τ.
    pub context_tag: [u8; 32],
    /// Bitmask of disclosed attributes.
    pub disclosure_mask: AttributeMask,
    /// Disclosed attribute values.
    pub attributes: AttributePayload,
    /// Fiat-Shamir challenge polynomial c.
    pub challenge: Polynomial,
    /// Response vector z = r + c · secret_key.
    pub z: VectorK,
    /// BDLOP commitment hash (SHA3-256 of commitment vector).
    pub commitment_hash: [u8; 32],
    /// Commitment vector w = A · r.
    pub commitment_w: VectorK,
}

impl SaapProof {
    pub const fn zero() -> Self {
        Self {
            context_tag: [0u8; 32],
            disclosure_mask: 0,
            attributes: AttributePayload::zero(),
            challenge: Polynomial::zero(),
            z: VectorK::zero(),
            commitment_hash: [0u8; 32],
            commitment_w: VectorK::zero(),
        }
    }
}

/// Typed verification failure reasons.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SaapValidationError {
    NormBoundViolation,
    ChallengeMismatch,
    InvalidAttributeCommitment,
}

// ── Polynomial arithmetic ─────────────────────────────────────────────────────

/// Negacyclic polynomial multiplication in R_q = Z_q[X]/(X^N + 1).
pub fn poly_mul_negacyclic(a: &Polynomial, b: &Polynomial) -> Polynomial {
    let mut result = Polynomial::zero();
    for i in 0..RING_N {
        for j in 0..RING_N {
            let idx = i + j;
            let product = (a.coeffs[i] as i64) * (b.coeffs[j] as i64);
            if idx < RING_N {
                let acc = (result.coeffs[idx] as i64) + product;
                result.coeffs[idx] = mod_q(acc);
            } else {
                let wrap_idx = idx - RING_N;
                let acc = (result.coeffs[wrap_idx] as i64) - product;
                result.coeffs[wrap_idx] = mod_q(acc);
            }
        }
    }
    result
}

/// Polynomial addition mod q (centered).
pub fn poly_add(a: &Polynomial, b: &Polynomial) -> Polynomial {
    let mut result = Polynomial::zero();
    for i in 0..RING_N {
        let acc = (a.coeffs[i] as i64) + (b.coeffs[i] as i64);
        result.coeffs[i] = mod_q(acc);
    }
    result
}

/// Polynomial subtraction mod q (centered).
pub fn poly_sub(a: &Polynomial, b: &Polynomial) -> Polynomial {
    let mut result = Polynomial::zero();
    for i in 0..RING_N {
        let acc = (a.coeffs[i] as i64) - (b.coeffs[i] as i64);
        result.coeffs[i] = mod_q(acc);
    }
    result
}

/// Centered reduction modulo q.
#[inline(always)]
pub fn mod_q(x: i64) -> i32 {
    let q = PARAM_Q as i64;
    let r = x % q;
    let r = if r < 0 { r + q } else { r };
    let r = if r > q / 2 { r - q } else { r };
    r as i32
}

// ── Norm verification ─────────────────────────────────────────────────────────

/// Constant-time response norm verification.
///
/// Returns 0 if all coefficients satisfy `|coeff| < REJECTION_BOUND`,
/// or a non-zero mask if any coefficient violates the bound.
pub fn verify_response_norm(z: &VectorK) -> u32 {
    let mut bad_mask: u32 = 0;
    for k in 0..MODULE_K {
        for n in 0..RING_N {
            let coeff = z.vec[k].coeffs[n];
            let sign_mask = coeff >> 31;
            let abs_coeff = (coeff + sign_mask) ^ sign_mask;
            let diff = (REJECTION_BOUND - 1) - abs_coeff;
            bad_mask |= ((diff >> 31) & 1) as u32 * 0xFFFF_FFFF;
        }
    }
    bad_mask
}

// ── SHAKE-256 Fiat-Shamir challenge ───────────────────────────────────────────

/// Derive a sparse ternary challenge polynomial from an XOF reader.
///
/// Produces exactly 60 ±1 coefficients using rejection sampling.
pub fn hash_to_challenge_from_xof(xof: &mut impl XofReader) -> Polynomial {
    let mut c_poly = Polynomial::zero();

    let mut signs = [0u8; 8];
    xof.read(&mut signs);
    let mut sign_bit = 0usize;

    let mut count = 0usize;
    let mut used = [false; RING_N];
    let mut pos_buf = [0u8; 1];

    while count < 60 {
        xof.read(&mut pos_buf);
        let pos = pos_buf[0] as usize;
        if pos >= RING_N {
            continue;
        }
        if used[pos] {
            continue;
        }
        used[pos] = true;
        let sign_byte = signs[sign_bit / 8];
        let sign: i32 = if (sign_byte >> (sign_bit % 8)) & 1 == 0 { 1 } else { -1 };
        sign_bit += 1;
        if sign_bit >= 64 {
            xof.read(&mut signs);
            sign_bit = 0;
        }
        c_poly.coeffs[pos] = sign;
        count += 1;
    }
    c_poly
}

/// Recompute the SAAP Fiat-Shamir challenge using SHAKE-256.
///
/// c = SHAKE-256("AETHEL_SAAP_CHALLENGE_V1" ∥ commitment_w ∥ tau ∥ disclosure_mask)
/// Derive the Fiat-Shamir challenge.
///
/// Binds the disclosed attribute values (`m_pub` in SAAP-SPEC.md §7 step 3)
/// alongside the commitment, context and mask. Without them in the hash, the
/// disclosed values ride in the transcript unbound and can be rewritten after
/// proof generation while the proof still verifies — see
/// `disclosed_attributes_are_bound_into_the_challenge`.
///
/// Only the values selected by `disclosure_mask` are bound. Undisclosed slots
/// are skipped rather than hashed, so the challenge cannot act as an oracle on
/// attributes the proof is meant to withhold (§11.5).
pub fn recompute_challenge(
    commitment_w: &VectorK,
    tau: &[u8],
    disclosure_mask: AttributeMask,
    attributes: &AttributePayload,
) -> Polynomial {
    let mut hasher = Shake256::default();
    hasher.update(b"AETHEL_SAAP_CHALLENGE_V1");
    for poly in commitment_w.vec.iter() {
        for coeff in poly.coeffs.iter() {
            hasher.update(&coeff.to_le_bytes());
        }
    }
    hasher.update(tau);
    hasher.update(&disclosure_mask.to_le_bytes());
    for i in 0..MAX_ATTRIBUTES {
        if (disclosure_mask >> i) & 1 == 1 {
            hasher.update(&(i as u8).to_le_bytes());
            hasher.update(&attributes.values[i].to_le_bytes());
        }
    }
    let mut xof = hasher.finalize_xof();
    hash_to_challenge_from_xof(&mut xof)
}

// ── SAAP Prover ───────────────────────────────────────────────────────────────

/// Derive the SAAP context matrix A from tau using SHAKE-256.
fn derive_saap_matrix(tau: &[u8]) -> [VectorK; MODULE_K] {
    let mut matrix = [VectorK::zero(); MODULE_K];
    for i in 0..MODULE_K {
        for j in 0..MODULE_K {
            let mut hasher = Shake256::default();
            hasher.update(b"AETHEL_SAAP_MATRIX_V1");
            hasher.update(tau);
            hasher.update(&[i as u8, j as u8]);
            let mut xof = hasher.finalize_xof();

            let mut coeff_idx = 0usize;
            while coeff_idx < RING_N {
                let mut buf = [0u8; 3];
                xof.read(&mut buf);
                let val = (buf[0] as u32)
                    | ((buf[1] as u32) << 8)
                    | ((buf[2] as u32 & 0x7F) << 16);
                if (val as i32) < PARAM_Q {
                    let centered = if val > (PARAM_Q as u32 / 2) {
                        val as i32 - PARAM_Q
                    } else {
                        val as i32
                    };
                    matrix[i].vec[j].coeffs[coeff_idx] = centered;
                    coeff_idx += 1;
                }
            }
        }
    }
    matrix
}

/// Sample a masking vector r from uniform [-γ₁, γ₁]^k using SHAKE-256.
/// Sample the sigma-protocol masking vector `r ← [-γ₁, γ₁]^k`.
///
/// `rho` MUST be fresh, secret entropy, distinct per proof. The mask is the
/// only thing hiding `sk` in the response `z = r + c·sk`: an earlier version
/// derived `r` from the public context tag, so a transcript's `w = A·r` could
/// be replayed to recover `r` and hence `c·sk`. Worse, `r` did not depend on
/// the disclosure mask, so two proofs of one credential under one τ disclosing
/// different attribute sets shared `r` and leaked `sk` via `z₁ − z₂ = (c₁−c₂)·sk`.
/// Both are closed by sampling `r` from fresh `rho` here.
/// Sample the sigma-protocol masking vector.
///
/// `rho` is caller-supplied fresh randomness and is the primary defence. `tau`
/// is bound as well so that a caller who *reuses* `rho` across two contexts
/// still cannot be attacked: without it, two proofs sharing `rho` but under
/// different contexts share `r` while their challenges differ, and
/// `z1 - z2 = (c1 - c2)*sk` recovers the secret key. That exact attack was
/// demonstrated against PLP, which had no fresh randomness at all
/// (P3-15 / 0X3-85); binding tau here makes the same mistake unreachable
/// through this path regardless of caller behaviour.
fn sample_saap_masking_vector(rho: &[u8], tau: &[u8; 32], nonce: u8) -> VectorK {
    let mut r = VectorK::zero();
    let range = 2 * PARAM_GAMMA1 as u32 + 1;

    for k in 0..MODULE_K {
        let mut hasher = Shake256::default();
        hasher.update(b"AETHEL_SAAP_MASK_V3");
        hasher.update(rho);
        hasher.update(tau);
        hasher.update(&[nonce, k as u8]);
        let mut xof = hasher.finalize_xof();

        let mut coeff_idx = 0usize;
        while coeff_idx < RING_N {
            let mut buf = [0u8; 3];
            xof.read(&mut buf);
            let val = (buf[0] as u32)
                | ((buf[1] as u32) << 8)
                | ((buf[2] as u32 & 0x7F) << 16);
            if val < range {
                let centered = val as i32 - PARAM_GAMMA1;
                r.vec[k].coeffs[coeff_idx] = centered;
                coeff_idx += 1;
            }
        }
    }
    r
}

/// Generate the SAAP proof. **L1-internal**: `secret_key` is caller-supplied
/// raw key material, taken by reference and never stored or returned — only
/// the public [`SaapProof`] (challenge/commitment/response, safe to disclose
/// by construction) leaves this function. This function does not zeroize the
/// caller's `secret_key` itself (it's borrowed, not owned — wiping the
/// caller's memory out from under them would be a correctness bug, not a
/// safety improvement); it does zeroize every local intermediate derived from
/// it (`r`, `cs_k`), and on a **rejected** iteration also `w`/`c`/`z` before
/// looping — same reasoning as `plp::Prover::prove_identity`: a rejected
/// response must never be observable, so it must be wiped, not merely
/// dropped. `Polynomial`/`VectorK` are `Copy` and cannot implement `Drop`, so
/// none of this happens automatically.
///
/// Implements the BDLOP commitment scheme with Fiat-Shamir ZK proof.
pub fn saap_prove(
    credential: &[u8],
    disclosure_mask: AttributeMask,
    tau: &[u8],
    secret_key: &VectorK,
    rho: &[u8],
) -> SaapProof {
    // 1. Parse credential into attribute vector (up to MAX_ATTRIBUTES u64 values)
    let mut attributes = AttributePayload::zero();
    for i in 0..MAX_ATTRIBUTES {
        let offset = i * 8;
        if offset + 8 <= credential.len() {
            let mut bytes = [0u8; 8];
            bytes.copy_from_slice(&credential[offset..offset + 8]);
            attributes.values[i] = u64::from_le_bytes(bytes);
        }
    }

    // 2. Derive context matrix A
    let matrix_a = derive_saap_matrix(tau);

    // 3. Context tag (first 32 bytes of tau, padded)
    let mut context_tag = [0u8; 32];
    let len = tau.len().min(32);
    context_tag[..len].copy_from_slice(&tau[..len]);

    // 4. Fixed 16-iteration rejection sampling loop
    for iter in 0u8..16 {
        // Sample masking vector r ← S_{γ₁}^k
        let mut r = sample_saap_masking_vector(rho, &context_tag, iter);

        // Compute commitment w = A · r
        let mut w = VectorK::zero();
        for i in 0..MODULE_K {
            for j in 0..MODULE_K {
                let prod = poly_mul_negacyclic(&matrix_a[i].vec[j], &r.vec[j]);
                w.vec[i] = poly_add(&w.vec[i], &prod);
            }
        }

        // Compute Fiat-Shamir challenge c using padded context_tag (same as verifier)
        let mut c = recompute_challenge(&w, &context_tag, disclosure_mask, &attributes);

        // Compute response z = r + c · secret_key
        let mut z = VectorK::zero();
        for k in 0..MODULE_K {
            let mut cs_k = poly_mul_negacyclic(&c, &secret_key.vec[k]);
            z.vec[k] = poly_add(&r.vec[k], &cs_k);
            cs_k.zeroize();
        }
        r.zeroize();

        // Rejection check: ||z||∞ < γ₁ - β
        if verify_response_norm(&z) == 0 {
            // Compute commitment hash
            let mut commitment_hash = [0u8; 32];
            let mut hasher = Shake256::default();
            hasher.update(b"AETHEL_SAAP_COMMIT_V1");
            for poly in w.vec.iter() {
                for coeff in poly.coeffs.iter() {
                    hasher.update(&coeff.to_le_bytes());
                }
            }
            let mut xof = hasher.finalize_xof();
            xof.read(&mut commitment_hash);

            return SaapProof {
                context_tag,
                disclosure_mask,
                attributes,
                challenge: c,
                z,
                commitment_hash,
                commitment_w: w,
            };
        }

        // Rejected: w/c/z must not survive to the next iteration unwiped.
        w.zeroize();
        c.zeroize();
        z.zeroize();
    }

    // Fallback: return last candidate (all 16 iterations rejected — negligible probability)
    let mut r = sample_saap_masking_vector(rho, &context_tag, 0);
    let mut w = VectorK::zero();
    for i in 0..MODULE_K {
        for j in 0..MODULE_K {
            let prod = poly_mul_negacyclic(&matrix_a[i].vec[j], &r.vec[j]);
            w.vec[i] = poly_add(&w.vec[i], &prod);
        }
    }
    let c = recompute_challenge(&w, &context_tag, disclosure_mask, &attributes);
    let mut z = VectorK::zero();
    for k in 0..MODULE_K {
        let mut cs_k = poly_mul_negacyclic(&c, &secret_key.vec[k]);
        z.vec[k] = poly_add(&r.vec[k], &cs_k);
        cs_k.zeroize();
    }
    r.zeroize();
    let mut commitment_hash = [0u8; 32];
    let mut hasher = Shake256::default();
    hasher.update(b"AETHEL_SAAP_COMMIT_V1");
    for poly in w.vec.iter() {
        for coeff in poly.coeffs.iter() {
            hasher.update(&coeff.to_le_bytes());
        }
    }
    let mut xof = hasher.finalize_xof();
    xof.read(&mut commitment_hash);

    SaapProof {
        context_tag,
        disclosure_mask,
        attributes,
        challenge: c,
        z,
        commitment_hash,
        commitment_w: w,
    }
}

// ── SAAP Verifier ─────────────────────────────────────────────────────────────

/// Compute `t = A_τ · sk` for the **superseded** SAAP construction.
///
/// # This is not an anchor any more
///
/// The question this function used to raise, whether `t` could be published, is
/// now moot rather than open. `t = A·sk` carries no error term, so it is an
/// exact linear image of the secret and recovering `sk` from it is linear
/// algebra over the ring rather than an M-LWE instance. It was never
/// distributable.
///
/// [`crate::credential`] replaces it. That construction anchors verification on
/// the PLP projection `b_τ = A_τ·s + e_τ`, which is an M-LWE sample and is
/// publishable precisely because of the noise this value lacks. Nothing needs a
/// SAAP-local public key any more.
///
/// Retained only so the characterisation tests in `tests/saap_soundness.rs`
/// stay executable: they pin the defects of the superseded verifier as running
/// code rather than prose. It disappears when they do. Not part of the shipped
/// surface, and not reachable through the WIT world.
#[doc(hidden)]
#[deprecated(
    since = "0.1.1",
    note = "superseded by the credential module, which anchors on the PLP projection b_tau.             This value was never safe to publish and is now unnecessary."
)]
pub fn saap_public_key(tau: &[u8], secret_key: &VectorK) -> VectorK {
    let matrix_a = derive_saap_matrix(tau);
    let mut t = VectorK::zero();
    for i in 0..MODULE_K {
        for j in 0..MODULE_K {
            let prod = poly_mul_negacyclic(&matrix_a[i].vec[j], &secret_key.vec[j]);
            t.vec[i] = poly_add(&t.vec[i], &prod);
        }
    }
    t
}

/// Verify a SAAP proof against a caller-supplied context and public key.
///
/// This is the verification the module documentation always described. Unlike
/// [`verify_saap_proof`], every check is anchored outside the proof:
///
/// 1. Norm bound on `z`
/// 2. Fiat-Shamir consistency, with the challenge recomputed against the
///    **caller's** τ, and the proof's own `context_tag` required to match it —
///    so a proof cannot certify its own context
/// 3. The verification equation `A_τ · z - c · t == w`
///
/// Step 3 is an exact equality rather than an approximate one because this
/// construction adds no error term: `A·z = A·(r + c·sk) = A·r + c·(A·sk) = w +
/// c·t`. PLP's analogous check is approximate because its `public_b` is an LWE
/// sample carrying noise.
pub fn verify_saap_proof_against(
    proof: &SaapProof,
    tau: &[u8],
    public_key: &VectorK,
) -> Result<(), SaapValidationError> {
    // 1. Norm bound.
    if verify_response_norm(&proof.z) != 0 {
        return Err(SaapValidationError::NormBoundViolation);
    }

    // 2. Challenge consistency, against the caller's context.
    let mut context_tag = [0u8; 32];
    let len = tau.len().min(32);
    context_tag[..len].copy_from_slice(&tau[..len]);

    let recomputed_c =
        recompute_challenge(&proof.commitment_w, &context_tag, proof.disclosure_mask, &proof.attributes);
    let mut mismatch = 0u32;
    for i in 0..RING_N {
        mismatch |= (recomputed_c.coeffs[i] ^ proof.challenge.coeffs[i]) as u32;
    }
    // The proof's own tag must match the caller's, or a proof issued for one
    // context could be replayed under another.
    let mut tag_mismatch = 0u8;
    for i in 0..32 {
        tag_mismatch |= proof.context_tag[i] ^ context_tag[i];
    }
    if mismatch != 0 || tag_mismatch != 0 {
        return Err(SaapValidationError::ChallengeMismatch);
    }

    // 3. Verification equation: A_τ · z - c · t == w.
    let matrix_a = derive_saap_matrix(tau);
    let mut equation_mismatch = 0u32;
    for i in 0..MODULE_K {
        let mut az_i = Polynomial::zero();
        for j in 0..MODULE_K {
            let prod = poly_mul_negacyclic(&matrix_a[i].vec[j], &proof.z.vec[j]);
            az_i = poly_add(&az_i, &prod);
        }
        let ct = poly_mul_negacyclic(&proof.challenge, &public_key.vec[i]);
        let w_prime = poly_sub(&az_i, &ct);
        for n in 0..RING_N {
            equation_mismatch |= (w_prime.coeffs[n] ^ proof.commitment_w.vec[i].coeffs[n]) as u32;
        }
    }
    if equation_mismatch != 0 {
        return Err(SaapValidationError::InvalidAttributeCommitment);
    }

    compiler_fence(Ordering::SeqCst);
    Ok(())
}

/// Verify a SAAP proof transcript.
///
/// Checks:
/// 1. Norm bound: ||z||∞ < γ₁ - β
/// 2. Challenge consistency: c' = SHAKE-256("AETHEL_SAAP_CHALLENGE_V1" ∥ w ∥ τ ∥ mask)
/// 3. Commitment hash consistency
#[deprecated(
    since = "0.1.1",
    note = "unsound: ignores its public parameters and checks the proof only against \
            itself, so it accepts proofs forged with no secret key. Use \
            verify_saap_proof_against(proof, tau, public_key). See P3-10 / 0X3-78."
)]
pub fn verify_saap_proof(
    proof: &SaapProof,
    _matrix_a: &[VectorK; MODULE_K],
    _public_attribute_commitments: &[Polynomial; MAX_ATTRIBUTES],
) -> Result<(), SaapValidationError> {
    // Step 1: Norm Bound Check
    let norm_failure = verify_response_norm(&proof.z);
    if norm_failure != 0 {
        return Err(SaapValidationError::NormBoundViolation);
    }

    // Step 2: Reconstruct w' = A * z - c * t_attr
    // For the verifier, we use the stored commitment_w and verify the challenge
    // matches the recomputed challenge from commitment_w.
    let recomputed_c = recompute_challenge(
        &proof.commitment_w,
        &proof.context_tag,
        proof.disclosure_mask,
        &proof.attributes,
    );

    // Step 3: Challenge Consistency Verification (constant-time)
    let mut mismatch = 0u32;
    for i in 0..RING_N {
        let a = recomputed_c.coeffs[i];
        let b = proof.challenge.coeffs[i];
        mismatch |= (a ^ b) as u32;
    }
    if mismatch != 0 {
        return Err(SaapValidationError::ChallengeMismatch);
    }

    // Step 4: Verify commitment hash
    let mut expected_hash = [0u8; 32];
    let mut hasher = Shake256::default();
    hasher.update(b"AETHEL_SAAP_COMMIT_V1");
    for poly in proof.commitment_w.vec.iter() {
        for coeff in poly.coeffs.iter() {
            hasher.update(&coeff.to_le_bytes());
        }
    }
    let mut xof = hasher.finalize_xof();
    xof.read(&mut expected_hash);

    let mut hash_mismatch = 0u8;
    for i in 0..32 {
        hash_mismatch |= proof.commitment_hash[i] ^ expected_hash[i];
    }
    if hash_mismatch != 0 {
        return Err(SaapValidationError::InvalidAttributeCommitment);
    }

    compiler_fence(Ordering::SeqCst);
    Ok(())
}

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

    fn make_test_secret_key() -> VectorK {
        let mut sk = VectorK::zero();
        for k in 0..MODULE_K {
            for n in 0..RING_N {
                sk.vec[k].coeffs[n] = (n % 5) as i32 - 2;
            }
        }
        sk
    }

    #[test]
    fn test_mod_q_range() {
        let q = PARAM_Q as i64;
        for x in [-q - 1, -q, -1, 0, 1, q - 1, q, q + 1] {
            let r = mod_q(x);
            assert!(r >= -(PARAM_Q / 2) && r <= PARAM_Q / 2,
                "mod_q({}) = {} out of range", x, r);
        }
    }

    #[test]
    fn test_recompute_challenge_deterministic() {
        let w = VectorK::zero();
        let tau = b"test_tau";
        let mask = 0b00001111u64;
        let c1 = recompute_challenge(&w, tau, mask, &AttributePayload::zero());
        let c2 = recompute_challenge(&w, tau, mask, &AttributePayload::zero());
        assert_eq!(c1.coeffs, c2.coeffs, "challenge should be deterministic");
    }

    #[test]
    fn test_recompute_challenge_sparse() {
        let w = VectorK::zero();
        let c = recompute_challenge(&w, b"tau", 0u64, &AttributePayload::zero());
        let nonzero = c.coeffs.iter().filter(|&&x| x != 0).count();
        assert_eq!(nonzero, 60, "challenge should have exactly 60 non-zero coefficients");
    }

    #[test]
    fn test_saap_prove_verify() {
        let sk = make_test_secret_key();
        let credential = [0u8; 64]; // 8 attributes of 8 bytes each
        let disclosure_mask = 0b00001111u64;
        let tau = b"test_context_tau_saap";

        let proof = saap_prove(&credential, disclosure_mask, tau, &sk, &[0x7cu8; 32]);

        // Verify norm bound
        assert_eq!(verify_response_norm(&proof.z), 0, "response norm should be within bound");

        // Verify challenge consistency — use proof.context_tag (padded) not raw tau
        let recomputed = recompute_challenge(&proof.commitment_w, &proof.context_tag, disclosure_mask, &proof.attributes);
        let mut mismatch = 0u32;
        for i in 0..RING_N {
            mismatch |= (recomputed.coeffs[i] ^ proof.challenge.coeffs[i]) as u32;
        }
        assert_eq!(mismatch, 0, "challenge should be consistent");
    }
}