nist-rand 0.1.0

A high-assurance, FIPS 140-3 and NIST SP 800-90A/B/C compliant Cryptographically Secure Pseudorandom Number Generator (CSPRNG) with multi-source entropy blending.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! # SP 800-90B/C Entropy Conditioning Pipeline
//!
//! This module implements the multi-source entropy gathering and conditioning
//! stage required by **NIST SP 800-90C** before instantiating a DRBG.
//!
//! ## Source Hierarchy
//!
//! | Layer | Source | Feature gate | Always active |
//! |-------|--------|-------------|---------------|
//! | Primary   | OS RNG (`/dev/urandom`) + SP 800-90B health tests | — | ✓ |
//! | Secondary | CPU timing jitter (Galois LFSR + Von Neumann unbiasing) | `advance` | |
//! | Tertiary  | System state (`/proc/*`, TSC, PID, stack/heap pointers) | `advance` | |
//! | Quaternary| AVX-256 SIMD thermal / frequency-scaling jitter | `exp_simd_rng` | |
//! | Quinary   | OS networking-stack latency (UDP round-trip timing) | `exp_network_rng` | |
//! | Senary    | Hardware RNG (`rdrand` / `rdseed`) instructions | `advance` | |
//!
//! All sources are **blended through SHA3-512** before being passed to the
//! DRBG.  This satisfies the SP 800-90C multi-source combining rule: even if
//! one source is fully compromised, the remaining independent sources prevent
//! the final seed from being predictable.
//!
//! ## FIPS Compliance Note
//!
//! SHA3-512 (FIPS 202) is an approved conditioning function.  Using it here
//! is fully compliant with both FIPS 140-3 and SP 800-90C § 4.1.

#[cfg(feature = "advance")]
use crate::rng::HealthTests;
use crate::rng::OsRng;
use sha3::{Digest, Sha3_512};

#[cfg(feature = "advance")]
use std::fs::File;
#[cfg(feature = "advance")]
use std::io::Read;
#[cfg(feature = "exp_network_rng")]
use std::net::UdpSocket;
#[cfg(feature = "advance")]
use std::process;
#[cfg(feature = "advance")]
use std::thread;
#[cfg(feature = "advance")]
use std::time::{Instant, SystemTime};

#[cfg(feature = "zeroize")]
use zeroize::Zeroizing;

// x86 / x86_64 RDTSC intrinsic
#[cfg(target_arch = "x86")]
use std::arch::x86::_rdtsc;
#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::_rdtsc;

// ────────────────────────────────────────────────────────────────────────────────
// Build-time & version separators (advance feature only)
// ────────────────────────────────────────────────────────────────────────────────

/// A 64-byte random value generated at compile time (written by `build.rs`).
/// Ensures that two binaries built from the same source at different times
/// produce distinct initial seeds even before any runtime entropy is gathered.
#[cfg(all(feature = "build_separator", feature = "advance"))]
const BUILD_SEPARATOR: &[u8; 64] =
    include_bytes!(concat!(env!("OUT_DIR"), "/build_separator.bin"));

// ────────────────────────────────────────────────────────────────────────────────
// Public entry point
// ────────────────────────────────────────────────────────────────────────────────

/// Returns 64 bytes (512 bits) of fully conditioned entropy suitable for
/// seeding a SP 800-90A DRBG.
///
/// # SP 800-90C Multi-Source Combining
///
/// All available entropy sources are blended through a single SHA3-512
/// invocation.  The hash's collision resistance (256-bit security) ensures
/// that the output carries full min-entropy even if a subset of sources is
/// weak or controlled by an adversary.
///
/// # Panics
///
/// Panics if the primary OS entropy source (`/dev/urandom`) is unavailable or
/// fails its SP 800-90B health tests.  This is the correct FIPS fail-safe
/// behaviour.
pub fn get_blended_entropy() -> [u8; 64] {
    let mut hasher = Sha3_512::new();

    // ── Primary: OS RNG (always active) ──────────────────────────────────────
    {
        let mut os_rng = OsRng::new().expect("Failed to open /dev/urandom");
        // Wrap in Zeroizing so the OS entropy is erased even on panic.
        #[cfg(feature = "zeroize")]
        let mut buf = Zeroizing::new([0u8; 64]);
        #[cfg(not(feature = "zeroize"))]
        let mut buf = [0u8; 64];
        os_rng.fill_bytes(buf.as_mut()).expect("Failed to read from /dev/urandom");
        hasher.update(buf.as_ref());
    }

    // ── Secondary + Tertiary: CPU jitter & system state ───────────────────────
    #[cfg(feature = "advance")]
    {
        hasher.update(gather_cpu_jitter());
        hasher.update(gather_system_entropy());
    }

    // ── Quaternary: SIMD thermal jitter ──────────────────────────────────────
    hasher.update(gather_simd_jitter());

    // ── Quinary: Network-stack timing jitter ─────────────────────────────────
    hasher.update(gather_network_jitter());

    // ── Senary: Hardware RNG (RDSEED/RDRAND) ─────────────────────────────────
    hasher.update(gather_hardware_rng());

    // ── Septenary: CPU Performance Counters (perf_event) ─────────────────────
    hasher.update(gather_perf_events());

    let mut result = [0u8; 64];
    result.copy_from_slice(&hasher.finalize());
    result
}

// ────────────────────────────────────────────────────────────────────────────────
// Secondary: CPU Timing Jitter (`advance` feature)
//
// Architecture inspired by jitterentropy-library (S. Müller), with several
// improvements over the C reference:
//
//  1. SHA3-512 entropy pool per output byte (vs LFSR mixing) — FIPS 202
//  2. Multi-level Δ/Δ²/Δ³ stuck detection (identical to jent_stuck())
//  3. 256 KiB memory block for L2/L3 cache-boundary thrashing
//  4. xoshiro128** PRNG for memory address selection (same as jitterentropy)
//  5. Volatile memory ops prevent compiler elimination of noise sources
//  6. Separate memory-noise and CPU-fold noise functions marked #[inline(never)]
//  7. SP 800-90B compliant warmup phase (64 discarded samples)
//  8. Dual-timer input: Instant + RDTSC (x86) for timer-source independence
//  9. 64:1 oversampling — feeds ALL timing bits into SHA3 pool, not just LSBs
// 10. Enhanced backtracking resistance via final whole-output SHA3-512 pass
// ────────────────────────────────────────────────────────────────────────────────

/// Size of the memory block used for cache thrashing.
/// 256 KiB is large enough to exceed L1 and straddle L2/L3 on most
/// architectures, forcing high-variance accesses.
#[cfg(feature = "advance")]
const JITTER_MEM_SIZE: usize = 256 * 1024;

/// Number of pseudo-random memory accesses per noise invocation.
#[cfg(feature = "advance")]
const JITTER_MEM_ACCESSES: usize = 64;

/// Number of iterations in the CPU fold loop per noise invocation.
#[cfg(feature = "advance")]
const JITTER_FOLD_ROUNDS: usize = 64;

/// Oversampling ratio: raw timing samples collected per output byte.
/// With an assumed H = 2 bits/sample and SHA3-512 conditioning, 64 samples
/// contribute ≈ 128 bits of min-entropy per byte — far exceeding the 8 needed.
#[cfg(feature = "advance")]
const JITTER_OVERSAMPLE: u32 = 64;

/// Warmup rounds: initial samples discarded to let CPU caches, TLBs, and
/// branch predictors reach a statistically representative steady state.
/// SP 800-90B § 4.3 requires at least 1024 startup samples; we collect 64
/// timing deltas per warmup round (memory + fold), totalling ≈ 4096
/// individual operations.
#[cfg(feature = "advance")]
const JITTER_WARMUP_ROUNDS: u32 = 64;

/// Maximum allowed stuck-sample percentage before we consider the timing
/// source compromised.  jitterentropy rejects any block with too many stuck
/// samples; we panic (FIPS fail-safe) if > 50 % are stuck.
#[cfg(feature = "advance")]
const JITTER_MAX_STUCK_PCT: u32 = 50;

// ── Multi-level delta stuck detector (jitterentropy-style) ───────────────

/// Tracks the 1st, 2nd, and 3rd discrete derivatives of consecutive timing
/// deltas to detect constant, linearly drifting, or quadratically drifting
/// clock behaviour — all indicators of a compromised or virtualised timer.
///
/// This is the Rust equivalent of `jent_stuck()` from `jitterentropy-health.c`.
///
/// | Derivative | Detects |
/// |------------|---------|
/// | Δ = 0  | Stuck / constant timer (identical consecutive deltas) |
/// | Δ² = 0 | Linearly drifting timer (constant rate of change) |
/// | Δ³ = 0 | Quadratically drifting timer (constant acceleration) |
#[cfg(feature = "advance")]
#[derive(Debug)]
struct DeltaTracker {
    last_delta: u64,
    last_delta2: u64,
    stuck_count: u32,
    total_count: u32,
}

#[cfg(feature = "advance")]
impl DeltaTracker {
    fn new() -> Self {
        Self { last_delta: 0, last_delta2: 0, stuck_count: 0, total_count: 0 }
    }

    /// Returns `true` if `current_delta` should be considered *stuck*
    /// (i.e. it carries negligible entropy and must not be counted toward
    /// the oversampling quota).
    ///
    /// A sample is stuck when **any** of the three derivative levels is zero:
    /// - `delta` = current – previous  (1st derivative)
    /// - `delta2` = delta – prev_delta  (2nd derivative)
    /// - `delta3` = delta2 – prev_delta2  (3rd derivative)
    fn is_stuck(&mut self, current_delta: u64) -> bool {
        let delta2 = current_delta.wrapping_sub(self.last_delta);
        let delta3 = delta2.wrapping_sub(self.last_delta2);

        self.last_delta = current_delta;
        self.last_delta2 = delta2;
        self.total_count += 1;

        let stuck = current_delta == 0 || delta2 == 0 || delta3 == 0;
        if stuck {
            self.stuck_count += 1;
        }
        stuck
    }

    /// Panics (FIPS fail-safe) if the stuck ratio exceeds
    /// [`JITTER_MAX_STUCK_PCT`], indicating a hostile or deterministic
    /// timing environment.
    fn assert_healthy(&self) {
        if self.total_count > 10
            && (self.stuck_count * 100) / self.total_count > JITTER_MAX_STUCK_PCT
        {
            panic!(
                "CPU jitter stuck-sample rate {}/{}  ({:.0}%) exceeds {}% — \
                 timing source is deterministic or compromised",
                self.stuck_count,
                self.total_count,
                self.stuck_count as f64 / self.total_count as f64 * 100.0,
                JITTER_MAX_STUCK_PCT,
            );
        }
    }
}

// ── xoshiro128** PRNG for memory address selection ───────────────────────
//
// Identical to the algorithm used in jitterentropy-noise.c.  It provides
// uniformly distributed memory indices that defeat hardware prefetchers
// without contributing any entropy itself (the entropy comes from the
// *timing* of the memory accesses, not their addresses).

#[cfg(feature = "advance")]
#[inline(always)]
fn xoshiro128ss(s: &mut [u32; 4]) -> u32 {
    let result = (s[1].wrapping_mul(5)).rotate_left(7).wrapping_mul(9);
    let t = s[1] << 9;
    s[2] ^= s[0];
    s[3] ^= s[1];
    s[1] ^= s[2];
    s[0] ^= s[3];
    s[2] ^= t;
    s[3] = s[3].rotate_left(11);
    result
}

// ── Noise source: memory access ──────────────────────────────────────────

/// Performs [`JITTER_MEM_ACCESSES`] pseudo-random read-modify-write accesses
/// across `mem_block`.
///
/// Marked `#[inline(never)]` so that the compiler cannot merge this with
/// the surrounding timer reads or reorder it across the timing boundary,
/// which would destroy the timing measurement.
///
/// Uses `core::ptr::read_volatile` / `write_volatile` to guarantee that
/// every access actually touches memory and is not elided.
#[cfg(feature = "advance")]
#[inline(never)]
fn memory_noise(mem_block: &mut [u8], prng: &mut [u32; 4]) {
    let mask = mem_block.len() - 1; // power-of-2 assumed
    for _ in 0..JITTER_MEM_ACCESSES {
        let idx = xoshiro128ss(prng) as usize & mask;
        // SAFETY: `idx` is bounded by `mask` which is `mem_block.len() - 1`.
        unsafe {
            let ptr = mem_block.as_mut_ptr().add(idx);
            let val = core::ptr::read_volatile(ptr);
            core::ptr::write_volatile(ptr, val.wrapping_add(1));
        }
    }
}

// ── Noise source: CPU fold loop ──────────────────────────────────────────

/// Tight arithmetic loop with data-dependent branches designed to create
/// unpredictable pipeline stalls.
///
/// The result is explicitly consumed via `black_box` to prevent dead-code
/// elimination.  The returned value is mixed into the entropy pool as
/// additional non-timing material.
#[cfg(feature = "advance")]
#[inline(never)]
fn cpu_fold_noise(seed: u64) -> u64 {
    let mut fold = seed;
    for i in 0..JITTER_FOLD_ROUNDS as u64 {
        // Multiplicative hash step (Knuth LCG constant).
        fold = fold.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(i);
        // Xorshift mixing.
        fold ^= fold >> 17;
        fold ^= fold << 13;
        fold ^= fold >> 7;
        // Data-dependent branch to thrash branch predictor.
        if fold & 0x80 != 0 {
            fold = fold.wrapping_add(fold >> 3);
        } else {
            fold ^= fold.wrapping_mul(fold | 1);
        }
        // Division with data-dependent divisor (variable latency on most µarches).
        fold = fold.wrapping_add(fold.wrapping_div(1 | (i.wrapping_mul(fold) & 0xFFFF)));
    }
    std::hint::black_box(fold)
}

// ── Main jitter collector ────────────────────────────────────────────────

/// Collects 64 bytes of entropy from CPU micro-architectural timing jitter.
///
/// ## Design (inspired by jitterentropy-library, hardened for Rust)
///
/// | Phase | Description |
/// |-------|-------------|
/// | **Warmup** | Execute [`JITTER_WARMUP_ROUNDS`] noise invocations and discard the timing deltas to stabilise caches, TLBs, and branch predictors. |
/// | **Collection** | For each of the 64 output bytes, collect [`JITTER_OVERSAMPLE`] valid (non-stuck) timing deltas. Each delta is produced by executing `memory_noise` + `cpu_fold_noise` and measuring the elapsed time. |
/// | **Stuck filter** | Every delta is checked with [`DeltaTracker::is_stuck`] (Δ/Δ²/Δ³). Stuck samples are still fed to the pool (they may carry *some* entropy) but do not count toward the oversample quota. |
/// | **Health tests** | Every raw sample byte is passed to the SP 800-90B RCT/APT. Failure panics immediately. |
/// | **Per-byte conditioning** | All timing + fold data is accumulated in a SHA3-512 hasher; the digest is XOR-folded into a single output byte. |
/// | **Backtracking resistance** | A final SHA3-512 pass over all 64 output bytes ensures that learning the output reveals nothing about intermediate pool states. |
///
/// ## Panics
///
/// - SP 800-90B health test failure (stuck/biased timing source).
/// - Stuck-sample ratio exceeds [`JITTER_MAX_STUCK_PCT`]%.
#[cfg(feature = "advance")]
fn gather_cpu_jitter() -> [u8; 64] {
    // Wrap in Zeroizing so the raw output is erased on panic.
    #[cfg(feature = "zeroize")]
    let mut output = Zeroizing::new([0u8; 64]);
    #[cfg(not(feature = "zeroize"))]
    let mut output = [0u8; 64];
    let mut health = HealthTests::new(
        crate::rng::JITTER_RCT_CUTOFF,
        crate::rng::JITTER_APT_CUTOFF,
        crate::rng::JITTER_AUTO_LOWER_BOUND,
        crate::rng::JITTER_AUTO_UPPER_BOUND,
        crate::rng::JITTER_SYMBOL_MIN_UNIQUE,
    );
    let mut deltas = DeltaTracker::new();

    // 256 KiB memory block (power of 2 for fast masking).
    let mut mem_block = vec![0u8; JITTER_MEM_SIZE];

    // xoshiro128** state — seeded from initial timing to avoid a fixed
    // starting state.  The PRNG itself contributes zero entropy; it only
    // selects which memory addresses are accessed.
    let mut prng: [u32; 4] = [0x8e93_eec0, 0xce65_608a, 0xa8d4_6b46, 0xe83c_ef69];
    {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        {
            // SAFETY: RDTSC is universally available on x86/x86_64.
            let tsc1 = unsafe { _rdtsc() };
            let tsc2 = unsafe { _rdtsc() };
            prng[0] ^= tsc1 as u32;
            prng[1] ^= (tsc1 >> 32) as u32;
            prng[2] ^= tsc2 as u32;
            prng[3] ^= (tsc2 >> 32) as u32;
        }
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
        {
            let t0 = Instant::now();
            std::hint::black_box(cpu_fold_noise(42));
            let d1 = t0.elapsed().as_nanos() as u32;
            let t1 = Instant::now();
            std::hint::black_box(cpu_fold_noise(84));
            let d2 = t1.elapsed().as_nanos() as u32;
            prng[0] ^= d1;
            prng[1] ^= d2;
            prng[2] ^= d1.rotate_left(16);
            prng[3] ^= d2.rotate_left(16);
        }
    }

    // ── Warmup phase ─────────────────────────────────────────────────────
    // Discard initial timing samples so that caches and branch predictors
    // reach a statistically representative steady state.
    for _ in 0..JITTER_WARMUP_ROUNDS {
        let t1 = Instant::now();
        memory_noise(&mut mem_block, &mut prng);
        cpu_fold_noise(prng[0] as u64);
        let delta = t1.elapsed().as_nanos() as u64;
        // Feed warmup deltas into the stuck tracker (establishes baseline)
        // and health tests, but do not store the output.
        let _ = deltas.is_stuck(delta);
        health.process_sample((delta & 0xFF) as u8);
    }

    // ── Collection phase ─────────────────────────────────────────────────
    let mut final_hash = Sha3_512::new();

    for byte in output.iter_mut() {
        let mut pool = Sha3_512::new();
        let mut valid_samples = 0u32;

        while valid_samples < JITTER_OVERSAMPLE {
            // ── Execute combined noise source ────────────────────────
            let t1 = Instant::now();
            memory_noise(&mut mem_block, &mut prng);
            let fold_result = cpu_fold_noise(prng[0] as u64);
            let delta_ns = t1.elapsed().as_nanos() as u64;

            // SP 800-90B health test on the raw timing byte.
            let raw_byte = (delta_ns & 0xFF) as u8;
            health.process_sample(raw_byte);

            // Feed the FULL 64-bit timing delta into the pool (not just the LSB).
            pool.update(delta_ns.to_le_bytes());

            // Also feed the fold result as additional non-timing material.
            pool.update(fold_result.to_le_bytes());

            // On x86, mix in a raw RDTSC reading for maximum timer resolution
            // and timer-source independence (RDTSC ≠ clock_gettime).
            #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
            {
                // SAFETY: RDTSC is universally available on x86/x86_64.
                let tsc = unsafe { _rdtsc() };
                pool.update(tsc.to_le_bytes());
            }

            // Multi-level stuck filter (Δ/Δ²/Δ³).
            // Stuck samples are still in the pool (they may carry partial
            // entropy) but do not count toward the oversample quota.
            if deltas.is_stuck(delta_ns) {
                continue;
            }

            valid_samples += 1;
        }

        // Check overall stuck ratio for this byte.
        deltas.assert_healthy();

        // Condition the accumulated timing data through SHA3-512.
        // Wrap the digest in Zeroizing so intermediate key material is erased.
        #[cfg(feature = "zeroize")]
        let digest = Zeroizing::new({
            let d = pool.finalize();
            let mut arr = [0u8; 64];
            arr.copy_from_slice(&d);
            arr
        });
        #[cfg(not(feature = "zeroize"))]
        let digest = {
            let d = pool.finalize();
            let mut arr = [0u8; 64];
            arr.copy_from_slice(&d);
            arr
        };
        *byte = digest[0];
        final_hash.update(digest.as_ref());
    }

    // ── Backtracking resistance ──────────────────────────────────────────
    // A final SHA3-512 pass over the entire output ensures that an attacker
    // who compromises memory *after* this function returns cannot recover
    // the intermediate per-byte pool states.
    final_hash.update(&*output);
    // Mix in one last timestamp to bind the output to this exact instant.
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        // SAFETY: RDTSC is universally available on x86/x86_64.
        let tsc = unsafe { _rdtsc() };
        final_hash.update(tsc.to_le_bytes());
    }
    let now_ns = SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    final_hash.update(now_ns.to_le_bytes());
    output.copy_from_slice(&final_hash.finalize());

    *output
}

// ────────────────────────────────────────────────────────────────────────────────
// Tertiary: System State Entropy (`advance` feature)
// ────────────────────────────────────────────────────────────────────────────────

/// Hashes a snapshot of volatile system state into a 64-byte value.
///
/// No individual field here is a high-quality entropy source, but collectively
/// they add unpredictability that an adversary who controls the OS RNG alone
/// cannot predict.
///
/// Sources include: version/build separators, wall-clock and monotonic time,
/// thread/process IDs, stack/heap ASLR pointers, Linux `/proc` counters
/// (uptime, load average, memory, interrupts, network stats), and RDTSC.
#[cfg(feature = "advance")]
fn gather_system_entropy() -> [u8; 64] {
    let mut h = Sha3_512::new();

    // Domain / version separators.
    h.update(env!("CARGO_PKG_VERSION").as_bytes());
    #[cfg(feature = "build_separator")]
    h.update(BUILD_SEPARATOR);

    // Temporal state.
    if let Ok(d) = SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
        h.update(d.as_nanos().to_le_bytes());
    }
    // Monotonic clock — format gives nanosecond-resolution internal representation.
    let mono_ns = std::time::Instant::now();
    h.update(format!("{mono_ns:?}").as_bytes());

    #[cfg(target_os = "linux")]
    {
        let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
        if unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut ts) } == 0 {
            h.update(ts.tv_sec.to_le_bytes());
            h.update(ts.tv_nsec.to_le_bytes());
        }
        if unsafe { libc::clock_gettime(libc::CLOCK_TAI, &mut ts) } == 0 {
            h.update(ts.tv_sec.to_le_bytes());
            h.update(ts.tv_nsec.to_le_bytes());
        }
    }

    // Process / thread identity.
    h.update(format!("{:?}", thread::current().id()).as_bytes());
    h.update(process::id().to_le_bytes());

    // ASLR-derived stack address.
    let stack_var = 0usize;
    h.update((&stack_var as *const usize as usize).to_le_bytes());

    // Linux /proc counters (best-effort; failures are silently ignored).
    for path in &[
        "/proc/uptime",
        "/proc/loadavg",
        "/proc/meminfo",
        "/proc/stat",
        "/proc/interrupts",
        "/proc/net/dev",
        "/proc/self/schedstat",
        "/proc/net/snmp",
        "/proc/self/statm",
        "/proc/self/schedstat",
        "/proc/self/status",
        
    ] {
        if let Ok(mut f) = File::open(path) {
            let mut buf = [0u8; 256];
            if let Ok(n) = f.read(&mut buf) {
                h.update(&buf[..n]);
            }
        }
    }

    // Hardware TSC (x86/x86_64 only).
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        // SAFETY: `_rdtsc` is always available on x86/x86_64 and has no
        // side effects beyond reading the time-stamp counter register.
        let tsc = unsafe { _rdtsc() };
        h.update(tsc.to_le_bytes());

    }

    let mut result = [0u8; 64];
    result.copy_from_slice(&h.finalize());
    result
}

// ────────────────────────────────────────────────────────────────────────────────
// Quinary: Network-Stack Timing Jitter (`exp_network_rng` feature)
// ────────────────────────────────────────────────────────────────────────────────

/// Entropy from OS networking-stack micro-latency (non-blocking UDP to WAN DNS).
///
/// Gracefully returns all-zero if the network is unavailable or strictly
/// isolated; the blender is still safe because the OS RNG alone is sufficient.
#[cfg(feature = "exp_network_rng")]
fn gather_network_jitter() -> [u8; 64] {
    use std::time::Instant;

    let mut result = [0u8; 64];

    // Binary source (p=0.5 after Von Neumann debiasing).
    let mut health = crate::rng::HealthTests::new(
        35,    // RCT_CUTOFF (1 + ceil(30/1))
        325,   // APT_CUTOFF (binomial CDF inverse for n=512, p=0.5)
        10,    // AUTO_LOWER_BOUND
        20000, // AUTO_UPPER_BOUND
        2,     // SYMBOL_MIN_UNIQUE
    );

    if let Ok(socket) = UdpSocket::bind("0.0.0.0:0")
        && socket.set_nonblocking(true).is_ok()
    {
        let mut hasher = Sha3_512::new();
        let mut recv_buf = [0u8; 512];

        // Minimal DNS query for root zone NS records.
        let mut dns_payload: [u8; 17] = [
            0x13, 0x37, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x02, 0x00, 0x01,
        ];

        let servers = ["9.9.9.9:53", "8.8.8.8:53", "1.1.1.1:53", "208.67.222.222:53"];
        let mut server_idx = 0usize;

        for byte in result.iter_mut() {
            let mut accumulator = 0u8;
            let mut bits_collected = 0u32;

            let mut get_raw_sample = |h: &mut Sha3_512| -> u8 {
                let start = Instant::now();
                // Randomize transaction ID
                let elapsed = start.elapsed().as_nanos();
                dns_payload[0] = (elapsed & 0xFF) as u8;
                dns_payload[1] = ((elapsed >> 8) & 0xFF) as u8;

                let _ = socket.send_to(&dns_payload, servers[server_idx % servers.len()]);
                server_idx += 1;
                let _ = socket.recv_from(&mut recv_buf);
                
                let elapsed_post = start.elapsed().as_nanos();
                h.update(elapsed_post.to_le_bytes()); // feed full resolution immediately
                (elapsed_post & 0xFF) as u8
            };

            while bits_collected < 8 {
                let b1 = get_raw_sample(&mut hasher) & 1;
                let b2 = get_raw_sample(&mut hasher) & 1;
                if b1 != b2 {
                    health.process_sample(b1);
                    accumulator = (accumulator << 1) | b1;
                    bits_collected += 1;
                }
            }
            *byte = accumulator;
        }

        hasher.update(result);
        result.copy_from_slice(&hasher.finalize());
    }

    result
}

#[cfg(not(feature = "exp_network_rng"))]
fn gather_network_jitter() -> [u8; 64] {
    [0u8; 64]
}

// ────────────────────────────────────────────────────────────────────────────────
// Quaternary: SIMD Thermal / Frequency Jitter (`exp_simd_rng` feature)
// ────────────────────────────────────────────────────────────────────────────────

/// Entropy from AVX-256 SIMD-induced CPU frequency-scaling latency spikes.
///
/// Requires `exp_simd_rng` (which implies `advance`) and an x86/x86_64 target
/// with AVX2. Falls back to all-zero on other targets / feature sets.
#[cfg(all(feature = "exp_simd_rng", any(target_arch = "x86", target_arch = "x86_64")))]
fn gather_simd_jitter() -> [u8; 64] {
    use std::arch::x86_64::{
        __m256i, _mm256_add_epi64, _mm256_loadu_si256, _mm256_mul_epi32, _mm256_set1_epi64x,
        _mm256_storeu_si256, _mm256_xor_si256,
    };
    use std::time::Instant;

    let mut jitter = [0u8; 64];

    if std::is_x86_feature_detected!("avx2") {
        // Nested `unsafe fn` keeps the target_feature annotation isolated.
        #[target_feature(enable = "avx2")]
        unsafe fn inner(jitter: &mut [u8; 64]) {
            // Very relaxed bounds: AVX2 throughput can be highly uniform.
            let mut health = crate::rng::HealthTests::new(
                5000, 5000, 10, 20_000, 2,
            );

            // 2 MiB block forces L3 / DRAM latency spikes.
            let mut mem_block = vec![0i64; 256 * 1024];
            let mut lfsr: u16 = 0xACE1;

            for byte in jitter.iter_mut() {
                let mut accumulator = 0u8;
                let mut bits_collected = 0u32;

                let mut get_raw_sample = || -> u8 {
                    let start = Instant::now();
                    // SAFETY: _rdtsc is always available on x86/x86_64
                    let start_tsc = unsafe { _rdtsc() };

                    let mut v1 = _mm256_set1_epi64x(0xDEAD_BEEF_CAFE_BABEu64 as i64);
                    let mut v2 = _mm256_set1_epi64x(0x1234_5678_90AB_CDEFu64 as i64);

                    for _ in 0..256 {
                        v1 = _mm256_add_epi64(v1, v2);
                        v2 = _mm256_xor_si256(v2, v1);
                        v1 = _mm256_mul_epi32(v1, v2);

                        lfsr = (lfsr >> 1) ^ (-(lfsr as i16 & 1) as u16 & 0xB400);
                        let idx = (lfsr as usize) % (mem_block.len() - 4);

                        // SAFETY: idx is bounded above; mem_block is a valid heap allocation.
                        unsafe {
                            let mem_vec =
                                _mm256_loadu_si256(mem_block.as_ptr().add(idx) as *const __m256i);
                            v1 = _mm256_add_epi64(v1, mem_vec);
                            _mm256_storeu_si256(
                                mem_block.as_mut_ptr().add(idx) as *mut __m256i,
                                v1,
                            );
                        }
                    }

                    let mut out = [0u64; 4];
                    // SAFETY: `out` is correctly sized for an unaligned 256-bit store.
                    unsafe {
                        _mm256_storeu_si256(out.as_mut_ptr() as *mut __m256i, v1);
                    }
                    std::hint::black_box(out);
                    std::hint::black_box(&mut mem_block);

                    let elapsed_ns = start.elapsed().as_nanos() as u64;
                    let elapsed_tsc = unsafe { _rdtsc() }.wrapping_sub(start_tsc);

                    ((elapsed_ns ^ elapsed_tsc) & 0xFF) as u8
                };

                while bits_collected < 8 {
                    let b1 = get_raw_sample() & 1;
                    let b2 = get_raw_sample() & 1;
                    if b1 != b2 {
                        health.process_sample(b1);
                        accumulator = (accumulator << 1) | b1;
                        bits_collected += 1;
                    }
                }

                // SHA3-512 post-conditioning.
                let mut h = Sha3_512::new();
                h.update([accumulator]);
                let d = h.finalize();
                *byte = d[0] ^ d[1];
            }
        }

        // SAFETY: AVX2 support was confirmed by the runtime check above.
        unsafe { inner(&mut jitter) };
    }

    jitter
}

#[cfg(not(all(feature = "exp_simd_rng", any(target_arch = "x86", target_arch = "x86_64"))))]
fn gather_simd_jitter() -> [u8; 64] {
    [0u8; 64]
}

// ────────────────────────────────────────────────────────────────────────────────
// Senary: Hardware RNG (`advance` feature)
// ────────────────────────────────────────────────────────────────────────────────

/// Entropy from hardware RNG instructions (RDSEED and RDRAND).
///
/// Available only on x86/x86_64 targets with the respective features.
/// - `RDSEED` provides true hardware entropy from a conditioned noise source.
/// - `RDRAND` provides pseudo-random numbers from a hardware DRBG.
#[cfg(all(feature = "advance", any(target_arch = "x86", target_arch = "x86_64")))]
fn gather_hardware_rng() -> [u8; 64] {
    let mut h = Sha3_512::new();

    // Iterate enough times to collect 64 bytes
    const ITERS: usize = 64 / core::mem::size_of::<usize>();

    // Try to collect 64 bytes from RDSEED.
    if std::is_x86_feature_detected!("rdseed") {
        for _ in 0..ITERS {
            let mut val: usize = 0;
            let mut ok: u8;
            // Retry loop: RDSEED can fail if the entropy source is exhausted
            for _ in 0..100 {
                unsafe {
                    core::arch::asm!(
                        "rdseed {val}",
                        "setc {ok}",
                        val = out(reg) val,
                        ok = out(reg_byte) ok,
                    );
                }
                if ok != 0 {
                    h.update(val.to_le_bytes());
                    break;
                }
                core::hint::spin_loop();
            }
        }
    }

    // Try to collect 64 bytes from RDRAND as a complementary source.
    if std::is_x86_feature_detected!("rdrand") {
        for _ in 0..ITERS {
            let mut val: usize = 0;
            let mut ok: u8;
            // RDRAND is faster but can also theoretically fail
            for _ in 0..10 {
                unsafe {
                    core::arch::asm!(
                        "rdrand {val}",
                        "setc {ok}",
                        val = out(reg) val,
                        ok = out(reg_byte) ok,
                    );
                }
                if ok != 0 {
                    h.update(val.to_le_bytes());
                    break;
                }
                core::hint::spin_loop();
            }
        }
    }

    let mut result = [0u8; 64];
    result.copy_from_slice(&h.finalize());
    result
}

#[cfg(not(all(feature = "advance", any(target_arch = "x86", target_arch = "x86_64"))))]
fn gather_hardware_rng() -> [u8; 64] {
    [0u8; 64]
}

// ────────────────────────────────────────────────────────────────────────────────
// Septenary: CPU Performance Counters (perf_event) (`advance` feature)
// ────────────────────────────────────────────────────────────────────────────────

#[cfg(all(feature = "advance", target_os = "linux"))]
fn gather_perf_events() -> [u8; 64] {
    let mut h = Sha3_512::new();

    #[repr(C)]
    #[derive(Default)]
    struct perf_event_attr {
        pub type_: u32,
        pub size: u32,
        pub config: u64,
        pub sample_period_or_freq: u64,
        pub sample_type: u64,
        pub read_format: u64,
        pub flags: u64,
        pub wakeup_events_or_watermark: u32,
        pub bp_type: u32,
        pub bp_addr: u64,
        pub bp_len: u64,
        pub branch_sample_type: u64,
        pub sample_regs_user: u64,
        pub sample_stack_user: u32,
        pub clockid: i32,
        pub sample_regs_intr: u64,
        pub aux_watermark: u32,
        pub sample_max_stack: u16,
        pub __reserved_2: u16,
    }

    // PERF_TYPE_HARDWARE = 0
    // PERF_COUNT_HW_CPU_CYCLES = 0
    // PERF_COUNT_HW_INSTRUCTIONS = 1
    // PERF_COUNT_HW_CACHE_MISSES = 3
    // PERF_COUNT_HW_BRANCH_MISSES = 5
    let events = [0, 1, 3, 5];

    for &event_id in &events {
        let mut attr: perf_event_attr = Default::default();
        attr.type_ = 0; // PERF_TYPE_HARDWARE
        attr.size = std::mem::size_of::<perf_event_attr>() as u32;
        attr.config = event_id as u64;
        
        // disabled(1) | exclude_kernel(1) | exclude_hv(1)
        attr.flags = (1 << 0) | (1 << 3) | (1 << 4);

        let fd = unsafe {
            libc::syscall(
                libc::SYS_perf_event_open,
                &attr as *const _ as *const libc::c_void,
                0isize,  // pid 0 = current thread
                -1isize, // cpu -1 = any cpu
                -1isize, // group_fd
                0isize,  // flags
            )
        };

        if fd >= 0 {
            // PERF_EVENT_IOC_ENABLE = _IO('$', 0) = 0x2400
            // PERF_EVENT_IOC_DISABLE = _IO('$', 1) = 0x2401
            let ioc_enable = 0x2400;
            let ioc_disable = 0x2401;

            unsafe { libc::ioctl(fd as i32, ioc_enable, 0) };

            for _ in 0..1000 {
                core::hint::spin_loop();
            }

            unsafe { libc::ioctl(fd as i32, ioc_disable, 0) };

            let mut count: u64 = 0;
            if unsafe {
                libc::read(fd as i32, &mut count as *mut _ as *mut libc::c_void, 8)
            } == 8 {
                h.update(count.to_le_bytes());
            }

            unsafe { libc::close(fd as i32) };
        }
    }

    let mut result = [0u8; 64];
    result.copy_from_slice(&h.finalize());
    result
}

#[cfg(not(all(feature = "advance", target_os = "linux")))]
fn gather_perf_events() -> [u8; 64] {
    [0u8; 64]
}

// ────────────────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────────────────

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

    #[test]
    #[cfg(feature = "advance")]
    fn cpu_jitter_produces_unique_outputs() {
        let mut seen = HashSet::new();
        for i in 0..5 {
            let j = gather_cpu_jitter();
            eprintln!("Jitter[{i}]: {j:02x?}");
            assert!(seen.insert(j.to_vec()), "CRITICAL: duplicate CPU jitter output");
        }
    }

    #[test]
    #[cfg(feature = "advance")]
    fn cpu_jitter_monobit_proportion() {
        let mut ones = 0u32;
        let mut total = 0u32;
        for _ in 0..10 {
            let j = gather_cpu_jitter();
            for &b in &j {
                ones += b.count_ones();
                total += 8;
            }
        }
        let p = ones as f64 / total as f64;
        eprintln!("Monobit proportion of 1s: {p:.4} (ideal 0.5000)");
        assert!(p > 0.40 && p < 0.60, "monobit test failed: {p}");
    }

    #[test]
    #[cfg(feature = "advance")]
    fn system_entropy_produces_unique_outputs() {
        let mut seen = HashSet::new();
        for i in 0..5 {
            let s = gather_system_entropy();
            eprintln!("SysEnt[{i}]: {:02x?}", &s[..16]);
            assert!(seen.insert(s.to_vec()), "CRITICAL: duplicate system entropy");
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
    }

    #[test]
    fn blended_entropy_produces_unique_outputs() {
        let mut seen = HashSet::new();
        for i in 0..5 {
            let b = get_blended_entropy();
            eprintln!("Blended[{i}]: {:02x?}", &b[..16]);
            assert!(seen.insert(b.to_vec()), "CRITICAL: duplicate blended entropy");
        }
    }
}