openentropy-core 0.10.0

Core entropy harvesting library — hardware noise sources, raw or SHA-256 conditioned
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
//! Shared helpers used by multiple entropy source implementations.
//!
//! This module prevents code duplication across sources that need common
//! low-level primitives like high-resolution timestamps and LSB extraction.

// ---------------------------------------------------------------------------
// High-resolution timing
// ---------------------------------------------------------------------------

/// High-resolution timestamp in nanoseconds.
///
/// On macOS, this reads the ARM system counter directly via `mach_absolute_time()`.
/// On other platforms, it falls back to `std::time::Instant` relative to a
/// process-local epoch.
#[cfg(target_os = "macos")]
pub fn mach_time() -> u64 {
    unsafe extern "C" {
        fn mach_absolute_time() -> u64;
    }
    // SAFETY: mach_absolute_time() is a stable macOS API that returns the
    // current value of the system absolute time counter. Always safe to call.
    unsafe { mach_absolute_time() }
}

#[cfg(not(target_os = "macos"))]
pub fn mach_time() -> u64 {
    use std::sync::OnceLock;
    use std::time::Instant;
    static EPOCH: OnceLock<Instant> = OnceLock::new();
    let epoch = EPOCH.get_or_init(Instant::now);
    epoch.elapsed().as_nanos() as u64
}

// ---------------------------------------------------------------------------
// LSB extraction
// ---------------------------------------------------------------------------

/// Pack a stream of individual bits (0 or 1) into bytes (MSB-first packing).
///
/// For every 8 input bits, one output byte is produced.
fn pack_bits_into_bytes(bits: &[u8]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(bits.len() / 8);
    for chunk in bits.chunks_exact(8) {
        let mut byte = 0u8;
        for (i, &bit) in chunk.iter().enumerate() {
            byte |= bit << (7 - i);
        }
        bytes.push(byte);
    }
    bytes
}

/// Extract the least-significant bit of each `u64` delta and pack into bytes.
///
/// For every 8 input values, one output byte is produced (MSB-first packing).
pub fn extract_lsbs_u64(deltas: &[u64]) -> Vec<u8> {
    let bits: Vec<u8> = deltas.iter().map(|d| (d & 1) as u8).collect();
    pack_bits_into_bytes(&bits)
}

/// Extract the least-significant bit of each `i64` delta and pack into bytes.
///
/// Identical to [`extract_lsbs_u64`] but for signed deltas.
pub fn extract_lsbs_i64(deltas: &[i64]) -> Vec<u8> {
    let bits: Vec<u8> = deltas.iter().map(|d| (d & 1) as u8).collect();
    pack_bits_into_bytes(&bits)
}

// ---------------------------------------------------------------------------
// Shared command utilities
// ---------------------------------------------------------------------------

/// Check if a command exists by running `which`.
pub fn command_exists(name: &str) -> bool {
    std::process::Command::new("which")
        .arg(name)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Execute a command and return its `Output` if it succeeds.
///
/// Uses a 30-second timeout to prevent indefinite hangs from system utilities
/// that might block (e.g. `ioreg -l -w0` on complex IOKit trees).
fn run_command_output(program: &str, args: &[&str]) -> Option<std::process::Output> {
    run_command_output_timeout(program, args, 30_000)
}

/// Run a subprocess command with a timeout and return full `Output`.
///
/// If the process does not finish within `timeout_ms`, it is killed and `None`
/// is returned. Stderr is suppressed to keep entropy collection paths quiet.
pub fn run_command_output_timeout(
    program: &str,
    args: &[&str],
    timeout_ms: u64,
) -> Option<std::process::Output> {
    use std::io::Read;
    use std::process::{Command, Stdio};
    use std::thread;
    use std::time::{Duration, Instant};

    let mut child = Command::new(program)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;

    // Drain stdout concurrently so producers like ffmpeg rawvideo do not block
    // on a full pipe before process exit.
    let mut stdout_reader = child.stdout.take().map(|mut stdout| {
        thread::spawn(move || {
            let mut buf = Vec::new();
            let _ = stdout.read_to_end(&mut buf);
            buf
        })
    });

    let start = Instant::now();
    let timeout = Duration::from_millis(timeout_ms.max(1));

    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let stdout = stdout_reader
                    .take()
                    .and_then(|h| h.join().ok())
                    .unwrap_or_default();
                let output = std::process::Output {
                    status,
                    stdout,
                    stderr: Vec::new(),
                };
                return output.status.success().then_some(output);
            }
            Ok(None) => {
                if start.elapsed() >= timeout {
                    let _ = child.kill();
                    let _ = child.wait();
                    if let Some(reader) = stdout_reader.take() {
                        let _ = reader.join();
                    }
                    return None;
                }
                thread::sleep(Duration::from_millis(10));
            }
            Err(_e) => {
                let _ = child.kill();
                let _ = child.wait();
                if let Some(reader) = stdout_reader.take() {
                    let _ = reader.join();
                }
                return None;
            }
        }
    }
}

/// Run a subprocess command and return its stdout as a `String`.
///
/// Returns `None` if the command fails to execute or exits with a non-zero
/// status. This is the shared helper for sources that shell out to system
/// utilities (sysctl, vm_stat, ps, ioreg, mdls, etc.).
pub fn run_command(program: &str, args: &[&str]) -> Option<String> {
    let output = run_command_output(program, args)?;
    Some(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Run a subprocess command and return its raw stdout bytes.
///
/// Returns `None` if the command fails to execute or exits with a non-zero
/// status.
pub fn run_command_raw(program: &str, args: &[&str]) -> Option<Vec<u8>> {
    run_command_output(program, args).map(|o| o.stdout)
}

/// Run a subprocess command with timeout and return raw stdout bytes.
pub fn run_command_raw_timeout(program: &str, args: &[&str], timeout_ms: u64) -> Option<Vec<u8>> {
    run_command_output_timeout(program, args, timeout_ms).map(|o| o.stdout)
}

/// Capture one grayscale frame from the camera via ffmpeg/avfoundation.
///
/// If `device_index` is `Some(n)`, only the selector `"{n}:none"` is tried.
/// If `None`, tries common avfoundation input selectors in fallback order
/// (`default:none`, `0:none`, `1:none`, `0:0`). Returns raw 8-bit grayscale
/// bytes when any selector succeeds.
pub fn capture_camera_gray_frame(timeout_ms: u64, device_index: Option<u32>) -> Option<Vec<u8>> {
    match device_index {
        Some(n) => {
            let input = format!("{n}:none");
            capture_camera_with_inputs(timeout_ms, &[&input])
        }
        None => {
            capture_camera_with_inputs(timeout_ms, &["default:none", "0:none", "1:none", "0:0"])
        }
    }
}

fn capture_camera_with_inputs(timeout_ms: u64, inputs: &[&str]) -> Option<Vec<u8>> {
    for &input in inputs {
        let args = [
            "-hide_banner",
            "-loglevel",
            "error",
            "-nostdin",
            "-f",
            "avfoundation",
            "-framerate",
            "30",
            "-i",
            input,
            "-frames:v",
            "1",
            "-f",
            "rawvideo",
            "-pix_fmt",
            "gray",
            "pipe:1",
        ];
        if let Some(frame) = run_command_raw_timeout("ffmpeg", &args, timeout_ms)
            && !frame.is_empty()
        {
            return Some(frame);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// ARM counter (CNTVCT_EL0)
// ---------------------------------------------------------------------------

/// Read the ARM generic timer counter (CNTVCT_EL0) directly.
///
/// Returns the raw hardware counter driven by the CPU's 24 MHz crystal oscillator,
/// independent of any OS abstraction layer. Used by frontier sources that measure
/// clock domain crossings against independent PLLs (audio, display, PCIe).
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
#[inline(always)]
pub fn read_cntvct() -> u64 {
    let val: u64;
    // SAFETY: CNTVCT_EL0 is always readable from EL0 on Apple Silicon.
    // Read-only system register, no side effects.
    unsafe {
        std::arch::asm!("mrs {}, cntvct_el0", out(reg) val, options(nostack, nomem));
    }
    val
}

#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
#[inline(always)]
pub fn read_cntvct() -> u64 {
    0
}

// ---------------------------------------------------------------------------
// Safe JIT instruction probe
// ---------------------------------------------------------------------------

/// Test whether a JIT-generated ARM64 instruction can execute without SIGILL.
///
/// Forks a child process that builds a MAP_JIT page with the given instruction
/// followed by RET, executes it, and exits. If the child exits normally (status 0),
/// the instruction is safe. If it crashes (SIGILL), only the child dies.
///
/// Returns `true` if the instruction executed successfully.
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
pub fn probe_jit_instruction_safe(mrs_instr: u32) -> bool {
    // Fork: child tests the instruction, parent waits for result.
    let pid = unsafe { libc::fork() };
    if pid < 0 {
        return false; // fork failed
    }
    if pid == 0 {
        // Child process: build JIT page, execute, exit
        let page = unsafe {
            libc::mmap(
                std::ptr::null_mut(),
                4096,
                libc::PROT_READ | libc::PROT_WRITE | libc::PROT_EXEC,
                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | 0x0800, // MAP_JIT
                -1,
                0,
            )
        };
        if page == libc::MAP_FAILED {
            unsafe { libc::_exit(1) };
        }
        unsafe {
            libc::pthread_jit_write_protect_np(0);
            let code = page as *mut u32;
            code.write(mrs_instr);
            code.add(1).write(0xD65F03C0u32); // RET
            libc::pthread_jit_write_protect_np(1);
            core::arch::asm!("dc cvau, {p}", "ic ivau, {p}", p = in(reg) page, options(nostack));
            core::arch::asm!("dsb ish", "isb", options(nostack));
        }
        type FnPtr = unsafe extern "C" fn() -> u64;
        let fn_ptr: FnPtr = unsafe { std::mem::transmute(page) };
        let _val = unsafe { fn_ptr() };
        unsafe {
            libc::munmap(page, 4096);
            libc::_exit(0); // Success — instruction didn't trap
        }
    }
    // Parent: wait for child
    let mut status: libc::c_int = 0;
    let ret = unsafe { libc::waitpid(pid, &mut status, 0) };
    if ret < 0 {
        return false;
    }
    // Check child exited normally with status 0
    libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0
}

// ---------------------------------------------------------------------------
// XOR-fold
// ---------------------------------------------------------------------------

/// XOR-fold all 8 bytes of a `u64` into a single byte.
///
/// Preserves entropy from every byte position instead of discarding the
/// upper 7 bytes. Used by timing-based sources where entropy is spread
/// across multiple byte positions.
#[inline]
pub fn xor_fold_u64(v: u64) -> u8 {
    let b = v.to_le_bytes();
    b[0] ^ b[1] ^ b[2] ^ b[3] ^ b[4] ^ b[5] ^ b[6] ^ b[7]
}

// ---------------------------------------------------------------------------
// Timing entropy extraction
// ---------------------------------------------------------------------------

/// Extract entropy bytes from a slice of raw timestamps.
///
/// Computes consecutive deltas, XORs adjacent deltas for mixing, then
/// XOR-folds each 8-byte value into one output byte. Returns at most
/// `n_samples` bytes.
///
/// Requires at least 4 input timings to produce any output (2 deltas
/// needed for the XOR mixing step).
pub fn extract_timing_entropy(timings: &[u64], n_samples: usize) -> Vec<u8> {
    if timings.len() < 2 {
        return Vec::new();
    }

    let deltas: Vec<u64> = timings
        .windows(2)
        .map(|w| w[1].wrapping_sub(w[0]))
        .collect();

    // XOR consecutive deltas for mixing (not conditioning — just combines adjacent values)
    let xored: Vec<u64> = deltas.windows(2).map(|w| w[0] ^ w[1]).collect();

    // XOR-fold all 8 bytes of each value into one byte
    let mut raw: Vec<u8> = xored.iter().map(|&x| xor_fold_u64(x)).collect();
    raw.truncate(n_samples);
    raw
}

// ---------------------------------------------------------------------------
// Nibble packing
// ---------------------------------------------------------------------------

/// Pack pairs of 4-bit nibbles into bytes.
///
/// Used by audio and camera sources to pack noise LSBs efficiently.
/// Returns at most `max_bytes` output bytes.
pub fn pack_nibbles(nibbles: impl Iterator<Item = u8>, max_bytes: usize) -> Vec<u8> {
    let mut output = Vec::with_capacity(max_bytes);
    let mut buf: u8 = 0;
    let mut count: u8 = 0;

    for nibble in nibbles {
        if count == 0 {
            buf = nibble << 4;
            count = 1;
        } else {
            buf |= nibble;
            output.push(buf);
            count = 0;
            if output.len() >= max_bytes {
                break;
            }
        }
    }

    // If we have an odd nibble left and still need more, include it.
    if count == 1 && output.len() < max_bytes {
        output.push(buf);
    }

    output.truncate(max_bytes);
    output
}

// ---------------------------------------------------------------------------
// i64 delta byte extraction (sysctl/vmstat/ioregistry pattern)
// ---------------------------------------------------------------------------

/// Extract entropy bytes from a list of i64 deltas.
///
/// First emits raw LE bytes from all deltas, then XOR'd consecutive delta bytes
/// if more output is needed. Returns at most `n_samples` bytes.
pub fn extract_delta_bytes_i64(deltas: &[i64], n_samples: usize) -> Vec<u8> {
    // XOR consecutive deltas for extra mixing
    let xor_deltas: Vec<i64> = if deltas.len() >= 2 {
        deltas.windows(2).map(|w| w[0] ^ w[1]).collect()
    } else {
        Vec::new()
    };

    let mut entropy = Vec::with_capacity(n_samples);

    // First: raw LE bytes from all non-zero deltas
    for d in deltas {
        for &b in &d.to_le_bytes() {
            entropy.push(b);
        }
        if entropy.len() >= n_samples {
            entropy.truncate(n_samples);
            return entropy;
        }
    }

    // Then: XOR'd delta bytes for more mixing
    for d in &xor_deltas {
        for &b in &d.to_le_bytes() {
            entropy.push(b);
        }
        if entropy.len() >= n_samples {
            break;
        }
    }

    entropy.truncate(n_samples);
    entropy
}

// ---------------------------------------------------------------------------
// Von Neumann debiased timing extraction
// ---------------------------------------------------------------------------

/// Von Neumann debiased timing extraction.
///
/// Takes pairs of consecutive timing deltas. If they differ, emit one bit
/// based on their relative order (first < second → 1, else → 0). This
/// removes bias from the raw timing stream at the cost of ~50% data loss.
#[cfg(target_os = "macos")]
pub fn extract_timing_entropy_debiased(timings: &[u64], n_samples: usize) -> Vec<u8> {
    if timings.len() < 4 {
        return Vec::new();
    }

    let deltas: Vec<u64> = timings
        .windows(2)
        .map(|w| w[1].wrapping_sub(w[0]))
        .collect();

    // Von Neumann debias: take pairs, discard equal, emit comparison bit.
    let mut debiased_bits: Vec<u8> = Vec::with_capacity(deltas.len() / 2);
    for pair in deltas.chunks_exact(2) {
        if pair[0] != pair[1] {
            debiased_bits.push(if pair[0] < pair[1] { 1 } else { 0 });
        }
    }

    // Pack bits into bytes (only full bytes).
    let mut bytes = Vec::with_capacity(n_samples);
    for chunk in debiased_bits.chunks(8) {
        if chunk.len() < 8 {
            break;
        }
        let mut byte = 0u8;
        for (i, &bit) in chunk.iter().enumerate() {
            byte |= bit << (7 - i);
        }
        bytes.push(byte);
        if bytes.len() >= n_samples {
            break;
        }
    }
    bytes.truncate(n_samples);
    bytes
}

// ---------------------------------------------------------------------------
// Timing variance extraction
// ---------------------------------------------------------------------------

/// Extract entropy from timing variance (delta-of-deltas).
///
/// Computes first-order deltas, then second-order deltas (capturing the
/// *change* in timing). This removes systematic bias and amplifies the
/// nondeterministic component.
pub fn extract_timing_entropy_variance(timings: &[u64], n_samples: usize) -> Vec<u8> {
    if timings.len() < 4 {
        return Vec::new();
    }

    let deltas: Vec<u64> = timings
        .windows(2)
        .map(|w| w[1].wrapping_sub(w[0]))
        .collect();

    let variance: Vec<u64> = deltas.windows(2).map(|w| w[1].wrapping_sub(w[0])).collect();

    let xored: Vec<u64> = variance.windows(2).map(|w| w[0] ^ w[1]).collect();

    let mut raw: Vec<u8> = xored.iter().map(|&x| xor_fold_u64(x)).collect();
    raw.truncate(n_samples);
    raw
}

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

    // -----------------------------------------------------------------------
    // LSB extraction tests
    // -----------------------------------------------------------------------

    #[test]
    fn extract_lsbs_u64_basic() {
        // 8 values with alternating LSBs: 0,1,0,1,0,1,0,1 → 0b01010101 = 0x55
        let deltas = vec![2, 3, 4, 5, 6, 7, 8, 9];
        let bytes = extract_lsbs_u64(&deltas);
        assert_eq!(bytes.len(), 1);
        assert_eq!(bytes[0], 0b01010101);
    }

    #[test]
    fn extract_lsbs_i64_basic() {
        let deltas = vec![2i64, 3, 4, 5, 6, 7, 8, 9];
        let bytes = extract_lsbs_i64(&deltas);
        assert_eq!(bytes.len(), 1);
        assert_eq!(bytes[0], 0b01010101);
    }

    #[test]
    fn extract_lsbs_u64_empty() {
        let bytes = extract_lsbs_u64(&[]);
        assert!(bytes.is_empty());
    }

    #[test]
    fn extract_lsbs_i64_empty() {
        let bytes = extract_lsbs_i64(&[]);
        assert!(bytes.is_empty());
    }

    #[test]
    fn extract_lsbs_u64_all_odd() {
        // All odd -> all LSBs are 1 -> 0xFF
        let deltas = vec![1u64, 3, 5, 7, 9, 11, 13, 15];
        let bytes = extract_lsbs_u64(&deltas);
        assert_eq!(bytes[0], 0xFF);
    }

    #[test]
    fn extract_lsbs_u64_all_even() {
        // All even -> all LSBs are 0 -> 0x00
        let deltas = vec![0u64, 2, 4, 6, 8, 10, 12, 14];
        let bytes = extract_lsbs_u64(&deltas);
        assert_eq!(bytes[0], 0x00);
    }

    #[test]
    fn extract_lsbs_partial_byte() {
        // 5 values -> only 5 bits, not enough for a full byte -> empty
        let deltas = vec![1u64, 0, 1, 0, 1];
        let bytes = extract_lsbs_u64(&deltas);
        assert!(bytes.is_empty());
    }

    #[test]
    fn extract_lsbs_u64_i64_agree() {
        // Same absolute values should produce same LSBs
        let u_deltas = vec![1u64, 2, 3, 4, 5, 6, 7, 8];
        let i_deltas = vec![1i64, 2, 3, 4, 5, 6, 7, 8];
        assert_eq!(extract_lsbs_u64(&u_deltas), extract_lsbs_i64(&i_deltas));
    }

    // -----------------------------------------------------------------------
    // pack_bits_into_bytes tests
    // -----------------------------------------------------------------------

    #[test]
    fn pack_bits_empty() {
        let bits: Vec<u8> = vec![];
        let bytes = pack_bits_into_bytes(&bits);
        assert!(bytes.is_empty());
    }

    #[test]
    fn pack_bits_full_byte() {
        let bits = vec![1, 0, 1, 0, 1, 0, 1, 0];
        let bytes = pack_bits_into_bytes(&bits);
        assert_eq!(bytes, vec![0b10101010]);
    }

    // -----------------------------------------------------------------------
    // mach_time tests
    // -----------------------------------------------------------------------

    #[test]
    fn mach_time_is_monotonic() {
        let t1 = mach_time();
        let t2 = mach_time();
        assert!(t2 >= t1);
    }

    // -----------------------------------------------------------------------
    // pack_nibbles tests
    // -----------------------------------------------------------------------

    #[test]
    fn pack_nibbles_basic() {
        let nibbles = vec![0x0A_u8, 0x0B];
        let bytes = pack_nibbles(nibbles.into_iter(), 10);
        assert_eq!(bytes.len(), 1);
        assert_eq!(bytes[0], 0xAB);
    }

    #[test]
    fn pack_nibbles_empty() {
        let bytes = pack_nibbles(std::iter::empty(), 10);
        assert!(bytes.is_empty());
    }

    #[test]
    fn pack_nibbles_odd_count() {
        let nibbles = vec![0x0C_u8, 0x0D, 0x0E];
        let bytes = pack_nibbles(nibbles.into_iter(), 10);
        assert_eq!(bytes.len(), 2);
        assert_eq!(bytes[0], 0xCD);
        assert_eq!(bytes[1], 0xE0); // odd nibble shifted left
    }

    #[test]
    fn pack_nibbles_respects_max() {
        let nibbles = vec![0x01_u8, 0x02, 0x03, 0x04, 0x05, 0x06];
        let bytes = pack_nibbles(nibbles.into_iter(), 2);
        assert_eq!(bytes.len(), 2);
    }

    // -----------------------------------------------------------------------
    // extract_delta_bytes_i64 tests
    // -----------------------------------------------------------------------

    #[test]
    fn extract_delta_bytes_empty() {
        let bytes = extract_delta_bytes_i64(&[], 10);
        assert!(bytes.is_empty());
    }

    #[test]
    fn extract_delta_bytes_single_delta() {
        let deltas = vec![0x0102030405060708i64];
        let bytes = extract_delta_bytes_i64(&deltas, 8);
        // LE bytes of the delta
        assert_eq!(bytes, 0x0102030405060708i64.to_le_bytes().to_vec());
    }

    #[test]
    fn extract_delta_bytes_truncated() {
        let deltas = vec![0x0102030405060708i64];
        let bytes = extract_delta_bytes_i64(&deltas, 4);
        assert_eq!(bytes.len(), 4);
        assert_eq!(bytes, &0x0102030405060708i64.to_le_bytes()[..4]);
    }

    #[test]
    fn extract_delta_bytes_with_xor_mixing() {
        // Two deltas -> also produces XOR'd delta bytes for extra output
        let deltas = vec![100i64, 200];
        let bytes = extract_delta_bytes_i64(&deltas, 24);
        // 2 deltas * 8 bytes = 16 raw LE bytes + 1 XOR'd delta * 8 bytes = 24 total
        assert_eq!(bytes.len(), 24);
    }

    #[test]
    fn extract_delta_bytes_respects_n_samples() {
        let deltas: Vec<i64> = (1..=100).collect();
        let bytes = extract_delta_bytes_i64(&deltas, 50);
        assert_eq!(bytes.len(), 50);
    }

    // -----------------------------------------------------------------------
    // xor_fold_u64 tests
    // -----------------------------------------------------------------------

    #[test]
    fn xor_fold_u64_zero() {
        assert_eq!(xor_fold_u64(0), 0);
    }

    #[test]
    fn xor_fold_u64_identical_bytes() {
        // All bytes the same: XOR-fold of 8 identical bytes = 0 (even count)
        assert_eq!(xor_fold_u64(0x0101010101010101), 0);
    }

    #[test]
    fn xor_fold_u64_single_byte() {
        assert_eq!(xor_fold_u64(0xFF), 0xFF);
    }

    #[test]
    fn xor_fold_u64_two_bytes() {
        // 0xAA ^ 0xBB = 0x11
        assert_eq!(xor_fold_u64(0xBB_00_00_00_00_00_00_AA), 0xAA ^ 0xBB);
    }

    #[test]
    fn xor_fold_u64_max() {
        // All 0xFF bytes: XOR of 8 identical = 0 (even count)
        assert_eq!(xor_fold_u64(u64::MAX), 0);
    }

    // -----------------------------------------------------------------------
    // extract_timing_entropy tests
    // -----------------------------------------------------------------------

    #[test]
    fn extract_timing_entropy_basic() {
        let timings = vec![100, 110, 105, 120, 108, 130, 112, 125];
        let result = extract_timing_entropy(&timings, 4);
        assert!(!result.is_empty());
        assert!(result.len() <= 4);
    }

    #[test]
    fn extract_timing_entropy_too_few_samples() {
        assert!(extract_timing_entropy(&[], 10).is_empty());
        assert!(extract_timing_entropy(&[42], 10).is_empty());
    }

    #[test]
    fn extract_timing_entropy_exactly_two_timings() {
        // 2 timings → 1 delta → 0 XOR'd pairs → empty
        let result = extract_timing_entropy(&[100, 200], 10);
        assert!(result.is_empty());
    }

    #[test]
    fn extract_timing_entropy_exactly_three_timings() {
        // 3 timings → 2 deltas → 1 XOR'd pair → 1 byte
        let result = extract_timing_entropy(&[100, 200, 150], 10);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn extract_timing_entropy_truncates_to_n_samples() {
        let timings: Vec<u64> = (0..100).collect();
        let result = extract_timing_entropy(&timings, 5);
        assert_eq!(result.len(), 5);
    }

    #[test]
    fn extract_timing_entropy_constant_timings() {
        // Constant timings → all deltas are 0 → XOR of 0s = 0 → all zeros
        let timings = vec![42u64; 20];
        let result = extract_timing_entropy(&timings, 10);
        assert!(result.iter().all(|&b| b == 0));
    }

    // -----------------------------------------------------------------------
    // run_command / run_command_raw tests
    // -----------------------------------------------------------------------

    #[test]
    fn run_command_echo() {
        let out = run_command("echo", &["hello"]);
        assert!(out.is_some());
        assert_eq!(out.unwrap().trim(), "hello");
    }

    #[test]
    fn run_command_nonexistent() {
        let out = run_command("/nonexistent/binary", &[]);
        assert!(out.is_none());
    }

    #[test]
    fn run_command_raw_echo() {
        let out = run_command_raw("echo", &["bytes"]);
        assert!(out.is_some());
        assert!(out.unwrap().starts_with(b"bytes"));
    }

    #[test]
    fn run_command_failing_status() {
        // `false` always exits with status 1
        let out = run_command("false", &[]);
        assert!(out.is_none());
    }

    #[test]
    fn run_command_raw_failing_status() {
        let out = run_command_raw("false", &[]);
        assert!(out.is_none());
    }

    #[test]
    fn run_command_empty_output() {
        // `true` exits 0 with no output
        let out = run_command("true", &[]);
        assert!(out.is_some());
        assert!(out.unwrap().is_empty());
    }

    #[test]
    fn command_exists_true() {
        assert!(command_exists("echo"));
    }

    #[test]
    fn command_exists_false() {
        assert!(!command_exists("nonexistent_binary_xyz_12345"));
    }

    // -----------------------------------------------------------------------
    // extract_timing_entropy_debiased tests
    // -----------------------------------------------------------------------

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    #[test]
    fn debiased_extraction_basic() {
        let timings: Vec<u64> = (0..200).map(|i| 100 + (i * 7 + i * i) % 50).collect();
        let result = extract_timing_entropy_debiased(&timings, 10);
        assert!(result.len() <= 10);
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    #[test]
    fn debiased_extraction_too_few() {
        assert!(extract_timing_entropy_debiased(&[1, 2, 3], 10).is_empty());
        assert!(extract_timing_entropy_debiased(&[], 10).is_empty());
    }

    #[cfg(all(target_os = "macos", target_arch = "aarch64"))]
    #[test]
    fn debiased_extraction_constant_input() {
        let timings = vec![42u64; 100];
        let result = extract_timing_entropy_debiased(&timings, 10);
        assert!(result.is_empty());
    }

    // -----------------------------------------------------------------------
    // extract_timing_entropy_variance tests
    // -----------------------------------------------------------------------

    #[test]
    fn variance_extraction_basic() {
        let timings: Vec<u64> = (0..100).map(|i| 100 + (i * 7 + i * i) % 50).collect();
        let result = extract_timing_entropy_variance(&timings, 10);
        assert!(!result.is_empty());
        assert!(result.len() <= 10);
    }

    #[test]
    fn variance_extraction_too_few() {
        assert!(extract_timing_entropy_variance(&[1, 2, 3], 10).is_empty());
    }
}