rust_qrng 0.1.2

Tsotchkes quantum random number generator library with cryptographic, financial, and gaming applications converted to Rust
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
use std::time::{SystemTime, UNIX_EPOCH};
use crate::core::error::{QuantumRngError, Result};

// Physical constants for quantum operations (ported from C)
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;

// Quantum mixing constants
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;

// Core quantum simulation parameters
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) {
        // Initialize entropy pool with multiple sources
        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;
        }

        // Initialize quantum state with runtime entropy
        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;
        }

        // Additional mixing rounds
        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],
        ]);

        // Enhanced output mixing with runtime entropy
        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 // Average over all sources
    }

    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;
        }

        // Update quantum state
        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;
        }

        // Update quantum context state
        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(())
    }

    // Private helper methods
    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();

        // Enhanced mixing rounds with improved quantum gates
        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)
                );
            }
        }

        // Fill output buffer with improved mixing
        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;
        
        // Use memory address as additional entropy
        let stack_var = 42u64;
        entropy ^= &stack_var as *const u64 as u64;
        
        entropy
    }

    fn quantum_noise(x: f64) -> f64 {
        let mut noise = x;
        
        // Apply quantum uncertainty principle
        noise = (noise * std::f64::consts::PI).sin() * (noise * std::f64::consts::E).cos();
        noise = noise.abs();
        
        // Apply Heisenberg uncertainty
        let momentum = (noise * QRNG_FINE_STRUCTURE as f64).cos();
        let position = (noise * QRNG_PLANCK as f64).sin();
        noise = (momentum * momentum + position * position) * 0.5;
        
        // Quantum tunneling effect
        noise = (noise * (1.0 - noise)).sqrt();
        
        // Normalize to [0,1]
        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);
        
        // Apply quantum superposition
        let mut superposition = ((noise_state * u64::MAX as f64) as u64) ^ x;
        superposition = Self::hadamard_mix(superposition);
        
        // Apply phase rotation
        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));
        
        // Apply quantum entanglement
        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)
        );
        
        // Update entropy pool with runtime entropy
        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;
        
        // Mix entropy pool
        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);
        
        // Apply quantum gates with 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()
    }
}