lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! # Post-Quantum Cryptography for LCPFS
//!
//! This module provides post-quantum key encapsulation using **real, audited
//! cryptographic implementations** from established crates:
//!
//! - **ML-KEM-1024** (Kyber): Via `ml-kem` crate (RustCrypto) - NIST FIPS 203 standard
//! - **X25519**: Via `x25519-dalek` crate - Classical ECDH for hybrid security
//!
//! ## Why Hybrid Encryption?
//!
//! LCPFS uses X25519 + ML-KEM-1024 hybrid for defense-in-depth:
//! - If quantum computers break X25519 → ML-KEM protects
//! - If ML-KEM has undiscovered weakness → X25519 protects
//!
//! ## IMPORTANT: No Custom Crypto
//!
//! This module contains NO custom cryptographic implementations. All crypto
//! operations are delegated to vetted external crates. We only provide:
//! - Type wrappers for LCPFS integration
//! - Hybrid KEM combination logic (simple hash-based key derivation)
//!
//! The previous implementation was broken - it used SHA-256 instead of SHAKE,
//! had incorrect CBD sampling, and the "encryption" was just XOR. This version
//! uses real implementations.

use alloc::vec::Vec;
use core::fmt;
use ed25519_dalek::{Signer as Ed25519Signer, Verifier as Ed25519Verifier};
use ed25519_dalek::{SigningKey as Ed25519SigningKey, VerifyingKey as Ed25519VerifyingKey};
use hybrid_array;
use ml_dsa::signature::{Keypair, Signer as MlDsaSigner, Verifier as MlDsaVerifier};
use ml_dsa::{B32, KeyGen as MlDsaKeyGen, KeyPair as MlDsaKeyPair, MlDsa65};
use ml_kem::kem::{Decapsulate, Encapsulate};
use ml_kem::{Ciphertext, EncodedSizeUser, KemCore, MlKem1024, SharedKey};
use rand_core::CryptoRngCore;
use sha2::{Digest, Sha256};
use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519SecretKey};
use zeroize::Zeroize;

// ═══════════════════════════════════════════════════════════════════════════════
// ERROR TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Post-quantum cryptography errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PqcError {
    /// ML-KEM encapsulation failed.
    EncapsulationFailed,
    /// ML-KEM decapsulation failed.
    DecapsulationFailed,
    /// Invalid ciphertext size.
    InvalidCiphertextSize,
    /// Invalid key size.
    InvalidKeySize,
    /// Seed conversion failed.
    SeedConversionFailed,
}

impl fmt::Display for PqcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PqcError::EncapsulationFailed => write!(f, "ML-KEM encapsulation failed"),
            PqcError::DecapsulationFailed => write!(f, "ML-KEM decapsulation failed"),
            PqcError::InvalidCiphertextSize => write!(f, "Invalid ciphertext size"),
            PqcError::InvalidKeySize => write!(f, "Invalid key size"),
            PqcError::SeedConversionFailed => write!(f, "Seed conversion failed"),
        }
    }
}

// Type aliases for the ml-kem types
type MlKem1024Ek = <MlKem1024 as KemCore>::EncapsulationKey;
type MlKem1024Dk = <MlKem1024 as KemCore>::DecapsulationKey;
type MlKem1024Ct = Ciphertext<MlKem1024>;
type MlKem1024Ss = SharedKey<MlKem1024>;

// Type aliases for the ml-dsa types using KeyPair
type MlDsa65Kp = MlDsaKeyPair<MlDsa65>;
type MlDsa65SigningKey = ml_dsa::SigningKey<MlDsa65>;
type MlDsa65VerifyingKey = ml_dsa::VerifyingKey<MlDsa65>;
type MlDsa65Signature = ml_dsa::Signature<MlDsa65>;

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS FROM ML-KEM-1024 SPECIFICATION
// ═══════════════════════════════════════════════════════════════════════════════

/// ML-KEM-1024 encapsulation key (public key) size: 1568 bytes
pub const MLKEM_EK_BYTES: usize = 1568;
/// ML-KEM-1024 decapsulation key (secret key) size: 3168 bytes
pub const MLKEM_DK_BYTES: usize = 3168;
/// ML-KEM-1024 ciphertext size: 1568 bytes
pub const MLKEM_CT_BYTES: usize = 1568;
/// Shared secret size: 32 bytes
pub const SHARED_SECRET_BYTES: usize = 32;

/// X25519 key size (32 bytes)
pub const X25519_KEY_BYTES: usize = 32;

/// Hybrid public key size: ML-KEM + X25519
pub const HYBRID_PK_BYTES: usize = MLKEM_EK_BYTES + X25519_KEY_BYTES;
/// Hybrid secret key size: ML-KEM + X25519
pub const HYBRID_SK_BYTES: usize = MLKEM_DK_BYTES + X25519_KEY_BYTES;
/// Hybrid ciphertext size: ML-KEM CT + X25519 ephemeral public key
pub const HYBRID_CT_BYTES: usize = MLKEM_CT_BYTES + X25519_KEY_BYTES;

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS FROM ML-DSA-65 SPECIFICATION (FIPS 204)
// ═══════════════════════════════════════════════════════════════════════════════

/// ML-DSA-65 verifying key (public key) size: 1952 bytes
pub const MLDSA_VK_BYTES: usize = 1952;
/// ML-DSA-65 signing key (secret key) size: 4032 bytes
pub const MLDSA_SK_BYTES: usize = 4032;
/// ML-DSA-65 signature size: 3309 bytes
pub const MLDSA_SIG_BYTES: usize = 3309;

/// Ed25519 key size (32 bytes)
pub const ED25519_KEY_BYTES: usize = 32;
/// Ed25519 signature size (64 bytes)
pub const ED25519_SIG_BYTES: usize = 64;

/// Hybrid signing public key size: ML-DSA VK + Ed25519 VK
pub const HYBRID_SIG_PK_BYTES: usize = MLDSA_VK_BYTES + ED25519_KEY_BYTES;
/// Hybrid signing secret key size: ML-DSA SK + Ed25519 SK
pub const HYBRID_SIG_SK_BYTES: usize = MLDSA_SK_BYTES + ED25519_KEY_BYTES;
/// Hybrid signature size: ML-DSA sig + Ed25519 sig
pub const HYBRID_SIG_BYTES: usize = MLDSA_SIG_BYTES + ED25519_SIG_BYTES;

// ═══════════════════════════════════════════════════════════════════════════════
// ML-KEM-1024 WRAPPER (Direct passthrough to ml-kem crate)
// ═══════════════════════════════════════════════════════════════════════════════

/// ML-KEM-1024 encapsulation key (public key) wrapper.
#[derive(Clone)]
pub struct MlKemEncapsulationKey {
    inner: MlKem1024Ek,
}

/// ML-KEM-1024 decapsulation key (secret key) wrapper.
pub struct MlKemDecapsulationKey {
    inner: MlKem1024Dk,
}

/// ML-KEM-1024 ciphertext wrapper.
#[derive(Clone)]
pub struct MlKemCiphertext {
    /// Raw ciphertext bytes
    pub bytes: [u8; MLKEM_CT_BYTES],
}

/// Generate an ML-KEM-1024 keypair using the provided RNG.
///
/// This is a direct wrapper around `ml_kem::MlKem1024::generate()`.
pub fn mlkem_keygen(
    rng: &mut impl CryptoRngCore,
) -> (MlKemEncapsulationKey, MlKemDecapsulationKey) {
    let (dk, ek) = MlKem1024::generate(rng);

    (
        MlKemEncapsulationKey { inner: ek },
        MlKemDecapsulationKey { inner: dk },
    )
}

/// Encapsulate a shared secret using an ML-KEM-1024 encapsulation key.
///
/// Returns (ciphertext, shared_secret) on success.
///
/// # Errors
///
/// Returns `PqcError::EncapsulationFailed` if the encapsulation operation fails.
pub fn mlkem_encaps(
    ek: &MlKemEncapsulationKey,
    rng: &mut impl CryptoRngCore,
) -> Result<(MlKemCiphertext, [u8; SHARED_SECRET_BYTES]), PqcError> {
    let (ct, ss): (MlKem1024Ct, MlKem1024Ss) = ek
        .inner
        .encapsulate(rng)
        .map_err(|_| PqcError::EncapsulationFailed)?;

    let mut ct_bytes = [0u8; MLKEM_CT_BYTES];
    ct_bytes.copy_from_slice(ct.as_slice());

    let mut ss_bytes = [0u8; SHARED_SECRET_BYTES];
    ss_bytes.copy_from_slice(ss.as_slice());

    Ok((MlKemCiphertext { bytes: ct_bytes }, ss_bytes))
}

/// Decapsulate a shared secret using an ML-KEM-1024 decapsulation key.
///
/// # Errors
///
/// Returns `PqcError::InvalidCiphertextSize` if the ciphertext has wrong size.
/// Returns `PqcError::DecapsulationFailed` if decapsulation fails.
pub fn mlkem_decaps(
    ct: &MlKemCiphertext,
    dk: &MlKemDecapsulationKey,
) -> Result<[u8; SHARED_SECRET_BYTES], PqcError> {
    let ct_arr =
        MlKem1024Ct::try_from(ct.bytes.as_slice()).map_err(|_| PqcError::InvalidCiphertextSize)?;

    let ss: MlKem1024Ss = dk
        .inner
        .decapsulate(&ct_arr)
        .map_err(|_| PqcError::DecapsulationFailed)?;

    let mut ss_bytes = [0u8; SHARED_SECRET_BYTES];
    ss_bytes.copy_from_slice(ss.as_slice());
    Ok(ss_bytes)
}

impl MlKemEncapsulationKey {
    /// Serialize to bytes.
    pub fn to_bytes(&self) -> [u8; MLKEM_EK_BYTES] {
        let mut out = [0u8; MLKEM_EK_BYTES];
        out.copy_from_slice(&self.inner.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8; MLKEM_EK_BYTES]) -> Self {
        use ml_kem::kem::EncapsulationKey;
        Self {
            inner: EncapsulationKey::from_bytes(data.into()),
        }
    }
}

impl MlKemDecapsulationKey {
    /// Serialize to bytes.
    pub fn to_bytes(&self) -> [u8; MLKEM_DK_BYTES] {
        let mut out = [0u8; MLKEM_DK_BYTES];
        out.copy_from_slice(&self.inner.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8; MLKEM_DK_BYTES]) -> Self {
        use ml_kem::kem::DecapsulationKey;
        Self {
            inner: DecapsulationKey::from_bytes(data.into()),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// X25519 WRAPPER (Direct passthrough to x25519-dalek)
// ═══════════════════════════════════════════════════════════════════════════════

/// Generate an X25519 keypair using the provided RNG.
pub fn x25519_keygen(rng: &mut impl CryptoRngCore) -> (X25519PublicKey, X25519SecretKey) {
    let secret = X25519SecretKey::random_from_rng(rng);
    let public = X25519PublicKey::from(&secret);
    (public, secret)
}

/// Perform X25519 Diffie-Hellman key exchange.
pub fn x25519_dh(our_secret: &X25519SecretKey, their_public: &X25519PublicKey) -> [u8; 32] {
    our_secret.diffie_hellman(their_public).to_bytes()
}

// ═══════════════════════════════════════════════════════════════════════════════
// HYBRID KEM: X25519 + ML-KEM-1024
// ═══════════════════════════════════════════════════════════════════════════════

/// Hybrid public key combining X25519 and ML-KEM-1024.
#[derive(Clone)]
pub struct HybridPublicKey {
    /// ML-KEM-1024 encapsulation key
    pub mlkem: MlKemEncapsulationKey,
    /// X25519 public key
    pub x25519: X25519PublicKey,
}

impl HybridPublicKey {
    /// Serialize to bytes: [ML-KEM EK || X25519 PK]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HYBRID_PK_BYTES);
        out.extend_from_slice(&self.mlkem.to_bytes());
        out.extend_from_slice(self.x25519.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() != HYBRID_PK_BYTES {
            return None;
        }

        let mut mlkem_bytes = [0u8; MLKEM_EK_BYTES];
        mlkem_bytes.copy_from_slice(&data[..MLKEM_EK_BYTES]);

        let mut x25519_bytes = [0u8; X25519_KEY_BYTES];
        x25519_bytes.copy_from_slice(&data[MLKEM_EK_BYTES..]);

        Some(Self {
            mlkem: MlKemEncapsulationKey::from_bytes(&mlkem_bytes),
            x25519: X25519PublicKey::from(x25519_bytes),
        })
    }
}

/// Hybrid secret key combining X25519 and ML-KEM-1024.
pub struct HybridSecretKey {
    /// ML-KEM-1024 decapsulation key
    pub mlkem: MlKemDecapsulationKey,
    /// X25519 secret key
    pub x25519: X25519SecretKey,
}

impl HybridSecretKey {
    /// Serialize to bytes: [ML-KEM DK || X25519 SK]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HYBRID_SK_BYTES);
        out.extend_from_slice(&self.mlkem.to_bytes());
        out.extend_from_slice(self.x25519.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() != HYBRID_SK_BYTES {
            return None;
        }

        let mut mlkem_bytes = [0u8; MLKEM_DK_BYTES];
        mlkem_bytes.copy_from_slice(&data[..MLKEM_DK_BYTES]);

        let mut x25519_bytes = [0u8; X25519_KEY_BYTES];
        x25519_bytes.copy_from_slice(&data[MLKEM_DK_BYTES..]);

        Some(Self {
            mlkem: MlKemDecapsulationKey::from_bytes(&mlkem_bytes),
            x25519: X25519SecretKey::from(x25519_bytes),
        })
    }
}

/// Hybrid ciphertext combining ML-KEM-1024 CT and X25519 ephemeral public key.
#[derive(Clone)]
pub struct HybridCiphertext {
    /// ML-KEM-1024 ciphertext
    pub mlkem_ct: MlKemCiphertext,
    /// X25519 ephemeral public key
    pub x25519_eph_pk: X25519PublicKey,
}

impl HybridCiphertext {
    /// Serialize to bytes: [ML-KEM CT || X25519 ephemeral PK]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HYBRID_CT_BYTES);
        out.extend_from_slice(&self.mlkem_ct.bytes);
        out.extend_from_slice(self.x25519_eph_pk.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() != HYBRID_CT_BYTES {
            return None;
        }

        let mut mlkem_bytes = [0u8; MLKEM_CT_BYTES];
        mlkem_bytes.copy_from_slice(&data[..MLKEM_CT_BYTES]);

        let mut x25519_bytes = [0u8; X25519_KEY_BYTES];
        x25519_bytes.copy_from_slice(&data[MLKEM_CT_BYTES..]);

        Some(Self {
            mlkem_ct: MlKemCiphertext { bytes: mlkem_bytes },
            x25519_eph_pk: X25519PublicKey::from(x25519_bytes),
        })
    }
}

/// Generate a hybrid X25519 + ML-KEM-1024 keypair.
pub fn hybrid_keygen(rng: &mut impl CryptoRngCore) -> (HybridPublicKey, HybridSecretKey) {
    let (mlkem_ek, mlkem_dk) = mlkem_keygen(rng);
    let (x25519_pk, x25519_sk) = x25519_keygen(rng);

    (
        HybridPublicKey {
            mlkem: mlkem_ek,
            x25519: x25519_pk,
        },
        HybridSecretKey {
            mlkem: mlkem_dk,
            x25519: x25519_sk,
        },
    )
}

/// Encapsulate a shared secret using hybrid X25519 + ML-KEM-1024.
///
/// The shared secret is derived as: SHA-256(domain || mlkem_ss || x25519_ss)
///
/// This provides defense-in-depth:
/// - If ML-KEM is broken, X25519 protects
/// - If X25519 is broken (quantum), ML-KEM protects
///
/// # Errors
///
/// Returns `PqcError::EncapsulationFailed` if ML-KEM encapsulation fails.
pub fn hybrid_encaps(
    pk: &HybridPublicKey,
    rng: &mut impl CryptoRngCore,
) -> Result<(HybridCiphertext, [u8; SHARED_SECRET_BYTES]), PqcError> {
    // ML-KEM encapsulation
    let (mlkem_ct, mlkem_ss) = mlkem_encaps(&pk.mlkem, rng)?;

    // X25519: Generate ephemeral keypair and compute DH
    let (x25519_eph_pk, x25519_eph_sk) = x25519_keygen(rng);
    let x25519_ss = x25519_dh(&x25519_eph_sk, &pk.x25519);

    // Combine shared secrets: SHA-256(domain || mlkem_ss || x25519_ss)
    let combined_ss = combine_shared_secrets(&mlkem_ss, &x25519_ss);

    let ct = HybridCiphertext {
        mlkem_ct,
        x25519_eph_pk,
    };

    Ok((ct, combined_ss))
}

/// Decapsulate a shared secret using hybrid X25519 + ML-KEM-1024.
///
/// # Errors
///
/// Returns `PqcError::DecapsulationFailed` or `PqcError::InvalidCiphertextSize`
/// if ML-KEM decapsulation fails.
pub fn hybrid_decaps(
    ct: &HybridCiphertext,
    sk: &HybridSecretKey,
) -> Result<[u8; SHARED_SECRET_BYTES], PqcError> {
    // ML-KEM decapsulation
    let mlkem_ss = mlkem_decaps(&ct.mlkem_ct, &sk.mlkem)?;

    // X25519: Compute DH with ephemeral public key
    let x25519_ss = x25519_dh(&sk.x25519, &ct.x25519_eph_pk);

    // Combine shared secrets: SHA-256(domain || mlkem_ss || x25519_ss)
    Ok(combine_shared_secrets(&mlkem_ss, &x25519_ss))
}

/// Combine two shared secrets using SHA-256.
///
/// This is the only "crypto" we do ourselves, and it's just a hash.
fn combine_shared_secrets(ss1: &[u8; 32], ss2: &[u8; 32]) -> [u8; 32] {
    let mut hasher = Sha256::new();
    hasher.update(b"LCPFS_HYBRID_KEM_V1"); // Domain separator
    hasher.update(ss1);
    hasher.update(ss2);
    let result = hasher.finalize();

    let mut out = [0u8; 32];
    out.copy_from_slice(&result);
    out
}

// ═══════════════════════════════════════════════════════════════════════════════
// LEGACY COMPATIBILITY ALIASES
// ═══════════════════════════════════════════════════════════════════════════════

/// Legacy alias: Kyber ciphertext (now ML-KEM ciphertext)
pub type KyberCiphertext = MlKemCiphertext;

/// Legacy alias: Kyber public key size (same as ML-KEM encapsulation key)
pub const KYBER_PK_BYTES: usize = MLKEM_EK_BYTES;
/// Legacy alias: Kyber secret key size (same as ML-KEM decapsulation key)
pub const KYBER_SK_BYTES: usize = MLKEM_DK_BYTES;
/// Legacy alias: Kyber ciphertext size (same as ML-KEM ciphertext)
pub const KYBER_CT_BYTES: usize = MLKEM_CT_BYTES;

/// Legacy wrapper for Kyber public key with `.data` field access.
#[derive(Clone)]
pub struct KyberPublicKey {
    /// Raw public key bytes for legacy code compatibility
    pub data: [u8; MLKEM_EK_BYTES],
    inner: MlKemEncapsulationKey,
}

impl KyberPublicKey {
    /// Get the inner ML-KEM encapsulation key.
    pub fn inner(&self) -> &MlKemEncapsulationKey {
        &self.inner
    }
}

/// Legacy wrapper for Kyber secret key.
pub struct KyberSecretKey {
    inner: MlKemDecapsulationKey,
}

impl Clone for KyberSecretKey {
    fn clone(&self) -> Self {
        Self {
            inner: MlKemDecapsulationKey::from_bytes(&self.inner.to_bytes()),
        }
    }
}

impl KyberSecretKey {
    /// Get the inner ML-KEM decapsulation key.
    pub fn inner(&self) -> &MlKemDecapsulationKey {
        &self.inner
    }

    /// Clone the secret key (requires explicit call for security awareness).
    pub fn clone_key(&self) -> Self {
        Self {
            inner: MlKemDecapsulationKey::from_bytes(&self.inner.to_bytes()),
        }
    }
}

/// Legacy Kyber engine for backward compatibility.
///
/// Provides a seed-based keypair generation method for legacy code.
pub struct KyberEngine;

impl KyberEngine {
    /// Generate a keypair from a 32-byte seed.
    ///
    /// Uses the seed to create a deterministic RNG for keypair generation.
    /// This is primarily for testing; production code should use proper RNGs.
    pub fn keypair(seed: &[u8; 32]) -> (KyberPublicKey, KyberSecretKey) {
        use rand_core::{CryptoRng, RngCore};

        // Simple seeded RNG for deterministic keypair generation
        struct SeededRng {
            state: [u8; 32],
            counter: u64,
        }

        impl SeededRng {
            fn new(seed: &[u8; 32]) -> Self {
                Self {
                    state: *seed,
                    counter: 0,
                }
            }
        }

        impl RngCore for SeededRng {
            fn next_u32(&mut self) -> u32 {
                self.next_u64() as u32
            }

            fn next_u64(&mut self) -> u64 {
                // Mix seed with counter using SHA-256-like mixing
                let mut hasher = Sha256::new();
                hasher.update(self.state);
                hasher.update(self.counter.to_le_bytes());
                let hash = hasher.finalize();

                self.counter += 1;

                // Update state for next iteration
                self.state.copy_from_slice(&hash);

                u64::from_le_bytes([
                    hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7],
                ])
            }

            fn fill_bytes(&mut self, dest: &mut [u8]) {
                for chunk in dest.chunks_mut(8) {
                    let val = self.next_u64().to_le_bytes();
                    let len = chunk.len().min(8);
                    chunk.copy_from_slice(&val[..len]);
                }
            }

            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
                self.fill_bytes(dest);
                Ok(())
            }
        }

        impl CryptoRng for SeededRng {}

        let mut rng = SeededRng::new(seed);
        let (ek, dk) = mlkem_keygen(&mut rng);

        let data = ek.to_bytes();

        (
            KyberPublicKey { data, inner: ek },
            KyberSecretKey { inner: dk },
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ML-DSA-65 WRAPPER (Direct passthrough to ml-dsa crate)
// ═══════════════════════════════════════════════════════════════════════════════

/// ML-DSA-65 verifying key (public key) wrapper.
#[derive(Clone)]
pub struct MlDsaVerifyingKey {
    inner: MlDsa65VerifyingKey,
}

/// ML-DSA-65 signing key (secret key) wrapper.
pub struct MlDsaSigningKey {
    inner: MlDsa65SigningKey,
}

/// ML-DSA-65 signature wrapper.
#[derive(Clone)]
pub struct MlDsaSignature {
    inner: MlDsa65Signature,
}

/// Generate an ML-DSA-65 keypair using the provided RNG.
///
/// Uses a 32-byte seed derived from the RNG for deterministic keypair generation.
///
/// # Errors
///
/// Returns `PqcError::SeedConversionFailed` if seed array conversion fails.
pub fn mldsa_keygen(
    rng: &mut impl CryptoRngCore,
) -> Result<(MlDsaVerifyingKey, MlDsaSigningKey), PqcError> {
    // Generate a 32-byte seed from the RNG
    let mut seed = [0u8; 32];
    rng.fill_bytes(&mut seed);

    // Use from_seed for deterministic keypair generation
    let seed_arr: B32 = hybrid_array::Array::try_from(seed.as_slice())
        .map_err(|_| PqcError::SeedConversionFailed)?;
    let kp: MlDsa65Kp = MlDsa65::from_seed(&seed_arr);

    Ok((
        MlDsaVerifyingKey {
            inner: kp.verifying_key().clone(),
        },
        MlDsaSigningKey {
            inner: kp.signing_key().clone(),
        },
    ))
}

/// Sign a message using ML-DSA-65.
pub fn mldsa_sign(sk: &MlDsaSigningKey, message: &[u8]) -> MlDsaSignature {
    let sig = sk.inner.sign(message);
    MlDsaSignature { inner: sig }
}

/// Verify an ML-DSA-65 signature.
pub fn mldsa_verify(vk: &MlDsaVerifyingKey, message: &[u8], sig: &MlDsaSignature) -> bool {
    vk.inner.verify(message, &sig.inner).is_ok()
}

impl MlDsaVerifyingKey {
    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.inner.encode().to_vec()
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        use ml_dsa::VerifyingKey;
        if data.len() != MLDSA_VK_BYTES {
            return None;
        }
        let arr: ml_dsa::EncodedVerifyingKey<MlDsa65> = hybrid_array::Array::try_from(data).ok()?;
        Some(Self {
            inner: VerifyingKey::decode(&arr),
        })
    }
}

impl MlDsaSigningKey {
    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.inner.encode().to_vec()
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        use ml_dsa::SigningKey;
        if data.len() != MLDSA_SK_BYTES {
            return None;
        }
        let arr: ml_dsa::EncodedSigningKey<MlDsa65> = hybrid_array::Array::try_from(data).ok()?;
        Some(Self {
            inner: SigningKey::decode(&arr),
        })
    }
}

impl MlDsaSignature {
    /// Serialize to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        self.inner.encode().to_vec()
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        use ml_dsa::Signature;
        if data.len() != MLDSA_SIG_BYTES {
            return None;
        }
        let arr: ml_dsa::EncodedSignature<MlDsa65> = hybrid_array::Array::try_from(data).ok()?;
        let sig = Signature::decode(&arr)?;
        Some(Self { inner: sig })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ED25519 WRAPPER (Direct passthrough to ed25519-dalek)
// ═══════════════════════════════════════════════════════════════════════════════

/// Generate an Ed25519 keypair using the provided RNG.
pub fn ed25519_keygen(rng: &mut impl CryptoRngCore) -> (Ed25519VerifyingKey, Ed25519SigningKey) {
    // Generate 32 random bytes for the secret key
    let mut secret_bytes = [0u8; 32];
    rng.fill_bytes(&mut secret_bytes);

    let signing_key = Ed25519SigningKey::from_bytes(&secret_bytes);
    let verifying_key = signing_key.verifying_key();
    (verifying_key, signing_key)
}

/// Sign a message using Ed25519.
pub fn ed25519_sign(sk: &Ed25519SigningKey, message: &[u8]) -> ed25519_dalek::Signature {
    sk.sign(message)
}

/// Verify an Ed25519 signature.
pub fn ed25519_verify(
    vk: &Ed25519VerifyingKey,
    message: &[u8],
    sig: &ed25519_dalek::Signature,
) -> bool {
    vk.verify(message, sig).is_ok()
}

// ═══════════════════════════════════════════════════════════════════════════════
// HYBRID SIGNATURES: Ed25519 + ML-DSA-65
// ═══════════════════════════════════════════════════════════════════════════════

/// Hybrid verifying key combining Ed25519 and ML-DSA-65.
///
/// ## Why Hybrid Signatures?
///
/// LCPFS uses Ed25519 + ML-DSA-65 hybrid for defense-in-depth:
/// - If quantum computers break Ed25519 → ML-DSA protects
/// - If ML-DSA has undiscovered weakness → Ed25519 protects
#[derive(Clone)]
pub struct HybridSigningPublicKey {
    /// ML-DSA-65 verifying key
    pub mldsa: MlDsaVerifyingKey,
    /// Ed25519 verifying key
    pub ed25519: Ed25519VerifyingKey,
}

impl HybridSigningPublicKey {
    /// Serialize to bytes: [ML-DSA VK || Ed25519 VK]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HYBRID_SIG_PK_BYTES);
        out.extend_from_slice(&self.mldsa.to_bytes());
        out.extend_from_slice(self.ed25519.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() != HYBRID_SIG_PK_BYTES {
            return None;
        }

        let mldsa = MlDsaVerifyingKey::from_bytes(&data[..MLDSA_VK_BYTES])?;

        let mut ed25519_bytes = [0u8; ED25519_KEY_BYTES];
        ed25519_bytes.copy_from_slice(&data[MLDSA_VK_BYTES..]);
        let ed25519 = Ed25519VerifyingKey::from_bytes(&ed25519_bytes).ok()?;

        Some(Self { mldsa, ed25519 })
    }
}

/// Hybrid signing key combining Ed25519 and ML-DSA-65.
pub struct HybridSigningSecretKey {
    /// ML-DSA-65 signing key
    pub mldsa: MlDsaSigningKey,
    /// Ed25519 signing key
    pub ed25519: Ed25519SigningKey,
}

impl HybridSigningSecretKey {
    /// Serialize to bytes: [ML-DSA SK || Ed25519 SK]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HYBRID_SIG_SK_BYTES);
        out.extend_from_slice(&self.mldsa.to_bytes());
        out.extend_from_slice(self.ed25519.as_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() != HYBRID_SIG_SK_BYTES {
            return None;
        }

        let mldsa = MlDsaSigningKey::from_bytes(&data[..MLDSA_SK_BYTES])?;

        let mut ed25519_bytes = [0u8; ED25519_KEY_BYTES];
        ed25519_bytes.copy_from_slice(&data[MLDSA_SK_BYTES..]);
        let ed25519 = Ed25519SigningKey::from_bytes(&ed25519_bytes);

        Some(Self { mldsa, ed25519 })
    }
}

/// Hybrid signature combining ML-DSA-65 and Ed25519.
#[derive(Clone)]
pub struct HybridSignature {
    /// ML-DSA-65 signature
    pub mldsa_sig: MlDsaSignature,
    /// Ed25519 signature
    pub ed25519_sig: ed25519_dalek::Signature,
}

impl HybridSignature {
    /// Serialize to bytes: [ML-DSA sig || Ed25519 sig]
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(HYBRID_SIG_BYTES);
        out.extend_from_slice(&self.mldsa_sig.to_bytes());
        out.extend_from_slice(&self.ed25519_sig.to_bytes());
        out
    }

    /// Deserialize from bytes.
    pub fn from_bytes(data: &[u8]) -> Option<Self> {
        if data.len() != HYBRID_SIG_BYTES {
            return None;
        }

        let mldsa_sig = MlDsaSignature::from_bytes(&data[..MLDSA_SIG_BYTES])?;

        let mut ed25519_bytes = [0u8; ED25519_SIG_BYTES];
        ed25519_bytes.copy_from_slice(&data[MLDSA_SIG_BYTES..]);
        let ed25519_sig = ed25519_dalek::Signature::from_bytes(&ed25519_bytes);

        Some(Self {
            mldsa_sig,
            ed25519_sig,
        })
    }
}

/// Generate a hybrid Ed25519 + ML-DSA-65 signing keypair.
///
/// # Errors
///
/// Returns `PqcError::SeedConversionFailed` if ML-DSA key generation fails.
pub fn hybrid_sign_keygen(
    rng: &mut impl CryptoRngCore,
) -> Result<(HybridSigningPublicKey, HybridSigningSecretKey), PqcError> {
    let (mldsa_vk, mldsa_sk) = mldsa_keygen(rng)?;
    let (ed25519_vk, ed25519_sk) = ed25519_keygen(rng);

    Ok((
        HybridSigningPublicKey {
            mldsa: mldsa_vk,
            ed25519: ed25519_vk,
        },
        HybridSigningSecretKey {
            mldsa: mldsa_sk,
            ed25519: ed25519_sk,
        },
    ))
}

/// Sign a message using hybrid Ed25519 + ML-DSA-65.
///
/// Both algorithms sign the same message independently.
/// This provides defense-in-depth:
/// - If ML-DSA is broken, Ed25519 protects
/// - If Ed25519 is broken (quantum), ML-DSA protects
pub fn hybrid_sign(sk: &HybridSigningSecretKey, message: &[u8]) -> HybridSignature {
    // ML-DSA signature
    let mldsa_sig = mldsa_sign(&sk.mldsa, message);

    // Ed25519 signature
    let ed25519_sig = ed25519_sign(&sk.ed25519, message);

    HybridSignature {
        mldsa_sig,
        ed25519_sig,
    }
}

/// Verify a hybrid Ed25519 + ML-DSA-65 signature.
///
/// BOTH signatures must be valid for the verification to succeed.
/// This ensures security even if one algorithm is broken.
pub fn hybrid_verify(pk: &HybridSigningPublicKey, message: &[u8], sig: &HybridSignature) -> bool {
    // Both signatures must verify
    let mldsa_ok = mldsa_verify(&pk.mldsa, message, &sig.mldsa_sig);
    let ed25519_ok = ed25519_verify(&pk.ed25519, message, &sig.ed25519_sig);

    mldsa_ok && ed25519_ok
}

// ═══════════════════════════════════════════════════════════════════════════════
// LEGACY COMPATIBILITY ALIASES FOR SIGNATURES
// ═══════════════════════════════════════════════════════════════════════════════

/// Legacy alias: Dilithium verifying key (now ML-DSA verifying key)
pub type DilithiumVerifyingKey = MlDsaVerifyingKey;

/// Legacy alias: Dilithium signing key (now ML-DSA signing key)
pub type DilithiumSigningKey = MlDsaSigningKey;

/// Legacy alias: Dilithium signature (now ML-DSA signature)
pub type DilithiumSignature = MlDsaSignature;

/// Legacy wrapper for Dilithium/ML-DSA key generation.
pub struct DilithiumEngine;

impl DilithiumEngine {
    /// Generate a keypair from a 32-byte seed.
    ///
    /// Uses the seed to create a deterministic RNG for keypair generation.
    /// This is primarily for testing; production code should use proper RNGs.
    ///
    /// # Errors
    ///
    /// Returns `PqcError::SeedConversionFailed` if key generation fails.
    pub fn keypair(seed: &[u8; 32]) -> Result<(MlDsaVerifyingKey, MlDsaSigningKey), PqcError> {
        use rand_core::{CryptoRng, RngCore};

        // Simple seeded RNG for deterministic keypair generation
        struct SeededRng {
            state: [u8; 32],
            counter: u64,
        }

        impl SeededRng {
            fn new(seed: &[u8; 32]) -> Self {
                Self {
                    state: *seed,
                    counter: 0,
                }
            }
        }

        impl RngCore for SeededRng {
            fn next_u32(&mut self) -> u32 {
                self.next_u64() as u32
            }

            fn next_u64(&mut self) -> u64 {
                let mut hasher = Sha256::new();
                hasher.update(self.state);
                hasher.update(self.counter.to_le_bytes());
                let hash = hasher.finalize();

                self.counter += 1;
                self.state.copy_from_slice(&hash);

                u64::from_le_bytes([
                    hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7],
                ])
            }

            fn fill_bytes(&mut self, dest: &mut [u8]) {
                for chunk in dest.chunks_mut(8) {
                    let val = self.next_u64().to_le_bytes();
                    let len = chunk.len().min(8);
                    chunk.copy_from_slice(&val[..len]);
                }
            }

            fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
                self.fill_bytes(dest);
                Ok(())
            }
        }

        impl CryptoRng for SeededRng {}

        let mut rng = SeededRng::new(seed);
        mldsa_keygen(&mut rng)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use rand_core::{CryptoRng, RngCore};

    // Simple deterministic RNG for testing (NOT for production!)
    struct TestRng {
        state: u64,
    }

    impl TestRng {
        fn new(seed: u64) -> Self {
            Self { state: seed }
        }
    }

    impl RngCore for TestRng {
        fn next_u32(&mut self) -> u32 {
            self.next_u64() as u32
        }

        fn next_u64(&mut self) -> u64 {
            // Simple xorshift64
            self.state ^= self.state << 13;
            self.state ^= self.state >> 7;
            self.state ^= self.state << 17;
            self.state
        }

        fn fill_bytes(&mut self, dest: &mut [u8]) {
            for chunk in dest.chunks_mut(8) {
                let val = self.next_u64().to_le_bytes();
                let len = chunk.len().min(8);
                chunk.copy_from_slice(&val[..len]);
            }
        }

        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
            self.fill_bytes(dest);
            Ok(())
        }
    }

    impl CryptoRng for TestRng {}

    #[test]
    fn test_mlkem_roundtrip() {
        let mut rng = TestRng::new(0x12345678);

        let (ek, dk) = mlkem_keygen(&mut rng);
        let (ct, ss_enc) = mlkem_encaps(&ek, &mut rng).expect("encapsulation failed");
        let ss_dec = mlkem_decaps(&ct, &dk).expect("decapsulation failed");

        assert_eq!(ss_enc, ss_dec, "ML-KEM shared secrets must match");
    }

    #[test]
    fn test_x25519_roundtrip() {
        let mut rng = TestRng::new(0xABCDEF00);

        let (pk_a, sk_a) = x25519_keygen(&mut rng);
        let (pk_b, sk_b) = x25519_keygen(&mut rng);

        let ss_ab = x25519_dh(&sk_a, &pk_b);
        let ss_ba = x25519_dh(&sk_b, &pk_a);

        assert_eq!(ss_ab, ss_ba, "X25519 DH must be symmetric");
    }

    #[test]
    fn test_hybrid_roundtrip() {
        let mut rng = TestRng::new(0xDEADBEEF);

        let (pk, sk) = hybrid_keygen(&mut rng);
        let (ct, ss_enc) = hybrid_encaps(&pk, &mut rng).expect("hybrid encapsulation failed");
        let ss_dec = hybrid_decaps(&ct, &sk).expect("hybrid decapsulation failed");

        assert_eq!(ss_enc, ss_dec, "Hybrid shared secrets must match");
    }

    #[test]
    fn test_hybrid_serialization() {
        let mut rng = TestRng::new(0xCAFEBABE);

        let (pk, sk) = hybrid_keygen(&mut rng);

        // Test public key serialization
        let pk_bytes = pk.to_bytes();
        assert_eq!(pk_bytes.len(), HYBRID_PK_BYTES);
        let pk_restored = HybridPublicKey::from_bytes(&pk_bytes).unwrap();
        assert_eq!(pk.mlkem.to_bytes(), pk_restored.mlkem.to_bytes());
        assert_eq!(pk.x25519.as_bytes(), pk_restored.x25519.as_bytes());

        // Test secret key serialization
        let sk_bytes = sk.to_bytes();
        assert_eq!(sk_bytes.len(), HYBRID_SK_BYTES);
        let sk_restored = HybridSecretKey::from_bytes(&sk_bytes).unwrap();
        assert_eq!(sk.mlkem.to_bytes(), sk_restored.mlkem.to_bytes());

        // Test ciphertext serialization
        let (ct, _) = hybrid_encaps(&pk, &mut rng).expect("encapsulation failed");
        let ct_bytes = ct.to_bytes();
        assert_eq!(ct_bytes.len(), HYBRID_CT_BYTES);
        let ct_restored = HybridCiphertext::from_bytes(&ct_bytes).unwrap();
        assert_eq!(ct.mlkem_ct.bytes, ct_restored.mlkem_ct.bytes);
        assert_eq!(
            ct.x25519_eph_pk.as_bytes(),
            ct_restored.x25519_eph_pk.as_bytes()
        );
    }

    #[test]
    fn test_different_keys_different_secrets() {
        let mut rng = TestRng::new(0x11111111);

        let (pk1, _sk1) = hybrid_keygen(&mut rng);
        let (pk2, sk2) = hybrid_keygen(&mut rng);

        // Encapsulate to pk1
        let (ct, ss_enc) = hybrid_encaps(&pk1, &mut rng).expect("encapsulation failed");

        // Try to decapsulate with sk2 (wrong key)
        let ss_wrong = hybrid_decaps(&ct, &sk2).expect("decapsulation failed");

        // Should NOT match (with overwhelming probability)
        assert_ne!(
            ss_enc, ss_wrong,
            "Wrong key must not produce correct secret"
        );
    }

    #[test]
    fn test_key_sizes() {
        // Verify our constants match the crate's actual sizes
        let mut rng = TestRng::new(0x99999999);
        let (ek, dk) = mlkem_keygen(&mut rng);

        assert_eq!(ek.to_bytes().len(), MLKEM_EK_BYTES);
        assert_eq!(dk.to_bytes().len(), MLKEM_DK_BYTES);

        let (ct, ss) = mlkem_encaps(&ek, &mut rng).expect("encapsulation failed");
        assert_eq!(ct.bytes.len(), MLKEM_CT_BYTES);
        assert_eq!(ss.len(), SHARED_SECRET_BYTES);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // ML-DSA SIGNATURE TESTS
    // ═══════════════════════════════════════════════════════════════════════════

    #[test]
    fn test_mldsa_sign_verify() {
        let mut rng = TestRng::new(0xA1A2A3A4);

        let (vk, sk) = mldsa_keygen(&mut rng).expect("keygen failed");
        let message = b"Hello, post-quantum world!";
        let sig = mldsa_sign(&sk, message);

        assert!(
            mldsa_verify(&vk, message, &sig),
            "Valid signature must verify"
        );
    }

    #[test]
    fn test_mldsa_wrong_message() {
        let mut rng = TestRng::new(0xB1B2B3B4);

        let (vk, sk) = mldsa_keygen(&mut rng).expect("keygen failed");
        let message = b"Original message";
        let sig = mldsa_sign(&sk, message);

        let wrong_message = b"Tampered message";
        assert!(
            !mldsa_verify(&vk, wrong_message, &sig),
            "Wrong message must not verify"
        );
    }

    #[test]
    fn test_mldsa_wrong_key() {
        let mut rng = TestRng::new(0xC1C2C3C4);

        let (vk1, sk1) = mldsa_keygen(&mut rng).expect("keygen failed");
        let (vk2, _sk2) = mldsa_keygen(&mut rng).expect("keygen failed");

        let message = b"Test message";
        let sig = mldsa_sign(&sk1, message);

        // Verify with wrong key
        assert!(
            !mldsa_verify(&vk2, message, &sig),
            "Wrong key must not verify"
        );
        // Verify with correct key
        assert!(mldsa_verify(&vk1, message, &sig), "Correct key must verify");
    }

    #[test]
    fn test_ed25519_sign_verify() {
        let mut rng = TestRng::new(0xD1D2D3D4);

        let (vk, sk) = ed25519_keygen(&mut rng);
        let message = b"Ed25519 test message";
        let sig = ed25519_sign(&sk, message);

        assert!(
            ed25519_verify(&vk, message, &sig),
            "Valid signature must verify"
        );
    }

    #[test]
    fn test_hybrid_signature_roundtrip() {
        let mut rng = TestRng::new(0xE1E2E3E4);

        let (pk, sk) = hybrid_sign_keygen(&mut rng).expect("keygen failed");
        let message = b"Hybrid signature test message";
        let sig = hybrid_sign(&sk, message);

        assert!(
            hybrid_verify(&pk, message, &sig),
            "Hybrid signature must verify"
        );
    }

    #[test]
    fn test_hybrid_signature_wrong_message() {
        let mut rng = TestRng::new(0xF1F2F3F4);

        let (pk, sk) = hybrid_sign_keygen(&mut rng).expect("keygen failed");
        let message = b"Original hybrid message";
        let sig = hybrid_sign(&sk, message);

        let wrong_message = b"Wrong hybrid message";
        assert!(
            !hybrid_verify(&pk, wrong_message, &sig),
            "Wrong message must fail verification"
        );
    }

    #[test]
    fn test_hybrid_signature_serialization() {
        let mut rng = TestRng::new(0x12121212);

        let (pk, sk) = hybrid_sign_keygen(&mut rng).expect("keygen failed");

        // Test public key serialization
        let pk_bytes = pk.to_bytes();
        assert_eq!(pk_bytes.len(), HYBRID_SIG_PK_BYTES);
        let pk_restored = HybridSigningPublicKey::from_bytes(&pk_bytes).unwrap();
        assert_eq!(pk.mldsa.to_bytes(), pk_restored.mldsa.to_bytes());

        // Test secret key serialization
        let sk_bytes = sk.to_bytes();
        assert_eq!(sk_bytes.len(), HYBRID_SIG_SK_BYTES);

        // Test signature serialization
        let message = b"Test serialization";
        let sig = hybrid_sign(&sk, message);
        let sig_bytes = sig.to_bytes();
        assert_eq!(sig_bytes.len(), HYBRID_SIG_BYTES);
        let sig_restored = HybridSignature::from_bytes(&sig_bytes).unwrap();

        // Verify restored signature works
        assert!(
            hybrid_verify(&pk, message, &sig_restored),
            "Restored signature must verify"
        );
    }

    #[test]
    fn test_dilithium_legacy_engine() {
        // Test legacy Dilithium API
        let seed = [0x42u8; 32];
        let (vk, sk) = DilithiumEngine::keypair(&seed).expect("legacy keygen failed");

        let message = b"Legacy Dilithium test";
        let sig = mldsa_sign(&sk, message);

        assert!(
            mldsa_verify(&vk, message, &sig),
            "Legacy Dilithium signature must verify"
        );
    }
}