Have Ext::ret take self by value (#1187)

* refactor externalities::ret to take self by-value, add GasLeft enum, and alter evm::Result.

* remove unused imports, StopExecutionWithGasLeft variant

* adjust tests

* remove extraneous call to reserve

* update json_tests Ext to match new trait

* adjust executive json_test

* have evms own their memory for their entire lifetime

* make finalize API more friendly

* indentation fix

[ci skip]
This commit is contained in:
Robert Habermeier 2016-06-02 19:04:15 +02:00 committed by Gav Wood
parent 18dac64abb
commit 0318bb9fe9
10 changed files with 233 additions and 199 deletions

View File

@ -63,13 +63,43 @@ pub enum Error {
Internal,
}
/// Evm result.
///
/// Returns `gas_left` if execution is successful, otherwise error.
pub type Result = result::Result<U256, Error>;
/// A specialized version of Result over EVM errors.
pub type Result<T> = ::std::result::Result<T, Error>;
/// Evm interface.
/// Gas Left: either it is a known value, or it needs to be computed by processing
/// a return instruction.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum GasLeft<'a> {
/// Known gas left
Known(U256),
/// Return instruction must be processed.
NeedsReturn(U256, &'a [u8]),
}
/// Types that can be "finalized" using an EVM.
///
/// In practice, this is just used to define an inherent impl on
/// `Reult<GasLeft<'a>>`.
pub trait Finalize {
/// Consume the externalities, call return if necessary, and produce a final amount of gas left.
fn finalize<E: Ext>(self, ext: E) -> Result<U256>;
}
impl<'a> Finalize for Result<GasLeft<'a>> {
fn finalize<E: Ext>(self, ext: E) -> Result<U256> {
match self {
Ok(GasLeft::Known(gas)) => Ok(gas),
Ok(GasLeft::NeedsReturn(gas, ret_code)) => ext.ret(&gas, ret_code),
Err(err) => Err(err),
}
}
}
/// Evm interface
pub trait Evm {
/// This function should be used to execute transaction.
fn exec(&self, params: ActionParams, ext: &mut Ext) -> Result;
///
/// It returns either an error, a known amount of gas left, or parameters to be used
/// to compute the final gas left.
fn exec(&mut self, params: ActionParams, ext: &mut Ext) -> Result<GasLeft>;
}

View File

@ -17,7 +17,7 @@
//! Interface for Evm externalities.
use util::common::*;
use evm::{Schedule, Error};
use evm::{self, Schedule};
use env_info::*;
/// Result of externalities create function.
@ -85,7 +85,7 @@ pub trait Ext {
/// Should be called when transaction calls `RETURN` opcode.
/// Returns gas_left if cost of returning the data is not too high.
fn ret(&mut self, gas: &U256, data: &[u8]) -> Result<U256, Error>;
fn ret(self, gas: &U256, data: &[u8]) -> evm::Result<U256> where Self: Sized;
/// Should be called when contract commits suicide.
/// Address to which funds should be refunded.

View File

@ -89,10 +89,10 @@ impl Factory {
pub fn create(&self) -> Box<Evm> {
match self.evm {
VMType::Jit => {
Box::new(super::jit::JitEvm)
Box::new(super::jit::JitEvm::default())
},
VMType::Interpreter => {
Box::new(super::interpreter::Interpreter)
Box::new(super::interpreter::Interpreter::default())
}
}
}
@ -102,7 +102,7 @@ impl Factory {
pub fn create(&self) -> Box<Evm> {
match self.evm {
VMType::Interpreter => {
Box::new(super::interpreter::Interpreter)
Box::new(super::interpreter::Interpreter::default())
}
}
}

View File

@ -21,7 +21,7 @@ use trace::VMTracer;
use super::instructions as instructions;
use super::instructions::{Instruction, get_info};
use std::marker::Copy;
use evm::{self, MessageCallResult, ContractCreateResult};
use evm::{self, MessageCallResult, ContractCreateResult, GasLeft};
#[cfg(not(feature = "evm-debug"))]
macro_rules! evm_debug {
@ -279,21 +279,26 @@ enum InstructionResult {
GasLeft(U256),
UnusedGas(U256),
JumpToPosition(U256),
StopExecutionWithGasLeft(U256),
StopExecution
// gas left, init_orf, init_size
StopExecutionNeedsReturn(U256, U256, U256),
StopExecution,
}
/// Intepreter EVM implementation
pub struct Interpreter;
#[derive(Default)]
pub struct Interpreter {
mem: Vec<u8>,
}
impl evm::Evm for Interpreter {
fn exec(&self, params: ActionParams, ext: &mut evm::Ext) -> evm::Result {
fn exec(&mut self, params: ActionParams, ext: &mut evm::Ext) -> evm::Result<GasLeft> {
self.mem.clear();
let code = &params.code.as_ref().unwrap();
let valid_jump_destinations = self.find_jump_destinations(&code);
let mut current_gas = params.gas;
let mut stack = VecStack::with_capacity(ext.schedule().stack_limit, U256::zero());
let mut mem = vec![];
let mut reader = CodeReader {
position: 0,
code: &code
@ -303,7 +308,7 @@ impl evm::Evm for Interpreter {
let instruction = code[reader.position];
// Calculate gas cost
let (gas_cost, mem_size) = try!(self.get_gas_cost_mem(ext, instruction, &mut mem, &stack));
let (gas_cost, mem_size) = try!(self.get_gas_cost_mem(ext, instruction, &stack));
// TODO: make compile-time removable if too much of a performance hit.
let trace_executed = ext.trace_prepare_execute(reader.position, instruction, &gas_cost);
@ -311,7 +316,7 @@ impl evm::Evm for Interpreter {
reader.position += 1;
try!(self.verify_gas(&current_gas, &gas_cost));
mem.expand(mem_size);
self.mem.expand(mem_size);
current_gas = current_gas - gas_cost; //TODO: use operator -=
evm_debug!({
@ -331,11 +336,11 @@ impl evm::Evm for Interpreter {
// Execute instruction
let result = try!(self.exec_instruction(
current_gas, &params, ext, instruction, &mut reader, &mut mem, &mut stack
current_gas, &params, ext, instruction, &mut reader, &mut stack
));
if trace_executed {
ext.trace_executed(current_gas, stack.peek_top(get_info(instruction).ret), mem_written.map(|(o, s)| (o, &(mem[o..(o + s)]))), store_written);
ext.trace_executed(current_gas, stack.peek_top(get_info(instruction).ret), mem_written.map(|(o, s)| (o, &(self.mem[o..(o + s)]))), store_written);
}
// Advance
@ -354,29 +359,25 @@ impl evm::Evm for Interpreter {
let pos = try!(self.verify_jump(position, &valid_jump_destinations));
reader.position = pos;
},
InstructionResult::StopExecutionWithGasLeft(gas_left) => {
current_gas = gas_left;
reader.position = code.len();
InstructionResult::StopExecutionNeedsReturn(gas, off, size) => {
return Ok(GasLeft::NeedsReturn(gas, self.mem.read_slice(off, size)));
},
InstructionResult::StopExecution => {
reader.position = code.len();
}
InstructionResult::StopExecution => break,
}
}
Ok(current_gas)
Ok(GasLeft::Known(current_gas))
}
}
impl Interpreter {
#[cfg_attr(feature="dev", allow(cyclomatic_complexity))]
fn get_gas_cost_mem(
&self,
&mut self,
ext: &evm::Ext,
instruction: Instruction,
mem: &mut Memory,
stack: &Stack<U256>
) -> Result<(U256, usize), evm::Error> {
) -> evm::Result<(U256, usize)> {
let schedule = ext.schedule();
let info = instructions::get_info(instruction);
@ -492,12 +493,12 @@ impl Interpreter {
Ok((gas, 0))
},
InstructionCost::GasMem(gas, mem_size) => {
let (mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, mem.size(), &mem_size));
let (mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, self.mem.size(), &mem_size));
let gas = overflowing!(gas.overflowing_add(mem_gas));
Ok((gas, new_mem_size))
},
InstructionCost::GasMemCopy(gas, mem_size, copy) => {
let (mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, mem.size(), &mem_size));
let (mem_gas, new_mem_size) = try!(self.mem_gas_cost(schedule, self.mem.size(), &mem_size));
let copy = overflowing!(add_u256_usize(&copy, 31));
let copy_gas = U256::from(schedule.copy_gas) * (copy / U256::from(32));
let gas = overflowing!(gas.overflowing_add(copy_gas));
@ -532,7 +533,7 @@ impl Interpreter {
}
}
fn mem_gas_cost(&self, schedule: &evm::Schedule, current_mem_size: usize, mem_size: &U256) -> Result<(U256, usize), evm::Error> {
fn mem_gas_cost(&self, schedule: &evm::Schedule, current_mem_size: usize, mem_size: &U256) -> evm::Result<(U256, usize)> {
let gas_for_mem = |mem_size: U256| {
let s = mem_size >> 5;
// s * memory_gas + s * s / quad_coeff_div
@ -557,11 +558,11 @@ impl Interpreter {
}, req_mem_size_rounded.low_u64() as usize))
}
fn mem_needed_const(&self, mem: &U256, add: usize) -> Result<U256, evm::Error> {
fn mem_needed_const(&self, mem: &U256, add: usize) -> evm::Result<U256> {
Ok(overflowing!(mem.overflowing_add(U256::from(add))))
}
fn mem_needed(&self, offset: &U256, size: &U256) -> Result<U256, ::evm::Error> {
fn mem_needed(&self, offset: &U256, size: &U256) -> evm::Result<U256> {
if self.is_zero(size) {
return Ok(U256::zero());
}
@ -571,15 +572,14 @@ impl Interpreter {
#[cfg_attr(feature="dev", allow(too_many_arguments))]
fn exec_instruction(
&self,
&mut self,
gas: Gas,
params: &ActionParams,
ext: &mut evm::Ext,
instruction: Instruction,
code: &mut CodeReader,
mem: &mut Memory,
stack: &mut Stack<U256>
) -> Result<InstructionResult, evm::Error> {
) -> evm::Result<InstructionResult> {
match instruction {
instructions::JUMP => {
let jump = stack.pop_back();
@ -604,7 +604,7 @@ impl Interpreter {
let init_off = stack.pop_back();
let init_size = stack.pop_back();
let contract_code = mem.read_slice(init_off, init_size);
let contract_code = self.mem.read_slice(init_off, init_size);
let can_create = ext.balance(&params.address) >= endowment && ext.depth() < ext.schedule().max_depth;
if !can_create {
@ -671,8 +671,8 @@ impl Interpreter {
let call_result = {
// we need to write and read from memory in the same time
// and we don't want to copy
let input = unsafe { ::std::mem::transmute(mem.read_slice(in_off, in_size)) };
let output = mem.writeable_slice(out_off, out_size);
let input = unsafe { ::std::mem::transmute(self.mem.read_slice(in_off, in_size)) };
let output = self.mem.writeable_slice(out_off, out_size);
ext.call(&call_gas, sender_address, receive_address, value, input, &code_address, output)
};
@ -690,11 +690,8 @@ impl Interpreter {
instructions::RETURN => {
let init_off = stack.pop_back();
let init_size = stack.pop_back();
let return_code = mem.read_slice(init_off, init_size);
let gas_left = try!(ext.ret(&gas, &return_code));
return Ok(InstructionResult::StopExecutionWithGasLeft(
gas_left
));
return Ok(InstructionResult::StopExecutionNeedsReturn(gas, init_off, init_size))
},
instructions::STOP => {
return Ok(InstructionResult::StopExecution);
@ -713,7 +710,7 @@ impl Interpreter {
.iter()
.map(H256::from)
.collect();
ext.log(topics, mem.read_slice(offset, size));
ext.log(topics, self.mem.read_slice(offset, size));
},
instructions::PUSH1...instructions::PUSH32 => {
let bytes = instructions::get_push_bytes(instruction);
@ -721,26 +718,26 @@ impl Interpreter {
stack.push(val);
},
instructions::MLOAD => {
let word = mem.read(stack.pop_back());
let word = self.mem.read(stack.pop_back());
stack.push(U256::from(word));
},
instructions::MSTORE => {
let offset = stack.pop_back();
let word = stack.pop_back();
mem.write(offset, word);
Memory::write(&mut self.mem, offset, word);
},
instructions::MSTORE8 => {
let offset = stack.pop_back();
let byte = stack.pop_back();
mem.write_byte(offset, byte);
self.mem.write_byte(offset, byte);
},
instructions::MSIZE => {
stack.push(U256::from(mem.size()));
stack.push(U256::from(self.mem.size()));
},
instructions::SHA3 => {
let offset = stack.pop_back();
let size = stack.pop_back();
let sha3 = mem.read_slice(offset, size).sha3();
let sha3 = self.mem.read_slice(offset, size).sha3();
stack.push(U256::from(sha3.as_slice()));
},
instructions::SLOAD => {
@ -813,15 +810,15 @@ impl Interpreter {
stack.push(U256::from(len));
},
instructions::CALLDATACOPY => {
self.copy_data_to_memory(mem, stack, &params.data.clone().unwrap_or_else(|| vec![]));
self.copy_data_to_memory(stack, &params.data.clone().unwrap_or_else(|| vec![]));
},
instructions::CODECOPY => {
self.copy_data_to_memory(mem, stack, &params.code.clone().unwrap_or_else(|| vec![]));
self.copy_data_to_memory(stack, &params.code.clone().unwrap_or_else(|| vec![]));
},
instructions::EXTCODECOPY => {
let address = u256_to_address(&stack.pop_back());
let code = ext.extcode(&address);
self.copy_data_to_memory(mem, stack, &code);
self.copy_data_to_memory(stack, &code);
},
instructions::GASPRICE => {
stack.push(params.gas_price.clone());
@ -853,7 +850,7 @@ impl Interpreter {
Ok(InstructionResult::Ok)
}
fn copy_data_to_memory(&self, mem: &mut Memory, stack: &mut Stack<U256>, data: &[u8]) {
fn copy_data_to_memory(&mut self, stack: &mut Stack<U256>, data: &[u8]) {
let dest_offset = stack.pop_back();
let source_offset = stack.pop_back();
let size = stack.pop_back();
@ -862,9 +859,9 @@ impl Interpreter {
let output_end = match source_offset > source_size || size > source_size || source_offset + size > source_size {
true => {
let zero_slice = if source_offset > source_size {
mem.writeable_slice(dest_offset, size)
self.mem.writeable_slice(dest_offset, size)
} else {
mem.writeable_slice(dest_offset + source_size - source_offset, source_offset + size - source_size)
self.mem.writeable_slice(dest_offset + source_size - source_offset, source_offset + size - source_size)
};
for i in zero_slice.iter_mut() {
*i = 0;
@ -876,7 +873,7 @@ impl Interpreter {
if source_offset < source_size {
let output_begin = source_offset.low_u64() as usize;
mem.write_slice(dest_offset, &data[output_begin..output_end]);
self.mem.write_slice(dest_offset, &data[output_begin..output_end]);
}
}
@ -885,7 +882,7 @@ impl Interpreter {
info: &instructions::InstructionInfo,
stack_limit: usize,
stack: &Stack<U256>
) -> Result<(), evm::Error> {
) -> evm::Result<()> {
if !stack.has(info.args) {
Err(evm::Error::StackUnderflow {
instruction: info.name,
@ -903,14 +900,14 @@ impl Interpreter {
}
}
fn verify_gas(&self, current_gas: &U256, gas_cost: &U256) -> Result<(), evm::Error> {
fn verify_gas(&self, current_gas: &U256, gas_cost: &U256) -> evm::Result<()> {
match current_gas < gas_cost {
true => Err(evm::Error::OutOfGas),
false => Ok(())
}
}
fn verify_jump(&self, jump_u: U256, valid_jump_destinations: &HashSet<usize>) -> Result<usize, evm::Error> {
fn verify_jump(&self, jump_u: U256, valid_jump_destinations: &HashSet<usize>) -> evm::Result<usize> {
let jump = jump_u.low_u64() as usize;
if valid_jump_destinations.contains(&jump) && jump_u < U256::from(!0 as usize) {
@ -934,7 +931,7 @@ impl Interpreter {
}
}
fn exec_stack_instruction(&self, instruction: Instruction, stack: &mut Stack<U256>) -> Result<(), evm::Error> {
fn exec_stack_instruction(&self, instruction: Instruction, stack: &mut Stack<U256>) -> evm::Result<()> {
match instruction {
instructions::DUP1...instructions::DUP16 => {
let position = instructions::get_dup_position(instruction);
@ -1185,7 +1182,7 @@ fn address_to_u256(value: Address) -> U256 {
#[test]
fn test_mem_gas_cost() {
// given
let interpreter = Interpreter;
let interpreter = Interpreter::default();
let schedule = evm::Schedule::default();
let current_mem_size = 5;
let mem_size = !U256::zero();
@ -1208,7 +1205,7 @@ mod tests {
#[test]
fn test_find_jump_destinations() {
// given
let interpreter = Interpreter;
let interpreter = Interpreter::default();
let code = "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff5b01600055".from_hex().unwrap();
// when
@ -1221,7 +1218,7 @@ mod tests {
#[test]
fn test_calculate_mem_cost() {
// given
let interpreter = Interpreter;
let interpreter = Interpreter::default();
let schedule = evm::Schedule::default();
let current_mem_size = 0;
let mem_size = U256::from(5);

View File

@ -18,7 +18,7 @@
use common::*;
use trace::VMTracer;
use evmjit;
use evm;
use evm::{self, Error, GasLeft};
/// Should be used to convert jit types to ethcore
trait FromJit<T>: Sized {
@ -301,10 +301,13 @@ impl<'a> evmjit::Ext for ExtAdapter<'a> {
}
}
pub struct JitEvm;
#[derive(Default)]
pub struct JitEvm {
ctxt: Option<evmjit::ContextHandle>,
}
impl evm::Evm for JitEvm {
fn exec(&self, params: ActionParams, ext: &mut evm::Ext) -> evm::Result {
fn exec(&mut self, params: ActionParams, ext: &mut evm::Ext) -> evm::Result<GasLeft> {
// Dirty hack. This is unsafe, but we interact with ffi, so it's justified.
let ext_adapter: ExtAdapter<'static> = unsafe { ::std::mem::transmute(ExtAdapter::new(ext, params.address.clone())) };
let mut ext_handle = evmjit::ExtHandle::new(ext_adapter);
@ -343,15 +346,17 @@ impl evm::Evm for JitEvm {
// don't really know why jit timestamp is int..
data.timestamp = ext.env_info().timestamp as i64;
let mut context = unsafe { evmjit::ContextHandle::new(data, schedule, &mut ext_handle) };
self.context = Some(unsafe { evmjit::ContextHandle::new(data, schedule, &mut ext_handle) });
let context = self.context.as_ref_mut().unwrap();
let res = context.exec();
match res {
evmjit::ReturnCode::Stop => Ok(U256::from(context.gas_left())),
evmjit::ReturnCode::Return => ext.ret(&U256::from(context.gas_left()), context.output_data()),
evmjit::ReturnCode::Stop => Ok(GasLeft::Known(U256::from(context.gas_left()))),
evmjit::ReturnCode::Return =>
Ok(GasLeft::NeedsReturn(U256::from(context.gas_left()), context.output_data())),
evmjit::ReturnCode::Suicide => {
ext.suicide(&Address::from_jit(&context.suicide_refund_address()));
Ok(U256::from(context.gas_left()))
Ok(GasLeft::Known(U256::from(context.gas_left())))
},
evmjit::ReturnCode::OutOfGas => Err(evm::Error::OutOfGas),
_err => Err(evm::Error::Internal)

View File

@ -29,7 +29,7 @@ mod jit;
#[cfg(test)]
mod tests;
pub use self::evm::{Evm, Error, Result};
pub use self::evm::{Evm, Error, Finalize, GasLeft, Result};
pub use self::ext::{Ext, ContractCreateResult, MessageCallResult};
pub use self::factory::{Factory, VMType};
pub use self::schedule::Schedule;

View File

@ -15,8 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use common::*;
use evm;
use evm::{Ext, Schedule, Factory, VMType, ContractCreateResult, MessageCallResult};
use evm::{self, Ext, Schedule, Factory, GasLeft, VMType, ContractCreateResult, MessageCallResult};
use std::fmt::Debug;
struct FakeLogEntry {
@ -58,6 +57,15 @@ struct FakeExt {
calls: HashSet<FakeCall>,
}
// similar to the normal `finalize` function, but ignoring NeedsReturn.
fn test_finalize(res: Result<GasLeft, evm::Error>) -> Result<U256, evm::Error> {
match res {
Ok(GasLeft::Known(gas)) => Ok(gas),
Ok(GasLeft::NeedsReturn(_, _)) => unimplemented!(), // since ret is unimplemented.
Err(e) => Err(e),
}
}
impl FakeExt {
fn new() -> Self {
FakeExt::default()
@ -136,7 +144,7 @@ impl Ext for FakeExt {
});
}
fn ret(&mut self, _gas: &U256, _data: &[u8]) -> result::Result<U256, evm::Error> {
fn ret(self, _gas: &U256, _data: &[u8]) -> evm::Result<U256> {
unimplemented!();
}
@ -173,8 +181,8 @@ fn test_stack_underflow() {
let mut ext = FakeExt::new();
let err = {
let vm : Box<evm::Evm> = Box::new(super::interpreter::Interpreter);
vm.exec(params, &mut ext).unwrap_err()
let mut vm : Box<evm::Evm> = Box::new(super::interpreter::Interpreter::default());
test_finalize(vm.exec(params, &mut ext)).unwrap_err()
};
match err {
@ -200,8 +208,8 @@ fn test_add(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_988));
@ -220,8 +228,8 @@ fn test_sha3(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_961));
@ -240,8 +248,8 @@ fn test_address(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -262,8 +270,8 @@ fn test_origin(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -284,8 +292,8 @@ fn test_sender(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -319,8 +327,8 @@ fn test_extcodecopy(factory: super::Factory) {
ext.codes.insert(sender, sender_code);
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_935));
@ -339,8 +347,8 @@ fn test_log_empty(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(99_619));
@ -371,8 +379,8 @@ fn test_log_sender(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(98_974));
@ -396,8 +404,8 @@ fn test_blockhash(factory: super::Factory) {
ext.blockhashes.insert(U256::zero(), blockhash.clone());
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_974));
@ -418,8 +426,8 @@ fn test_calldataload(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_991));
@ -439,8 +447,8 @@ fn test_author(factory: super::Factory) {
ext.info.author = author;
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -459,8 +467,8 @@ fn test_timestamp(factory: super::Factory) {
ext.info.timestamp = timestamp;
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -479,8 +487,8 @@ fn test_number(factory: super::Factory) {
ext.info.number = number;
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -499,8 +507,8 @@ fn test_difficulty(factory: super::Factory) {
ext.info.difficulty = difficulty;
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -519,8 +527,8 @@ fn test_gas_limit(factory: super::Factory) {
ext.info.gas_limit = gas_limit;
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
@ -537,8 +545,8 @@ fn test_mul(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "000000000000000000000000000000000000000000000000734349397b853383");
@ -555,8 +563,8 @@ fn test_sub(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000012364ad0302");
@ -573,8 +581,8 @@ fn test_div(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "000000000000000000000000000000000000000000000000000000000002e0ac");
@ -591,8 +599,8 @@ fn test_div_zero(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000000");
@ -609,8 +617,8 @@ fn test_mod(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000076b4b");
@ -628,8 +636,8 @@ fn test_smod(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000076b4b");
@ -647,8 +655,8 @@ fn test_sdiv(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "000000000000000000000000000000000000000000000000000000000002e0ac");
@ -666,8 +674,8 @@ fn test_exp(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "90fd23767b60204c3d6fc8aec9e70a42a3f127140879c133a20129a597ed0c59");
@ -686,8 +694,8 @@ fn test_comparison(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000000");
@ -707,8 +715,8 @@ fn test_signed_comparison(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000000");
@ -728,8 +736,8 @@ fn test_bitops(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "00000000000000000000000000000000000000000000000000000000000000f0");
@ -751,8 +759,8 @@ fn test_addmod_mulmod(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000001");
@ -772,8 +780,8 @@ fn test_byte(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000000");
@ -791,8 +799,8 @@ fn test_signextend(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000fff");
@ -811,8 +819,8 @@ fn test_badinstruction_int() {
let mut ext = FakeExt::new();
let err = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap_err()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap_err()
};
match err {
@ -831,8 +839,8 @@ fn test_pop(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "00000000000000000000000000000000000000000000000000000000000000f0");
@ -851,8 +859,8 @@ fn test_extops(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_store(&ext, 0, "0000000000000000000000000000000000000000000000000000000000000004"); // PC / CALLDATASIZE
@ -874,8 +882,8 @@ fn test_jumps(factory: super::Factory) {
let mut ext = FakeExt::new();
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_eq!(ext.sstore_clears, 1);
@ -903,8 +911,8 @@ fn test_calls(factory: super::Factory) {
};
let gas_left = {
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
let mut vm = factory.create();
test_finalize(vm.exec(params, &mut ext)).unwrap()
};
assert_set_contains(&ext.calls, &FakeCall {

View File

@ -18,7 +18,7 @@
use common::*;
use state::*;
use engine::*;
use evm::{self, Ext, Factory};
use evm::{self, Ext, Factory, Finalize};
use externalities::*;
use substate::*;
use trace::{Trace, Tracer, NoopTracer, ExecutiveTracer, VMTrace, VMTracer, ExecutiveVMTracer, NoopVMTracer};
@ -205,13 +205,13 @@ impl<'a> Executive<'a> {
output_policy: OutputPolicy,
tracer: &mut T,
vm_tracer: &mut V
) -> evm::Result where T: Tracer, V: VMTracer {
) -> evm::Result<U256> where T: Tracer, V: VMTracer {
// Ordinary execution - keep VM in same thread
if (self.depth + 1) % MAX_VM_DEPTH_FOR_THREAD != 0 {
let vm_factory = self.vm_factory;
let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy, tracer, vm_tracer);
trace!(target: "executive", "ext.schedule.have_delegate_call: {}", ext.schedule().have_delegate_call);
return vm_factory.create().exec(params, &mut ext);
return vm_factory.create().exec(params, &mut ext).finalize(ext);
}
// Start in new thread to reset stack
@ -222,7 +222,7 @@ impl<'a> Executive<'a> {
let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy, tracer, vm_tracer);
scope.spawn(move || {
vm_factory.create().exec(params, &mut ext)
vm_factory.create().exec(params, &mut ext).finalize(ext)
})
}).join()
}
@ -238,7 +238,7 @@ impl<'a> Executive<'a> {
mut output: BytesRef,
tracer: &mut T,
vm_tracer: &mut V
) -> evm::Result where T: Tracer, V: VMTracer {
) -> evm::Result<U256> where T: Tracer, V: VMTracer {
// backup used in case of running out of gas
self.state.snapshot();
@ -351,7 +351,7 @@ impl<'a> Executive<'a> {
substate: &mut Substate,
tracer: &mut T,
vm_tracer: &mut V
) -> evm::Result where T: Tracer, V: VMTracer {
) -> evm::Result<U256> where T: Tracer, V: VMTracer {
// backup used in case of running out of gas
self.state.snapshot();
@ -402,7 +402,7 @@ impl<'a> Executive<'a> {
&mut self,
t: &SignedTransaction,
substate: Substate,
result: evm::Result,
result: evm::Result<U256>,
output: Bytes,
trace: Option<Trace>,
vm_trace: Option<VMTrace>
@ -468,7 +468,7 @@ impl<'a> Executive<'a> {
}
}
fn enact_result(&mut self, result: &evm::Result, substate: &mut Substate, un_substate: Substate) {
fn enact_result(&mut self, result: &evm::Result<U256>, substate: &mut Substate, un_substate: Substate) {
match *result {
Err(evm::Error::OutOfGas)
| Err(evm::Error::BadJumpDestination {..})

View File

@ -203,7 +203,8 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT
}
#[cfg_attr(feature="dev", allow(match_ref_pats))]
fn ret(&mut self, gas: &U256, data: &[u8]) -> Result<U256, evm::Error> {
fn ret(mut self, gas: &U256, data: &[u8]) -> evm::Result<U256>
where Self: Sized {
let handle_copy = |to: &mut Option<&mut Bytes>| {
to.as_mut().map(|b| **b = data.to_owned());
};
@ -212,20 +213,14 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT
handle_copy(copy);
let len = cmp::min(slice.len(), data.len());
unsafe {
ptr::copy(data.as_ptr(), slice.as_mut_ptr(), len);
}
(&mut slice[..len]).copy_from_slice(&data[..len]);
Ok(*gas)
},
OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => {
handle_copy(copy);
vec.clear();
vec.reserve(data.len());
unsafe {
ptr::copy(data.as_ptr(), vec.as_mut_ptr(), data.len());
vec.set_len(data.len());
}
vec.extend_from_slice(data);
Ok(*gas)
},
OutputPolicy::InitContract(ref mut copy) => {
@ -240,11 +235,8 @@ impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMT
handle_copy(copy);
let mut code = vec![];
code.reserve(data.len());
unsafe {
ptr::copy(data.as_ptr(), code.as_mut_ptr(), data.len());
code.set_len(data.len());
}
code.extend_from_slice(data);
self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost)
}

View File

@ -19,7 +19,7 @@ use state::*;
use executive::*;
use engine::*;
use evm;
use evm::{Schedule, Ext, Factory, VMType, ContractCreateResult, MessageCallResult};
use evm::{Schedule, Ext, Factory, Finalize, VMType, ContractCreateResult, MessageCallResult};
use externalities::*;
use substate::*;
use tests::helpers::*;
@ -27,7 +27,7 @@ use ethjson;
use trace::{Tracer, NoopTracer};
use trace::{VMTracer, NoopVMTracer};
#[derive(Debug, PartialEq)]
#[derive(Debug, PartialEq, Clone)]
struct CallCreate {
data: Bytes,
destination: Option<Address>,
@ -133,7 +133,7 @@ impl<'a, T, V> Ext for TestExt<'a, T, V> where T: Tracer, V: VMTracer {
self.ext.log(topics, data)
}
fn ret(&mut self, gas: &U256, data: &[u8]) -> Result<U256, evm::Error> {
fn ret(self, gas: &U256, data: &[u8]) -> Result<U256, evm::Error> {
self.ext.ret(gas, data)
}
@ -208,9 +208,11 @@ fn do_json_test_for(vm_type: &VMType, json_data: &[u8]) -> Vec<String> {
&mut tracer,
&mut vm_tracer,
);
let evm = vm_factory.create();
let mut evm = vm_factory.create();
let res = evm.exec(params, &mut ex);
(res, ex.callcreates)
// a return in finalize will not alter callcreates
let callcreates = ex.callcreates.clone();
(res.finalize(ex), callcreates)
};
match res {