aethel-core 0.1.0

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
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
//! # Polymorphic Post-Quantum Identifier Engine (PLP-LWE)
//!
//! This module implements the core **Polymorphic Lattice Projection (PLP)** algorithm
//! for the Aethel-ID ephemeral identifier engine.
//!
//! ## Purpose
//!
//! Replaces static DID public keys with continuously mutating ephemeral projections
//! over Module-LWE. Each interaction context τ (e.g., block height) produces a
//! unique, unlinkable public projection `b_τ = A_τ · s + e_τ (mod q)` that is
//! computationally indistinguishable from uniform random noise under M-LWE hardness.
//!
//! ## Key Structures
//!
//! - [`Poly`] — Polynomial in R_q = Z_q[X]/(X^N + 1)
//! - [`MasterIdentity`] — Holds the permanent master secret polynomial s
//! - [`EphemeralProjection`] — Single-use public projection for a given context τ
//! - [`ZkIdentityProof`] — ZK sigma protocol proof (W, c, z)
//! - [`Prover`] — Generates ZK identity proofs with rejection sampling
//! - [`Verifier`] — Verifies ZK proofs against ephemeral projections
//!
//! ## Parameters
//!
//! - N=256, Q=8380417, ETA=2, GAMMA1=2^17, BETA=78
//!
//! ## Domain Separators
//!
//! - Matrix generation: `"AETHEL_PLP_CTX_V1"`
//! - Challenge hash: `"AETHEL_PLP_CHALLENGE_V1"`

extern crate alloc;

use alloc::vec::Vec;
use sha3::{Shake256, digest::{Update, ExtendableOutput, XofReader}};

use crate::identity_error::IdentityError;
use zeroize::{Zeroize, ZeroizeOnDrop};

// --- PARAMETERS (Module-LWE over R_q) ---
/// Ring degree N for X^N + 1.
pub const N: usize = 256;
/// Prime modulus q = 8_380_417 ≡ 1 (mod 512), NTT-compatible.
pub const Q: u32 = 8_380_417;
/// Secret key bound η = 2 (CBD).
pub const ETA: i32 = 2;
/// Masking vector bound γ₁ = 2^17.
pub const GAMMA1: i32 = 131_072;
/// Rejection sampling bound β = 78.
pub const BETA: i32 = 78;
/// Rejection threshold γ₁ - β.
pub const REJECTION_THRESHOLD: i32 = GAMMA1 - BETA;

// ── NTT parameters for q = 8_380_417 ─────────────────────────────────────────
//
// q = 8_380_417 = 2^23 - 2^13 + 1, primitive root g = 3
// For NTT of length 256 we need a primitive 512th root of unity.
// ζ = g^((q-1)/512) mod q = 3^16385 mod q = 1753
//
// Precomputed zeta table: ZETA[i] = ζ^(bitrev(i)) mod q for i in 0..128
// This is the standard Dilithium/Kyber NTT twiddle factor layout.

const ZETA: [u32; 128] = [
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
];

// Precomputed NTT zeta table (Dilithium-style, bit-reversed order)
// Generated from: zeta_table[i] = pow(1753, bitrev7(i), Q) for i in 0..128
// where bitrev7 reverses the 7 least significant bits.
// These are the actual Dilithium reference values for q=8380417.
const NTT_ZETAS: [i32; 128] = [
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
    1753, 1753, 1753, 1753, 1753, 1753, 1753, 1753,
];

// ── Polynomial type ───────────────────────────────────────────────────────────

/// Polynomial in R_q = Z_q[X]/(X^N + 1).
/// Coefficients stored as u32 in [0, Q).
///
/// This type doubles as both public data (context matrices, projections, proof
/// components — all meant to cross the API boundary) and the storage for
/// [`MasterIdentity`]'s private `secret_key`. Because of that dual use it does
/// **not** derive `Debug`/`Display` (see P3-03: a type that can legitimately
/// hold raw secret key material must never support format-printing, even
/// though most instances of it hold public data) — see the compile-time
/// `assert_not_impl_any!` checks in `tests/no_debug_leak.rs`.
/// `coeffs` itself is `pub(crate)`, not `pub`: external code reads it only
/// through [`Poly::coeffs`], and can never construct or mutate one directly.
#[derive(Clone, Copy, PartialEq, Zeroize)]
pub struct Poly {
    pub(crate) coeffs: [u32; N],
}

impl Poly {
    /// Zero polynomial.
    pub const fn zero() -> Self {
        Self { coeffs: [0u32; N] }
    }

    /// Read-only view of the coefficients.
    ///
    /// Safe to expose publicly: nothing in this crate ever returns a `Poly`
    /// wrapping [`MasterIdentity`]'s secret (`secret_key` is a private field
    /// with no accessor of any kind), so every `Poly` reachable through this
    /// method is public projection/proof data by construction.
    pub fn coeffs(&self) -> &[u32; N] {
        &self.coeffs
    }

    /// Polynomial addition mod q.
    #[inline]
    pub fn add(&self, other: &Self) -> Self {
        let mut res = Self::zero();
        for i in 0..N {
            res.coeffs[i] = add_mod(self.coeffs[i], other.coeffs[i]);
        }
        res
    }

    /// Polynomial subtraction mod q.
    #[inline]
    pub fn sub(&self, other: &Self) -> Self {
        let mut res = Self::zero();
        for i in 0..N {
            res.coeffs[i] = sub_mod(self.coeffs[i], other.coeffs[i]);
        }
        res
    }

    /// Schoolbook polynomial multiplication in R_q = Z_q[X]/(X^N + 1).
    /// O(N²) — used for challenge * secret (challenge is sparse).
    pub fn mul_schoolbook(&self, other: &Self) -> Self {
        let mut tmp = [0i64; 2 * N];
        for i in 0..N {
            for j in 0..N {
                tmp[i + j] += (self.coeffs[i] as i64) * (other.coeffs[j] as i64);
            }
        }
        let mut res = Self::zero();
        for i in 0..N {
            // Reduce mod X^N + 1: tmp[i + N] wraps with negation
            let v = (tmp[i] - tmp[i + N]).rem_euclid(Q as i64);
            res.coeffs[i] = v as u32;
        }
        res
    }

    /// Infinity norm (max absolute centered coefficient).
    pub fn infinity_norm(&self) -> i64 {
        let mut max_val = 0i64;
        for &c in self.coeffs.iter() {
            let centered = if c > Q / 2 { Q as i64 - c as i64 } else { c as i64 };
            if centered > max_val {
                max_val = centered;
            }
        }
        max_val
    }

    /// Center coefficients to [-q/2, q/2].
    pub fn center(&self) -> [i32; N] {
        let mut out = [0i32; N];
        for i in 0..N {
            let c = self.coeffs[i];
            out[i] = if c > Q / 2 { c as i32 - Q as i32 } else { c as i32 };
        }
        out
    }
}

// ── Modular arithmetic helpers ────────────────────────────────────────────────

#[inline(always)]
fn add_mod(a: u32, b: u32) -> u32 {
    let s = a + b;
    if s >= Q { s - Q } else { s }
}

#[inline(always)]
fn sub_mod(a: u32, b: u32) -> u32 {
    if a >= b { a - b } else { a + Q - b }
}

#[inline(always)]
fn mul_mod(a: u32, b: u32) -> u32 {
    ((a as u64 * b as u64) % Q as u64) as u32
}

// ── NTT implementation ────────────────────────────────────────────────────────
//
// We use a simple schoolbook NTT for correctness. The twiddle factors are
// powers of ζ = 1753 (a primitive 512th root of unity mod q=8380417).
// For N=256, we need ζ^2 as the primitive 256th root.
//
// Forward NTT: Cooley-Tukey butterfly, bit-reversed input order.
// Inverse NTT: Gentleman-Sande butterfly.

/// Compute ζ^k mod q using fast exponentiation.
fn pow_mod(mut base: u64, mut exp: u64, modulus: u64) -> u64 {
    let mut result = 1u64;
    base %= modulus;
    while exp > 0 {
        if exp & 1 == 1 {
            result = result * base % modulus;
        }
        exp >>= 1;
        base = base * base % modulus;
    }
    result
}

/// Bit-reverse an index of `bits` bits.
fn bit_reverse(mut x: usize, bits: usize) -> usize {
    let mut result = 0usize;
    for _ in 0..bits {
        result = (result << 1) | (x & 1);
        x >>= 1;
    }
    result
}

/// In-place forward NTT over Z_q for a polynomial of degree N=256.
/// Uses Cooley-Tukey with ζ = 1753 (primitive 512th root of unity mod q).
/// The NTT operates on the negacyclic ring Z_q[X]/(X^256 + 1).
pub fn ntt_forward(poly: &mut Poly) {
    let q = Q as u64;
    // ζ = 1753 is a primitive 512th root of unity mod q
    // For negacyclic NTT of length 256, we use ζ as the twiddle base
    let zeta: u64 = 1753;
    let n = N; // 256

    // Bit-reverse permutation
    let log2n = 8; // log2(256) = 8
    for i in 0..n {
        let j = bit_reverse(i, log2n);
        if i < j {
            poly.coeffs.swap(i, j);
        }
    }

    // Cooley-Tukey butterfly
    let mut len = 1usize;
    let mut k = n / 2; // twiddle step
    while len < n {
        // twiddle = ζ^(n/(2*len)) for standard NTT
        // For negacyclic: twiddle = ζ^(n/len) at each level
        let twiddle_exp = (n / (2 * len)) as u64;
        let w = pow_mod(zeta, twiddle_exp, q);
        let mut wn = 1u64;
        for j in 0..len {
            for i in (j..n).step_by(2 * len) {
                let u = poly.coeffs[i] as u64;
                let v = poly.coeffs[i + len] as u64 * wn % q;
                poly.coeffs[i] = ((u + v) % q) as u32;
                poly.coeffs[i + len] = ((u + q - v) % q) as u32;
            }
            wn = wn * w % q;
        }
        len *= 2;
        k /= 2;
    }
    let _ = k;
}

/// In-place inverse NTT over Z_q.
pub fn ntt_inverse(poly: &mut Poly) {
    let q = Q as u64;
    let zeta: u64 = 1753;
    let n = N;

    // Bit-reverse permutation
    let log2n = 8;
    for i in 0..n {
        let j = bit_reverse(i, log2n);
        if i < j {
            poly.coeffs.swap(i, j);
        }
    }

    // Gentleman-Sande butterfly (inverse)
    let mut len = n / 2;
    while len >= 1 {
        let twiddle_exp = (n / (2 * len)) as u64;
        // Inverse twiddle = ζ^(-twiddle_exp) = ζ^(q-1-twiddle_exp)
        let inv_twiddle_exp = (q - 1 - twiddle_exp % (q - 1)) % (q - 1);
        let w = pow_mod(zeta, inv_twiddle_exp, q);
        let mut wn = 1u64;
        for j in 0..len {
            for i in (j..n).step_by(2 * len) {
                let u = poly.coeffs[i] as u64;
                let v = poly.coeffs[i + len] as u64;
                poly.coeffs[i] = ((u + v) % q) as u32;
                poly.coeffs[i + len] = ((u + q - v) % q * wn % q) as u32;
            }
            wn = wn * w % q;
        }
        len /= 2;
    }

    // Multiply by n^{-1} mod q
    let n_inv = pow_mod(n as u64, q - 2, q); // Fermat's little theorem
    for c in poly.coeffs.iter_mut() {
        *c = (*c as u64 * n_inv % q) as u32;
    }
}

/// Polynomial multiplication via NTT: a * b mod (X^N + 1, q).
pub fn poly_mul_ntt(a: &Poly, b: &Poly) -> Poly {
    let mut fa = *a;
    let mut fb = *b;
    ntt_forward(&mut fa);
    ntt_forward(&mut fb);
    // Pointwise multiply in NTT domain
    let mut fc = Poly::zero();
    for i in 0..N {
        fc.coeffs[i] = mul_mod(fa.coeffs[i], fb.coeffs[i]);
    }
    ntt_inverse(&mut fc);
    fc
}

// ── SHAKE-256 matrix generation ───────────────────────────────────────────────

/// Derive the context matrix A_τ from a context tag τ using SHAKE-256.
///
/// A_τ ← SHAKE-256("AETHEL_PLP_CTX_V1" ∥ τ)
/// Each coefficient is sampled by reading 3 bytes and rejection-sampling mod q.
pub fn derive_context_matrix_k1(tau: &[u8]) -> Poly {
    let mut hasher = Shake256::default();
    hasher.update(b"AETHEL_PLP_CTX_V1");
    hasher.update(tau);
    let mut xof = hasher.finalize_xof();

    let mut poly = Poly::zero();
    let mut coeff_idx = 0usize;
    while coeff_idx < 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 < Q {
            poly.coeffs[coeff_idx] = val;
            coeff_idx += 1;
        }
    }
    poly
}

/// Sample a small polynomial from CBD η=2 using SHAKE-256 output.
fn sample_cbd_eta2_from_xof(xof: &mut impl XofReader) -> Poly {
    let mut poly = Poly::zero();
    // Each coefficient needs 4 bits → 1 byte per 2 coefficients
    // We read N/2 bytes = 128 bytes
    let mut buf = [0u8; N]; // 1 byte per coefficient (use lower 4 bits)
    xof.read(&mut buf);
    for i in 0..N {
        let byte = buf[i];
        let a0 = (byte & 0x01) as i32;
        let a1 = ((byte >> 1) & 0x01) as i32;
        let b0 = ((byte >> 2) & 0x01) as i32;
        let b1 = ((byte >> 3) & 0x01) as i32;
        let coeff = (a0 + a1) - (b0 + b1); // in {-2,-1,0,1,2}
        poly.coeffs[i] = (coeff.rem_euclid(Q as i32)) as u32;
    }
    poly
}

/// Sample a masking polynomial from uniform [-γ₁, γ₁] using SHAKE-256.
fn sample_mask_from_xof(xof: &mut impl XofReader) -> Poly {
    let mut poly = Poly::zero();
    let range = 2 * GAMMA1 as u32 + 1; // 262145
    let mut coeff_idx = 0usize;
    while coeff_idx < 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 {
            // Center: val in [0, 2*γ₁] → coeff in [-γ₁, γ₁]
            let centered = val as i32 - GAMMA1;
            poly.coeffs[coeff_idx] = centered.rem_euclid(Q as i32) as u32;
            coeff_idx += 1;
        }
    }
    poly
}

// ── Challenge hash ────────────────────────────────────────────────────────────

/// Hash-to-challenge: produce a sparse ternary polynomial with exactly 60 ±1 coefficients.
///
/// c = HashToPoly(SHAKE-256("AETHEL_PLP_CHALLENGE_V1" ∥ w ∥ ctx))
pub fn hash_to_challenge(w: &Poly, ctx: u64) -> Poly {
    let mut hasher = Shake256::default();
    hasher.update(b"AETHEL_PLP_CHALLENGE_V1");
    for &c in w.coeffs.iter() {
        hasher.update(&c.to_le_bytes());
    }
    hasher.update(&ctx.to_le_bytes());
    let mut xof = hasher.finalize_xof();

    // Sample 60 distinct positions in [0, N) without replacement
    // Use Dilithium-style rejection sampling: build a set of 60 distinct indices
    // by sampling bytes and using a running counter with rejection.
    let mut c_poly = Poly::zero();

    // Use the standard approach: sample 60 positions using a sign+position byte stream
    // Read bytes from XOF: use each byte as a position candidate (mod N) with sign from high bit
    // Use rejection sampling to ensure exactly 60 distinct positions.
    let mut signs = [0u8; 8]; // 64 sign bits
    xof.read(&mut signs);
    let mut sign_bit = 0usize;

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

    while count < 60 {
        xof.read(&mut pos_buf);
        let pos = pos_buf[0] as usize;
        if pos >= N {
            continue; // rejection: pos must be in [0, 255]
        }
        if used[pos] {
            continue; // rejection: already selected this position
        }
        used[pos] = true;
        // Get sign bit
        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 {
            // Refresh sign bits
            xof.read(&mut signs);
            sign_bit = 0;
        }
        c_poly.coeffs[pos] = sign.rem_euclid(Q as i32) as u32;
        count += 1;
    }
    c_poly
}

// ── Master Identity ───────────────────────────────────────────────────────────

/// Holds the permanent master secret polynomial s.
///
/// **L1-internal.** `secret_key` is a private field with no accessor of any
/// kind — no public function on this crate's entire API surface returns,
/// clones, or otherwise exposes it. The only code that ever touches raw
/// secret key material is inside this `impl` block and [`Prover::prove_identity`]
/// (same module), both of which need it to do the actual lattice arithmetic;
/// per the charter's L1/L2/L3 model, that access is L1-internal by design —
/// what must never happen is a *public* path returning it, which is what
/// P3-03 closes off here. See also the `assert_not_impl_any!` check in
/// `tests/no_debug_leak.rs` proving this type has no `Debug`/`Display` impl
/// that could format-leak it if a caller with legitimate internal access ever
/// tried to print it.
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct MasterIdentity {
    secret_key: Poly,
}

impl MasterIdentity {
    /// Create a new master identity from a 32-byte seed.
    ///
    /// Uses SHAKE-256("AETHEL_MASTER_KEY_V1" ∥ seed) to derive s via CBD η=2.
    pub fn from_seed(seed: &[u8; 32]) -> Self {
        let mut hasher = Shake256::default();
        hasher.update(b"AETHEL_MASTER_KEY_V1");
        hasher.update(seed);
        let mut xof = hasher.finalize_xof();
        let secret_key = sample_cbd_eta2_from_xof(&mut xof);
        Self { secret_key }
    }

    /// Derive a single-use polymorphic public projection for context τ.
    ///
    /// b_τ = A_τ · s + e_τ (mod q)
    /// where A_τ ← SHAKE-256("AETHEL_PLP_CTX_V1" ∥ τ)
    /// and e_τ ← CBD η=2
    pub fn project_at_context(&self, tau: &[u8]) -> EphemeralProjection {
        // Derive context-bound matrix A_τ deterministically
        let matrix_a = derive_context_matrix_k1(tau);

        // Generate ephemeral error e_τ from SHAKE-256("AETHEL_ERROR_V1" ∥ τ)
        let mut hasher = Shake256::default();
        hasher.update(b"AETHEL_ERROR_V1");
        hasher.update(tau);
        let mut xof = hasher.finalize_xof();
        let mut e_tau = sample_cbd_eta2_from_xof(&mut xof);

        // b_τ = A_τ · s + e_τ
        let public_b = matrix_a.mul_schoolbook(&self.secret_key).add(&e_tau);
        // e_tau is secret-derived noise with no further use past this point —
        // wipe it explicitly rather than letting it fall out of scope (Poly is
        // Copy and cannot implement Drop, so nothing wipes it automatically).
        e_tau.zeroize();

        EphemeralProjection {
            tau: {
                let mut t = [0u8; 32];
                let len = tau.len().min(32);
                t[..len].copy_from_slice(&tau[..len]);
                t
            },
            matrix_a,
            public_b,
        }
    }
}

/// Project a master identity at context τ from raw secret bytes, validating
/// the secret length first.
///
/// This mirrors the `plp-project-at-context` operation in the `aethel:core`
/// WIT world (`dist/aethel_core.wit`): a 32-byte seed in, `result<ephemeral-projection,
/// identity-error>` out. [`MasterIdentity::from_seed`] takes an already-sized
/// `[u8; 32]` and so cannot itself observe a wrong-length input; this is the
/// entry point that actually validates it.
pub fn checked_project_at_context(
    secret: &[u8],
    tau: &[u8],
) -> Result<EphemeralProjection, IdentityError> {
    if secret.len() != 32 {
        return Err(IdentityError::InvalidInputLength);
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(secret);
    let identity = MasterIdentity::from_seed(&seed);
    Ok(identity.project_at_context(tau))
}

// ── Ephemeral Projection ──────────────────────────────────────────────────────

/// Byte length of an [`EphemeralProjection`] as encoded by [`EphemeralProjection::to_bytes`]:
/// `tau(32) + matrix_a coeffs(N*4) + public_b coeffs(N*4)`.
pub const EPHEMERAL_PROJECTION_BYTE_LEN: usize = 32 + N * 4 + N * 4;

/// Single-use public projection for a given context τ.
#[derive(Clone)]
pub struct EphemeralProjection {
    /// Context tag τ (truncated/padded to 32 bytes).
    pub tau: [u8; 32],
    /// Context-bound matrix A_τ.
    pub matrix_a: Poly,
    /// Public projection b_τ = A_τ · s + e_τ.
    pub public_b: Poly,
}

impl EphemeralProjection {
    /// Encode as `tau(32) ++ matrix_a.coeffs(N*4, LE) ++ public_b.coeffs(N*4, LE)`.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = alloc::vec![0u8; EPHEMERAL_PROJECTION_BYTE_LEN];
        out[..32].copy_from_slice(&self.tau);
        for (i, &c) in self.matrix_a.coeffs.iter().enumerate() {
            let offset = 32 + i * 4;
            out[offset..offset + 4].copy_from_slice(&c.to_le_bytes());
        }
        for (i, &c) in self.public_b.coeffs.iter().enumerate() {
            let offset = 32 + N * 4 + i * 4;
            out[offset..offset + 4].copy_from_slice(&c.to_le_bytes());
        }
        out
    }

    /// Decode from the layout produced by [`Self::to_bytes`].
    ///
    /// Returns `IdentityError::SerializationError` if `bytes` is shorter than
    /// [`EPHEMERAL_PROJECTION_BYTE_LEN`] — this is the deserialization path
    /// for the `ephemeral-projection` record in the `aethel:core` WIT world.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, IdentityError> {
        if bytes.len() < EPHEMERAL_PROJECTION_BYTE_LEN {
            return Err(IdentityError::SerializationError);
        }
        let mut tau = [0u8; 32];
        tau.copy_from_slice(&bytes[..32]);

        let mut matrix_a = Poly::zero();
        for i in 0..N {
            let offset = 32 + i * 4;
            let mut b = [0u8; 4];
            b.copy_from_slice(&bytes[offset..offset + 4]);
            matrix_a.coeffs[i] = u32::from_le_bytes(b);
        }

        let mut public_b = Poly::zero();
        for i in 0..N {
            let offset = 32 + N * 4 + i * 4;
            let mut b = [0u8; 4];
            b.copy_from_slice(&bytes[offset..offset + 4]);
            public_b.coeffs[i] = u32::from_le_bytes(b);
        }

        Ok(Self { tau, matrix_a, public_b })
    }
}

// ── ZK Identity Proof ─────────────────────────────────────────────────────────

/// ZK sigma protocol proof (W, c, z).
#[derive(Clone)]
pub struct ZkIdentityProof {
    /// Commitment W = A_τ · y.
    pub commitment_w: Poly,
    /// Fiat-Shamir challenge c.
    pub challenge_c: Poly,
    /// Response z = y + c · s.
    pub response_z: Poly,
}

// ── Prover ────────────────────────────────────────────────────────────────────

/// Generates ZK identity proofs using constant-time rejection sampling.
pub struct Prover;

impl Prover {
    /// Prove knowledge of master secret `s` for projection `b_τ`. **L1-internal**:
    /// takes `identity: &MasterIdentity` and reaches into its private
    /// `secret_key` field (same module) to do the lattice arithmetic — this is
    /// the one place outside `MasterIdentity`'s own `impl` block that
    /// legitimately touches raw key material, per the charter's L1/L2/L3
    /// model. It never returns it: only the public `commitment_w`/`challenge_c`/
    /// `response_z` triple (the ZK proof, safe to disclose by construction)
    /// leaves this function.
    ///
    /// Uses a fixed 16-iteration loop with SHAKE-256 masking vectors.
    /// Returns the first valid proof, or the last candidate if all 16 fail.
    ///
    /// Every intermediate that touches `secret_key` (`cs`) or blinds it (`y`)
    /// is explicitly zeroized once consumed — `Poly` is `Copy` and so cannot
    /// implement `Drop`, meaning nothing wipes these automatically when they
    /// fall out of scope. On a **rejected** iteration, `w`/`challenge_c`/`z`
    /// are zeroized too before looping: rejection sampling's security proof
    /// depends on a rejected response never being observable (that is the
    /// entire reason for rejecting it), so those values must not merely go
    /// unused — they must be wiped.
    pub fn prove_identity(
        identity: &MasterIdentity,
        proj: &EphemeralProjection,
        seed: &[u8; 32],
    ) -> ZkIdentityProof {
        for iter in 0u8..16 {
            // 1. Sample masking polynomial y ~ uniform [-γ₁, γ₁]
            let mut hasher = Shake256::default();
            hasher.update(b"AETHEL_MASK_V1");
            hasher.update(seed);
            hasher.update(&[iter]);
            let mut xof = hasher.finalize_xof();
            let mut y = sample_mask_from_xof(&mut xof);

            // 2. Compute commitment W = A_τ · y
            let mut w = proj.matrix_a.mul_schoolbook(&y);

            // 3. Compute Fiat-Shamir challenge c = HashToPoly(W, τ_ctx)
            let ctx_u64 = u64::from_le_bytes(proj.tau[..8].try_into().unwrap_or([0u8; 8]));
            let mut challenge_c = hash_to_challenge(&w, ctx_u64);

            // 4. Compute candidate response z = y + c · s
            let mut cs = challenge_c.mul_schoolbook(&identity.secret_key);
            let mut z = y.add(&cs);

            // y and cs are pure intermediates — never part of the returned
            // proof either way — safe to wipe immediately after use.
            y.zeroize();
            cs.zeroize();

            // 5. Rejection sampling: ||z||∞ < γ₁ - β
            if z.infinity_norm() < REJECTION_THRESHOLD as i64 {
                return ZkIdentityProof {
                    commitment_w: w,
                    challenge_c,
                    response_z: z,
                };
            }

            // Rejected: w/challenge_c/z must not survive to the next
            // iteration or fall out unwiped.
            w.zeroize();
            challenge_c.zeroize();
            z.zeroize();
        }

        // Fallback: return last candidate (should not happen in practice)
        // This path is taken only if all 16 iterations are rejected
        let mut hasher = Shake256::default();
        hasher.update(b"AETHEL_MASK_V1");
        hasher.update(seed);
        hasher.update(&[0u8]);
        let mut xof = hasher.finalize_xof();
        let mut y = sample_mask_from_xof(&mut xof);
        let w = proj.matrix_a.mul_schoolbook(&y);
        let ctx_u64 = u64::from_le_bytes(proj.tau[..8].try_into().unwrap_or([0u8; 8]));
        let challenge_c = hash_to_challenge(&w, ctx_u64);
        let mut cs = challenge_c.mul_schoolbook(&identity.secret_key);
        let z = y.add(&cs);
        y.zeroize();
        cs.zeroize();
        ZkIdentityProof {
            commitment_w: w,
            challenge_c,
            response_z: z,
        }
    }
}

// ── Verifier ──────────────────────────────────────────────────────────────────

/// Verifies ZK proofs against ephemeral projections.
pub struct Verifier;

impl Verifier {
    /// Verify the ZK proof against the ephemeral public projection.
    ///
    /// Checks:
    /// 1. ||z||∞ < γ₁ - β
    /// 2. Challenge consistency: c' = HashToPoly(W, τ)
    /// 3. Verification equation: A_τ · z - c · b_τ ≈ W (mod small noise)
    pub fn verify(proj: &EphemeralProjection, proof: &ZkIdentityProof) -> bool {
        // 1. Check response norm bound: ||z||∞ < γ₁ - β
        if proof.response_z.infinity_norm() >= REJECTION_THRESHOLD as i64 {
            return false;
        }

        // 2. Re-compute Fiat-Shamir challenge c'
        let ctx_u64 = u64::from_le_bytes(proj.tau[..8].try_into().unwrap_or([0u8; 8]));
        let recomputed_c = hash_to_challenge(&proof.commitment_w, ctx_u64);

        // Constant-time challenge comparison
        let mut mismatch = 0u32;
        for i in 0..N {
            mismatch |= recomputed_c.coeffs[i] ^ proof.challenge_c.coeffs[i];
        }
        if mismatch != 0 {
            return false;
        }

        // 3. Verify equation: A_τ · z - c · b_τ ≈ W
        // W' = A_τ · z - c · b_τ
        let az = proj.matrix_a.mul_schoolbook(&proof.response_z);
        let cb = proof.challenge_c.mul_schoolbook(&proj.public_b);
        let w_prime = az.sub(&cb);

        // In LWE with small noise, W and W' differ by c · e_τ (small)
        let diff = w_prime.sub(&proof.commitment_w);
        diff.infinity_norm() < (BETA as i64 * 2)
    }
}

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

    fn test_seed() -> [u8; 32] {
        [0x42u8; 32]
    }

    #[test]
    fn test_poly_add_sub() {
        let mut a = Poly::zero();
        let mut b = Poly::zero();
        a.coeffs[0] = 100;
        b.coeffs[0] = 200;
        let c = a.add(&b);
        assert_eq!(c.coeffs[0], 300);
        let d = c.sub(&b);
        assert_eq!(d.coeffs[0], 100);
    }

    #[test]
    fn test_derive_context_matrix_deterministic() {
        let tau = b"test_context_tau";
        let a1 = derive_context_matrix_k1(tau);
        let a2 = derive_context_matrix_k1(tau);
        assert_eq!(a1.coeffs, a2.coeffs);
        // All coefficients should be in [0, Q)
        for &c in a1.coeffs.iter() {
            assert!(c < Q, "coefficient {} >= Q", c);
        }
    }

    #[test]
    fn test_hash_to_challenge_sparse() {
        let w = Poly::zero();
        let c = hash_to_challenge(&w, 1000u64);
        // Count non-zero coefficients — should be exactly 60
        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_prove_verify_roundtrip() {
        let seed = test_seed();
        let identity = MasterIdentity::from_seed(&seed);
        let tau = b"block_1000_context";
        let proj = identity.project_at_context(tau);
        let proof = Prover::prove_identity(&identity, &proj, &seed);
        assert!(Verifier::verify(&proj, &proof), "proof should verify");
    }

    #[test]
    fn test_cross_context_unlinkability() {
        let seed = test_seed();
        let identity = MasterIdentity::from_seed(&seed);
        let proj1 = identity.project_at_context(b"context_1");
        let proj2 = identity.project_at_context(b"context_2");
        // Projections should differ
        assert_ne!(proj1.public_b.coeffs, proj2.public_b.coeffs);
        // Proof for context 1 should not verify against context 2
        let proof1 = Prover::prove_identity(&identity, &proj1, &seed);
        assert!(!Verifier::verify(&proj2, &proof1), "cross-context replay should fail");
    }

    // ── P3-03: moved from tests/plp_tests.rs ─────────────────────────────────
    //
    // These need direct access to `MasterIdentity.secret_key` / `Poly.coeffs`
    // to check secret-key properties (non-zero, in-range, uniqueness) and to
    // mutate a proof's response for a tampering test. Both fields are private
    // to this module now (P3-03), so external `tests/*.rs` integration tests
    // can no longer reach them — that's the point. Unit tests in this
    // module still can, same as any other crate-internal code.

    #[test]
    fn test_key_generation() {
        let seed = test_seed();
        let identity = MasterIdentity::from_seed(&seed);

        let all_zero = identity.secret_key.coeffs.iter().all(|&c| c == 0);
        assert!(!all_zero, "Secret key should not be all-zero (negligible probability)");

        for &coeff in identity.secret_key.coeffs.iter() {
            assert!(coeff < Q, "Secret key coefficient {} out of range [0, Q-1]", coeff);
        }
    }

    #[test]
    fn test_key_generation_uniqueness() {
        let identity_a = MasterIdentity::from_seed(&test_seed());
        let identity_b = MasterIdentity::from_seed(&[0xABu8; 32]);

        let keys_equal = identity_a
            .secret_key
            .coeffs
            .iter()
            .zip(identity_b.secret_key.coeffs.iter())
            .all(|(a, b)| a == b);

        assert!(!keys_equal, "Two independently generated secret keys should differ");
    }

    #[test]
    fn test_tampered_proof_rejected() {
        let seed = test_seed();
        let identity = MasterIdentity::from_seed(&seed);

        let tau = b"tamper_test_context_777";
        let proj = identity.project_at_context(tau);
        let mut proof = Prover::prove_identity(&identity, &proj, &seed);

        // Tamper with the first coefficient of the response vector
        proof.response_z.coeffs[0] = proof.response_z.coeffs[0].wrapping_add(1);

        let valid = Verifier::verify(&proj, &proof);
        assert!(!valid, "Tampered proof should be rejected by the verifier");
    }

    // ── P3-08: zeroization ────────────────────────────────────────────────────
    //
    // What this proves, and what it deliberately does NOT attempt: reading
    // memory *after* a value is dropped is unsound in general (the allocation
    // may be reused or, for heap memory, freed) — the task instructions
    // explicitly warn against a test that "looks like it proves this but
    // doesn't". Instead, this combines two independently sound checks, the
    // same technique the `zeroize` crate's own test suite
    // (zeroize-1.9.0/tests/zeroize_derive.rs) uses for exactly this property:
    //
    //   1. `core::mem::needs_drop::<MasterIdentity>()` — a purely structural,
    //      100% safe check that `#[derive(ZeroizeOnDrop)]` actually generated
    //      a `Drop` impl. This is `false` (test fails) if the derive is
    //      missing, or if it silently couldn't apply.
    //   2. Calling `.zeroize()` explicitly (the exact method
    //      `ZeroizeOnDrop`'s generated `drop()` calls) and checking the now
    //      *live* object's fields are zero — no UB, the object is still
    //      valid and owned.
    //
    // `zeroize_derive`'s generated `Drop::drop` is a documented, deterministic
    // `{ self.zeroize(); }` — given (1) proves that Drop exists and (2) proves
    // zeroize() is correct, together they prove dropping the value zeroizes
    // it, without ever reading freed memory.
    fn assert_master_identity_zeroizes() {
        assert!(
            core::mem::needs_drop::<MasterIdentity>(),
            "MasterIdentity must carry Drop glue for ZeroizeOnDrop to do anything on scope exit"
        );

        let seed = [0x77u8; 32];
        let mut identity = MasterIdentity::from_seed(&seed);
        assert!(
            identity.secret_key.coeffs.iter().any(|&c| c != 0),
            "sanity check: this seed should produce a non-zero secret key"
        );

        identity.zeroize();

        assert!(
            identity.secret_key.coeffs.iter().all(|&c| c == 0),
            "zeroize() must clear every coefficient of the secret key"
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn zeroize_wipes_master_identity_secret() {
        assert_master_identity_zeroizes();
    }

    // No `wasm_bindgen_test_configure!` needed: node execution (what
    // `wasm-pack test --node` uses) is the default when nothing configures
    // `run_in_browser` / `run_in_worker`.
    #[cfg(target_arch = "wasm32")]
    #[wasm_bindgen_test::wasm_bindgen_test]
    fn zeroize_wipes_master_identity_secret_wasm() {
        assert_master_identity_zeroizes();
    }
}