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

Compliance fix 1 #218

Merged
merged 1 commit into from
Nov 18, 2023
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
5 changes: 1 addition & 4 deletions interpreter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,7 @@ impl<S> Machine<S> {
self.position = p;
Ok(())
}
Control::Trap(opcode) => {
self.position = position + 1;
Err(Capture::Trap(opcode))
}
Control::Trap(opcode) => Err(Capture::Trap(opcode)),
};

if position >= self.code.len() {
Expand Down
4 changes: 4 additions & 0 deletions interpreter/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ pub trait RuntimeBackend: RuntimeBaseBackend {
fn deleted(&self, address: H160) -> bool;
/// Checks if the address or (address, index) pair has been previously accessed.
fn is_cold(&self, address: H160, index: Option<H256>) -> bool;
fn is_hot(&self, address: H160, index: Option<H256>) -> bool {
!self.is_cold(address, index)
}

/// Mark an address or (address, index) pair as hot.
fn mark_hot(&mut self, address: H160, index: Option<H256>) -> Result<(), ExitError>;
/// Set storage value of address at index.
Expand Down
4 changes: 2 additions & 2 deletions interpreter/src/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ impl Stack {
}

pub fn check_pop_push(&self, pop: usize, push: usize) -> Result<(), ExitException> {
if self.data.len() >= pop {
if self.data.len() < pop {
return Err(ExitException::StackUnderflow);
}
if self.data.len() - pop + push <= self.limit {
if self.data.len() - pop + push + 1 > self.limit {
return Err(ExitException::StackOverflow);
}
Ok(())
Expand Down
2 changes: 2 additions & 0 deletions jsontests/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use thiserror::Error;
pub enum TestError {
#[error("state root is different")]
StateMismatch,
#[error("expect error, but got okay")]
ExpectException,
}

#[derive(Error, Debug)]
Expand Down
33 changes: 23 additions & 10 deletions jsontests/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,43 +14,56 @@ use std::io::BufReader;
#[command(author, version, about, long_about = None)]
struct Cli {
filenames: Vec<String>,

#[arg(short, long, default_value_t = false)]
debug: bool,
}

fn run_file(filename: &str) -> Result<(), Error> {
fn run_file(filename: &str, debug: bool) -> Result<(), Error> {
let test_multi: BTreeMap<String, TestMulti> =
serde_json::from_reader(BufReader::new(File::open(filename)?))?;

for (test_name, test_multi) in test_multi {
let tests = test_multi.tests();

for test in tests {
print!(
"{}/{}/{:?}/{}: ",
filename, test_name, test.fork, test.index
);
match crate::run::run_test(filename, &test_name, test) {
if debug {
println!(
"{}/{}/{:?}/{} ===>",
filename, test_name, test.fork, test.index
);
} else {
print!(
"{}/{}/{:?}/{}: ",
filename, test_name, test.fork, test.index
);
}
match crate::run::run_test(filename, &test_name, test, debug) {
Ok(()) => println!("okay"),
Err(Error::UnsupportedFork) => println!("skipped"),
Err(err) => {
println!("err {:?}", err);
return Err(err);
}
}
if debug {
println!("");
}
}
}

Ok(())
}

fn run_single(filename: &str) -> Result<(), Error> {
fn run_single(filename: &str, debug: bool) -> Result<(), Error> {
if fs::metadata(&filename)?.is_dir() {
for filename in fs::read_dir(&filename)? {
let filepath = filename?.path();
let filename = filepath.to_str().ok_or(Error::NonUtf8Filename)?;
run_file(filename)?;
run_file(filename, debug)?;
}
} else {
run_file(&filename)?;
run_file(&filename, debug)?;
}

Ok(())
Expand All @@ -60,7 +73,7 @@ fn main() -> Result<(), Error> {
let cli = Cli::parse();

for filename in cli.filenames {
run_single(&filename)?;
run_single(&filename, cli.debug)?;
}

Ok(())
Expand Down
63 changes: 45 additions & 18 deletions jsontests/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use evm::backend::in_memory::{
};
use evm::standard::{Config, Etable, Gasometer, Invoker, TransactArgs};
use evm::utils::u256_to_h256;
use evm::RuntimeState;
use evm::{Capture, RuntimeState};
use primitive_types::U256;
use std::collections::{BTreeMap, BTreeSet};

pub fn run_test(_filename: &str, _test_name: &str, test: Test) -> Result<(), Error> {
pub fn run_test(_filename: &str, _test_name: &str, test: Test, debug: bool) -> Result<(), Error> {
let config = match test.fork {
Fork::Berlin => Config::berlin(),
_ => return Err(Error::UnsupportedFork),
Expand Down Expand Up @@ -75,8 +75,7 @@ pub fn run_test(_filename: &str, _test_name: &str, test: Test) -> Result<(), Err
let mut step_backend = run_backend.clone();

// Run

let _run_result = evm::transact::<RuntimeState, Gasometer, _, _, _, _>(
let run_result = evm::transact::<RuntimeState, Gasometer, _, _, _, _>(
args.clone(),
Some(4),
&mut run_backend,
Expand All @@ -85,24 +84,52 @@ pub fn run_test(_filename: &str, _test_name: &str, test: Test) -> Result<(), Err
);

// Step
let mut stepper = evm::HeapTransact::<RuntimeState, Gasometer, _, _, _>::new(
args,
&invoker,
&mut step_backend,
)?;
let _step_result = loop {
println!(
"opcode: {:?}",
stepper.last_machine()?.machine.peek_opcode()
);
if let Err(result) = stepper.step(&etable) {
break result;
}
};
if debug {
let _step_result = evm::HeapTransact::<RuntimeState, Gasometer, _, _, _>::new(
args,
&invoker,
&mut step_backend,
)
.and_then(|mut stepper| loop {
{
let machine = stepper.last_machine()?;
println!(
"pc: {}, opcode: {:?}, gas: 0x{:x}",
machine.machine.position(),
machine.machine.peek_opcode(),
machine.gasometer.gas(),
);
}
if let Err(Capture::Exit(result)) = stepper.step(&etable) {
break result;
}
});
}

let state_root = crate::hash::state_root(&run_backend);

if test.post.expect_exception.is_some() {
if run_result.is_err() {
return Ok(());
} else {
return Err(TestError::ExpectException.into());
}
}

if state_root != test.post.hash {
if debug {
for (address, account) in &run_backend.layers[0].state {
println!(
"address: {:?}, balance: {}, nonce: {}, code: 0x{}, storage: {:?}",
address,
account.balance,
account.nonce,
hex::encode(&account.code),
account.storage
);
}
}

return Err(TestError::StateMismatch.into());
}

Expand Down
2 changes: 2 additions & 0 deletions jsontests/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,13 @@ pub enum Fork {
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TestPostState {
pub hash: H256,
pub indexes: TestPostStateIndexes,
pub logs: H256,
pub txbytes: HexBytes,
pub expect_exception: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
Expand Down
2 changes: 1 addition & 1 deletion src/backend/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl RuntimeBackend for InMemoryBackend {
.get(&address)
.cloned()
.unwrap_or(Default::default())
.storage
.original_storage
.get(&index)
.cloned()
.unwrap_or(H256::default())
Expand Down
32 changes: 18 additions & 14 deletions src/standard/invoker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ where
context,
transaction_context: Rc::new(transaction_context),
retbuf: Vec::new(),
gas: U256::zero(),
gas: U256::from(gas_limit),
}),
gasometer,
handler,
Expand Down Expand Up @@ -247,7 +247,7 @@ where
context,
transaction_context: Rc::new(transaction_context),
retbuf: Vec::new(),
gas: U256::zero(),
gas: U256::from(gas_limit),
}),
gasometer,
handler,
Expand All @@ -274,6 +274,8 @@ where
mut machine: GasedMachine<S, G>,
handler: &mut H,
) -> Result<Self::TransactValue, ExitError> {
let left_gas = machine.gasometer.gas();

let work = || -> Result<Self::TransactValue, ExitError> {
if result.is_ok() {
if let Some(address) = invoke.create_address {
Expand All @@ -289,20 +291,22 @@ where
}
}

let refunded_gas = match result {
Ok(_) | Err(ExitError::Reverted) => machine.gasometer.gas(),
Err(_) => U256::zero(),
};
let refunded_fee = refunded_gas.saturating_mul(invoke.gas_price);
let coinbase_reward = invoke.gas_fee.saturating_sub(refunded_fee);
result.map(|s| (s, invoke.create_address))
};

handler.deposit(invoke.caller, refunded_fee);
handler.deposit(handler.block_coinbase(), coinbase_reward);
let result = work();

result.map(|s| (s, invoke.create_address))
let refunded_gas = match result {
Ok(_) | Err(ExitError::Reverted) => left_gas,
Err(_) => U256::zero(),
};
let refunded_fee = refunded_gas.saturating_mul(invoke.gas_price);
let coinbase_reward = invoke.gas_fee.saturating_sub(refunded_fee);

match work() {
handler.deposit(invoke.caller, refunded_fee);
handler.deposit(handler.block_coinbase(), coinbase_reward);

match result {
Ok(exit) => {
handler.pop_substate(MergeStrategy::Commit);
Ok(exit)
Expand Down Expand Up @@ -377,7 +381,7 @@ where
context: call_trap_data.context.clone(),
transaction_context,
retbuf: Vec::new(),
gas: U256::zero(),
gas: U256::from(gas_limit),
});

Capture::Exit(routines::enter_call_substack(
Expand All @@ -401,7 +405,7 @@ where
},
transaction_context,
retbuf: Vec::new(),
gas: U256::zero(),
gas: U256::from(gas_limit),
});

Capture::Exit(routines::enter_create_substack(
Expand Down
Loading