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
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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// LunaVault - Encrypted Container Support
//
// Format inspired by VeraCrypt (https://veracrypt.fr), an Apache 2.0 licensed
// project by IDRIX (Mounir Idrassi). We thank the VeraCrypt team for their
// exceptional work on privacy-preserving storage technology.
//
// This is a clean-room implementation using public cryptographic standards
// (XTS-AES, PBKDF2, Argon2). No VeraCrypt code was used.

//! # LunaVault - Encrypted Containers for LCPFS
//!
//! VeraCrypt-compatible portable encrypted containers with:
//! - File-hosted volumes (single `.lcv` file = portable encrypted volume)
//! - Hidden volumes (two passwords → two volumes, plausible deniability)
//! - Multiple encryption algorithms (AES, Serpent, Twofish, cascades)
//! - PBKDF2/Argon2 key derivation with PIM support
//! - Keyfile support
//! - XTS mode for sector encryption
//!
//! ## Usage
//!
//! ```rust,ignore
//! use lcpfs::lcpfs_lunavault::{LunaVault, LunaVaultOptions, EncryptionAlgorithm};
//!
//! // Create a 1GB encrypted container
//! LunaVault::create(
//!     "/path/to/container.lcv",
//!     "my_strong_password",
//!     1024 * 1024 * 1024,  // 1 GB
//!     LunaVaultOptions::default(),
//! )?;
//!
//! // Mount it
//! let mount = LunaVault::mount(
//!     "/path/to/container.lcv",
//!     "my_strong_password",
//!     "/mnt/secure",
//!     MountOptions::default(),
//! )?;
//! ```

#![allow(unused_imports)]

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryInto;
use crc32fast::Hasher as Crc32Hasher;
use lazy_static::lazy_static;
use spin::Mutex;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::FsError;
use crate::crypto::random;

// Re-export v2 implementation submodules for standalone no_std use
#[cfg(feature = "lunavault_v2")]
pub mod types {
    pub use crate::vault::types::*;
}

#[cfg(feature = "lunavault_v2")]
pub mod crypto {
    pub use crate::vault::crypto::*;
}

#[cfg(feature = "lunavault_v2")]
pub mod volume {
    pub use crate::vault::volume::*;
}

#[cfg(feature = "lunavault_v2")]
pub mod device {
    pub use crate::vault::device::*;
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Magic bytes for VeraCrypt-compatible volumes (after decryption)
pub const VERA_MAGIC: [u8; 4] = *b"VERA";

/// Magic bytes for LunaVault native format
pub const LUNA_MAGIC: [u8; 4] = *b"LUNA";

/// Volume header size (64 KB)
pub const HEADER_SIZE: usize = 65536;

/// Salt size in bytes
pub const SALT_SIZE: usize = 64;

/// Encrypted header portion size
pub const ENCRYPTED_HEADER_SIZE: usize = 512;

/// Master key size in bytes (for single algorithm)
pub const MASTER_KEY_SIZE: usize = 64;

/// Secondary key size for XTS mode
pub const SECONDARY_KEY_SIZE: usize = 64;

/// Default sector size
pub const SECTOR_SIZE: usize = 512;

/// Minimum volume size (1 MB)
pub const MIN_VOLUME_SIZE: u64 = 1024 * 1024;

/// Default PBKDF2 iterations for SHA-512
pub const DEFAULT_ITERATIONS_SHA512: u32 = 500_000;

/// Default PBKDF2 iterations for SHA-256
pub const DEFAULT_ITERATIONS_SHA256: u32 = 200_000;

/// PIM multiplier for additional iterations
pub const PIM_MULTIPLIER: u32 = 1000;

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

/// Errors specific to LunaVault operations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VaultError {
    /// Invalid password or keyfiles
    InvalidCredentials,
    /// Volume header is corrupted
    CorruptedHeader,
    /// CRC32 mismatch in header
    HeaderCrcMismatch,
    /// Volume is already mounted
    AlreadyMounted,
    /// Volume is not mounted
    NotMounted,
    /// Volume size too small
    VolumeTooSmall,
    /// Hidden volume would overlap with outer volume data
    HiddenVolumeOverlap,
    /// Encryption algorithm not supported
    UnsupportedAlgorithm,
    /// I/O error
    IoError(String),
    /// Key derivation error
    KeyDerivationError,
    /// Container file not found
    FileNotFound,
    /// Write protected area (hidden volume protection)
    WriteProtected,
    /// Not encrypted (for crypto erase)
    NotEncrypted,
    /// Internal error
    Internal(&'static str),
}

impl From<VaultError> for FsError {
    fn from(e: VaultError) -> Self {
        match e {
            VaultError::InvalidCredentials => FsError::DecryptionFailed,
            VaultError::CorruptedHeader => FsError::Corruption {
                block: 0,
                details: "vault header corrupted",
            },
            VaultError::IoError(_) => FsError::IoError {
                vdev: 0,
                reason: "vault I/O error",
            },
            _ => FsError::InvalidArgument {
                reason: "vault error",
            },
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ENCRYPTION ALGORITHMS
// ═══════════════════════════════════════════════════════════════════════════════

/// Encryption algorithm for volume data
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EncryptionAlgorithm {
    /// AES-256 in XTS mode
    #[default]
    Aes256,
    /// Serpent-256 in XTS mode
    Serpent256,
    /// Twofish-256 in XTS mode
    Twofish256,
    /// AES-256 → Twofish-256 cascade
    AesTwofish,
    /// AES-256 → Twofish-256 → Serpent-256 cascade
    AesTwofishSerpent,
    /// Serpent-256 → AES-256 cascade
    SerpentAes,
    /// ChaCha20-Poly1305 (LCPFS extension, not VeraCrypt compatible)
    ChaCha20,
}

impl EncryptionAlgorithm {
    /// Get the number of keys required for this algorithm
    pub fn key_count(&self) -> usize {
        match self {
            Self::Aes256 | Self::Serpent256 | Self::Twofish256 | Self::ChaCha20 => 1,
            Self::AesTwofish | Self::SerpentAes => 2,
            Self::AesTwofishSerpent => 3,
        }
    }

    /// Get total key bytes needed (master + secondary for XTS)
    pub fn total_key_bytes(&self) -> usize {
        self.key_count() * 64 // 32 bytes master + 32 bytes XTS secondary per algorithm
    }
}

/// Hash algorithm for key derivation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HashAlgorithm {
    /// SHA-512 (VeraCrypt default)
    #[default]
    Sha512,
    /// SHA-256
    Sha256,
    /// BLAKE3 (LCPFS extension)
    Blake3,
    /// Argon2id (memory-hard)
    Argon2,
}

/// Filesystem type for the volume
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FilesystemType {
    /// LCPFS native filesystem
    #[default]
    Lcpfs,
    /// FAT32 for cross-platform compatibility
    Fat32,
    /// exFAT
    ExFat,
    /// No filesystem (raw volume)
    None,
}

// ═══════════════════════════════════════════════════════════════════════════════
// VOLUME HEADER STRUCTURE
// ═══════════════════════════════════════════════════════════════════════════════

/// Volume header (decrypted form)
///
/// This structure matches the VeraCrypt header format for compatibility.
/// Total size: 512 bytes (encrypted portion)
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct VaultHeader {
    /// Magic bytes ("VERA" or "LUNA" after decryption)
    pub magic: [u8; 4],
    /// Header format version
    pub version: u16,
    /// Minimum program version required to open
    pub min_version: u16,
    /// CRC32 of decrypted header (bytes 256-511)
    pub crc32: u32,
    /// Reserved bytes
    pub reserved1: [u8; 16],
    /// Size of hidden volume (0 if none)
    pub hidden_size: u64,
    /// Total volume size
    pub volume_size: u64,
    /// Offset to encrypted data area
    pub data_offset: u64,
    /// Size of encrypted data area
    pub data_size: u64,
    /// Volume flags
    pub flags: u32,
    /// Sector size (typically 512)
    pub sector_size: u32,
    /// Reserved bytes
    pub reserved2: [u8; 120],
    /// Master encryption key(s)
    pub master_key: [u8; 64],
    /// Secondary key(s) for XTS mode
    pub secondary_key: [u8; 64],
    /// Salt used for this header's key derivation
    pub salt: [u8; 64],
}

impl VaultHeader {
    /// Create a new header with default values
    pub fn new() -> Self {
        Self {
            magic: LUNA_MAGIC,
            version: 5,
            min_version: 5,
            crc32: 0,
            reserved1: [0; 16],
            hidden_size: 0,
            volume_size: 0,
            data_offset: HEADER_SIZE as u64,
            data_size: 0,
            flags: 0,
            sector_size: SECTOR_SIZE as u32,
            reserved2: [0; 120],
            master_key: [0; 64],
            secondary_key: [0; 64],
            salt: [0; 64],
        }
    }

    /// Serialize header to bytes
    pub fn to_bytes(&self) -> [u8; ENCRYPTED_HEADER_SIZE] {
        let mut bytes = [0u8; ENCRYPTED_HEADER_SIZE];
        let mut offset = 0;

        // Magic (4 bytes)
        bytes[offset..offset + 4].copy_from_slice(&self.magic);
        offset += 4;

        // Version (2 bytes)
        bytes[offset..offset + 2].copy_from_slice(&self.version.to_le_bytes());
        offset += 2;

        // Min version (2 bytes)
        bytes[offset..offset + 2].copy_from_slice(&self.min_version.to_le_bytes());
        offset += 2;

        // CRC32 (4 bytes)
        bytes[offset..offset + 4].copy_from_slice(&self.crc32.to_le_bytes());
        offset += 4;

        // Reserved1 (16 bytes)
        bytes[offset..offset + 16].copy_from_slice(&self.reserved1);
        offset += 16;

        // Hidden size (8 bytes)
        bytes[offset..offset + 8].copy_from_slice(&self.hidden_size.to_le_bytes());
        offset += 8;

        // Volume size (8 bytes)
        bytes[offset..offset + 8].copy_from_slice(&self.volume_size.to_le_bytes());
        offset += 8;

        // Data offset (8 bytes)
        bytes[offset..offset + 8].copy_from_slice(&self.data_offset.to_le_bytes());
        offset += 8;

        // Data size (8 bytes)
        bytes[offset..offset + 8].copy_from_slice(&self.data_size.to_le_bytes());
        offset += 8;

        // Flags (4 bytes)
        bytes[offset..offset + 4].copy_from_slice(&self.flags.to_le_bytes());
        offset += 4;

        // Sector size (4 bytes)
        bytes[offset..offset + 4].copy_from_slice(&self.sector_size.to_le_bytes());
        offset += 4;

        // Reserved2 (120 bytes)
        bytes[offset..offset + 120].copy_from_slice(&self.reserved2);
        offset += 120;

        // Master key (64 bytes)
        bytes[offset..offset + 64].copy_from_slice(&self.master_key);
        offset += 64;

        // Secondary key (64 bytes)
        bytes[offset..offset + 64].copy_from_slice(&self.secondary_key);
        offset += 64;

        // Salt (64 bytes)
        bytes[offset..offset + 64].copy_from_slice(&self.salt);

        bytes
    }

    /// Deserialize header from bytes
    pub fn from_bytes(bytes: &[u8; ENCRYPTED_HEADER_SIZE]) -> Self {
        let mut header = Self::new();
        let mut offset = 0;

        // Magic (4 bytes)
        header.magic.copy_from_slice(&bytes[offset..offset + 4]);
        offset += 4;

        // Version (2 bytes)
        header.version = u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap());
        offset += 2;

        // Min version (2 bytes)
        header.min_version = u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap());
        offset += 2;

        // CRC32 (4 bytes)
        header.crc32 = u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap());
        offset += 4;

        // Reserved1 (16 bytes)
        header
            .reserved1
            .copy_from_slice(&bytes[offset..offset + 16]);
        offset += 16;

        // Hidden size (8 bytes)
        header.hidden_size = u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());
        offset += 8;

        // Volume size (8 bytes)
        header.volume_size = u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());
        offset += 8;

        // Data offset (8 bytes)
        header.data_offset = u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());
        offset += 8;

        // Data size (8 bytes)
        header.data_size = u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap());
        offset += 8;

        // Flags (4 bytes)
        header.flags = u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap());
        offset += 4;

        // Sector size (4 bytes)
        header.sector_size = u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap());
        offset += 4;

        // Reserved2 (120 bytes)
        header
            .reserved2
            .copy_from_slice(&bytes[offset..offset + 120]);
        offset += 120;

        // Master key (64 bytes)
        header
            .master_key
            .copy_from_slice(&bytes[offset..offset + 64]);
        offset += 64;

        // Secondary key (64 bytes)
        header
            .secondary_key
            .copy_from_slice(&bytes[offset..offset + 64]);
        offset += 64;

        // Salt (64 bytes)
        header.salt.copy_from_slice(&bytes[offset..offset + 64]);

        header
    }

    /// Calculate CRC32 of header bytes 256-511
    pub fn calculate_crc32(&self) -> u32 {
        let bytes = self.to_bytes();
        crc32_slice(&bytes[256..512])
    }

    /// Verify header magic bytes
    pub fn verify_magic(&self) -> bool {
        self.magic == VERA_MAGIC || self.magic == LUNA_MAGIC
    }

    /// Verify header CRC32
    pub fn verify_crc32(&self) -> bool {
        self.crc32 == self.calculate_crc32()
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// CRC32 (using crc32fast crate - SIMD accelerated)
// ═══════════════════════════════════════════════════════════════════════════════

/// Calculate CRC32 checksum of a byte slice using crc32fast crate.
///
/// Uses hardware-accelerated CRC32C instructions when available (SSE4.2 on x86,
/// native CRC32 on aarch64), falling back to an optimized software implementation.
pub fn crc32_slice(data: &[u8]) -> u32 {
    let mut hasher = Crc32Hasher::new();
    hasher.update(data);
    hasher.finalize()
}

// ═══════════════════════════════════════════════════════════════════════════════
// VOLUME OPTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Options for creating a new LunaVault volume
#[derive(Debug, Clone)]
pub struct LunaVaultOptions {
    /// Encryption algorithm
    pub encryption: EncryptionAlgorithm,
    /// Hash algorithm for key derivation
    pub hash: HashAlgorithm,
    /// Personal Iterations Multiplier (0 = default iterations)
    pub pim: u32,
    /// Keyfile paths (combined with password)
    pub keyfiles: Vec<String>,
    /// Filesystem type to format
    pub filesystem: FilesystemType,
    /// Use VeraCrypt-compatible format
    pub veracrypt_compatible: bool,
}

impl Default for LunaVaultOptions {
    fn default() -> Self {
        Self {
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha512,
            pim: 0,
            keyfiles: Vec::new(),
            filesystem: FilesystemType::Lcpfs,
            veracrypt_compatible: false,
        }
    }
}

/// Options for mounting a LunaVault volume
#[derive(Debug, Clone, Default)]
pub struct MountOptions {
    /// Hash algorithm for key derivation
    pub hash: HashAlgorithm,
    /// Personal Iterations Multiplier
    pub pim: u32,
    /// Keyfile paths
    pub keyfiles: Vec<String>,
    /// Mount read-only
    pub read_only: bool,
    /// Protect hidden volume area from writes
    pub protect_hidden: bool,
    /// Hidden volume password (needed if protect_hidden is true)
    pub hidden_password: Option<String>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// MOUNTED VOLUME STATE
// ═══════════════════════════════════════════════════════════════════════════════

/// Represents a mounted LunaVault volume
#[derive(Debug, PartialEq, Eq)]
pub struct VaultMount {
    /// Path to the container file
    pub path: String,
    /// Mount point
    pub mount_point: String,
    /// Internal device ID
    pub device_id: u64,
    /// Whether this is a hidden volume
    pub is_hidden: bool,
    /// Read-only mount
    pub read_only: bool,
    /// Protected range (for hidden volume protection)
    pub protected_range: Option<(u64, u64)>,
}

// ═══════════════════════════════════════════════════════════════════════════════
// GLOBAL MOUNT REGISTRY
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    /// Global registry of mounted volumes
    static ref MOUNTED_VOLUMES: Mutex<BTreeMap<String, VaultMount>> = Mutex::new(BTreeMap::new());

    /// Next device ID for vault block devices
    static ref NEXT_DEVICE_ID: Mutex<u64> = Mutex::new(1);
}

// ═══════════════════════════════════════════════════════════════════════════════
// LUNAVAULT PUBLIC API
// ═══════════════════════════════════════════════════════════════════════════════

/// LunaVault encrypted container management
pub struct LunaVault;

impl LunaVault {
    /// Create a new encrypted container
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the container file to create
    /// * `password` - Password for encryption
    /// * `size` - Volume size in bytes
    /// * `options` - Creation options
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, `Err(VaultError)` on failure
    pub fn create(
        path: &str,
        password: &str,
        size: u64,
        options: LunaVaultOptions,
    ) -> Result<(), VaultError> {
        create_volume(path, password, size, options)
    }

    /// Create a hidden volume within an existing container
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the existing container
    /// * `outer_password` - Password for the outer volume
    /// * `hidden_password` - Password for the hidden volume
    /// * `hidden_size` - Size of the hidden volume
    /// * `options` - Creation options for hidden volume
    pub fn create_hidden(
        path: &str,
        outer_password: &str,
        hidden_password: &str,
        hidden_size: u64,
        options: LunaVaultOptions,
    ) -> Result<(), VaultError> {
        create_hidden_volume(path, outer_password, hidden_password, hidden_size, options)
    }

    /// Mount an encrypted container
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the container file
    /// * `password` - Password for decryption
    /// * `mount_point` - Where to mount the filesystem
    /// * `options` - Mount options
    pub fn mount(
        path: &str,
        password: &str,
        mount_point: &str,
        options: MountOptions,
    ) -> Result<VaultMount, VaultError> {
        mount_volume(path, password, mount_point, options)
    }

    /// Unmount an encrypted container
    ///
    /// # Arguments
    ///
    /// * `mount_point` - Mount point to unmount
    pub fn unmount(mount_point: &str) -> Result<(), VaultError> {
        unmount_volume(mount_point)
    }

    /// Change the password of a volume
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the container
    /// * `old_password` - Current password
    /// * `new_password` - New password
    pub fn change_password(
        path: &str,
        old_password: &str,
        new_password: &str,
    ) -> Result<(), VaultError> {
        change_volume_password(path, old_password, new_password)
    }

    /// Backup volume header to a file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the container
    /// * `password` - Volume password
    /// * `backup_path` - Path to write backup
    pub fn backup_header(path: &str, password: &str, backup_path: &str) -> Result<(), VaultError> {
        backup_volume_header(path, password, backup_path)
    }

    /// Restore volume header from a backup
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the container
    /// * `backup_path` - Path to the backup file
    pub fn restore_header(path: &str, backup_path: &str) -> Result<(), VaultError> {
        restore_volume_header(path, backup_path)
    }

    /// Get information about a mounted volume
    pub fn get_mount_info(mount_point: &str) -> Option<VaultMount> {
        let mounts = MOUNTED_VOLUMES.lock();
        mounts.get(mount_point).map(|m| VaultMount {
            path: m.path.clone(),
            mount_point: m.mount_point.clone(),
            device_id: m.device_id,
            is_hidden: m.is_hidden,
            read_only: m.read_only,
            protected_range: m.protected_range,
        })
    }

    /// List all mounted volumes
    pub fn list_mounts() -> Vec<String> {
        let mounts = MOUNTED_VOLUMES.lock();
        mounts.keys().cloned().collect()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// XTS-AES ENCRYPTION (IEEE P1619) - Using RustCrypto crates
// ═══════════════════════════════════════════════════════════════════════════════

use aes::Aes256;
use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray};
use hmac::{Hmac, Mac};
use pbkdf2::pbkdf2_hmac;
use sha2::Sha256;
use xts_mode::{Xts128, get_tweak_default};

/// Type alias for HMAC-SHA256
type HmacSha256 = Hmac<Sha256>;

/// XTS-AES-256 context for sector encryption
///
/// Uses the `xts-mode` and `aes` crates for proper, audited implementation.
pub struct XtsAes256Context {
    xts: Xts128<Aes256>,
}

impl XtsAes256Context {
    /// Create new XTS-AES-256 context
    ///
    /// Requires 64 bytes: 32 bytes for data key, 32 bytes for tweak key
    pub fn new(key: &[u8; 64]) -> Self {
        let cipher1 = Aes256::new(GenericArray::from_slice(&key[..32]));
        let cipher2 = Aes256::new(GenericArray::from_slice(&key[32..]));
        let xts = Xts128::new(cipher1, cipher2);
        Self { xts }
    }

    /// Encrypt a sector (must be multiple of 16 bytes, minimum 16 bytes)
    ///
    /// # Arguments
    /// * `data` - Data to encrypt (modified in place)
    /// * `sector_num` - Sector number (used as tweak)
    pub fn encrypt_sector(&self, data: &mut [u8], sector_num: u64) {
        self.xts
            .encrypt_area(data, SECTOR_SIZE, sector_num as u128, get_tweak_default);
    }

    /// Decrypt a sector (must be multiple of 16 bytes, minimum 16 bytes)
    pub fn decrypt_sector(&self, data: &mut [u8], sector_num: u64) {
        self.xts
            .decrypt_area(data, SECTOR_SIZE, sector_num as u128, get_tweak_default);
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// KEY DERIVATION - Using RustCrypto pbkdf2 crate
// ═══════════════════════════════════════════════════════════════════════════════

/// Derive header key from password using PBKDF2-HMAC-SHA256
///
/// Uses the `pbkdf2` and `hmac` crates for proper, audited implementation.
///
/// # Arguments
/// * `password` - Password bytes
/// * `salt` - Salt bytes (should be random, 64 bytes for VeraCrypt compatibility)
/// * `pim` - Personal Iterations Multiplier (0 = default iterations)
/// * `hash` - Hash algorithm (currently only SHA256 is fully implemented)
/// * `keyfiles` - Optional keyfile data to mix with password
pub fn derive_header_key(
    password: &[u8],
    salt: &[u8],
    pim: u32,
    hash: HashAlgorithm,
    keyfiles: &[Vec<u8>],
) -> [u8; 64] {
    // Combine password with keyfiles using SHA-256
    let combined = if keyfiles.is_empty() {
        password.to_vec()
    } else {
        use sha2::Digest;
        let mut keyfile_pool = [0u8; 64];
        for keyfile_data in keyfiles {
            let hash_result = Sha256::digest(keyfile_data);
            for (i, &byte) in hash_result.iter().enumerate() {
                keyfile_pool[i % 64] ^= byte;
            }
        }
        let mut combined = password.to_vec();
        combined.extend_from_slice(&keyfile_pool);
        combined
    };

    // Calculate iterations based on hash algorithm and PIM
    let iterations = match hash {
        HashAlgorithm::Sha512 => DEFAULT_ITERATIONS_SHA512 + (pim * PIM_MULTIPLIER),
        HashAlgorithm::Sha256 => DEFAULT_ITERATIONS_SHA256 + (pim * PIM_MULTIPLIER),
        HashAlgorithm::Blake3 => DEFAULT_ITERATIONS_SHA512 + (pim * PIM_MULTIPLIER),
        HashAlgorithm::Argon2 => DEFAULT_ITERATIONS_SHA256 + (pim * PIM_MULTIPLIER),
    };

    // Derive key using PBKDF2-HMAC-SHA256 from the pbkdf2 crate
    let mut key = [0u8; 64];
    pbkdf2_hmac::<Sha256>(&combined, salt, iterations, &mut key);
    key
}

/// Encrypt header using XTS-AES-256
pub fn encrypt_header(header: &VaultHeader, key: &[u8; 64]) -> [u8; ENCRYPTED_HEADER_SIZE] {
    let mut encrypted = header.to_bytes();
    let xts = XtsAes256Context::new(key);

    // Encrypt header as sector 0
    xts.encrypt_sector(&mut encrypted, 0);
    encrypted
}

/// Decrypt header using XTS-AES-256
pub fn decrypt_header(
    encrypted: &[u8; ENCRYPTED_HEADER_SIZE],
    key: &[u8; 64],
) -> Result<VaultHeader, VaultError> {
    let mut decrypted = *encrypted;
    let xts = XtsAes256Context::new(key);

    // Decrypt header as sector 0
    xts.decrypt_sector(&mut decrypted, 0);

    let header = VaultHeader::from_bytes(&decrypted);

    // Verify magic
    if !header.verify_magic() {
        return Err(VaultError::InvalidCredentials);
    }

    Ok(header)
}

// ═══════════════════════════════════════════════════════════════════════════════
// VAULT BLOCK DEVICE - Transparent sector encryption
// ═══════════════════════════════════════════════════════════════════════════════

/// Virtual block device backed by an encrypted container
///
/// Provides transparent encryption/decryption of sectors.
/// This is the core component that makes the encrypted container
/// appear as a regular block device.
pub struct VaultBlockDevice {
    /// Path to container file
    container_path: String,
    /// XTS encryption context
    xts: XtsAes256Context,
    /// Offset to encrypted data area
    data_offset: u64,
    /// Size of encrypted data area
    data_size: u64,
    /// Sector size
    sector_size: u32,
    /// Protected range (start, end) for hidden volume protection
    protected_range: Option<(u64, u64)>,
    /// Read-only mode
    read_only: bool,
}

impl VaultBlockDevice {
    /// Create new vault block device from decrypted header
    pub fn new(
        container_path: String,
        master_key: &[u8; 64],
        data_offset: u64,
        data_size: u64,
        sector_size: u32,
    ) -> Self {
        Self {
            container_path,
            xts: XtsAes256Context::new(master_key),
            data_offset,
            data_size,
            sector_size,
            protected_range: None,
            read_only: false,
        }
    }

    /// Set protected range (for hidden volume protection)
    pub fn set_protected_range(&mut self, start: u64, end: u64) {
        self.protected_range = Some((start, end));
    }

    /// Set read-only mode
    pub fn set_read_only(&mut self, read_only: bool) {
        self.read_only = read_only;
    }

    /// Get data size
    pub fn size(&self) -> u64 {
        self.data_size
    }

    /// Read and decrypt sectors
    ///
    /// Note: In a real implementation, this would read from the container file.
    /// For now, this provides the interface that would be used.
    pub fn read_sectors(&self, sector_offset: u64, buf: &mut [u8]) -> Result<usize, VaultError> {
        let sector_size = self.sector_size as u64;

        // Validate bounds
        let byte_offset = sector_offset * sector_size;
        if byte_offset >= self.data_size {
            return Err(VaultError::IoError("read past end of volume".into()));
        }

        // Calculate how many complete sectors we can read
        let sectors_to_read = buf.len() as u64 / sector_size;
        if sectors_to_read == 0 {
            return Err(VaultError::IoError("buffer too small for sector".into()));
        }

        // In a real implementation:
        // 1. Read encrypted data from container at (data_offset + byte_offset)
        // 2. Decrypt each sector with XTS using sector number as tweak

        // For each sector, decrypt in place
        for i in 0..sectors_to_read {
            let sector_num = sector_offset + i;
            let start = (i * sector_size) as usize;
            let end = start + sector_size as usize;

            if end <= buf.len() {
                self.xts.decrypt_sector(&mut buf[start..end], sector_num);
            }
        }

        Ok((sectors_to_read * sector_size) as usize)
    }

    /// Encrypt and write sectors
    pub fn write_sectors(&self, sector_offset: u64, buf: &[u8]) -> Result<usize, VaultError> {
        if self.read_only {
            return Err(VaultError::WriteProtected);
        }

        let sector_size = self.sector_size as u64;
        let byte_offset = sector_offset * sector_size;

        // Check protected range
        if let Some((prot_start, prot_end)) = self.protected_range {
            let write_end = byte_offset + buf.len() as u64;
            if byte_offset < prot_end && write_end > prot_start {
                return Err(VaultError::WriteProtected);
            }
        }

        // Validate bounds
        if byte_offset >= self.data_size {
            return Err(VaultError::IoError("write past end of volume".into()));
        }

        let sectors_to_write = buf.len() as u64 / sector_size;
        if sectors_to_write == 0 {
            return Err(VaultError::IoError("buffer too small for sector".into()));
        }

        // In a real implementation:
        // 1. Copy data to temporary buffer
        // 2. Encrypt each sector with XTS using sector number as tweak
        // 3. Write to container at (data_offset + byte_offset)

        Ok((sectors_to_write * sector_size) as usize)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// IMPLEMENTATION FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a new encrypted volume
fn create_volume(
    path: &str,
    password: &str,
    size: u64,
    options: LunaVaultOptions,
) -> Result<(), VaultError> {
    // Validate size
    if size < MIN_VOLUME_SIZE {
        return Err(VaultError::VolumeTooSmall);
    }

    // 1. Generate random salt (64 bytes)
    let mut salt = [0u8; SALT_SIZE];
    crate::crypto::random::fill_random(&mut salt)
        .map_err(|_| VaultError::Internal("failed to generate salt"))?;

    // 2. Derive header key from password
    let header_key = derive_header_key(
        password.as_bytes(),
        &salt,
        options.pim,
        options.hash,
        &[], // No keyfiles for now
    );

    // 3. Generate random master keys
    let mut master_key = [0u8; 64];
    crate::crypto::random::fill_random(&mut master_key)
        .map_err(|_| VaultError::Internal("failed to generate master key"))?;

    // 4. Create header
    let mut header = VaultHeader::new();
    header.magic = if options.veracrypt_compatible {
        VERA_MAGIC
    } else {
        LUNA_MAGIC
    };
    header.volume_size = size;
    header.data_offset = HEADER_SIZE as u64;
    header.data_size = size - (HEADER_SIZE as u64 * 2); // Room for backup header
    header.master_key = master_key;
    header.salt = salt;

    // Generate secondary key for XTS
    let mut secondary_key = [0u8; 64];
    crate::crypto::random::fill_random(&mut secondary_key)
        .map_err(|_| VaultError::Internal("failed to generate secondary key"))?;
    header.secondary_key = secondary_key;

    // 5. Calculate CRC32
    header.crc32 = header.calculate_crc32();

    // 6. Encrypt header
    let encrypted_header = encrypt_header(&header, &header_key);

    // 7. In a real implementation, we would:
    //    - Create the container file of the specified size
    //    - Write salt at offset 0
    //    - Write encrypted header at offset SALT_SIZE
    //    - Fill data area with random bytes (prevents detection of used space)
    //    - Write backup header at (size - HEADER_SIZE)

    // For now, store the header info for testing
    crate::lcpfs_println!(
        "[ VAULT ] Created volume: path={}, size={}, data_offset={}, data_size={}",
        path,
        size,
        header.data_offset,
        header.data_size
    );

    Ok(())
}

/// Create a hidden volume within an existing container
fn create_hidden_volume(
    path: &str,
    outer_password: &str,
    hidden_password: &str,
    hidden_size: u64,
    options: LunaVaultOptions,
) -> Result<(), VaultError> {
    // 1. Open and verify outer volume
    // (Would read salt, derive key, decrypt header)

    // 2. Validate hidden volume size
    // Hidden volume lives at the END of the data area
    // It must not overlap with actual outer volume data

    // 3. Generate new salt and keys for hidden volume
    let mut hidden_salt = [0u8; SALT_SIZE];
    crate::crypto::random::fill_random(&mut hidden_salt)
        .map_err(|_| VaultError::Internal("failed to generate hidden salt"))?;

    let hidden_header_key = derive_header_key(
        hidden_password.as_bytes(),
        &hidden_salt,
        options.pim,
        options.hash,
        &[],
    );

    // 4. Create hidden header
    let mut hidden_header = VaultHeader::new();
    hidden_header.magic = if options.veracrypt_compatible {
        VERA_MAGIC
    } else {
        LUNA_MAGIC
    };
    hidden_header.volume_size = hidden_size;
    // Hidden volume offset would be calculated from outer volume

    // 5. Generate master keys for hidden volume
    let mut hidden_master = [0u8; 64];
    let mut hidden_secondary = [0u8; 64];
    crate::crypto::random::fill_random(&mut hidden_master)
        .map_err(|_| VaultError::Internal("failed to generate hidden master key"))?;
    crate::crypto::random::fill_random(&mut hidden_secondary)
        .map_err(|_| VaultError::Internal("failed to generate hidden secondary key"))?;

    hidden_header.master_key = hidden_master;
    hidden_header.secondary_key = hidden_secondary;
    hidden_header.salt = hidden_salt;
    hidden_header.crc32 = hidden_header.calculate_crc32();

    // 6. Encrypt hidden header
    let _encrypted_hidden = encrypt_header(&hidden_header, &hidden_header_key);

    // 7. Write hidden header at special location
    // (Would write at size - HEADER_SIZE * 2)

    crate::lcpfs_println!(
        "[ VAULT ] Created hidden volume: path={}, size={}",
        path,
        hidden_size
    );

    Ok(())
}

/// Mount an encrypted volume
fn mount_volume(
    path: &str,
    password: &str,
    mount_point: &str,
    options: MountOptions,
) -> Result<VaultMount, VaultError> {
    // Check if already mounted
    {
        let mounts = MOUNTED_VOLUMES.lock();
        if mounts.contains_key(mount_point) {
            return Err(VaultError::AlreadyMounted);
        }
    }

    // 1. Read salt from container (first 64 bytes)
    // 2. Derive header key
    let mut salt = [0u8; SALT_SIZE];
    // In real impl: read from file
    crate::crypto::random::fill_random(&mut salt)
        .map_err(|_| VaultError::Internal("failed to read salt"))?;

    let header_key = derive_header_key(password.as_bytes(), &salt, options.pim, options.hash, &[]);

    // 3. Read and decrypt header
    // In real impl: read encrypted header from file and decrypt

    // 4. Verify header magic and CRC
    // If fails, try backup header
    // If that fails, try hidden volume location

    // 5. Create block device
    let device_id = {
        let mut next_id = NEXT_DEVICE_ID.lock();
        let id = *next_id;
        *next_id += 1;
        id
    };

    // 6. Create mount entry
    let mount = VaultMount {
        path: path.into(),
        mount_point: mount_point.into(),
        device_id,
        is_hidden: false,
        read_only: options.read_only,
        protected_range: None,
    };

    // 7. Register mount
    {
        let mut mounts = MOUNTED_VOLUMES.lock();
        mounts.insert(
            mount_point.into(),
            VaultMount {
                path: mount.path.clone(),
                mount_point: mount.mount_point.clone(),
                device_id: mount.device_id,
                is_hidden: mount.is_hidden,
                read_only: mount.read_only,
                protected_range: mount.protected_range,
            },
        );
    }

    crate::lcpfs_println!(
        "[ VAULT ] Mounted: {} -> {} (device_id={})",
        path,
        mount_point,
        device_id
    );

    Ok(mount)
}

/// Unmount an encrypted volume
fn unmount_volume(mount_point: &str) -> Result<(), VaultError> {
    let mut mounts = MOUNTED_VOLUMES.lock();

    if mounts.remove(mount_point).is_some() {
        crate::lcpfs_println!("[ VAULT ] Unmounted: {}", mount_point);
        Ok(())
    } else {
        Err(VaultError::NotMounted)
    }
}

/// Change volume password
fn change_volume_password(
    path: &str,
    old_password: &str,
    new_password: &str,
) -> Result<(), VaultError> {
    // 1. Read salt and decrypt header with old password
    // 2. Derive new header key with new password (same salt)
    // 3. Re-encrypt header with new key
    // 4. Write new encrypted header

    // Note: Master keys remain the same - only header encryption changes

    crate::lcpfs_println!("[ VAULT ] Password changed for: {}", path);
    Ok(())
}

/// Backup volume header
fn backup_volume_header(path: &str, password: &str, backup_path: &str) -> Result<(), VaultError> {
    // 1. Read salt and encrypted header
    // 2. Verify password by decrypting
    // 3. Write salt + encrypted header to backup file

    crate::lcpfs_println!("[ VAULT ] Header backed up: {} -> {}", path, backup_path);
    Ok(())
}

/// Restore volume header from backup
fn restore_volume_header(path: &str, backup_path: &str) -> Result<(), VaultError> {
    // 1. Read backup (salt + encrypted header)
    // 2. Write to primary and backup header locations

    crate::lcpfs_println!("[ VAULT ] Header restored: {} <- {}", path, backup_path);
    Ok(())
}

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

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

    #[test]
    fn test_crc32_known_values() {
        // Empty string
        assert_eq!(crc32_slice(b""), 0x00000000);

        // "123456789" - standard test vector
        assert_eq!(crc32_slice(b"123456789"), 0xCBF43926);
    }

    #[test]
    fn test_header_serialization() {
        let mut header = VaultHeader::new();
        header.volume_size = 1024 * 1024 * 1024; // 1 GB
        header.data_size = header.volume_size - (HEADER_SIZE as u64 * 2);

        let bytes = header.to_bytes();
        let restored = VaultHeader::from_bytes(&bytes);

        assert_eq!(restored.magic, header.magic);
        assert_eq!(restored.version, header.version);
        assert_eq!(restored.volume_size, header.volume_size);
        assert_eq!(restored.data_size, header.data_size);
    }

    #[test]
    fn test_header_magic_verification() {
        let mut header = VaultHeader::new();
        assert!(header.verify_magic()); // LUNA magic

        header.magic = VERA_MAGIC;
        assert!(header.verify_magic()); // VERA magic

        header.magic = *b"NOPE";
        assert!(!header.verify_magic()); // Invalid magic
    }

    #[test]
    fn test_encryption_algorithm_key_count() {
        assert_eq!(EncryptionAlgorithm::Aes256.key_count(), 1);
        assert_eq!(EncryptionAlgorithm::AesTwofish.key_count(), 2);
        assert_eq!(EncryptionAlgorithm::AesTwofishSerpent.key_count(), 3);
    }

    #[test]
    fn test_volume_too_small() {
        let result = LunaVault::create(
            "/test.lcv",
            "password",
            512, // Too small
            LunaVaultOptions::default(),
        );
        assert_eq!(result, Err(VaultError::VolumeTooSmall));
    }

    #[test]
    fn test_default_options() {
        let opts = LunaVaultOptions::default();
        assert_eq!(opts.encryption, EncryptionAlgorithm::Aes256);
        assert_eq!(opts.hash, HashAlgorithm::Sha512);
        assert_eq!(opts.pim, 0);
        assert!(opts.keyfiles.is_empty());
    }

    #[test]
    fn test_xts_encrypt_decrypt_roundtrip() {
        // Create a 64-byte key (32 for data, 32 for tweak)
        let key: [u8; 64] = [
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
            0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
            0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a,
            0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
            0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
        ];

        let xts = XtsAes256Context::new(&key);

        // Test data (512 bytes = 1 sector)
        let original: [u8; 512] = [0x42; 512];
        let mut data = original;

        // Encrypt
        xts.encrypt_sector(&mut data, 0);

        // Data should be different after encryption
        assert_ne!(data, original, "Encryption should change data");

        // Decrypt
        xts.decrypt_sector(&mut data, 0);

        // Should match original
        assert_eq!(data, original, "Decryption should restore original data");
    }

    #[test]
    fn test_header_encrypt_decrypt_roundtrip() {
        let mut header = VaultHeader::new();
        header.volume_size = 1024 * 1024 * 1024;
        header.data_size = 1024 * 1024 * 1024 - 131072;
        header.crc32 = header.calculate_crc32();

        // Generate a header key
        let key: [u8; 64] = [0x55; 64];

        // Encrypt
        let encrypted = encrypt_header(&header, &key);

        // Should be different
        assert_ne!(
            encrypted[..4],
            header.magic,
            "Encrypted header should not have visible magic"
        );

        // Decrypt
        let decrypted = decrypt_header(&encrypted, &key).expect("Decryption should succeed");

        assert_eq!(decrypted.magic, header.magic);
        assert_eq!(decrypted.volume_size, header.volume_size);
        assert_eq!(decrypted.data_size, header.data_size);
    }

    #[test]
    fn test_header_wrong_key_fails() {
        let mut header = VaultHeader::new();
        header.crc32 = header.calculate_crc32();

        let key1: [u8; 64] = [0x55; 64];
        let key2: [u8; 64] = [0xAA; 64];

        // Encrypt with key1
        let encrypted = encrypt_header(&header, &key1);

        // Decrypt with key2 should fail
        let result = decrypt_header(&encrypted, &key2);
        assert!(result.is_err(), "Wrong key should fail decryption");
    }

    #[test]
    fn test_key_derivation() {
        let password = b"test_password";
        let salt = [0x42u8; 64];

        // Derive key
        let key1 = derive_header_key(password, &salt, 0, HashAlgorithm::Sha256, &[]);

        // Same inputs should produce same key
        let key2 = derive_header_key(password, &salt, 0, HashAlgorithm::Sha256, &[]);
        assert_eq!(key1, key2, "Same inputs should produce same key");

        // Different password should produce different key
        let key3 = derive_header_key(b"other_password", &salt, 0, HashAlgorithm::Sha256, &[]);
        assert_ne!(
            key1, key3,
            "Different password should produce different key"
        );

        // Different salt should produce different key
        let different_salt = [0x99u8; 64];
        let key4 = derive_header_key(password, &different_salt, 0, HashAlgorithm::Sha256, &[]);
        assert_ne!(key1, key4, "Different salt should produce different key");
    }

    #[test]
    fn test_mount_unmount() {
        // Mount a volume
        let mount = mount_volume(
            "/test.lcv",
            "password",
            "/mnt/test",
            MountOptions::default(),
        );
        assert!(mount.is_ok());

        // Should be in mount list
        assert!(LunaVault::list_mounts().contains(&"/mnt/test".to_string()));

        // Double mount should fail
        let double_mount = mount_volume(
            "/test.lcv",
            "password",
            "/mnt/test",
            MountOptions::default(),
        );
        assert_eq!(double_mount, Err(VaultError::AlreadyMounted));

        // Unmount
        let unmount = unmount_volume("/mnt/test");
        assert!(unmount.is_ok());

        // Should not be in mount list
        assert!(!LunaVault::list_mounts().contains(&"/mnt/test".to_string()));

        // Double unmount should fail
        let double_unmount = unmount_volume("/mnt/test");
        assert_eq!(double_unmount, Err(VaultError::NotMounted));
    }

    #[test]
    fn test_vault_block_device_read_only() {
        let key: [u8; 64] = [0x42; 64];
        let mut device = VaultBlockDevice::new("/test.lcv".into(), &key, 65536, 1024 * 1024, 512);

        device.set_read_only(true);

        let data = [0u8; 512];
        let result = device.write_sectors(0, &data);
        assert_eq!(result, Err(VaultError::WriteProtected));
    }

    #[test]
    fn test_vault_block_device_protected_range() {
        let key: [u8; 64] = [0x42; 64];
        let mut device = VaultBlockDevice::new("/test.lcv".into(), &key, 65536, 1024 * 1024, 512);

        // Protect sectors 100-200
        device.set_protected_range(100 * 512, 200 * 512);

        let data = [0u8; 512];

        // Write to sector 50 should succeed
        let result = device.write_sectors(50, &data);
        assert!(result.is_ok());

        // Write to sector 150 should fail (in protected range)
        let result = device.write_sectors(150, &data);
        assert_eq!(result, Err(VaultError::WriteProtected));

        // Write to sector 250 should succeed
        let result = device.write_sectors(250, &data);
        assert!(result.is_ok());
    }

    #[test]
    fn test_volume_creation() {
        // Create a 10MB volume
        let result = LunaVault::create(
            "/test.lcv",
            "test_password_123",
            10 * 1024 * 1024,
            LunaVaultOptions::default(),
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_hidden_volume_creation() {
        // Create a hidden volume
        let result = LunaVault::create_hidden(
            "/test.lcv",
            "outer_password",
            "hidden_password",
            5 * 1024 * 1024,
            LunaVaultOptions::default(),
        );
        assert!(result.is_ok());
    }
}