From b85e75b9e819deeb316d26eb91fe07cfa23a05fb Mon Sep 17 00:00:00 2001 From: arkpar Date: Wed, 14 Jun 2017 19:56:01 +0200 Subject: [PATCH] eip214, #4833 --- ethcore/res/ethereum/frontier_like_test.json | 2 +- ethcore/res/ethereum/transition_test.json | 2 +- ethcore/src/client/test_client.rs | 4 +- ethcore/src/engines/authority_round.rs | 8 +-- ethcore/src/engines/instant_seal.rs | 7 -- ethcore/src/engines/mod.rs | 4 +- ethcore/src/engines/tendermint/mod.rs | 6 -- ethcore/src/ethereum/ethash.rs | 8 +-- ethcore/src/evm/evm.rs | 4 +- ethcore/src/evm/ext.rs | 21 +++--- ethcore/src/evm/instructions.rs | 3 + ethcore/src/evm/interpreter/gasometer.rs | 2 +- ethcore/src/evm/interpreter/mod.rs | 9 ++- ethcore/src/evm/schedule.rs | 37 ++++++++-- ethcore/src/evm/tests.rs | 21 +++--- ethcore/src/executive.rs | 33 +++++++-- ethcore/src/externalities.rs | 71 +++++++++++++------- ethcore/src/json_tests/executive.rs | 23 ++++--- ethcore/src/spec/spec.rs | 3 + ethcore/src/types/executed.rs | 7 ++ ethcore/src/types/trace_types/error.rs | 6 ++ json/src/spec/params.rs | 3 + rpc/src/v1/types/trace.rs | 4 ++ 23 files changed, 185 insertions(+), 103 deletions(-) diff --git a/ethcore/res/ethereum/frontier_like_test.json b/ethcore/res/ethereum/frontier_like_test.json index aab433033e6..fde04f6b596 100644 --- a/ethcore/res/ethereum/frontier_like_test.json +++ b/ethcore/res/ethereum/frontier_like_test.json @@ -12,7 +12,7 @@ "homesteadTransition": "0x118c30", "daoHardforkTransition": "0x1d4c00", "daoHardforkBeneficiary": "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", - "daoHardforkAccounts": [ + "daoHardforkAccounts": [ "0xd4fe7bc31cedb7bfb8a345f31e668033056b2728", "0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425", "0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f", diff --git a/ethcore/res/ethereum/transition_test.json b/ethcore/res/ethereum/transition_test.json index 41251dc8c31..7709ba01548 100644 --- a/ethcore/res/ethereum/transition_test.json +++ b/ethcore/res/ethereum/transition_test.json @@ -12,7 +12,7 @@ "homesteadTransition": "0x5", "daoHardforkTransition": "0x8", "daoHardforkBeneficiary": "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", - "daoHardforkAccounts": [ + "daoHardforkAccounts": [ "0xd4fe7bc31cedb7bfb8a345f31e668033056b2728", "0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425", "0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f", diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index a823e295f76..19c208b4590 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -55,7 +55,7 @@ pub struct TestBlockChainClient { /// Blocks. pub blocks: RwLock>, /// Mapping of numbers to hashes. - pub numbers: RwLock>, + pub numbers: RwLock>, /// Genesis block hash. pub genesis_hash: H256, /// Last block hash. @@ -353,7 +353,7 @@ pub fn get_temp_state_db() -> GuardedTempResult { impl MiningBlockChainClient for TestBlockChainClient { fn latest_schedule(&self) -> Schedule { - Schedule::new_post_eip150(24576, true, true, true, true) + Schedule::new_post_eip150(24576, true, true, true) } fn prepare_open_block(&self, author: Address, gas_range_target: (U256, U256), extra_data: Bytes) -> OpenBlock { diff --git a/ethcore/src/engines/authority_round.rs b/ethcore/src/engines/authority_round.rs index 84c1df8fc59..22860ebbd74 100644 --- a/ethcore/src/engines/authority_round.rs +++ b/ethcore/src/engines/authority_round.rs @@ -26,9 +26,8 @@ use account_provider::AccountProvider; use block::*; use spec::CommonParams; use engines::{Call, Engine, Seal, EngineError}; -use header::{Header, BlockNumber}; +use header::Header; use error::{Error, TransactionError, BlockError}; -use evm::Schedule; use ethjson; use io::{IoContext, IoHandler, TimerToken, IoService}; use builtin::Builtin; @@ -296,11 +295,6 @@ impl Engine for AuthorityRound { ] } - fn schedule(&self, block_number: BlockNumber) -> Schedule { - let eip86 = block_number >= self.params.eip86_transition; - Schedule::new_post_eip150(usize::max_value(), true, true, true, eip86) - } - fn populate_from_parent(&self, header: &mut Header, parent: &Header, gas_floor_target: U256, _gas_ceil_target: U256) { // Chain scoring: total weight is sqrt(U256::max_value())*height - step let new_difficulty = U256::from(U128::max_value()) + header_step(parent).expect("Header has been verified; qed").into() - self.step.load().into(); diff --git a/ethcore/src/engines/instant_seal.rs b/ethcore/src/engines/instant_seal.rs index 702afde4f4f..249aa8ac23c 100644 --- a/ethcore/src/engines/instant_seal.rs +++ b/ethcore/src/engines/instant_seal.rs @@ -19,9 +19,7 @@ use util::{Address, HashMap}; use builtin::Builtin; use engines::{Engine, Seal}; use spec::CommonParams; -use evm::Schedule; use block::ExecutedBlock; -use header::BlockNumber; /// An engine which does not provide any consensus mechanism, just seals blocks internally. pub struct InstantSeal { @@ -58,11 +56,6 @@ impl Engine for InstantSeal { &self.builtins } - fn schedule(&self, block_number: BlockNumber) -> Schedule { - let eip86 = block_number >= self.params.eip86_transition; - Schedule::new_post_eip150(usize::max_value(), true, true, true, eip86) - } - fn seals_internally(&self) -> Option { Some(true) } fn generate_seal(&self, _block: &ExecutedBlock) -> Seal { diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index 7d3963eace2..849e08cf227 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -147,7 +147,9 @@ pub trait Engine : Sync + Send { fn params(&self) -> &CommonParams; /// Get the EVM schedule for the given `block_number`. - fn schedule(&self, block_number: BlockNumber) -> Schedule; + fn schedule(&self, block_number: BlockNumber) -> Schedule { + Schedule::from_params(block_number, self.params()) + } /// Builtin-contracts we would like to see in the chain. /// (In principle these are just hints for the engine since that has the last word on them.) diff --git a/ethcore/src/engines/tendermint/mod.rs b/ethcore/src/engines/tendermint/mod.rs index 98e274e9b3b..1a462a634ad 100644 --- a/ethcore/src/engines/tendermint/mod.rs +++ b/ethcore/src/engines/tendermint/mod.rs @@ -38,7 +38,6 @@ use account_provider::AccountProvider; use block::*; use spec::CommonParams; use engines::{Engine, Seal, EngineError}; -use evm::Schedule; use state::CleanupMode; use io::IoService; use super::signer::EngineSigner; @@ -404,11 +403,6 @@ impl Engine for Tendermint { ] } - fn schedule(&self, block_number: BlockNumber) -> Schedule { - let eip86 = block_number >= self.params.eip86_transition; - Schedule::new_post_eip150(usize::max_value(), true, true, true, eip86) - } - fn populate_from_parent(&self, header: &mut Header, parent: &Header, gas_floor_target: U256, _gas_ceil_target: U256) { // Chain scoring: total weight is sqrt(U256::max_value())*height - view let new_difficulty = U256::from(U128::max_value()) + consensus_view(parent).expect("Header has been verified; qed").into() - self.view.load(AtomicOrdering::SeqCst).into(); diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 1013612e89b..2566846669c 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -196,13 +196,13 @@ impl Engine for Arc { } else if block_number < self.ethash_params.eip150_transition { Schedule::new_homestead() } else { - Schedule::new_post_eip150( + let mut schedule = Schedule::new_post_eip150( self.ethash_params.max_code_size as usize, block_number >= self.ethash_params.eip160_transition, block_number >= self.ethash_params.eip161abc_transition, - block_number >= self.ethash_params.eip161d_transition, - block_number >= self.params.eip86_transition - ) + block_number >= self.ethash_params.eip161d_transition); + schedule.apply_params(block_number, self.params()); + schedule } } diff --git a/ethcore/src/evm/evm.rs b/ethcore/src/evm/evm.rs index a644fd255b6..31ecb13f84a 100644 --- a/ethcore/src/evm/evm.rs +++ b/ethcore/src/evm/evm.rs @@ -62,7 +62,8 @@ pub enum Error { }, /// Built-in contract failed on given input BuiltIn(&'static str), - /// Returned on evm internal error. Should never be ignored during development. + /// When execution tries to modify the state in static context + MutableCallInStaticContext, /// Likely to cause consensus issues. Internal(String), } @@ -90,6 +91,7 @@ impl fmt::Display for Error { OutOfStack { instruction, wanted, limit } => write!(f, "Out of stack {} {}/{}", instruction, wanted, limit), BuiltIn(name) => write!(f, "Built-in failed: {}", name), Internal(ref msg) => write!(f, "Internal error: {}", msg), + MutableCallInStaticContext => write!(f, "Mutable call in static context"), } } } diff --git a/ethcore/src/evm/ext.rs b/ethcore/src/evm/ext.rs index 2eb99fe7c53..c66d1d3fffa 100644 --- a/ethcore/src/evm/ext.rs +++ b/ethcore/src/evm/ext.rs @@ -53,25 +53,24 @@ pub enum CreateContractAddress { } /// Externalities interface for EVMs -// TODO: [rob] associated error type instead of `trie::Result`. Not all EVMs are trie powered. pub trait Ext { /// Returns a value for given key. - fn storage_at(&self, key: &H256) -> trie::Result; + fn storage_at(&self, key: &H256) -> evm::Result; /// Stores a value for given key. - fn set_storage(&mut self, key: H256, value: H256) -> trie::Result<()>; + fn set_storage(&mut self, key: H256, value: H256) -> evm::Result<()>; /// Determine whether an account exists. - fn exists(&self, address: &Address) -> trie::Result; + fn exists(&self, address: &Address) -> evm::Result; /// Determine whether an account exists and is not null (zero balance/nonce, no code). - fn exists_and_not_null(&self, address: &Address) -> trie::Result; + fn exists_and_not_null(&self, address: &Address) -> evm::Result; /// Balance of the origin account. - fn origin_balance(&self) -> trie::Result; + fn origin_balance(&self) -> evm::Result; /// Returns address balance. - fn balance(&self, address: &Address) -> trie::Result; + fn balance(&self, address: &Address) -> evm::Result; /// Returns the hash of one of the 256 most recent complete blocks. fn blockhash(&mut self, number: &U256) -> H256; @@ -99,13 +98,13 @@ pub trait Ext { ) -> MessageCallResult; /// Returns code at given address - fn extcode(&self, address: &Address) -> trie::Result>; + fn extcode(&self, address: &Address) -> evm::Result>; /// Returns code size at given address - fn extcodesize(&self, address: &Address) -> trie::Result; + fn extcodesize(&self, address: &Address) -> evm::Result; /// Creates log entry with given topics and data - fn log(&mut self, topics: Vec, data: &[u8]); + fn log(&mut self, topics: Vec, data: &[u8]) -> evm::Result<()>; /// Should be called when transaction calls `RETURN` opcode. /// Returns gas_left if cost of returning the data is not too high. @@ -113,7 +112,7 @@ pub trait Ext { /// Should be called when contract commits suicide. /// Address to which funds should be refunded. - fn suicide(&mut self, refund_address: &Address) -> trie::Result<()> ; + fn suicide(&mut self, refund_address: &Address) -> evm::Result<()> ; /// Returns schedule. fn schedule(&self) -> &Schedule; diff --git a/ethcore/src/evm/instructions.rs b/ethcore/src/evm/instructions.rs index 351517386fb..83be0c95460 100644 --- a/ethcore/src/evm/instructions.rs +++ b/ethcore/src/evm/instructions.rs @@ -298,6 +298,7 @@ lazy_static! { arr[CALLCODE as usize] = InstructionInfo::new("CALLCODE", 7, 1, GasPriceTier::Special); arr[RETURN as usize] = InstructionInfo::new("RETURN", 2, 0, GasPriceTier::Zero); arr[DELEGATECALL as usize] = InstructionInfo::new("DELEGATECALL", 6, 1, GasPriceTier::Special); + arr[STATICCALL as usize] = InstructionInfo::new("STATICCALL", 6, 1, GasPriceTier::Special); arr[SUICIDE as usize] = InstructionInfo::new("SUICIDE", 1, 0, GasPriceTier::Special); arr[CREATE2 as usize] = InstructionInfo::new("CREATE2", 3, 1, GasPriceTier::Special); arr[REVERT as usize] = InstructionInfo::new("REVERT", 2, 0, GasPriceTier::Zero); @@ -584,6 +585,8 @@ pub const DELEGATECALL: Instruction = 0xf4; pub const CREATE2: Instruction = 0xfb; /// stop execution and revert state changes. Return output data. pub const REVERT: Instruction = 0xfd; +/// like CALL but it does not take value, nor modify the state +pub const STATICCALL: Instruction = 0xfa; /// halt execution and register account for later deletion pub const SUICIDE: Instruction = 0xff; diff --git a/ethcore/src/evm/interpreter/gasometer.rs b/ethcore/src/evm/interpreter/gasometer.rs index e76a5971e0c..426b8ffd075 100644 --- a/ethcore/src/evm/interpreter/gasometer.rs +++ b/ethcore/src/evm/interpreter/gasometer.rs @@ -213,7 +213,7 @@ impl Gasometer { Request::GasMemProvide(gas, mem, Some(requested)) }, - instructions::DELEGATECALL => { + instructions::DELEGATECALL | instructions::STATICCALL => { let gas = Gas::from(schedule.call_gas); let mem = cmp::max( mem_needed(stack.peek(4), stack.peek(5))?, diff --git a/ethcore/src/evm/interpreter/mod.rs b/ethcore/src/evm/interpreter/mod.rs index 32d010daf28..a4ff69c2a84 100644 --- a/ethcore/src/evm/interpreter/mod.rs +++ b/ethcore/src/evm/interpreter/mod.rs @@ -199,6 +199,7 @@ impl Interpreter { if (instruction == instructions::DELEGATECALL && !schedule.have_delegate_call) || (instruction == instructions::CREATE2 && !schedule.have_create2) || + (instruction == instructions::STATICCALL && !schedule.have_static_call) || (instruction == instructions::REVERT && !schedule.have_revert) { return Err(evm::Error::BadInstruction { @@ -312,14 +313,15 @@ impl Interpreter { } }; }, - instructions::CALL | instructions::CALLCODE | instructions::DELEGATECALL => { + instructions::CALL | instructions::CALLCODE | instructions::DELEGATECALL | instructions::STATICCALL => { assert!(ext.schedule().call_value_transfer_gas > ext.schedule().call_stipend, "overflow possible"); + stack.pop_back(); let call_gas = provided.expect("`provided` comes through Self::exec from `Gasometer::get_gas_cost_mem`; `gas_gas_mem_cost` guarantees `Some` when instruction is `CALL`/`CALLCODE`/`DELEGATECALL`/`CREATE`; this is one of `CALL`/`CALLCODE`/`DELEGATECALL`; qed"); let code_address = stack.pop_back(); let code_address = u256_to_address(&code_address); - let value = if instruction == instructions::DELEGATECALL { + let value = if instruction == instructions::DELEGATECALL || instruction == instructions::STATICCALL { None } else { Some(stack.pop_back()) @@ -347,6 +349,7 @@ impl Interpreter { (¶ms.address, ¶ms.address, has_balance, CallType::CallCode) }, instructions::DELEGATECALL => (¶ms.sender, ¶ms.address, true, CallType::DelegateCall), + instructions::STATICCALL => (¶ms.sender, ¶ms.address, true, CallType::StaticCall), _ => panic!(format!("Unexpected instruction {} in CALL branch.", instruction)) }; @@ -405,7 +408,7 @@ impl Interpreter { .iter() .map(H256::from) .collect(); - ext.log(topics, self.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); diff --git a/ethcore/src/evm/schedule.rs b/ethcore/src/evm/schedule.rs index 7fafb2e1203..de440676735 100644 --- a/ethcore/src/evm/schedule.rs +++ b/ethcore/src/evm/schedule.rs @@ -15,6 +15,7 @@ // along with Parity. If not, see . //! Cost schedule and other parameterisations for the EVM. +use spec::CommonParams; /// Definition of the cost schedule and other parameterisations for the EVM. pub struct Schedule { @@ -105,6 +106,8 @@ pub struct Schedule { pub kill_empty: bool, /// Blockhash instruction gas cost. pub blockhash_gas: usize, + /// Static Call opcode enabled. + pub have_static_call: bool, } impl Schedule { @@ -119,12 +122,12 @@ impl Schedule { } /// Schedule for the post-EIP-150-era of the Ethereum main net. - pub fn new_post_eip150(max_code_size: usize, fix_exp: bool, no_empty: bool, kill_empty: bool, have_metropolis_instructions: bool) -> Schedule { + pub fn new_post_eip150(max_code_size: usize, fix_exp: bool, no_empty: bool, kill_empty: bool) -> Schedule { Schedule { exceptional_failed_code_deposit: true, have_delegate_call: true, - have_create2: have_metropolis_instructions, - have_revert: have_metropolis_instructions, + have_create2: false, + have_revert: false, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], @@ -163,13 +166,36 @@ impl Schedule { sub_gas_cap_divisor: Some(64), no_empty: no_empty, kill_empty: kill_empty, - blockhash_gas: if have_metropolis_instructions { 350 } else { 20 }, + blockhash_gas: 20, + have_static_call: false, + } + } + + /// Schedule for the Metropolis era from common spec params. + pub fn from_params(block_number: u64, params: &CommonParams) -> Schedule { + let mut schedule = Schedule::new_post_eip150(usize::max_value(), true, true, true); + schedule.apply_params(block_number, params); + schedule + } + + /// Apply common spec config parameters to the schedule. + pub fn apply_params(&mut self, block_number: u64, params: &CommonParams) { + self.have_create2 = block_number >= params.eip86_transition; + self.have_revert = block_number >= params.eip140_transition; + self.have_static_call = block_number >= params.eip214_transition; + if block_number >= params.eip210_transition { + self.blockhash_gas = 350; } } /// Schedule for the Metropolis of the Ethereum main net. pub fn new_metropolis() -> Schedule { - Self::new_post_eip150(24576, true, true, true, true) + let mut schedule = Self::new_post_eip150(24576, true, true, true); + schedule.have_create2 = true; + schedule.have_revert = true; + schedule.have_static_call = true; + schedule.blockhash_gas = 350; + schedule } fn new(efcd: bool, hdc: bool, tcg: usize) -> Schedule { @@ -217,6 +243,7 @@ impl Schedule { no_empty: false, kill_empty: false, blockhash_gas: 20, + have_static_call: false, } } } diff --git a/ethcore/src/evm/tests.rs b/ethcore/src/evm/tests.rs index 462a632b4a2..7f3cf0e1c34 100644 --- a/ethcore/src/evm/tests.rs +++ b/ethcore/src/evm/tests.rs @@ -87,28 +87,28 @@ impl Default for Schedule { } impl Ext for FakeExt { - fn storage_at(&self, key: &H256) -> trie::Result { + fn storage_at(&self, key: &H256) -> evm::Result { Ok(self.store.get(key).unwrap_or(&H256::new()).clone()) } - fn set_storage(&mut self, key: H256, value: H256) -> trie::Result<()> { + fn set_storage(&mut self, key: H256, value: H256) -> evm::Result<()> { self.store.insert(key, value); Ok(()) } - fn exists(&self, address: &Address) -> trie::Result { + fn exists(&self, address: &Address) -> evm::Result { Ok(self.balances.contains_key(address)) } - fn exists_and_not_null(&self, address: &Address) -> trie::Result { + fn exists_and_not_null(&self, address: &Address) -> evm::Result { Ok(self.balances.get(address).map_or(false, |b| !b.is_zero())) } - fn origin_balance(&self) -> trie::Result { + fn origin_balance(&self) -> evm::Result { unimplemented!() } - fn balance(&self, address: &Address) -> trie::Result { + fn balance(&self, address: &Address) -> evm::Result { Ok(self.balances[address]) } @@ -152,26 +152,27 @@ impl Ext for FakeExt { MessageCallResult::Success(*gas, ReturnData::empty()) } - fn extcode(&self, address: &Address) -> trie::Result> { + fn extcode(&self, address: &Address) -> evm::Result> { Ok(self.codes.get(address).unwrap_or(&Arc::new(Bytes::new())).clone()) } - fn extcodesize(&self, address: &Address) -> trie::Result { + fn extcodesize(&self, address: &Address) -> evm::Result { Ok(self.codes.get(address).map_or(0, |c| c.len())) } - fn log(&mut self, topics: Vec, data: &[u8]) { + fn log(&mut self, topics: Vec, data: &[u8]) -> evm::Result<()> { self.logs.push(FakeLogEntry { topics: topics, data: data.to_vec() }); + Ok(()) } fn ret(self, _gas: &U256, _data: &ReturnData) -> evm::Result { unimplemented!(); } - fn suicide(&mut self, _refund_address: &Address) -> trie::Result<()> { + fn suicide(&mut self, _refund_address: &Address) -> evm::Result<()> { unimplemented!(); } diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index 4dbee6bde6e..7e582ccae56 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -76,6 +76,7 @@ pub struct Executive<'a, B: 'a + StateBackend, E: 'a + Engine + ?Sized> { info: &'a EnvInfo, engine: &'a E, depth: usize, + static_flag: bool, } impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { @@ -86,16 +87,18 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { info: info, engine: engine, depth: 0, + static_flag: false, } } /// Populates executive from parent properties. Increments executive depth. - pub fn from_parent(state: &'a mut State, info: &'a EnvInfo, engine: &'a E, parent_depth: usize) -> Self { + pub fn from_parent(state: &'a mut State, info: &'a EnvInfo, engine: &'a E, parent_depth: usize, static_flag: bool) -> Self { Executive { state: state, info: info, engine: engine, depth: parent_depth + 1, + static_flag: static_flag, } } @@ -106,9 +109,11 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { substate: &'any mut Substate, output: OutputPolicy<'any, 'any>, tracer: &'any mut T, - vm_tracer: &'any mut V + vm_tracer: &'any mut V, + static_call: bool, ) -> Externalities<'any, T, V, B, E> where T: Tracer, V: VMTracer { - Externalities::new(self.state, self.info, self.engine, self.depth, origin_info, substate, output, tracer, vm_tracer) + let is_static = self.static_flag || static_call; + Externalities::new(self.state, self.info, self.engine, self.depth, origin_info, substate, output, tracer, vm_tracer, is_static) } /// This function should be used to execute transaction. @@ -246,11 +251,12 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { ) -> evm::Result where T: Tracer, V: VMTracer { let depth_threshold = ::io::LOCAL_STACK_SIZE.with(|sz| sz.get() / STACK_SIZE_PER_DEPTH); + let static_call = params.call_type == CallType::StaticCall; // Ordinary execution - keep VM in same thread if (self.depth + 1) % depth_threshold != 0 { let vm_factory = self.state.vm_factory(); - let mut ext = self.as_externalities(OriginInfo::from(¶ms), unconfirmed_substate, output_policy, tracer, vm_tracer); + let mut ext = self.as_externalities(OriginInfo::from(¶ms), unconfirmed_substate, output_policy, tracer, vm_tracer, static_call); trace!(target: "executive", "ext.schedule.have_delegate_call: {}", ext.schedule().have_delegate_call); return vm_factory.create(params.gas).exec(params, &mut ext).finalize(ext); } @@ -260,7 +266,7 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { // https://github.com/aturon/crossbeam/issues/16 crossbeam::scope(|scope| { let vm_factory = self.state.vm_factory(); - let mut ext = self.as_externalities(OriginInfo::from(¶ms), unconfirmed_substate, output_policy, tracer, vm_tracer); + let mut ext = self.as_externalities(OriginInfo::from(¶ms), unconfirmed_substate, output_policy, tracer, vm_tracer, static_call); scope.spawn(move || { vm_factory.create(params.gas).exec(params, &mut ext).finalize(ext) @@ -280,6 +286,15 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { tracer: &mut T, vm_tracer: &mut V ) -> evm::Result<(U256, ReturnData)> where T: Tracer, V: VMTracer { + + trace!("Executive::call(params={:?}) self.env_info={:?}", params, self.info); + if (params.call_type == CallType::StaticCall || + ((params.call_type == CallType::Call || params.call_type == CallType::DelegateCall) && + self.static_flag)) + && params.value.value() > 0.into() { + return Err(evm::Error::MutableCallInStaticContext); + } + // backup used in case of running out of gas self.state.checkpoint(); @@ -289,7 +304,6 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { if let ActionValue::Transfer(val) = params.value { self.state.transfer_balance(¶ms.sender, ¶ms.address, &val, substate.to_cleanup_mode(&schedule))?; } - trace!("Executive::call(params={:?}) self.env_info={:?}", params, self.info); // if destination is builtin, try to execute it if let Some(builtin) = self.engine.builtin(¶ms.code_address, self.info.number) { @@ -403,6 +417,12 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { return Err(evm::Error::OutOfGas); } + if params.call_type == CallType::StaticCall || self.static_flag { + let trace_info = tracer.prepare_trace_create(¶ms); + tracer.trace_failed_create(trace_info, vec![], evm::Error::MutableCallInStaticContext.into()); + return Err(evm::Error::MutableCallInStaticContext); + } + // backup used in case of running out of gas self.state.checkpoint(); @@ -541,6 +561,7 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { | Err(evm::Error::StackUnderflow {..}) | Err(evm::Error::BuiltIn {..}) | Err(evm::Error::OutOfStack {..}) + | Err(evm::Error::MutableCallInStaticContext) | Ok(FinalizationResult { apply_state: false, .. }) => { self.state.revert_to_checkpoint(); }, diff --git a/ethcore/src/externalities.rs b/ethcore/src/externalities.rs index d0895306eb7..72c13f0624f 100644 --- a/ethcore/src/externalities.rs +++ b/ethcore/src/externalities.rs @@ -40,7 +40,7 @@ pub struct OriginInfo { address: Address, origin: Address, gas_price: U256, - value: U256 + value: U256, } impl OriginInfo { @@ -52,7 +52,7 @@ impl OriginInfo { gas_price: params.gas_price, value: match params.value { ActionValue::Transfer(val) | ActionValue::Apparent(val) => val - } + }, } } } @@ -71,6 +71,7 @@ pub struct Externalities<'a, T: 'a, V: 'a, B: 'a, E: 'a + Engine + ?Sized> output: OutputPolicy<'a, 'a>, tracer: &'a mut T, vm_tracer: &'a mut V, + static_flag: bool, } impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Externalities<'a, T, V, B, E> @@ -87,6 +88,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Externalities<'a, T, V, B, E> output: OutputPolicy<'a, 'a>, tracer: &'a mut T, vm_tracer: &'a mut V, + static_flag: bool, ) -> Self { Externalities { state: state, @@ -99,6 +101,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Externalities<'a, T, V, B, E> output: output, tracer: tracer, vm_tracer: vm_tracer, + static_flag: static_flag, } } } @@ -106,26 +109,32 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Externalities<'a, T, V, B, E> impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> where T: Tracer, V: VMTracer, B: StateBackend, E: Engine + ?Sized { - fn storage_at(&self, key: &H256) -> trie::Result { - self.state.storage_at(&self.origin_info.address, key) + fn storage_at(&self, key: &H256) -> evm::Result { + self.state.storage_at(&self.origin_info.address, key).map_err(Into::into) } - fn set_storage(&mut self, key: H256, value: H256) -> trie::Result<()> { - self.state.set_storage(&self.origin_info.address, key, value) + fn set_storage(&mut self, key: H256, value: H256) -> evm::Result<()> { + if self.static_flag { + Err(evm::Error::MutableCallInStaticContext) + } else { + self.state.set_storage(&self.origin_info.address, key, value).map_err(Into::into) + } } - fn exists(&self, address: &Address) -> trie::Result { - self.state.exists(address) + fn exists(&self, address: &Address) -> evm::Result { + self.state.exists(address).map_err(Into::into) } - fn exists_and_not_null(&self, address: &Address) -> trie::Result { - self.state.exists_and_not_null(address) + fn exists_and_not_null(&self, address: &Address) -> evm::Result { + self.state.exists_and_not_null(address).map_err(Into::into) } - fn origin_balance(&self) -> trie::Result { self.balance(&self.origin_info.address) } + fn origin_balance(&self) -> evm::Result { + self.balance(&self.origin_info.address).map_err(Into::into) + } - fn balance(&self, address: &Address) -> trie::Result { - self.state.balance(address) + fn balance(&self, address: &Address) -> evm::Result { + self.state.balance(address).map_err(Into::into) } fn blockhash(&mut self, number: &U256) -> H256 { @@ -208,7 +217,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> return ContractCreateResult::Failed } } - let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth); + let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth, self.static_flag); // TODO: handle internal error separately match ex.create(params, self.substate, self.tracer, self.vm_tracer) { @@ -258,7 +267,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> params.value = ActionValue::Transfer(value); } - let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth); + let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth, self.static_flag); match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer, self.vm_tracer) { Ok((gas_left, return_data)) => MessageCallResult::Success(gas_left, return_data), @@ -266,11 +275,11 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> } } - fn extcode(&self, address: &Address) -> trie::Result> { + fn extcode(&self, address: &Address) -> evm::Result> { Ok(self.state.code(address)?.unwrap_or_else(|| Arc::new(vec![]))) } - fn extcodesize(&self, address: &Address) -> trie::Result { + fn extcodesize(&self, address: &Address) -> evm::Result { Ok(self.state.code_size(address)?.unwrap_or(0)) } @@ -312,18 +321,28 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> } } - fn log(&mut self, topics: Vec, data: &[u8]) { + fn log(&mut self, topics: Vec, data: &[u8]) -> evm::Result<()> { use log_entry::LogEntry; + if self.static_flag { + return Err(evm::Error::MutableCallInStaticContext); + } + let address = self.origin_info.address.clone(); self.substate.logs.push(LogEntry { address: address, topics: topics, data: data.to_vec() }); + + Ok(()) } - fn suicide(&mut self, refund_address: &Address) -> trie::Result<()> { + fn suicide(&mut self, refund_address: &Address) -> evm::Result<()> { + if self.static_flag { + return Err(evm::Error::MutableCallInStaticContext); + } + let address = self.origin_info.address.clone(); let balance = self.balance(&address)?; if &address == refund_address { @@ -434,7 +453,7 @@ mod tests { let mut tracer = NoopTracer; let mut vm_tracer = NoopVMTracer; - let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer); + let ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); assert_eq!(ext.env_info().number, 100); } @@ -446,7 +465,7 @@ mod tests { let mut tracer = NoopTracer; let mut vm_tracer = NoopVMTracer; - let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer); + let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap()); @@ -470,7 +489,7 @@ mod tests { let mut tracer = NoopTracer; let mut vm_tracer = NoopVMTracer; - let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer); + let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap()); @@ -485,7 +504,7 @@ mod tests { let mut tracer = NoopTracer; let mut vm_tracer = NoopVMTracer; - let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer); + let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); let mut output = vec![]; @@ -513,8 +532,8 @@ mod tests { let mut vm_tracer = NoopVMTracer; { - let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer); - ext.log(log_topics, &log_data); + let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); + ext.log(log_topics, &log_data).unwrap(); } assert_eq!(setup.sub_state.logs.len(), 1); @@ -530,7 +549,7 @@ mod tests { let mut vm_tracer = NoopVMTracer; { - let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer); + let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer, false); ext.suicide(refund_account).unwrap(); } diff --git a/ethcore/src/json_tests/executive.rs b/ethcore/src/json_tests/executive.rs index b2125909010..7e37818f227 100644 --- a/ethcore/src/json_tests/executive.rs +++ b/ethcore/src/json_tests/executive.rs @@ -75,9 +75,10 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> TestExt<'a, T, V, B, E> tracer: &'a mut T, vm_tracer: &'a mut V, ) -> trie::Result { + let static_call = false; Ok(TestExt { nonce: state.nonce(&address)?, - ext: Externalities::new(state, info, engine, depth, origin_info, substate, output, tracer, vm_tracer), + ext: Externalities::new(state, info, engine, depth, origin_info, substate, output, tracer, vm_tracer, static_call), callcreates: vec![], sender: address, }) @@ -87,27 +88,27 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> TestExt<'a, T, V, B, E> impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for TestExt<'a, T, V, B, E> where T: Tracer, V: VMTracer, B: StateBackend, E: Engine + ?Sized { - fn storage_at(&self, key: &H256) -> trie::Result { + fn storage_at(&self, key: &H256) -> evm::Result { self.ext.storage_at(key) } - fn set_storage(&mut self, key: H256, value: H256) -> trie::Result<()> { + fn set_storage(&mut self, key: H256, value: H256) -> evm::Result<()> { self.ext.set_storage(key, value) } - fn exists(&self, address: &Address) -> trie::Result { + fn exists(&self, address: &Address) -> evm::Result { self.ext.exists(address) } - fn exists_and_not_null(&self, address: &Address) -> trie::Result { + fn exists_and_not_null(&self, address: &Address) -> evm::Result { self.ext.exists_and_not_null(address) } - fn balance(&self, address: &Address) -> trie::Result { + fn balance(&self, address: &Address) -> evm::Result { self.ext.balance(address) } - fn origin_balance(&self) -> trie::Result { + fn origin_balance(&self) -> evm::Result { self.ext.origin_balance() } @@ -145,15 +146,15 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for TestExt<'a, T, V, B, E> MessageCallResult::Success(*gas, ReturnData::empty()) } - fn extcode(&self, address: &Address) -> trie::Result> { + fn extcode(&self, address: &Address) -> evm::Result> { self.ext.extcode(address) } - fn extcodesize(&self, address: &Address) -> trie::Result { + fn extcodesize(&self, address: &Address) -> evm::Result { self.ext.extcodesize(address) } - fn log(&mut self, topics: Vec, data: &[u8]) { + fn log(&mut self, topics: Vec, data: &[u8]) -> evm::Result<()> { self.ext.log(topics, data) } @@ -161,7 +162,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for TestExt<'a, T, V, B, E> self.ext.ret(gas, data) } - fn suicide(&mut self, refund_address: &Address) -> trie::Result<()> { + fn suicide(&mut self, refund_address: &Address) -> evm::Result<()> { self.ext.suicide(refund_address) } diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 819964aefbf..d1a7ce4849e 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -74,6 +74,8 @@ pub struct CommonParams { pub eip210_contract_gas: U256, /// Number of first block where EIP-211 (Metropolis: RETURNDATASIZE/RETURNDATACOPY) rules begin. pub eip211_transition: BlockNumber, + /// Number of first block where EIP-214 rules begin. + pub eip214_transition: BlockNumber, } impl From for CommonParams { @@ -97,6 +99,7 @@ impl From for CommonParams { Into::into), eip210_contract_gas: p.eip210_contract_gas.map_or(1000000.into(), Into::into), eip211_transition: p.eip211_transition.map_or(BlockNumber::max_value(), Into::into), + eip214_transition: p.eip214_transition.map_or(BlockNumber::max_value(), Into::into), } } } diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs index f18bd1bee47..571d8af97d9 100644 --- a/ethcore/src/types/executed.rs +++ b/ethcore/src/types/executed.rs @@ -36,6 +36,8 @@ pub enum CallType { CallCode, /// DELEGATECALL. DelegateCall, + /// STATICCALL + StaticCall, } impl Encodable for CallType { @@ -45,6 +47,7 @@ impl Encodable for CallType { CallType::Call => 1, CallType::CallCode => 2, CallType::DelegateCall => 3, + CallType::StaticCall => 4, }; Encodable::rlp_append(&v, s); } @@ -57,6 +60,7 @@ impl Decodable for CallType { 1 => CallType::Call, 2 => CallType::CallCode, 3 => CallType::DelegateCall, + 4 => CallType::StaticCall, _ => return Err(DecoderError::Custom("Invalid value of CallType item")), })) } @@ -145,6 +149,8 @@ pub enum ExecutionError { /// Actual balance. got: U512 }, + /// When execution tries to modify the state in static context + MutableCallInStaticContext, /// Returned when internal evm error occurs. Internal(String), /// Returned when generic transaction occurs @@ -172,6 +178,7 @@ impl fmt::Display for ExecutionError { NotEnoughCash { ref required, ref got } => format!("Cost of transaction exceeds sender balance. {} is required \ but the sender only has {}", required, got), + MutableCallInStaticContext => "Mutable Call in static context".to_owned(), Internal(ref msg) => msg.clone(), TransactionMalformed(ref err) => format!("Malformed transaction: {}", err), }; diff --git a/ethcore/src/types/trace_types/error.rs b/ethcore/src/types/trace_types/error.rs index 758c78eec8c..0348fc2a4c1 100644 --- a/ethcore/src/types/trace_types/error.rs +++ b/ethcore/src/types/trace_types/error.rs @@ -40,6 +40,8 @@ pub enum Error { /// Returned on evm internal error. Should never be ignored during development. /// Likely to cause consensus issues. Internal, + /// When execution tries to modify the state in static context + MutableCallInStaticContext, } impl<'a> From<&'a EvmError> for Error { @@ -52,6 +54,7 @@ impl<'a> From<&'a EvmError> for Error { EvmError::OutOfStack { .. } => Error::OutOfStack, EvmError::BuiltIn { .. } => Error::BuiltIn, EvmError::Internal(_) => Error::Internal, + EvmError::MutableCallInStaticContext => Error::MutableCallInStaticContext, } } } @@ -73,6 +76,7 @@ impl fmt::Display for Error { OutOfStack => "Out of stack", BuiltIn => "Built-in failed", Internal => "Internal error", + MutableCallInStaticContext => "Mutable Call In Static Context", }; message.fmt(f) } @@ -89,6 +93,7 @@ impl Encodable for Error { OutOfStack => 4, Internal => 5, BuiltIn => 6, + MutableCallInStaticContext => 7, }; s.append_internal(&value); @@ -107,6 +112,7 @@ impl Decodable for Error { 4 => Ok(OutOfStack), 5 => Ok(Internal), 6 => Ok(BuiltIn), + 7 => Ok(MutableCallInStaticContext), _ => Err(DecoderError::Custom("Invalid error type")), } } diff --git a/json/src/spec/params.rs b/json/src/spec/params.rs index fc69435c961..b170674261f 100644 --- a/json/src/spec/params.rs +++ b/json/src/spec/params.rs @@ -78,6 +78,9 @@ pub struct Params { /// See `CommonParams` docs. #[serde(rename="eip211Transition")] pub eip211_transition: Option, + /// See `CommonParams` docs. + #[serde(rename="eip214Transition")] + pub eip214_transition: Option, } #[cfg(test)] diff --git a/rpc/src/v1/types/trace.rs b/rpc/src/v1/types/trace.rs index f911004211a..084c19cd168 100644 --- a/rpc/src/v1/types/trace.rs +++ b/rpc/src/v1/types/trace.rs @@ -251,6 +251,9 @@ pub enum CallType { /// Delegate call #[serde(rename="delegatecall")] DelegateCall, + /// Static call + #[serde(rename="staticcall")] + StaticCall, } impl From for CallType { @@ -260,6 +263,7 @@ impl From for CallType { executed::CallType::Call => CallType::Call, executed::CallType::CallCode => CallType::CallCode, executed::CallType::DelegateCall => CallType::DelegateCall, + executed::CallType::StaticCall => CallType::StaticCall, } } }