Skip to main content

deterministic_wasi_ctx/
lib.rs

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