circuits_lib/common/
zkvm.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::io::Write;

use borsh::BorshDeserialize;
use risc0_zkvm::guest::env::{self};

pub trait ZkvmGuest {
    fn read_from_host<T: borsh::BorshDeserialize>(&self) -> T;
    fn commit<T: borsh::BorshSerialize>(&self, item: &T);
    fn verify<T: borsh::BorshSerialize>(&self, method_id: [u32; 8], journal: &T);
}

#[derive(Debug, Clone)]
pub struct Proof {
    pub method_id: [u32; 8],
    pub journal: Vec<u8>,
}

pub trait ZkvmHost {
    // Adding data to the host
    fn write<T: borsh::BorshSerialize>(&self, value: &T);

    fn add_assumption(&self, proof: Proof);

    // Proves with the given data
    fn prove(&self, elf: &[u32]) -> Proof;
}

#[derive(Debug, Clone)]
pub struct Risc0Guest;

impl Risc0Guest {
    pub fn new() -> Self {
        Self {}
    }
}

impl Default for Risc0Guest {
    fn default() -> Self {
        Self::new()
    }
}

impl ZkvmGuest for Risc0Guest {
    /// This uses little endianness in the items it deserializes
    fn read_from_host<T: borsh::BorshDeserialize>(&self) -> T {
        let mut reader = env::stdin();
        BorshDeserialize::deserialize_reader(&mut reader)
            .expect("Failed to deserialize input from host")
    }

    /// This uses little endianness in the items it serializes
    fn commit<T: borsh::BorshSerialize>(&self, item: &T) {
        // use risc0_zkvm::guest::env::Write as _;
        let buf = borsh::to_vec(item).expect("Serialization to vec is infallible");
        let mut journal = env::journal();
        journal.write_all(&buf).unwrap();
    }

    fn verify<T: borsh::BorshSerialize>(&self, method_id: [u32; 8], output: &T) {
        env::verify(method_id, &borsh::to_vec(output).unwrap()).unwrap();
    }
}