// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see .
//! Transaction Execution environment.
use std::cmp;
use std::sync::Arc;
use ethereum_types::{H256, U256, Address};
use bytes::Bytes;
use state::{Backend as StateBackend, State, Substate, CleanupMode};
use machine::EthereumMachine as Machine;
use executive::*;
use vm::{
self, ActionParams, ActionValue, EnvInfo, CallType, Schedule,
Ext, ContractCreateResult, MessageCallResult, CreateContractAddress,
ReturnData, TrapKind
};
use types::transaction::UNSIGNED_SENDER;
use trace::{Tracer, VMTracer};
/// Policy for handling output data on `RETURN` opcode.
pub enum OutputPolicy {
/// Return reference to fixed sized output.
/// Used for message calls.
Return,
/// Init new contract as soon as `RETURN` is called.
InitContract,
}
/// Transaction properties that externalities need to know about.
pub struct OriginInfo {
address: Address,
origin: Address,
gas_price: U256,
value: U256,
}
impl OriginInfo {
/// Populates origin info from action params.
pub fn from(params: &ActionParams) -> Self {
OriginInfo {
address: params.address.clone(),
origin: params.origin.clone(),
gas_price: params.gas_price,
value: match params.value {
ActionValue::Transfer(val) | ActionValue::Apparent(val) => val
},
}
}
}
/// Implementation of evm Externalities.
pub struct Externalities<'a, T: 'a, V: 'a, B: 'a> {
state: &'a mut State,
env_info: &'a EnvInfo,
depth: usize,
stack_depth: usize,
origin_info: &'a OriginInfo,
substate: &'a mut Substate,
machine: &'a Machine,
schedule: &'a Schedule,
output: OutputPolicy,
tracer: &'a mut T,
vm_tracer: &'a mut V,
static_flag: bool,
}
impl<'a, T: 'a, V: 'a, B: 'a> Externalities<'a, T, V, B>
where T: Tracer, V: VMTracer, B: StateBackend
{
/// Basic `Externalities` constructor.
pub fn new(
state: &'a mut State,
env_info: &'a EnvInfo,
machine: &'a Machine,
schedule: &'a Schedule,
depth: usize,
stack_depth: usize,
origin_info: &'a OriginInfo,
substate: &'a mut Substate,
output: OutputPolicy,
tracer: &'a mut T,
vm_tracer: &'a mut V,
static_flag: bool,
) -> Self {
Externalities {
state: state,
env_info: env_info,
depth: depth,
stack_depth: stack_depth,
origin_info: origin_info,
substate: substate,
machine: machine,
schedule: schedule,
output: output,
tracer: tracer,
vm_tracer: vm_tracer,
static_flag: static_flag,
}
}
}
impl<'a, T: 'a, V: 'a, B: 'a> Ext for Externalities<'a, T, V, B>
where T: Tracer, V: VMTracer, B: StateBackend
{
fn initial_storage_at(&self, key: &H256) -> vm::Result {
if self.state.is_base_storage_root_unchanged(&self.origin_info.address)? {
self.state.checkpoint_storage_at(0, &self.origin_info.address, key).map(|v| v.unwrap_or_default()).map_err(Into::into)
} else {
warn!(target: "externalities", "Detected existing account {:#x} where a forced contract creation happened.", self.origin_info.address);
Ok(H256::zero())
}
}
fn storage_at(&self, key: &H256) -> vm::Result {
self.state.storage_at(&self.origin_info.address, key).map_err(Into::into)
}
fn set_storage(&mut self, key: H256, value: H256) -> vm::Result<()> {
if self.static_flag {
Err(vm::Error::MutableCallInStaticContext)
} else {
self.state.set_storage(&self.origin_info.address, key, value).map_err(Into::into)
}
}
fn is_static(&self) -> bool {
return self.static_flag
}
fn exists(&self, address: &Address) -> vm::Result {
self.state.exists(address).map_err(Into::into)
}
fn exists_and_not_null(&self, address: &Address) -> vm::Result {
self.state.exists_and_not_null(address).map_err(Into::into)
}
fn origin_balance(&self) -> vm::Result {
self.balance(&self.origin_info.address).map_err(Into::into)
}
fn balance(&self, address: &Address) -> vm::Result {
self.state.balance(address).map_err(Into::into)
}
fn blockhash(&mut self, number: &U256) -> H256 {
if self.env_info.number + 256 >= self.machine.params().eip210_transition {
let blockhash_contract_address = self.machine.params().eip210_contract_address;
let code_res = self.state.code(&blockhash_contract_address)
.and_then(|code| self.state.code_hash(&blockhash_contract_address).map(|hash| (code, hash)));
let (code, code_hash) = match code_res {
Ok((code, hash)) => (code, hash),
Err(_) => return H256::zero(),
};
let params = ActionParams {
sender: self.origin_info.address.clone(),
address: blockhash_contract_address.clone(),
value: ActionValue::Apparent(self.origin_info.value),
code_address: blockhash_contract_address.clone(),
origin: self.origin_info.origin.clone(),
gas: self.machine.params().eip210_contract_gas,
gas_price: 0.into(),
code: code,
code_hash: code_hash,
data: Some(H256::from(number).to_vec()),
call_type: CallType::Call,
params_type: vm::ParamsType::Separate,
};
let mut ex = Executive::new(self.state, self.env_info, self.machine, self.schedule);
let r = ex.call_with_crossbeam(params, self.substate, self.stack_depth + 1, self.tracer, self.vm_tracer);
let output = match &r {
Ok(ref r) => H256::from(&r.return_data[..32]),
_ => H256::new(),
};
trace!("ext: blockhash contract({}) -> {:?}({}) self.env_info.number={}\n", number, r, output, self.env_info.number);
output
} else {
// TODO: comment out what this function expects from env_info, since it will produce panics if the latter is inconsistent
match *number < U256::from(self.env_info.number) && number.low_u64() >= cmp::max(256, self.env_info.number) - 256 {
true => {
let index = self.env_info.number - number.low_u64() - 1;
assert!(index < self.env_info.last_hashes.len() as u64, format!("Inconsistent env_info, should contain at least {:?} last hashes", index+1));
let r = self.env_info.last_hashes[index as usize].clone();
trace!("ext: blockhash({}) -> {} self.env_info.number={}\n", number, r, self.env_info.number);
r
},
false => {
trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number);
H256::zero()
},
}
}
}
fn create(
&mut self,
gas: &U256,
value: &U256,
code: &[u8],
address_scheme: CreateContractAddress,
trap: bool,
) -> ::std::result::Result {
// create new contract address
let (address, code_hash) = match self.state.nonce(&self.origin_info.address) {
Ok(nonce) => contract_address(address_scheme, &self.origin_info.address, &nonce, &code),
Err(e) => {
debug!(target: "ext", "Database corruption encountered: {:?}", e);
return Ok(ContractCreateResult::Failed)
}
};
// prepare the params
let params = ActionParams {
code_address: address.clone(),
address: address.clone(),
sender: self.origin_info.address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
value: ActionValue::Transfer(*value),
code: Some(Arc::new(code.to_vec())),
code_hash: code_hash,
data: None,
call_type: CallType::None,
params_type: vm::ParamsType::Embedded,
};
if !self.static_flag {
if !self.schedule.keep_unsigned_nonce || params.sender != UNSIGNED_SENDER {
if let Err(e) = self.state.inc_nonce(&self.origin_info.address) {
debug!(target: "ext", "Database corruption encountered: {:?}", e);
return Ok(ContractCreateResult::Failed)
}
}
}
if trap {
return Err(TrapKind::Create(params, address));
}
// TODO: handle internal error separately
let mut ex = Executive::from_parent(self.state, self.env_info, self.machine, self.schedule, self.depth, self.static_flag);
let out = ex.create_with_crossbeam(params, self.substate, self.stack_depth + 1, self.tracer, self.vm_tracer);
Ok(into_contract_create_result(out, &address, self.substate))
}
fn call(
&mut self,
gas: &U256,
sender_address: &Address,
receive_address: &Address,
value: Option,
data: &[u8],
code_address: &Address,
call_type: CallType,
trap: bool,
) -> ::std::result::Result {
trace!(target: "externalities", "call");
let code_res = self.state.code(code_address)
.and_then(|code| self.state.code_hash(code_address).map(|hash| (code, hash)));
let (code, code_hash) = match code_res {
Ok((code, hash)) => (code, hash),
Err(_) => return Ok(MessageCallResult::Failed),
};
let mut params = ActionParams {
sender: sender_address.clone(),
address: receive_address.clone(),
value: ActionValue::Apparent(self.origin_info.value),
code_address: code_address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
code: code,
code_hash: code_hash,
data: Some(data.to_vec()),
call_type: call_type,
params_type: vm::ParamsType::Separate,
};
if let Some(value) = value {
params.value = ActionValue::Transfer(value);
}
if trap {
return Err(TrapKind::Call(params));
}
let mut ex = Executive::from_parent(self.state, self.env_info, self.machine, self.schedule, self.depth, self.static_flag);
let out = ex.call_with_crossbeam(params, self.substate, self.stack_depth + 1, self.tracer, self.vm_tracer);
Ok(into_message_call_result(out))
}
fn extcode(&self, address: &Address) -> vm::Result