vrf_wasm/rng/
browser.rs

1//! Browser-specific RNG implementation using crypto.getRandomValues()
2
3use getrandom::getrandom;
4use rand_core::{CryptoRng, RngCore};
5use crate::traits::AllowedRng;
6
7/// Browser-compatible RNG using crypto.getRandomValues()
8pub struct WasmRng;
9
10impl CryptoRng for WasmRng {}
11
12impl RngCore for WasmRng {
13    fn next_u32(&mut self) -> u32 {
14        let mut bytes = [0u8; 4];
15        self.fill_bytes(&mut bytes);
16        u32::from_le_bytes(bytes)
17    }
18
19    fn next_u64(&mut self) -> u64 {
20        let mut bytes = [0u8; 8];
21        self.fill_bytes(&mut bytes);
22        u64::from_le_bytes(bytes)
23    }
24
25    fn fill_bytes(&mut self, dest: &mut [u8]) {
26        getrandom(dest).expect("getrandom failed in browser environment");
27    }
28
29    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
30        // getrandom doesn't provide a fallible interface in WASM/browser context
31        // Fall back to fill_bytes which will panic on failure
32        self.fill_bytes(dest);
33        Ok(())
34    }
35}
36
37impl AllowedRng for WasmRng {}
38
39impl Default for WasmRng {
40    fn default() -> Self {
41        Self
42    }
43}
44
45/// WASM-compatible seeded RNG using ChaCha20 for deterministic operations
46pub type WasmRngFromSeed = rand_chacha::ChaCha20Rng;
47
48// Note: AllowedRng for ChaCha20Rng is implemented in traits.rs to avoid conflicts