monerochan_runtime/syscalls/
sys.rs

1use std::sync::Mutex;
2
3use lazy_static::lazy_static;
4use rand::{rngs::StdRng, Rng, SeedableRng};
5
6use crate::syscalls::{syscall_halt, syscall_write};
7
8/// The random number generator seed for the zkVM.
9///
10/// In the future, we can pass in this seed from the host or have the verifier generate it.
11const PRNG_SEED: u64 = 0x123456789abcdef0;
12
13lazy_static! {
14    /// A lazy static to generate a global random number generator.
15    static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::seed_from_u64(PRNG_SEED));
16}
17
18/// A lazy static to print a warning once for using the `sys_rand` system call.
19static SYS_RAND_WARNING: std::sync::Once = std::sync::Once::new();
20
21/// Generates random bytes.
22///
23/// # Safety
24///
25/// Make sure that `buf` has at least `nwords` words.
26#[no_mangle]
27pub unsafe extern "C" fn sys_rand(recv_buf: *mut u8, words: usize) {
28    SYS_RAND_WARNING.call_once(|| {
29        eprintln!("WARNING: Using insecure random number generator.");
30    });
31    let mut rng = RNG.lock().unwrap();
32    for i in 0..words {
33        let element = recv_buf.add(i);
34        *element = rng.gen();
35    }
36}
37
38#[allow(clippy::missing_safety_doc)]
39#[no_mangle]
40pub unsafe extern "C" fn sys_panic(msg_ptr: *const u8, len: usize) -> ! {
41    sys_write(2, msg_ptr, len);
42    syscall_halt(1);
43}
44
45#[allow(unused_variables)]
46#[no_mangle]
47pub const fn sys_getenv(
48    recv_buf: *mut u32,
49    words: usize,
50    varname: *const u8,
51    varname_len: usize,
52) -> usize {
53    usize::MAX
54}
55
56#[allow(unused_variables)]
57#[no_mangle]
58pub const fn sys_alloc_words(nwords: usize) -> *mut u32 {
59    core::ptr::null_mut()
60}
61
62#[allow(unused_unsafe)]
63#[no_mangle]
64pub fn sys_write(fd: u32, write_buf: *const u8, nbytes: usize) {
65    unsafe {
66        syscall_write(fd, write_buf, nbytes);
67    }
68}