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
//! LunaVault Type Definitions
//!
//! # Attribution
//!
//! The LunaVault format is inspired by VeraCrypt (<https://veracrypt.fr>),
//! an Apache 2.0 licensed project by IDRIX (Mounir Idrassi).
//! We gratefully acknowledge their exceptional work on privacy-preserving
//! storage technology and their commitment to open source.
//!
//! This is a clean-room implementation using public cryptographic standards
//! (XTS-AES, PBKDF2, Argon2). We thank the VeraCrypt team for pioneering
//! deniable encryption and making privacy accessible to everyone.

#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

// ============================================================================
// Constants
// ============================================================================

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

/// Alternative magic for TrueCrypt compatibility
pub const TRUE_MAGIC: [u8; 4] = *b"TRUE";

/// LunaVault extension magic
pub const LUNA_MAGIC: [u8; 4] = *b"LUNA";

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

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

/// Encrypted header data size (448 bytes)
pub const ENCRYPTED_HEADER_SIZE: usize = 448;

/// Master key size (64 bytes for XTS mode - 2x 256-bit keys)
pub const MASTER_KEY_SIZE: usize = 64;

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

/// Sector size for encryption
pub const SECTOR_SIZE: usize = 512;

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

/// Default PIM (Personal Iterations Multiplier)
pub const DEFAULT_PIM: u32 = 0;

/// Base iteration count for SHA-512
pub const SHA512_BASE_ITERATIONS: u32 = 500000;

/// Base iteration count for SHA-256
pub const SHA256_BASE_ITERATIONS: u32 = 200000;

/// Iteration multiplier per PIM unit
pub const PIM_MULTIPLIER: u32 = 1000;

// ============================================================================
// Header Structure
// ============================================================================

/// VeraCrypt-compatible volume header.
/// Total size: 512 bytes (encrypted portion after salt).
#[derive(Clone)]
#[repr(C)]
pub struct VaultHeader {
    /// Magic bytes: "VERA", "TRUE", 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 for future use
    pub reserved1: [u8; 16],
    /// Size of hidden volume (0 if none)
    pub hidden_size: u64,
    /// Total volume size in bytes
    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: VaultFlags,
    /// Sector size (usually 512)
    pub sector_size: u32,
    /// Reserved for future use
    pub reserved2: [u8; 120],
    /// Master encryption key (encrypted with header key)
    pub master_key: [u8; 64],
    /// Secondary key for XTS mode (encrypted with header key)
    pub secondary_key: [u8; 64],
    /// Salt for master key derivation (stored unencrypted at offset 0)
    pub salt: [u8; 64],
}

impl VaultHeader {
    /// Create a new header with default values.
    pub fn new() -> Self {
        Self {
            magic: VERA_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: VaultFlags::default(),
            sector_size: SECTOR_SIZE as u32,
            reserved2: [0; 120],
            master_key: [0; 64],
            secondary_key: [0; 64],
            salt: [0; 64],
        }
    }

    /// Check if magic is valid.
    pub fn is_valid_magic(&self) -> bool {
        self.magic == VERA_MAGIC || self.magic == TRUE_MAGIC || self.magic == LUNA_MAGIC
    }

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

        buf[0..4].copy_from_slice(&self.magic);
        buf[4..6].copy_from_slice(&self.version.to_le_bytes());
        buf[6..8].copy_from_slice(&self.min_version.to_le_bytes());
        buf[8..12].copy_from_slice(&self.crc32.to_le_bytes());
        buf[12..28].copy_from_slice(&self.reserved1);
        buf[28..36].copy_from_slice(&self.hidden_size.to_le_bytes());
        buf[36..44].copy_from_slice(&self.volume_size.to_le_bytes());
        buf[44..52].copy_from_slice(&self.data_offset.to_le_bytes());
        buf[52..60].copy_from_slice(&self.data_size.to_le_bytes());
        buf[60..64].copy_from_slice(&self.flags.bits().to_le_bytes());
        buf[64..68].copy_from_slice(&self.sector_size.to_le_bytes());
        buf[68..188].copy_from_slice(&self.reserved2);
        buf[188..252].copy_from_slice(&self.master_key);
        buf[252..316].copy_from_slice(&self.secondary_key);
        buf[316..380].copy_from_slice(&self.salt);
        // Remaining bytes (380-512) are padding

        buf
    }

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

        header.magic.copy_from_slice(&buf[0..4]);
        header.version = u16::from_le_bytes([buf[4], buf[5]]);
        header.min_version = u16::from_le_bytes([buf[6], buf[7]]);
        header.crc32 = u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]);
        header.reserved1.copy_from_slice(&buf[12..28]);
        header.hidden_size = u64::from_le_bytes(buf[28..36].try_into().unwrap());
        header.volume_size = u64::from_le_bytes(buf[36..44].try_into().unwrap());
        header.data_offset = u64::from_le_bytes(buf[44..52].try_into().unwrap());
        header.data_size = u64::from_le_bytes(buf[52..60].try_into().unwrap());
        header.flags =
            VaultFlags::from_bits_truncate(u32::from_le_bytes(buf[60..64].try_into().unwrap()));
        header.sector_size = u32::from_le_bytes(buf[64..68].try_into().unwrap());
        header.reserved2.copy_from_slice(&buf[68..188]);
        header.master_key.copy_from_slice(&buf[188..252]);
        header.secondary_key.copy_from_slice(&buf[252..316]);
        header.salt.copy_from_slice(&buf[316..380]);

        header
    }
}

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

// ============================================================================
// Flags
// ============================================================================

/// Volume flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct VaultFlags(u32);

impl VaultFlags {
    /// No flags set.
    pub const NONE: Self = Self(0);
    /// Volume is a system encryption volume.
    pub const SYSTEM: Self = Self(1 << 0);
    /// Volume contains a hidden operating system.
    pub const HIDDEN_OS: Self = Self(1 << 1);
    /// Volume is read-only.
    pub const READ_ONLY: Self = Self(1 << 2);
    /// Volume uses backup header.
    pub const BACKUP_HEADER: Self = Self(1 << 3);
    /// LunaVault extension: uses LCPFS filesystem.
    pub const LCPFS_NATIVE: Self = Self(1 << 16);
    /// LunaVault extension: uses ChaCha20 instead of AES.
    pub const CHACHA20: Self = Self(1 << 17);

    /// Get raw bits.
    pub const fn bits(&self) -> u32 {
        self.0
    }

    /// Create from raw bits.
    pub const fn from_bits_truncate(bits: u32) -> Self {
        Self(bits)
    }

    /// Check if flag is set.
    pub const fn contains(&self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// Set a flag.
    pub fn insert(&mut self, other: Self) {
        self.0 |= other.0;
    }

    /// Clear a flag.
    pub fn remove(&mut self, other: Self) {
        self.0 &= !other.0;
    }
}

// ============================================================================
// Encryption Algorithms
// ============================================================================

/// Encryption algorithm for volume data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EncryptionAlgorithm {
    /// AES-256 in XTS mode (default, most compatible)
    #[default]
    Aes256,
    /// Serpent-256 in XTS mode
    Serpent256,
    /// Twofish-256 in XTS mode
    Twofish256,
    /// AES-256 → Twofish-256 cascade
    AesTwofish,
    /// Twofish-256 → AES-256 cascade
    TwofishAes,
    /// AES-256 → Twofish-256 → Serpent-256 cascade
    AesTwofishSerpent,
    /// Serpent-256 → Twofish-256 → AES-256 cascade
    SerpentTwofishAes,
    /// Serpent-256 → AES-256 cascade
    SerpentAes,
    /// ChaCha20-Poly1305 (LCPFS extension, not VeraCrypt compatible)
    ChaCha20Poly1305,
    /// AES-256-XTS with ML-KEM-1024 (Kyber) hybrid key encapsulation (LCPFS PQC)
    /// Uses X25519 + ML-KEM-1024 hybrid for quantum-resistant key exchange
    Aes256MlKem1024,
    /// ChaCha20-Poly1305 with ML-KEM-1024 hybrid key encapsulation (LCPFS PQC)
    ChaCha20MlKem1024,
    /// Triple cascade with ML-KEM-1024: AES → Twofish → Serpent (maximum security)
    AesTwofishSerpentMlKem1024,
}

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::ChaCha20Poly1305 => 1,
            Self::Aes256MlKem1024 | Self::ChaCha20MlKem1024 => 1,
            Self::AesTwofish | Self::TwofishAes | Self::SerpentAes => 2,
            Self::AesTwofishSerpent | Self::SerpentTwofishAes => 3,
            Self::AesTwofishSerpentMlKem1024 => 3,
        }
    }

    /// Get the total key size in bytes (for XTS mode, doubled).
    pub fn total_key_size(&self) -> usize {
        // XTS mode requires 2x key size (encrypt key + tweak key)
        self.key_count() * 64
    }

    /// Check if this is a cascade cipher.
    pub fn is_cascade(&self) -> bool {
        self.key_count() > 1
    }

    /// Check if this algorithm uses post-quantum key encapsulation.
    pub fn is_post_quantum(&self) -> bool {
        matches!(
            self,
            Self::Aes256MlKem1024 | Self::ChaCha20MlKem1024 | Self::AesTwofishSerpentMlKem1024
        )
    }

    /// Algorithm ID for serialization.
    pub fn id(&self) -> u8 {
        match self {
            Self::Aes256 => 0,
            Self::Serpent256 => 1,
            Self::Twofish256 => 2,
            Self::AesTwofish => 3,
            Self::TwofishAes => 4,
            Self::AesTwofishSerpent => 5,
            Self::SerpentTwofishAes => 6,
            Self::SerpentAes => 7,
            Self::ChaCha20Poly1305 => 128,
            // Post-quantum algorithms use 192+ range
            Self::Aes256MlKem1024 => 192,
            Self::ChaCha20MlKem1024 => 193,
            Self::AesTwofishSerpentMlKem1024 => 194,
        }
    }

    /// Create from algorithm ID.
    pub fn from_id(id: u8) -> Option<Self> {
        match id {
            0 => Some(Self::Aes256),
            1 => Some(Self::Serpent256),
            2 => Some(Self::Twofish256),
            3 => Some(Self::AesTwofish),
            4 => Some(Self::TwofishAes),
            5 => Some(Self::AesTwofishSerpent),
            6 => Some(Self::SerpentTwofishAes),
            7 => Some(Self::SerpentAes),
            128 => Some(Self::ChaCha20Poly1305),
            // Post-quantum algorithms
            192 => Some(Self::Aes256MlKem1024),
            193 => Some(Self::ChaCha20MlKem1024),
            194 => Some(Self::AesTwofishSerpentMlKem1024),
            _ => None,
        }
    }
}

impl fmt::Display for EncryptionAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Aes256 => write!(f, "AES-256-XTS"),
            Self::Serpent256 => write!(f, "Serpent-256-XTS"),
            Self::Twofish256 => write!(f, "Twofish-256-XTS"),
            Self::AesTwofish => write!(f, "AES-Twofish"),
            Self::TwofishAes => write!(f, "Twofish-AES"),
            Self::AesTwofishSerpent => write!(f, "AES-Twofish-Serpent"),
            Self::SerpentTwofishAes => write!(f, "Serpent-Twofish-AES"),
            Self::SerpentAes => write!(f, "Serpent-AES"),
            Self::ChaCha20Poly1305 => write!(f, "ChaCha20-Poly1305"),
            // Post-quantum hybrid algorithms
            Self::Aes256MlKem1024 => write!(f, "AES-256-XTS + ML-KEM-1024 (Hybrid PQC)"),
            Self::ChaCha20MlKem1024 => write!(f, "ChaCha20-Poly1305 + ML-KEM-1024 (Hybrid PQC)"),
            Self::AesTwofishSerpentMlKem1024 => {
                write!(f, "AES-Twofish-Serpent + ML-KEM-1024 (Hybrid PQC)")
            }
        }
    }
}

// ============================================================================
// Hash Algorithms
// ============================================================================

/// Hash algorithm for key derivation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HashAlgorithm {
    /// SHA-512 (default, most compatible)
    #[default]
    Sha512,
    /// SHA-256
    Sha256,
    /// BLAKE3 (LCPFS extension)
    Blake3,
    /// Argon2id (memory-hard, LCPFS extension)
    Argon2id,
    /// Whirlpool
    Whirlpool,
    /// RIPEMD-160 (legacy)
    Ripemd160,
}

impl HashAlgorithm {
    /// Get base iteration count for PBKDF2.
    pub fn base_iterations(&self) -> u32 {
        match self {
            Self::Sha512 => SHA512_BASE_ITERATIONS,
            Self::Sha256 => SHA256_BASE_ITERATIONS,
            Self::Blake3 => SHA512_BASE_ITERATIONS,
            Self::Argon2id => 3, // Argon2 uses different parameters
            Self::Whirlpool => SHA512_BASE_ITERATIONS,
            Self::Ripemd160 => 655331, // VeraCrypt default for RIPEMD-160
        }
    }

    /// Calculate actual iterations with PIM.
    pub fn iterations_with_pim(&self, pim: u32) -> u32 {
        if *self == Self::Argon2id {
            // Argon2 uses time cost, not iterations
            3 + pim
        } else {
            self.base_iterations() + (pim * PIM_MULTIPLIER)
        }
    }

    /// Hash output size in bytes.
    pub fn output_size(&self) -> usize {
        match self {
            Self::Sha512 => 64,
            Self::Sha256 => 32,
            Self::Blake3 => 32,
            Self::Argon2id => 64,
            Self::Whirlpool => 64,
            Self::Ripemd160 => 20,
        }
    }

    /// Algorithm ID for serialization.
    pub fn id(&self) -> u8 {
        match self {
            Self::Sha512 => 0,
            Self::Sha256 => 1,
            Self::Blake3 => 2,
            Self::Argon2id => 3,
            Self::Whirlpool => 4,
            Self::Ripemd160 => 5,
        }
    }

    /// Create from algorithm ID.
    pub fn from_id(id: u8) -> Option<Self> {
        match id {
            0 => Some(Self::Sha512),
            1 => Some(Self::Sha256),
            2 => Some(Self::Blake3),
            3 => Some(Self::Argon2id),
            4 => Some(Self::Whirlpool),
            5 => Some(Self::Ripemd160),
            _ => None,
        }
    }
}

impl fmt::Display for HashAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Sha512 => write!(f, "SHA-512"),
            Self::Sha256 => write!(f, "SHA-256"),
            Self::Blake3 => write!(f, "BLAKE3"),
            Self::Argon2id => write!(f, "Argon2id"),
            Self::Whirlpool => write!(f, "Whirlpool"),
            Self::Ripemd160 => write!(f, "RIPEMD-160"),
        }
    }
}

// ============================================================================
// Filesystem Types
// ============================================================================

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

// ============================================================================
// Error Types
// ============================================================================

/// Error type for vault operations.
#[derive(Debug, Clone)]
pub enum VaultError {
    /// Invalid password or keyfile.
    InvalidPassword,
    /// Corrupted header (CRC mismatch).
    CorruptedHeader,
    /// Invalid magic bytes.
    InvalidMagic,
    /// Volume too small.
    VolumeTooSmall,
    /// IO error.
    IoError(String),
    /// Encryption error.
    EncryptionError(String),
    /// Header not found.
    HeaderNotFound,
    /// Hidden volume not found.
    HiddenVolumeNotFound,
    /// Volume already mounted.
    AlreadyMounted,
    /// Volume not mounted.
    NotMounted,
    /// Unsupported algorithm.
    UnsupportedAlgorithm,
    /// Insufficient space for hidden volume.
    InsufficientSpace,
    /// Protected area write attempt.
    ProtectedAreaViolation,
    /// Version mismatch.
    VersionMismatch {
        /// Required minimum version.
        required: u16,
        /// Version that was found.
        found: u16,
    },
}

impl fmt::Display for VaultError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPassword => write!(f, "Invalid password or keyfile"),
            Self::CorruptedHeader => write!(f, "Corrupted header (CRC mismatch)"),
            Self::InvalidMagic => write!(f, "Invalid magic bytes"),
            Self::VolumeTooSmall => write!(f, "Volume size too small (minimum 1 MB)"),
            Self::IoError(msg) => write!(f, "IO error: {}", msg),
            Self::EncryptionError(msg) => write!(f, "Encryption error: {}", msg),
            Self::HeaderNotFound => write!(f, "Header not found"),
            Self::HiddenVolumeNotFound => write!(f, "Hidden volume not found"),
            Self::AlreadyMounted => write!(f, "Volume already mounted"),
            Self::NotMounted => write!(f, "Volume not mounted"),
            Self::UnsupportedAlgorithm => write!(f, "Unsupported algorithm"),
            Self::InsufficientSpace => write!(f, "Insufficient space for hidden volume"),
            Self::ProtectedAreaViolation => write!(f, "Write to protected hidden volume area"),
            Self::VersionMismatch { required, found } => {
                write!(
                    f,
                    "Version mismatch: requires {}, found {}",
                    required, found
                )
            }
        }
    }
}

// ============================================================================
// Options
// ============================================================================

/// Options for creating a new vault.
#[derive(Clone)]
pub struct VaultCreateOptions {
    /// Volume size in bytes.
    pub size: u64,
    /// Encryption algorithm.
    pub encryption: EncryptionAlgorithm,
    /// Hash algorithm for key derivation.
    pub hash: HashAlgorithm,
    /// Personal Iterations Multiplier.
    pub pim: u32,
    /// Keyfile paths (hashed and XORed into key).
    pub keyfiles: Vec<String>,
    /// Filesystem to create inside the volume.
    pub filesystem: FilesystemType,
    /// Fill data area with random bytes.
    pub wipe_mode: WipeMode,
}

impl Default for VaultCreateOptions {
    fn default() -> Self {
        Self {
            size: 100 * 1024 * 1024, // 100 MB
            encryption: EncryptionAlgorithm::default(),
            hash: HashAlgorithm::default(),
            pim: DEFAULT_PIM,
            keyfiles: Vec::new(),
            filesystem: FilesystemType::default(),
            wipe_mode: WipeMode::Random,
        }
    }
}

/// Options for mounting a vault.
#[derive(Clone, Default)]
pub struct VaultMountOptions {
    /// Personal Iterations Multiplier.
    pub pim: u32,
    /// Hash algorithm hint (try this first).
    pub hash_hint: Option<HashAlgorithm>,
    /// Encryption algorithm hint.
    pub encryption_hint: Option<EncryptionAlgorithm>,
    /// Keyfile paths.
    pub keyfiles: Vec<String>,
    /// Mount read-only.
    pub read_only: bool,
    /// Protect hidden volume from writes.
    pub protect_hidden: bool,
    /// Hidden volume password (needed for protection).
    pub hidden_password: Option<String>,
    /// Try backup header if primary fails.
    pub try_backup_header: bool,
    /// Try hidden volume location.
    pub try_hidden: bool,
}

/// Wipe mode for volume initialization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WipeMode {
    /// Fill with cryptographically random bytes (default, most secure).
    #[default]
    Random,
    /// Fill with zeros (faster but reveals used space).
    Zero,
    /// Don't wipe (fastest but least secure).
    None,
}

// ============================================================================
// Post-Quantum Cryptography Extension Header
// ============================================================================

/// Size of hybrid KEM ciphertext: ML-KEM-1024 CT (1568) + X25519 ephemeral PK (32).
pub const PQC_HYBRID_CT_BYTES: usize = 1600;
/// Size of hybrid KEM public key: ML-KEM-1024 EK (1568) + X25519 PK (32).
pub const PQC_HYBRID_PK_BYTES: usize = 1600;
/// Size of hybrid signature: ML-DSA-65 sig (3309) + Ed25519 sig (64).
pub const PQC_HYBRID_SIG_BYTES: usize = 3373;
/// Size of hybrid signing public key: ML-DSA-65 VK (1952) + Ed25519 VK (32).
pub const PQC_HYBRID_SIG_PK_BYTES: usize = 1984;

/// PQC header extension size (aligned to 4096 for sector alignment)
/// Layout: magic(4) + version(2) + reserved1(2) + flags(4) + algorithm_id(1) + reserved2(3) +
///         kem_ciphertext(1600) + recipient_pk(1600) + wrapped_keys(156) +
///         signature(3373) + signer_pk(1984) + crc32(4) = 8733 base, rounded up to 12288 (3x 4096)
pub const PQC_HEADER_EXT_SIZE: usize = 12288;

/// Post-Quantum Cryptography header extension.
///
/// This extension is stored immediately after the standard 512-byte header
/// for volumes using PQC encryption algorithms (Aes256MlKem1024, etc.).
///
/// ## Security Design
///
/// The master key is wrapped using hybrid X25519 + ML-KEM-1024 encapsulation:
/// 1. During volume creation, a hybrid keypair is generated
/// 2. The public key is stored in the header (for future key re-wrapping)
/// 3. The ephemeral ciphertext is stored in the header
/// 4. The shared secret from decapsulation is used to derive the key-encryption-key
/// 5. The master key is encrypted with AES-256-GCM using the KEK
///
/// The header is also signed with hybrid Ed25519 + ML-DSA-65 signatures
/// to detect tampering and provide authenticity.
#[derive(Clone)]
#[repr(C)]
pub struct PqcHeaderExtension {
    /// Extension magic: "PQC1" (indicates PQC extension v1)
    pub magic: [u8; 4],
    /// Extension version
    pub version: u16,
    /// Reserved for alignment
    pub reserved1: [u8; 2],
    /// Flags for PQC features
    pub flags: u32,
    /// Algorithm identifier (matches EncryptionAlgorithm::id())
    pub algorithm_id: u8,
    /// Reserved for alignment
    pub reserved2: [u8; 3],
    /// Hybrid KEM ciphertext (X25519 + ML-KEM-1024)
    /// Used to encapsulate the key-encryption-key (KEK)
    pub kem_ciphertext: [u8; PQC_HYBRID_CT_BYTES],
    /// Recipient's hybrid public key (for future re-keying)
    /// Stored so the volume can be re-encrypted with a new password
    pub recipient_public_key: [u8; PQC_HYBRID_PK_BYTES],
    /// Wrapped master key (AES-256-GCM encrypted with KEK)
    /// 64 bytes master key + 64 bytes secondary key + 16 bytes GCM tag + 12 bytes nonce
    pub wrapped_master_key: [u8; 156],
    /// Hybrid signature over the header (Ed25519 + ML-DSA-65)
    /// Signs: magic || version || algorithm_id || kem_ciphertext || wrapped_master_key
    pub header_signature: [u8; PQC_HYBRID_SIG_BYTES],
    /// Signer's hybrid public key (for signature verification)
    pub signer_public_key: [u8; PQC_HYBRID_SIG_PK_BYTES],
    /// CRC32 of the extension (excluding this field)
    pub crc32: u32,
    /// Reserved padding to reach PQC_HEADER_EXT_SIZE
    /// Total fixed fields: 8733 bytes. Padding needed: 12288 - 8733 = 3555
    pub reserved_padding: [u8; 3555],
}

/// PQC extension magic bytes
pub const PQC_MAGIC: [u8; 4] = *b"PQC1";

impl PqcHeaderExtension {
    /// Create a new PQC header extension with default values.
    pub fn new() -> Self {
        Self {
            magic: PQC_MAGIC,
            version: 1,
            reserved1: [0; 2],
            flags: 0,
            algorithm_id: 0,
            reserved2: [0; 3],
            kem_ciphertext: [0; PQC_HYBRID_CT_BYTES],
            recipient_public_key: [0; PQC_HYBRID_PK_BYTES],
            wrapped_master_key: [0; 156],
            header_signature: [0; PQC_HYBRID_SIG_BYTES],
            signer_public_key: [0; PQC_HYBRID_SIG_PK_BYTES],
            crc32: 0,
            reserved_padding: [0; 3555],
        }
    }

    /// Check if magic is valid.
    pub fn is_valid_magic(&self) -> bool {
        self.magic == PQC_MAGIC
    }

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

        buf[offset..offset + 4].copy_from_slice(&self.magic);
        offset += 4;
        buf[offset..offset + 2].copy_from_slice(&self.version.to_le_bytes());
        offset += 2;
        buf[offset..offset + 2].copy_from_slice(&self.reserved1);
        offset += 2;
        buf[offset..offset + 4].copy_from_slice(&self.flags.to_le_bytes());
        offset += 4;
        buf[offset] = self.algorithm_id;
        offset += 1;
        buf[offset..offset + 3].copy_from_slice(&self.reserved2);
        offset += 3;
        buf[offset..offset + PQC_HYBRID_CT_BYTES].copy_from_slice(&self.kem_ciphertext);
        offset += PQC_HYBRID_CT_BYTES;
        buf[offset..offset + PQC_HYBRID_PK_BYTES].copy_from_slice(&self.recipient_public_key);
        offset += PQC_HYBRID_PK_BYTES;
        buf[offset..offset + 156].copy_from_slice(&self.wrapped_master_key);
        offset += 156;
        buf[offset..offset + PQC_HYBRID_SIG_BYTES].copy_from_slice(&self.header_signature);
        offset += PQC_HYBRID_SIG_BYTES;
        buf[offset..offset + PQC_HYBRID_SIG_PK_BYTES].copy_from_slice(&self.signer_public_key);
        offset += PQC_HYBRID_SIG_PK_BYTES;
        buf[offset..offset + 4].copy_from_slice(&self.crc32.to_le_bytes());
        offset += 4;
        buf[offset..offset + 3555].copy_from_slice(&self.reserved_padding);

        buf
    }

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

        let mut ext = Self::new();
        let mut offset = 0;

        ext.magic.copy_from_slice(&buf[offset..offset + 4]);
        offset += 4;
        ext.version = u16::from_le_bytes([buf[offset], buf[offset + 1]]);
        offset += 2;
        ext.reserved1.copy_from_slice(&buf[offset..offset + 2]);
        offset += 2;
        ext.flags = u32::from_le_bytes(buf[offset..offset + 4].try_into().ok()?);
        offset += 4;
        ext.algorithm_id = buf[offset];
        offset += 1;
        ext.reserved2.copy_from_slice(&buf[offset..offset + 3]);
        offset += 3;
        ext.kem_ciphertext
            .copy_from_slice(&buf[offset..offset + PQC_HYBRID_CT_BYTES]);
        offset += PQC_HYBRID_CT_BYTES;
        ext.recipient_public_key
            .copy_from_slice(&buf[offset..offset + PQC_HYBRID_PK_BYTES]);
        offset += PQC_HYBRID_PK_BYTES;
        ext.wrapped_master_key
            .copy_from_slice(&buf[offset..offset + 156]);
        offset += 156;
        ext.header_signature
            .copy_from_slice(&buf[offset..offset + PQC_HYBRID_SIG_BYTES]);
        offset += PQC_HYBRID_SIG_BYTES;
        ext.signer_public_key
            .copy_from_slice(&buf[offset..offset + PQC_HYBRID_SIG_PK_BYTES]);
        offset += PQC_HYBRID_SIG_PK_BYTES;
        ext.crc32 = u32::from_le_bytes(buf[offset..offset + 4].try_into().ok()?);

        Some(ext)
    }
}

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

// ============================================================================
// Mount State
// ============================================================================

/// Mounted vault state.
#[derive(Clone)]
pub struct VaultMount {
    /// Path to the container file.
    pub container_path: String,
    /// Mount point path.
    pub mount_point: String,
    /// Device ID (for LCPFS).
    pub device_id: u64,
    /// Is this a hidden volume?
    pub is_hidden: bool,
    /// Read-only mount.
    pub read_only: bool,
    /// Protected range start (for hidden volume protection).
    pub protected_start: Option<u64>,
    /// Protected range end.
    pub protected_end: Option<u64>,
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_header_serialize_deserialize() {
        let mut header = VaultHeader::new();
        header.volume_size = 100 * 1024 * 1024;
        header.data_size = header.volume_size - (HEADER_SIZE as u64 * 2);
        header.master_key[0] = 0xAB;
        header.salt[0] = 0xCD;

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

        assert_eq!(restored.magic, VERA_MAGIC);
        assert_eq!(restored.volume_size, header.volume_size);
        assert_eq!(restored.data_size, header.data_size);
        assert_eq!(restored.master_key[0], 0xAB);
        assert_eq!(restored.salt[0], 0xCD);
    }

    #[test]
    fn test_valid_magic() {
        let mut header = VaultHeader::new();
        assert!(header.is_valid_magic());

        header.magic = TRUE_MAGIC;
        assert!(header.is_valid_magic());

        header.magic = LUNA_MAGIC;
        assert!(header.is_valid_magic());

        header.magic = *b"FAKE";
        assert!(!header.is_valid_magic());
    }

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

        assert!(!EncryptionAlgorithm::Aes256.is_cascade());
        assert!(EncryptionAlgorithm::AesTwofishSerpent.is_cascade());

        let id = EncryptionAlgorithm::Serpent256.id();
        assert_eq!(
            EncryptionAlgorithm::from_id(id),
            Some(EncryptionAlgorithm::Serpent256)
        );
    }

    #[test]
    fn test_pqc_algorithms() {
        // Test PQC algorithm properties
        assert!(EncryptionAlgorithm::Aes256MlKem1024.is_post_quantum());
        assert!(EncryptionAlgorithm::ChaCha20MlKem1024.is_post_quantum());
        assert!(EncryptionAlgorithm::AesTwofishSerpentMlKem1024.is_post_quantum());

        // Non-PQC algorithms should not be post-quantum
        assert!(!EncryptionAlgorithm::Aes256.is_post_quantum());
        assert!(!EncryptionAlgorithm::ChaCha20Poly1305.is_post_quantum());
        assert!(!EncryptionAlgorithm::AesTwofishSerpent.is_post_quantum());

        // Test serialization roundtrip
        let pqc_id = EncryptionAlgorithm::Aes256MlKem1024.id();
        assert_eq!(
            EncryptionAlgorithm::from_id(pqc_id),
            Some(EncryptionAlgorithm::Aes256MlKem1024)
        );

        let cascade_pqc_id = EncryptionAlgorithm::AesTwofishSerpentMlKem1024.id();
        assert_eq!(
            EncryptionAlgorithm::from_id(cascade_pqc_id),
            Some(EncryptionAlgorithm::AesTwofishSerpentMlKem1024)
        );

        // PQC cascade should have 3 ciphers
        assert_eq!(
            EncryptionAlgorithm::AesTwofishSerpentMlKem1024.key_count(),
            3
        );
        assert!(EncryptionAlgorithm::AesTwofishSerpentMlKem1024.is_cascade());
    }

    #[test]
    fn test_hash_algorithm_iterations() {
        let sha512 = HashAlgorithm::Sha512;
        assert_eq!(sha512.iterations_with_pim(0), 500000);
        assert_eq!(sha512.iterations_with_pim(10), 510000);

        let argon2 = HashAlgorithm::Argon2id;
        assert_eq!(argon2.iterations_with_pim(0), 3);
        assert_eq!(argon2.iterations_with_pim(5), 8);
    }

    #[test]
    fn test_vault_flags() {
        let mut flags = VaultFlags::NONE;
        assert!(!flags.contains(VaultFlags::READ_ONLY));

        flags.insert(VaultFlags::READ_ONLY);
        assert!(flags.contains(VaultFlags::READ_ONLY));

        flags.insert(VaultFlags::LCPFS_NATIVE);
        assert!(flags.contains(VaultFlags::READ_ONLY));
        assert!(flags.contains(VaultFlags::LCPFS_NATIVE));

        flags.remove(VaultFlags::READ_ONLY);
        assert!(!flags.contains(VaultFlags::READ_ONLY));
        assert!(flags.contains(VaultFlags::LCPFS_NATIVE));
    }
}