aethel-core 0.7.5

Post-quantum anonymous identity for Rust and WASM. A no_std alternative to static W3C DIDs: per-context identifiers, no reusable public key, context-bound ML-DSA signing. Selective disclosure ships and is being hardened; see SECURITY.md.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
//! # SAAP Selective Attribute Verification Engine
//!
//! This module implements the **Selective Attribute Attestation Protocol (SAAP)**
//! prove/verify engine for Aethel-ID. This code has had no independent security
//! audit (see the README's audit status), and its pathway is retired (D-13).
//! 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"`

// The single-response prove and verify pathway below is retired (D-13 in
// docs/DEVIATIONS.md, 0X3-110): nothing outside this file's tests calls it.
// It is marked rather than deleted because `SaapProof` and
// `SaapValidationError` are public, so removing it belongs in a breaking
// release.
#![allow(dead_code)]
// Ring arithmetic indexes several coefficient arrays in step, so an index
// loop is the clear form here (as in `component.rs`).
#![allow(clippy::needless_range_loop)]

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

use crate::identity_error::IdentityError;

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 {
    /// An all-zero proof, used as an output buffer.
    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 {
    /// A response coefficient is at or above the rejection bound.
    NormBoundViolation,
    /// The recomputed Fiat-Shamir challenge differs from the proof's.
    ChallengeMismatch,
    /// A disclosed attribute does not match its commitment.
    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 pc = crate::plp::poly_mul_ntt(&to_plp_poly(a), &to_plp_poly(b));

    let mut result = Polynomial::zero();
    for i in 0..RING_N {
        result.coeffs[i] = mod_q(pc.coeffs[i] as i64);
    }
    result
}

/// Convert a centered SAAP polynomial into PLP's unsigned representation.
///
/// SAAP carries coefficients centered in `(-q/2, q/2]` (see [`mod_q`]); PLP
/// carries them in `[0, q)`. The NTT is PLP's, so the bridge lives here rather
/// than making PLP aware of a second convention.
fn to_plp_poly(p: &Polynomial) -> crate::plp::Poly {
    let mut out = crate::plp::Poly::zero();
    for i in 0..RING_N {
        let c = p.coeffs[i];
        out.coeffs[i] = if c < 0 { (c + PARAM_Q) as u32 } else { c as u32 };
    }
    out
}

/// Schoolbook negacyclic multiplication, retained as the reference.
///
/// [`poly_mul_negacyclic`] is the fast path and this is what it is checked
/// against, by `ntt_and_schoolbook_agree_over_saap_polynomials`. Keeping the
/// O(N^2) version is the only way that check means anything: a fast path with no
/// independent reference is a fast path nobody can falsify.
pub fn poly_mul_schoolbook(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 [`crate::plp::CHALLENGE_WEIGHT`] coefficients in `{±1}`
/// using rejection sampling. The weight is shared with `plp` deliberately:
/// `BETA` is derived from it, and two challenge spaces with one bound would
/// mean the bound is wrong for at least one of them.
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 < crate::plp::CHALLENGE_WEIGHT {
        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.
///
/// Returns the first response that satisfies the norm bound, or
/// `Err(RejectionSamplingFailed)` if all 16 iterations are rejected. There is
/// deliberately **no fallback proof**: see the note above the error return for
/// why emitting a candidate there was a soundness hazard rather than a
/// convenience.
pub fn saap_prove(
    credential: &[u8],
    disclosure_mask: AttributeMask,
    tau: &[u8],
    secret_key: &VectorK,
    rho: &[u8],
) -> Result<SaapProof, IdentityError> {
    // 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 Ok(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();
    }

    // No fallback, and specifically not the one that used to be here.
    //
    // This path rebuilt a candidate by re-deriving the mask as
    // `sample_saap_masking_vector(rho, &context_tag, 0)` — nonce zero, which is
    // iteration 0's mask. The derivation is a pure function of
    // `(rho, context_tag, nonce)`, so `w`, `c` and `z` all recomputed to
    // iteration 0's values and the function returned, verbatim, the response
    // iteration 0 had already rejected. It did not compute a fresh candidate; it
    // re-emitted a rejected one, without re-checking the bound.
    //
    // That is precisely the value rejection sampling exists to withhold. A
    // response outside the bound verifies nowhere, so it could only leak, never
    // authenticate: an out-of-bound `z` is how a sigma protocol gives up its
    // secret, which is the whole reason the bound is there.
    //
    // "Negligible probability" is the wrong frame for how reachable this was.
    // All 16 iterations rejecting is negligible by chance, but the derivation is
    // deterministic in `(rho, context_tag)`, so an attacker searches for a
    // context that lands here rather than waiting for one. `plp::Prover::
    // prove_identity` (0X3-85) and `credential::prove` already refuse for this
    // reason; this brings the third implementation of the same primitive in
    // line with them.
    Err(IdentityError::RejectionSamplingFailed)
}

// ── 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!((-(PARAM_Q / 2)..=PARAM_Q / 2).contains(&r),
                "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, crate::plp::CHALLENGE_WEIGHT,
            "challenge should have exactly CHALLENGE_WEIGHT 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])
            .expect("honest parameters: 16 rejections is negligible");

        // 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");
    }
}

// ── Characterisation and soundness tests ────────────────────────
//
// Moved here from tests/saap_soundness.rs and tests/randomness_is_secret.rs
// when this module became crate-private (P3-10 / 0X3-78). An integration test
// cannot reach a pub(crate) module, and this module had to stop being public
// because saap_prove's signature takes a raw u64 disclosure mask, which the
// WIT world is explicit about never putting on the wire.
//
// They are kept, not deleted: they pin the superseded verifier's defects as
// executable characterisation rather than prose, and they disappear when it
// does.

#[cfg(test)]
#[allow(deprecated)]
mod soundness_tests {
    use super::*;

    fn test_sk() -> VectorK {
        let mut sk = VectorK::zero();
        for k in 0..MODULE_K {
            for n in 0..RING_N {
                sk.vec[k].coeffs[n] = ((k * 31 + n * 7) % 5) as i32 - 2;
            }
        }
        sk
    }
    use sha3::{digest::{ExtendableOutput, Update, XofReader}, Shake256};

    const RHO_A: [u8; 32] = [0x11u8; 32];

    const RHO_B: [u8; 32] = [0x22u8; 32];


    /// Build a proof with no secret key, no credential, and no key material of any
    /// kind — only public knowledge of the verification procedure.
    ///
    /// Strategy: every check in `verify_saap_proof` derives its expected value from
    /// a field of the proof. So pick the free fields first, then compute the
    /// dependent ones the same way the verifier will.
    fn forge(context_tag: [u8; 32], disclosure_mask: u64) -> SaapProof {
        let mut proof = SaapProof::zero();

        proof.context_tag = context_tag;
        proof.disclosure_mask = disclosure_mask;
        proof.attributes = AttributePayload::zero();

        // Free choice: the commitment vector. The verifier never checks it against
        // A·z, because `matrix_a` is ignored. Zero is the simplest witness that the
        // choice is unconstrained.
        proof.commitment_w = VectorK::zero();

        // Free choice: the response vector. Only its norm is checked, and the norm
        // of zero trivially passes the bound.
        proof.z = VectorK::zero();

        // Dependent: the challenge is whatever `recompute_challenge` produces from
        // fields we already control.
        proof.challenge = recompute_challenge(
            &proof.commitment_w,
            &proof.context_tag,
            proof.disclosure_mask,
            &proof.attributes,
        );

        // Dependent: the commitment hash is SHAKE-256 over the commitment vector,
        // recomputed by the verifier from the same field.
        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 proof.commitment_hash);

        proof
    }

    /// Characterises the defect in the deprecated verifier, executably.
    ///
    /// This asserts the **known-bad** behaviour deliberately: `verify_saap_proof`
    /// accepts a proof forged with no secret key. It is written as a passing test so
    /// the defect is pinned rather than merely described, and so it disappears
    /// together with the function it characterises. The correctness assertions live
    /// in `corrected_verifier_*` above.
    #[test]
    #[allow(deprecated)]
    fn deprecated_verifier_accepts_forgeries_known_defect() {
        let matrix_a = [VectorK::zero(); MODULE_K];
        let attr_commits = [Polynomial::zero(); MAX_ATTRIBUTES];

        let proof = forge([7u8; 32], 0b0000_0011);

        assert!(
            verify_saap_proof(&proof, &matrix_a, &attr_commits).is_ok(),
            "the deprecated verifier now rejects the forgery — if it was fixed, delete \
             this characterisation test along with the function"
        );
    }

    /// Positive control for the forgery methodology above.
    ///
    /// PLP's verifier performs the same three-step shape as SAAP's — norm bound,
    /// Fiat-Shamir challenge consistency, verification equation — but its third
    /// step actually uses the projection's public parameters:
    ///
    /// ```text
    /// W' = A_τ · z - c · b_τ    then    ||W' - W||∞ < 2β
    /// ```
    ///
    /// So the analogous forgery must fail there. If this test passes while the
    /// SAAP forgery is accepted, the difference is in the verifiers, not in the
    /// way these tests construct a forgery.
    #[test]
    fn plp_rejects_the_analogous_forgery() {
        use crate::plp::{MasterIdentity, Poly, Verifier, ZkIdentityProof};

        // The forger is allowed to know the public projection — that is the point
        // of a public key. It has no access to the master secret.
        let identity = MasterIdentity::from_seed(&[0x11u8; 32]);
        let projection = identity.project_at_context(b"context-under-attack", &[0xa5u8; 32]);

        // Same free choices as the SAAP forgery: zero commitment, zero response,
        // challenge recomputed the way the verifier will recompute it.
        let commitment_w = [Poly::zero(); crate::plp::MODULE_K];
        let challenge_c = crate::plp::hash_to_challenge(
            &commitment_w,
            &projection.public_b,
            &projection.tau,
            &projection.salt,
        );
        let proof = ZkIdentityProof {
            commitment_w,
            challenge_c,
            response_z: [Poly::zero(); crate::plp::MODULE_K],
        };

        assert!(
            !Verifier::verify(&projection, &proof),
            "PLP accepted the same style of forgery SAAP accepts — in that case the \
             forgery helper is what is wrong, not the SAAP verifier, and the SAAP \
             finding must be re-derived before it is reported."
        );
    }

    // ── The corrected verifier ────────────────────────────────────────────────────

    const TAU: &[u8] = b"context-alpha";
    const CREDENTIAL: &[u8] = b"attribute-block-0123456789abcdef";

    fn 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
    }

    /// The load-bearing test: an honestly generated proof must satisfy
    /// `A_τ · z - c · t == w`. If this fails, the verification equation is wrong and
    /// nothing built on it can be trusted.
    #[test]
    fn honest_proof_satisfies_the_verification_equation() {
        let sk = test_secret_key();
        let proof = saap_prove(CREDENTIAL, 0b0000_0011, TAU, &sk, &[0x7cu8; 32])
            .expect("honest parameters: 16 rejections is negligible");
        let public_key = saap_public_key(TAU, &sk);

        assert_eq!(
            verify_saap_proof_against(&proof, TAU, &public_key),
            Ok(()),
            "an honestly generated proof failed the verification equation"
        );
    }

    #[test]
    fn corrected_verifier_rejects_the_forgery() {
        let sk = test_secret_key();
        let public_key = saap_public_key(TAU, &sk);
        let forged = forge_for(TAU, 0b0000_0011);

        assert!(
            verify_saap_proof_against(&forged, TAU, &public_key).is_err(),
            "the corrected verifier still accepts a proof forged with no secret key"
        );
    }

    #[test]
    fn corrected_verifier_rejects_a_proof_from_another_context() {
        let sk = test_secret_key();
        let proof = saap_prove(CREDENTIAL, 0b0000_0011, TAU, &sk, &[0x7cu8; 32])
            .expect("honest parameters: 16 rejections is negligible");

        // Same identity, different context: derive the public key for the context
        // the verifier actually cares about.
        let other_tau: &[u8] = b"context-beta";
        let public_key_beta = saap_public_key(other_tau, &sk);

        assert!(
            verify_saap_proof_against(&proof, other_tau, &public_key_beta).is_err(),
            "a proof issued for one context verified under another"
        );
    }

    #[test]
    fn corrected_verifier_rejects_a_tampered_response() {
        let sk = test_secret_key();
        let mut proof = saap_prove(CREDENTIAL, 0b0000_0011, TAU, &sk, &[0x7cu8; 32])
            .expect("honest parameters: 16 rejections is negligible");
        let public_key = saap_public_key(TAU, &sk);

        proof.z.vec[0].coeffs[0] = proof.z.vec[0].coeffs[0].wrapping_add(1);

        assert!(
            verify_saap_proof_against(&proof, TAU, &public_key).is_err(),
            "a tampered response vector still verified"
        );
    }

    /// SAAP-SPEC.md §7 step 3 requires the Fiat-Shamir challenge to bind the
    /// disclosed attribute values:
    ///
    /// ```text
    /// c' = Hash(W_1' ∥ W_2' ∥ b_τ ∥ t_blind ∥ m_pub ∥ τ)
    /// ```
    ///
    /// `recompute_challenge` hashes only `(commitment_w, τ, disclosure_mask)`. The
    /// disclosed values ride in the transcript as `proof.attributes` and never enter
    /// the challenge, so they can be rewritten after the fact.
    ///
    /// This is a gap in the corrected verifier too — fixing the verification
    /// equation did not fix attribute binding, because the two are independent.
    #[test]
    fn disclosed_attributes_are_bound_into_the_challenge() {
        let sk = test_secret_key();
        let mut proof = saap_prove(CREDENTIAL, 0b0000_0011, TAU, &sk, &[0x7cu8; 32])
            .expect("honest parameters: 16 rejections is negligible");
        let public_key = saap_public_key(TAU, &sk);

        // Sanity: the untampered proof verifies.
        assert_eq!(
            verify_saap_proof_against(&proof, TAU, &public_key),
            Ok(()),
            "test setup: the honest proof should verify before tampering"
        );

        // Rewrite a disclosed attribute value. Nothing else is touched.
        let original = proof.attributes.values[0];
        proof.attributes.values[0] = original.wrapping_add(0xDEAD_BEEF);

        assert!(
            verify_saap_proof_against(&proof, TAU, &public_key).is_err(),
            "a disclosed attribute value was rewritten after proof generation and the \
             proof still verified. SAAP-SPEC.md §7 step 3 binds m_pub into the \
             challenge; recompute_challenge does not. The verifier therefore attests \
             to attribute values the prover never committed to, which is the property \
             SAAP exists to provide."
        );
    }

    /// Same construction as `forge`, parameterised by τ so it can be aimed at the
    /// corrected verifier.
    fn forge_for(tau: &[u8], disclosure_mask: u64) -> SaapProof {
        let mut context_tag = [0u8; 32];
        let len = tau.len().min(32);
        context_tag[..len].copy_from_slice(&tau[..len]);
        forge(context_tag, disclosure_mask)
    }

    /// Characterises the second defect in the deprecated verifier: it takes no
    /// caller-supplied τ at all, so a proof certifies its own context. Asserted as
    /// known-bad for the same reason as above.
    #[test]
    #[allow(deprecated)]
    fn deprecated_verifier_is_self_certifying_known_defect() {
        let matrix_a = [VectorK::zero(); MODULE_K];
        let attr_commits = [Polynomial::zero(); MAX_ATTRIBUTES];

        let proof = forge([0xAAu8; 32], 0b0000_0001);

        assert!(
            verify_saap_proof(&proof, &matrix_a, &attr_commits).is_ok(),
            "the deprecated verifier has no τ parameter, so it cannot answer 'is this \
             valid for MY context?' — it accepts whatever context the proof asserts \
             about itself. The WIT world declares \
             saap-verify(proof, tau) -> result<bool, identity-error>."
        );
    }

    /// Fresh randomness changes the proof commitment; the same randomness reproduces
    /// it. The commitment `w = A·r` moves with `r`, so it carries per-call entropy.
    #[test]
    fn saap_mask_is_fresh_per_rho_and_reproducible_given_rho() {
        let sk = test_sk();
        // A fixed array, not a Vec: this module is no_std and `alloc` is not
        // imported here. The wasm job builds test targets with
        // --no-default-features, so a Vec here fails only there.
        let credential: [u8; 64] = core::array::from_fn(|i| i as u8);
        let tau = b"verifier-session-tau-0001";

        let p_a1 = saap_prove(&credential, 0b0000_0011, tau, &sk, &RHO_A)
            .expect("honest parameters: 16 rejections is negligible");
        let p_a2 = saap_prove(&credential, 0b0000_0011, tau, &sk, &RHO_A)
            .expect("honest parameters: 16 rejections is negligible");
        let p_b = saap_prove(&credential, 0b0000_0011, tau, &sk, &RHO_B)
            .expect("honest parameters: 16 rejections is negligible");

        let commitments_equal = |x: &SaapProof, y: &SaapProof| {
            (0..MODULE_K).all(|i| {
                (0..RING_N).all(|n| x.commitment_w.vec[i].coeffs[n] == y.commitment_w.vec[i].coeffs[n])
            })
        };

        assert!(
            commitments_equal(&p_a1, &p_a2),
            "same rho must reproduce the same commitment"
        );
        assert!(
            !commitments_equal(&p_a1, &p_b),
            "different rho must change the commitment — r carries per-call entropy"
        );
    }

    /// Proofs of one credential under one τ disclosing different attribute sets,
    /// each with its own fresh `rho`, carry independent masks — their commitments
    /// differ, so nothing links the two presentations through a shared mask.
    #[test]
    fn saap_distinct_rho_gives_distinct_masks_across_disclosures() {
        let sk = test_sk();
        // A fixed array, not a Vec: this module is no_std and `alloc` is not
        // imported here. The wasm job builds test targets with
        // --no-default-features, so a Vec here fails only there.
        let credential: [u8; 64] = core::array::from_fn(|i| i as u8);
        let tau = b"verifier-session-tau-0001";

        let p1 = saap_prove(&credential, 0b0000_0001, tau, &sk, &RHO_A)
            .expect("honest parameters: 16 rejections is negligible");
        let p2 = saap_prove(&credential, 0b0000_0010, tau, &sk, &RHO_B)
            .expect("honest parameters: 16 rejections is negligible");

        let mut any_diff = false;
        for i in 0..MODULE_K {
            for n in 0..RING_N {
                if p1.commitment_w.vec[i].coeffs[n] != p2.commitment_w.vec[i].coeffs[n] {
                    any_diff = true;
                }
            }
        }
        assert!(
            any_diff,
            "commitments must differ across proofs — masks are independent per rho"
        );
    }

}

// ── P3-03: Debug/Display redaction, asserted at compile time ────────────────
//
// `VectorK` is the type `saap_prove`'s `secret_key` parameter uses to carry a
// raw SAAP secret, and `Polynomial` is its component type, so neither may
// implement `Debug`/`Display`: a derive on either would let anyone holding a
// value format-print the raw secret with a single `{:?}`.
//
// `assert_not_impl_any!` expands to code that compiles only if the named type
// does NOT implement the named traits, so re-adding a naive `#[derive(Debug)]`
// breaks the build rather than a test run. These assertions used to live in
// `tests/no_debug_leak.rs`; they moved here when the module became crate-private
// and an integration test could no longer name these types.
#[cfg(test)]
mod no_debug_leak {
    use static_assertions::assert_not_impl_any;

    assert_not_impl_any!(super::Polynomial: core::fmt::Debug, core::fmt::Display);
    assert_not_impl_any!(super::VectorK: core::fmt::Debug, core::fmt::Display);
}

// ── Prove/verify round-trip, moved from tests/plp_tests.rs ──────────────────
//
// Same reason as the blocks above: this module is crate-private since
// P3-10 / 0X3-78, so these can no longer live in an integration test.
#[cfg(test)]
#[allow(deprecated)]
mod roundtrip_tests {
    use super::*;



    /// Verify that the SAAP prover produces a proof that passes norm check.
    #[test]
    fn test_saap_prove_norm_bound() {
        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;
            }
        }
        let credential = [0u8; 64];
        let disclosure_mask = 0b00001111u64;
        let tau = b"test_saap_context";

        let proof = saap_prove(&credential, disclosure_mask, tau, &sk, &[0x7cu8; 32])
            .expect("honest parameters: 16 rejections is negligible");

        // Norm bound check
        let norm_result = verify_response_norm(&proof.z);
        assert_eq!(norm_result, 0, "SAAP response norm should be within bound");
    }

    /// Verify that the SAAP verifier accepts a well-formed proof.
    #[test]
    fn test_saap_prove_verify_roundtrip() {
        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;
            }
        }
        let credential = [0u8; 64];
        let disclosure_mask = 0b00001111u64;
        let tau = b"test_saap_context_verify";

        let proof = saap_prove(&credential, disclosure_mask, tau, &sk, &[0x7cu8; 32])
            .expect("honest parameters: 16 rejections is negligible");

        // Build dummy matrix and attribute commitments
        let matrix_a = [VectorK::zero(); MODULE_K];
        let attr_commits = [Polynomial::zero(); MAX_ATTRIBUTES];

        let result = verify_saap_proof(&proof, &matrix_a, &attr_commits);
        assert!(result.is_ok(), "SAAP verify should accept valid proof: {:?}", result);
    }

    /// Verify that the SAAP verifier rejects a proof with an out-of-bounds response norm.
    #[test]
    fn test_saap_verify_rejects_invalid_norm() {
        let mut proof = SaapProof::zero();
        // Set a coefficient way out of bounds
        proof.z.vec[0].coeffs[0] = REJECTION_BOUND + 1000;

        let matrix_a = [VectorK::zero(); MODULE_K];
        let attr_commits = [Polynomial::zero(); MAX_ATTRIBUTES];

        let result = verify_saap_proof(&proof, &matrix_a, &attr_commits);
        assert_eq!(
            result,
            Err(SaapValidationError::NormBoundViolation),
            "Should reject proof with out-of-bounds norm"
        );
    }



    // ── NTT fast path equivalence (Q3 Fix 2) ─────────────────────────────────

    /// A deterministic pseudo-random polynomial with full-range coefficients.
    ///
    /// Small or structured inputs would not exercise the modular reduction, and
    /// the schoolbook path accumulates differently from the NTT path, so the
    /// coefficients must span the whole centered range for the comparison to be
    /// worth anything.
    fn pseudo_random_poly(seed: u64) -> Polynomial {
        let mut p = Polynomial::zero();
        let mut x = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
        for i in 0..RING_N {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            p.coeffs[i] = mod_q((x % (PARAM_Q as u64 * 2)) as i64 - PARAM_Q as i64);
        }
        p
    }

    /// The NTT fast path must agree with the schoolbook reference exactly.
    ///
    /// This is the whole contract of `poly_mul_negacyclic` after Q3 Fix 2. A
    /// faster multiply that returns different answers is not an optimisation,
    /// it is a silent break in every SAAP proof and verification, all of which
    /// route through this one function.
    #[test]
    fn ntt_and_schoolbook_agree_over_saap_polynomials() {
        for seed in 0..24u64 {
            let a = pseudo_random_poly(seed * 2 + 1);
            let b = pseudo_random_poly(seed * 2 + 2);

            let fast = poly_mul_negacyclic(&a, &b);
            let reference = poly_mul_schoolbook(&a, &b);

            assert_eq!(
                fast.coeffs, reference.coeffs,
                "NTT and schoolbook disagree at seed {seed}"
            );
        }
    }

    /// Positive control for the test above.
    ///
    /// If `pseudo_random_poly` returned the same polynomial for every seed, or
    /// the comparison were vacuous, the equivalence test would pass while
    /// proving nothing. Distinct operands must produce distinct products.
    #[test]
    fn the_multiplication_agreement_check_can_fail() {
        let a = pseudo_random_poly(1);
        let b = pseudo_random_poly(2);
        let c = pseudo_random_poly(3);

        assert_ne!(a.coeffs, b.coeffs, "operand generator is not varying");
        assert_ne!(
            poly_mul_negacyclic(&a, &b).coeffs,
            poly_mul_negacyclic(&a, &c).coeffs,
            "different operands produced the same product, so agreement proves nothing"
        );
    }

    /// The centered/unsigned bridge must round trip.
    ///
    /// SAAP centers coefficients in (-q/2, q/2]; PLP uses [0, q). Every SAAP
    /// multiplication now crosses that boundary twice, so an error here would
    /// corrupt results in a way that looks like a cryptographic failure rather
    /// than a representation bug.
    #[test]
    fn the_centered_to_unsigned_bridge_round_trips() {
        for seed in 0..8u64 {
            let p = pseudo_random_poly(seed + 100);
            let bridged = to_plp_poly(&p);
            for i in 0..RING_N {
                assert!(
                    bridged.coeffs[i] < PARAM_Q as u32,
                    "bridged coefficient outside [0, q)"
                );
                assert_eq!(
                    mod_q(bridged.coeffs[i] as i64),
                    p.coeffs[i],
                    "round trip changed coefficient {i} at seed {seed}"
                );
            }
        }
    }
}


// ── Rejection sampling has no fallback (AETHEL-F-01, saap half) ──────────────
//
// The `plp.rs` half of this finding was fixed in 0b24bc0. This module is the
// evidence for the same property here.
#[cfg(test)]
mod rejection_sampling_tests {
    use super::*;

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

    /// Every proof `saap_prove` returns satisfies the norm bound.
    ///
    /// This is the invariant the fallback broke. It re-derived iteration 0's
    /// mask, recomputed iteration 0's `w`, `c` and `z`, and returned that `z`
    /// without re-checking the bound — so the one response the function was
    /// certain to be out of bounds was the one it emitted on exhaustion.
    ///
    /// Swept across contexts and randomness rather than asserted once, because
    /// a single honest call proves only that the happy path works.
    #[test]
    fn every_returned_proof_satisfies_the_norm_bound() {
        let sk = test_sk();
        let credential = [0x3Cu8; 64];

        for tau_idx in 0u8..12 {
            for rho_idx in 0u8..4 {
                let tau = [b'c', b't', b'x', tau_idx];
                let rho = [0x40u8 ^ rho_idx; 32];

                let proof = saap_prove(&credential, 0b0000_0011, &tau, &sk, &rho)
                    .expect("honest parameters: 16 rejections is negligible");

                assert_eq!(
                    verify_response_norm(&proof.z),
                    0,
                    "saap_prove returned a response outside the rejection bound \
                     at tau {tau_idx}, rho {rho_idx}"
                );
            }
        }
    }

    /// Positive control for the sweep above.
    ///
    /// Without this, the sweep would pass just as happily against a norm check
    /// that accepted everything, which would make it evidence of nothing.
    #[test]
    fn the_norm_check_rejects_an_out_of_bound_response() {
        let sk = test_sk();
        let credential = [0x3Cu8; 64];
        let mut proof = saap_prove(&credential, 0b0000_0011, b"ctx", &sk, &[0x41u8; 32])
            .expect("honest parameters: 16 rejections is negligible");

        assert_eq!(verify_response_norm(&proof.z), 0, "test setup: an honest proof is in bounds");

        proof.z.vec[0].coeffs[0] = REJECTION_BOUND;
        assert_ne!(
            verify_response_norm(&proof.z),
            0,
            "a response at the rejection bound was accepted, so the sweep above \
             is not testing anything"
        );
    }

    /// Nothing may re-derive the mask after the loop.
    ///
    /// The old fallback was `sample_saap_masking_vector(rho, &context_tag, 0)`.
    /// Nonce zero is iteration 0's nonce, and the derivation is a pure function
    /// of `(rho, context_tag, nonce)`, so that call reproduced iteration 0's
    /// mask exactly and the proof rebuilt from it was, byte for byte, the
    /// response iteration 0 had already rejected.
    ///
    /// A behavioural test cannot reach this: forcing 16 consecutive rejections
    /// at honest parameters is exactly the negligible event the fallback was
    /// excused by. So the derivation itself is pinned instead, the same way
    /// `plp.rs` pins `no_tau_independent_mask_derivation_remains`.
    #[test]
    fn no_fallback_mask_derivation_remains() {
        let source = include_str!("saap.rs");

        // Split across `concat!` so the needle never appears contiguously in
        // this file, which would otherwise make the test match itself. Comment
        // lines are skipped for the same reason: the doc comment above names
        // the old call on purpose.
        let needle = concat!("sample_saap_masking_vector(rho, &context_tag, ", "0)");
        let hits = source
            .lines()
            .filter(|l| !l.trim_start().starts_with("//"))
            .filter(|l| l.contains(needle))
            .count();

        assert_eq!(
            hits, 0,
            "the fallback mask derivation is back in saap_prove. Nonce 0 is \
             iteration 0's nonce and the derivation is pure, so it reproduces \
             iteration 0's mask and rebuilds, byte for byte, the response \
             iteration 0 already rejected. That is precisely the value rejection \
             sampling exists to withhold. See AETHEL-F-01 and 0b24bc0 before \
             restoring it."
        );
    }

    /// Exhaustion is reported, not papered over.
    ///
    /// Pins the signature: a caller must be able to tell "no proof exists" from
    /// "here is a proof", which the previous `-> SaapProof` return type made
    /// impossible.
    #[test]
    fn exhaustion_has_an_error_to_report() {
        let sk = test_sk();
        let proof: Result<SaapProof, IdentityError> =
            saap_prove(&[0x3Cu8; 64], 0b0000_0011, b"ctx", &sk, &[0x42u8; 32]);
        assert!(proof.is_ok(), "honest parameters must still produce a proof");

        // The variant the exhausted path returns, matching plp::Prover::
        // prove_identity and credential::prove.
        assert_eq!(
            IdentityError::from(crate::sampling::RejectionError::AllIterationsRejected),
            IdentityError::RejectionSamplingFailed
        );
    }
}