deterministic_wasi_ctx/
lib.rs

1mod clocks;
2#[cfg(feature = "wasi-common")]
3mod legacy;
4mod scheduling;
5
6use clocks::{DeterministicMonotonicClock, DeterministicWallClock};
7#[cfg(feature = "wasi-common")]
8pub use legacy::build_wasi_ctx;
9use rand_core::SeedableRng;
10use rand_pcg::Pcg64Mcg;
11pub use scheduling::{
12    replace_scheduling_functions, replace_scheduling_functions_for_wasi_preview_0,
13};
14use wasmtime_wasi::p2::WasiCtxBuilder;
15
16pub fn add_determinism_to_wasi_ctx_builder(
17    wasi_builder: &mut WasiCtxBuilder,
18) -> &mut WasiCtxBuilder {
19    // Using Pcg64Mcg because it balances memory usage, performance, is adequately random, does not have major issues,
20    // and has reproducible results across different platforms. SmallRng and StdRng were considered but are documented
21    // as deterministic but not reproducible.
22    // See https://rust-random.github.io/book/guide-rngs.html#basic-pseudo-random-number-generators-prngs
23    // and https://docs.rs/rand_pcg/latest/rand_pcg/struct.Mcg128Xsl64.html for further details.
24    const RANDOM_SEED: u64 = 42; // the answer to life, the universe, and everything
25    let random = Box::new(Pcg64Mcg::seed_from_u64(RANDOM_SEED));
26
27    wasi_builder
28        .allow_tcp(false)
29        .allow_udp(false)
30        .insecure_random(random.clone())
31        .secure_random(random)
32        .wall_clock(DeterministicWallClock)
33        .monotonic_clock(DeterministicMonotonicClock)
34}