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
//! LunaVault Volume Operations
//!
//! Create, open, and manage encrypted volumes.

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

extern crate alloc;

use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryInto;

use super::crypto::*;
use super::types::*;

// ============================================================================
// Volume Storage (no_std compatible)
// ============================================================================

/// In-memory volume storage for no_std environments.
/// In std environments, this would be replaced with file I/O.
pub struct VolumeStorage {
    /// Volume data.
    data: Vec<u8>,
    /// Volume path (for identification).
    path: String,
}

impl VolumeStorage {
    /// Create new storage with given size.
    pub fn new(path: &str, size: u64) -> Self {
        Self {
            data: vec![0u8; size as usize],
            path: path.to_string(),
        }
    }

    /// Create from existing data.
    pub fn from_data(path: &str, data: Vec<u8>) -> Self {
        Self {
            data,
            path: path.to_string(),
        }
    }

    /// Read bytes at offset.
    pub fn read(&self, offset: u64, len: usize) -> Result<Vec<u8>, VaultError> {
        let start = offset as usize;
        let end = start + len;

        if end > self.data.len() {
            return Err(VaultError::IoError("Read past end of volume".to_string()));
        }

        Ok(self.data[start..end].to_vec())
    }

    /// Write bytes at offset.
    pub fn write(&mut self, offset: u64, data: &[u8]) -> Result<(), VaultError> {
        let start = offset as usize;
        let end = start + data.len();

        if end > self.data.len() {
            return Err(VaultError::IoError("Write past end of volume".to_string()));
        }

        self.data[start..end].copy_from_slice(data);
        Ok(())
    }

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

    /// Get path.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Get raw data.
    pub fn into_data(self) -> Vec<u8> {
        self.data
    }

    /// Get data reference.
    pub fn data(&self) -> &[u8] {
        &self.data
    }
}

// ============================================================================
// Volume Creation
// ============================================================================

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

    // Generate random salt
    let salt = generate_salt();

    // Process keyfiles
    let keyfile_data: Vec<Vec<u8>> = Vec::new(); // Would load from paths in std
    let keyfile_refs: Vec<&[u8]> = keyfile_data.iter().map(|v| v.as_slice()).collect();

    // Derive header key
    let header_key = derive_with_keyfiles(
        password.as_bytes(),
        &keyfile_refs,
        &salt,
        options.pim,
        options.hash,
    );

    // Generate random master keys
    let master_key = generate_master_key();
    let secondary_key = generate_master_key();

    // Calculate data area
    let data_offset = HEADER_SIZE as u64;
    let data_size = options.size - (HEADER_SIZE as u64 * 2); // Two headers

    // Create header
    let mut header = VaultHeader::new();
    header.magic = VERA_MAGIC;
    header.version = 5;
    header.min_version = 5;
    header.hidden_size = 0;
    header.volume_size = options.size;
    header.data_offset = data_offset;
    header.data_size = data_size;
    header.sector_size = SECTOR_SIZE as u32;
    header.master_key.copy_from_slice(&master_key);
    header.secondary_key.copy_from_slice(&secondary_key);
    header.salt.copy_from_slice(&salt);

    // Set flags based on options
    if options.filesystem == FilesystemType::Lcpfs {
        header.flags.insert(VaultFlags::LCPFS_NATIVE);
    }
    if options.encryption == EncryptionAlgorithm::ChaCha20Poly1305 {
        header.flags.insert(VaultFlags::CHACHA20);
    }

    // Calculate CRC32 of header (bytes 256-511)
    let header_bytes = header.to_bytes();
    header.crc32 = crc32(&header_bytes[256..512]);

    // Create storage
    let mut storage = VolumeStorage::new("", options.size);

    // Write salt at offset 0 (unencrypted)
    storage.write(0, &salt)?;

    // Encrypt and write header
    let encrypted_header = encrypt_header(&header, &header_key, options.encryption)?;
    storage.write(SALT_SIZE as u64, &encrypted_header)?;

    // Write backup header at end
    let backup_offset = options.size - HEADER_SIZE as u64;
    storage.write(backup_offset, &salt)?;
    storage.write(backup_offset + SALT_SIZE as u64, &encrypted_header)?;

    // Initialize data area based on wipe mode
    match options.wipe_mode {
        WipeMode::Random => {
            // Write random data in chunks
            let chunk_size = 64 * 1024; // 64 KB chunks
            let mut offset = data_offset;
            while offset < data_offset + data_size {
                let remaining = (data_offset + data_size - offset) as usize;
                let size = core::cmp::min(chunk_size, remaining);
                let random_data = generate_random_bytes(size);
                storage.write(offset, &random_data)?;
                offset += size as u64;
            }
        }
        WipeMode::Zero => {
            // Already zeroed from VolumeStorage::new()
        }
        WipeMode::None => {
            // Don't initialize
        }
    }

    Ok(storage)
}

/// Encrypt a volume header.
fn encrypt_header(
    header: &VaultHeader,
    header_key: &[u8; 64],
    algorithm: EncryptionAlgorithm,
) -> Result<Vec<u8>, VaultError> {
    let mut header_bytes = header.to_bytes();

    // Encrypt the header (treating it as sector 0, but using different key)
    // Use first 32 bytes as encryption key, next 32 as XTS key
    encrypt_sector(
        &mut header_bytes,
        0,
        &header_key[..32],
        &header_key[32..],
        algorithm,
    );

    Ok(header_bytes.to_vec())
}

/// Decrypt a volume header.
fn decrypt_header(
    encrypted: &[u8],
    header_key: &[u8; 64],
    algorithm: EncryptionAlgorithm,
) -> Result<VaultHeader, VaultError> {
    if encrypted.len() < 512 {
        return Err(VaultError::CorruptedHeader);
    }

    let mut decrypted = [0u8; 512];
    decrypted.copy_from_slice(&encrypted[..512]);

    decrypt_sector(
        &mut decrypted,
        0,
        &header_key[..32],
        &header_key[32..],
        algorithm,
    );

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

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

    // Verify CRC32
    let expected_crc = crc32(&decrypted[256..512]);
    if header.crc32 != expected_crc {
        return Err(VaultError::CorruptedHeader);
    }

    Ok(header)
}

// ============================================================================
// Volume Opening
// ============================================================================

/// Open and decrypt a volume header.
pub fn open_volume(
    storage: &VolumeStorage,
    password: &str,
    options: &VaultMountOptions,
) -> Result<(VaultHeader, EncryptionAlgorithm), VaultError> {
    // Read salt from header
    let salt_bytes = storage.read(0, SALT_SIZE)?;
    let salt: [u8; 64] = salt_bytes
        .try_into()
        .map_err(|_| VaultError::CorruptedHeader)?;

    // Process keyfiles
    let keyfile_data: Vec<Vec<u8>> = Vec::new();
    let keyfile_refs: Vec<&[u8]> = keyfile_data.iter().map(|v| v.as_slice()).collect();

    // Try different hash algorithms
    let hashes = if let Some(hint) = options.hash_hint {
        vec![hint]
    } else {
        vec![
            HashAlgorithm::Sha512,
            HashAlgorithm::Sha256,
            HashAlgorithm::Blake3,
            HashAlgorithm::Whirlpool,
            HashAlgorithm::Argon2id,
        ]
    };

    // Try different encryption algorithms (including PQC hybrids)
    let encryptions = if let Some(hint) = options.encryption_hint {
        vec![hint]
    } else {
        vec![
            // Classical algorithms
            EncryptionAlgorithm::Aes256,
            EncryptionAlgorithm::AesTwofish,
            EncryptionAlgorithm::AesTwofishSerpent,
            EncryptionAlgorithm::Serpent256,
            EncryptionAlgorithm::Twofish256,
            EncryptionAlgorithm::ChaCha20Poly1305,
            // Post-quantum hybrid algorithms (X25519 + ML-KEM-1024)
            EncryptionAlgorithm::Aes256MlKem1024,
            EncryptionAlgorithm::ChaCha20MlKem1024,
            EncryptionAlgorithm::AesTwofishSerpentMlKem1024,
        ]
    };

    // Read encrypted header
    let encrypted_header = storage.read(SALT_SIZE as u64, 512)?;

    // Try primary header
    for hash in &hashes {
        let header_key = derive_with_keyfiles(
            password.as_bytes(),
            &keyfile_refs,
            &salt,
            options.pim,
            *hash,
        );

        for enc in &encryptions {
            if let Ok(header) = decrypt_header(&encrypted_header, &header_key, *enc) {
                return Ok((header, *enc));
            }
        }
    }

    // Try backup header
    if options.try_backup_header {
        let backup_offset = storage.size() - HEADER_SIZE as u64;
        let backup_salt = storage.read(backup_offset, SALT_SIZE)?;
        let backup_header = storage.read(backup_offset + SALT_SIZE as u64, 512)?;

        let salt: [u8; 64] = backup_salt
            .try_into()
            .map_err(|_| VaultError::CorruptedHeader)?;

        for hash in &hashes {
            let header_key = derive_with_keyfiles(
                password.as_bytes(),
                &keyfile_refs,
                &salt,
                options.pim,
                *hash,
            );

            for enc in &encryptions {
                if let Ok(header) = decrypt_header(&backup_header, &header_key, *enc) {
                    return Ok((header, *enc));
                }
            }
        }
    }

    // Try hidden volume location
    if options.try_hidden {
        return open_hidden_volume(storage, password, options);
    }

    Err(VaultError::InvalidPassword)
}

/// Open hidden volume.
fn open_hidden_volume(
    storage: &VolumeStorage,
    password: &str,
    options: &VaultMountOptions,
) -> Result<(VaultHeader, EncryptionAlgorithm), VaultError> {
    // Hidden header is at: end - 2*HEADER_SIZE (before backup header)
    let hidden_offset = storage.size() - (HEADER_SIZE as u64 * 2);

    let salt_bytes = storage.read(hidden_offset, SALT_SIZE)?;
    let salt: [u8; 64] = salt_bytes
        .try_into()
        .map_err(|_| VaultError::HiddenVolumeNotFound)?;

    let encrypted_header = storage.read(hidden_offset + SALT_SIZE as u64, 512)?;

    let keyfile_data: Vec<Vec<u8>> = Vec::new();
    let keyfile_refs: Vec<&[u8]> = keyfile_data.iter().map(|v| v.as_slice()).collect();

    let hashes = vec![
        HashAlgorithm::Sha512,
        HashAlgorithm::Sha256,
        HashAlgorithm::Blake3,
    ];

    let encryptions = vec![
        EncryptionAlgorithm::Aes256,
        EncryptionAlgorithm::AesTwofishSerpent,
    ];

    for hash in &hashes {
        let header_key = derive_with_keyfiles(
            password.as_bytes(),
            &keyfile_refs,
            &salt,
            options.pim,
            *hash,
        );

        for enc in &encryptions {
            if let Ok(header) = decrypt_header(&encrypted_header, &header_key, *enc) {
                return Ok((header, *enc));
            }
        }
    }

    Err(VaultError::HiddenVolumeNotFound)
}

// ============================================================================
// Hidden Volume Creation
// ============================================================================

/// Create a hidden volume within an existing container.
pub fn create_hidden_volume(
    storage: &mut VolumeStorage,
    outer_password: &str,
    hidden_password: &str,
    hidden_size: u64,
    options: &VaultCreateOptions,
) -> Result<(), VaultError> {
    // First, verify outer volume
    let mount_options = VaultMountOptions {
        pim: options.pim,
        try_backup_header: true,
        ..Default::default()
    };

    let (outer_header, _outer_enc) = open_volume(storage, outer_password, &mount_options)?;

    // Check if there's enough space
    let max_hidden_size = outer_header.data_size / 2; // At most half the data area
    if hidden_size > max_hidden_size {
        return Err(VaultError::InsufficientSpace);
    }

    // Hidden volume location: end of outer data area
    let hidden_data_offset = outer_header.data_offset + outer_header.data_size - hidden_size;

    // Generate new salt and keys
    let hidden_salt = generate_salt();
    let hidden_master_key = generate_master_key();
    let hidden_secondary_key = generate_master_key();

    // Create hidden header
    let mut hidden_header = VaultHeader::new();
    hidden_header.magic = VERA_MAGIC;
    hidden_header.version = 5;
    hidden_header.min_version = 5;
    hidden_header.volume_size = hidden_size;
    hidden_header.data_offset = hidden_data_offset;
    hidden_header.data_size = hidden_size - HEADER_SIZE as u64;
    hidden_header.sector_size = SECTOR_SIZE as u32;
    hidden_header.master_key.copy_from_slice(&hidden_master_key);
    hidden_header
        .secondary_key
        .copy_from_slice(&hidden_secondary_key);
    hidden_header.salt.copy_from_slice(&hidden_salt);

    if options.filesystem == FilesystemType::Lcpfs {
        hidden_header.flags.insert(VaultFlags::LCPFS_NATIVE);
    }

    // Calculate CRC
    let header_bytes = hidden_header.to_bytes();
    hidden_header.crc32 = crc32(&header_bytes[256..512]);

    // Derive key from hidden password
    let hidden_header_key = derive_header_key(
        hidden_password.as_bytes(),
        &hidden_salt,
        options.pim,
        options.hash,
    );

    // Encrypt hidden header
    let encrypted_hidden = encrypt_header(&hidden_header, &hidden_header_key, options.encryption)?;

    // Write hidden header (before backup header area)
    let hidden_header_offset = storage.size() - (HEADER_SIZE as u64 * 2);
    storage.write(hidden_header_offset, &hidden_salt)?;
    storage.write(hidden_header_offset + SALT_SIZE as u64, &encrypted_hidden)?;

    Ok(())
}

// ============================================================================
// Password Change
// ============================================================================

/// Change volume password.
pub fn change_password(
    storage: &mut VolumeStorage,
    old_password: &str,
    new_password: &str,
    options: &VaultMountOptions,
    new_pim: Option<u32>,
    new_hash: Option<HashAlgorithm>,
) -> Result<(), VaultError> {
    // Open with old password
    let (mut header, encryption) = open_volume(storage, old_password, options)?;

    // Read original salt
    let salt_bytes = storage.read(0, SALT_SIZE)?;
    let original_salt: [u8; 64] = salt_bytes
        .try_into()
        .map_err(|_| VaultError::CorruptedHeader)?;

    // Generate new salt
    let new_salt = generate_salt();
    let pim = new_pim.unwrap_or(options.pim);
    let hash = new_hash.unwrap_or(options.hash_hint.unwrap_or(HashAlgorithm::Sha512));

    // Derive new header key
    let new_header_key = derive_header_key(new_password.as_bytes(), &new_salt, pim, hash);

    // Update salt in header
    header.salt.copy_from_slice(&new_salt);

    // Recalculate CRC
    let header_bytes = header.to_bytes();
    header.crc32 = crc32(&header_bytes[256..512]);

    // Encrypt with new key
    let encrypted = encrypt_header(&header, &new_header_key, encryption)?;

    // Write new primary header
    storage.write(0, &new_salt)?;
    storage.write(SALT_SIZE as u64, &encrypted)?;

    // Write new backup header
    let backup_offset = storage.size() - HEADER_SIZE as u64;
    storage.write(backup_offset, &new_salt)?;
    storage.write(backup_offset + SALT_SIZE as u64, &encrypted)?;

    Ok(())
}

// ============================================================================
// Header Backup/Restore
// ============================================================================

/// Backup volume header.
pub fn backup_header(storage: &VolumeStorage) -> Result<Vec<u8>, VaultError> {
    // Read salt + encrypted header
    let salt = storage.read(0, SALT_SIZE)?;
    let encrypted = storage.read(SALT_SIZE as u64, ENCRYPTED_HEADER_SIZE + 64)?;

    let mut backup = Vec::with_capacity(SALT_SIZE + ENCRYPTED_HEADER_SIZE + 64);
    backup.extend_from_slice(&salt);
    backup.extend_from_slice(&encrypted);

    Ok(backup)
}

/// Restore volume header from backup.
pub fn restore_header(storage: &mut VolumeStorage, backup: &[u8]) -> Result<(), VaultError> {
    if backup.len() < SALT_SIZE + 512 {
        return Err(VaultError::CorruptedHeader);
    }

    // Write to primary header
    storage.write(0, &backup[..SALT_SIZE + 512])?;

    // Write to backup header
    let backup_offset = storage.size() - HEADER_SIZE as u64;
    storage.write(backup_offset, &backup[..SALT_SIZE + 512])?;

    Ok(())
}

// ============================================================================
// Volume Information
// ============================================================================

/// Get volume information without full decryption.
pub struct VolumeInfo {
    /// Total size.
    pub size: u64,
    /// Data area size.
    pub data_size: u64,
    /// Has backup header.
    pub has_backup_header: bool,
    /// Potentially has hidden volume (always true for plausible deniability).
    pub may_have_hidden: bool,
}

/// Get basic volume information.
pub fn get_volume_info(storage: &VolumeStorage) -> VolumeInfo {
    VolumeInfo {
        size: storage.size(),
        data_size: storage.size().saturating_sub(HEADER_SIZE as u64 * 2),
        has_backup_header: storage.size() >= HEADER_SIZE as u64 * 2,
        may_have_hidden: true, // Always true for deniability
    }
}

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

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

    #[test]
    fn test_create_volume() {
        let options = VaultCreateOptions {
            size: 2 * 1024 * 1024, // 2 MB
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256, // Faster for tests
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        let storage = create_volume("test_password", &options).unwrap();
        assert_eq!(storage.size(), 2 * 1024 * 1024);
    }

    #[test]
    fn test_open_volume() {
        let password = "secure_password_123";
        let options = VaultCreateOptions {
            size: 2 * 1024 * 1024,
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256,
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        let storage = create_volume(password, &options).unwrap();

        let mount_options = VaultMountOptions {
            hash_hint: Some(HashAlgorithm::Sha256),
            encryption_hint: Some(EncryptionAlgorithm::Aes256),
            ..Default::default()
        };

        let (header, enc) = open_volume(&storage, password, &mount_options).unwrap();

        assert_eq!(header.magic, VERA_MAGIC);
        assert_eq!(header.volume_size, 2 * 1024 * 1024);
        assert_eq!(enc, EncryptionAlgorithm::Aes256);
    }

    #[test]
    fn test_wrong_password() {
        let options = VaultCreateOptions {
            size: 2 * 1024 * 1024,
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256,
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        let storage = create_volume("correct_password", &options).unwrap();

        let mount_options = VaultMountOptions {
            hash_hint: Some(HashAlgorithm::Sha256),
            encryption_hint: Some(EncryptionAlgorithm::Aes256),
            try_backup_header: false,
            try_hidden: false,
            ..Default::default()
        };

        let result = open_volume(&storage, "wrong_password", &mount_options);
        assert!(matches!(result, Err(VaultError::InvalidPassword)));
    }

    #[test]
    fn test_hidden_volume() {
        let outer_password = "outer_secret";
        let hidden_password = "hidden_secret";

        let options = VaultCreateOptions {
            size: 10 * 1024 * 1024, // 10 MB
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256,
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        let mut storage = create_volume(outer_password, &options).unwrap();

        // Create hidden volume
        let hidden_options = VaultCreateOptions {
            size: 2 * 1024 * 1024, // 2 MB hidden
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256,
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        create_hidden_volume(
            &mut storage,
            outer_password,
            hidden_password,
            2 * 1024 * 1024,
            &hidden_options,
        )
        .unwrap();

        // Open outer volume
        let mount_options = VaultMountOptions {
            hash_hint: Some(HashAlgorithm::Sha256),
            encryption_hint: Some(EncryptionAlgorithm::Aes256),
            ..Default::default()
        };

        let (outer_header, _) = open_volume(&storage, outer_password, &mount_options).unwrap();
        assert_eq!(outer_header.volume_size, 10 * 1024 * 1024);

        // Open hidden volume
        let hidden_mount_options = VaultMountOptions {
            hash_hint: Some(HashAlgorithm::Sha256),
            encryption_hint: Some(EncryptionAlgorithm::Aes256),
            try_hidden: true,
            ..Default::default()
        };

        let (hidden_header, _) =
            open_volume(&storage, hidden_password, &hidden_mount_options).unwrap();
        assert!(hidden_header.volume_size < 10 * 1024 * 1024);
    }

    #[test]
    fn test_change_password() {
        let old_password = "old_password";
        let new_password = "new_password";

        let options = VaultCreateOptions {
            size: 2 * 1024 * 1024,
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256,
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        let mut storage = create_volume(old_password, &options).unwrap();

        let mount_options = VaultMountOptions {
            hash_hint: Some(HashAlgorithm::Sha256),
            encryption_hint: Some(EncryptionAlgorithm::Aes256),
            ..Default::default()
        };

        // Change password
        change_password(
            &mut storage,
            old_password,
            new_password,
            &mount_options,
            None,
            None,
        )
        .unwrap();

        // Old password should fail
        let result = open_volume(&storage, old_password, &mount_options);
        assert!(result.is_err());

        // New password should work
        let (header, _) = open_volume(&storage, new_password, &mount_options).unwrap();
        assert_eq!(header.magic, VERA_MAGIC);
    }

    #[test]
    fn test_backup_restore_header() {
        let password = "test_password";

        let options = VaultCreateOptions {
            size: 2 * 1024 * 1024,
            encryption: EncryptionAlgorithm::Aes256,
            hash: HashAlgorithm::Sha256,
            wipe_mode: WipeMode::Zero,
            ..Default::default()
        };

        let mut storage = create_volume(password, &options).unwrap();

        // Backup header
        let backup = backup_header(&storage).unwrap();

        // Corrupt the header
        storage.write(0, &[0u8; SALT_SIZE]).unwrap();

        // Restore should work
        restore_header(&mut storage, &backup).unwrap();

        // Volume should open
        let mount_options = VaultMountOptions {
            hash_hint: Some(HashAlgorithm::Sha256),
            encryption_hint: Some(EncryptionAlgorithm::Aes256),
            ..Default::default()
        };

        let (header, _) = open_volume(&storage, password, &mount_options).unwrap();
        assert_eq!(header.magic, VERA_MAGIC);
    }
}