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
//! WebAssembly entropy backends for [`OsRng`](super::OsRng).
//!
//! `wasm32` has no ambient operating-system CSPRNG the way Unix (`/dev/urandom`)
//! or Windows (`ProcessPrng`) do, so entropy must be routed in from the host.
//! Two interchangeable backends are provided here, selected purely by the build
//! target (and, for WASI, one opt-in feature) — mirroring how `linux-getrandom`
//! selects between `getrandom(2)` and `/dev/urandom` on Linux:
//!
//! * **Browser / generic host** — `wasm32-unknown-unknown`. Calls an imported
//! host function `purecrypto.random_get(ptr, len)` that the embedder must
//! supply, typically wired to `crypto.getRandomValues` in the browser or
//! `crypto.randomFillSync` under Node. There is no error return (matching the
//! other platforms' [`OsRng`]): the host glue MUST fill the whole buffer or
//! trap. If the import is absent the module fails to instantiate.
//!
//! * **WASI preview 1** — `wasm32-wasip1` with the `wasi-getrandom` feature.
//! Calls `random_get` from the `wasi_snapshot_preview1` module; no host glue
//! is needed because the WASI runtime provides it.
//!
//! Example browser wiring (JS), given the instance's linear `memory`:
//!
//! ```js
//! const imports = {
//! purecrypto: {
//! random_get(ptr, len) {
//! const buf = new Uint8Array(memory.buffer, ptr, len);
//! // crypto.getRandomValues caps at 65536 bytes per call — chunk it.
//! for (let off = 0; off < len; off += 65536) {
//! crypto.getRandomValues(buf.subarray(off, Math.min(off + 65536, len)));
//! }
//! },
//! },
//! };
//! ```
// `rng/` is one of the two crate-wide `unsafe_code = "deny"` carve-outs; the
// only `unsafe` here is the FFI declaration of the host entropy import.
use ;
/// Operating-system entropy source (WebAssembly).
///
/// Draws from the host: the imported `purecrypto.random_get` on
/// `wasm32-unknown-unknown`, or `wasi_snapshot_preview1::random_get` on
/// `wasm32-wasip1` (feature `wasi-getrandom`).
;
// --- Browser / generic host import backend --------------------------------
// --- WASI preview 1 backend -----------------------------------------------