Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(revm): make FrameOrResult serializable #1282

Merged
merged 4 commits into from
Apr 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion crates/interpreter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ serde = { version = "1.0", default-features = false, features = [
[dev-dependencies]
walkdir = "2.5"
serde_json = { version = "1.0"}
bincode = "1.3"

[[test]]
name = "eof"
path = "tests/eof.rs"
required-features = ["serde"]


[features]
default = ["std"]
std = ["serde?/std", "revm-primitives/std"]
Expand Down
2 changes: 2 additions & 0 deletions crates/interpreter/src/function_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::vec::Vec;
/// Function return frame.
/// Needed information for returning from a function.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionReturnFrame {
/// The index of the code container that this frame is executing.
pub idx: usize,
Expand All @@ -18,6 +19,7 @@ impl FunctionReturnFrame {

/// Function Stack
#[derive(Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionStack {
pub return_stack: Vec<FunctionReturnFrame>,
pub current_code_idx: usize,
Expand Down
1 change: 1 addition & 0 deletions crates/interpreter/src/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub use constants::*;

/// Represents the state of gas during execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Gas {
/// The initial gas limit. This is constant throughout execution.
limit: u64,
Expand Down
3 changes: 3 additions & 0 deletions crates/interpreter/src/interpreter.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
pub mod analysis;
mod contract;
#[cfg(feature = "serde")]
pub mod serde;
mod shared_memory;
mod stack;

Expand Down Expand Up @@ -68,6 +70,7 @@ impl Default for Interpreter {

/// The result of an interpreter operation.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub struct InterpreterResult {
/// The result of the instruction execution.
pub result: InstructionResult,
Expand Down
1 change: 1 addition & 0 deletions crates/interpreter/src/interpreter/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{

/// EVM contract information.
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Contract {
/// Contracts data
pub input: Bytes,
Expand Down
242 changes: 242 additions & 0 deletions crates/interpreter/src/interpreter/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
use crate::{
Contract, FunctionStack, Gas, InstructionResult, InterpreterAction, SharedMemory, Stack,
};

use super::Interpreter;
use revm_primitives::Bytes;
use serde::de::{self, MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

impl Serialize for Interpreter {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("Interpreter", 8)?;
// Convert the instruction pointer to a usize for serialization
let program_counter = self.program_counter();
state.serialize_field("program_counter", &program_counter)?;
state.serialize_field("gas", &self.gas)?;
state.serialize_field("contract", &self.contract)?;
state.serialize_field("instruction_result", &self.instruction_result)?;
state.serialize_field("bytecode", &self.bytecode)?;
state.serialize_field("is_eof", &self.is_eof)?;
state.serialize_field("is_eof_init", &self.is_eof_init)?;
state.serialize_field("shared_memory", &self.shared_memory)?;
state.serialize_field("stack", &self.stack)?;
state.serialize_field("function_stack", &self.function_stack)?;
state.serialize_field("return_data_buffer", &self.return_data_buffer)?;
state.serialize_field("is_static", &self.is_static)?;
state.serialize_field("next_action", &self.next_action)?;
state.end()
}
}

impl<'de> Deserialize<'de> for Interpreter {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct InterpreterVisitor;

#[derive(serde::Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum InterpreterFields {
ProgramCounter,
Gas,
Contract,
InstructionResult,
Bytecode,
IsEof,
IsEofInit,
SharedMemory,
Stack,
FunctionStack,
ReturnDataBuffer,
IsStatic,
NextAction,
}

#[allow(clippy::too_many_arguments)]
fn rebuild_interp(
program_counter: isize,
gas: Gas,
contract: Contract,
instruction_result: InstructionResult,
bytecode: Bytes,
is_eof: bool,
is_eof_init: bool,
shared_memory: SharedMemory,
stack: Stack,
function_stack: FunctionStack,
return_data_buffer: Bytes,
is_static: bool,
next_action: InterpreterAction,
) -> Result<Interpreter, &'static str> {
// Reconstruct the instruction pointer from usize
if program_counter < 0 || program_counter >= bytecode.len() as isize {
return Err("program_counter index out of range");
}

// SAFETY: range of program_counter checked above
let instruction_pointer = unsafe { bytecode.as_ptr().offset(program_counter) };

// Construct and return the Interpreter instance
Ok(Interpreter {
instruction_pointer,
gas,
contract,
instruction_result,
bytecode,
is_eof,
is_eof_init,
shared_memory,
stack,
function_stack,
return_data_buffer,
is_static,
next_action,
})
}

impl<'de> Visitor<'de> for InterpreterVisitor {
type Value = Interpreter;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("struct Interpreter")
}

fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: de::SeqAccess<'de>,
{
macro_rules! extract_field {
($i:ident, $idx:expr) => {
let $i = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length($idx, &self))?;
};
}
extract_field!(instruction_pointer, 0);
extract_field!(gas, 1);
extract_field!(contract, 2);
extract_field!(instruction_result, 3);
extract_field!(bytecode, 4);
extract_field!(is_eof, 5);
extract_field!(is_eof_init, 6);
extract_field!(shared_memory, 7);
extract_field!(stack, 8);
extract_field!(function_stack, 9);
extract_field!(return_data_buffer, 10);
extract_field!(is_static, 11);
extract_field!(next_action, 12);
rebuild_interp(
instruction_pointer,
gas,
contract,
instruction_result,
bytecode,
is_eof,
is_eof_init,
shared_memory,
stack,
function_stack,
return_data_buffer,
is_static,
next_action,
)
.map_err(de::Error::custom)
}

fn visit_map<V>(self, mut map: V) -> Result<Interpreter, V::Error>
where
V: MapAccess<'de>,
{
macro_rules! parse_map {
( $(($enum:pat, $var_name:ident)),* ) => {
$(
let mut $var_name = None;
)*
while let Some(key) = map.next_key()? {
match key {
$(
$enum => {
$var_name = Some(map.next_value()?);
}
)*
}
}
$(
let $var_name = $var_name.ok_or_else(|| de::Error::missing_field(stringify!($var_name)))?;
)*
};
}
parse_map!(
(InterpreterFields::ProgramCounter, program_counter),
(InterpreterFields::Gas, gas),
(InterpreterFields::Contract, contract),
(InterpreterFields::InstructionResult, instruction_result),
(InterpreterFields::Bytecode, bytecode),
(InterpreterFields::IsEof, is_eof),
(InterpreterFields::IsEofInit, is_eof_init),
(InterpreterFields::SharedMemory, shared_memory),
(InterpreterFields::Stack, stack),
(InterpreterFields::FunctionStack, function_stack),
(InterpreterFields::ReturnDataBuffer, return_data_buffer),
(InterpreterFields::IsStatic, is_static),
(InterpreterFields::NextAction, next_action)
);

rebuild_interp(
program_counter,
gas,
contract,
instruction_result,
bytecode,
is_eof,
is_eof_init,
shared_memory,
stack,
function_stack,
return_data_buffer,
is_static,
next_action,
)
.map_err(de::Error::custom)
}
}

const FIELDS: &[&str] = &[
"program_counter",
"gas",
"contract",
"instruction_result",
"bytecode",
"is_eof",
"is_eof_init",
"shared_memory",
"stack",
"function_stack",
"return_data_buffer",
"is_static",
"next_action",
];

deserializer.deserialize_struct("Interpreter", FIELDS, InterpreterVisitor)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_serde() {
let interp = Interpreter::new(Contract::default(), u64::MAX, false);
let serialized = bincode::serialize(&interp).unwrap();
let de: Interpreter = bincode::deserialize(&serialized).unwrap();
assert_eq!(interp.program_counter(), de.program_counter());
}
}
1 change: 1 addition & 0 deletions crates/interpreter/src/interpreter_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use crate::InterpreterResult;
use std::boxed::Box;

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum InterpreterAction {
/// CALL, CALLCODE, DELEGATECALL, STATICCALL
/// or EOF EXT instuction called.
Expand Down
1 change: 1 addition & 0 deletions crates/interpreter/src/interpreter_action/call_outcome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use revm_primitives::Bytes;
/// * `result` - The result of the interpreter's execution, including output data and gas usage.
/// * `memory_offset` - The range in memory where the output data is located.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CallOutcome {
pub result: InterpreterResult,
pub memory_offset: Range<usize>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use revm_primitives::{Address, Bytes};
/// This struct holds the result of the operation along with an optional address.
/// It provides methods to determine the next action based on the result of the operation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CreateOutcome {
// The result of the interpreter operation.
pub result: InterpreterResult,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use core::ops::Range;

/// Inputs for EOF create call.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EOFCreateInput {
/// Caller of Eof Craate
pub caller: Address,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use revm_primitives::{Address, Bytes};
/// This struct holds the result of the operation along with an optional address.
/// It provides methods to determine the next action based on the result of the operation.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EOFCreateOutcome {
/// The result of the interpreter operation.
pub result: InterpreterResult,
Expand Down
Loading
Loading