yip-crypto 0.1.0

Post-quantum hybrid Noise-IKpsk2 + ML-KEM-512 cryptographic handshake and AEAD session ciphers for yip
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
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
//! Noise-IKpsk2 post-quantum hybrid handshake and AEAD session crypto for the yip data plane, built
//! on the `snow` Noise Protocol Framework. Establishing a [`Session`] requires
//! completing an IKpsk2 [`Handshake`]; the session then seals/opens inner frames
//! with explicit per-frame nonces and a sliding anti-replay window.
//!
//! `snow` drives the Noise handshake only. Once the handshake completes, the two
//! secret transport keys are extracted via snow's `dangerously_get_raw_split()`
//! (the same HKDF-derived bytes snow's own `split()` uses internally) and handed
//! to `ring`'s asm ChaCha20-Poly1305 for the data-plane hot path, keyed with the
//! Noise nonce convention (4 zero bytes ++ 8-byte little-endian counter). This is
//! byte-identical to snow's own transport state but faster.
#![forbid(unsafe_code)]

use ml_kem::{
    array::Array,
    kem::{Decapsulate, Encapsulate, Kem, KeyExport},
    ml_kem_512::{self, MlKem512},
};
use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305};
use zeroize::Zeroizing;

/// The Noise parameter set: IKpsk2 pattern, X25519, ChaCha20-Poly1305, BLAKE2s.
pub(crate) const NOISE_PARAMS: &str = "Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s";

/// An X25519 static keypair (32-byte private and public halves).
#[derive(Debug, Clone)]
pub struct Keypair {
    /// X25519 private key.
    pub private: [u8; 32],
    /// X25519 public key.
    pub public: [u8; 32],
}

/// Generate a fresh X25519 static keypair.
pub fn generate_keypair() -> Keypair {
    let kp = snow::Builder::new(NOISE_PARAMS.parse().expect("valid params"))
        .generate_keypair()
        .expect("keypair generation");
    let mut private = [0u8; 32];
    let mut public = [0u8; 32];
    private.copy_from_slice(&kp.private);
    public.copy_from_slice(&kp.public);
    Keypair { private, public }
}

/// ML-KEM-512 encapsulation key length in bytes (FIPS 203).
pub const PQ_ENCAPS_KEY_LEN: usize = 800;

/// ML-KEM-512 ciphertext length in bytes (FIPS 203).
pub const PQ_CIPHERTEXT_LEN: usize = 768;

/// ML-KEM-512 shared secret length in bytes (FIPS 203).
pub const PQ_SHARED_SECRET_LEN: usize = 32;

/// An ML-KEM-512 public encapsulation key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PqEncapsKey(pub [u8; PQ_ENCAPS_KEY_LEN]);

/// An ML-KEM-512 private decapsulation key wrapped in zeroizing memory.
pub struct PqDecapsKey(Box<ml_kem_512::DecapsulationKey>);

impl std::fmt::Debug for PqDecapsKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("PqDecapsKey([REDACTED])")
    }
}

/// An ML-KEM-512 encapsulated ciphertext.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PqCiphertext(pub [u8; PQ_CIPHERTEXT_LEN]);

/// Generate a fresh ML-KEM-512 keypair.
pub fn generate_pq_keypair() -> (PqEncapsKey, PqDecapsKey) {
    let (dk, ek) = MlKem512::generate_keypair();
    let ek_bytes = ek.to_bytes();
    let mut ek_arr = [0u8; PQ_ENCAPS_KEY_LEN];
    ek_arr.copy_from_slice(ek_bytes.as_slice());
    (PqEncapsKey(ek_arr), PqDecapsKey(Box::new(dk)))
}

/// Encapsulate a shared secret toward `ek`, producing `(ciphertext, shared_secret)`.
///
/// Explicitly validates FIPS 203 Section 7.2 ByteDecode_12 (all 12-bit coefficients < 3329)
/// across the first 768 bytes before invoking key encapsulation.
pub fn pq_encapsulate(
    ek: &PqEncapsKey,
) -> Result<(PqCiphertext, Zeroizing<[u8; PQ_SHARED_SECRET_LEN]>), CryptoError> {
    // FIPS 203 Section 7.2: ByteDecode_12 modulus check (all 12-bit coeffs < 3329)
    for chunk in ek.0[..768].as_chunks::<3>().0 {
        let d0 = u16::from(chunk[0]) | ((u16::from(chunk[1]) & 0x0F) << 8);
        let d1 = (u16::from(chunk[1]) >> 4) | (u16::from(chunk[2]) << 4);
        if d0 >= 3329 || d1 >= 3329 {
            return Err(CryptoError::Handshake);
        }
    }

    let ek_arr = Array::from(ek.0);
    let key = ml_kem_512::EncapsulationKey::new(&ek_arr).map_err(|_| CryptoError::Handshake)?;
    let (ct, ss) = key.encapsulate();
    let ss = Zeroizing::new(ss);
    let mut ct_arr = [0u8; PQ_CIPHERTEXT_LEN];
    ct_arr.copy_from_slice(ct.as_slice());
    let mut ss_arr = Zeroizing::new([0u8; PQ_SHARED_SECRET_LEN]);
    ss_arr.copy_from_slice(ss.as_slice());
    Ok((PqCiphertext(ct_arr), ss_arr))
}

/// Decapsulate `ct` using `dk`, recovering the 32-byte shared secret wrapped in zeroizing memory.
pub fn pq_decapsulate(
    dk: &PqDecapsKey,
    ct: &PqCiphertext,
) -> Result<Zeroizing<[u8; PQ_SHARED_SECRET_LEN]>, CryptoError> {
    let ct_arr = Array::from(ct.0);
    let ss = Zeroizing::new(dk.0.decapsulate(&ct_arr));
    let mut ss_arr = Zeroizing::new([0u8; PQ_SHARED_SECRET_LEN]);
    ss_arr.copy_from_slice(ss.as_slice());
    Ok(ss_arr)
}

/// Standard profile replay window parameters (1 KB bitmap).
pub const REPLAY_WINDOW_BITS_STANDARD: u64 = 8_192;
pub const REPLAY_WORDS_STANDARD: usize = 128;

/// HighThroughput profile replay window parameters (16 KB bitmap).
pub const REPLAY_WINDOW_BITS_HIGH_THROUGHPUT: u64 = 131_072;
pub const REPLAY_WORDS_HIGH_THROUGHPUT: usize = 2048;

/// Number of past counters the replay window tracks behind the latest in HighThroughput mode.
pub const REPLAY_WINDOW_BITS: u64 = REPLAY_WINDOW_BITS_HIGH_THROUGHPUT;
pub const REPLAY_WORDS: usize = REPLAY_WORDS_HIGH_THROUGHPUT;

/// Sizing profile for the sliding replay window bitmap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplayProfile {
    /// 1 KB bitmap tracking 8,192 bits behind the latest seen counter.
    /// Fits tightly into L1/L2 cache for standard latency-critical connections.
    Standard,
    /// 16 KB bitmap tracking 131,072 bits behind the latest seen counter.
    /// Designed for multi-gigabit multi-core pipelines absorbing high burst jitter.
    HighThroughput,
}

impl ReplayProfile {
    /// Number of past counters tracked behind the latest counter.
    #[inline]
    pub const fn bits(self) -> u64 {
        match self {
            Self::Standard => REPLAY_WINDOW_BITS_STANDARD,
            Self::HighThroughput => REPLAY_WINDOW_BITS_HIGH_THROUGHPUT,
        }
    }

    /// Number of 64-bit words in the circular ring bitmap.
    #[inline]
    pub const fn words(self) -> usize {
        match self {
            Self::Standard => REPLAY_WORDS_STANDARD,
            Self::HighThroughput => REPLAY_WORDS_HIGH_THROUGHPUT,
        }
    }
}

/// A wide sliding replay window over a monotonic `u64` counter using a circular word ring.
#[derive(Clone)]
pub struct ReplayWindow {
    profile: ReplayProfile,
    latest: u64,
    bitmap: Box<[u64]>,
    started: bool,
}

impl ReplayWindow {
    /// Create a replay window with the default `HighThroughput` profile (16 KB / 131,072 bits).
    pub fn new() -> Self {
        Self::new_with_profile(ReplayProfile::HighThroughput)
    }

    /// Create a replay window configured with a specific sizing profile.
    pub fn new_with_profile(profile: ReplayProfile) -> Self {
        let words = profile.words();
        Self {
            profile,
            latest: 0,
            bitmap: vec![0u64; words].into_boxed_slice(),
            started: false,
        }
    }

    /// Current sizing profile of the replay window.
    pub fn profile(&self) -> ReplayProfile {
        self.profile
    }

    /// Dynamically promote window capacity to `HighThroughput` (16 KB / 131,072 bits).
    /// Preserves all previously seen counters without dropping replay protection.
    pub fn promote_to_high_throughput(&mut self) {
        if self.profile == ReplayProfile::HighThroughput {
            return;
        }
        let old_words = self.bitmap.len();
        let new_words = ReplayProfile::HighThroughput.words();
        let mut new_bitmap = vec![0u64; new_words].into_boxed_slice();

        if self.started {
            let latest_word = self.latest / 64;
            let start_word = latest_word.saturating_sub((old_words - 1) as u64);
            for w in start_word..=latest_word {
                let old_idx = (w as usize) & (old_words - 1);
                let new_idx = (w as usize) & (new_words - 1);
                new_bitmap[new_idx] = self.bitmap[old_idx];
            }
        }

        self.profile = ReplayProfile::HighThroughput;
        self.bitmap = new_bitmap;
    }

    #[inline]
    fn word_idx(&self, counter: u64) -> usize {
        ((counter / 64) as usize) & (self.bitmap.len() - 1)
    }

    #[inline]
    fn bit_mask(counter: u64) -> u64 {
        1u64 << (counter % 64)
    }

    /// Would `counter` be accepted right now? Read-only — does not mutate state.
    pub fn check(&self, counter: u64) -> bool {
        if !self.started {
            return true;
        }
        if counter > self.latest {
            true
        } else {
            let diff = self.latest - counter;
            if diff >= self.profile.bits() {
                return false; // too old
            }
            let idx = self.word_idx(counter);
            let mask = Self::bit_mask(counter);
            (self.bitmap[idx] & mask) == 0
        }
    }

    /// Record `counter` as seen, advancing the window. Must be preceded by check().
    pub fn commit(&mut self, counter: u64) {
        if !self.started {
            self.started = true;
            self.latest = counter;
            let idx = self.word_idx(counter);
            self.bitmap[idx] = Self::bit_mask(counter);
            return;
        }

        if counter > self.latest {
            let diff = counter - self.latest;
            let window_bits = self.profile.bits();
            let total_words = self.bitmap.len();
            if diff >= window_bits {
                // Large leap: clear entire bitmap
                self.bitmap.fill(0);
            } else {
                // Clear any words in the circular ring that were overtaken
                let old_word = self.latest / 64;
                let new_word = counter / 64;
                if new_word > old_word {
                    let words_to_clear = ((new_word - old_word) as usize).min(total_words);
                    for w in 1..=words_to_clear {
                        let idx = ((old_word + w as u64) as usize) & (total_words - 1);
                        self.bitmap[idx] = 0;
                    }
                }
            }
            self.latest = counter;
            let idx = self.word_idx(counter);
            self.bitmap[idx] |= Self::bit_mask(counter);
        } else {
            let diff = self.latest - counter;
            if diff < self.profile.bits() {
                let idx = self.word_idx(counter);
                self.bitmap[idx] |= Self::bit_mask(counter);
            }
        }
    }

    /// Convenience helper to check and commit a counter in one step.
    /// Used by test harnesses and benchmark suites.
    pub fn check_and_set(&mut self, counter: u64) -> bool {
        if self.check(counter) {
            self.commit(counter);
            true
        } else {
            false
        }
    }
}

impl Default for ReplayWindow {
    fn default() -> Self {
        Self::new()
    }
}

/// Errors from the crypto layer.

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum CryptoError {
    /// AEAD tag did not verify / decryption failed.
    #[error("decryption failed")]
    Decrypt,
    /// Nonce/counter outside the anti-replay window (replayed or too old).
    #[error("replayed message")]
    Replay,
    /// Handshake step failed (bad message, wrong state, or key error).
    #[error("handshake failed")]
    Handshake,
}

/// Internal role-specific state for post-quantum hybrid key exchange.
enum HandshakePqRole {
    Initiator {
        dk: Option<PqDecapsKey>,
        ek: PqEncapsKey,
    },
    Responder {
        pending_ct: Option<PqCiphertext>,
    },
}

/// An in-progress Noise-IKpsk2 post-quantum hybrid handshake.
pub struct Handshake {
    inner: std::sync::Mutex<snow::HandshakeState>,
    role: HandshakePqRole,
}

impl Handshake {
    /// Begin as the initiator, which must already know the responder's static public key.
    pub fn initiator(
        local_private: &[u8; 32],
        peer_public: &[u8; 32],
    ) -> Result<Handshake, CryptoError> {
        let inner = snow::Builder::new(NOISE_PARAMS.parse().map_err(|_| CryptoError::Handshake)?)
            .local_private_key(local_private)
            .map_err(|_| CryptoError::Handshake)?
            .remote_public_key(peer_public)
            .map_err(|_| CryptoError::Handshake)?
            .build_initiator()
            .map_err(|_| CryptoError::Handshake)?;

        let (ek, dk) = generate_pq_keypair();
        Ok(Handshake {
            inner: std::sync::Mutex::new(inner),
            role: HandshakePqRole::Initiator { dk: Some(dk), ek },
        })
    }

    /// Begin as the responder; learns the initiator's static key during the handshake.
    pub fn responder(local_private: &[u8; 32]) -> Result<Handshake, CryptoError> {
        let inner = snow::Builder::new(NOISE_PARAMS.parse().map_err(|_| CryptoError::Handshake)?)
            .local_private_key(local_private)
            .map_err(|_| CryptoError::Handshake)?
            .build_responder()
            .map_err(|_| CryptoError::Handshake)?;

        Ok(Handshake {
            inner: std::sync::Mutex::new(inner),
            role: HandshakePqRole::Responder { pending_ct: None },
        })
    }

    /// Produce the next handshake message to send to the peer.
    ///
    /// - For Initiator (Msg 1): Encrypts `[ek_A (800B) || payload]` inside Noise Msg 1.
    /// - For Responder (Msg 2): Encrypts `payload` inside Noise Msg 2, framed as `[ct (768B) || Noise Msg 2]`.
    pub fn write_message(&mut self, payload: &[u8]) -> Result<Vec<u8>, CryptoError> {
        let mut buf = [0u8; 4096];
        match &mut self.role {
            HandshakePqRole::Initiator { ek, .. } => {
                let mut full_payload = Vec::with_capacity(PQ_ENCAPS_KEY_LEN + payload.len());
                full_payload.extend_from_slice(&ek.0);
                full_payload.extend_from_slice(payload);
                let n = self
                    .inner
                    .get_mut()
                    .expect("handshake lock")
                    .write_message(&full_payload, &mut buf)
                    .map_err(|_| CryptoError::Handshake)?;
                Ok(buf[..n].to_vec())
            }
            HandshakePqRole::Responder { pending_ct } => {
                let ct = pending_ct.take().ok_or(CryptoError::Handshake)?;
                let n = self
                    .inner
                    .get_mut()
                    .expect("handshake lock")
                    .write_message(payload, &mut buf)
                    .map_err(|_| CryptoError::Handshake)?;
                let mut out = Vec::with_capacity(PQ_CIPHERTEXT_LEN + n);
                out.extend_from_slice(&ct.0);
                out.extend_from_slice(&buf[..n]);
                Ok(out)
            }
        }
    }

    /// Consume a handshake message received from the peer, returning the decrypted app payload.
    ///
    /// - For Responder (Msg 1): Decrypts Noise Msg 1, extracts `ek_A`, encapsulates `(ct, ss)`,
    ///   calls `set_psk(2, &ss)`, and returns `payload`.
    /// - For Initiator (Msg 2): Slices `ct` from Msg 2 prefix, decapsulates `ss`,
    ///   calls `set_psk(2, &ss)`, decrypts Noise Msg 2, scrubs `dk`, and returns `payload`.
    pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>, CryptoError> {
        let mut buf = [0u8; 4096];
        match &mut self.role {
            HandshakePqRole::Responder { pending_ct } => {
                let n = self
                    .inner
                    .get_mut()
                    .expect("handshake lock")
                    .read_message(msg, &mut buf)
                    .map_err(|_| CryptoError::Handshake)?;
                if n < PQ_ENCAPS_KEY_LEN {
                    return Err(CryptoError::Handshake);
                }
                let ek_bytes: [u8; PQ_ENCAPS_KEY_LEN] = buf[..PQ_ENCAPS_KEY_LEN]
                    .try_into()
                    .map_err(|_| CryptoError::Handshake)?;
                let ek = PqEncapsKey(ek_bytes);
                let (ct, ss) = pq_encapsulate(&ek)?;
                self.inner
                    .get_mut()
                    .expect("handshake lock")
                    .set_psk(2, &ss[..])
                    .map_err(|_| CryptoError::Handshake)?;
                *pending_ct = Some(ct);
                Ok(buf[PQ_ENCAPS_KEY_LEN..n].to_vec())
            }
            HandshakePqRole::Initiator { dk, .. } => {
                let ct_slice = msg.get(..PQ_CIPHERTEXT_LEN).ok_or(CryptoError::Handshake)?;
                let ct_bytes: [u8; PQ_CIPHERTEXT_LEN] =
                    ct_slice.try_into().map_err(|_| CryptoError::Handshake)?;
                let ct = PqCiphertext(ct_bytes);
                let decaps_key = dk.take().ok_or(CryptoError::Handshake)?;
                let ss = pq_decapsulate(&decaps_key, &ct)?;
                drop(decaps_key); // Explicit scrub of dk_A

                let inner = self.inner.get_mut().expect("handshake lock");
                inner
                    .set_psk(2, &ss[..])
                    .map_err(|_| CryptoError::Handshake)?;
                let n = inner
                    .read_message(&msg[PQ_CIPHERTEXT_LEN..], &mut buf)
                    .map_err(|_| CryptoError::Handshake)?;
                Ok(buf[..n].to_vec())
            }
        }
    }

    /// Whether the handshake has completed and a session can be derived.
    pub fn is_finished(&self) -> bool {
        self.inner
            .lock()
            .expect("handshake lock")
            .is_handshake_finished()
    }

    /// The peer's authenticated static public key, if learned yet.
    pub fn remote_static(&self) -> Option<[u8; 32]> {
        self.inner
            .lock()
            .expect("handshake lock")
            .get_remote_static()
            .map(|k| {
                let mut out = [0u8; 32];
                out.copy_from_slice(k);
                out
            })
    }

    /// The Noise channel-binding hash (snow's handshake hash), identical on both
    /// peers after the handshake completes. Use it to derive subkeys (e.g. the
    /// wire codec keys) bound to this session.
    pub fn channel_binding(&self) -> [u8; 32] {
        let mut out = [0u8; 32];
        out.copy_from_slice(
            self.inner
                .lock()
                .expect("handshake lock")
                .get_handshake_hash(),
        );
        out
    }

    /// Extract the two raw 32-byte secret Noise transport keys (send key, recv key)
    /// derived from the handshake.
    pub fn raw_split_keys(&self) -> ([u8; 32], [u8; 32]) {
        let mut inner = self.inner.lock().expect("handshake lock");
        let is_initiator = inner.is_initiator();
        let (k0, k1) = inner.dangerously_get_raw_split();
        if is_initiator {
            (k0, k1)
        } else {
            (k1, k0)
        }
    }

    /// Convert a completed handshake into an AEAD [`Session`].
    ///
    /// Extracts the two secret Noise transport keys via snow's raw split and
    /// builds `ring` AEAD keys from them directly; snow's own transport state is
    /// not used for the data plane. Per snow's split convention, element 0 of
    /// the pair is the initiator's send key (= responder's receive key) and
    /// element 1 is the responder's send key (= initiator's receive key), so
    /// the mapping below is role-dependent.
    pub fn into_session(self) -> Result<Session, CryptoError> {
        let (k_send, k_recv) = self.raw_split_keys();
        Session::from_raw_keys(&k_send, &k_recv, 0, 1)
    }

    #[cfg(test)]
    pub(crate) fn to_session_for_test(&self) -> Result<Session, CryptoError> {
        let (k_send, k_recv) = self.raw_split_keys();
        Session::from_raw_keys(&k_send, &k_recv, 0, 1)
    }

    #[cfg(test)]
    pub(crate) fn into_inner_snow_for_test(self) -> snow::HandshakeState {
        self.inner.into_inner().expect("handshake lock")
    }
}

/// Noise ChaChaPoly nonce: 4 zero bytes ++ 8-byte little-endian counter.
fn noise_nonce(counter: u64) -> Nonce {
    let mut n = [0u8; 12];
    n[4..].copy_from_slice(&counter.to_le_bytes());
    Nonce::assume_unique_for_key(n)
}

/// A sealed frame: the AEAD ciphertext plus the explicit nonce it was sealed
/// under. The caller carries `counter` on the wire so the peer can `open`.
#[derive(Debug, Clone)]
pub struct Sealed {
    /// The explicit AEAD nonce assigned to this frame.
    pub counter: u64,
    /// The AEAD ciphertext (plaintext length + 16-byte tag).
    pub ciphertext: Vec<u8>,
}

/// An established AEAD session. Seals outgoing frames under a monotonic counter
/// and opens incoming frames out of order, rejecting replays.
///
/// Uses `ring`'s ChaCha20-Poly1305 keyed by the Noise Split() transport keys
/// (see [`Handshake::into_session`]) rather than snow's own transport state.
pub struct Session {
    send_key: LessSafeKey,
    recv_key: LessSafeKey,
    send_counter: u64,
    stride: u64,
    replay: ReplayWindow,
}

impl Session {
    /// Construct a session directly from raw 32-byte send and receive keys,
    /// with an explicit start counter and stride increment (e.g. for worker sharding).
    pub fn from_raw_keys(
        k_send: &[u8; 32],
        k_recv: &[u8; 32],
        start_counter: u64,
        stride: u64,
    ) -> Result<Self, CryptoError> {
        let send =
            UnboundKey::new(&CHACHA20_POLY1305, k_send).map_err(|_| CryptoError::Handshake)?;
        let recv =
            UnboundKey::new(&CHACHA20_POLY1305, k_recv).map_err(|_| CryptoError::Handshake)?;
        Ok(Session {
            send_key: LessSafeKey::new(send),
            recv_key: LessSafeKey::new(recv),
            send_counter: start_counter,
            stride: if stride == 0 { 1 } else { stride },
            replay: ReplayWindow::new(),
        })
    }

    /// Reconfigure the send counter and stride increment for this session.
    pub fn set_stride(&mut self, start_counter: u64, stride: u64) {
        let stride = if stride == 0 { 1 } else { stride };
        if self.send_counter == 0 {
            self.send_counter = start_counter;
        } else {
            let rem = self.send_counter % stride;
            let target_rem = start_counter % stride;
            let diff = if rem <= target_rem {
                target_rem - rem
            } else {
                stride - (rem - target_rem)
            };
            self.send_counter = self.send_counter.saturating_add(diff);
        }
        self.stride = stride;
    }

    /// The current nonce stride increment.
    pub fn stride(&self) -> u64 {
        self.stride
    }

    /// The current send counter.
    pub fn send_counter(&self) -> u64 {
        self.send_counter
    }

    /// Seal one inner frame, assigning it the next send counter.
    pub fn seal(&mut self, plaintext: &[u8]) -> Result<Sealed, CryptoError> {
        let counter = self.send_counter;
        let mut buf = plaintext.to_vec();
        self.send_key
            .seal_in_place_append_tag(noise_nonce(counter), Aad::empty(), &mut buf)
            .map_err(|_| CryptoError::Decrypt)?;
        self.send_counter = self
            .send_counter
            .checked_add(self.stride)
            .ok_or(CryptoError::Decrypt)?;
        Ok(Sealed {
            counter,
            ciphertext: buf,
        })
    }

    /// Open one inner frame received under explicit `counter`, enforcing replay protection.
    ///
    /// The replay window is checked read-only *before* AEAD, then committed only
    /// *after* the frame authenticates (matching WireGuard, which advances its
    /// window post-decrypt). This ordering prevents a forged frame carrying an
    /// arbitrary counter from advancing the window and starving legitimate
    /// packets — an off-path DoS the mark-before-auth ordering was open to.
    pub fn open(&mut self, counter: u64, ciphertext: &[u8]) -> Result<Vec<u8>, CryptoError> {
        if !self.replay.check(counter) {
            return Err(CryptoError::Replay);
        }
        let mut buf = ciphertext.to_vec();
        let plain = self
            .recv_key
            .open_in_place(noise_nonce(counter), Aad::empty(), &mut buf)
            .map_err(|_| CryptoError::Decrypt)?;
        self.replay.commit(counter);
        Ok(plain.to_vec())
    }

    /// Check whether `counter` is valid within the anti-replay window without committing it.
    /// Used for pre-decoding packet validation and DoS rejection.
    #[inline]
    pub fn check_replay(&self, counter: u64) -> bool {
        self.replay.check(counter)
    }

    /// Seal into a caller-owned reusable buffer (no per-call allocation).
    pub fn seal_into(&mut self, plaintext: &[u8], out: &mut Vec<u8>) -> Result<u64, CryptoError> {
        let counter = self.send_counter;
        out.clear();
        out.extend_from_slice(plaintext);
        self.send_key
            .seal_in_place_append_tag(noise_nonce(counter), Aad::empty(), out)
            .map_err(|_| CryptoError::Decrypt)?;
        self.send_counter = self
            .send_counter
            .checked_add(self.stride)
            .ok_or(CryptoError::Decrypt)?;
        Ok(counter)
    }

    /// Seal one inner frame under an explicit counter, without mutating internal counter.
    /// This allows multi-threaded workers sharing a single peer connection to seal
    /// concurrently using nonces dispensed from a ChunkedNonceDispenser.
    pub fn seal_with_counter(&self, counter: u64, plaintext: &[u8]) -> Result<Sealed, CryptoError> {
        let mut buf = plaintext.to_vec();
        self.send_key
            .seal_in_place_append_tag(noise_nonce(counter), Aad::empty(), &mut buf)
            .map_err(|_| CryptoError::Decrypt)?;
        Ok(Sealed {
            counter,
            ciphertext: buf,
        })
    }

    /// Seal into a caller-owned reusable buffer under an explicit counter.
    pub fn seal_into_with_counter(
        &self,
        counter: u64,
        plaintext: &[u8],
        out: &mut Vec<u8>,
    ) -> Result<(), CryptoError> {
        out.clear();
        out.extend_from_slice(plaintext);
        self.send_key
            .seal_in_place_append_tag(noise_nonce(counter), Aad::empty(), out)
            .map_err(|_| CryptoError::Decrypt)?;
        Ok(())
    }

    /// Open one inner frame received under explicit counter against a caller-provided replay window.
    pub fn open_with_window(
        &self,
        counter: u64,
        ciphertext: &[u8],
        replay: &mut ReplayWindow,
    ) -> Result<Vec<u8>, CryptoError> {
        if !replay.check(counter) {
            return Err(CryptoError::Replay);
        }
        let mut buf = ciphertext.to_vec();
        let plain = self
            .recv_key
            .open_in_place(noise_nonce(counter), Aad::empty(), &mut buf)
            .map_err(|_| CryptoError::Decrypt)?;
        replay.commit(counter);
        Ok(plain.to_vec())
    }

    /// Open into a caller-owned reusable buffer under explicit counter against a caller-provided replay window.
    pub fn open_into_with_window(
        &self,
        counter: u64,
        ciphertext: &[u8],
        replay: &mut ReplayWindow,
        out: &mut Vec<u8>,
    ) -> Result<(), CryptoError> {
        if !replay.check(counter) {
            return Err(CryptoError::Replay);
        }
        out.clear();
        out.extend_from_slice(ciphertext);
        let n = {
            let plain = self
                .recv_key
                .open_in_place(noise_nonce(counter), Aad::empty(), out)
                .map_err(|_| CryptoError::Decrypt)?;
            plain.len()
        };
        replay.commit(counter);
        out.truncate(n);
        Ok(())
    }

    /// Open into a caller-owned reusable buffer (no per-call allocation).
    pub fn open_into(
        &mut self,
        counter: u64,
        ciphertext: &[u8],
        out: &mut Vec<u8>,
    ) -> Result<(), CryptoError> {
        if !self.replay.check(counter) {
            return Err(CryptoError::Replay);
        }
        out.clear();
        out.extend_from_slice(ciphertext);
        let n = {
            let plain = self
                .recv_key
                .open_in_place(noise_nonce(counter), Aad::empty(), out)
                .map_err(|_| CryptoError::Decrypt)?;
            plain.len()
        };
        self.replay.commit(counter);
        out.truncate(n);
        Ok(())
    }

    /// Seal plaintext in-place inside `buf[..plaintext_len]`, writing the 16-byte Poly1305
    /// authentication tag immediately following the ciphertext into `buf[plaintext_len..plaintext_len + 16]`.
    ///
    /// The buffer must have capacity of at least `plaintext_len + 16` bytes.
    /// Returns the explicit counter assigned to this frame.
    pub fn seal_in_place(
        &mut self,
        buf: &mut [u8],
        plaintext_len: usize,
    ) -> Result<u64, CryptoError> {
        let counter = self.send_counter;
        let total_len = plaintext_len.checked_add(16).ok_or(CryptoError::Decrypt)?;
        if buf.len() < total_len {
            return Err(CryptoError::Decrypt);
        }
        let (in_out, tag_out) = buf[..total_len].split_at_mut(plaintext_len);
        let tag = self
            .send_key
            .seal_in_place_separate_tag(noise_nonce(counter), Aad::empty(), in_out)
            .map_err(|_| CryptoError::Decrypt)?;
        tag_out.copy_from_slice(tag.as_ref());
        self.send_counter = self
            .send_counter
            .checked_add(self.stride)
            .ok_or(CryptoError::Decrypt)?;
        Ok(counter)
    }

    /// Open and authenticate ciphertext in-place inside `buf[..sealed_len]`, enforcing anti-replay.
    ///
    /// Expects the 16-byte Poly1305 authentication tag at the end of the ciphertext:
    /// `buf[sealed_len - 16..sealed_len]`.
    /// Returns the decrypted plaintext length (`sealed_len - 16`).
    pub fn open_in_place(
        &mut self,
        counter: u64,
        buf: &mut [u8],
        sealed_len: usize,
    ) -> Result<usize, CryptoError> {
        if !self.replay.check(counter) {
            return Err(CryptoError::Replay);
        }
        if sealed_len < 16 || buf.len() < sealed_len {
            return Err(CryptoError::Decrypt);
        }
        let plain = self
            .recv_key
            .open_in_place(noise_nonce(counter), Aad::empty(), &mut buf[..sealed_len])
            .map_err(|_| CryptoError::Decrypt)?;
        self.replay.commit(counter);
        Ok(plain.len())
    }
}

/// ChaCha20-Poly1305 AEAD cipher supporting zero-copy in-place encryption and decryption
/// directly within pre-allocated network packet buffers (such as AF_XDP UMEM chunks).
pub struct ChaCha20Poly1305Cipher {
    key: LessSafeKey,
}

impl std::fmt::Debug for ChaCha20Poly1305Cipher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ChaCha20Poly1305Cipher")
            .finish_non_exhaustive()
    }
}

impl ChaCha20Poly1305Cipher {
    /// Creates a new cipher instance from a 32-byte symmetric key.
    pub fn new(key: [u8; 32]) -> Self {
        let unbound = UnboundKey::new(&CHACHA20_POLY1305, &key)
            .expect("32-byte key is valid for ChaCha20-Poly1305");
        Self {
            key: LessSafeKey::new(unbound),
        }
    }

    /// Seal plaintext in-place inside `buf[..plaintext_len]`, writing the 16-byte Poly1305
    /// authentication tag immediately following the ciphertext into `buf[plaintext_len..plaintext_len + 16]`.
    ///
    /// The buffer must have capacity of at least `plaintext_len + 16` bytes.
    /// Returns the total sealed ciphertext length (`plaintext_len + 16`).
    pub fn seal_in_place(
        &self,
        counter: u64,
        buf: &mut [u8],
        plaintext_len: usize,
    ) -> Result<usize, CryptoError> {
        let total_len = plaintext_len.checked_add(16).ok_or(CryptoError::Decrypt)?;
        if buf.len() < total_len {
            return Err(CryptoError::Decrypt);
        }
        let (in_out, tag_out) = buf[..total_len].split_at_mut(plaintext_len);
        let tag = self
            .key
            .seal_in_place_separate_tag(noise_nonce(counter), Aad::empty(), in_out)
            .map_err(|_| CryptoError::Decrypt)?;
        tag_out.copy_from_slice(tag.as_ref());
        Ok(total_len)
    }

    /// Open and authenticate ciphertext in-place inside `buf[..sealed_len]`.
    ///
    /// Expects the 16-byte Poly1305 authentication tag at the end of the ciphertext:
    /// `buf[sealed_len - 16..sealed_len]`.
    /// Returns the decrypted plaintext length (`sealed_len - 16`).
    pub fn open_in_place(
        &self,
        counter: u64,
        buf: &mut [u8],
        sealed_len: usize,
    ) -> Result<usize, CryptoError> {
        if sealed_len < 16 || buf.len() < sealed_len {
            return Err(CryptoError::Decrypt);
        }
        let plain = self
            .key
            .open_in_place(noise_nonce(counter), Aad::empty(), &mut buf[..sealed_len])
            .map_err(|_| CryptoError::Decrypt)?;
        Ok(plain.len())
    }

    /// Open and authenticate ciphertext in-place, verifying against a sliding anti-replay window.
    ///
    /// The replay window is checked before AEAD decryption and committed only upon
    /// successful authentication.
    pub fn open_in_place_with_window(
        &self,
        counter: u64,
        buf: &mut [u8],
        sealed_len: usize,
        replay: &mut ReplayWindow,
    ) -> Result<usize, CryptoError> {
        if !replay.check(counter) {
            return Err(CryptoError::Replay);
        }
        let plain_len = self.open_in_place(counter, buf, sealed_len)?;
        replay.commit(counter);
        Ok(plain_len)
    }
}

/// Test-only helper: drive a full initiator/responder handshake to completion
/// and return the two established sessions. Mirrors `yip_bench::established_pair`.
#[cfg(test)]
pub(crate) fn test_session_pair() -> (Session, Session) {
    let resp_kp = generate_keypair();
    let init_kp = generate_keypair();
    let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
    let mut res = Handshake::responder(&resp_kp.private).unwrap();
    let m1 = ini.write_message(&[]).unwrap();
    let _ = res.read_message(&m1).unwrap();
    let m2 = res.write_message(&[]).unwrap();
    let _ = ini.read_message(&m2).unwrap();
    (ini.into_session().unwrap(), res.into_session().unwrap())
}

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

    #[test]
    fn generated_keypairs_are_distinct_32_byte_keys() {
        let a = generate_keypair();
        let b = generate_keypair();
        assert_eq!(a.private.len(), 32);
        assert_eq!(a.public.len(), 32);
        assert_ne!(a.private, b.private, "two keypairs differ");
        assert_ne!(a.public, [0u8; 32], "public key is not all-zero");
    }

    #[test]
    fn session_seal_and_open_in_place_with_stride() {
        let (k_send, k_recv) = ([0x11u8; 32], [0x22u8; 32]);
        let mut s_tx = Session::from_raw_keys(&k_send, &k_recv, 2, 4).unwrap();
        let mut s_rx = Session::from_raw_keys(&k_recv, &k_send, 0, 1).unwrap();

        let mut buf = vec![0u8; 64];
        buf[..10].copy_from_slice(b"0123456789");

        let c1 = s_tx.seal_in_place(&mut buf, 10).unwrap();
        assert_eq!(c1, 2);
        let plain_len = s_rx.open_in_place(c1, &mut buf, 26).unwrap();
        assert_eq!(plain_len, 10);
        assert_eq!(&buf[..10], b"0123456789");

        // Next counter with stride 4
        buf[..10].copy_from_slice(b"abcdefghij");
        let c2 = s_tx.seal_in_place(&mut buf, 10).unwrap();
        assert_eq!(c2, 6);
        let plain_len2 = s_rx.open_in_place(c2, &mut buf, 26).unwrap();
        assert_eq!(plain_len2, 10);
        assert_eq!(&buf[..10], b"abcdefghij");

        // Replay of c2 should fail
        assert!(s_rx.open_in_place(c2, &mut buf, 26).is_err());
    }

    #[test]
    fn replay_window_accepts_fresh_rejects_replays_and_old() {
        let mut w = ReplayWindow::new();
        assert!(w.check_and_set(0), "first counter accepted");
        assert!(!w.check_and_set(0), "exact replay rejected");
        assert!(w.check_and_set(1), "next in order accepted");
        assert!(w.check_and_set(5), "jump ahead accepted");
        assert!(w.check_and_set(3), "in-window out-of-order accepted");
        assert!(!w.check_and_set(3), "replay of out-of-order rejected");
        assert!(w.check_and_set(100), "large advance accepted");
        assert!(
            !w.check_and_set(5),
            "counter now far below window rejected as too old"
        );
    }

    /// Advancing the window from counter A to B and then replaying A must be
    /// rejected.  Kills the `shift = counter + latest` mutant on the advance
    /// path (line 60) and the `bitmap << shift` → `bitmap >> shift` mutant on
    /// the same path (line 64): both mutations misplace the old-counter bits so
    /// the replay is no longer detected.
    #[test]
    fn replay_window_advance_then_replay_old_counter_rejected() {
        let mut w = ReplayWindow::new();
        // Establish counter 10 as the first-ever packet.
        assert!(w.check_and_set(10), "counter 10 accepted as first");
        // Advance to counter 15 (shift = 5 in real code; shift = 25 under the
        // `counter + latest` mutant, and bits shift wrong under `>> shift`).
        assert!(w.check_and_set(15), "advance to 15 accepted");
        // Counter 10 is now diff=5 from latest=15; its bit must still be set.
        assert!(
            !w.check_and_set(10),
            "replay of counter 10 after advance to 15 rejected"
        );
    }

    /// After advancing the window to a new latest, an immediate replay of that
    /// latest counter must be rejected.  Kills the `bitmap | 1` → `bitmap & 1`
    /// and `bitmap | 1` → `bitmap ^ 1` mutants: both can leave bit-0 of the
    /// new bitmap unset, making the just-accepted counter replayable.
    #[test]
    fn replay_window_new_latest_immediately_replayable_rejected() {
        let mut w = ReplayWindow::new();
        // Build a window where counter 9 is also recorded (bit 1 will be set
        // at latest=10), so that when we advance to 11 the shifted bitmap has
        // its LSB = 1.  Under `^ 1` that would clear bit-0, leaving latest-11
        // unprotected.
        assert!(w.check_and_set(10), "first packet at 10");
        assert!(w.check_and_set(9), "counter 9 accepted in-order-ish");
        // Advance from 10 to 11: shift=1, old bitmap has bit-1 set (counter 9).
        // `bitmap << 1` yields a value with LSB = old-bit-1 = 1.
        // Under `^ 1` that XORs the LSB back to 0, so the replay check below
        // would wrongly accept.
        assert!(w.check_and_set(11), "advance to 11 accepted");
        assert!(!w.check_and_set(11), "replay of new latest 11 rejected");
    }

    /// The `diff = self.latest - counter` on the in-window path (line 69) must
    /// use subtraction, not addition.  With `diff = latest + counter` the
    /// diff is 25 (not 5) for latest=15 counter=10, so bit-5 (which is set)
    /// is not checked and the replay slips through.
    #[test]
    fn replay_window_in_window_replay_rejected_after_advance() {
        let mut w = ReplayWindow::new();
        assert!(w.check_and_set(10), "first packet");
        assert!(w.check_and_set(15), "advance to 15");
        // Counter 10 is 5 below the new latest; real diff = 5, mutant diff = 25.
        // Both are < 64, but bit-5 is set while bit-25 is not.
        assert!(!w.check_and_set(10), "in-window replay at diff=5 rejected");
    }

    /// A freshly-built responder `Handshake` must not report `is_finished`
    /// before any messages have been exchanged.  Kills the mutant that
    /// replaces the `is_finished` body with `true` (line 150).
    #[test]
    fn handshake_not_finished_before_message_exchange() {
        let kp = generate_keypair();
        let res = Handshake::responder(&kp.private).unwrap();
        assert!(
            !res.is_finished(),
            "responder reports not-finished before any messages"
        );
        let ini = Handshake::initiator(&kp.private, &kp.public).unwrap();
        assert!(
            !ini.is_finished(),
            "initiator reports not-finished before any messages"
        );
    }

    #[test]
    fn handshake_payload_round_trips_and_sessions_match() {
        // msg1 carries an app payload (the initiator's cert, in 2c); msg2
        // carries a different one (the responder's cert). Noise-IK encrypts
        // both (msg1 under `es`, msg2 fully), so this also documents that
        // certs never appear in cleartext on the wire.
        let resp_kp = generate_keypair();
        let init_kp = generate_keypair();
        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();

        let m1 = ini.write_message(b"cert-A").unwrap();
        let got_a = res.read_message(&m1).unwrap();
        assert_eq!(got_a, b"cert-A");

        let m2 = res.write_message(b"cert-B").unwrap();
        let got_b = ini.read_message(&m2).unwrap();
        assert_eq!(got_b, b"cert-B");

        // Both sides derive the same channel binding (proof the payloads
        // didn't perturb the handshake transcript) before consuming into a
        // transport-mode session, then prove the sessions actually talk.
        assert_eq!(ini.channel_binding(), res.channel_binding());
        let mut ini_session = ini.into_session().unwrap();
        let mut res_session = res.into_session().unwrap();
        let sealed = ini_session.seal(b"payload round-trip ok").unwrap();
        assert_eq!(
            res_session
                .open(sealed.counter, &sealed.ciphertext)
                .unwrap(),
            b"payload round-trip ok"
        );
    }

    #[test]
    fn session_seals_and_opens_roundtrip() {
        let (mut a, mut b) = test_session_pair();
        let s = a.seal(b"inner packet").unwrap();
        assert_eq!(s.counter, 0, "first counter is 0");
        assert_eq!(b.open(s.counter, &s.ciphertext).unwrap(), b"inner packet");
    }

    #[test]
    fn session_opens_out_of_order() {
        let (mut a, mut b) = test_session_pair();
        let s0 = a.seal(b"zero").unwrap();
        let s1 = a.seal(b"one").unwrap();
        assert_eq!(s1.counter, 1);
        // deliver 1 before 0
        assert_eq!(b.open(s1.counter, &s1.ciphertext).unwrap(), b"one");
        assert_eq!(b.open(s0.counter, &s0.ciphertext).unwrap(), b"zero");
    }

    #[test]
    fn session_rejects_replay() {
        let (mut a, mut b) = test_session_pair();
        let s = a.seal(b"x").unwrap();
        assert!(b.open(s.counter, &s.ciphertext).is_ok());
        assert_eq!(b.open(s.counter, &s.ciphertext), Err(CryptoError::Replay));
    }

    #[test]
    fn session_rejects_tampered_ciphertext() {
        let (mut a, mut b) = test_session_pair();
        let s = a.seal(b"y").unwrap();
        let mut bad = s.ciphertext.clone();
        bad[0] ^= 0x01;
        assert_eq!(b.open(s.counter, &bad), Err(CryptoError::Decrypt));
    }

    /// A forged frame carrying a large counter but garbage ciphertext must fail
    /// AEAD *without* advancing the anti-replay window. Otherwise an off-path
    /// attacker who injects one such frame slides `latest` far forward, so every
    /// subsequent legitimate packet is rejected as "too old" — a session-killing
    /// DoS. The window slot must only be committed after AEAD verification.
    #[test]
    fn forged_frame_does_not_advance_replay_window() {
        let (mut a, mut b) = test_session_pair();
        let s0 = a.seal(b"zero").unwrap();
        let s1 = a.seal(b"one").unwrap();

        // Establish the receive window with a legitimate frame.
        assert_eq!(b.open(s0.counter, &s0.ciphertext).unwrap(), b"zero");

        // Off-path attacker injects a forged frame at a far-future counter.
        let garbage = vec![0u8; s0.ciphertext.len()];
        assert_eq!(
            b.open(1_000_000, &garbage),
            Err(CryptoError::Decrypt),
            "forged frame fails AEAD"
        );

        // The forged frame must not have moved the window: the next legitimate
        // in-flight frame still opens.
        assert_eq!(
            b.open(s1.counter, &s1.ciphertext).unwrap(),
            b"one",
            "legit frame still opens after forged far-future injection"
        );
    }

    /// Same invariant on the alloc-free `open_into` path.
    #[test]
    fn forged_frame_does_not_advance_replay_window_open_into() {
        let (mut a, mut b) = test_session_pair();
        let s0 = a.seal(b"zero").unwrap();
        let s1 = a.seal(b"one").unwrap();
        let mut out = Vec::new();

        b.open_into(s0.counter, &s0.ciphertext, &mut out).unwrap();
        assert_eq!(out, b"zero");

        let garbage = vec![0u8; s0.ciphertext.len()];
        assert_eq!(
            b.open_into(1_000_000, &garbage, &mut out),
            Err(CryptoError::Decrypt),
            "forged frame fails AEAD"
        );

        b.open_into(s1.counter, &s1.ciphertext, &mut out).unwrap();
        assert_eq!(
            out, b"one",
            "legit frame still opens after forged injection"
        );
    }

    #[test]
    fn channel_binding_matches_on_both_peers() {
        let resp_kp = generate_keypair();
        let init_kp = generate_keypair();
        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();
        let m1 = ini.write_message(&[]).unwrap();
        let _ = res.read_message(&m1).unwrap();
        let m2 = res.write_message(&[]).unwrap();
        let _ = ini.read_message(&m2).unwrap();
        assert!(ini.is_finished() && res.is_finished());
        assert_eq!(
            ini.channel_binding(),
            res.channel_binding(),
            "both peers derive the same binding"
        );
        assert_ne!(ini.channel_binding(), [0u8; 32]);
    }

    /// `channel_binding` must be a genuine, transcript-dependent hash — not a
    /// constant. Kills the `replace channel_binding -> [u8; 32] with [1; 32]`
    /// mutant (line 207): two independently-keyed handshakes must derive
    /// DIFFERENT bindings, and neither may equal the all-ones constant.
    #[test]
    fn channel_binding_is_transcript_dependent_not_constant() {
        fn complete_binding() -> [u8; 32] {
            let resp_kp = generate_keypair();
            let init_kp = generate_keypair();
            let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
            let mut res = Handshake::responder(&resp_kp.private).unwrap();
            let m1 = ini.write_message(&[]).unwrap();
            let _ = res.read_message(&m1).unwrap();
            let m2 = res.write_message(&[]).unwrap();
            let _ = ini.read_message(&m2).unwrap();
            assert!(ini.is_finished() && res.is_finished());
            let binding = ini.channel_binding();
            assert_eq!(binding, res.channel_binding());
            binding
        }

        let binding_a = complete_binding();
        let binding_b = complete_binding();
        assert_ne!(
            binding_a, [1u8; 32],
            "channel_binding must not be the constant [1; 32]"
        );
        assert_ne!(
            binding_b, [1u8; 32],
            "channel_binding must not be the constant [1; 32]"
        );
        assert_ne!(
            binding_a, binding_b,
            "two independent handshakes (different keys/transcripts) must \
             derive different channel bindings"
        );
    }

    #[test]
    fn ik_handshake_completes_and_authenticates_initiator() {
        let resp_kp = generate_keypair();
        let init_kp = generate_keypair();

        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();

        let msg1 = ini.write_message(&[]).unwrap();
        let _ = res.read_message(&msg1).unwrap();
        let msg2 = res.write_message(&[]).unwrap();
        let _ = ini.read_message(&msg2).unwrap();

        assert!(ini.is_finished() && res.is_finished());
        // IK: the responder learns the initiator's static public key.
        assert_eq!(res.remote_static(), Some(init_kp.public));
    }

    #[test]
    fn seal_is_byte_identical_across_a_reference_session() {
        // Two independently-built sessions from the same handshake produce the same
        // keystream for the same counter+plaintext; a receiver opens what a sender seals.
        let (mut a, mut b) = crate::test_session_pair();
        for ctr in 0u64..8 {
            let s = a.seal(&[0x5Au8; 64]).unwrap();
            assert_eq!(s.counter, ctr);
            assert_eq!(b.open(s.counter, &s.ciphertext).unwrap(), vec![0x5Au8; 64]);
        }
    }

    #[test]
    fn open_rejects_tampered_ciphertext() {
        let (mut a, mut b) = crate::test_session_pair();
        let s = a.seal(b"secret").unwrap();
        let mut bad = s.ciphertext.clone();
        bad[0] ^= 1;
        assert_eq!(b.open(s.counter, &bad), Err(CryptoError::Decrypt));
    }

    #[test]
    fn open_rejects_replay_and_opens_out_of_order() {
        let (mut a, mut b) = crate::test_session_pair();
        let s0 = a.seal(b"zero").unwrap();
        let s1 = a.seal(b"one").unwrap();
        assert_eq!(b.open(s1.counter, &s1.ciphertext).unwrap(), b"one"); // out of order
        assert_eq!(b.open(s0.counter, &s0.ciphertext).unwrap(), b"zero");
        assert_eq!(b.open(s1.counter, &s1.ciphertext), Err(CryptoError::Replay));
        // replay
    }

    /// Durable KAT (spec §5): the production `Session`'s `ring` ChaCha20-Poly1305
    /// output must be byte-for-byte identical to snow's own transport AEAD, for
    /// both handshake directions and several counters. This is the regression
    /// guard for `Handshake::into_session`'s role-dependent key mapping and for
    /// `noise_nonce`'s counter encoding: a swapped send/recv mapping or a
    /// big-endian (or otherwise wrong) nonce would still round-trip internally
    /// (seal/open use the same buggy convention on both sides) but would no
    /// longer match the expected output.
    ///
    /// Verify that driving completed initiator and responder handshakes yields
    /// symmetric raw split keys, and confirm that `Session::seal` produces
    /// byte-identical ciphertext to `snow::StatelessTransportState::write_message`
    /// across both peers in both directions for several counters.
    #[test]
    fn session_seal_is_byte_identical_to_snow_write_message_both_directions() {
        let resp_kp = generate_keypair();
        let init_kp = generate_keypair();

        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();

        let m1 = ini.write_message(&[]).unwrap();
        let _ = res.read_message(&m1).unwrap();
        let m2 = res.write_message(&[]).unwrap();
        let _ = ini.read_message(&m2).unwrap();

        assert!(ini.is_finished() && res.is_finished());

        let (ini_send, ini_recv) = ini.raw_split_keys();
        let (res_send, res_recv) = res.raw_split_keys();
        assert_eq!(
            ini_send, res_recv,
            "initiator send key matches responder recv key"
        );
        assert_eq!(
            ini_recv, res_send,
            "initiator recv key matches responder send key"
        );

        let mut ini_session = ini.to_session_for_test().unwrap();
        let mut res_session = res.to_session_for_test().unwrap();
        let snow_ini_ref = ini
            .into_inner_snow_for_test()
            .into_stateless_transport_mode()
            .unwrap();
        let snow_res_ref = res
            .into_inner_snow_for_test()
            .into_stateless_transport_mode()
            .unwrap();

        let plaintext: Vec<u8> = (0u8..200).collect();

        // initiator -> responder: production seal byte-identical to snow's
        // write_message (initiator role), and the responder session opens it.
        for ctr in 0u64..=4 {
            let sealed = ini_session.seal(&plaintext).unwrap();
            assert_eq!(sealed.counter, ctr);
            let mut snow_out = vec![0u8; plaintext.len() + 16];
            let n = snow_ini_ref
                .write_message(ctr, &plaintext, &mut snow_out)
                .unwrap();
            snow_out.truncate(n);
            assert_eq!(
                sealed.ciphertext, snow_out,
                "initiator->responder ciphertext byte-identical to snow at counter {ctr}"
            );
            assert_eq!(
                res_session
                    .open(sealed.counter, &sealed.ciphertext)
                    .unwrap(),
                plaintext,
                "responder opens what the initiator sealed at counter {ctr}"
            );
        }

        // responder -> initiator: the symmetric case
        for ctr in 0u64..=4 {
            let sealed = res_session.seal(&plaintext).unwrap();
            assert_eq!(sealed.counter, ctr);
            let mut snow_out = vec![0u8; plaintext.len() + 16];
            let n = snow_res_ref
                .write_message(ctr, &plaintext, &mut snow_out)
                .unwrap();
            snow_out.truncate(n);
            assert_eq!(
                sealed.ciphertext, snow_out,
                "responder->initiator ciphertext byte-identical to snow at counter {ctr}"
            );
            assert_eq!(
                ini_session
                    .open(sealed.counter, &sealed.ciphertext)
                    .unwrap(),
                plaintext,
                "initiator opens what the responder sealed at counter {ctr}"
            );
        }
    }

    #[test]
    fn seal_into_matches_seal_and_opens() {
        let (mut a, mut b) = crate::test_session_pair();
        let mut sbuf = Vec::new();
        let ctr = a.seal_into(b"reuse me", &mut sbuf).unwrap();
        let mut obuf = Vec::new();
        b.open_into(ctr, &sbuf, &mut obuf).unwrap();
        assert_eq!(obuf, b"reuse me");
    }

    #[test]
    fn test_wide_replay_window_jitter_and_rejection() {
        let mut w = ReplayWindow::new();
        // Initially accepts 0
        assert!(w.check(0));
        w.commit(0);

        // Advance latest to 100,000
        assert!(w.check(100_000));
        w.commit(100_000);

        // Packet 50,000 (diff = 50,000 < 131,072) must be accepted
        assert!(w.check(50_000));
        w.commit(50_000);

        // Duplicate 50,000 must be rejected
        assert!(!w.check(50_000));

        // Packet 0 is now 100,000 behind, which is < 131,072, but it was already seen
        assert!(!w.check(0));

        // Advance to 250,000
        assert!(w.check(250_000));
        w.commit(250_000);

        // Packet 100,000 is 150,000 behind (>= 131,072), must be rejected as too old
        assert!(!w.check(100_000));
    }

    #[test]
    fn test_seal_with_counter_and_open_with_window() {
        let (a, b) = crate::test_session_pair();
        let payload = b"concurrent multi-worker payload";
        let sealed = a.seal_with_counter(42, payload).unwrap();
        assert_eq!(sealed.counter, 42);

        let mut replay = ReplayWindow::new();
        let decrypted = b
            .open_with_window(sealed.counter, &sealed.ciphertext, &mut replay)
            .unwrap();
        assert_eq!(decrypted, payload);

        // Replay attempt must fail
        assert_eq!(
            b.open_with_window(sealed.counter, &sealed.ciphertext, &mut replay),
            Err(CryptoError::Replay)
        );
    }

    #[test]
    fn test_chacha20_poly1305_cipher_in_place() {
        let key = [0x5au8; 32];
        let cipher = ChaCha20Poly1305Cipher::new(key);
        let mut buffer = [0u8; 128];
        let plaintext = b"zero-copy in-place packet buffer payload";
        buffer[..plaintext.len()].copy_from_slice(plaintext);

        let counter = 100u64;
        let sealed_len = cipher
            .seal_in_place(counter, &mut buffer, plaintext.len())
            .expect("seal_in_place should succeed");
        assert_eq!(sealed_len, plaintext.len() + 16);
        assert_ne!(&buffer[..plaintext.len()], plaintext);

        let mut replay = ReplayWindow::new();
        let plain_len = cipher
            .open_in_place_with_window(counter, &mut buffer, sealed_len, &mut replay)
            .expect("open_in_place_with_window should succeed");
        assert_eq!(plain_len, plaintext.len());
        assert_eq!(&buffer[..plain_len], plaintext);

        // Replay rejection
        assert_eq!(
            cipher.open_in_place_with_window(counter, &mut buffer, sealed_len, &mut replay),
            Err(CryptoError::Replay)
        );
    }

    #[test]
    fn test_chacha20_poly1305_cipher_debug_and_boundaries() {
        let key = [0x5au8; 32];
        let cipher = ChaCha20Poly1305Cipher::new(key);
        let debug_str = format!("{cipher:?}");
        assert!(debug_str.contains("ChaCha20Poly1305Cipher"));

        let mut buf = [0u8; 32];
        // Exact buffer length (buf.len() == plaintext_len + 16): must succeed
        assert_eq!(cipher.seal_in_place(1, &mut buf[..16], 0).unwrap(), 16);

        // Buffer smaller than total_len (buf.len() < plaintext_len + 16): must fail
        assert_eq!(
            cipher.seal_in_place(1, &mut buf[..15], 0),
            Err(CryptoError::Decrypt)
        );

        // open_in_place: sealed_len < 16 must fail
        assert_eq!(
            cipher.open_in_place(1, &mut buf, 15),
            Err(CryptoError::Decrypt)
        );
        assert_eq!(
            cipher.open_in_place(1, &mut buf, 0),
            Err(CryptoError::Decrypt)
        );

        // open_in_place: buf.len() < sealed_len must fail (even when sealed_len >= 16)
        assert_eq!(
            cipher.open_in_place(1, &mut buf[..10], 16),
            Err(CryptoError::Decrypt)
        );

        // open_in_place: exact boundary sealed_len == 16 and buf.len() == 16
        let mut exact = [0u8; 16];
        cipher.seal_in_place(2, &mut exact, 0).unwrap();
        assert_eq!(cipher.open_in_place(2, &mut exact, 16).unwrap(), 0);
    }

    #[test]
    fn test_seal_into_with_counter_and_open_into_with_window() {
        let (a, b) = crate::test_session_pair();
        let payload = b"buffer test payload";
        let mut sealed_buf = Vec::new();
        a.seal_into_with_counter(42, payload, &mut sealed_buf)
            .unwrap();
        assert_ne!(sealed_buf, payload);
        assert_eq!(sealed_buf.len(), payload.len() + 16);

        let mut replay = ReplayWindow::new();
        let mut out = Vec::new();
        b.open_into_with_window(42, &sealed_buf, &mut replay, &mut out)
            .unwrap();
        assert_eq!(out, payload);

        // Replay attempt must fail and not modify output buffer
        out.clear();
        let err = b.open_into_with_window(42, &sealed_buf, &mut replay, &mut out);
        assert_eq!(err, Err(CryptoError::Replay));
        assert!(out.is_empty());

        // Forged tag must fail
        let mut bad_buf = sealed_buf.clone();
        bad_buf[0] ^= 1;
        let mut fresh_replay = ReplayWindow::new();
        let bad_err = b.open_into_with_window(43, &bad_buf, &mut fresh_replay, &mut out);
        assert_eq!(bad_err, Err(CryptoError::Decrypt));
    }

    #[test]
    fn test_replay_window_word_idx_distinct_words() {
        let mut w = ReplayWindow::new();
        w.commit(0);
        // Counters across different word indices (64, 128) must not falsely collide with 0
        assert!(w.check(64));
        assert!(w.check(128));
        w.commit(64);
        assert!(!w.check(64));
        assert!(!w.check(0));
        assert!(w.check(128));
    }

    #[test]
    fn test_promote_to_high_throughput_preserves_multi_word_state() {
        let mut w = ReplayWindow::new_with_profile(ReplayProfile::Standard);
        w.commit(100);
        w.commit(200);
        w.commit(1000);
        w.commit(1500);
        w.promote_to_high_throughput();
        assert_eq!(w.profile(), ReplayProfile::HighThroughput);

        assert!(!w.check(100));
        assert!(!w.check(200));
        assert!(!w.check(1000));
        assert!(!w.check(1500));

        assert!(w.check(101));
        assert!(w.check(201));
        assert!(w.check(1001));
        assert!(w.check(1499));
    }

    #[test]
    fn test_promote_to_high_throughput_large_latest() {
        // Case 1: latest_word is small (< old_words = 128 words).
        // latest_word = 10, so saturating_sub(127) == 0.
        // Under mutant `old_words + 1` = 129, saturating_sub(129) == 0 (no diff).
        // But under mutant `old_words / 1` = 128, saturating_sub(128) == 0.
        //
        // Case 2: latest_word >= old_words (e.g. latest_word = 200).
        // start_word should be 200 - 127 = 73.
        // Under mutant `+`: (old_words + 1) = 129 -> 200 - 129 = 71.
        // Under mutant `/`: (old_words / 1) = 128 -> 200 - 128 = 72.
        // Counter at word 72 is (72 * 64). Under the correct code (start_word = 73),
        // word 72 is NOT copied (it's older than 127 words from latest).
        // BUT wait: in standard window of 128 words, word 72 is diff = 200 - 72 = 128 words = 8192 bits!
        // 8192 bits is beyond standard window bits (8192), so its slot in old_bitmap is actually word 200's slot!
        // Notice: 72 & 127 = 72. 200 & 127 = 72!
        // If word 72 is copied to new_bitmap[72], while word 200 is copied to new_bitmap[200],
        // then word 72 in new_bitmap would receive the contents of old_bitmap[72]!
        // In the correct code (start_word = 73), word 72 is NOT visited, so new_bitmap[72] is 0!
        // Under mutant `+` or `/`: start_word <= 72, so loop visits w = 72 and copies old_bitmap[72] into new_bitmap[72]!
        // Therefore, counter (72 * 64 + bit) would falsely appear as committed in new_bitmap!
        let mut w = ReplayWindow::new_with_profile(ReplayProfile::Standard);
        let latest = 200 * 64 + 10;
        w.commit(latest);
        w.promote_to_high_throughput();

        // Counter at word 72 (e.g. 72 * 64 + 10) was never committed (it is 128 words older than latest).
        // In correct code, new_bitmap[72] == 0, so check(72 * 64 + 10) is true (not seen, acceptable).
        // Under mutant `-` -> `+` or `/`, w = 72 is included in the loop, copying old_bitmap[72] (which has bit 10 set from latest!)
        // into new_bitmap[72], so check(72 * 64 + 10) would falsely return false (already seen)!
        assert!(
            w.check(72 * 64 + 10),
            "counter 72 * 64 + 10 was never committed and must be acceptable"
        );

        // Also test that actual valid tail counter (word 73: 73 * 64 + 10) was committed and preserved:
        let mut w2 = ReplayWindow::new_with_profile(ReplayProfile::Standard);
        w2.commit(73 * 64 + 10);
        w2.commit(latest);
        w2.promote_to_high_throughput();
        assert!(!w2.check(latest), "latest must still be marked seen");
        assert!(
            !w2.check(73 * 64 + 10),
            "tail counter in word 73 must be marked seen"
        );
    }

    #[test]
    fn test_replay_window_circular_word_clearing() {
        let mut w = ReplayWindow::new_with_profile(ReplayProfile::Standard);
        w.commit(69);
        assert!(!w.check(69));

        w.commit(8192 + 74);
        assert!(!w.check(8192 + 74));

        assert!(
            w.check(8192 + 69),
            "counter 8192 + 69 must not be blocked by stale bit from counter 69"
        );
    }

    #[test]
    fn test_replay_window_consecutive_word_clearing() {
        let mut w = ReplayWindow::new_with_profile(ReplayProfile::Standard);
        w.commit(130);
        w.commit(8192 + 70);
        w.commit(8192 + 135);
        assert!(
            w.check(8192 + 130),
            "counter 8192 + 130 must be accepted after word 2 is overtaken and cleared"
        );

        // Kills: replace - with + in diff = counter - self.latest
        w.commit(3000);
        w.commit(3001);
        w.commit(3500); // 3500 - 3001 = 499 < 8192. Under +, 3500 + 3001 = 6501, wait!
                        // Under +, diff = 3500 + 3001 = 6501, which is < 8192! We need counter + latest >= 8192:
                        // Say latest = 5000, counter = 5100: diff = 5100 - 5000 = 100 < 8192.
                        // Under +, diff = 5100 + 5000 = 10100 >= 8192 (large leap clears bitmap!).
        w.commit(5000);
        w.commit(5001);
        w.commit(5100);
        assert!(!w.check(5001), "counter 5001 must still be marked seen");
    }

    #[test]
    fn test_session_set_stride_and_send_counter() {
        let (mut a, _) = crate::test_session_pair();
        assert_eq!(a.send_counter(), 0);
        assert_ne!(a.send_counter(), 1);

        // Initial configuration on fresh session (send_counter == 0):
        a.set_stride(5, 4);
        assert_eq!(a.stride(), 4);
        assert_eq!(a.send_counter(), 5);

        // Stride 0 falls back to 1:
        // send_counter was 5. With stride 1, target_rem = 10 % 1 = 0, rem = 5 % 1 = 0.
        // send_counter remains 5.
        a.set_stride(10, 0);
        assert_eq!(a.stride(), 1);
        assert_eq!(a.send_counter(), 5);

        // Reconfiguration with send_counter > 0 and rem <= target_rem:
        // currently send_counter is 5.
        // stride = 4, start_counter = 3.
        // rem = 5 % 4 = 1.
        // target_rem = 3 % 4 = 3.
        // rem (1) <= target_rem (3) -> diff = 3 - 1 = 2.
        // send_counter becomes 5 + 2 = 7. 7 % 4 == 3.
        a.set_stride(3, 4);
        assert_eq!(a.stride(), 4);
        assert_eq!(a.send_counter(), 7);
        assert_eq!(a.send_counter() % 4, 3);

        // Reconfiguration with send_counter > 0 and rem > target_rem where (rem - target_rem) > 1:
        // currently send_counter is 7.
        // Let's set stride = 8, start_counter = 1.
        // rem = 7 % 8 = 7.
        // target_rem = 1 % 8 = 1.
        // rem (7) > target_rem (1) -> (rem - target_rem) = 6.
        // Correct diff: 8 - 6 = 2. send_counter becomes 7 + 2 = 9. 9 % 8 = 1.
        // Mutant diff: 8 / 6 = 1. send_counter becomes 7 + 1 = 8. 8 % 8 = 0 != 1.
        a.set_stride(1, 8);
        assert_eq!(a.stride(), 8);
        assert_eq!(a.send_counter(), 9);
        assert_eq!(a.send_counter() % 8, 1);
    }

    #[test]
    fn test_session_seal_in_place_and_open_in_place_boundaries() {
        let (mut a, mut b) = crate::test_session_pair();
        let mut buf = [0u8; 32];
        // Exact length buf.len() == plaintext_len + 16: succeeds
        let ctr = a.seal_in_place(&mut buf[..16], 0).unwrap();
        assert_eq!(ctr, 0);

        // Buffer smaller than total_len: fails
        assert_eq!(
            a.seal_in_place(&mut buf[..15], 0),
            Err(CryptoError::Decrypt)
        );

        // open_in_place: sealed_len < 16 fails
        assert_eq!(b.open_in_place(0, &mut buf, 15), Err(CryptoError::Decrypt));
        assert_eq!(b.open_in_place(0, &mut buf, 0), Err(CryptoError::Decrypt));

        // open_in_place: buf.len() < sealed_len fails
        assert_eq!(
            b.open_in_place(0, &mut buf[..10], 16),
            Err(CryptoError::Decrypt)
        );

        // open_in_place: exact boundary sealed_len == 16 and buf.len() == 16: succeeds
        let mut exact = [0u8; 16];
        let ctr2 = a.seal_in_place(&mut exact, 0).unwrap();
        assert_eq!(b.open_in_place(ctr2, &mut exact, 16).unwrap(), 0);
    }

    #[test]
    fn pq_keypair_encapsulate_decapsulate_roundtrip() {
        let (ek, dk) = generate_pq_keypair();
        assert_eq!(ek.0.len(), PQ_ENCAPS_KEY_LEN);

        let (ct, ss_sender) = pq_encapsulate(&ek).expect("encapsulation succeeds");
        assert_eq!(ct.0.len(), PQ_CIPHERTEXT_LEN);
        assert_eq!(ss_sender.len(), PQ_SHARED_SECRET_LEN);

        let ss_recipient = pq_decapsulate(&dk, &ct).expect("decapsulation succeeds");
        assert_eq!(
            *ss_sender, *ss_recipient,
            "both sides agree on 32-byte shared secret"
        );
    }

    #[test]
    fn pq_encapsulate_rejects_fips203_invalid_modulus() {
        let (mut ek, _dk) = generate_pq_keypair();
        // FIPS 203 Section 7.2 ByteDecode_12 requires all 12-bit coefficients < q (3329).
        // Inject 0x0FFF (4095 >= 3329) into the first coefficient pair.
        ek.0[0] = 0xFF;
        ek.0[1] = 0x0F;
        let res = pq_encapsulate(&ek);
        assert!(
            res.is_err(),
            "encapsulation must reject coefficient >= 3329"
        );
    }

    #[test]
    fn pq_decapsulate_implicit_rejection_on_tampered_ciphertext() {
        let (ek, dk) = generate_pq_keypair();
        let (mut ct, ss_sender) = pq_encapsulate(&ek).expect("encapsulation succeeds");

        // Tamper with the ciphertext: flip one bit in ct
        ct.0[0] ^= 0x01;
        let ss_recipient =
            pq_decapsulate(&dk, &ct).expect("decapsulation succeeds via implicit rejection");
        assert_ne!(
            *ss_sender, *ss_recipient,
            "FIPS 203 implicit rejection must yield a distinct pseudorandom secret on tampered ciphertext"
        );
    }

    #[test]
    fn pq_decaps_key_debug_redacted() {
        let (_ek, dk) = generate_pq_keypair();
        assert_eq!(format!("{:?}", dk), "PqDecapsKey([REDACTED])");
    }

    #[test]
    fn pq_encapsulate_rejects_fips203_invalid_modulus_second_coeff() {
        let (mut ek, _dk) = generate_pq_keypair();
        // FIPS 203 Section 7.2 ByteDecode_12 requires all 12-bit coefficients < q (3329).
        // Inject 0x0FFF (4095 >= 3329) into the second coefficient (d1) of the first chunk.
        // d1 = (chunk[1] >> 4) | (chunk[2] << 4)
        // Setting chunk[1] = 0xF0 and chunk[2] = 0xFF gives d1 = 0xFFF = 4095.
        // Ensure d0 = chunk[0] | ((chunk[1] & 0x0F) << 8) remains < 3329: chunk[0]=0, chunk[1]&0x0F=0 => d0 = 0.
        ek.0[0] = 0x00;
        ek.0[1] = 0xF0;
        ek.0[2] = 0xFF;
        let res = pq_encapsulate(&ek);
        assert!(
            res.is_err(),
            "encapsulation must reject second coefficient >= 3329"
        );
    }

    #[test]
    fn pq_hybrid_handshake_roundtrip_with_payload() {
        let init_kp = generate_keypair();
        let resp_kp = generate_keypair();

        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();

        let cert_a = b"initiator-test-certificate-128b";
        let cert_b = b"responder-test-certificate-128b";

        // Msg 1: Initiator -> Responder
        let msg1 = ini.write_message(cert_a).unwrap();
        // Msg 1 wire size = 32(e) + 48(s) + 800(ek) + cert_a.len() + 16(tag)
        assert_eq!(msg1.len(), 32 + 48 + PQ_ENCAPS_KEY_LEN + cert_a.len() + 16);

        let p1 = res.read_message(&msg1).unwrap();
        assert_eq!(p1, cert_a);
        assert_eq!(res.remote_static(), Some(init_kp.public));

        // Msg 2: Responder -> Initiator
        let msg2 = res.write_message(cert_b).unwrap();
        // Msg 2 wire size = 768(ct) + 32(e) + cert_b.len() + 16(tag)
        assert_eq!(msg2.len(), PQ_CIPHERTEXT_LEN + 32 + cert_b.len() + 16);

        let p2 = ini.read_message(&msg2).unwrap();
        assert_eq!(p2, cert_b);
        assert_eq!(ini.remote_static(), Some(resp_kp.public));

        assert!(ini.is_finished());
        assert!(res.is_finished());
        assert_eq!(ini.channel_binding(), res.channel_binding());

        let (ini_send, ini_recv) = ini.raw_split_keys();
        let (res_send, res_recv) = res.raw_split_keys();
        assert_eq!(ini_send, res_recv);
        assert_eq!(ini_recv, res_send);

        let mut ini_session = ini.into_session().unwrap();
        let mut res_session = res.into_session().unwrap();
        let sealed = ini_session.seal(b"quantum safe transport payload").unwrap();
        let opened = res_session
            .open(sealed.counter, &sealed.ciphertext)
            .unwrap();
        assert_eq!(opened, b"quantum safe transport payload");
    }

    #[test]
    fn pq_hybrid_handshake_rejects_tampered_ciphertext() {
        let init_kp = generate_keypair();
        let resp_kp = generate_keypair();

        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();

        let msg1 = ini.write_message(b"certA").unwrap();
        let _ = res.read_message(&msg1).unwrap();
        let mut msg2 = res.write_message(b"certB").unwrap();

        // Tamper with the cleartext ct prefix of msg2
        msg2[10] ^= 0x01;

        // Initiator decapsulates to a mismatched ss, causing snow Poly1305 MAC to fail
        let err = ini.read_message(&msg2);
        assert!(err.is_err(), "tampered ct must fail handshake verification");
    }

    #[test]
    fn pq_handshake_read_message_rejects_truncated_message() {
        let init_kp = generate_keypair();
        let resp_kp = generate_keypair();

        let mut ini = Handshake::initiator(&init_kp.private, &resp_kp.public).unwrap();
        let mut res = Handshake::responder(&resp_kp.private).unwrap();

        // Initiator sends valid msg1 to responder
        let msg1 = ini.write_message(b"certA").unwrap();
        // Responder rejects truncated msg1
        assert!(res.read_message(&msg1[..10]).is_err());

        let _ = res.read_message(&msg1).unwrap();
        let msg2 = res.write_message(b"certB").unwrap();

        // Initiator rejects msg2 shorter than PQ_CIPHERTEXT_LEN
        let truncated = vec![0u8; PQ_CIPHERTEXT_LEN - 1];
        assert!(ini.read_message(&truncated).is_err());
        assert!(ini.read_message(&msg2[..PQ_CIPHERTEXT_LEN]).is_err());
    }

    #[test]
    fn session_check_replay_is_non_committing() {
        let (a, mut b) = crate::test_session_pair();
        assert!(b.check_replay(1));
        assert!(b.check_replay(1));

        let sealed = a.seal_with_counter(1, b"hello").unwrap();
        let opened = b.open(sealed.counter, &sealed.ciphertext).unwrap();
        assert_eq!(opened, b"hello");

        assert!(!b.check_replay(1));
    }
}