Skip to main content

logicaffeine_system/
aead.rs

1//! ChaCha20-Poly1305 AEAD (RFC 8439) — the symmetric seal that closes the post-quantum channel:
2//! an ML-KEM-768 handshake establishes the shared secret, HKDF derives this 32-byte key, and every
3//! wire message is sealed here. ChaCha20 is a pure `Word32` ARX cipher (the same primitive the
4//! `assets/std/crypto.lg` `chacha20Block` ships in Logos); Poly1305 is the one-time authenticator in
5//! constant-time 5×26-bit limbs (no bignum). Verified against the RFC 8439 §2.4.2 / §2.5.2 / §2.8.2
6//! known-answer vectors. The tag compare is constant-time.
7
8use crate::kernel_args as args;
9
10// ── ChaCha20 (RFC 8439 §2.3–2.4) ───────────────────────────────────────────────────────────────
11
12#[inline]
13fn qr(s: &mut [u32; 16], a: usize, b: usize, c: usize, d: usize) {
14    s[a] = s[a].wrapping_add(s[b]);
15    s[d] = (s[d] ^ s[a]).rotate_left(16);
16    s[c] = s[c].wrapping_add(s[d]);
17    s[b] = (s[b] ^ s[c]).rotate_left(12);
18    s[a] = s[a].wrapping_add(s[b]);
19    s[d] = (s[d] ^ s[a]).rotate_left(8);
20    s[c] = s[c].wrapping_add(s[d]);
21    s[b] = (s[b] ^ s[c]).rotate_left(7);
22}
23
24fn chacha20_block(key: &[u32; 8], counter: u32, nonce: &[u32; 3]) -> [u32; 16] {
25    let mut state = [
26        0x6170_7865,
27        0x3320_646e,
28        0x7962_2d32,
29        0x6b20_6574,
30        key[0],
31        key[1],
32        key[2],
33        key[3],
34        key[4],
35        key[5],
36        key[6],
37        key[7],
38        counter,
39        nonce[0],
40        nonce[1],
41        nonce[2],
42    ];
43    let mut w = state;
44    for _ in 0..10 {
45        qr(&mut w, 0, 4, 8, 12);
46        qr(&mut w, 1, 5, 9, 13);
47        qr(&mut w, 2, 6, 10, 14);
48        qr(&mut w, 3, 7, 11, 15);
49        qr(&mut w, 0, 5, 10, 15);
50        qr(&mut w, 1, 6, 11, 12);
51        qr(&mut w, 2, 7, 8, 13);
52        qr(&mut w, 3, 4, 9, 14);
53    }
54    for i in 0..16 {
55        state[i] = w[i].wrapping_add(state[i]);
56    }
57    state
58}
59
60fn le_u32x8(b: &[u8; 32]) -> [u32; 8] {
61    std::array::from_fn(|i| u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap()))
62}
63fn le_u32x3(b: &[u8; 12]) -> [u32; 3] {
64    std::array::from_fn(|i| u32::from_le_bytes(b[i * 4..i * 4 + 4].try_into().unwrap()))
65}
66
67/// ChaCha20 keystream XOR (RFC 8439 §2.4): `data ⊕ ChaCha20(key, counter‖nonce)`. AVX2 (8 blocks at
68/// a time) when available, else scalar — bit-identical.
69pub fn chacha20_xor(key: &[u8; 32], nonce: &[u8; 12], counter: u32, data: &[u8]) -> Vec<u8> {
70    #[cfg(target_arch = "x86_64")]
71    {
72        // The 8-block AVX2 path computes 512 B of keystream at once, so it only pays off past a few
73        // blocks; below that the scalar single-block path avoids the wasted work.
74        if data.len() >= 256 && std::is_x86_feature_detected!("avx2") {
75            return unsafe { chacha20_xor_avx2(&le_u32x8(key), &le_u32x3(nonce), counter, data) };
76        }
77    }
78    chacha20_xor_scalar(key, nonce, counter, data)
79}
80
81fn chacha20_xor_scalar(key: &[u8; 32], nonce: &[u8; 12], counter: u32, data: &[u8]) -> Vec<u8> {
82    let kw = le_u32x8(key);
83    let nw = le_u32x3(nonce);
84    let mut out = Vec::with_capacity(data.len());
85    for (bi, chunk) in data.chunks(64).enumerate() {
86        let block = chacha20_block(&kw, counter.wrapping_add(bi as u32), &nw);
87        let mut ks = [0u8; 64];
88        for i in 0..16 {
89            ks[i * 4..i * 4 + 4].copy_from_slice(&block[i].to_le_bytes());
90        }
91        for (j, &b) in chunk.iter().enumerate() {
92            out.push(b ^ ks[j]);
93        }
94    }
95    out
96}
97
98/// AVX2 ChaCha20: 8 blocks computed in parallel (each `__m256i` lane is one block's word at a fixed
99/// index), the keystream serialized and XORed. The `<512`-byte tail falls back to the scalar block.
100#[cfg(target_arch = "x86_64")]
101#[target_feature(enable = "avx2")]
102unsafe fn chacha20_xor_avx2(
103    key: &[u32; 8],
104    nonce: &[u32; 3],
105    counter: u32,
106    data: &[u8],
107) -> Vec<u8> {
108    use std::arch::x86_64::*;
109    let rot16 = _mm256_setr_epi8(
110        2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13, 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9,
111        14, 15, 12, 13,
112    );
113    let rot8 = _mm256_setr_epi8(
114        3, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14, 3, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10,
115        15, 12, 13, 14,
116    );
117    #[inline(always)]
118    unsafe fn rotl12(x: std::arch::x86_64::__m256i) -> std::arch::x86_64::__m256i {
119        use std::arch::x86_64::*;
120        _mm256_or_si256(_mm256_slli_epi32::<12>(x), _mm256_srli_epi32::<20>(x))
121    }
122    #[inline(always)]
123    unsafe fn rotl7(x: std::arch::x86_64::__m256i) -> std::arch::x86_64::__m256i {
124        use std::arch::x86_64::*;
125        _mm256_or_si256(_mm256_slli_epi32::<7>(x), _mm256_srli_epi32::<25>(x))
126    }
127
128    let mut out = Vec::with_capacity(data.len());
129    let lane_ctr = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7);
130    let mut off = 0usize;
131    let mut base = counter;
132    while off < data.len() {
133        let init: [__m256i; 16] = [
134            _mm256_set1_epi32(0x6170_7865u32 as i32),
135            _mm256_set1_epi32(0x3320_646eu32 as i32),
136            _mm256_set1_epi32(0x7962_2d32u32 as i32),
137            _mm256_set1_epi32(0x6b20_6574u32 as i32),
138            _mm256_set1_epi32(key[0] as i32),
139            _mm256_set1_epi32(key[1] as i32),
140            _mm256_set1_epi32(key[2] as i32),
141            _mm256_set1_epi32(key[3] as i32),
142            _mm256_set1_epi32(key[4] as i32),
143            _mm256_set1_epi32(key[5] as i32),
144            _mm256_set1_epi32(key[6] as i32),
145            _mm256_set1_epi32(key[7] as i32),
146            _mm256_add_epi32(_mm256_set1_epi32(base as i32), lane_ctr),
147            _mm256_set1_epi32(nonce[0] as i32),
148            _mm256_set1_epi32(nonce[1] as i32),
149            _mm256_set1_epi32(nonce[2] as i32),
150        ];
151        let mut v = init;
152        macro_rules! qr {
153            ($a:tt, $b:tt, $c:tt, $d:tt) => {
154                v[$a] = _mm256_add_epi32(v[$a], v[$b]);
155                v[$d] = _mm256_shuffle_epi8(_mm256_xor_si256(v[$d], v[$a]), rot16);
156                v[$c] = _mm256_add_epi32(v[$c], v[$d]);
157                v[$b] = rotl12(_mm256_xor_si256(v[$b], v[$c]));
158                v[$a] = _mm256_add_epi32(v[$a], v[$b]);
159                v[$d] = _mm256_shuffle_epi8(_mm256_xor_si256(v[$d], v[$a]), rot8);
160                v[$c] = _mm256_add_epi32(v[$c], v[$d]);
161                v[$b] = rotl7(_mm256_xor_si256(v[$b], v[$c]));
162            };
163        }
164        for _ in 0..10 {
165            qr!(0, 4, 8, 12);
166            qr!(1, 5, 9, 13);
167            qr!(2, 6, 10, 14);
168            qr!(3, 7, 11, 15);
169            qr!(0, 5, 10, 15);
170            qr!(1, 6, 11, 12);
171            qr!(2, 7, 8, 13);
172            qr!(3, 4, 9, 14);
173        }
174        let mut words = [[0u32; 8]; 16];
175        for j in 0..16 {
176            let sum = _mm256_add_epi32(v[j], init[j]);
177            _mm256_storeu_si256(words[j].as_mut_ptr() as *mut __m256i, sum);
178        }
179        let mut ks = [0u8; 512];
180        for blk in 0..8 {
181            for j in 0..16 {
182                ks[blk * 64 + j * 4..blk * 64 + j * 4 + 4]
183                    .copy_from_slice(&words[j][blk].to_le_bytes());
184            }
185        }
186        let n = (data.len() - off).min(512);
187        let dst_start = out.len();
188        out.resize(dst_start + n, 0);
189        let dst = out.as_mut_ptr().add(dst_start);
190        let src = data.as_ptr().add(off);
191        let mut i = 0;
192        while i + 32 <= n {
193            let a = _mm256_loadu_si256(src.add(i) as *const __m256i);
194            let b = _mm256_loadu_si256(ks.as_ptr().add(i) as *const __m256i);
195            _mm256_storeu_si256(dst.add(i) as *mut __m256i, _mm256_xor_si256(a, b));
196            i += 32;
197        }
198        while i < n {
199            *dst.add(i) = *src.add(i) ^ ks[i];
200            i += 1;
201        }
202        off += 512;
203        base = base.wrapping_add(8);
204    }
205    out
206}
207
208// ── Poly1305 (RFC 8439 §2.5), 5×26-bit limbs, constant-time ────────────────────────────────────
209
210const MASK26: u32 = 0x3ff_ffff;
211
212/// Clamp `r` into 5×26-bit limbs.
213fn poly1305_clamp(key: &[u8; 32]) -> [u32; 5] {
214    let t0 = u32::from_le_bytes([key[0], key[1], key[2], key[3]]);
215    let t1 = u32::from_le_bytes([key[4], key[5], key[6], key[7]]);
216    let t2 = u32::from_le_bytes([key[8], key[9], key[10], key[11]]);
217    let t3 = u32::from_le_bytes([key[12], key[13], key[14], key[15]]);
218    [
219        t0 & 0x3ff_ffff,
220        ((t0 >> 26) | (t1 << 6)) & 0x3ff_ff03,
221        ((t1 >> 20) | (t2 << 12)) & 0x3ff_c0ff,
222        ((t2 >> 14) | (t3 << 18)) & 0x3f0_3fff,
223        (t3 >> 8) & 0x00f_ffff,
224    ]
225}
226
227/// A 16-byte block's 5×26-bit limbs; `hibit = 1` adds the 2¹²⁸ marker (a full block — for a partial
228/// block the caller writes the appended `1` byte inside `b` and passes `hibit = 0`).
229fn poly1305_block(b: &[u8; 16], hibit: u32) -> [u32; 5] {
230    let m0 = u32::from_le_bytes([b[0], b[1], b[2], b[3]]);
231    let m1 = u32::from_le_bytes([b[4], b[5], b[6], b[7]]);
232    let m2 = u32::from_le_bytes([b[8], b[9], b[10], b[11]]);
233    let m3 = u32::from_le_bytes([b[12], b[13], b[14], b[15]]);
234    [
235        m0 & MASK26,
236        ((m0 >> 26) | (m1 << 6)) & MASK26,
237        ((m1 >> 20) | (m2 << 12)) & MASK26,
238        ((m2 >> 14) | (m3 << 18)) & MASK26,
239        (m3 >> 8) | (hibit << 24),
240    ]
241}
242
243/// Carry-reduce 5 wide limbs (each ≤ ~2⁶⁰, e.g. the sum of four 130-bit products) into 5×26-bit
244/// limbs mod (2¹³⁰−5).
245fn poly1305_reduce(d: [u64; 5]) -> [u32; 5] {
246    let m = MASK26 as u64;
247    let mut c = d[0] >> 26;
248    let h0 = (d[0] & m) as u32;
249    let d1 = d[1] + c;
250    c = d1 >> 26;
251    let h1 = (d1 & m) as u32;
252    let d2 = d[2] + c;
253    c = d2 >> 26;
254    let h2 = (d2 & m) as u32;
255    let d3 = d[3] + c;
256    c = d3 >> 26;
257    let h3 = (d3 & m) as u32;
258    let d4 = d[4] + c;
259    c = d4 >> 26;
260    let h4 = (d4 & m) as u32;
261    // Top carry `c` (up to ~2³⁴) wraps via ·5 into limb 0 — it can span more than one limb.
262    let h0w = h0 as u64 + c * 5;
263    let mut h = [(h0w & m) as u32, h1 + (h0w >> 26) as u32, h2, h3, h4];
264    let c1 = h[1] >> 26;
265    h[1] &= MASK26;
266    h[2] += c1;
267    h
268}
269
270/// `a · b mod (2¹³⁰−5)` over 5×26-bit limbs (inputs ≤ ~2²⁷), fully reduced.
271fn poly1305_mul(a: &[u32; 5], b: &[u32; 5]) -> [u32; 5] {
272    let (a0, a1, a2, a3, a4) = (
273        a[0] as u64,
274        a[1] as u64,
275        a[2] as u64,
276        a[3] as u64,
277        a[4] as u64,
278    );
279    let (b0, b1, b2, b3, b4) = (
280        b[0] as u64,
281        b[1] as u64,
282        b[2] as u64,
283        b[3] as u64,
284        b[4] as u64,
285    );
286    let (s1, s2, s3, s4) = (b1 * 5, b2 * 5, b3 * 5, b4 * 5);
287    poly1305_reduce([
288        a0 * b0 + a1 * s4 + a2 * s3 + a3 * s2 + a4 * s1,
289        a0 * b1 + a1 * b0 + a2 * s4 + a3 * s3 + a4 * s2,
290        a0 * b2 + a1 * b1 + a2 * b0 + a3 * s4 + a4 * s3,
291        a0 * b3 + a1 * b2 + a2 * b1 + a3 * b0 + a4 * s4,
292        a0 * b4 + a1 * b3 + a2 * b2 + a3 * b1 + a4 * b0,
293    ])
294}
295
296/// Finalize: full reduction mod p, then `+ s mod 2¹²⁸` → the 16-byte tag.
297fn poly1305_finalize(h: [u32; 5], key: &[u8; 32]) -> [u8; 16] {
298    let (mut h0, mut h1, mut h2, mut h3, mut h4) = (h[0], h[1], h[2], h[3], h[4]);
299    let mut c;
300    c = h1 >> 26;
301    h1 &= 0x3ff_ffff;
302    h2 += c;
303    c = h2 >> 26;
304    h2 &= 0x3ff_ffff;
305    h3 += c;
306    c = h3 >> 26;
307    h3 &= 0x3ff_ffff;
308    h4 += c;
309    c = h4 >> 26;
310    h4 &= 0x3ff_ffff;
311    h0 += c * 5;
312    c = h0 >> 26;
313    h0 &= 0x3ff_ffff;
314    h1 += c;
315    let mut g0 = h0.wrapping_add(5);
316    c = g0 >> 26;
317    g0 &= 0x3ff_ffff;
318    let mut g1 = h1.wrapping_add(c);
319    c = g1 >> 26;
320    g1 &= 0x3ff_ffff;
321    let mut g2 = h2.wrapping_add(c);
322    c = g2 >> 26;
323    g2 &= 0x3ff_ffff;
324    let mut g3 = h3.wrapping_add(c);
325    c = g3 >> 26;
326    g3 &= 0x3ff_ffff;
327    let g4 = h4.wrapping_add(c).wrapping_sub(1 << 26);
328    let mask = (g4 >> 31).wrapping_sub(1);
329    let nmask = !mask;
330    h0 = (h0 & nmask) | (g0 & mask);
331    h1 = (h1 & nmask) | (g1 & mask);
332    h2 = (h2 & nmask) | (g2 & mask);
333    h3 = (h3 & nmask) | (g3 & mask);
334    h4 = (h4 & nmask) | (g4 & mask);
335    let f0 = (h0 | (h1 << 26)) as u64;
336    let f1 = ((h1 >> 6) | (h2 << 20)) as u64;
337    let f2 = ((h2 >> 12) | (h3 << 14)) as u64;
338    let f3 = ((h3 >> 18) | (h4 << 8)) as u64;
339    let s0 = u32::from_le_bytes([key[16], key[17], key[18], key[19]]) as u64;
340    let s1 = u32::from_le_bytes([key[20], key[21], key[22], key[23]]) as u64;
341    let s2 = u32::from_le_bytes([key[24], key[25], key[26], key[27]]) as u64;
342    let s3 = u32::from_le_bytes([key[28], key[29], key[30], key[31]]) as u64;
343    let mut tag = [0u8; 16];
344    let mut f = f0 + s0;
345    tag[0..4].copy_from_slice(&(f as u32).to_le_bytes());
346    f = f1 + s1 + (f >> 32);
347    tag[4..8].copy_from_slice(&(f as u32).to_le_bytes());
348    f = f2 + s2 + (f >> 32);
349    tag[8..12].copy_from_slice(&(f as u32).to_le_bytes());
350    f = f3 + s3 + (f >> 32);
351    tag[12..16].copy_from_slice(&(f as u32).to_le_bytes());
352    tag
353}
354
355/// Process one block scalar: `h ← (h + block) · r`.
356#[inline]
357fn poly1305_absorb(h: &mut [u32; 5], msg: &[u8], i: usize, r: &[u32; 5]) {
358    let n = (msg.len() - i).min(16);
359    let mut b = [0u8; 16];
360    b[..n].copy_from_slice(&msg[i..i + n]);
361    let hibit = if n == 16 {
362        1
363    } else {
364        b[n] = 1;
365        0
366    };
367    let m = poly1305_block(&b, hibit);
368    let sum = [
369        h[0] + m[0],
370        h[1] + m[1],
371        h[2] + m[2],
372        h[3] + m[3],
373        h[4] + m[4],
374    ];
375    *h = poly1305_mul(&sum, r);
376}
377
378/// Poly1305 one-time authenticator: `tag = ((Σ blockᵢ·r^(n−i)) mod (2¹³⁰−5)) + s mod 2¹²⁸`. AVX2
379/// (4 blocks/group via precomputed r¹..r⁴) for long messages, else scalar — bit-identical.
380pub fn poly1305(key: &[u8; 32], msg: &[u8]) -> [u8; 16] {
381    #[cfg(target_arch = "x86_64")]
382    {
383        if msg.len() >= 256 && std::is_x86_feature_detected!("avx2") {
384            return unsafe { poly1305_avx2(key, msg) };
385        }
386    }
387    poly1305_scalar(key, msg)
388}
389
390fn poly1305_scalar(key: &[u8; 32], msg: &[u8]) -> [u8; 16] {
391    let r = poly1305_clamp(key);
392    let mut h = [0u32; 5];
393    let mut i = 0;
394    while i < msg.len() {
395        poly1305_absorb(&mut h, msg, i, &r);
396        i += 16;
397    }
398    poly1305_finalize(h, key)
399}
400
401/// Horizontal sum of the four u64 lanes.
402#[cfg(target_arch = "x86_64")]
403#[target_feature(enable = "avx2")]
404#[inline]
405unsafe fn poly1305_hsum(v: std::arch::x86_64::__m256i) -> u64 {
406    use std::arch::x86_64::*;
407    let lo = _mm256_castsi256_si128(v);
408    let hi = _mm256_extracti128_si256::<1>(v);
409    let s = _mm_add_epi64(lo, hi);
410    let s2 = _mm_add_epi64(s, _mm_unpackhi_epi64(s, s));
411    _mm_cvtsi128_si64(s2) as u64
412}
413
414/// Per-limb multiplier vectors `[r⁴, r³, r², r¹]` (and `5×` for the 2¹³⁰ wrap) at even 32-bit lanes.
415#[cfg(target_arch = "x86_64")]
416#[target_feature(enable = "avx2")]
417unsafe fn poly1305_vectors(
418    r: &[u32; 5],
419) -> (
420    [std::arch::x86_64::__m256i; 5],
421    [std::arch::x86_64::__m256i; 5],
422) {
423    use std::arch::x86_64::*;
424    let r2 = poly1305_mul(r, r);
425    let r3 = poly1305_mul(&r2, r);
426    let r4 = poly1305_mul(&r2, &r2);
427    let mut vb = [_mm256_setzero_si256(); 5];
428    let mut vs = [_mm256_setzero_si256(); 5];
429    for l in 0..5 {
430        vb[l] = _mm256_set_epi32(
431            0,
432            r[l] as i32,
433            0,
434            r2[l] as i32,
435            0,
436            r3[l] as i32,
437            0,
438            r4[l] as i32,
439        );
440        vs[l] = _mm256_set_epi32(
441            0,
442            (r[l] * 5) as i32,
443            0,
444            (r2[l] * 5) as i32,
445            0,
446            (r3[l] * 5) as i32,
447            0,
448            (r4[l] * 5) as i32,
449        );
450    }
451    (vb, vs)
452}
453
454/// Absorb the full 4-block groups of `data` into `h` (four products/group via `_mm256_mul_epu32`,
455/// one per lane, summed), each block carrying the 2¹²⁸ marker. Returns bytes consumed (`groups·64`).
456#[cfg(target_arch = "x86_64")]
457#[target_feature(enable = "avx2")]
458unsafe fn poly1305_groups(
459    h: &mut [u32; 5],
460    data: &[u8],
461    vb: &[std::arch::x86_64::__m256i; 5],
462    vs: &[std::arch::x86_64::__m256i; 5],
463) -> usize {
464    use std::arch::x86_64::*;
465    let groups = (data.len() / 16) / 4;
466    for g in 0..groups {
467        let base = g * 64;
468        let mut t = [[0u32; 5]; 4];
469        for k in 0..4 {
470            let b: &[u8; 16] = data[base + k * 16..base + k * 16 + 16].try_into().unwrap();
471            t[k] = poly1305_block(b, 1);
472        }
473        for l in 0..5 {
474            t[0][l] += h[l];
475        }
476        let mut va = [_mm256_setzero_si256(); 5];
477        for l in 0..5 {
478            va[l] = _mm256_set_epi32(
479                0,
480                t[3][l] as i32,
481                0,
482                t[2][l] as i32,
483                0,
484                t[1][l] as i32,
485                0,
486                t[0][l] as i32,
487            );
488        }
489        macro_rules! mul {
490            ($x:expr, $y:expr) => {
491                _mm256_mul_epu32($x, $y)
492            };
493        }
494        macro_rules! add5 {
495            ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr) => {
496                _mm256_add_epi64(
497                    _mm256_add_epi64(_mm256_add_epi64($a, $b), _mm256_add_epi64($c, $d)),
498                    $e,
499                )
500            };
501        }
502        let d = [
503            add5!(
504                mul!(va[0], vb[0]),
505                mul!(va[1], vs[4]),
506                mul!(va[2], vs[3]),
507                mul!(va[3], vs[2]),
508                mul!(va[4], vs[1])
509            ),
510            add5!(
511                mul!(va[0], vb[1]),
512                mul!(va[1], vb[0]),
513                mul!(va[2], vs[4]),
514                mul!(va[3], vs[3]),
515                mul!(va[4], vs[2])
516            ),
517            add5!(
518                mul!(va[0], vb[2]),
519                mul!(va[1], vb[1]),
520                mul!(va[2], vb[0]),
521                mul!(va[3], vs[4]),
522                mul!(va[4], vs[3])
523            ),
524            add5!(
525                mul!(va[0], vb[3]),
526                mul!(va[1], vb[2]),
527                mul!(va[2], vb[1]),
528                mul!(va[3], vb[0]),
529                mul!(va[4], vs[4])
530            ),
531            add5!(
532                mul!(va[0], vb[4]),
533                mul!(va[1], vb[3]),
534                mul!(va[2], vb[2]),
535                mul!(va[3], vb[1]),
536                mul!(va[4], vb[0])
537            ),
538        ];
539        *h = poly1305_reduce([
540            poly1305_hsum(d[0]),
541            poly1305_hsum(d[1]),
542            poly1305_hsum(d[2]),
543            poly1305_hsum(d[3]),
544            poly1305_hsum(d[4]),
545        ]);
546    }
547    groups * 64
548}
549
550/// AVX2 Poly1305: 4 message blocks per group in parallel, then a scalar tail.
551#[cfg(target_arch = "x86_64")]
552#[target_feature(enable = "avx2")]
553unsafe fn poly1305_avx2(key: &[u8; 32], msg: &[u8]) -> [u8; 16] {
554    let r = poly1305_clamp(key);
555    let (vb, vs) = poly1305_vectors(&r);
556    let mut h = [0u32; 5];
557    let mut i = poly1305_groups(&mut h, msg, &vb, &vs);
558    while i < msg.len() {
559        poly1305_absorb(&mut h, msg, i, &r);
560        i += 16;
561    }
562    poly1305_finalize(h, key)
563}
564
565/// Absorb one AEAD block: up to 16 bytes, zero-padded to 16, ALWAYS with the 2¹²⁸ marker — the AEAD
566/// MAC zero-pads `aad`/`ct` to 16-byte boundaries, so every block is "full" (unlike generic
567/// Poly1305, which appends a `1` to a short final block).
568#[inline]
569fn poly1305_absorb_padded(h: &mut [u32; 5], data: &[u8], r: &[u32; 5]) {
570    let n = data.len().min(16);
571    let mut b = [0u8; 16];
572    b[..n].copy_from_slice(&data[..n]);
573    let m = poly1305_block(&b, 1);
574    let sum = [
575        h[0] + m[0],
576        h[1] + m[1],
577        h[2] + m[2],
578        h[3] + m[3],
579        h[4] + m[4],
580    ];
581    *h = poly1305_mul(&sum, r);
582}
583
584/// The AEAD MAC over `aad ‖ pad ‖ ct ‖ pad ‖ len(aad) ‖ len(ct)`, STREAMED — no `mac_data` buffer.
585/// `ct` runs through the AVX2 4-block path in place (the dominant cost on bulk); `aad`, the padded
586/// tails, and the length block are scalar. Bit-identical to `poly1305(otk, &mac_data(aad, ct))`.
587fn poly1305_aead(otk: &[u8; 32], aad: &[u8], ct: &[u8]) -> [u8; 16] {
588    let r = poly1305_clamp(otk);
589    let mut h = [0u32; 5];
590    let mut a = 0;
591    while a < aad.len() {
592        poly1305_absorb_padded(&mut h, &aad[a..(a + 16).min(aad.len())], &r);
593        a += 16;
594    }
595    let mut i = 0usize;
596    #[cfg(target_arch = "x86_64")]
597    {
598        if ct.len() >= 256 && std::is_x86_feature_detected!("avx2") {
599            unsafe {
600                let (vb, vs) = poly1305_vectors(&r);
601                i = poly1305_groups(&mut h, ct, &vb, &vs);
602            }
603        }
604    }
605    while i < ct.len() {
606        poly1305_absorb_padded(&mut h, &ct[i..(i + 16).min(ct.len())], &r);
607        i += 16;
608    }
609    let mut lb = [0u8; 16];
610    lb[0..8].copy_from_slice(&(aad.len() as u64).to_le_bytes());
611    lb[8..16].copy_from_slice(&(ct.len() as u64).to_le_bytes());
612    poly1305_absorb_padded(&mut h, &lb, &r);
613    poly1305_finalize(h, otk)
614}
615
616// ── ChaCha20-Poly1305 AEAD (RFC 8439 §2.8) ─────────────────────────────────────────────────────
617
618fn poly1305_key_gen(key: &[u8; 32], nonce: &[u8; 12]) -> [u8; 32] {
619    let block = chacha20_block(&le_u32x8(key), 0, &le_u32x3(nonce));
620    let mut otk = [0u8; 32];
621    for i in 0..8 {
622        otk[i * 4..i * 4 + 4].copy_from_slice(&block[i].to_le_bytes());
623    }
624    otk
625}
626
627/// The MAC input `aad ‖ pad ‖ ct ‖ pad ‖ len(aad) ‖ len(ct)`, materialized. Kept only as the
628/// reference the streaming `poly1305_aead` is fuzzed against — the shipped seal/open stream instead.
629#[cfg(test)]
630fn mac_data(aad: &[u8], ciphertext: &[u8]) -> Vec<u8> {
631    let mut m = Vec::with_capacity(aad.len() + ciphertext.len() + 32);
632    m.extend_from_slice(aad);
633    m.resize(m.len() + ((16 - aad.len() % 16) % 16), 0);
634    m.extend_from_slice(ciphertext);
635    m.resize(m.len() + ((16 - ciphertext.len() % 16) % 16), 0);
636    m.extend_from_slice(&(aad.len() as u64).to_le_bytes());
637    m.extend_from_slice(&(ciphertext.len() as u64).to_le_bytes());
638    m
639}
640
641/// The longest plaintext one (key, nonce) seals (RFC 8439 §2.8): the payload's blocks start at
642/// counter 1 and must not wrap the 32-bit counter back onto the one-time key's keystream.
643pub const MAX_PLAINTEXT: u64 = (1 << 38) - 64;
644
645/// AEAD seal: returns `ciphertext ‖ tag[16]`.
646pub fn chacha20poly1305_seal(
647    key: &[u8; 32],
648    nonce: &[u8; 12],
649    aad: &[u8],
650    plaintext: &[u8],
651) -> Vec<u8> {
652    assert!(
653        plaintext.len() as u64 <= MAX_PLAINTEXT,
654        "ChaCha20-Poly1305 seals at most 2^38 - 64 bytes under one nonce"
655    );
656    let otk = poly1305_key_gen(key, nonce);
657    let mut out = chacha20_xor(key, nonce, 1, plaintext);
658    let tag = poly1305_aead(&otk, aad, &out);
659    out.extend_from_slice(&tag);
660    out
661}
662
663/// AEAD open: verifies the tag (constant-time) and decrypts, or `None` on tamper/truncation.
664pub fn chacha20poly1305_open(
665    key: &[u8; 32],
666    nonce: &[u8; 12],
667    aad: &[u8],
668    sealed: &[u8],
669) -> Option<Vec<u8>> {
670    if sealed.len() < 16 || (sealed.len() - 16) as u64 > MAX_PLAINTEXT {
671        return None;
672    }
673    let (ciphertext, tag) = sealed.split_at(sealed.len() - 16);
674    let otk = poly1305_key_gen(key, nonce);
675    let expected = poly1305_aead(&otk, aad, ciphertext);
676    let mut diff = 0u8;
677    for i in 0..16 {
678        diff |= expected[i] ^ tag[i];
679    }
680    if diff != 0 {
681        return None;
682    }
683    Some(chacha20_xor(key, nonce, 1, ciphertext))
684}
685
686// ── XChaCha20-Poly1305 (draft-irtf-cfrg-xchacha-03) ─────────────────────────────────────────────
687
688/// HChaCha20 (draft-irtf-cfrg-xchacha §2.2): the ChaCha20 rounds over `key` and a 128-bit `nonce` in
689/// the counter-and-nonce words, without the final addition, returning the first and last rows — a
690/// subkey as uniform as the key, one per nonce.
691pub fn hchacha20(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] {
692    let k = le_u32x8(key);
693    let n: [u32; 4] =
694        std::array::from_fn(|i| u32::from_le_bytes(nonce[i * 4..i * 4 + 4].try_into().unwrap()));
695    let mut w = [
696        0x6170_7865,
697        0x3320_646e,
698        0x7962_2d32,
699        0x6b20_6574,
700        k[0],
701        k[1],
702        k[2],
703        k[3],
704        k[4],
705        k[5],
706        k[6],
707        k[7],
708        n[0],
709        n[1],
710        n[2],
711        n[3],
712    ];
713    for _ in 0..10 {
714        qr(&mut w, 0, 4, 8, 12);
715        qr(&mut w, 1, 5, 9, 13);
716        qr(&mut w, 2, 6, 10, 14);
717        qr(&mut w, 3, 7, 11, 15);
718        qr(&mut w, 0, 5, 10, 15);
719        qr(&mut w, 1, 6, 11, 12);
720        qr(&mut w, 2, 7, 8, 13);
721        qr(&mut w, 3, 4, 9, 14);
722    }
723    let mut out = [0u8; 32];
724    for (i, word) in w[..4].iter().chain(&w[12..]).enumerate() {
725        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes());
726    }
727    out
728}
729
730/// The ChaCha20-Poly1305 key and nonce an XChaCha20-Poly1305 nonce selects: the HChaCha20 subkey of
731/// its first 16 bytes, and its last 8 behind four zero bytes.
732fn xchacha_subkey(key: &[u8; 32], nonce: &[u8; 24]) -> ([u8; 32], [u8; 12]) {
733    let subkey = hchacha20(key, nonce[..16].try_into().unwrap());
734    let mut inner = [0u8; 12];
735    inner[4..].copy_from_slice(&nonce[16..]);
736    (subkey, inner)
737}
738
739/// XChaCha20-Poly1305 seal: `ciphertext ‖ tag[16]`. Its 192-bit nonce is wide enough to draw at
740/// random for every message under one key, which a 96-bit nonce is not.
741pub fn xchacha20poly1305_seal(
742    key: &[u8; 32],
743    nonce: &[u8; 24],
744    aad: &[u8],
745    plaintext: &[u8],
746) -> Vec<u8> {
747    let (subkey, inner) = xchacha_subkey(key, nonce);
748    chacha20poly1305_seal(&subkey, &inner, aad, plaintext)
749}
750
751/// XChaCha20-Poly1305 open: verifies the tag (constant-time) and decrypts, or `None` on
752/// tamper/truncation.
753pub fn xchacha20poly1305_open(
754    key: &[u8; 32],
755    nonce: &[u8; 24],
756    aad: &[u8],
757    sealed: &[u8],
758) -> Option<Vec<u8>> {
759    let (subkey, inner) = xchacha_subkey(key, nonce);
760    chacha20poly1305_open(&subkey, &inner, aad, sealed)
761}
762
763// ── Boxes: XChaCha20-Poly1305 under a nonce drawn for each seal ────────────────────────────────
764
765/// The associated data a box of bytes is sealed under.
766pub const BOX_BYTES_LABEL: &[u8] = b"logos box: bytes";
767
768/// The associated data a box of a wire-encoded value is sealed under: a box of one kind never opens
769/// as the other.
770pub const BOX_VALUE_LABEL: &[u8] = b"logos box: value";
771
772/// What a box adds to what it seals: its 24-byte nonce in front and its 16-byte tag behind.
773pub const BOX_OVERHEAD: usize = 24 + 16;
774
775/// The box of `plaintext` under `key` and `nonce`: `nonce ‖ XChaCha20-Poly1305(key, nonce, label,
776/// plaintext)`.
777pub fn seal_box_under(key: &[u8; 32], nonce: &[u8; 24], label: &[u8], plaintext: &[u8]) -> Vec<u8> {
778    let mut out = Vec::with_capacity(BOX_OVERHEAD + plaintext.len());
779    out.extend_from_slice(nonce);
780    out.extend(xchacha20poly1305_seal(key, nonce, label, plaintext));
781    out
782}
783
784/// The box of `plaintext` under `key`, its nonce drawn from the system's entropy: 192 random bits, so
785/// one key seals any number of boxes without two sharing a nonce.
786pub fn seal_box(key: &[u8; 32], label: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, String> {
787    let mut nonce = [0u8; 24];
788    crate::random::fill_from_entropy(&mut nonce)?;
789    Ok(seal_box_under(key, &nonce, label, plaintext))
790}
791
792/// The plaintext of a box sealed under `key` and `label`, or `None` when it is shorter than a box or
793/// does not authenticate.
794pub fn open_box(key: &[u8; 32], label: &[u8], sealed: &[u8]) -> Option<Vec<u8>> {
795    if sealed.len() < BOX_OVERHEAD {
796        return None;
797    }
798    let (nonce, body) = sealed.split_at(24);
799    xchacha20poly1305_open(key, nonce.try_into().ok()?, label, body)
800}
801
802// ── Logos-facing wrappers (Seq of Int bytes 0..255) ────────────────────────────────────────────
803
804/// `chacha20Encrypt(key, nonce, counter, data)` → `data ⊕ keystream` (RFC 8439 §2.4): a 32-byte key,
805/// a 12-byte nonce, and a block counter the data's blocks stay inside of.
806pub fn chacha20_encrypt_seq(
807    key: &[i64],
808    nonce: &[i64],
809    counter: i64,
810    data: &[i64],
811) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
812    let k = args::byte_array::<32>("key", key)?;
813    let n = args::byte_array::<12>("nonce", nonce)?;
814    let counter = args::int_in("block counter", counter, 0, u32::MAX as i64)?;
815    let data = args::bytes("data", data)?;
816    let last = counter + data.len().div_ceil(64) as i64 - 1;
817    if last > u32::MAX as i64 {
818        return Err(format!(
819            "the data runs the block counter from {counter} to {last}, past its 32 bits"
820        ));
821    }
822    Ok(args::seq_of_bytes(&chacha20_xor(
823        &k,
824        &n,
825        counter as u32,
826        &data,
827    )))
828}
829
830/// `poly1305Mac(key, msg)` → 16-byte tag. The MAC primitive (constant-time 5×26-bit limbs).
831pub fn poly1305_seq(key: &[i64], msg: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
832    let k = args::byte_array::<32>("one-time key", key)?;
833    Ok(args::seq_of_bytes(&poly1305(
834        &k,
835        &args::bytes("message", msg)?,
836    )))
837}
838
839#[cfg(test)]
840#[path = "../../logicaffeine_tests/unit/logicaffeine_system/aead/tests.rs"]
841mod tests;