mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 01:11:10 +00:00
Contracts module rejig (#1358)
* Move prepare under code. * Schedule update * CodeHash * create takes code_hash * pass mem def and use code in vm::execute * Actually save and load code * Use T::Hash as CodeHash * Explicit entrypoint name * Return code_hash and deposit an Event * Charge for deployed code with gas. * ImportSatisfyCheck and FunctionImplProvider * Progress. * Use new infrastructure for checking imports * Rename entrypoint to entrypoint_name * Use strings instead of a Error enum * Clean * WIP * Fix macro_define_env test. * Fix vm code tests. * Remove tests for now. * Fix borked merge * Fix build for wasm * fmt * Scaffolding for abstracting vm. * Hook up execution to exec layer. * Fix vm tests. * Use schedule directly in WasmLoader * Implement test language. * Add input_data test. * Max depth test * ext_caller * Simplify test. * Add TODO * Some tests and todos. * top_level * Clean. * Restore a couple of integration tests. * Add a few comments. * Add ext_address runtime call. * Deduplicate caller/self_account * Add not_exists test. * Change bool to TransferCause. * Add address tests. * Remove output_buf from parameter. * return from start fn. * Smart gas meter * Tracing * Fix prepare tests. * Code moving * Add ExecFeeToken * Use tokens everywhere. * Make it compile in no_std. * Lift all test requirements to TestAuxiliaries * A minor clean * First create tests * Remove unneeded TODO * Docs. * Code shuffling * Rename create → instantiate * Add test address. * Code shuffling * Add base_fee tests. * rejig the code * Add some comments * on_finalise comment * Move event deposit further * Update Cargo.lock * Use crates.io version of pwasm-utils * Format todo comments * Fix formatting * Comments * EmptyOutputBuf and OutputBuf split. * Restore code_hash * Fix node-executor. * Fix typo * Fix fmt * Update srml/contract/src/account_db.rs Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Update srml/contract/src/lib.rs Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Line wraps * Wrapping macros * Add _ prefix * Grumbles * Doc updates. * Update srml/contract/src/wasm/mod.rs Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Update srml/contract/src/lib.rs Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Add comment * Use saturation to signal overflow * Add prepare_test! macro * Require deploy function. * Add entry point tests * Add comment. * Rename code → code_cache to better describe * Get rid of weird match! * Recompile binaries * Add comments * refuse_instantiate_with_value_below_existential_deposit * Little fix * Make test more complete * Clean * Add integration test for instantiation * Rebuild runtime. * Add some tests. * Attach an issue to a TODO * Attach another issue * Apply suggestions from code review Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Update srml/contract/src/exec.rs Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Update srml/contract/src/exec.rs Co-Authored-By: pepyakin <s.pepyakin@gmail.com> * Recompile node_runtime
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! A module that implements instrumented code cache.
|
||||
//!
|
||||
//! - In order to run contract code we need to instrument it with gas metering.
|
||||
//! To do that we need to provide the schedule which will supply exact gas costs values.
|
||||
//! We cache this code in the storage saving the schedule version.
|
||||
//! - Before running contract code we check if the cached code has the schedule version that is equal to the current saved schedule.
|
||||
//! If it is equal then run the code, if it isn't reinstrument with the current schedule.
|
||||
//! - When we update the schedule we want it to have strictly greater version than the current saved one:
|
||||
//! this guarantees that every instrumented contract code in cache cannot have the version equal to the current one.
|
||||
//! Thus, before executing a contract it should be reinstrument with new schedule.
|
||||
|
||||
use gas::{GasMeter, Token};
|
||||
use rstd::prelude::*;
|
||||
use runtime_primitives::traits::{As, CheckedMul, Hash, Bounded};
|
||||
use runtime_support::StorageMap;
|
||||
use wasm::{prepare, runtime::Env, PrefabWasmModule};
|
||||
use {CodeHash, CodeStorage, PristineCode, Schedule, Trait};
|
||||
|
||||
/// Gas metering token that used for charging storing code into the code storage.
|
||||
///
|
||||
/// Specifies the code length in bytes.
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct PutCodeToken(u64);
|
||||
|
||||
impl<T: Trait> Token<T> for PutCodeToken {
|
||||
type Metadata = Schedule<T::Gas>;
|
||||
|
||||
fn calculate_amount(&self, metadata: &Schedule<T::Gas>) -> T::Gas {
|
||||
let code_len_in_gas = <T::Gas as As<u64>>::sa(self.0);
|
||||
metadata
|
||||
.put_code_per_byte_cost
|
||||
.checked_mul(&code_len_in_gas)
|
||||
.unwrap_or_else(|| Bounded::max_value())
|
||||
}
|
||||
}
|
||||
|
||||
/// Put code in the storage. The hash of code is used as a key and is returned
|
||||
/// as a result of this function.
|
||||
///
|
||||
/// This function instruments the given code and caches it in the storage.
|
||||
pub fn save<T: Trait>(
|
||||
original_code: Vec<u8>,
|
||||
gas_meter: &mut GasMeter<T>,
|
||||
schedule: &Schedule<T::Gas>,
|
||||
) -> Result<CodeHash<T>, &'static str> {
|
||||
// The first time instrumentation is on the user. However, consequent reinstrumentation
|
||||
// due to the schedule changes is on governance system.
|
||||
if gas_meter
|
||||
.charge(schedule, PutCodeToken(original_code.len() as u64))
|
||||
.is_out_of_gas()
|
||||
{
|
||||
return Err("there is not enough gas for storing the code");
|
||||
}
|
||||
|
||||
let prefab_module = prepare::prepare_contract::<T, Env>(&original_code, schedule)?;
|
||||
let code_hash = T::Hashing::hash(&original_code);
|
||||
|
||||
// TODO: #1416 validate the code. If the code is not valid, then don't store it.
|
||||
|
||||
<CodeStorage<T>>::insert(code_hash, prefab_module);
|
||||
<PristineCode<T>>::insert(code_hash, original_code);
|
||||
|
||||
Ok(code_hash)
|
||||
}
|
||||
|
||||
/// Load code with the given code hash.
|
||||
///
|
||||
/// If the module was instrumented with a lower version of schedule than
|
||||
/// the current one given as an argument, then this function will perform
|
||||
/// re-instrumentation and update the cache in the storage.
|
||||
pub fn load<T: Trait>(
|
||||
code_hash: &CodeHash<T>,
|
||||
schedule: &Schedule<T::Gas>,
|
||||
) -> Result<PrefabWasmModule, &'static str> {
|
||||
let mut prefab_module =
|
||||
<CodeStorage<T>>::get(code_hash).ok_or_else(|| "code is not found")?;
|
||||
|
||||
if prefab_module.schedule_version < schedule.version {
|
||||
// The current schedule version is greater than the version of the one cached
|
||||
// in the storage.
|
||||
//
|
||||
// We need to re-instrument the code with the latest schedule here.
|
||||
let original_code =
|
||||
<PristineCode<T>>::get(code_hash).ok_or_else(|| "pristine code is not found")?;
|
||||
prefab_module = prepare::prepare_contract::<T, Env>(&original_code, schedule)?;
|
||||
<CodeStorage<T>>::insert(code_hash, prefab_module.clone());
|
||||
}
|
||||
Ok(prefab_module)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Definition of macros that hides boilerplate of defining external environment
|
||||
//! for a wasm module.
|
||||
//!
|
||||
//! Most likely you should use `define_env` macro.
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! convert_args {
|
||||
() => (vec![]);
|
||||
( $( $t:ty ),* ) => ( vec![ $( { use $crate::wasm::env_def::ConvertibleToWasm; <$t>::VALUE_TYPE }, )* ] );
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! gen_signature {
|
||||
( ( $( $params: ty ),* ) ) => (
|
||||
{
|
||||
$crate::parity_wasm::elements::FunctionType::new(convert_args!($($params),*), None)
|
||||
}
|
||||
);
|
||||
|
||||
( ( $( $params: ty ),* ) -> $returns: ty ) => (
|
||||
{
|
||||
$crate::parity_wasm::elements::FunctionType::new(convert_args!($($params),*), Some({
|
||||
use $crate::wasm::env_def::ConvertibleToWasm; <$returns>::VALUE_TYPE
|
||||
}))
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! gen_signature_dispatch {
|
||||
(
|
||||
$needle_name:ident,
|
||||
$needle_sig:ident ;
|
||||
$name:ident
|
||||
( $ctx:ident $( , $names:ident : $params:ty )* ) $( -> $returns:ty )* , $($rest:tt)* ) => {
|
||||
if stringify!($name).as_bytes() == $needle_name {
|
||||
let signature = gen_signature!( ( $( $params ),* ) $( -> $returns )* );
|
||||
if $needle_sig == &signature {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
gen_signature_dispatch!($needle_name, $needle_sig ; $($rest)*);
|
||||
}
|
||||
};
|
||||
( $needle_name:ident, $needle_sig:ident ; ) => {
|
||||
};
|
||||
}
|
||||
|
||||
/// Unmarshall arguments and then execute `body` expression and return its result.
|
||||
macro_rules! unmarshall_then_body {
|
||||
( $body:tt, $ctx:ident, $args_iter:ident, $( $names:ident : $params:ty ),* ) => ({
|
||||
$(
|
||||
let $names : <$params as $crate::wasm::env_def::ConvertibleToWasm>::NativeType =
|
||||
$args_iter.next()
|
||||
.and_then(|v| <$params as $crate::wasm::env_def::ConvertibleToWasm>
|
||||
::from_typed_value(v.clone()))
|
||||
.expect(
|
||||
"precondition: all imports should be checked against the signatures of corresponding
|
||||
functions defined by `define_env!` macro by the user of the macro;
|
||||
signatures of these functions defined by `$params`;
|
||||
calls always made with arguments types of which are defined by the corresponding imports;
|
||||
thus types of arguments should be equal to type list in `$params` and
|
||||
length of argument list and $params should be equal;
|
||||
thus this can never be `None`;
|
||||
qed;
|
||||
"
|
||||
);
|
||||
)*
|
||||
$body
|
||||
})
|
||||
}
|
||||
|
||||
/// Since we can't specify the type of closure directly at binding site:
|
||||
///
|
||||
/// ```nocompile
|
||||
/// let f: FnOnce() -> Result<<u32 as ConvertibleToWasm>::NativeType, _> = || { /* ... */ };
|
||||
/// ```
|
||||
///
|
||||
/// we use this function to constrain the type of the closure.
|
||||
#[inline(always)]
|
||||
pub fn constrain_closure<R, F>(f: F) -> F
|
||||
where
|
||||
F: FnOnce() -> Result<R, ::sandbox::HostError>,
|
||||
{
|
||||
f
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! unmarshall_then_body_then_marshall {
|
||||
( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) -> $returns:ty => $body:tt ) => ({
|
||||
let body = $crate::wasm::env_def::macros::constrain_closure::<
|
||||
<$returns as $crate::wasm::env_def::ConvertibleToWasm>::NativeType, _
|
||||
>(|| {
|
||||
unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*)
|
||||
});
|
||||
let r = body()?;
|
||||
return Ok($crate::sandbox::ReturnValue::Value({ use $crate::wasm::env_def::ConvertibleToWasm; r.to_typed_value() }))
|
||||
});
|
||||
( $args_iter:ident, $ctx:ident, ( $( $names:ident : $params:ty ),* ) => $body:tt ) => ({
|
||||
let body = $crate::wasm::env_def::macros::constrain_closure::<(), _>(|| {
|
||||
unmarshall_then_body!($body, $ctx, $args_iter, $( $names : $params ),*)
|
||||
});
|
||||
body()?;
|
||||
return Ok($crate::sandbox::ReturnValue::Unit)
|
||||
})
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! define_func {
|
||||
( < E: $ext_ty:tt > $name:ident ( $ctx: ident $(, $names:ident : $params:ty)*) $(-> $returns:ty)* => $body:tt ) => {
|
||||
fn $name< E: $ext_ty >(
|
||||
$ctx: &mut $crate::wasm::Runtime<E>,
|
||||
args: &[$crate::sandbox::TypedValue],
|
||||
) -> Result<sandbox::ReturnValue, sandbox::HostError> {
|
||||
#[allow(unused)]
|
||||
let mut args = args.iter();
|
||||
|
||||
unmarshall_then_body_then_marshall!(
|
||||
args,
|
||||
$ctx,
|
||||
( $( $names : $params ),* ) $( -> $returns )* => $body
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! register_func {
|
||||
( $reg_cb:ident, < E: $ext_ty:tt > ; ) => {};
|
||||
|
||||
( $reg_cb:ident, < E: $ext_ty:tt > ;
|
||||
$name:ident ( $ctx:ident $( , $names:ident : $params:ty )* )
|
||||
$( -> $returns:ty )* => $body:tt $($rest:tt)*
|
||||
) => {
|
||||
$reg_cb(
|
||||
stringify!($name).as_bytes(),
|
||||
{
|
||||
define_func!(
|
||||
< E: $ext_ty > $name ( $ctx $(, $names : $params )* ) $( -> $returns )* => $body
|
||||
);
|
||||
$name::<E>
|
||||
}
|
||||
);
|
||||
register_func!( $reg_cb, < E: $ext_ty > ; $($rest)* );
|
||||
};
|
||||
}
|
||||
|
||||
/// Define a function set that can be imported by executing wasm code.
|
||||
///
|
||||
/// **NB**: Be advised that all functions defined by this macro
|
||||
/// will panic if called with unexpected arguments.
|
||||
///
|
||||
/// It's up to the user of this macro to check signatures of wasm code to be executed
|
||||
/// and reject the code if any imported function has a mismached signature.
|
||||
macro_rules! define_env {
|
||||
( $init_name:ident , < E: $ext_ty:tt > ,
|
||||
$( $name:ident ( $ctx:ident $( , $names:ident : $params:ty )* )
|
||||
$( -> $returns:ty )* => $body:tt , )*
|
||||
) => {
|
||||
pub struct $init_name;
|
||||
|
||||
impl $crate::wasm::env_def::ImportSatisfyCheck for $init_name {
|
||||
fn can_satisfy(name: &[u8], func_type: &$crate::parity_wasm::elements::FunctionType) -> bool {
|
||||
gen_signature_dispatch!( name, func_type ; $( $name ( $ctx $(, $names : $params )* ) $( -> $returns )* , )* );
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: Ext> $crate::wasm::env_def::FunctionImplProvider<E> for $init_name {
|
||||
fn impls<F: FnMut(&[u8], $crate::wasm::env_def::HostFunc<E>)>(f: &mut F) {
|
||||
register_func!(f, < E: $ext_ty > ; $( $name ( $ctx $( , $names : $params )* ) $( -> $returns)* => $body )* );
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use parity_wasm::elements::FunctionType;
|
||||
use parity_wasm::elements::ValueType;
|
||||
use runtime_primitives::traits::{As, Zero};
|
||||
use sandbox::{self, ReturnValue, TypedValue};
|
||||
use wasm::tests::MockExt;
|
||||
use wasm::Runtime;
|
||||
use exec::Ext;
|
||||
use Trait;
|
||||
|
||||
#[test]
|
||||
fn macro_unmarshall_then_body_then_marshall_value_or_trap() {
|
||||
fn test_value(
|
||||
_ctx: &mut u32,
|
||||
args: &[sandbox::TypedValue],
|
||||
) -> Result<ReturnValue, sandbox::HostError> {
|
||||
let mut args = args.iter();
|
||||
unmarshall_then_body_then_marshall!(
|
||||
args,
|
||||
_ctx,
|
||||
(a: u32, b: u32) -> u32 => {
|
||||
if b == 0 {
|
||||
Err(sandbox::HostError)
|
||||
} else {
|
||||
Ok(a / b)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
let ctx = &mut 0;
|
||||
assert_eq!(
|
||||
test_value(ctx, &[TypedValue::I32(15), TypedValue::I32(3)]).unwrap(),
|
||||
ReturnValue::Value(TypedValue::I32(5)),
|
||||
);
|
||||
assert!(test_value(ctx, &[TypedValue::I32(15), TypedValue::I32(0)]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_unmarshall_then_body_then_marshall_unit() {
|
||||
fn test_unit(
|
||||
ctx: &mut u32,
|
||||
args: &[sandbox::TypedValue],
|
||||
) -> Result<ReturnValue, sandbox::HostError> {
|
||||
let mut args = args.iter();
|
||||
unmarshall_then_body_then_marshall!(
|
||||
args,
|
||||
ctx,
|
||||
(a: u32, b: u32) => {
|
||||
*ctx = a + b;
|
||||
Ok(())
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
let ctx = &mut 0;
|
||||
let result = test_unit(ctx, &[TypedValue::I32(2), TypedValue::I32(3)]).unwrap();
|
||||
assert_eq!(result, ReturnValue::Unit);
|
||||
assert_eq!(*ctx, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_define_func() {
|
||||
define_func!( <E: Ext> ext_gas (_ctx, amount: u32) => {
|
||||
let amount = <<E::T as Trait>::Gas as As<u32>>::sa(amount);
|
||||
if !amount.is_zero() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(sandbox::HostError)
|
||||
}
|
||||
});
|
||||
let _f: fn(&mut Runtime<MockExt>, &[sandbox::TypedValue])
|
||||
-> Result<sandbox::ReturnValue, sandbox::HostError> = ext_gas::<MockExt>;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_gen_signature() {
|
||||
assert_eq!(
|
||||
gen_signature!((i32)),
|
||||
FunctionType::new(vec![ValueType::I32], None),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
gen_signature!( (i32, u32) -> u32 ),
|
||||
FunctionType::new(vec![ValueType::I32, ValueType::I32], Some(ValueType::I32)),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_unmarshall_then_body() {
|
||||
let args = vec![TypedValue::I32(5), TypedValue::I32(3)];
|
||||
let mut args = args.iter();
|
||||
|
||||
let ctx: &mut u32 = &mut 0;
|
||||
|
||||
let r = unmarshall_then_body!(
|
||||
{
|
||||
*ctx = a + b;
|
||||
a * b
|
||||
},
|
||||
ctx,
|
||||
args,
|
||||
a: u32,
|
||||
b: u32
|
||||
);
|
||||
|
||||
assert_eq!(*ctx, 8);
|
||||
assert_eq!(r, 15);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_define_env() {
|
||||
use wasm::env_def::ImportSatisfyCheck;
|
||||
|
||||
define_env!(Env, <E: Ext>,
|
||||
ext_gas( _ctx, amount: u32 ) => {
|
||||
let amount = <<E::T as Trait>::Gas as As<u32>>::sa(amount);
|
||||
if !amount.is_zero() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(sandbox::HostError)
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
assert!(Env::can_satisfy(b"ext_gas", &FunctionType::new(vec![ValueType::I32], None)));
|
||||
assert!(!Env::can_satisfy(b"not_exists", &FunctionType::new(vec![], None)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use super::Runtime;
|
||||
use exec::Ext;
|
||||
use parity_wasm::elements::{FunctionType, ValueType};
|
||||
use sandbox::{self, TypedValue};
|
||||
|
||||
#[macro_use]
|
||||
pub(crate) mod macros;
|
||||
|
||||
pub trait ConvertibleToWasm: Sized {
|
||||
const VALUE_TYPE: ValueType;
|
||||
type NativeType;
|
||||
fn to_typed_value(self) -> TypedValue;
|
||||
fn from_typed_value(TypedValue) -> Option<Self>;
|
||||
}
|
||||
impl ConvertibleToWasm for i32 {
|
||||
type NativeType = i32;
|
||||
const VALUE_TYPE: ValueType = ValueType::I32;
|
||||
fn to_typed_value(self) -> TypedValue {
|
||||
TypedValue::I32(self)
|
||||
}
|
||||
fn from_typed_value(v: TypedValue) -> Option<Self> {
|
||||
v.as_i32()
|
||||
}
|
||||
}
|
||||
impl ConvertibleToWasm for u32 {
|
||||
type NativeType = u32;
|
||||
const VALUE_TYPE: ValueType = ValueType::I32;
|
||||
fn to_typed_value(self) -> TypedValue {
|
||||
TypedValue::I32(self as i32)
|
||||
}
|
||||
fn from_typed_value(v: TypedValue) -> Option<Self> {
|
||||
match v {
|
||||
TypedValue::I32(v) => Some(v as u32),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ConvertibleToWasm for u64 {
|
||||
type NativeType = u64;
|
||||
const VALUE_TYPE: ValueType = ValueType::I64;
|
||||
fn to_typed_value(self) -> TypedValue {
|
||||
TypedValue::I64(self as i64)
|
||||
}
|
||||
fn from_typed_value(v: TypedValue) -> Option<Self> {
|
||||
match v {
|
||||
TypedValue::I64(v) => Some(v as u64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type HostFunc<E> =
|
||||
fn(
|
||||
&mut Runtime<E>,
|
||||
&[sandbox::TypedValue]
|
||||
) -> Result<sandbox::ReturnValue, sandbox::HostError>;
|
||||
|
||||
pub(crate) trait FunctionImplProvider<E: Ext> {
|
||||
fn impls<F: FnMut(&[u8], HostFunc<E>)>(f: &mut F);
|
||||
}
|
||||
|
||||
/// This trait can be used to check whether the host environment can satisfy
|
||||
/// a requested function import.
|
||||
pub trait ImportSatisfyCheck {
|
||||
/// Returns `true` if the host environment contains a function with
|
||||
/// the specified name and its type matches to the given type, or `false`
|
||||
/// otherwise.
|
||||
fn can_satisfy(name: &[u8], func_type: &FunctionType) -> bool;
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! This module provides a means for executing contracts
|
||||
//! represented in wasm.
|
||||
|
||||
use codec::Compact;
|
||||
use exec::{Ext, EmptyOutputBuf, VmExecResult};
|
||||
use gas::GasMeter;
|
||||
use rstd::prelude::*;
|
||||
use sandbox;
|
||||
use wasm::env_def::FunctionImplProvider;
|
||||
use {CodeHash, Schedule, Trait};
|
||||
|
||||
#[macro_use]
|
||||
mod env_def;
|
||||
mod code_cache;
|
||||
mod prepare;
|
||||
mod runtime;
|
||||
|
||||
use self::runtime::{to_execution_result, Runtime};
|
||||
use self::code_cache::load as load_code;
|
||||
|
||||
pub use self::code_cache::save as save_code;
|
||||
|
||||
/// A prepared wasm module ready for execution.
|
||||
#[derive(Clone, Encode, Decode)]
|
||||
pub struct PrefabWasmModule {
|
||||
/// Version of the schedule with which the code was instrumented.
|
||||
#[codec(compact)]
|
||||
schedule_version: u32,
|
||||
#[codec(compact)]
|
||||
initial: u32,
|
||||
#[codec(compact)]
|
||||
maximum: u32,
|
||||
/// This field is reserved for future evolution of format.
|
||||
///
|
||||
/// Basically, for now this field will be serialized as `None`. In the future
|
||||
/// we would be able to extend this structure with.
|
||||
_reserved: Option<()>,
|
||||
/// Code instrumented with the latest schedule.
|
||||
code: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Wasm executable loaded by `WasmLoader` and executed by `WasmVm`.
|
||||
pub struct WasmExecutable {
|
||||
entrypoint_name: &'static [u8],
|
||||
prefab_module: PrefabWasmModule,
|
||||
}
|
||||
|
||||
/// Loader which fetches `WasmExecutable` from the code cache.
|
||||
pub struct WasmLoader<'a, T: Trait> {
|
||||
schedule: &'a Schedule<T::Gas>,
|
||||
}
|
||||
|
||||
impl<'a, T: Trait> WasmLoader<'a, T> {
|
||||
pub fn new(schedule: &'a Schedule<T::Gas>) -> Self {
|
||||
WasmLoader { schedule }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Trait> ::exec::Loader<T> for WasmLoader<'a, T> {
|
||||
type Executable = WasmExecutable;
|
||||
|
||||
fn load_init(&self, code_hash: &CodeHash<T>) -> Result<WasmExecutable, &'static str> {
|
||||
let prefab_module = load_code::<T>(code_hash, self.schedule)?;
|
||||
Ok(WasmExecutable {
|
||||
entrypoint_name: b"deploy",
|
||||
prefab_module,
|
||||
})
|
||||
}
|
||||
fn load_main(&self, code_hash: &CodeHash<T>) -> Result<WasmExecutable, &'static str> {
|
||||
let prefab_module = load_code::<T>(code_hash, self.schedule)?;
|
||||
Ok(WasmExecutable {
|
||||
entrypoint_name: b"call",
|
||||
prefab_module,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation of `Vm` that takes `WasmExecutable` and executes it.
|
||||
pub struct WasmVm<'a, T: Trait> {
|
||||
schedule: &'a Schedule<T::Gas>,
|
||||
}
|
||||
|
||||
impl<'a, T: Trait> WasmVm<'a, T> {
|
||||
pub fn new(schedule: &'a Schedule<T::Gas>) -> Self {
|
||||
WasmVm { schedule }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Trait> ::exec::Vm<T> for WasmVm<'a, T> {
|
||||
type Executable = WasmExecutable;
|
||||
|
||||
fn execute<E: Ext<T = T>>(
|
||||
&self,
|
||||
exec: &WasmExecutable,
|
||||
ext: &mut E,
|
||||
input_data: &[u8],
|
||||
empty_output_buf: EmptyOutputBuf,
|
||||
gas_meter: &mut GasMeter<E::T>,
|
||||
) -> VmExecResult {
|
||||
let memory =
|
||||
sandbox::Memory::new(exec.prefab_module.initial, Some(exec.prefab_module.maximum))
|
||||
.unwrap_or_else(|_| {
|
||||
// unlike `.expect`, explicit panic preserves the source location.
|
||||
// Needed as we can't use `RUST_BACKTRACE` in here.
|
||||
panic!(
|
||||
"exec.prefab_module.initial can't be greater than exec.prefab_module.maximum;
|
||||
thus Memory::new must not fail;
|
||||
qed"
|
||||
)
|
||||
});
|
||||
|
||||
let mut imports = sandbox::EnvironmentDefinitionBuilder::new();
|
||||
imports.add_memory("env", "memory", memory.clone());
|
||||
runtime::Env::impls(&mut |name, func_ptr| {
|
||||
imports.add_host_func("env", name, func_ptr);
|
||||
});
|
||||
|
||||
let mut runtime = Runtime::new(
|
||||
ext,
|
||||
input_data,
|
||||
empty_output_buf,
|
||||
&self.schedule,
|
||||
memory,
|
||||
gas_meter,
|
||||
);
|
||||
|
||||
// Instantiate the instance from the instrumented module code.
|
||||
match sandbox::Instance::new(&exec.prefab_module.code, &imports, &mut runtime) {
|
||||
// No errors or traps were generated on instantiation! That
|
||||
// means we can now invoke the contract entrypoint.
|
||||
Ok(mut instance) => {
|
||||
let err = instance
|
||||
.invoke(exec.entrypoint_name, &[], &mut runtime)
|
||||
.err();
|
||||
to_execution_result(runtime, err)
|
||||
}
|
||||
// `start` function trapped. Treat it in the same manner as an execution error.
|
||||
Err(err @ sandbox::Error::Execution) => to_execution_result(runtime, Some(err)),
|
||||
Err(_err @ sandbox::Error::Module) => {
|
||||
// `Error::Module` is returned only if instantiation or linking failed (i.e.
|
||||
// wasm bianry tried to import a function that is not provided by the host).
|
||||
// This shouldn't happen because validation proccess ought to reject such binaries.
|
||||
//
|
||||
// Because panics are really undesirable in the runtime code, we treat this as
|
||||
// a trap for now. Eventually, we might want to revisit this.
|
||||
return VmExecResult::Trap("validation error");
|
||||
}
|
||||
// Other instantiation errors.
|
||||
// Return without executing anything.
|
||||
Err(_) => return VmExecResult::Trap("during start function"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
use substrate_primitives::H256;
|
||||
use exec::{CallReceipt, Ext, InstantiateReceipt, EmptyOutputBuf};
|
||||
use gas::GasMeter;
|
||||
use tests::Test;
|
||||
use wabt;
|
||||
use wasm::prepare::prepare_contract;
|
||||
use CodeHash;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct CreateEntry {
|
||||
code_hash: H256,
|
||||
endowment: u64,
|
||||
data: Vec<u8>,
|
||||
gas_left: u64,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct TransferEntry {
|
||||
to: u64,
|
||||
value: u64,
|
||||
data: Vec<u8>,
|
||||
gas_left: u64,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct MockExt {
|
||||
storage: HashMap<Vec<u8>, Vec<u8>>,
|
||||
creates: Vec<CreateEntry>,
|
||||
transfers: Vec<TransferEntry>,
|
||||
next_account_id: u64,
|
||||
}
|
||||
impl Ext for MockExt {
|
||||
type T = Test;
|
||||
|
||||
fn get_storage(&self, key: &[u8]) -> Option<Vec<u8>> {
|
||||
self.storage.get(key).cloned()
|
||||
}
|
||||
fn set_storage(&mut self, key: &[u8], value: Option<Vec<u8>>) {
|
||||
*self.storage.entry(key.to_vec()).or_insert(Vec::new()) = value.unwrap_or(Vec::new());
|
||||
}
|
||||
fn instantiate(
|
||||
&mut self,
|
||||
code_hash: &CodeHash<Test>,
|
||||
endowment: u64,
|
||||
gas_meter: &mut GasMeter<Test>,
|
||||
data: &[u8],
|
||||
) -> Result<InstantiateReceipt<u64>, &'static str> {
|
||||
self.creates.push(CreateEntry {
|
||||
code_hash: code_hash.clone(),
|
||||
endowment,
|
||||
data: data.to_vec(),
|
||||
gas_left: gas_meter.gas_left(),
|
||||
});
|
||||
let address = self.next_account_id;
|
||||
self.next_account_id += 1;
|
||||
|
||||
Ok(InstantiateReceipt { address })
|
||||
}
|
||||
fn call(
|
||||
&mut self,
|
||||
to: &u64,
|
||||
value: u64,
|
||||
gas_meter: &mut GasMeter<Test>,
|
||||
data: &[u8],
|
||||
_output_data: EmptyOutputBuf,
|
||||
) -> Result<CallReceipt, &'static str> {
|
||||
self.transfers.push(TransferEntry {
|
||||
to: *to,
|
||||
value,
|
||||
data: data.to_vec(),
|
||||
gas_left: gas_meter.gas_left(),
|
||||
});
|
||||
// Assume for now that it was just a plain transfer.
|
||||
// TODO: Add tests for different call outcomes.
|
||||
Ok(CallReceipt {
|
||||
output_data: Vec::new(),
|
||||
})
|
||||
}
|
||||
fn caller(&self) -> &u64 {
|
||||
&42
|
||||
}
|
||||
fn address(&self) -> &u64 {
|
||||
&69
|
||||
}
|
||||
}
|
||||
|
||||
fn execute<E: Ext>(
|
||||
wat: &str,
|
||||
input_data: &[u8],
|
||||
output_data: &mut Vec<u8>,
|
||||
ext: &mut E,
|
||||
gas_meter: &mut GasMeter<E::T>,
|
||||
) -> Result<(), &'static str> {
|
||||
use exec::Vm;
|
||||
|
||||
let wasm = wabt::wat2wasm(wat).unwrap();
|
||||
let schedule = ::Schedule::<u64>::default();
|
||||
let prefab_module =
|
||||
prepare_contract::<Test, super::runtime::Env>(&wasm, &schedule).unwrap();
|
||||
|
||||
let exec = WasmExecutable {
|
||||
// Use a "call" convention.
|
||||
entrypoint_name: b"call",
|
||||
prefab_module,
|
||||
};
|
||||
|
||||
let cfg = Default::default();
|
||||
let vm = WasmVm::new(&cfg);
|
||||
|
||||
*output_data = vm
|
||||
.execute(&exec, ext, input_data, EmptyOutputBuf::new(), gas_meter)
|
||||
.into_result()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const CODE_TRANSFER: &str = r#"
|
||||
(module
|
||||
;; ext_call(
|
||||
;; callee_ptr: u32,
|
||||
;; callee_len: u32,
|
||||
;; gas: u64,
|
||||
;; value_ptr: u32,
|
||||
;; value_len: u32,
|
||||
;; input_data_ptr: u32,
|
||||
;; input_data_len: u32
|
||||
;;) -> u32
|
||||
(import "env" "ext_call" (func $ext_call (param i32 i32 i64 i32 i32 i32 i32) (result i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
(func (export "call")
|
||||
(drop
|
||||
(call $ext_call
|
||||
(i32.const 4) ;; Pointer to "callee" address.
|
||||
(i32.const 8) ;; Length of "callee" address.
|
||||
(i64.const 0) ;; How much gas to devote for the execution. 0 = all.
|
||||
(i32.const 12) ;; Pointer to the buffer with value to transfer
|
||||
(i32.const 8) ;; Length of the buffer with value to transfer.
|
||||
(i32.const 20) ;; Pointer to input data buffer address
|
||||
(i32.const 4) ;; Length of input data buffer
|
||||
)
|
||||
)
|
||||
)
|
||||
(func (export "deploy"))
|
||||
|
||||
;; Destination AccountId to transfer the funds.
|
||||
;; Represented by u64 (8 bytes long) in little endian.
|
||||
(data (i32.const 4) "\09\00\00\00\00\00\00\00")
|
||||
;; Amount of value to transfer.
|
||||
;; Represented by u64 (8 bytes long) in little endian.
|
||||
(data (i32.const 12) "\06\00\00\00\00\00\00\00")
|
||||
|
||||
(data (i32.const 20) "\01\02\03\04")
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn contract_transfer() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
execute(
|
||||
CODE_TRANSFER,
|
||||
&[],
|
||||
&mut Vec::new(),
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
&mock_ext.transfers,
|
||||
&[TransferEntry {
|
||||
to: 9,
|
||||
value: 6,
|
||||
data: vec![1, 2, 3, 4],
|
||||
gas_left: 49970,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
const CODE_CREATE: &str = r#"
|
||||
(module
|
||||
;; ext_create(
|
||||
;; code_ptr: u32,
|
||||
;; code_len: u32,
|
||||
;; gas: u64,
|
||||
;; value_ptr: u32,
|
||||
;; value_len: u32,
|
||||
;; input_data_ptr: u32,
|
||||
;; input_data_len: u32,
|
||||
;; ) -> u32
|
||||
(import "env" "ext_create" (func $ext_create (param i32 i32 i64 i32 i32 i32 i32) (result i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
(func (export "call")
|
||||
(drop
|
||||
(call $ext_create
|
||||
(i32.const 16) ;; Pointer to `code_hash`
|
||||
(i32.const 32) ;; Length of `code_hash`
|
||||
(i64.const 0) ;; How much gas to devote for the execution. 0 = all.
|
||||
(i32.const 4) ;; Pointer to the buffer with value to transfer
|
||||
(i32.const 8) ;; Length of the buffer with value to transfer
|
||||
(i32.const 12) ;; Pointer to input data buffer address
|
||||
(i32.const 4) ;; Length of input data buffer
|
||||
)
|
||||
)
|
||||
)
|
||||
(func (export "deploy"))
|
||||
|
||||
;; Amount of value to transfer.
|
||||
;; Represented by u64 (8 bytes long) in little endian.
|
||||
(data (i32.const 4) "\03\00\00\00\00\00\00\00")
|
||||
;; Input data to pass to the contract being created.
|
||||
(data (i32.const 12) "\01\02\03\04")
|
||||
;; Hash of code.
|
||||
(data (i32.const 16) "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11")
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn contract_create() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
execute(
|
||||
CODE_CREATE,
|
||||
&[],
|
||||
&mut Vec::new(),
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
&mock_ext.creates,
|
||||
&[CreateEntry {
|
||||
code_hash: [0x11; 32].into(),
|
||||
endowment: 3,
|
||||
data: vec![1, 2, 3, 4],
|
||||
gas_left: 49946,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
const CODE_TRANSFER_LIMITED_GAS: &str = r#"
|
||||
(module
|
||||
;; ext_call(
|
||||
;; callee_ptr: u32,
|
||||
;; callee_len: u32,
|
||||
;; gas: u64,
|
||||
;; value_ptr: u32,
|
||||
;; value_len: u32,
|
||||
;; input_data_ptr: u32,
|
||||
;; input_data_len: u32
|
||||
;;) -> u32
|
||||
(import "env" "ext_call" (func $ext_call (param i32 i32 i64 i32 i32 i32 i32) (result i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
(func (export "call")
|
||||
(drop
|
||||
(call $ext_call
|
||||
(i32.const 4) ;; Pointer to "callee" address.
|
||||
(i32.const 8) ;; Length of "callee" address.
|
||||
(i64.const 228) ;; How much gas to devote for the execution.
|
||||
(i32.const 12) ;; Pointer to the buffer with value to transfer
|
||||
(i32.const 8) ;; Length of the buffer with value to transfer.
|
||||
(i32.const 20) ;; Pointer to input data buffer address
|
||||
(i32.const 4) ;; Length of input data buffer
|
||||
)
|
||||
)
|
||||
)
|
||||
(func (export "deploy"))
|
||||
|
||||
;; Destination AccountId to transfer the funds.
|
||||
;; Represented by u64 (8 bytes long) in little endian.
|
||||
(data (i32.const 4) "\09\00\00\00\00\00\00\00")
|
||||
;; Amount of value to transfer.
|
||||
;; Represented by u64 (8 bytes long) in little endian.
|
||||
(data (i32.const 12) "\06\00\00\00\00\00\00\00")
|
||||
|
||||
(data (i32.const 20) "\01\02\03\04")
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn contract_call_limited_gas() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
execute(
|
||||
&CODE_TRANSFER_LIMITED_GAS,
|
||||
&[],
|
||||
&mut Vec::new(),
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
&mock_ext.transfers,
|
||||
&[TransferEntry {
|
||||
to: 9,
|
||||
value: 6,
|
||||
data: vec![1, 2, 3, 4],
|
||||
gas_left: 228,
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
const CODE_GET_STORAGE: &str = r#"
|
||||
(module
|
||||
(import "env" "ext_get_storage" (func $ext_get_storage (param i32) (result i32)))
|
||||
(import "env" "ext_scratch_size" (func $ext_scratch_size (result i32)))
|
||||
(import "env" "ext_scratch_copy" (func $ext_scratch_copy (param i32 i32 i32)))
|
||||
(import "env" "ext_return" (func $ext_return (param i32 i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(func $assert (param i32)
|
||||
(block $ok
|
||||
(br_if $ok
|
||||
(get_local 0)
|
||||
)
|
||||
(unreachable)
|
||||
)
|
||||
)
|
||||
|
||||
(func (export "call")
|
||||
(local $buf_size i32)
|
||||
|
||||
|
||||
;; Load a storage value into the scratch buf.
|
||||
(call $assert
|
||||
(i32.eq
|
||||
(call $ext_get_storage
|
||||
(i32.const 4) ;; The pointer to the storage key to fetch
|
||||
)
|
||||
|
||||
;; Return value 0 means that the value is found and there were
|
||||
;; no errors.
|
||||
(i32.const 0)
|
||||
)
|
||||
)
|
||||
|
||||
;; Find out the size of the scratch buffer
|
||||
(set_local $buf_size
|
||||
(call $ext_scratch_size)
|
||||
)
|
||||
|
||||
;; Copy scratch buffer into this contract memory.
|
||||
(call $ext_scratch_copy
|
||||
(i32.const 36) ;; The pointer where to store the scratch buffer contents,
|
||||
;; 36 = 4 + 32
|
||||
(i32.const 0) ;; Offset from the start of the scratch buffer.
|
||||
(get_local ;; Count of bytes to copy.
|
||||
$buf_size
|
||||
)
|
||||
)
|
||||
|
||||
;; Return the contents of the buffer
|
||||
(call $ext_return
|
||||
(i32.const 36)
|
||||
(get_local $buf_size)
|
||||
)
|
||||
|
||||
;; env:ext_return doesn't return, so this is effectively unreachable.
|
||||
(unreachable)
|
||||
)
|
||||
|
||||
(func (export "deploy"))
|
||||
|
||||
(data (i32.const 4) "\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11")
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn get_storage_puts_data_into_scratch_buf() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
mock_ext
|
||||
.storage
|
||||
.insert([0x11; 32].to_vec(), [0x22; 32].to_vec());
|
||||
|
||||
let mut return_buf = Vec::new();
|
||||
execute(
|
||||
CODE_GET_STORAGE,
|
||||
&[],
|
||||
&mut return_buf,
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(return_buf, [0x22; 32].to_vec());
|
||||
}
|
||||
|
||||
/// calls `ext_caller`, loads the address from the scratch buffer and
|
||||
/// compares it with the constant 42.
|
||||
const CODE_CALLER: &'static str = r#"
|
||||
(module
|
||||
(import "env" "ext_caller" (func $ext_caller))
|
||||
(import "env" "ext_scratch_size" (func $ext_scratch_size (result i32)))
|
||||
(import "env" "ext_scratch_copy" (func $ext_scratch_copy (param i32 i32 i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(func $assert (param i32)
|
||||
(block $ok
|
||||
(br_if $ok
|
||||
(get_local 0)
|
||||
)
|
||||
(unreachable)
|
||||
)
|
||||
)
|
||||
|
||||
(func (export "call")
|
||||
;; fill the scratch buffer with the caller.
|
||||
(call $ext_caller)
|
||||
|
||||
;; assert $ext_scratch_size == 8
|
||||
(call $assert
|
||||
(i32.eq
|
||||
(call $ext_scratch_size)
|
||||
(i32.const 8)
|
||||
)
|
||||
)
|
||||
|
||||
;; copy contents of the scratch buffer into the contract's memory.
|
||||
(call $ext_scratch_copy
|
||||
(i32.const 8) ;; Pointer in memory to the place where to copy.
|
||||
(i32.const 0) ;; Offset from the start of the scratch buffer.
|
||||
(i32.const 8) ;; Count of bytes to copy.
|
||||
)
|
||||
|
||||
;; assert that contents of the buffer is equal to the i64 value of 42.
|
||||
(call $assert
|
||||
(i64.eq
|
||||
(i64.load
|
||||
(i32.const 8)
|
||||
)
|
||||
(i64.const 42)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn caller() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
execute(
|
||||
CODE_CALLER,
|
||||
&[],
|
||||
&mut Vec::new(),
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// calls `ext_address`, loads the address from the scratch buffer and
|
||||
/// compares it with the constant 69.
|
||||
const CODE_ADDRESS: &'static str = r#"
|
||||
(module
|
||||
(import "env" "ext_address" (func $ext_address))
|
||||
(import "env" "ext_scratch_size" (func $ext_scratch_size (result i32)))
|
||||
(import "env" "ext_scratch_copy" (func $ext_scratch_copy (param i32 i32 i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(func $assert (param i32)
|
||||
(block $ok
|
||||
(br_if $ok
|
||||
(get_local 0)
|
||||
)
|
||||
(unreachable)
|
||||
)
|
||||
)
|
||||
|
||||
(func (export "call")
|
||||
;; fill the scratch buffer with the self address.
|
||||
(call $ext_address)
|
||||
|
||||
;; assert $ext_scratch_size == 8
|
||||
(call $assert
|
||||
(i32.eq
|
||||
(call $ext_scratch_size)
|
||||
(i32.const 8)
|
||||
)
|
||||
)
|
||||
|
||||
;; copy contents of the scratch buffer into the contract's memory.
|
||||
(call $ext_scratch_copy
|
||||
(i32.const 8) ;; Pointer in memory to the place where to copy.
|
||||
(i32.const 0) ;; Offset from the start of the scratch buffer.
|
||||
(i32.const 8) ;; Count of bytes to copy.
|
||||
)
|
||||
|
||||
;; assert that contents of the buffer is equal to the i64 value of 69.
|
||||
(call $assert
|
||||
(i64.eq
|
||||
(i64.load
|
||||
(i32.const 8)
|
||||
)
|
||||
(i64.const 69)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn address() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
execute(
|
||||
CODE_ADDRESS,
|
||||
&[],
|
||||
&mut Vec::new(),
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
const CODE_RETURN_FROM_START_FN: &str = r#"
|
||||
(module
|
||||
(import "env" "ext_return" (func $ext_return (param i32 i32)))
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(start $start)
|
||||
(func $start
|
||||
(call $ext_return
|
||||
(i32.const 8)
|
||||
(i32.const 4)
|
||||
)
|
||||
(unreachable)
|
||||
)
|
||||
|
||||
(func (export "call")
|
||||
(unreachable)
|
||||
)
|
||||
(func (export "deploy"))
|
||||
|
||||
(data (i32.const 8) "\01\02\03\04")
|
||||
)
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn return_from_start_fn() {
|
||||
let mut mock_ext = MockExt::default();
|
||||
let mut output_data = Vec::new();
|
||||
execute(
|
||||
CODE_RETURN_FROM_START_FN,
|
||||
&[],
|
||||
&mut output_data,
|
||||
&mut mock_ext,
|
||||
&mut GasMeter::with_limit(50_000, 1),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(output_data, vec![1, 2, 3, 4]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! This module takes care of loading, checking and preprocessing of a
|
||||
//! wasm module before execution. It also extracts some essential information
|
||||
//! from a module.
|
||||
|
||||
use parity_wasm::elements::{self, Internal, External, MemoryType, Type};
|
||||
use pwasm_utils;
|
||||
use pwasm_utils::rules;
|
||||
use rstd::prelude::*;
|
||||
use runtime_primitives::traits::As;
|
||||
use wasm::env_def::ImportSatisfyCheck;
|
||||
use wasm::PrefabWasmModule;
|
||||
use {Schedule, Trait};
|
||||
|
||||
struct ContractModule<'a, Gas: 'a> {
|
||||
// An `Option` is used here for loaning (`take()`-ing) the module.
|
||||
// Invariant: Can't be `None` (i.e. on enter and on exit from the function
|
||||
// the value *must* be `Some`).
|
||||
module: Option<elements::Module>,
|
||||
schedule: &'a Schedule<Gas>,
|
||||
}
|
||||
|
||||
impl<'a, Gas: 'a + As<u32> + Clone> ContractModule<'a, Gas> {
|
||||
fn new(
|
||||
original_code: &[u8],
|
||||
schedule: &'a Schedule<Gas>,
|
||||
) -> Result<ContractModule<'a, Gas>, &'static str> {
|
||||
let module =
|
||||
elements::deserialize_buffer(original_code).map_err(|_| "can't decode wasm code")?;
|
||||
Ok(ContractModule {
|
||||
module: Some(module),
|
||||
schedule,
|
||||
})
|
||||
}
|
||||
|
||||
/// Ensures that module doesn't declare internal memories.
|
||||
///
|
||||
/// In this runtime we only allow wasm module to import memory from the environment.
|
||||
/// Memory section contains declarations of internal linear memories, so if we find one
|
||||
/// we reject such a module.
|
||||
fn ensure_no_internal_memory(&self) -> Result<(), &'static str> {
|
||||
let module = self
|
||||
.module
|
||||
.as_ref()
|
||||
.expect("On entry to the function `module` can't be None; qed");
|
||||
if module
|
||||
.memory_section()
|
||||
.map_or(false, |ms| ms.entries().len() > 0)
|
||||
{
|
||||
return Err("module declares internal memory");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inject_gas_metering(&mut self) -> Result<(), &'static str> {
|
||||
let gas_rules =
|
||||
rules::Set::new(
|
||||
self.schedule.regular_op_cost.clone().as_(),
|
||||
Default::default(),
|
||||
)
|
||||
.with_grow_cost(self.schedule.grow_mem_cost.clone().as_())
|
||||
.with_forbidden_floats();
|
||||
|
||||
let module = self
|
||||
.module
|
||||
.take()
|
||||
.expect("On entry to the function `module` can't be `None`; qed");
|
||||
|
||||
let contract_module = pwasm_utils::inject_gas_counter(module, &gas_rules)
|
||||
.map_err(|_| "gas instrumentation failed")?;
|
||||
|
||||
self.module = Some(contract_module);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inject_stack_height_metering(&mut self) -> Result<(), &'static str> {
|
||||
let module = self
|
||||
.module
|
||||
.take()
|
||||
.expect("On entry to the function `module` can't be `None`; qed");
|
||||
|
||||
let contract_module =
|
||||
pwasm_utils::stack_height::inject_limiter(module, self.schedule.max_stack_height)
|
||||
.map_err(|_| "stack height instrumentation failed")?;
|
||||
|
||||
self.module = Some(contract_module);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check that the module has required exported functions. For now
|
||||
/// these are just entrypoints:
|
||||
///
|
||||
/// - 'call'
|
||||
/// - 'deploy'
|
||||
fn scan_exports(&self) -> Result<(), &'static str> {
|
||||
let mut deploy_found = false;
|
||||
let mut call_found = false;
|
||||
|
||||
let module = self
|
||||
.module
|
||||
.as_ref()
|
||||
.expect("On entry to the function `module` can't be `None`; qed");
|
||||
|
||||
let types = module.type_section().map(|ts| ts.types()).unwrap_or(&[]);
|
||||
let export_entries = module
|
||||
.export_section()
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[]);
|
||||
let func_entries = module
|
||||
.function_section()
|
||||
.map(|fs| fs.entries())
|
||||
.unwrap_or(&[]);
|
||||
|
||||
// Function index space consists of imported function following by
|
||||
// declared functions. Calculate the total number of imported functions so
|
||||
// we can use it to convert indexes from function space to declared function space.
|
||||
let fn_space_offset = module
|
||||
.import_section()
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.filter(|entry| {
|
||||
match *entry.external() {
|
||||
External::Function(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
.count();
|
||||
|
||||
for export in export_entries {
|
||||
match export.field() {
|
||||
"call" => call_found = true,
|
||||
"deploy" => deploy_found = true,
|
||||
_ => continue,
|
||||
}
|
||||
|
||||
// Then check the export kind. "call" and "deploy" are
|
||||
// functions.
|
||||
let fn_idx = match export.internal() {
|
||||
Internal::Function(ref fn_idx) => *fn_idx,
|
||||
_ => return Err("expected a function"),
|
||||
};
|
||||
|
||||
// convert index from function index space to declared index space.
|
||||
let fn_idx = match fn_idx.checked_sub(fn_space_offset as u32) {
|
||||
Some(fn_idx) => fn_idx,
|
||||
None => {
|
||||
// Underflow here means fn_idx points to imported function which we don't allow!
|
||||
return Err("entry point points to an imported function");
|
||||
}
|
||||
};
|
||||
|
||||
// Then check the signature.
|
||||
// Both "call" and "deploy" has a () -> () function type.
|
||||
let func_ty_idx = func_entries.get(fn_idx as usize)
|
||||
.ok_or_else(|| "export refers to non-existent function")?
|
||||
.type_ref();
|
||||
let Type::Function(ref func_ty) = types
|
||||
.get(func_ty_idx as usize)
|
||||
.ok_or_else(|| "function has a non-existent type")?;
|
||||
if !(func_ty.params().is_empty() && func_ty.return_type().is_none()) {
|
||||
return Err("entry point has wrong signature");
|
||||
}
|
||||
}
|
||||
|
||||
if !deploy_found {
|
||||
return Err("deploy function isn't exported");
|
||||
}
|
||||
if !call_found {
|
||||
return Err("call function isn't exported");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scan an import section if any.
|
||||
///
|
||||
/// This accomplishes two tasks:
|
||||
///
|
||||
/// - checks any imported function against defined host functions set, incl.
|
||||
/// their signatures.
|
||||
/// - if there is a memory import, returns it's descriptor
|
||||
fn scan_imports<C: ImportSatisfyCheck>(&self) -> Result<Option<&MemoryType>, &'static str> {
|
||||
let module = self
|
||||
.module
|
||||
.as_ref()
|
||||
.expect("On entry to the function `module` can't be `None`; qed");
|
||||
|
||||
let types = module.type_section().map(|ts| ts.types()).unwrap_or(&[]);
|
||||
let import_entries = module
|
||||
.import_section()
|
||||
.map(|is| is.entries())
|
||||
.unwrap_or(&[]);
|
||||
|
||||
let mut imported_mem_type = None;
|
||||
|
||||
for import in import_entries {
|
||||
if import.module() != "env" {
|
||||
// This import tries to import something from non-"env" module,
|
||||
// but all imports are located in "env" at the moment.
|
||||
return Err("module has imports from a non-'env' namespace");
|
||||
}
|
||||
|
||||
let type_idx = match import.external() {
|
||||
&External::Function(ref type_idx) => type_idx,
|
||||
&External::Memory(ref memory_type) => {
|
||||
imported_mem_type = Some(memory_type);
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let Type::Function(ref func_ty) = types
|
||||
.get(*type_idx as usize)
|
||||
.ok_or_else(|| "validation: import entry points to a non-existent type")?;
|
||||
|
||||
if !C::can_satisfy(import.field().as_bytes(), func_ty) {
|
||||
return Err("module imports a non-existent function");
|
||||
}
|
||||
}
|
||||
Ok(imported_mem_type)
|
||||
}
|
||||
|
||||
fn into_wasm_code(mut self) -> Result<Vec<u8>, &'static str> {
|
||||
elements::serialize(
|
||||
self.module
|
||||
.take()
|
||||
.expect("On entry to the function `module` can't be `None`; qed"),
|
||||
)
|
||||
.map_err(|_| "error serializing instrumented module")
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the given module given in `original_code`, performs some checks on it and
|
||||
/// does some preprocessing.
|
||||
///
|
||||
/// The checks are:
|
||||
///
|
||||
/// - module doesn't define an internal memory instance,
|
||||
/// - imported memory (if any) doesn't reserve more memory than permitted by the `schedule`,
|
||||
/// - all imported functions from the external environment matches defined by `env` module,
|
||||
///
|
||||
/// The preprocessing includes injecting code for gas metering and metering the height of stack.
|
||||
pub fn prepare_contract<T: Trait, C: ImportSatisfyCheck>(
|
||||
original_code: &[u8],
|
||||
schedule: &Schedule<T::Gas>,
|
||||
) -> Result<PrefabWasmModule, &'static str> {
|
||||
let mut contract_module = ContractModule::new(original_code, schedule)?;
|
||||
contract_module.scan_exports()?;
|
||||
contract_module.ensure_no_internal_memory()?;
|
||||
contract_module.inject_gas_metering()?;
|
||||
contract_module.inject_stack_height_metering()?;
|
||||
|
||||
struct MemoryDefinition {
|
||||
initial: u32,
|
||||
maximum: u32,
|
||||
}
|
||||
|
||||
let memory_def = if let Some(memory_type) = contract_module.scan_imports::<C>()? {
|
||||
// Inspect the module to extract the initial and maximum page count.
|
||||
let limits = memory_type.limits();
|
||||
match (limits.initial(), limits.maximum()) {
|
||||
(initial, Some(maximum)) if initial > maximum => {
|
||||
return Err(
|
||||
"Requested initial number of pages should not exceed the requested maximum",
|
||||
);
|
||||
}
|
||||
(_, Some(maximum)) if maximum > schedule.max_memory_pages => {
|
||||
return Err("Maximum number of pages should not exceed the configured maximum.");
|
||||
}
|
||||
(initial, Some(maximum)) => MemoryDefinition { initial, maximum },
|
||||
(_, None) => {
|
||||
// Maximum number of pages should be always declared.
|
||||
// This isn't a hard requirement and can be treated as a maxiumum set
|
||||
// to configured maximum.
|
||||
return Err("Maximum number of pages should be always declared.");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If none memory imported then just crate an empty placeholder.
|
||||
// Any access to it will lead to out of bounds trap.
|
||||
MemoryDefinition {
|
||||
initial: 0,
|
||||
maximum: 0,
|
||||
}
|
||||
};
|
||||
|
||||
Ok(PrefabWasmModule {
|
||||
schedule_version: schedule.version,
|
||||
initial: memory_def.initial,
|
||||
maximum: memory_def.maximum,
|
||||
_reserved: None,
|
||||
code: contract_module.into_wasm_code()?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fmt;
|
||||
use tests::Test;
|
||||
use exec::Ext;
|
||||
use wabt;
|
||||
|
||||
impl fmt::Debug for PrefabWasmModule {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "PreparedContract {{ .. }}")
|
||||
}
|
||||
}
|
||||
|
||||
// Define test environment for tests. We need ImportSatisfyCheck
|
||||
// implementation from it. So actual implementations doesn't matter.
|
||||
define_env!(TestEnv, <E: Ext>,
|
||||
panic(_ctx) => { unreachable!(); },
|
||||
gas(_ctx, _amount: u32) => { unreachable!(); },
|
||||
);
|
||||
|
||||
macro_rules! prepare_test {
|
||||
($name:ident, $wat:expr, $($expected:tt)*) => {
|
||||
#[test]
|
||||
fn $name() {
|
||||
let wasm = wabt::Wat2Wasm::new().validate(false).convert($wat).unwrap();
|
||||
let schedule = Schedule::<u64>::default();
|
||||
let r = prepare_contract::<Test, TestEnv>(wasm.as_ref(), &schedule);
|
||||
assert_matches!(r, $($expected)*);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
mod memories {
|
||||
use super::*;
|
||||
|
||||
// Tests below assumes that maximum page number is configured to a certain number.
|
||||
#[test]
|
||||
fn assume_memory_size() {
|
||||
assert_eq!(Schedule::<u64>::default().max_memory_pages, 16);
|
||||
}
|
||||
|
||||
prepare_test!(memory_with_one_page,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(internal_memory_declaration,
|
||||
r#"
|
||||
(module
|
||||
(memory 1 1)
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module declares internal memory")
|
||||
);
|
||||
|
||||
prepare_test!(no_memory_import,
|
||||
r#"
|
||||
(module
|
||||
;; no memory imported
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(initial_exceeds_maximum,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 16 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Requested initial number of pages should not exceed the requested maximum")
|
||||
);
|
||||
|
||||
prepare_test!(no_maximum,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Maximum number of pages should be always declared.")
|
||||
);
|
||||
|
||||
prepare_test!(requested_maximum_exceeds_configured_maximum,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "memory" (memory 1 17))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("Maximum number of pages should not exceed the configured maximum.")
|
||||
);
|
||||
}
|
||||
|
||||
mod imports {
|
||||
use super::*;
|
||||
|
||||
prepare_test!(can_import_legit_function,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "gas" (func (param i32)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
// nothing can be imported from non-"env" module for now.
|
||||
prepare_test!(non_env_import,
|
||||
r#"
|
||||
(module
|
||||
(import "another_module" "memory" (memory 1 1))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module has imports from a non-'env' namespace")
|
||||
);
|
||||
|
||||
// wrong signature
|
||||
prepare_test!(wrong_signature,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "gas" (func (param i64)))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module imports a non-existent function")
|
||||
);
|
||||
|
||||
prepare_test!(unknown_func_name,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "unknown_func" (func))
|
||||
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("module imports a non-existent function")
|
||||
);
|
||||
}
|
||||
|
||||
mod entrypoints {
|
||||
use super::*;
|
||||
|
||||
prepare_test!(it_works,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call"))
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Ok(_)
|
||||
);
|
||||
|
||||
prepare_test!(omit_deploy,
|
||||
r#"
|
||||
(module
|
||||
(func (export "call"))
|
||||
)
|
||||
"#,
|
||||
Err("deploy function isn't exported")
|
||||
);
|
||||
|
||||
prepare_test!(omit_call,
|
||||
r#"
|
||||
(module
|
||||
(func (export "deploy"))
|
||||
)
|
||||
"#,
|
||||
Err("call function isn't exported")
|
||||
);
|
||||
|
||||
// Try to use imported function as an entry point.
|
||||
prepare_test!(try_sneak_export_as_entrypoint,
|
||||
r#"
|
||||
(module
|
||||
(import "env" "panic" (func))
|
||||
|
||||
(func (export "deploy"))
|
||||
|
||||
(export "call" (func 0))
|
||||
)
|
||||
"#,
|
||||
Err("entry point points to an imported function")
|
||||
);
|
||||
|
||||
// Try to use imported function as an entry point.
|
||||
prepare_test!(try_sneak_export_as_global,
|
||||
r#"
|
||||
(module
|
||||
(func (export "deploy"))
|
||||
(global (export "call") i32 (i32.const 0))
|
||||
)
|
||||
"#,
|
||||
Err("expected a function")
|
||||
);
|
||||
|
||||
prepare_test!(wrong_signature,
|
||||
r#"
|
||||
(module
|
||||
(func (export "deploy"))
|
||||
(func (export "call") (param i32))
|
||||
)
|
||||
"#,
|
||||
Err("entry point has wrong signature")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
// Copyright 2018 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Environment definition of the wasm smart-contract runtime.
|
||||
|
||||
use super::{Schedule};
|
||||
use exec::{Ext, BalanceOf, VmExecResult, OutputBuf, EmptyOutputBuf, CallReceipt, InstantiateReceipt};
|
||||
use rstd::prelude::*;
|
||||
use rstd::mem;
|
||||
use codec::{Decode, Encode};
|
||||
use gas::{GasMeter, Token, GasMeterResult};
|
||||
use runtime_primitives::traits::{As, CheckedMul, Bounded};
|
||||
use sandbox;
|
||||
use system;
|
||||
use {Trait, CodeHash};
|
||||
|
||||
/// Enumerates all possible *special* trap conditions.
|
||||
///
|
||||
/// In this runtime traps used not only for signaling about errors but also
|
||||
/// to just terminate quickly in some cases.
|
||||
enum SpecialTrap {
|
||||
/// Signals that trap was generated in response to call `ext_return` host function.
|
||||
Return(OutputBuf),
|
||||
}
|
||||
|
||||
/// Can only be used for one call.
|
||||
pub(crate) struct Runtime<'a, 'data, E: Ext + 'a> {
|
||||
ext: &'a mut E,
|
||||
input_data: &'data [u8],
|
||||
// A VM can return a result only once and only by value. So
|
||||
// we wrap output buffer to make it possible to take the buffer out.
|
||||
empty_output_buf: Option<EmptyOutputBuf>,
|
||||
scratch_buf: Vec<u8>,
|
||||
schedule: &'a Schedule<<E::T as Trait>::Gas>,
|
||||
memory: sandbox::Memory,
|
||||
gas_meter: &'a mut GasMeter<E::T>,
|
||||
special_trap: Option<SpecialTrap>,
|
||||
}
|
||||
impl<'a, 'data, E: Ext + 'a> Runtime<'a, 'data, E> {
|
||||
pub(crate) fn new(
|
||||
ext: &'a mut E,
|
||||
input_data: &'data [u8],
|
||||
empty_output_buf: EmptyOutputBuf,
|
||||
schedule: &'a Schedule<<E::T as Trait>::Gas>,
|
||||
memory: sandbox::Memory,
|
||||
gas_meter: &'a mut GasMeter<E::T>,
|
||||
) -> Self {
|
||||
Runtime {
|
||||
ext,
|
||||
input_data,
|
||||
empty_output_buf: Some(empty_output_buf),
|
||||
scratch_buf: Vec::new(),
|
||||
schedule,
|
||||
memory,
|
||||
gas_meter,
|
||||
special_trap: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn memory(&self) -> &sandbox::Memory {
|
||||
&self.memory
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_execution_result<E: Ext>(
|
||||
runtime: Runtime<E>,
|
||||
sandbox_err: Option<sandbox::Error>,
|
||||
) -> VmExecResult {
|
||||
// Check the exact type of the error. It could be plain trap or
|
||||
// special runtime trap the we must recognize.
|
||||
match (sandbox_err, runtime.special_trap) {
|
||||
// No traps were generated. Proceed normally.
|
||||
(None, None) => VmExecResult::Ok,
|
||||
// Special case. The trap was the result of the execution `return` host function.
|
||||
(Some(sandbox::Error::Execution), Some(SpecialTrap::Return(buf))) => VmExecResult::Returned(buf),
|
||||
// Any other kind of a trap should result in a failure.
|
||||
(Some(_), _) => VmExecResult::Trap("during execution"),
|
||||
// Any other case (such as special trap flag without actual trap) signifies
|
||||
// a logic error.
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum RuntimeToken {
|
||||
/// Explicit call to the `gas` function. Charge the gas meter
|
||||
/// with the value provided.
|
||||
Explicit(u32),
|
||||
/// The given number of bytes is read from the sandbox memory.
|
||||
ReadMemory(u32),
|
||||
/// The given number of bytes is written to the sandbox memory.
|
||||
WriteMemory(u32),
|
||||
/// The given number of bytes is read from the sandbox memory and
|
||||
/// is returned as the return data buffer of the call.
|
||||
ReturnData(u32),
|
||||
}
|
||||
|
||||
impl<T: Trait> Token<T> for RuntimeToken {
|
||||
type Metadata = Schedule<T::Gas>;
|
||||
|
||||
fn calculate_amount(&self, metadata: &Schedule<T::Gas>) -> T::Gas {
|
||||
use self::RuntimeToken::*;
|
||||
let value = match *self {
|
||||
Explicit(amount) => Some(<T::Gas as As<u32>>::sa(amount)),
|
||||
ReadMemory(byte_count) => metadata
|
||||
.sandbox_data_read_cost
|
||||
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
|
||||
WriteMemory(byte_count) => metadata
|
||||
.sandbox_data_write_cost
|
||||
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
|
||||
ReturnData(byte_count) => metadata
|
||||
.return_data_per_byte_cost
|
||||
.checked_mul(&<T::Gas as As<u32>>::sa(byte_count)),
|
||||
};
|
||||
|
||||
value.unwrap_or_else(|| Bounded::max_value())
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge the gas meter with the specified token.
|
||||
///
|
||||
/// Returns `Err(HostError)` if there is not enough gas.
|
||||
fn charge_gas<T: Trait, Tok: Token<T>>(
|
||||
gas_meter: &mut GasMeter<T>,
|
||||
metadata: &Tok::Metadata,
|
||||
token: Tok,
|
||||
) -> Result<(), sandbox::HostError> {
|
||||
match gas_meter.charge(metadata, token) {
|
||||
GasMeterResult::Proceed => Ok(()),
|
||||
GasMeterResult::OutOfGas => Err(sandbox::HostError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read designated chunk from the sandbox memory, consuming an appropriate amount of
|
||||
/// gas.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - requested buffer is not within the bounds of the sandbox memory.
|
||||
fn read_sandbox_memory<E: Ext>(
|
||||
ctx: &mut Runtime<E>,
|
||||
ptr: u32,
|
||||
len: u32,
|
||||
) -> Result<Vec<u8>, sandbox::HostError> {
|
||||
charge_gas(ctx.gas_meter, ctx.schedule, RuntimeToken::ReadMemory(len))?;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.resize(len as usize, 0);
|
||||
|
||||
ctx.memory().get(ptr, &mut buf)?;
|
||||
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// Write the given buffer to the designated location in the sandbox memory, consuming
|
||||
/// an appropriate amount of gas.
|
||||
///
|
||||
/// Returns `Err` if one of the following conditions occurs:
|
||||
///
|
||||
/// - calculating the gas cost resulted in overflow.
|
||||
/// - out of gas
|
||||
/// - designated area is not within the bounds of the sandbox memory.
|
||||
fn write_sandbox_memory<T: Trait>(
|
||||
schedule: &Schedule<T::Gas>,
|
||||
gas_meter: &mut GasMeter<T>,
|
||||
memory: &sandbox::Memory,
|
||||
ptr: u32,
|
||||
buf: &[u8],
|
||||
) -> Result<(), sandbox::HostError> {
|
||||
charge_gas(gas_meter, schedule, RuntimeToken::WriteMemory(buf.len() as u32))?;
|
||||
|
||||
memory.set(ptr, buf)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ***********************************************************
|
||||
// * AFTER MAKING A CHANGE MAKE SURE TO UPDATE COMPLEXITY.MD *
|
||||
// ***********************************************************
|
||||
|
||||
// TODO: ext_balance, ext_address, ext_callvalue, etc.
|
||||
|
||||
// Define a function `fn init_env<E: Ext>() -> HostFunctionSet<E>` that returns
|
||||
// a function set which can be imported by an executed contract.
|
||||
define_env!(Env, <E: Ext>,
|
||||
|
||||
// Account for used gas. Traps if gas used is greater than gas limit.
|
||||
//
|
||||
// - amount: How much gas is used.
|
||||
gas(ctx, amount: u32) => {
|
||||
charge_gas(&mut ctx.gas_meter, ctx.schedule, RuntimeToken::Explicit(amount))?;
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Change the value at the given key in the storage or remove the entry.
|
||||
//
|
||||
// - key_ptr: pointer into the linear
|
||||
// memory where the location of the requested value is placed.
|
||||
// - value_non_null: if set to 0, then the entry
|
||||
// at the given location will be removed.
|
||||
// - value_ptr: pointer into the linear memory
|
||||
// where the value to set is placed. If `value_non_null` is set to 0, then this parameter is ignored.
|
||||
// - value_len: the length of the value. If `value_non_null` is set to 0, then this parameter is ignored.
|
||||
ext_set_storage(ctx, key_ptr: u32, value_non_null: u32, value_ptr: u32, value_len: u32) => {
|
||||
let key = read_sandbox_memory(ctx, key_ptr, 32)?;
|
||||
let value =
|
||||
if value_non_null != 0 {
|
||||
Some(read_sandbox_memory(ctx, value_ptr, value_len)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
ctx.ext.set_storage(&key, value);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Retrieve the value at the given location from the strorage and return 0.
|
||||
// If there is no entry at the given location then this function will return 1 and
|
||||
// clear the scratch buffer.
|
||||
//
|
||||
// - key_ptr: pointer into the linear memory where the key
|
||||
// of the requested value is placed.
|
||||
ext_get_storage(ctx, key_ptr: u32) -> u32 => {
|
||||
let key = read_sandbox_memory(ctx, key_ptr, 32)?;
|
||||
if let Some(value) = ctx.ext.get_storage(&key) {
|
||||
ctx.scratch_buf = value;
|
||||
Ok(0)
|
||||
} else {
|
||||
ctx.scratch_buf.clear();
|
||||
Ok(1)
|
||||
}
|
||||
},
|
||||
|
||||
// Make a call to another contract.
|
||||
//
|
||||
// Returns 0 on the successful execution and puts the result data returned
|
||||
// by the callee into the scratch buffer. Otherwise, returns 1 and clears the scratch
|
||||
// buffer.
|
||||
//
|
||||
// - callee_ptr: a pointer to the address of the callee contract.
|
||||
// Should be decodable as an `T::AccountId`. Traps otherwise.
|
||||
// - callee_len: length of the address buffer.
|
||||
// - gas: how much gas to devote to the execution.
|
||||
// - value_ptr: a pointer to the buffer with value, how much value to send.
|
||||
// Should be decodable as a `T::Balance`. Traps otherwise.
|
||||
// - value_len: length of the value buffer.
|
||||
// - input_data_ptr: a pointer to a buffer to be used as input data to the callee.
|
||||
// - input_data_len: length of the input data buffer.
|
||||
ext_call(
|
||||
ctx,
|
||||
callee_ptr: u32,
|
||||
callee_len: u32,
|
||||
gas: u64,
|
||||
value_ptr: u32,
|
||||
value_len: u32,
|
||||
input_data_ptr: u32,
|
||||
input_data_len: u32
|
||||
) -> u32 => {
|
||||
let callee = {
|
||||
let callee_buf = read_sandbox_memory(ctx, callee_ptr, callee_len)?;
|
||||
<<E as Ext>::T as system::Trait>::AccountId::decode(&mut &callee_buf[..])
|
||||
.ok_or_else(|| sandbox::HostError)?
|
||||
};
|
||||
let value = {
|
||||
let value_buf = read_sandbox_memory(ctx, value_ptr, value_len)?;
|
||||
BalanceOf::<<E as Ext>::T>::decode(&mut &value_buf[..])
|
||||
.ok_or_else(|| sandbox::HostError)?
|
||||
};
|
||||
let input_data = read_sandbox_memory(ctx, input_data_ptr, input_data_len)?;
|
||||
|
||||
// Grab the scratch buffer and put in its' place an empty one.
|
||||
// We will use it for creating `EmptyOutputBuf` container for the call.
|
||||
let scratch_buf = mem::replace(&mut ctx.scratch_buf, Vec::new());
|
||||
let empty_output_buf = EmptyOutputBuf::from_spare_vec(scratch_buf);
|
||||
|
||||
let nested_gas_limit = if gas == 0 {
|
||||
ctx.gas_meter.gas_left()
|
||||
} else {
|
||||
<<E::T as Trait>::Gas as As<u64>>::sa(gas)
|
||||
};
|
||||
let ext = &mut ctx.ext;
|
||||
let call_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
|
||||
match nested_meter {
|
||||
Some(nested_meter) => {
|
||||
ext.call(
|
||||
&callee,
|
||||
value,
|
||||
nested_meter,
|
||||
&input_data,
|
||||
empty_output_buf
|
||||
)
|
||||
.map_err(|_| ())
|
||||
}
|
||||
// there is not enough gas to allocate for the nested call.
|
||||
None => Err(()),
|
||||
}
|
||||
});
|
||||
|
||||
match call_outcome {
|
||||
Ok(CallReceipt { output_data }) => {
|
||||
ctx.scratch_buf = output_data;
|
||||
Ok(0)
|
||||
},
|
||||
Err(_) => Ok(1),
|
||||
}
|
||||
},
|
||||
|
||||
// Instantiate a contract with code returned by the specified initializer code.
|
||||
//
|
||||
// This function creates an account and executes initializer code. After the execution,
|
||||
// the returned buffer is saved as the code of the created account.
|
||||
//
|
||||
// Returns 0 on the successful contract creation and puts the address
|
||||
// of the created contract into the scratch buffer.
|
||||
// Otherwise, returns 1 and clears the scratch buffer.
|
||||
//
|
||||
// - init_code_ptr: a pointer to the buffer that contains the initializer code.
|
||||
// - init_code_len: length of the initializer code buffer.
|
||||
// - gas: how much gas to devote to the execution of the initializer code.
|
||||
// - value_ptr: a pointer to the buffer with value, how much value to send.
|
||||
// Should be decodable as a `T::Balance`. Traps otherwise.
|
||||
// - value_len: length of the value buffer.
|
||||
// - input_data_ptr: a pointer to a buffer to be used as input data to the initializer code.
|
||||
// - input_data_len: length of the input data buffer.
|
||||
ext_create(
|
||||
ctx,
|
||||
init_code_ptr: u32,
|
||||
init_code_len: u32,
|
||||
gas: u64,
|
||||
value_ptr: u32,
|
||||
value_len: u32,
|
||||
input_data_ptr: u32,
|
||||
input_data_len: u32
|
||||
) -> u32 => {
|
||||
let code_hash = {
|
||||
let code_hash_buf = read_sandbox_memory(ctx, init_code_ptr, init_code_len)?;
|
||||
<CodeHash<<E as Ext>::T>>::decode(&mut &code_hash_buf[..]).ok_or_else(|| sandbox::HostError)?
|
||||
};
|
||||
let value = {
|
||||
let value_buf = read_sandbox_memory(ctx, value_ptr, value_len)?;
|
||||
BalanceOf::<<E as Ext>::T>::decode(&mut &value_buf[..])
|
||||
.ok_or_else(|| sandbox::HostError)?
|
||||
};
|
||||
let input_data = read_sandbox_memory(ctx, input_data_ptr, input_data_len)?;
|
||||
|
||||
// Clear the scratch buffer in any case.
|
||||
ctx.scratch_buf.clear();
|
||||
|
||||
let nested_gas_limit = if gas == 0 {
|
||||
ctx.gas_meter.gas_left()
|
||||
} else {
|
||||
<<E::T as Trait>::Gas as As<u64>>::sa(gas)
|
||||
};
|
||||
let ext = &mut ctx.ext;
|
||||
let instantiate_outcome = ctx.gas_meter.with_nested(nested_gas_limit, |nested_meter| {
|
||||
match nested_meter {
|
||||
Some(nested_meter) => {
|
||||
ext.instantiate(
|
||||
&code_hash,
|
||||
value,
|
||||
nested_meter,
|
||||
&input_data
|
||||
)
|
||||
.map_err(|_| ())
|
||||
}
|
||||
// there is not enough gas to allocate for the nested call.
|
||||
None => Err(()),
|
||||
}
|
||||
});
|
||||
match instantiate_outcome {
|
||||
Ok(InstantiateReceipt { address }) => {
|
||||
// Write the address to the scratch buffer.
|
||||
address.encode_to(&mut ctx.scratch_buf);
|
||||
Ok(0)
|
||||
},
|
||||
Err(_) => Ok(1),
|
||||
}
|
||||
},
|
||||
|
||||
// Save a data buffer as a result of the execution, terminate the execution and return a
|
||||
// successful result to the caller.
|
||||
ext_return(ctx, data_ptr: u32, data_len: u32) => {
|
||||
match ctx
|
||||
.gas_meter
|
||||
.charge(
|
||||
ctx.schedule,
|
||||
RuntimeToken::ReturnData(data_len)
|
||||
)
|
||||
{
|
||||
GasMeterResult::Proceed => (),
|
||||
GasMeterResult::OutOfGas => return Err(sandbox::HostError),
|
||||
}
|
||||
|
||||
let empty_output_buf = ctx
|
||||
.empty_output_buf
|
||||
.take()
|
||||
.expect(
|
||||
"`empty_output_buf` is taken only here;
|
||||
`ext_return` traps;
|
||||
`Runtime` can only be used only for one execution;
|
||||
qed"
|
||||
);
|
||||
let output_buf = empty_output_buf.fill(
|
||||
data_len as usize,
|
||||
|slice_mut| {
|
||||
// Read the memory at the specified pointer to the provided slice.
|
||||
ctx.memory.get(data_ptr, slice_mut)
|
||||
}
|
||||
)?;
|
||||
ctx.special_trap = Some(SpecialTrap::Return(output_buf));
|
||||
|
||||
// The trap mechanism is used to immediately terminate the execution.
|
||||
// This trap should be handled appropriately before returning the result
|
||||
// to the user of this crate.
|
||||
Err(sandbox::HostError)
|
||||
},
|
||||
|
||||
// Stores the address of the caller into the scratch buffer.
|
||||
//
|
||||
// If this is a top-level call (i.e. initiated by an extrinsic) the origin address of the extrinsic
|
||||
// will be returned. Otherwise, if this call is initiated by another contract then the address
|
||||
// of the contract will be returned.
|
||||
ext_caller(ctx) => {
|
||||
ctx.scratch_buf = ctx.ext.caller().encode();
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Stores the address of the current contract into the scratch buffer.
|
||||
ext_address(ctx) => {
|
||||
ctx.scratch_buf = ctx.ext.address().encode();
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Returns the size of the input buffer.
|
||||
ext_input_size(ctx) -> u32 => {
|
||||
Ok(ctx.input_data.len() as u32)
|
||||
},
|
||||
|
||||
// Copy data from the input buffer starting from `offset` with length `len` into the contract memory.
|
||||
// The region at which the data should be put is specified by `dest_ptr`.
|
||||
ext_input_copy(ctx, dest_ptr: u32, offset: u32, len: u32) => {
|
||||
let offset = offset as usize;
|
||||
if offset > ctx.input_data.len() {
|
||||
// Offset can't be larger than input buffer length.
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// This can't panic since `offset <= ctx.input_data.len()`.
|
||||
let src = &ctx.input_data[offset..];
|
||||
if src.len() != len as usize {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// Finally, perform the write.
|
||||
write_sandbox_memory(
|
||||
ctx.schedule,
|
||||
ctx.gas_meter,
|
||||
&ctx.memory,
|
||||
dest_ptr,
|
||||
src,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
|
||||
// Returns the size of the scratch buffer.
|
||||
ext_scratch_size(ctx) -> u32 => {
|
||||
Ok(ctx.scratch_buf.len() as u32)
|
||||
},
|
||||
|
||||
// Copy data from the scratch buffer starting from `offset` with length `len` into the contract memory.
|
||||
// The region at which the data should be put is specified by `dest_ptr`.
|
||||
ext_scratch_copy(ctx, dest_ptr: u32, offset: u32, len: u32) => {
|
||||
let offset = offset as usize;
|
||||
if offset > ctx.scratch_buf.len() {
|
||||
// Offset can't be larger than scratch buffer length.
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// This can't panic since `offset <= ctx.scratch_buf.len()`.
|
||||
let src = &ctx.scratch_buf[offset..];
|
||||
if src.len() != len as usize {
|
||||
return Err(sandbox::HostError);
|
||||
}
|
||||
|
||||
// Finally, perform the write.
|
||||
write_sandbox_memory(
|
||||
ctx.schedule,
|
||||
ctx.gas_meter,
|
||||
&ctx.memory,
|
||||
dest_ptr,
|
||||
src,
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user