monerochan_runtime/syscalls/
io.rs

1cfg_if::cfg_if! {
2    if #[cfg(target_os = "zkvm")] {
3        use core::arch::asm;
4        use crate::zkvm;
5        use sha2::digest::Update;
6        use monerochan_primitives::consts::fd::FD_PUBLIC_VALUES;
7    }
8}
9
10/// Write `nbytes` of data to the prover to a given file descriptor `fd` from `write_buf`.
11#[allow(unused_variables)]
12#[no_mangle]
13pub extern "C" fn syscall_write(fd: u32, write_buf: *const u8, nbytes: usize) {
14    cfg_if::cfg_if! {
15        if #[cfg(target_os = "zkvm")] {
16            unsafe {
17                asm!(
18                    "ecall",
19                    in("t0") crate::syscalls::WRITE,
20                    in("a0") fd,
21                    in("a1") write_buf,
22                    in("a2") nbytes,
23                );
24            }
25
26            // For writes to the public values fd, we update a global program hasher with the bytes
27            // being written. At the end of the program, we call the COMMIT ecall with the finalized
28            // version of this hash.
29            if fd == FD_PUBLIC_VALUES {
30                let pi_slice: &[u8] = unsafe { core::slice::from_raw_parts(write_buf, nbytes) };
31                unsafe { zkvm::PUBLIC_VALUES_HASHER.as_mut().unwrap().update(pi_slice) };
32            }
33        } else {
34            unreachable!()
35        }
36    }
37}
38
39/// Returns the length of the next element in the hint stream.
40#[allow(unused_variables)]
41#[no_mangle]
42pub extern "C" fn syscall_hint_len() -> usize {
43    #[cfg(target_os = "zkvm")]
44    unsafe {
45        let len;
46        asm!(
47            "ecall",
48            in("t0") crate::syscalls::HINT_LEN,
49            lateout("t0") len,
50        );
51        len
52    }
53
54    #[cfg(not(target_os = "zkvm"))]
55    unreachable!()
56}
57
58/// Reads the next element in the hint stream into the given buffer.
59#[allow(unused_variables)]
60#[no_mangle]
61pub extern "C" fn syscall_hint_read(ptr: *mut u8, len: usize) {
62    #[cfg(target_os = "zkvm")]
63    unsafe {
64        asm!(
65            "ecall",
66            in("t0") crate::syscalls::HINT_READ,
67            in("a0") ptr,
68            in("a1") len,
69        );
70    }
71
72    #[cfg(not(target_os = "zkvm"))]
73    unreachable!()
74}