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, Internal,
} }
/// Evm result. /// A specialized version of Result over EVM errors.
/// pub type Result<T> = ::std::result::Result<T, Error>;
/// Returns `gas_left` if execution is successful, otherwise error.
pub type Result = result::Result<U256, 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 { pub trait Evm {
/// This function should be used to execute transaction. /// 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. //! Interface for Evm externalities.
use util::common::*; use util::common::*;
use evm::{Schedule, Error}; use evm::{self, Schedule};
use env_info::*; use env_info::*;
/// Result of externalities create function. /// Result of externalities create function.
@ -85,7 +85,7 @@ pub trait Ext {
/// Should be called when transaction calls `RETURN` opcode. /// Should be called when transaction calls `RETURN` opcode.
/// Returns gas_left if cost of returning the data is not too high. /// 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. /// Should be called when contract commits suicide.
/// Address to which funds should be refunded. /// Address to which funds should be refunded.

View File

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

View File

@ -18,7 +18,7 @@
use common::*; use common::*;
use trace::VMTracer; use trace::VMTracer;
use evmjit; use evmjit;
use evm; use evm::{self, Error, GasLeft};
/// Should be used to convert jit types to ethcore /// Should be used to convert jit types to ethcore
trait FromJit<T>: Sized { 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 { 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. // 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 ext_adapter: ExtAdapter<'static> = unsafe { ::std::mem::transmute(ExtAdapter::new(ext, params.address.clone())) };
let mut ext_handle = evmjit::ExtHandle::new(ext_adapter); 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.. // don't really know why jit timestamp is int..
data.timestamp = ext.env_info().timestamp as i64; 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(); let res = context.exec();
match res { match res {
evmjit::ReturnCode::Stop => Ok(U256::from(context.gas_left())), evmjit::ReturnCode::Stop => Ok(GasLeft::Known(U256::from(context.gas_left()))),
evmjit::ReturnCode::Return => ext.ret(&U256::from(context.gas_left()), context.output_data()), evmjit::ReturnCode::Return =>
Ok(GasLeft::NeedsReturn(U256::from(context.gas_left()), context.output_data())),
evmjit::ReturnCode::Suicide => { evmjit::ReturnCode::Suicide => {
ext.suicide(&Address::from_jit(&context.suicide_refund_address())); 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), evmjit::ReturnCode::OutOfGas => Err(evm::Error::OutOfGas),
_err => Err(evm::Error::Internal) _err => Err(evm::Error::Internal)

View File

@ -29,7 +29,7 @@ mod jit;
#[cfg(test)] #[cfg(test)]
mod tests; 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::ext::{Ext, ContractCreateResult, MessageCallResult};
pub use self::factory::{Factory, VMType}; pub use self::factory::{Factory, VMType};
pub use self::schedule::Schedule; pub use self::schedule::Schedule;

View File

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

View File

@ -18,7 +18,7 @@
use common::*; use common::*;
use state::*; use state::*;
use engine::*; use engine::*;
use evm::{self, Ext, Factory}; use evm::{self, Ext, Factory, Finalize};
use externalities::*; use externalities::*;
use substate::*; use substate::*;
use trace::{Trace, Tracer, NoopTracer, ExecutiveTracer, VMTrace, VMTracer, ExecutiveVMTracer, NoopVMTracer}; use trace::{Trace, Tracer, NoopTracer, ExecutiveTracer, VMTrace, VMTracer, ExecutiveVMTracer, NoopVMTracer};
@ -205,13 +205,13 @@ impl<'a> Executive<'a> {
output_policy: OutputPolicy, output_policy: OutputPolicy,
tracer: &mut T, tracer: &mut T,
vm_tracer: &mut V 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 // Ordinary execution - keep VM in same thread
if (self.depth + 1) % MAX_VM_DEPTH_FOR_THREAD != 0 { if (self.depth + 1) % MAX_VM_DEPTH_FOR_THREAD != 0 {
let vm_factory = self.vm_factory; let vm_factory = self.vm_factory;
let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy, tracer, vm_tracer); 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); 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 // 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); let mut ext = self.as_externalities(OriginInfo::from(&params), unconfirmed_substate, output_policy, tracer, vm_tracer);
scope.spawn(move || { scope.spawn(move || {
vm_factory.create().exec(params, &mut ext) vm_factory.create().exec(params, &mut ext).finalize(ext)
}) })
}).join() }).join()
} }
@ -238,7 +238,7 @@ impl<'a> Executive<'a> {
mut output: BytesRef, mut output: BytesRef,
tracer: &mut T, tracer: &mut T,
vm_tracer: &mut V 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 // backup used in case of running out of gas
self.state.snapshot(); self.state.snapshot();
@ -351,7 +351,7 @@ impl<'a> Executive<'a> {
substate: &mut Substate, substate: &mut Substate,
tracer: &mut T, tracer: &mut T,
vm_tracer: &mut V 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 // backup used in case of running out of gas
self.state.snapshot(); self.state.snapshot();
@ -402,7 +402,7 @@ impl<'a> Executive<'a> {
&mut self, &mut self,
t: &SignedTransaction, t: &SignedTransaction,
substate: Substate, substate: Substate,
result: evm::Result, result: evm::Result<U256>,
output: Bytes, output: Bytes,
trace: Option<Trace>, trace: Option<Trace>,
vm_trace: Option<VMTrace> 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 { match *result {
Err(evm::Error::OutOfGas) Err(evm::Error::OutOfGas)
| Err(evm::Error::BadJumpDestination {..}) | 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))] #[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>| { let handle_copy = |to: &mut Option<&mut Bytes>| {
to.as_mut().map(|b| **b = data.to_owned()); 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); handle_copy(copy);
let len = cmp::min(slice.len(), data.len()); let len = cmp::min(slice.len(), data.len());
unsafe { (&mut slice[..len]).copy_from_slice(&data[..len]);
ptr::copy(data.as_ptr(), slice.as_mut_ptr(), len);
}
Ok(*gas) Ok(*gas)
}, },
OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => { OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => {
handle_copy(copy); handle_copy(copy);
vec.clear(); vec.clear();
vec.reserve(data.len()); vec.extend_from_slice(data);
unsafe {
ptr::copy(data.as_ptr(), vec.as_mut_ptr(), data.len());
vec.set_len(data.len());
}
Ok(*gas) Ok(*gas)
}, },
OutputPolicy::InitContract(ref mut copy) => { 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); handle_copy(copy);
let mut code = vec![]; let mut code = vec![];
code.reserve(data.len()); code.extend_from_slice(data);
unsafe {
ptr::copy(data.as_ptr(), code.as_mut_ptr(), data.len());
code.set_len(data.len());
}
self.state.init_code(&self.origin_info.address, code); self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost) Ok(*gas - return_cost)
} }

View File

@ -19,7 +19,7 @@ use state::*;
use executive::*; use executive::*;
use engine::*; use engine::*;
use evm; use evm;
use evm::{Schedule, Ext, Factory, VMType, ContractCreateResult, MessageCallResult}; use evm::{Schedule, Ext, Factory, Finalize, VMType, ContractCreateResult, MessageCallResult};
use externalities::*; use externalities::*;
use substate::*; use substate::*;
use tests::helpers::*; use tests::helpers::*;
@ -27,7 +27,7 @@ use ethjson;
use trace::{Tracer, NoopTracer}; use trace::{Tracer, NoopTracer};
use trace::{VMTracer, NoopVMTracer}; use trace::{VMTracer, NoopVMTracer};
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Clone)]
struct CallCreate { struct CallCreate {
data: Bytes, data: Bytes,
destination: Option<Address>, 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) 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) 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 tracer,
&mut vm_tracer, &mut vm_tracer,
); );
let evm = vm_factory.create(); let mut evm = vm_factory.create();
let res = evm.exec(params, &mut ex); 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 { match res {