From d59e074d6520369a616f730a78059d19a3a7ef6d Mon Sep 17 00:00:00 2001 From: debris Date: Thu, 14 Jan 2016 17:40:38 +0100 Subject: [PATCH] executive create --- src/evm/ext.rs | 6 +-- src/evm/jit.rs | 28 +++++--------- src/evm/tests.rs | 2 +- src/executive.rs | 84 ++++++++++++++++++++++-------------------- src/tests/executive.rs | 14 ++++--- src/tests/state.rs | 1 + 6 files changed, 66 insertions(+), 69 deletions(-) diff --git a/src/evm/ext.rs b/src/evm/ext.rs index 52b8af24f..6bbd2bce3 100644 --- a/src/evm/ext.rs +++ b/src/evm/ext.rs @@ -21,10 +21,8 @@ pub trait Ext { /// Creates new contract. /// - /// If contract creation is successfull, return gas_left and contract address, - /// If depth is too big or transfer value exceeds balance, return None - /// Otherwise return appropriate `Error`. - fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> Result<(U256, Option
), Error>; + /// Return gas_left and contract address if contract creation was succesfull. + fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> (U256, Option
); /// Message call. /// diff --git a/src/evm/jit.rs b/src/evm/jit.rs index f907c4be8..8b71515d0 100644 --- a/src/evm/jit.rs +++ b/src/evm/jit.rs @@ -209,23 +209,12 @@ impl<'a> evmjit::Ext for ExtAdapter<'a> { init_size: u64, address: *mut evmjit::H256) { unsafe { - match self.ext.create(&U256::from(*io_gas), &U256::from_jit(&*endowment), slice::from_raw_parts(init_beg, init_size as usize)) { - Ok((gas_left, opt)) => { - *io_gas = gas_left.low_u64(); - *address = match opt { - Some(addr) => addr.into_jit(), - _ => Address::new().into_jit() - }; - }, - Err(err @ evm::Error::OutOfGas) => { - *self.err = Some(err); - // hack to propagate `OutOfGas` to evmjit and stop - // the execution immediately. - // Works, cause evmjit uses i64, not u64 - *io_gas = -1i64 as u64; - }, - Err(err) => *self.err = Some(err) - } + let (gas_left, opt_addr) = self.ext.create(&U256::from(*io_gas), &U256::from_jit(&*endowment), slice::from_raw_parts(init_beg, init_size as usize)); + *io_gas = gas_left.low_u64(); + *address = match opt_addr { + Some(addr) => addr.into_jit(), + _ => Address::new().into_jit() + }; } } @@ -254,11 +243,11 @@ impl<'a> evmjit::Ext for ExtAdapter<'a> { true }, Err(err @ evm::Error::OutOfGas) => { - *self.err = Some(err); + //*self.err = Some(err); // hack to propagate `OutOfGas` to evmjit and stop // the execution immediately. // Works, cause evmjit uses i64, not u64 - *io_gas = -1i64 as u64; + *io_gas = 0 as u64; false }, Err(err) => { @@ -337,6 +326,7 @@ impl evm::Evm for JitEvm { let mut context = unsafe { evmjit::ContextHandle::new(data.into_jit(), &mut ext_handle) }; let res = context.exec(); + println!("jit res: {:?}", res); // check in adapter if execution of children contracts failed. if let Some(err) = optional_err { diff --git a/src/evm/tests.rs b/src/evm/tests.rs index 7aff9f407..78a47d7e3 100644 --- a/src/evm/tests.rs +++ b/src/evm/tests.rs @@ -42,7 +42,7 @@ impl Ext for FakeExt { self.blockhashes.get(number).unwrap_or(&H256::new()).clone() } - fn create(&mut self, _gas: &U256, _value: &U256, _code: &[u8]) -> result::Result<(U256, Option
), evm::Error> { + fn create(&mut self, _gas: &U256, _value: &U256, _code: &[u8]) -> (U256, Option
) { unimplemented!(); } diff --git a/src/executive.rs b/src/executive.rs index de65e183f..ceeb5f658 100644 --- a/src/executive.rs +++ b/src/executive.rs @@ -21,6 +21,8 @@ pub struct Substate { logs: Vec, /// Refund counter of SSTORE nonzero->zero. refunds_count: U256, + /// True if transaction, or one of it's subcalls runs out of gas. + out_of_gas: bool, /// Created contracts. contracts_created: Vec
} @@ -32,6 +34,7 @@ impl Substate { suicides: HashSet::new(), logs: vec![], refunds_count: U256::zero(), + out_of_gas: false, contracts_created: vec![] } } @@ -135,7 +138,6 @@ impl<'a> Executive<'a> { self.state.sub_balance(&sender, &U256::from(gas_cost)); let mut substate = Substate::new(); - let backup = self.state.clone(); let schedule = self.engine.schedule(self.info); let init_gas = t.gas - U256::from(t.gas_required(&schedule)); @@ -172,7 +174,7 @@ impl<'a> Executive<'a> { }; // finalize here! - Ok(try!(self.finalize(t, substate, backup, res))) + Ok(try!(self.finalize(t, substate, res))) } /// Calls contract function with given contract params. @@ -180,6 +182,9 @@ impl<'a> Executive<'a> { /// Modifies the substate and the output. /// Returns either gas_left or `evm::Error`. pub fn call(&mut self, params: &ActionParams, substate: &mut Substate, mut output: BytesRef) -> evm::Result { + // backup used in case of running out of gas + let backup = self.state.clone(); + // at first, transfer value to destination self.state.transfer_balance(¶ms.sender, ¶ms.address, ¶ms.value); @@ -191,13 +196,18 @@ impl<'a> Executive<'a> { self.engine.execute_builtin(¶ms.address, ¶ms.data, &mut output); Ok(params.gas - cost) }, - false => Err(evm::Error::OutOfGas) + // just drain the whole gas + false => Ok(U256::zero()) } } else if params.code.len() > 0 { // if destination is a contract, do normal message call - let mut ext = Externalities::from_executive(self, params, substate, OutputPolicy::Return(output)); - let evm = Factory::create(); - evm.exec(¶ms, &mut ext) + + let res = { + let mut ext = Externalities::from_executive(self, params, substate, OutputPolicy::Return(output)); + let evm = Factory::create(); + evm.exec(¶ms, &mut ext) + }; + self.handle_out_of_gas(res, substate, backup) } else { // otherwise, nothing Ok(params.gas) @@ -208,44 +218,27 @@ impl<'a> Executive<'a> { /// NOTE. It does not finalize the transaction (doesn't do refunds, nor suicides). /// Modifies the substate. fn create(&mut self, params: &ActionParams, substate: &mut Substate) -> evm::Result { + // backup used in case of running out of gas + let backup = self.state.clone(); + // at first create new contract self.state.new_contract(¶ms.address); + // then transfer value to it self.state.transfer_balance(¶ms.sender, ¶ms.address, ¶ms.value); - let mut ext = Externalities::from_executive(self, params, substate, OutputPolicy::InitContract); - let evm = Factory::create(); - evm.exec(¶ms, &mut ext) + let res = { + let mut ext = Externalities::from_executive(self, params, substate, OutputPolicy::InitContract); + let evm = Factory::create(); + evm.exec(¶ms, &mut ext) + }; + self.handle_out_of_gas(res, substate, backup) } /// Finalizes the transaction (does refunds and suicides). - fn finalize(&mut self, t: &Transaction, substate: Substate, mut backup: State, result: evm::Result) -> ExecutionResult { + fn finalize(&mut self, t: &Transaction, substate: Substate, result: evm::Result) -> ExecutionResult { match result { Err(evm::Error::Internal) => Err(ExecutionError::Internal), - Err(evm::Error::OutOfGas) => { - // apply first transfer to backup, and then revert everything - let sender = t.sender().unwrap(); - match t.action() { - &Action::Create => { - let nonce = backup.nonce(&sender); - let address = contract_address(&sender, &nonce); - backup.new_contract(&address); - backup.transfer_balance(&sender, &address, &t.value); - } - &Action::Call(ref address) => backup.transfer_balance(&sender, address, &t.value) - } - - self.state.revert(backup); - Ok(Executed { - gas: t.gas, - gas_used: t.gas, - refunded: U256::zero(), - cumulative_gas_used: self.info.gas_used + t.gas, - logs: vec![], - out_of_gas: true, - contracts_created: vec![] - }) - }, Ok(gas_left) => { let schedule = self.engine.schedule(self.info); @@ -277,12 +270,21 @@ impl<'a> Executive<'a> { refunded: refund, cumulative_gas_used: self.info.gas_used + gas_used, logs: substate.logs, - out_of_gas: false, + out_of_gas: substate.out_of_gas, contracts_created: substate.contracts_created }) - } + }, + _err => { unreachable!() } } } + + pub fn handle_out_of_gas(&mut self, result: evm::Result, substate: &mut Substate, backup: State) -> evm::Result { + if let &Err(evm::Error::OutOfGas) = &result { + substate.out_of_gas = true; + self.state.revert(backup); + } + result + } } /// Policy for handling output data on `RETURN` opcode. @@ -366,10 +368,10 @@ impl<'a> Ext for Externalities<'a> { } } - fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> Result<(U256, Option
), evm::Error> { + fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> (U256, Option
) { // if balance is insufficient or we are to deep, return if self.state.balance(&self.params.address) < *value || self.depth >= self.schedule.max_depth { - return Ok((*gas, None)); + return (*gas, None); } // create new contract address @@ -389,7 +391,11 @@ impl<'a> Ext for Externalities<'a> { let mut ex = Executive::from_parent(self.state, self.info, self.engine, self.depth); ex.state.inc_nonce(&self.params.address); - ex.create(¶ms, self.substate).map(|gas_left| (gas_left, Some(address))) + match ex.create(¶ms, self.substate) { + Ok(gas_left) => (gas_left, Some(address)), + _ => (U256::zero(), None) + } + //ex.create(¶ms, self.substate).map(|gas_left| (gas_left, Some(address))) } fn call(&mut self, gas: &U256, call_gas: &U256, receive_address: &Address, value: &U256, data: &[u8], code_address: &Address, output: &mut [u8]) -> Result { diff --git a/src/tests/executive.rs b/src/tests/executive.rs index 25166dc04..07f70e72e 100644 --- a/src/tests/executive.rs +++ b/src/tests/executive.rs @@ -71,24 +71,24 @@ impl<'a> Ext for TestExt<'a> { self.ext.blockhash(number) } - fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> Result<(U256, Option
), evm::Error> { + fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> (U256, Option
) { // in call and create we need to check if we exited with insufficient balance or max limit reached. // in case of reaching max depth, we should store callcreates. Otherwise, ignore. let res = self.ext.create(gas, value, code); let ext = &self.ext; match res { // just record call create - Ok((gas_left, Some(address))) => { + (gas_left, Some(address)) => { self.callcreates.push(CallCreate { data: code.to_vec(), destination: address.clone(), _gas_limit: *gas, value: *value }); - Ok((gas_left, Some(address))) + (gas_left, Some(address)) }, // creation failed only due to reaching max_depth - Ok((gas_left, None)) if ext.state.balance(&ext.params.address) >= *value => { + (gas_left, None) if ext.state.balance(&ext.params.address) >= *value => { let address = contract_address(&ext.params.address, &ext.state.nonce(&ext.params.address)); self.callcreates.push(CallCreate { data: code.to_vec(), @@ -97,9 +97,10 @@ impl<'a> Ext for TestExt<'a> { _gas_limit: *gas, value: *value }); - Ok((gas_left, Some(address))) + (gas_left, Some(address)) }, - other => other + // compiler is wrong... + _other => { unreachable!() } } } @@ -156,6 +157,7 @@ fn do_json_test(json_data: &[u8]) -> Vec { let json = Json::from_str(::std::str::from_utf8(json_data).unwrap()).expect("Json is invalid"); let mut failed = Vec::new(); for (name, test) in json.as_object().unwrap() { + println!("name: {:?}", name); // sync io is usefull when something crashes in jit //::std::io::stdout().write(&name.as_bytes()); //::std::io::stdout().write(b"\n"); diff --git a/src/tests/state.rs b/src/tests/state.rs index 10ad3a657..29fe30c96 100644 --- a/src/tests/state.rs +++ b/src/tests/state.rs @@ -10,6 +10,7 @@ fn do_json_test(json_data: &[u8]) -> Vec { let engine = ethereum::new_frontier_test().to_engine().unwrap(); for (name, test) in json.as_object().unwrap() { + println!("name: {:?}", name); let mut fail = false; let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.to_string()); fail = true; true } else {false};