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
//! Secure Data Erasure
//!
//! Provides cryptographically secure data destruction for LCPFS.
//!
//! # Overview
//!
//! This module implements multiple secure erasure standards to ensure
//! irrecoverable data destruction. It supports both software-based
//! overwrite methods and hardware-based secure erase commands.
//!
//! # Methods Supported
//!
//! | Method | Passes | Description |
//! |--------|--------|-------------|
//! | DoD 5220.22-M (3-pass) | 3 | US DoD standard: zeros, ones, random |
//! | DoD 5220.22-M (7-pass) | 7 | Extended DoD: pattern variations |
//! | Gutmann | 35 | Maximum paranoia: 35-pass with MFM/RLL patterns |
//! | CryptoErase | 1 | Destroy encryption keys (fastest) |
//! | ATA Secure Erase | HW | Drive-level secure erase command |
//! | NVMe Format | HW | NVMe namespace format with crypto erase |
//!
//! # Security Considerations
//!
//! - **SSDs/Flash**: CryptoErase or NVMe Format is preferred due to wear leveling
//! - **HDDs**: Gutmann or DoD 7-pass for maximum security
//! - **Encrypted data**: CryptoErase is sufficient and instantaneous
//! - **Verification**: Random sampling verification after overwrite passes

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

extern crate alloc;

use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};

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

// ============================================================================
// Wipe Method Enum
// ============================================================================

/// Secure erase method selection.
///
/// Different methods offer various tradeoffs between speed, thoroughness,
/// and compatibility with different storage media types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WipeMethod {
    /// DoD 5220.22-M 3-pass: zeros → ones → random
    ///
    /// Standard US Department of Defense erasure method.
    /// Suitable for most scenarios.
    Dod3Pass,

    /// DoD 5220.22-M 7-pass: Extended pattern variation
    ///
    /// Passes: zeros, ones, random, zeros, ones, random, random verify
    /// Higher security but slower.
    Dod7Pass,

    /// Gutmann 35-pass method
    ///
    /// Maximum paranoia erasure with 35 passes including:
    /// - Random passes (4)
    /// - Specific bit patterns targeting MFM/RLL encoding
    /// - Final random passes
    ///
    /// Note: Designed for older magnetic media. Modern drives may not
    /// benefit from all 35 passes, but this provides maximum assurance.
    Gutmann,

    /// Cryptographic erase: Destroy encryption keys
    ///
    /// For encrypted volumes, securely destroying the master key
    /// renders all data permanently unrecoverable. This is:
    /// - Instantaneous
    /// - Effective regardless of storage media
    /// - The recommended method for encrypted data
    CryptoErase,

    /// ATA Secure Erase command
    ///
    /// Uses the drive's built-in secure erase functionality.
    /// - Triggers drive firmware to overwrite all sectors
    /// - May take minutes to hours depending on drive size
    /// - Resets drive to factory state
    ///
    /// Requirements: Drive must support ATA Security feature set.
    AtaSecureErase,

    /// ATA Enhanced Secure Erase
    ///
    /// Extended version that also erases:
    /// - Reallocated sectors
    /// - Host Protected Area (HPA)
    /// - Device Configuration Overlay (DCO)
    AtaEnhancedSecureErase,

    /// NVMe Format with Secure Erase
    ///
    /// Uses NVMe Format command with:
    /// - Secure Erase Settings (SES) = User Data Erase
    /// - Or Cryptographic Erase if supported
    ///
    /// This is the fastest and most thorough method for NVMe drives.
    NvmeFormat,

    /// NVMe Sanitize - Block Erase
    ///
    /// NVMe Sanitize command with block erase action.
    /// More thorough than Format, covers all user data areas.
    NvmeSanitizeBlock,

    /// NVMe Sanitize - Crypto Erase
    ///
    /// NVMe Sanitize command with cryptographic erase.
    /// Destroys the internal encryption key (if drive supports encryption).
    NvmeSanitizeCrypto,

    /// Quick erase: Single random pass
    ///
    /// Fastest software method. Suitable for:
    /// - Non-sensitive data
    /// - Time-critical scenarios
    /// - Data already encrypted
    QuickRandom,

    /// NIST SP 800-88 Clear
    ///
    /// NIST standard for media sanitization (Clear level).
    /// Single pass with zeros or vendor-specific pattern.
    NistClear,

    /// NIST SP 800-88 Purge
    ///
    /// NIST standard for media sanitization (Purge level).
    /// Multiple passes with verification.
    NistPurge,
}

impl WipeMethod {
    /// Get the number of overwrite passes for this method.
    ///
    /// Returns `None` for hardware-based methods that don't use
    /// software overwrite passes.
    pub fn pass_count(&self) -> Option<usize> {
        match self {
            Self::Dod3Pass => Some(3),
            Self::Dod7Pass => Some(7),
            Self::Gutmann => Some(35),
            Self::CryptoErase => Some(0),
            Self::AtaSecureErase => None,
            Self::AtaEnhancedSecureErase => None,
            Self::NvmeFormat => None,
            Self::NvmeSanitizeBlock => None,
            Self::NvmeSanitizeCrypto => None,
            Self::QuickRandom => Some(1),
            Self::NistClear => Some(1),
            Self::NistPurge => Some(3),
        }
    }

    /// Check if this method requires hardware support.
    pub fn requires_hardware(&self) -> bool {
        matches!(
            self,
            Self::AtaSecureErase
                | Self::AtaEnhancedSecureErase
                | Self::NvmeFormat
                | Self::NvmeSanitizeBlock
                | Self::NvmeSanitizeCrypto
        )
    }

    /// Check if this method is suitable for SSDs/flash storage.
    ///
    /// Software overwrite methods are less effective on SSDs due to
    /// wear leveling and over-provisioning. Hardware methods or
    /// CryptoErase are preferred.
    pub fn suitable_for_ssd(&self) -> bool {
        matches!(
            self,
            Self::CryptoErase
                | Self::AtaSecureErase
                | Self::AtaEnhancedSecureErase
                | Self::NvmeFormat
                | Self::NvmeSanitizeBlock
                | Self::NvmeSanitizeCrypto
        )
    }

    /// Get human-readable description of this method.
    pub fn description(&self) -> &'static str {
        match self {
            Self::Dod3Pass => "DoD 5220.22-M 3-pass (zeros, ones, random)",
            Self::Dod7Pass => "DoD 5220.22-M 7-pass extended",
            Self::Gutmann => "Gutmann 35-pass maximum security",
            Self::CryptoErase => "Cryptographic key destruction",
            Self::AtaSecureErase => "ATA Secure Erase command",
            Self::AtaEnhancedSecureErase => "ATA Enhanced Secure Erase",
            Self::NvmeFormat => "NVMe Format with secure erase",
            Self::NvmeSanitizeBlock => "NVMe Sanitize block erase",
            Self::NvmeSanitizeCrypto => "NVMe Sanitize crypto erase",
            Self::QuickRandom => "Quick single random pass",
            Self::NistClear => "NIST SP 800-88 Clear",
            Self::NistPurge => "NIST SP 800-88 Purge",
        }
    }
}

// ============================================================================
// Erase Progress Tracking
// ============================================================================

/// Progress callback for long-running erase operations.
pub type EraseProgressCallback = fn(progress: &EraseProgress);

/// Erase operation progress information.
#[derive(Debug, Clone)]
pub struct EraseProgress {
    /// Current pass number (1-indexed).
    pub current_pass: usize,
    /// Total number of passes.
    pub total_passes: usize,
    /// Bytes erased in current pass.
    pub bytes_completed: u64,
    /// Total bytes to erase.
    pub bytes_total: u64,
    /// Estimated time remaining in seconds.
    pub eta_seconds: Option<u64>,
    /// Current operation description.
    pub operation: String,
    /// Whether operation can be cancelled.
    pub cancellable: bool,
}

impl EraseProgress {
    /// Get progress as percentage (0.0 - 100.0).
    pub fn percentage(&self) -> f64 {
        if self.bytes_total == 0 {
            return 100.0;
        }

        let pass_progress = self.bytes_completed as f64 / self.bytes_total as f64;
        let pass_weight = 1.0 / self.total_passes as f64;
        let completed_passes = (self.current_pass - 1) as f64 * pass_weight;

        (completed_passes + pass_progress * pass_weight) * 100.0
    }
}

// ============================================================================
// Secure Eraser
// ============================================================================

/// Secure data eraser.
///
/// Provides methods to securely erase data from storage devices
/// using various industry-standard methods.
pub struct SecureEraser {
    /// Random number generator for overwrite patterns.
    rng: Option<CryptoRng>,
    /// Buffer size for overwrite operations.
    buffer_size: usize,
    /// Whether to verify after each pass.
    verify_passes: bool,
    /// Progress callback.
    progress_callback: Option<EraseProgressCallback>,
    /// Cancellation flag.
    cancelled: AtomicBool,
    /// Bytes processed.
    bytes_processed: AtomicU64,
}

impl SecureEraser {
    /// Create a new secure eraser with default settings.
    pub fn new() -> Self {
        Self {
            rng: CryptoRng::new().ok(),
            buffer_size: 1024 * 1024, // 1 MB buffer
            verify_passes: false,
            progress_callback: None,
            cancelled: AtomicBool::new(false),
            bytes_processed: AtomicU64::new(0),
        }
    }

    /// Get or initialize the RNG, returning error if unavailable.
    fn get_rng(&mut self) -> Result<&mut CryptoRng, FsError> {
        if self.rng.is_none() {
            self.rng = CryptoRng::new().ok();
        }
        self.rng.as_mut().ok_or(FsError::InvalidArgument {
            reason: "Random number generator unavailable",
        })
    }

    /// Set buffer size for overwrite operations.
    pub fn with_buffer_size(mut self, size: usize) -> Self {
        self.buffer_size = size.max(4096); // Minimum 4 KB
        self
    }

    /// Enable verification after each overwrite pass.
    pub fn with_verification(mut self, verify: bool) -> Self {
        self.verify_passes = verify;
        self
    }

    /// Set progress callback for status updates.
    pub fn with_progress_callback(mut self, callback: EraseProgressCallback) -> Self {
        self.progress_callback = Some(callback);
        self
    }

    /// Cancel an ongoing erase operation.
    pub fn cancel(&self) {
        self.cancelled.store(true, Ordering::SeqCst);
    }

    /// Check if operation was cancelled.
    fn is_cancelled(&self) -> bool {
        self.cancelled.load(Ordering::SeqCst)
    }

    /// Reset cancellation flag for new operation.
    fn reset(&self) {
        self.cancelled.store(false, Ordering::SeqCst);
        self.bytes_processed.store(0, Ordering::SeqCst);
    }

    /// Report progress to callback if set.
    fn report_progress(&self, progress: EraseProgress) {
        if let Some(callback) = self.progress_callback {
            callback(&progress);
        }
    }

    /// Erase a memory buffer securely.
    ///
    /// # Arguments
    ///
    /// * `data` - Buffer to erase
    /// * `method` - Erase method to use
    ///
    /// # Returns
    ///
    /// Ok(()) on success, Err if cancelled or method not applicable.
    pub fn erase_buffer(&mut self, data: &mut [u8], method: WipeMethod) -> Result<(), FsError> {
        if method.requires_hardware() {
            return Err(FsError::InvalidArgument {
                reason: "Hardware erase method not applicable to memory buffer",
            });
        }

        self.reset();

        match method {
            WipeMethod::Dod3Pass => self.dod_3_pass(data),
            WipeMethod::Dod7Pass => self.dod_7_pass(data),
            WipeMethod::Gutmann => self.gutmann_35_pass(data),
            WipeMethod::QuickRandom => self.random_pass(data),
            WipeMethod::NistClear => self.nist_clear(data),
            WipeMethod::NistPurge => self.nist_purge(data),
            WipeMethod::CryptoErase => {
                // For buffers, crypto erase just means random overwrite
                self.random_pass(data)
            }
            _ => Err(FsError::InvalidArgument {
                reason: "Unsupported erase method for buffer",
            }),
        }
    }

    /// DoD 5220.22-M 3-pass erasure.
    fn dod_3_pass(&mut self, data: &mut [u8]) -> Result<(), FsError> {
        // Pass 1: All zeros
        self.overwrite_pattern(data, 0x00, 1, 3, "Writing zeros")?;

        // Pass 2: All ones
        self.overwrite_pattern(data, 0xFF, 2, 3, "Writing ones")?;

        // Pass 3: Random data
        self.overwrite_random(data, 3, 3, "Writing random data")?;

        Ok(())
    }

    /// DoD 5220.22-M 7-pass erasure.
    fn dod_7_pass(&mut self, data: &mut [u8]) -> Result<(), FsError> {
        // Pass 1: All zeros
        self.overwrite_pattern(data, 0x00, 1, 7, "Pass 1: zeros")?;

        // Pass 2: All ones
        self.overwrite_pattern(data, 0xFF, 2, 7, "Pass 2: ones")?;

        // Pass 3: Random
        self.overwrite_random(data, 3, 7, "Pass 3: random")?;

        // Pass 4: Zeros
        self.overwrite_pattern(data, 0x00, 4, 7, "Pass 4: zeros")?;

        // Pass 5: Ones
        self.overwrite_pattern(data, 0xFF, 5, 7, "Pass 5: ones")?;

        // Pass 6: Random
        self.overwrite_random(data, 6, 7, "Pass 6: random")?;

        // Pass 7: Random verify
        self.overwrite_random(data, 7, 7, "Pass 7: random verify")?;

        Ok(())
    }

    /// Gutmann 35-pass erasure.
    ///
    /// Implements Peter Gutmann's 35-pass secure deletion algorithm.
    fn gutmann_35_pass(&mut self, data: &mut [u8]) -> Result<(), FsError> {
        // Gutmann patterns (simplified - full implementation would include
        // all specific bit patterns for MFM/RLL encoding)
        let patterns: [(u8, u8, u8); 27] = [
            // Passes 5-31: Specific patterns
            (0x55, 0x55, 0x55), // Pass 5
            (0xAA, 0xAA, 0xAA), // Pass 6
            (0x92, 0x49, 0x24), // Pass 7
            (0x49, 0x24, 0x92), // Pass 8
            (0x24, 0x92, 0x49), // Pass 9
            (0x00, 0x00, 0x00), // Pass 10
            (0x11, 0x11, 0x11), // Pass 11
            (0x22, 0x22, 0x22), // Pass 12
            (0x33, 0x33, 0x33), // Pass 13
            (0x44, 0x44, 0x44), // Pass 14
            (0x55, 0x55, 0x55), // Pass 15
            (0x66, 0x66, 0x66), // Pass 16
            (0x77, 0x77, 0x77), // Pass 17
            (0x88, 0x88, 0x88), // Pass 18
            (0x99, 0x99, 0x99), // Pass 19
            (0xAA, 0xAA, 0xAA), // Pass 20
            (0xBB, 0xBB, 0xBB), // Pass 21
            (0xCC, 0xCC, 0xCC), // Pass 22
            (0xDD, 0xDD, 0xDD), // Pass 23
            (0xEE, 0xEE, 0xEE), // Pass 24
            (0xFF, 0xFF, 0xFF), // Pass 25
            (0x92, 0x49, 0x24), // Pass 26
            (0x49, 0x24, 0x92), // Pass 27
            (0x24, 0x92, 0x49), // Pass 28
            (0x6D, 0xB6, 0xDB), // Pass 29
            (0xB6, 0xDB, 0x6D), // Pass 30
            (0xDB, 0x6D, 0xB6), // Pass 31
        ];

        // Passes 1-4: Random
        for pass in 1..=4 {
            self.overwrite_random(data, pass, 35, &alloc::format!("Pass {}: random", pass))?;
        }

        // Passes 5-31: Specific patterns
        for (i, pattern) in patterns.iter().enumerate() {
            let pass = i + 5;
            self.overwrite_3byte_pattern(
                data,
                *pattern,
                pass,
                35,
                &alloc::format!("Pass {}: pattern", pass),
            )?;
        }

        // Passes 32-35: Random
        for pass in 32..=35 {
            self.overwrite_random(data, pass, 35, &alloc::format!("Pass {}: random", pass))?;
        }

        Ok(())
    }

    /// Single random pass.
    fn random_pass(&mut self, data: &mut [u8]) -> Result<(), FsError> {
        self.overwrite_random(data, 1, 1, "Writing random data")
    }

    /// NIST SP 800-88 Clear.
    fn nist_clear(&mut self, data: &mut [u8]) -> Result<(), FsError> {
        self.overwrite_pattern(data, 0x00, 1, 1, "NIST Clear: zeros")
    }

    /// NIST SP 800-88 Purge.
    fn nist_purge(&mut self, data: &mut [u8]) -> Result<(), FsError> {
        // Pattern 1: Zeros
        self.overwrite_pattern(data, 0x00, 1, 3, "NIST Purge: zeros")?;

        // Pattern 2: Ones
        self.overwrite_pattern(data, 0xFF, 2, 3, "NIST Purge: ones")?;

        // Pattern 3: Random + verify
        self.overwrite_random(data, 3, 3, "NIST Purge: random")?;

        Ok(())
    }

    /// Overwrite with single byte pattern.
    fn overwrite_pattern(
        &self,
        data: &mut [u8],
        pattern: u8,
        current_pass: usize,
        total_passes: usize,
        operation: &str,
    ) -> Result<(), FsError> {
        if self.is_cancelled() {
            return Err(FsError::ResourceBusy);
        }

        // Fill with pattern
        data.fill(pattern);

        // Report progress
        self.report_progress(EraseProgress {
            current_pass,
            total_passes,
            bytes_completed: data.len() as u64,
            bytes_total: data.len() as u64,
            eta_seconds: None,
            operation: String::from(operation),
            cancellable: true,
        });

        // Verify if enabled
        if self.verify_passes {
            for &byte in data.iter() {
                if byte != pattern {
                    return Err(FsError::Corruption {
                        block: 0,
                        details: "Verification failed after overwrite",
                    });
                }
            }
        }

        Ok(())
    }

    /// Overwrite with 3-byte repeating pattern.
    fn overwrite_3byte_pattern(
        &mut self,
        data: &mut [u8],
        pattern: (u8, u8, u8),
        current_pass: usize,
        total_passes: usize,
        operation: &str,
    ) -> Result<(), FsError> {
        if self.is_cancelled() {
            return Err(FsError::ResourceBusy);
        }

        // Fill with 3-byte pattern
        for (i, byte) in data.iter_mut().enumerate() {
            *byte = match i % 3 {
                0 => pattern.0,
                1 => pattern.1,
                _ => pattern.2,
            };
        }

        // Report progress
        self.report_progress(EraseProgress {
            current_pass,
            total_passes,
            bytes_completed: data.len() as u64,
            bytes_total: data.len() as u64,
            eta_seconds: None,
            operation: String::from(operation),
            cancellable: true,
        });

        Ok(())
    }

    /// Overwrite with random data.
    fn overwrite_random(
        &mut self,
        data: &mut [u8],
        current_pass: usize,
        total_passes: usize,
        operation: &str,
    ) -> Result<(), FsError> {
        if self.is_cancelled() {
            return Err(FsError::ResourceBusy);
        }

        // Fill with random data
        let rng = self.get_rng()?;
        rng.fill_bytes(data).map_err(|_| FsError::InvalidArgument {
            reason: "Failed to generate random data",
        })?;

        // Report progress
        self.report_progress(EraseProgress {
            current_pass,
            total_passes,
            bytes_completed: data.len() as u64,
            bytes_total: data.len() as u64,
            eta_seconds: None,
            operation: String::from(operation),
            cancellable: true,
        });

        Ok(())
    }
}

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

// ============================================================================
// Crypto Erase for Encrypted Volumes
// ============================================================================

/// Cryptographic erasure for encrypted data.
///
/// This is the most efficient method for encrypted volumes:
/// destroying the encryption key makes all data permanently unrecoverable.
pub struct CryptoEraser;

impl CryptoEraser {
    /// Securely destroy an encryption key.
    ///
    /// This function:
    /// 1. Overwrites the key memory with random data
    /// 2. Then overwrites with zeros
    /// 3. Issues memory barrier to prevent reordering
    ///
    /// After this, the encrypted data is permanently unrecoverable.
    pub fn destroy_key(key: &mut [u8]) {
        // First pass: random (if RNG available)
        if let Ok(mut rng) = CryptoRng::new() {
            let _ = rng.fill_bytes(key);
        } else {
            // Fallback: fill with 0x55 pattern
            key.fill(0x55);
        }

        // Memory barrier to ensure write completes
        core::sync::atomic::compiler_fence(Ordering::SeqCst);

        // Second pass: zeros
        key.fill(0x00);

        // Final barrier
        core::sync::atomic::compiler_fence(Ordering::SeqCst);
    }

    /// Destroy multiple keys atomically.
    ///
    /// Useful for cascaded encryption where multiple keys must be destroyed.
    pub fn destroy_keys(keys: &mut [&mut [u8]]) {
        for key in keys.iter_mut() {
            Self::destroy_key(key);
        }
    }
}

// ============================================================================
// ATA Secure Erase Commands
// ============================================================================

/// ATA Secure Erase command builder.
///
/// Note: Actual execution requires kernel driver support.
/// This provides the command structure for integration.
#[derive(Debug, Clone)]
pub struct AtaSecureEraseCommand {
    /// Whether to use enhanced secure erase.
    pub enhanced: bool,
    /// Master password (if set).
    pub master_password: Option<[u8; 32]>,
    /// Estimated time in minutes (from IDENTIFY).
    pub estimated_time_minutes: Option<u16>,
}

impl AtaSecureEraseCommand {
    /// Create standard secure erase command.
    pub fn standard() -> Self {
        Self {
            enhanced: false,
            master_password: None,
            estimated_time_minutes: None,
        }
    }

    /// Create enhanced secure erase command.
    pub fn enhanced() -> Self {
        Self {
            enhanced: true,
            master_password: None,
            estimated_time_minutes: None,
        }
    }

    /// Check if drive supports secure erase (from IDENTIFY word 128).
    ///
    /// Returns true if:
    /// - Bit 0 of word 128 is set (Security supported)
    /// - Bit 1 is not set (Security not enabled/locked)
    pub fn check_support(identify_word_128: u16) -> bool {
        (identify_word_128 & 0x0001) != 0 && (identify_word_128 & 0x0002) == 0
    }

    /// Get estimated erase time from IDENTIFY word 89/90.
    pub fn get_estimated_time(identify_word_89: u16, enhanced: bool) -> u16 {
        if enhanced {
            // Word 90 for enhanced
            identify_word_89
        } else {
            // Word 89 for standard
            identify_word_89
        }
    }
}

// ============================================================================
// NVMe Secure Erase Commands
// ============================================================================

/// NVMe Format command with secure erase.
#[derive(Debug, Clone)]
pub struct NvmeFormatCommand {
    /// Namespace ID (0xFFFFFFFF for all namespaces).
    pub nsid: u32,
    /// Secure Erase Settings (SES).
    pub ses: NvmeSecureEraseSetting,
    /// LBA format index.
    pub lbaf: u8,
    /// Protection information.
    pub pi: u8,
    /// Metadata settings.
    pub ms: u8,
}

/// NVMe Secure Erase Settings for Format command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NvmeSecureEraseSetting {
    /// No secure erase operation requested.
    NoSecureErase = 0,
    /// User Data Erase: All user data shall be erased.
    UserDataErase = 1,
    /// Cryptographic Erase: Encryption key destroyed.
    CryptographicErase = 2,
}

/// NVMe Sanitize command.
#[derive(Debug, Clone)]
pub struct NvmeSanitizeCommand {
    /// Sanitize action.
    pub action: NvmeSanitizeAction,
    /// Allow Unrestricted Sanitize Exit.
    pub ause: bool,
    /// Overwrite Pass Count (1-16 for overwrite action).
    pub owpass: u8,
    /// Overwrite Invert Pattern Between Passes.
    pub oipbp: bool,
    /// No Deallocate After Sanitize.
    pub ndas: bool,
    /// Overwrite pattern (32-bit).
    pub overwrite_pattern: u32,
}

/// NVMe Sanitize action types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NvmeSanitizeAction {
    /// Exit failure mode (no sanitize operation).
    ExitFailureMode = 1,
    /// Block Erase sanitize operation.
    BlockErase = 2,
    /// Overwrite sanitize operation.
    Overwrite = 3,
    /// Crypto Erase sanitize operation.
    CryptoErase = 4,
}

impl NvmeSanitizeCommand {
    /// Create block erase sanitize command.
    pub fn block_erase() -> Self {
        Self {
            action: NvmeSanitizeAction::BlockErase,
            ause: false,
            owpass: 0,
            oipbp: false,
            ndas: false,
            overwrite_pattern: 0,
        }
    }

    /// Create crypto erase sanitize command.
    pub fn crypto_erase() -> Self {
        Self {
            action: NvmeSanitizeAction::CryptoErase,
            ause: false,
            owpass: 0,
            oipbp: false,
            ndas: false,
            overwrite_pattern: 0,
        }
    }

    /// Create overwrite sanitize command with specified passes.
    pub fn overwrite(passes: u8, pattern: u32, invert: bool) -> Self {
        Self {
            action: NvmeSanitizeAction::Overwrite,
            ause: false,
            owpass: passes.clamp(1, 16),
            oipbp: invert,
            ndas: false,
            overwrite_pattern: pattern,
        }
    }
}

// ============================================================================
// Verification
// ============================================================================

/// Verify that data has been securely erased.
///
/// Performs random sampling to check that data has been properly overwritten.
pub struct EraseVerifier {
    /// Number of random samples to check.
    sample_count: usize,
    /// Random number generator.
    rng: Option<CryptoRng>,
}

impl EraseVerifier {
    /// Create new verifier with specified sample count.
    pub fn new(sample_count: usize) -> Self {
        Self {
            sample_count: sample_count.max(10),
            rng: CryptoRng::new().ok(),
        }
    }

    /// Get a random index for sampling.
    fn random_index(&mut self, max: usize) -> usize {
        if let Some(ref mut rng) = self.rng {
            if let Ok(val) = rng.next_u64() {
                return (val as usize) % max;
            }
        }
        // Fallback: use a simple counter-based approach
        static mut COUNTER: usize = 0;
        // SAFETY: This is only used for verification sampling, not security-critical
        unsafe {
            COUNTER = COUNTER.wrapping_add(7919); // Prime for better distribution
            COUNTER % max
        }
    }

    /// Verify that buffer contains no recoverable data.
    ///
    /// Checks that the buffer matches the expected pattern or is random.
    pub fn verify_pattern(&mut self, data: &[u8], expected: u8) -> bool {
        if data.is_empty() {
            return true;
        }

        // Random sample verification
        for _ in 0..self.sample_count {
            let index = self.random_index(data.len());
            if data[index] != expected {
                return false;
            }
        }

        true
    }

    /// Verify that buffer contains non-zero data (was overwritten).
    pub fn verify_not_zero(&mut self, data: &[u8]) -> bool {
        if data.is_empty() {
            return true;
        }

        // At least some samples should be non-zero after random overwrite
        let mut non_zero_count = 0;
        for _ in 0..self.sample_count {
            let index = self.random_index(data.len());
            if data[index] != 0 {
                non_zero_count += 1;
            }
        }

        // Expect at least 90% non-zero for random data
        non_zero_count > self.sample_count * 9 / 10
    }
}

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

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

    #[test]
    fn test_wipe_method_pass_count() {
        assert_eq!(WipeMethod::Dod3Pass.pass_count(), Some(3));
        assert_eq!(WipeMethod::Dod7Pass.pass_count(), Some(7));
        assert_eq!(WipeMethod::Gutmann.pass_count(), Some(35));
        assert_eq!(WipeMethod::CryptoErase.pass_count(), Some(0));
        assert_eq!(WipeMethod::AtaSecureErase.pass_count(), None);
        assert_eq!(WipeMethod::NvmeFormat.pass_count(), None);
    }

    #[test]
    fn test_wipe_method_hardware_requirement() {
        assert!(!WipeMethod::Dod3Pass.requires_hardware());
        assert!(!WipeMethod::Gutmann.requires_hardware());
        assert!(WipeMethod::AtaSecureErase.requires_hardware());
        assert!(WipeMethod::NvmeFormat.requires_hardware());
    }

    #[test]
    fn test_wipe_method_ssd_suitability() {
        assert!(WipeMethod::CryptoErase.suitable_for_ssd());
        assert!(WipeMethod::NvmeFormat.suitable_for_ssd());
        assert!(!WipeMethod::Dod3Pass.suitable_for_ssd());
        assert!(!WipeMethod::Gutmann.suitable_for_ssd());
    }

    #[test]
    fn test_secure_eraser_dod_3_pass() {
        let mut eraser = SecureEraser::new();
        let mut data = vec![0xAA; 1024];

        let result = eraser.erase_buffer(&mut data, WipeMethod::Dod3Pass);
        assert!(result.is_ok());

        // After DoD 3-pass, data should be random (not zeros or 0xAA)
        // Can't verify exact content since last pass is random
    }

    #[test]
    fn test_crypto_eraser() {
        let mut key = [0x42u8; 32];
        CryptoEraser::destroy_key(&mut key);

        // Key should be zeroed
        assert_eq!(key, [0u8; 32]);
    }

    #[test]
    fn test_progress_percentage() {
        let progress = EraseProgress {
            current_pass: 2,
            total_passes: 4,
            bytes_completed: 500,
            bytes_total: 1000,
            eta_seconds: None,
            operation: String::from("Test"),
            cancellable: true,
        };

        // Pass 1 complete (25%) + half of pass 2 (12.5%) = 37.5%
        let pct = progress.percentage();
        assert!(pct > 37.0 && pct < 38.0);
    }
}