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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// AES-NI Inline Encryption
// Hardware-accelerated encryption using CPU AES-NI instructions.

use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Key, Nonce as AesNonce};
use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use spin::Mutex;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::FsError;
use crate::arch;

/// Encryption algorithm
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EncryptAlgo {
    /// ChaCha20-Poly1305 (software, fast)
    ChaCha20Poly1305,
    /// AES-256-GCM (AES-NI hardware accelerated)
    Aes256Gcm,
}

/// CPU features for encryption
#[derive(Debug, Clone)]
pub struct CpuFeatures {
    /// Supports AES-NI instructions
    pub aes_ni: bool,
    /// Supports PCLMULQDQ (for GCM)
    pub pclmulqdq: bool,
    /// Supports AVX2
    pub avx2: bool,
    /// Supports AVX-512
    pub avx512: bool,
}

impl CpuFeatures {
    /// Create new CPU features (simulated detection)
    pub fn detect() -> Self {
        // In real implementation, would use CPUID instruction
        Self {
            aes_ni: true, // Assume modern CPU
            pclmulqdq: true,
            avx2: true,
            avx512: false, // Not universal yet
        }
    }

    /// Check if algorithm can be hardware accelerated
    pub fn supports_algo(&self, algo: EncryptAlgo) -> bool {
        match algo {
            EncryptAlgo::ChaCha20Poly1305 => true, // Software implementation always available
            EncryptAlgo::Aes256Gcm => self.aes_ni && self.pclmulqdq,
        }
    }

    /// Get hardware acceleration status
    pub fn is_accelerated(&self, algo: EncryptAlgo) -> bool {
        match algo {
            EncryptAlgo::ChaCha20Poly1305 => self.avx2, // AVX2 can accelerate ChaCha20
            EncryptAlgo::Aes256Gcm => self.aes_ni && self.pclmulqdq,
        }
    }
}

/// Encryption key (256-bit)
///
/// # Security
///
/// This struct automatically zeroizes the key material when dropped,
/// preventing sensitive data from remaining in memory.
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct EncryptionKey {
    /// Key bytes (automatically zeroized on drop)
    pub key: [u8; 32],
    /// Algorithm (not sensitive, skip zeroization)
    #[zeroize(skip)]
    pub algo: EncryptAlgo,
    /// Key ID (not sensitive, skip zeroization)
    #[zeroize(skip)]
    pub key_id: u64,
}

impl EncryptionKey {
    /// Create new encryption key
    pub fn new(key: [u8; 32], algo: EncryptAlgo, key_id: u64) -> Self {
        Self { key, algo, key_id }
    }

    /// Generate random key using CSPRNG
    pub fn generate(
        algo: EncryptAlgo,
        key_id: u64,
    ) -> Result<Self, crate::crypto::random::RandomError> {
        let key = crate::crypto::random::generate_key()?;
        Ok(Self::new(key, algo, key_id))
    }
}

/// Nonce (96-bit for both ChaCha20 and AES-GCM)
#[derive(Debug, Clone, Copy)]
pub struct Nonce {
    /// Nonce bytes
    pub bytes: [u8; 12],
}

impl Nonce {
    /// Create new nonce
    pub fn new(bytes: [u8; 12]) -> Self {
        Self { bytes }
    }

    /// Generate from counter
    pub fn from_counter(counter: u64) -> Self {
        let mut bytes = [0u8; 12];
        bytes[0..8].copy_from_slice(&counter.to_le_bytes());
        Self { bytes }
    }

    /// Increment nonce (for sequential operations)
    pub fn increment(&mut self) {
        // SAFETY INVARIANT: Nonce is 12 bytes; slicing [0..8] always yields 8 bytes.
        // Compile-time guarantee: self.bytes is [u8; 12], so [0..8] always valid.
        let counter_bytes: [u8; 8] = [
            self.bytes[0],
            self.bytes[1],
            self.bytes[2],
            self.bytes[3],
            self.bytes[4],
            self.bytes[5],
            self.bytes[6],
            self.bytes[7],
        ];
        let mut counter = u64::from_le_bytes(counter_bytes);
        counter += 1;
        self.bytes[0..8].copy_from_slice(&counter.to_le_bytes());
    }
}

/// Encryption operation
#[derive(Debug, Clone)]
pub struct EncryptOp {
    /// Operation ID
    pub op_id: u64,
    /// Algorithm
    pub algo: EncryptAlgo,
    /// Key ID
    pub key_id: u64,
    /// Input size
    pub input_size: u64,
    /// Hardware accelerated
    pub hw_accelerated: bool,
    /// Submitted timestamp
    pub submitted: u64,
}

/// Encryption result
#[derive(Debug, Clone)]
pub struct EncryptResult {
    /// Operation ID
    pub op_id: u64,
    /// Output size (input + tag)
    pub output_size: u64,
    /// Nonce used
    pub nonce: Nonce,
    /// Execution time (nanoseconds)
    pub exec_time_ns: u64,
    /// Hardware accelerated
    pub hw_accelerated: bool,
}

impl EncryptResult {
    /// Calculate throughput in GB/s
    pub fn throughput_gbps(&self, input_size: u64) -> f32 {
        if self.exec_time_ns == 0 {
            return 0.0;
        }
        // GB/s = bytes / (nanoseconds / 1e9) / 1e9
        (input_size as f64 / (self.exec_time_ns as f64 / 1e9) / 1e9) as f32
    }

    /// Calculate cycles per byte (assuming 3 GHz CPU)
    pub fn cycles_per_byte(&self, input_size: u64) -> f32 {
        if input_size == 0 {
            return 0.0;
        }
        let cpu_freq_ghz = 3.0; // 3 GHz
        let cycles = (self.exec_time_ns as f64 / 1e9) * cpu_freq_ghz * 1e9;
        cycles as f32 / input_size as f32
    }
}

/// Encryption statistics
#[derive(Debug, Clone, Default)]
pub struct EncryptStats {
    /// Total operations
    pub total_ops: u64,
    /// Hardware accelerated operations
    pub hw_accel_ops: u64,
    /// Software operations
    pub sw_ops: u64,
    /// Total bytes encrypted
    pub total_bytes: u64,
    /// Total execution time (nanoseconds)
    pub total_time_ns: u64,
}

impl EncryptStats {
    /// Calculate hardware acceleration ratio
    pub fn hw_accel_ratio(&self) -> f32 {
        if self.total_ops == 0 {
            return 0.0;
        }
        self.hw_accel_ops as f32 / self.total_ops as f32
    }

    /// Calculate average throughput (GB/s)
    pub fn avg_throughput_gbps(&self) -> f32 {
        if self.total_time_ns == 0 {
            return 0.0;
        }
        (self.total_bytes as f64 / (self.total_time_ns as f64 / 1e9) / 1e9) as f32
    }

    /// Calculate average cycles per byte
    pub fn avg_cycles_per_byte(&self) -> f32 {
        if self.total_bytes == 0 {
            return 0.0;
        }
        let cpu_freq_ghz = 3.0;
        let total_cycles = (self.total_time_ns as f64 / 1e9) * cpu_freq_ghz * 1e9;
        total_cycles as f32 / self.total_bytes as f32
    }
}

/// Inline encryption manager
pub struct InlineEncryptManager {
    /// CPU features
    features: CpuFeatures,
    /// Encryption keys
    keys: BTreeMap<u64, EncryptionKey>,
    /// Nonce counter
    nonce_counter: u64,
    /// Next operation ID
    next_op_id: u64,
    /// Statistics
    stats: EncryptStats,
}

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

impl InlineEncryptManager {
    /// Create new inline encryption manager
    pub fn new() -> Self {
        Self {
            features: CpuFeatures::detect(),
            keys: BTreeMap::new(),
            nonce_counter: 1,
            next_op_id: 1,
            stats: EncryptStats::default(),
        }
    }

    /// Add encryption key
    pub fn add_key(&mut self, key: EncryptionKey) -> Result<(), &'static str> {
        if !self.features.supports_algo(key.algo) {
            return Err("Algorithm not supported by CPU");
        }
        self.keys.insert(key.key_id, key);
        Ok(())
    }

    /// Remove encryption key
    pub fn remove_key(&mut self, key_id: u64) -> bool {
        self.keys.remove(&key_id).is_some()
    }

    /// Encrypt data (simulated)
    pub fn encrypt(
        &mut self,
        key_id: u64,
        input_size: u64,
        timestamp: u64,
    ) -> Result<EncryptResult, &'static str> {
        let key = self.keys.get(&key_id).ok_or("Key not found")?;

        // Check if hardware accelerated
        let hw_accelerated = self.features.is_accelerated(key.algo);

        // Generate nonce
        let nonce = Nonce::from_counter(self.nonce_counter);
        self.nonce_counter += 1;

        // Simulate encryption performance
        let exec_time_ns = if hw_accelerated {
            // AES-NI: ~0.63 cycles/byte at 3 GHz = ~4.76 GB/s
            // ChaCha20 with AVX2: ~1.2 cycles/byte = ~2.5 GB/s
            match key.algo {
                EncryptAlgo::Aes256Gcm => (input_size as f64 * 0.63 / 3.0) as u64, // 0.63 cycles/byte
                EncryptAlgo::ChaCha20Poly1305 => (input_size as f64 * 1.2 / 3.0) as u64, // 1.2 cycles/byte
            }
        } else {
            // Software: ~5-10 cycles/byte
            (input_size as f64 * 7.0 / 3.0) as u64
        };

        let op_id = self.next_op_id;
        self.next_op_id += 1;

        // Update statistics
        self.stats.total_ops += 1;
        if hw_accelerated {
            self.stats.hw_accel_ops += 1;
        } else {
            self.stats.sw_ops += 1;
        }
        self.stats.total_bytes += input_size;
        self.stats.total_time_ns += exec_time_ns;

        Ok(EncryptResult {
            op_id,
            output_size: input_size + 16, // Add 16-byte auth tag
            nonce,
            exec_time_ns,
            hw_accelerated,
        })
    }

    /// Decrypt data (simulated)
    pub fn decrypt(
        &mut self,
        key_id: u64,
        input_size: u64,
        _nonce: Nonce,
        timestamp: u64,
    ) -> Result<EncryptResult, &'static str> {
        // Decryption has same performance as encryption
        self.encrypt(key_id, input_size - 16, timestamp) // Subtract tag size
    }

    /// Get statistics
    pub fn stats(&self) -> EncryptStats {
        self.stats.clone()
    }

    /// Get CPU features
    pub fn features(&self) -> &CpuFeatures {
        &self.features
    }

    /// Get key
    pub fn get_key(&self, key_id: u64) -> Option<&EncryptionKey> {
        self.keys.get(&key_id)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// GLOBAL INLINE ENCRYPTION ENGINE
// ═══════════════════════════════════════════════════════════════════════════════

lazy_static! {
    static ref INLINE_ENCRYPT_ENGINE: Mutex<InlineEncryptManager> =
        Mutex::new(InlineEncryptManager::new());
}

/// Global inline encryption engine API
pub struct InlineEncryptEngine;

impl InlineEncryptEngine {
    /// Add encryption key
    pub fn add_key(key: EncryptionKey) -> Result<(), &'static str> {
        let mut engine = INLINE_ENCRYPT_ENGINE.lock();
        engine.add_key(key)
    }

    /// Remove encryption key
    pub fn remove_key(key_id: u64) -> bool {
        let mut engine = INLINE_ENCRYPT_ENGINE.lock();
        engine.remove_key(key_id)
    }

    /// Encrypt data
    pub fn encrypt(
        key_id: u64,
        input_size: u64,
        timestamp: u64,
    ) -> Result<EncryptResult, &'static str> {
        let mut engine = INLINE_ENCRYPT_ENGINE.lock();
        engine.encrypt(key_id, input_size, timestamp)
    }

    /// Decrypt data
    pub fn decrypt(
        key_id: u64,
        input_size: u64,
        nonce: Nonce,
        timestamp: u64,
    ) -> Result<EncryptResult, &'static str> {
        let mut engine = INLINE_ENCRYPT_ENGINE.lock();
        engine.decrypt(key_id, input_size, nonce, timestamp)
    }

    /// Get statistics
    pub fn stats() -> EncryptStats {
        let engine = INLINE_ENCRYPT_ENGINE.lock();
        engine.stats()
    }

    /// Get CPU features
    pub fn features() -> CpuFeatures {
        let engine = INLINE_ENCRYPT_ENGINE.lock();
        engine.features().clone()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// REAL AES-256-GCM ENCRYPTION FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Size of AES-256-GCM key in bytes (256 bits).
pub const AES_KEY_SIZE: usize = 32;

/// Size of AES-GCM nonce in bytes (96 bits).
pub const AES_NONCE_SIZE: usize = 12;

/// Size of GCM authentication tag in bytes (128 bits).
pub const AES_TAG_SIZE: usize = 16;

/// Check if AES-NI hardware acceleration is available.
///
/// Returns `true` if the CPU supports AES-NI instructions for
/// hardware-accelerated AES encryption/decryption.
///
/// # Platform Support
///
/// - **x86_64**: Checks CPUID for AES-NI support (bit 25 of ECX)
/// - **AArch64**: Checks for ARMv8 Cryptographic Extension
/// - **Other**: Returns `false`
#[inline]
pub fn has_aesni() -> bool {
    arch::has_aesni()
}

/// Encrypt data using AES-256-GCM with hardware acceleration.
///
/// This function uses the CPU's AES-NI instructions (or ARM Crypto Extension)
/// for high-performance authenticated encryption.
///
/// # Arguments
///
/// * `data` - Plaintext data to encrypt
/// * `key` - 32-byte AES-256 key
///
/// # Returns
///
/// On success, returns `Vec<u8>` containing:
/// - Bytes 0..12: Random nonce
/// - Bytes 12..N: Ciphertext with authentication tag (16 bytes longer than plaintext)
///
/// Total output length: `AES_NONCE_SIZE + data.len() + AES_TAG_SIZE` (28 bytes overhead)
///
/// # Errors
///
/// - `FsError::InvalidArgument` - Key is not 32 bytes
/// - `FsError::EncryptionFailed` - Encryption failed or AES-NI unavailable
///
/// # Performance
///
/// With AES-NI: ~4.76 GB/s (0.63 cycles/byte at 3 GHz)
/// Without AES-NI: Falls back to software implementation (~1-2 GB/s)
///
/// # Example
///
/// ```rust,ignore
/// use lcpfs::lcpfs_aesni::{aesni_encrypt, aesni_decrypt, has_aesni};
///
/// if has_aesni() {
///     let key = [0x42u8; 32];
///     let plaintext = b"Hello, AES-NI!";
///
///     let ciphertext = aesni_encrypt(plaintext, &key).unwrap();
///     let decrypted = aesni_decrypt(&ciphertext, &key).unwrap();
///
///     assert_eq!(decrypted, plaintext);
/// }
/// ```
pub fn aesni_encrypt(data: &[u8], key: &[u8]) -> Result<Vec<u8>, FsError> {
    // Validate key length
    if key.len() != AES_KEY_SIZE {
        return Err(FsError::InvalidArgument {
            reason: "AES-256 key must be 32 bytes",
        });
    }

    // Create cipher instance
    let cipher_key = Key::<Aes256Gcm>::from_slice(key);
    let cipher = Aes256Gcm::new(cipher_key);

    // Generate random nonce using hardware entropy
    let mut nonce_bytes = [0u8; AES_NONCE_SIZE];
    fill_hardware_entropy(&mut nonce_bytes)?;
    let nonce = AesNonce::from_slice(&nonce_bytes);

    // Encrypt with authenticated encryption
    let ciphertext = cipher
        .encrypt(nonce, data)
        .map_err(|_| FsError::EncryptionFailed)?;

    // Prepend nonce to ciphertext for stateless decryption
    let mut result = Vec::with_capacity(AES_NONCE_SIZE + ciphertext.len());
    result.extend_from_slice(&nonce_bytes);
    result.extend_from_slice(&ciphertext);

    Ok(result)
}

/// Decrypt data using AES-256-GCM with hardware acceleration.
///
/// This function verifies the authentication tag before returning plaintext.
/// If the ciphertext has been tampered with, decryption will fail.
///
/// # Arguments
///
/// * `data` - Ciphertext from [`aesni_encrypt`], including prepended nonce
/// * `key` - 32-byte AES-256 key (must match encryption key)
///
/// # Returns
///
/// On success, returns `Vec<u8>` containing the original plaintext.
///
/// # Errors
///
/// - `FsError::InvalidArgument` - Key is not 32 bytes or data is too short
/// - `FsError::DecryptionFailed` - Authentication failed (wrong key or tampering)
///
/// # Security
///
/// - Constant-time authentication tag verification (via GHASH)
/// - Fails fast if ciphertext is too short
pub fn aesni_decrypt(data: &[u8], key: &[u8]) -> Result<Vec<u8>, FsError> {
    // Validate key length
    if key.len() != AES_KEY_SIZE {
        return Err(FsError::InvalidArgument {
            reason: "AES-256 key must be 32 bytes",
        });
    }

    // Minimum ciphertext length: nonce (12) + tag (16) = 28 bytes
    if data.len() < AES_NONCE_SIZE + AES_TAG_SIZE {
        return Err(FsError::InvalidArgument {
            reason: "ciphertext too short (minimum 28 bytes)",
        });
    }

    // Extract nonce from prepended bytes
    let nonce = AesNonce::from_slice(&data[..AES_NONCE_SIZE]);
    let ciphertext = &data[AES_NONCE_SIZE..];

    // Create cipher instance
    let cipher_key = Key::<Aes256Gcm>::from_slice(key);
    let cipher = Aes256Gcm::new(cipher_key);

    // Decrypt and verify authentication tag
    let plaintext = cipher
        .decrypt(nonce, ciphertext)
        .map_err(|_| FsError::DecryptionFailed)?;

    Ok(plaintext)
}

/// Fill buffer with hardware entropy for nonce generation.
fn fill_hardware_entropy(buf: &mut [u8]) -> Result<(), FsError> {
    // Try hardware entropy first
    if arch::has_rdrand() && arch::fill_hardware_entropy(buf).is_ok() {
        return Ok(());
    }

    // Fallback to lcpfs_random module
    crate::crypto::random::fill_random(buf).map_err(|_| FsError::EncryptionFailed)
}

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

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

    #[test]
    fn test_cpu_features() {
        let features = CpuFeatures::detect();
        assert!(features.aes_ni);
        assert!(features.pclmulqdq);
        assert!(features.supports_algo(EncryptAlgo::Aes256Gcm));
        assert!(features.supports_algo(EncryptAlgo::ChaCha20Poly1305));
    }

    #[test]
    fn test_key_management() {
        let mut mgr = InlineEncryptManager::new();
        let key = EncryptionKey::generate(EncryptAlgo::Aes256Gcm, 1)
            .expect("test: operation should succeed");

        mgr.add_key(key.clone())
            .expect("test: operation should succeed");
        assert!(mgr.get_key(1).is_some());

        assert!(mgr.remove_key(1));
        assert!(mgr.get_key(1).is_none());
    }

    #[test]
    fn test_nonce_generation() {
        let nonce1 = Nonce::from_counter(1);
        let nonce2 = Nonce::from_counter(2);
        assert_ne!(nonce1.bytes, nonce2.bytes);

        let mut nonce = Nonce::from_counter(100);
        nonce.increment();
        let expected = Nonce::from_counter(101);
        assert_eq!(nonce.bytes, expected.bytes);
    }

    #[test]
    fn test_encrypt_aes_gcm() {
        let mut mgr = InlineEncryptManager::new();
        let key = EncryptionKey::generate(EncryptAlgo::Aes256Gcm, 1)
            .expect("test: operation should succeed");
        mgr.add_key(key).expect("test: operation should succeed");

        let result = mgr
            .encrypt(1, 1_000_000, 0)
            .expect("test: operation should succeed");
        assert_eq!(result.output_size, 1_000_016); // Input + 16-byte tag
        assert!(result.hw_accelerated); // AES-NI available
        assert!(result.exec_time_ns > 0);
    }

    #[test]
    fn test_encrypt_chacha20() {
        let mut mgr = InlineEncryptManager::new();
        let key = EncryptionKey::generate(EncryptAlgo::ChaCha20Poly1305, 1)
            .expect("test: operation should succeed");
        mgr.add_key(key).expect("test: operation should succeed");

        let result = mgr
            .encrypt(1, 1_000_000, 0)
            .expect("test: operation should succeed");
        assert_eq!(result.output_size, 1_000_016);
        assert!(result.hw_accelerated); // AVX2 available
    }

    #[test]
    fn test_decrypt() {
        let mut mgr = InlineEncryptManager::new();
        let key = EncryptionKey::generate(EncryptAlgo::Aes256Gcm, 1)
            .expect("test: operation should succeed");
        mgr.add_key(key).expect("test: operation should succeed");

        let enc_result = mgr
            .encrypt(1, 1_000_000, 0)
            .expect("test: operation should succeed");
        let dec_result = mgr
            .decrypt(1, enc_result.output_size, enc_result.nonce, 0)
            .expect("test: operation should succeed");

        assert_eq!(dec_result.output_size, enc_result.output_size);
    }

    #[test]
    fn test_throughput_calculation() {
        let result = EncryptResult {
            op_id: 1,
            output_size: 1_000_016,
            nonce: Nonce::from_counter(1),
            exec_time_ns: 210_000, // 210 microseconds for 1MB = ~4.76 GB/s
            hw_accelerated: true,
        };

        let throughput = result.throughput_gbps(1_000_000);
        // Expected: ~4.76 GB/s for AES-GCM with AES-NI
        assert!(throughput > 4.0 && throughput < 6.0);
    }

    #[test]
    fn test_cycles_per_byte() {
        let result = EncryptResult {
            op_id: 1,
            output_size: 1_000_016,
            nonce: Nonce::from_counter(1),
            exec_time_ns: 210_000,
            hw_accelerated: true,
        };

        let cpb = result.cycles_per_byte(1_000_000);
        // Expected: ~0.63 cycles/byte for AES-GCM
        assert!(cpb > 0.5 && cpb < 1.0);
    }

    #[test]
    fn test_statistics() {
        let mut mgr = InlineEncryptManager::new();
        let key = EncryptionKey::generate(EncryptAlgo::Aes256Gcm, 1)
            .expect("test: operation should succeed");
        mgr.add_key(key).expect("test: operation should succeed");

        // Encrypt 10 blocks
        for _ in 0..10 {
            mgr.encrypt(1, 1_000_000, 0)
                .expect("test: operation should succeed");
        }

        let stats = mgr.stats();
        assert_eq!(stats.total_ops, 10);
        assert_eq!(stats.hw_accel_ops, 10);
        assert_eq!(stats.total_bytes, 10_000_000);
        assert!(stats.avg_throughput_gbps() > 4.0);
    }

    #[test]
    fn test_hw_accel_ratio() {
        let mut stats = EncryptStats::default();
        stats.total_ops = 100;
        stats.hw_accel_ops = 80;
        stats.sw_ops = 20;

        assert_eq!(stats.hw_accel_ratio(), 0.8);
    }

    #[test]
    fn test_key_not_found() {
        let mut mgr = InlineEncryptManager::new();
        let result = mgr.encrypt(999, 1000, 0);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Key not found");
    }

    // ───────────────────────────────────────────────────────────────────────────
    // REAL AES-256-GCM ENCRYPTION TESTS
    // ───────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_aesni_encrypt_actually_encrypts() {
        let plaintext = b"secret data that must be encrypted with AES-NI";
        let key = [0u8; 32];

        let ciphertext = aesni_encrypt(plaintext, &key).unwrap();

        // Ciphertext must NOT equal plaintext
        assert_ne!(
            &ciphertext[AES_NONCE_SIZE..],
            plaintext.as_slice(),
            "AES encryption must change data!"
        );

        // Must be longer: nonce (12) + plaintext + tag (16)
        assert_eq!(
            ciphertext.len(),
            AES_NONCE_SIZE + plaintext.len() + AES_TAG_SIZE,
            "Ciphertext should be plaintext + 28 bytes overhead"
        );
    }

    #[test]
    fn test_aesni_encrypt_produces_different_ciphertext_each_time() {
        let plaintext = b"same plaintext";
        let key = [0x42u8; 32];

        let ciphertext1 = aesni_encrypt(plaintext, &key).unwrap();
        let ciphertext2 = aesni_encrypt(plaintext, &key).unwrap();

        // Different nonces should produce different ciphertext
        assert_ne!(
            ciphertext1, ciphertext2,
            "Same plaintext should produce different ciphertext due to random nonce"
        );
    }

    #[test]
    fn test_aesni_decrypt_reverses_encrypt() {
        let plaintext = b"secret data to round-trip through AES-GCM";
        let key = [0x42u8; 32];

        let ciphertext = aesni_encrypt(plaintext, &key).unwrap();
        let decrypted = aesni_decrypt(&ciphertext, &key).unwrap();

        assert_eq!(
            decrypted.as_slice(),
            plaintext.as_slice(),
            "AES decryption must recover original plaintext"
        );
    }

    #[test]
    fn test_aesni_decrypt_with_wrong_key_fails() {
        let plaintext = b"secret";
        let key1 = [0x42u8; 32];
        let key2 = [0x43u8; 32];

        let ciphertext = aesni_encrypt(plaintext, &key1).unwrap();

        // Wrong key should fail authentication
        assert!(
            matches!(
                aesni_decrypt(&ciphertext, &key2),
                Err(FsError::DecryptionFailed)
            ),
            "AES decryption with wrong key must fail"
        );
    }

    #[test]
    fn test_aesni_decrypt_tampered_ciphertext_fails() {
        let plaintext = b"secret";
        let key = [0u8; 32];

        let mut ciphertext = aesni_encrypt(plaintext, &key).unwrap();

        // Tamper with ciphertext
        ciphertext[AES_NONCE_SIZE + 1] ^= 0xFF;

        // Tampered ciphertext should fail authentication
        assert!(
            matches!(
                aesni_decrypt(&ciphertext, &key),
                Err(FsError::DecryptionFailed)
            ),
            "Tampered AES ciphertext must fail authentication"
        );
    }

    #[test]
    fn test_aesni_invalid_key_length() {
        let plaintext = b"test";

        // Too short
        assert!(matches!(
            aesni_encrypt(plaintext, &[0u8; 16]),
            Err(FsError::InvalidArgument { .. })
        ));

        // Too long
        assert!(matches!(
            aesni_encrypt(plaintext, &[0u8; 64]),
            Err(FsError::InvalidArgument { .. })
        ));
    }

    #[test]
    fn test_aesni_ciphertext_too_short() {
        let key = [0u8; 32];

        // Less than minimum (nonce + tag = 28 bytes)
        assert!(matches!(
            aesni_decrypt(&[0u8; 27], &key),
            Err(FsError::InvalidArgument { .. })
        ));

        // Empty
        assert!(matches!(
            aesni_decrypt(&[], &key),
            Err(FsError::InvalidArgument { .. })
        ));
    }

    #[test]
    fn test_aesni_encrypt_decrypt_empty_plaintext() {
        let plaintext = b"";
        let key = [0x42u8; 32];

        let ciphertext = aesni_encrypt(plaintext, &key).unwrap();

        // Should be exactly nonce + tag (no data)
        assert_eq!(ciphertext.len(), AES_NONCE_SIZE + AES_TAG_SIZE);

        let decrypted = aesni_decrypt(&ciphertext, &key).unwrap();
        assert!(decrypted.is_empty());
    }

    #[test]
    fn test_aesni_encrypt_decrypt_large_data() {
        let plaintext = alloc::vec![0xAB_u8; 1024 * 1024]; // 1 MiB
        let key = [0x42u8; 32];

        let ciphertext = aesni_encrypt(&plaintext, &key).unwrap();
        let decrypted = aesni_decrypt(&ciphertext, &key).unwrap();

        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_has_aesni_returns_bool() {
        // Just verify it runs without panicking and returns a boolean
        let result = has_aesni();
        // On most modern x86_64 CPUs, this should be true
        // But we don't assert it because it depends on hardware
        let _ = result;
    }
}