From d4ae55609c4026cef5936aaf9d93c35566f740a7 Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Wed, 21 Dec 2022 13:38:18 -0800 Subject: [PATCH] Add a way to get a random `u64`. This anticipates https://github.com/WebAssembly/wasi-random/pull/18. --- host/src/random.rs | 6 +++++- src/lib.rs | 2 +- wit/wasi.wit | 11 ++++++++++- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/host/src/random.rs b/host/src/random.rs index 35a5f816..36c76aa8 100644 --- a/host/src/random.rs +++ b/host/src/random.rs @@ -4,10 +4,14 @@ use crate::{wasi_random, WasiCtx}; #[async_trait::async_trait] impl wasi_random::WasiRandom for WasiCtx { - async fn getrandom(&mut self, len: u32) -> anyhow::Result> { + async fn get_random_bytes(&mut self, len: u32) -> anyhow::Result> { Ok((&mut self.random) .sample_iter(Standard) .take(len as usize) .collect()) } + + async fn get_random_u64(&mut self) -> anyhow::Result { + Ok((&mut self.random).sample(Standard)) + } } diff --git a/src/lib.rs b/src/lib.rs index 16bf4d48..f105f667 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1474,7 +1474,7 @@ pub unsafe extern "C" fn random_get(buf: *mut u8, buf_len: Size) -> Errno { state.register_buffer(buf, buf_len); assert_eq!(buf_len as u32 as Size, buf_len); - let result = wasi_random::getrandom(buf_len as u32); + let result = wasi_random::get_random_bytes(buf_len as u32); assert_eq!(result.as_ptr(), buf); // The returned buffer's memory was allocated in `buf`, so don't separately diff --git a/wit/wasi.wit b/wit/wasi.wit index 3f2faa6e..da050637 100644 --- a/wit/wasi.wit +++ b/wit/wasi.wit @@ -151,7 +151,16 @@ interface wasi-random { /// /// Deterministic environments must omit this function, rather than /// implementing it with deterministic data. - getrandom: func(len: u32) -> list + get-random-bytes: func(len: u32) -> list + + /// Return a random `u64` value. + /// + /// This function must produce data from an adaquately seeded CSPRNG, so it + /// must not block, and the returned data is always unpredictable. + /// + /// Deterministic environments must omit this function, rather than + /// implementing it with deterministic data. + get-random-u64: func() -> u64 /// A value containing 128 random bits. ///