essential_vm/
state_read.rs

1//! State read operation implementations.
2
3use crate::{
4    error::{MemoryError, OpError, OpResult, StackError, StateReadArgError},
5    Memory, Stack,
6};
7use essential_types::{convert::u8_32_from_word_4, ContentAddress, Key, Value, Word};
8
9#[cfg(test)]
10mod tests;
11
12/// Read-only access to state required by the VM.
13pub trait StateRead {
14    /// An error type describing any cases that might occur during state reading.
15    type Error: core::fmt::Debug + core::fmt::Display;
16
17    /// Read the given number of values from state at the given key associated
18    /// with the given contract address.
19    fn key_range(
20        &self,
21        contract_addr: ContentAddress,
22        key: Key,
23        num_values: usize,
24    ) -> Result<Vec<Vec<Word>>, Self::Error>;
25}
26
27/// Pre and post sync state reads.
28pub trait StateReads {
29    /// Common error type
30    type Error: core::fmt::Debug + core::fmt::Display;
31
32    /// Pre state read
33    type Pre: StateRead<Error = Self::Error>;
34
35    /// Post state read
36    type Post: StateRead<Error = Self::Error>;
37
38    /// Get the pre state read
39    fn pre(&self) -> &Self::Pre;
40
41    /// Get the post state read
42    fn post(&self) -> &Self::Post;
43}
44
45impl<S, P> StateReads for (S, P)
46where
47    S: StateRead,
48    P: StateRead<Error = S::Error>,
49{
50    type Error = S::Error;
51
52    type Pre = S;
53
54    type Post = P;
55
56    fn pre(&self) -> &Self::Pre {
57        &self.0
58    }
59
60    fn post(&self) -> &Self::Post {
61        &self.1
62    }
63}
64/// `StateRead::KeyRange` operation.
65/// Uses a synchronous state read.
66pub fn key_range<S>(
67    state_read: &S,
68    contract_addr: &ContentAddress,
69    stack: &mut Stack,
70    memory: &mut Memory,
71) -> OpResult<(), S::Error>
72where
73    S: StateRead,
74{
75    let mem_addr = pop_memory_address(stack)?;
76    let values = read_key_range(state_read, contract_addr, stack)?;
77    write_values_to_memory(mem_addr, values, memory)?;
78    Ok(())
79}
80
81/// `StateRead::KeyRangeExtern` operation.
82/// Uses a synchronous state read.
83pub fn key_range_ext<S>(
84    state_read: &S,
85    stack: &mut Stack,
86    memory: &mut Memory,
87) -> OpResult<(), S::Error>
88where
89    S: StateRead,
90{
91    let mem_addr = pop_memory_address(stack)?;
92    let values = read_key_range_ext(state_read, stack)?;
93    write_values_to_memory(mem_addr, values, memory)?;
94    Ok(())
95}
96
97/// Read the length and key from the top of the stack and read the associated words from state.
98/// Uses a synchronous state read.
99fn read_key_range<S>(
100    state_read: &S,
101    contract_addr: &ContentAddress,
102    stack: &mut Stack,
103) -> OpResult<Vec<Value>, S::Error>
104where
105    S: StateRead,
106{
107    let (key, num_keys) = pop_key_range_args(stack)?;
108    state_read
109        .key_range(contract_addr.clone(), key, num_keys)
110        .map_err(OpError::StateRead)
111}
112
113/// Read the length, key and external contract address from the top of the stack and
114/// read the associated words from state.
115/// Uses a synchronous state read.
116fn read_key_range_ext<S>(state_read: &S, stack: &mut Stack) -> OpResult<Vec<Value>, S::Error>
117where
118    S: StateRead,
119{
120    let (key, num_keys) = pop_key_range_args(stack)?;
121    let contract_addr = ContentAddress(u8_32_from_word_4(stack.pop4()?));
122    state_read
123        .key_range(contract_addr, key, num_keys)
124        .map_err(OpError::StateRead)
125}
126
127/// Pop the memory address that the state read will write to from the stack.
128fn pop_memory_address(stack: &mut Stack) -> Result<usize, StateReadArgError> {
129    let mem_addr = stack.pop()?;
130    let mem_addr = usize::try_from(mem_addr).map_err(|_| MemoryError::IndexOutOfBounds)?;
131    Ok(mem_addr)
132}
133
134/// Pop the key and number of keys from the stack.
135fn pop_key_range_args(stack: &mut Stack) -> Result<(Key, usize), StackError> {
136    let num_keys = stack.pop()?;
137    let num_keys = usize::try_from(num_keys).map_err(|_| StackError::IndexOutOfBounds)?;
138    let key = stack.pop_len_words::<_, _, StackError>(|words| Ok(words.to_vec()))?;
139    Ok((key, num_keys))
140}
141
142/// Write the given values to memory.
143fn write_values_to_memory(
144    mem_addr: usize,
145    values: Vec<Vec<Word>>,
146    memory: &mut Memory,
147) -> Result<(), MemoryError> {
148    let values_len = Word::try_from(values.len()).map_err(|_| MemoryError::Overflow)?;
149    let index_len_pairs_len = values_len.checked_mul(2).ok_or(MemoryError::Overflow)?;
150    let mut mem_addr = Word::try_from(mem_addr).map_err(|_| MemoryError::IndexOutOfBounds)?;
151    let mut value_addr = mem_addr
152        .checked_add(index_len_pairs_len)
153        .ok_or(MemoryError::Overflow)?;
154    for value in values {
155        let value_len = Word::try_from(value.len()).map_err(|_| MemoryError::Overflow)?;
156        // Write the [index, len] pair.
157        memory.store_range(mem_addr, &[value_addr, value_len])?;
158        // Write the value.
159        memory.store_range(value_addr, &value)?;
160        // No need to check addition here as `store_range` would have failed.
161        value_addr += value_len;
162        mem_addr += 2;
163    }
164    Ok(())
165}