use std::time::{SystemTime, UNIX_EPOCH};
use crate::core::error::{QuantumRngError, Result};
const QRNG_FINE_STRUCTURE: u64 = 0x7297352743776A1B;
const QRNG_PLANCK: u64 = 0x6955927086495225;
const QRNG_RYDBERG: u64 = 0x9E3779B97F4A7C15;
const QRNG_ELECTRON_G: u64 = 0x2B992DDFA232945;
const QRNG_GOLDEN_RATIO: u64 = 0x9E3779B97F4A7C15;
const QRNG_HEISENBERG: u64 = 0xC13FA9A902A6328F;
const QRNG_SCHRODINGER: u64 = 0x91E10DA5C79E7B1D;
const QRNG_PAULI_X: u64 = 0x4C957F2D8A1E6B3C;
const QRNG_PAULI_Y: u64 = 0xD3E99E3B6C1A4F78;
const QRNG_PAULI_Z: u64 = 0x8F142FC07892A5B6;
const QRNG_NUM_QUBITS: usize = 8;
const QRNG_STATE_MULTIPLIER: usize = 16;
const QRNG_STATE_SIZE: usize = QRNG_NUM_QUBITS * QRNG_STATE_MULTIPLIER;
const QRNG_BUFFER_SIZE: usize = QRNG_STATE_SIZE;
const QRNG_MIXING_ROUNDS: usize = 4;
pub struct QuantumRNG {
phase: [u64; QRNG_NUM_QUBITS],
entangle: [u64; QRNG_NUM_QUBITS],
quantum_state: [f64; QRNG_NUM_QUBITS],
last_measurement: [u64; QRNG_NUM_QUBITS],
buffer: [u8; QRNG_BUFFER_SIZE],
buffer_pos: usize,
counter: u64,
entropy_pool: [f64; 16],
pool_mixer: u64,
pool_index: u8,
_init_time: SystemTime,
_pid: u32,
unique_id: u64,
system_entropy: u64,
runtime_entropy: u64,
}
impl QuantumRNG {
pub fn new() -> Self {
let mut rng = Self::with_seed(&[]);
rng.init_from_system();
rng
}
pub fn with_seed(seed: &[u8]) -> Self {
let _init_time = SystemTime::now();
let system_entropy = Self::get_system_entropy();
let unique_id = Self::splitmix64(system_entropy);
let mut rng = QuantumRNG {
phase: [0; QRNG_NUM_QUBITS],
entangle: [0; QRNG_NUM_QUBITS],
quantum_state: [0.0; QRNG_NUM_QUBITS],
last_measurement: [0; QRNG_NUM_QUBITS],
buffer: [0; QRNG_BUFFER_SIZE],
buffer_pos: QRNG_BUFFER_SIZE,
counter: 0,
entropy_pool: [0.0; 16],
pool_mixer: QRNG_HEISENBERG ^ unique_id,
pool_index: 0,
_init_time: SystemTime::now(),
_pid: std::process::id(),
unique_id,
system_entropy,
runtime_entropy: 0,
};
rng.reseed(seed);
rng
}
fn init_from_system(&mut self) {
for i in 0..16 {
let entropy_val = Self::quantum_noise(
(self.system_entropy as f64 / u64::MAX as f64) + (i as f64 / 16.0)
);
self.entropy_pool[i] = entropy_val;
}
self.runtime_entropy = self.get_runtime_entropy();
let mut mixer = QRNG_GOLDEN_RATIO ^ self.system_entropy;
for i in 0..QRNG_NUM_QUBITS {
mixer = Self::hadamard_mix(mixer ^ self.runtime_entropy);
self.phase[i] = mixer;
self.entangle[i] = Self::hadamard_gate(mixer);
self.quantum_state[i] = Self::quantum_noise((mixer as f64) / (u64::MAX as f64));
self.last_measurement[i] = 0;
}
for _ in 0..(QRNG_MIXING_ROUNDS * 2) {
self.quantum_step();
}
}
pub fn reseed(&mut self, seed: &[u8]) {
if seed.is_empty() {
return;
}
self.runtime_entropy = self.get_runtime_entropy();
let mut mixer = QRNG_GOLDEN_RATIO ^ self.runtime_entropy;
for (i, &byte) in seed.iter().enumerate() {
if i >= QRNG_NUM_QUBITS {
break;
}
mixer = Self::hadamard_mix(mixer ^ (byte as u64));
self.phase[i] ^= mixer;
self.entangle[i] = Self::hadamard_gate(mixer);
self.quantum_state[i] = Self::quantum_noise((mixer as f64) / (u64::MAX as f64));
}
for _ in 0..(QRNG_MIXING_ROUNDS * 2) {
self.quantum_step();
}
}
pub fn generate_random_bytes(&mut self, length: usize) -> Vec<u8> {
let mut result = vec![0u8; length];
for (_i, byte) in result.iter_mut().enumerate() {
if self.buffer_pos >= QRNG_BUFFER_SIZE {
self.quantum_step();
}
*byte = self.buffer[self.buffer_pos];
self.buffer_pos += 1;
}
result
}
pub fn generate_random_number(&mut self) -> f64 {
let value = self.generate_u64();
(value >> 11) as f64 * (1.0 / 9007199254740992.0)
}
pub fn generate_u64(&mut self) -> u64 {
let bytes = self.generate_random_bytes(8);
let mut result = u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7],
]);
self.runtime_entropy = self.get_runtime_entropy();
result = Self::splitmix64(result ^ self.runtime_entropy);
result ^= QRNG_PAULI_X.wrapping_mul(result >> 27);
result = result.wrapping_mul(QRNG_HEISENBERG);
result ^= QRNG_PAULI_Y.wrapping_mul(result >> 31);
result = result.wrapping_mul(QRNG_SCHRODINGER);
result ^= QRNG_PAULI_Z.wrapping_mul(result >> 29);
result
}
pub fn generate_range_u64(&mut self, min: u64, max: u64) -> u64 {
if min > max {
return max.wrapping_add(1);
}
if min == max {
return min;
}
let range = max - min + 1;
if range == 0 {
return self.generate_u64();
}
let threshold = range.wrapping_neg() % range;
loop {
let r = self.generate_u64();
if r >= threshold {
return min + (r % range);
}
}
}
pub fn generate_range_i32(&mut self, min: i32, max: i32) -> i32 {
if min > max {
return min;
}
let range = (max - min + 1) as u32;
if range == 0 {
return (self.generate_u64() as i32).wrapping_add(min);
}
let threshold = range.wrapping_neg() % range;
loop {
let r = self.generate_u64() as u32;
if r >= threshold {
return min + (r % range) as i32;
}
}
}
pub fn get_entropy_estimate(&mut self) -> f64 {
let mut entropy = 0.0;
for &pool_val in &self.entropy_pool {
if pool_val > 0.0 {
entropy += -pool_val.log2();
}
}
self.runtime_entropy = self.get_runtime_entropy();
entropy += -((self.runtime_entropy & 0xFF) as f64 / 256.0 + 1e-10).log2();
entropy / 17.0 }
pub fn entangle_states(&mut self, state1: &mut [u8], state2: &mut [u8]) -> Result<()> {
if state1.len() != state2.len() {
return Err(QuantumRngError::InvalidLength);
}
self.runtime_entropy = self.get_runtime_entropy();
let mut mixer = Self::splitmix64(self.counter.wrapping_mul(QRNG_GOLDEN_RATIO));
for (s1, s2) in state1.iter_mut().zip(state2.iter_mut()) {
mixer = Self::hadamard_mix(mixer ^ self.runtime_entropy);
let entangled = Self::phase_gate(mixer, mixer >> 32);
*s1 ^= (entangled & 0xFF) as u8;
*s2 ^= ((entangled >> 8) & 0xFF) as u8;
}
for i in 0..QRNG_NUM_QUBITS {
self.quantum_state[i] = Self::quantum_noise(
self.quantum_state[i] + (mixer as f64) / (u64::MAX as f64)
);
}
Ok(())
}
pub fn measure_state(&mut self, state: &mut [u8]) -> Result<()> {
if state.is_empty() {
return Err(QuantumRngError::InvalidLength);
}
self.runtime_entropy = self.get_runtime_entropy();
let mut mixer = Self::splitmix64(self.counter.wrapping_mul(QRNG_GOLDEN_RATIO));
for byte in state.iter_mut() {
mixer = Self::hadamard_mix(mixer ^ self.runtime_entropy);
let measured = self.measure_state_internal(
Self::quantum_noise((mixer as f64) / (u64::MAX as f64)),
mixer
);
*byte = (measured & 0xFF) as u8;
}
for i in 0..QRNG_NUM_QUBITS {
self.quantum_state[i] = Self::quantum_noise(
self.quantum_state[i] + (mixer as f64) / (u64::MAX as f64)
);
}
Ok(())
}
fn quantum_step(&mut self) {
self.counter = self.counter.wrapping_add(1);
let mut mixer = Self::splitmix64(self.counter.wrapping_mul(QRNG_GOLDEN_RATIO));
self.runtime_entropy = self.get_runtime_entropy();
for _ in 0..QRNG_MIXING_ROUNDS {
mixer = Self::hadamard_mix(mixer ^ self.pool_mixer ^ self.runtime_entropy);
for i in 0..QRNG_NUM_QUBITS {
self.phase[i] = Self::hadamard_gate(self.phase[i] ^ mixer);
self.entangle[i] = Self::phase_gate(self.entangle[i], self.phase[i]);
self.quantum_state[i] = Self::quantum_noise(
self.quantum_state[i] + (mixer as f64) / (u64::MAX as f64)
);
}
}
let mut prev = mixer;
let words_in_buffer = QRNG_BUFFER_SIZE / 8;
for i in 0..words_in_buffer {
let current = self.measure_state_internal(
self.quantum_state[i % QRNG_NUM_QUBITS],
prev
);
let bytes = current.to_le_bytes();
let start_idx = i * 8;
if start_idx + 8 <= QRNG_BUFFER_SIZE {
self.buffer[start_idx..start_idx + 8].copy_from_slice(&bytes);
}
prev = current;
}
self.buffer_pos = 0;
}
fn get_runtime_entropy(&self) -> u64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let mut runtime = ((now.as_secs() as u64) << 32) | (now.subsec_micros() as u64);
runtime ^= self.system_entropy;
runtime ^= self.unique_id;
runtime ^= self.counter;
Self::hadamard_mix(runtime)
}
fn get_system_entropy() -> u64 {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
let mut entropy = ((now.as_secs() as u64) << 32) | (now.subsec_micros() as u64);
entropy ^= (std::process::id() as u64) << 32;
let stack_var = 42u64;
entropy ^= &stack_var as *const u64 as u64;
entropy
}
fn quantum_noise(x: f64) -> f64 {
let mut noise = x;
noise = (noise * std::f64::consts::PI).sin() * (noise * std::f64::consts::E).cos();
noise = noise.abs();
let momentum = (noise * QRNG_FINE_STRUCTURE as f64).cos();
let position = (noise * QRNG_PLANCK as f64).sin();
noise = (momentum * momentum + position * position) * 0.5;
noise = (noise * (1.0 - noise)).sqrt();
noise - noise.floor()
}
fn splitmix64(mut x: u64) -> u64 {
x ^= x >> 30;
x = x.wrapping_mul(0xbf58476d1ce4e5b9);
x ^= x >> 27;
x = x.wrapping_mul(0x94d049bb133111eb);
x ^= x >> 31;
x = x.wrapping_mul(QRNG_HEISENBERG);
x ^= x >> 29;
x
}
fn hadamard_mix(mut x: u64) -> u64 {
x = Self::splitmix64(x);
x ^= QRNG_PAULI_X.wrapping_mul(x >> 12);
x = x.wrapping_mul(QRNG_FINE_STRUCTURE);
x ^= QRNG_PAULI_Y.wrapping_mul(x >> 25);
x = x.wrapping_mul(QRNG_PLANCK);
x ^= QRNG_PAULI_Z.wrapping_mul(x >> 27);
x = x.wrapping_mul(QRNG_SCHRODINGER);
x ^= x >> 13;
x
}
fn hadamard_gate(x: u64) -> u64 {
let state = (x as f64) / (u64::MAX as f64);
let noise_state = Self::quantum_noise(state);
let mut superposition = ((noise_state * u64::MAX as f64) as u64) ^ x;
superposition = Self::hadamard_mix(superposition);
let phase = Self::quantum_noise(state + 0.5);
let rotation = (phase * u64::MAX as f64) as u64;
superposition ^= rotation;
Self::hadamard_mix(superposition)
}
fn phase_gate(x: u64, angle: u64) -> u64 {
let phase = Self::quantum_noise((angle as f64) / (u64::MAX as f64));
let mut mixed = (phase * u64::MAX as f64) as u64;
mixed = Self::hadamard_mix(mixed.wrapping_mul(QRNG_RYDBERG));
mixed ^= QRNG_PAULI_X.wrapping_mul(mixed >> 17);
mixed = mixed.wrapping_mul(QRNG_HEISENBERG);
mixed ^= QRNG_PAULI_Y.wrapping_mul(mixed >> 23);
mixed = mixed.wrapping_mul(QRNG_SCHRODINGER);
x ^ mixed
}
fn measure_state_internal(&mut self, quantum_state: f64, last: u64) -> u64 {
self.runtime_entropy = self.get_runtime_entropy();
let collapsed = Self::quantum_noise(
quantum_state + (self.runtime_entropy as f64) / (u64::MAX as f64)
);
self.entropy_pool[self.pool_index as usize] = Self::quantum_noise(
self.entropy_pool[self.pool_index as usize] + collapsed +
(self.runtime_entropy as f64) / (u64::MAX as f64)
);
self.pool_index = (self.pool_index + 1) & 15;
self.pool_mixer = Self::hadamard_mix(
self.pool_mixer ^
((self.entropy_pool[self.pool_index as usize] * u64::MAX as f64) as u64) ^
self.runtime_entropy
);
let mut result = (collapsed * u64::MAX as f64) as u64;
result = Self::hadamard_mix(result ^ last.wrapping_mul(QRNG_ELECTRON_G) ^ self.runtime_entropy);
result ^= QRNG_PAULI_X.wrapping_mul(self.pool_mixer >> 29);
result = result.wrapping_mul(QRNG_HEISENBERG);
result ^= QRNG_PAULI_Y.wrapping_mul(result >> 31);
result = result.wrapping_mul(QRNG_SCHRODINGER);
result ^= QRNG_PAULI_Z.wrapping_mul(result >> 27);
result
}
}
impl Default for QuantumRNG {
fn default() -> Self {
Self::new()
}
}