sp1_core_executor/
io.rs

1use std::io::Read;
2
3use serde::{de::DeserializeOwned, Serialize};
4use sp1_stark::{baby_bear_poseidon2::BabyBearPoseidon2, SP1ReduceProof, StarkVerifyingKey};
5
6use super::Executor;
7
8impl Read for Executor<'_> {
9    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
10        self.read_public_values_slice(buf);
11        Ok(buf.len())
12    }
13}
14
15impl Executor<'_> {
16    /// Write a serializable input to the standard input stream.
17    pub fn write_stdin<T: Serialize>(&mut self, input: &T) {
18        let mut buf = Vec::new();
19        bincode::serialize_into(&mut buf, input).expect("serialization failed");
20        self.state.input_stream.push_back(buf);
21    }
22
23    /// Write a slice of bytes to the standard input stream.
24    pub fn write_stdin_slice(&mut self, input: &[u8]) {
25        self.state.input_stream.push_back(input.to_vec());
26    }
27
28    /// Write a slice of vecs to the standard input stream.
29    pub fn write_vecs(&mut self, inputs: &[Vec<u8>]) {
30        for input in inputs {
31            self.state.input_stream.push_back(input.clone());
32        }
33    }
34
35    /// Write a proof and verifying key to the proof stream.
36    pub fn write_proof(
37        &mut self,
38        proof: SP1ReduceProof<BabyBearPoseidon2>,
39        vk: StarkVerifyingKey<BabyBearPoseidon2>,
40    ) {
41        self.state.proof_stream.push((proof, vk));
42    }
43
44    /// Read a serializable public values from the public values stream.
45    pub fn read_public_values<T: DeserializeOwned>(&mut self) -> T {
46        let result = bincode::deserialize_from::<_, T>(self);
47        result.unwrap()
48    }
49
50    /// Read a slice of bytes from the public values stream.
51    pub fn read_public_values_slice(&mut self, buf: &mut [u8]) {
52        let len = buf.len();
53        let start = self.state.public_values_stream_ptr;
54        let end = start + len;
55        assert!(end <= self.state.public_values_stream.len());
56        buf.copy_from_slice(&self.state.public_values_stream[start..end]);
57        self.state.public_values_stream_ptr = end;
58    }
59}