use crate::{
chain_extension::ChainExtension,
storage::meter::Diff,
wasm::{
runtime::AllowDeprecatedInterface, CodeInfo, Determinism, Environment, WasmBlob,
BYTES_PER_PAGE,
},
AccountIdOf, CodeVec, Config, Error, Schedule, LOG_TARGET,
};
#[cfg(any(test, feature = "runtime-benchmarks"))]
use alloc::vec::Vec;
use codec::MaxEncodedLen;
use sp_runtime::{traits::Hash, DispatchError};
use wasmi::{
core::ValType as WasmiValueType, CompilationMode, Config as WasmiConfig, Engine, ExternType,
Module, StackLimits,
};
pub const IMPORT_MODULE_MEMORY: &str = "env";
pub struct LoadedModule {
pub module: Module,
pub engine: Engine,
}
#[derive(PartialEq, Debug, Clone)]
pub enum LoadingMode {
Checked,
Unchecked,
}
#[cfg(test)]
pub mod tracker {
use core::cell::RefCell;
thread_local! {
pub static LOADED_MODULE: RefCell<Vec<super::LoadingMode>> = RefCell::new(Vec::new());
}
}
impl LoadedModule {
pub fn new<T>(
code: &[u8],
determinism: Determinism,
stack_limits: Option<StackLimits>,
loading_mode: LoadingMode,
compilation_mode: CompilationMode,
) -> Result<Self, &'static str> {
let mut config = WasmiConfig::default();
config
.wasm_multi_value(false)
.wasm_mutable_global(false)
.wasm_sign_extension(true)
.wasm_bulk_memory(false)
.wasm_reference_types(false)
.wasm_tail_call(false)
.wasm_extended_const(false)
.wasm_saturating_float_to_int(false)
.floats(matches!(determinism, Determinism::Relaxed))
.compilation_mode(compilation_mode)
.consume_fuel(true);
if let Some(stack_limits) = stack_limits {
config.set_stack_limits(stack_limits);
}
let engine = Engine::new(&config);
let module = match loading_mode {
LoadingMode::Checked => Module::new(&engine, code),
LoadingMode::Unchecked => unsafe { Module::new_unchecked(&engine, code) },
}
.map_err(|err| {
log::debug!(target: LOG_TARGET, "Module creation failed: {:?}", err);
"Can't load the module into wasmi!"
})?;
#[cfg(test)]
tracker::LOADED_MODULE.with(|t| t.borrow_mut().push(loading_mode));
Ok(LoadedModule { module, engine })
}
fn scan_exports(&self) -> Result<(), &'static str> {
let mut deploy_found = false;
let mut call_found = false;
let module = &self.module;
let exports = module.exports();
for export in exports {
match export.ty() {
ExternType::Func(ft) => {
match export.name() {
"call" => call_found = true,
"deploy" => deploy_found = true,
_ =>
return Err(
"unknown function export: expecting only deploy and call functions",
),
}
if !(ft.params().is_empty() &&
(ft.results().is_empty() || ft.results() == [WasmiValueType::I32]))
{
return Err("entry point has wrong signature")
}
},
ExternType::Memory(_) => return Err("memory export is forbidden"),
ExternType::Global(_) => return Err("global export is forbidden"),
ExternType::Table(_) => return Err("table export is forbidden"),
}
}
if !deploy_found {
return Err("deploy function isn't exported")
}
if !call_found {
return Err("call function isn't exported")
}
Ok(())
}
pub fn scan_imports<T: Config>(
&self,
schedule: &Schedule<T>,
) -> Result<(u32, u32), &'static str> {
let module = &self.module;
let imports = module.imports();
let mut memory_limits = None;
for import in imports {
match *import.ty() {
ExternType::Table(_) => return Err("Cannot import tables"),
ExternType::Global(_) => return Err("Cannot import globals"),
ExternType::Func(_) => {
let _ = import.ty().func().ok_or("expected a function")?;
if !<T as Config>::ChainExtension::enabled() &&
(import.name().as_bytes() == b"seal_call_chain_extension" ||
import.name().as_bytes() == b"call_chain_extension")
{
return Err("Module uses chain extensions but chain extensions are disabled")
}
},
ExternType::Memory(mt) => {
if import.module().as_bytes() != IMPORT_MODULE_MEMORY.as_bytes() {
return Err("Invalid module for imported memory")
}
if import.name().as_bytes() != b"memory" {
return Err("Memory import must have the field name 'memory'")
}
if memory_limits.is_some() {
return Err("Multiple memory imports defined")
}
let (initial, maximum) = (
mt.initial_pages().to_bytes().unwrap_or(0).saturating_div(BYTES_PER_PAGE)
as u32,
mt.maximum_pages().map_or(schedule.limits.memory_pages, |p| {
p.to_bytes().unwrap_or(0).saturating_div(BYTES_PER_PAGE) as u32
}),
);
if initial > maximum {
return Err(
"Requested initial number of memory pages should not exceed the requested maximum",
)
}
if maximum > schedule.limits.memory_pages {
return Err("Maximum number of memory pages should not exceed the maximum configured in the Schedule")
}
memory_limits = Some((initial, maximum));
continue
},
}
}
memory_limits.ok_or("No memory import found in the module")
}
}
fn validate<E, T>(
code: &[u8],
schedule: &Schedule<T>,
determinism: &mut Determinism,
) -> Result<(), (DispatchError, &'static str)>
where
E: Environment<()>,
T: Config,
{
let module = (|| {
let stack_limits = Some(StackLimits::new(1, 1, 0).expect("initial <= max; qed"));
let contract_module = match *determinism {
Determinism::Relaxed =>
if let Ok(module) = LoadedModule::new::<T>(
code,
Determinism::Enforced,
stack_limits,
LoadingMode::Checked,
CompilationMode::Eager,
) {
*determinism = Determinism::Enforced;
module
} else {
LoadedModule::new::<T>(
code,
Determinism::Relaxed,
None,
LoadingMode::Checked,
CompilationMode::Eager,
)?
},
Determinism::Enforced => LoadedModule::new::<T>(
code,
Determinism::Enforced,
stack_limits,
LoadingMode::Checked,
CompilationMode::Eager,
)?,
};
contract_module.scan_exports()?;
contract_module.scan_imports::<T>(schedule)?;
Ok(contract_module)
})()
.map_err(|msg: &str| {
log::debug!(target: LOG_TARGET, "New code rejected on validation: {}", msg);
(Error::<T>::CodeRejected.into(), msg)
})?;
WasmBlob::<T>::instantiate::<E, _>(module, (), schedule, AllowDeprecatedInterface::No)
.map_err(|err| {
log::debug!(target: LOG_TARGET, "{err}");
(Error::<T>::CodeRejected.into(), "New code rejected on wasmi instantiation!")
})?;
Ok(())
}
pub fn prepare<E, T>(
code: CodeVec<T>,
schedule: &Schedule<T>,
owner: AccountIdOf<T>,
mut determinism: Determinism,
) -> Result<WasmBlob<T>, (DispatchError, &'static str)>
where
E: Environment<()>,
T: Config,
{
validate::<E, T>(code.as_ref(), schedule, &mut determinism)?;
let code_len = code.len() as u32;
let bytes_added = code_len.saturating_add(<CodeInfo<T>>::max_encoded_len() as u32);
let deposit = Diff { bytes_added, items_added: 2, ..Default::default() }
.update_contract::<T>(None)
.charge_or_zero();
let code_info = CodeInfo { owner, deposit, determinism, refcount: 0, code_len };
let code_hash = T::Hashing::hash(&code);
Ok(WasmBlob { code, code_info, code_hash })
}
#[cfg(any(test, feature = "runtime-benchmarks"))]
pub mod benchmarking {
use super::*;
pub fn prepare<T: Config>(
code: Vec<u8>,
schedule: &Schedule<T>,
owner: AccountIdOf<T>,
) -> Result<WasmBlob<T>, DispatchError> {
let determinism = Determinism::Enforced;
let contract_module = LoadedModule::new::<T>(
&code,
determinism,
None,
LoadingMode::Checked,
CompilationMode::Eager,
)?;
let _ = contract_module.scan_imports::<T>(schedule)?;
let code: CodeVec<T> = code.try_into().map_err(|_| <Error<T>>::CodeTooLarge)?;
let code_info = CodeInfo {
owner,
deposit: Default::default(),
refcount: 0,
code_len: code.len() as u32,
determinism,
};
let code_hash = T::Hashing::hash(&code);
Ok(WasmBlob { code, code_info, code_hash })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
exec::Ext,
schedule::Limits,
tests::{Test, ALICE},
};
use pallet_contracts_proc_macro::define_env;
use std::fmt;
impl fmt::Debug for WasmBlob<Test> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ContractCode {{ .. }}")
}
}
#[allow(unreachable_code)]
mod env {
use super::*;
use crate::wasm::runtime::{AllowDeprecatedInterface, AllowUnstableInterface, TrapReason};
#[define_env]
pub mod test_env {
fn panic(_ctx: _, _memory: _) -> Result<(), TrapReason> {
Ok(())
}
fn gas(_ctx: _, _memory: _, _amount: u64) -> Result<(), TrapReason> {
Ok(())
}
fn nop(_ctx: _, _memory: _, _unused: u64) -> Result<(), TrapReason> {
Ok(())
}
#[version(1)]
fn nop(_ctx: _, _memory: _, _unused: i32) -> Result<(), TrapReason> {
Ok(())
}
}
}
macro_rules! prepare_test {
($name:ident, $wat:expr, $($expected:tt)*) => {
#[test]
fn $name() {
let wasm = wat::parse_str($wat).unwrap().try_into().unwrap();
let schedule = Schedule {
limits: Limits {
memory_pages: 16,
.. Default::default()
},
.. Default::default()
};
let r = prepare::<env::Env, Test>(
wasm,
&schedule,
ALICE,
Determinism::Enforced,
);
assert_matches::assert_matches!(r.map_err(|(_, msg)| msg), $($expected)*);
}
};
}
prepare_test!(
no_floats,
r#"
(module
(func (export "call")
(drop
(f32.add
(f32.const 0)
(f32.const 1)
)
)
)
(func (export "deploy"))
)"#,
Err("Can't load the module into wasmi!")
);
mod memories {
use super::*;
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("No memory import found in the module")
);
prepare_test!(
no_memory_import,
r#"
(module
;; no memory imported
(func (export "call"))
(func (export "deploy"))
)"#,
Err("No memory import found in the module")
);
prepare_test!(
initial_exceeds_maximum,
r#"
(module
(import "env" "memory" (memory 16 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Can't load the module into wasmi!")
);
prepare_test!(
requested_maximum_valid,
r#"
(module
(import "env" "memory" (memory 1 16))
(func (export "call"))
(func (export "deploy"))
)
"#,
Ok(_)
);
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 memory pages should not exceed the maximum configured in the Schedule")
);
prepare_test!(
field_name_not_memory,
r#"
(module
(import "env" "forgetit" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Memory import must have the field name 'memory'")
);
prepare_test!(
multiple_memory_imports,
r#"
(module
(import "env" "memory" (memory 1 1))
(import "env" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Can't load the module into wasmi!")
);
prepare_test!(
table_import,
r#"
(module
(import "seal0" "table" (table 1 anyfunc))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Cannot import tables")
);
prepare_test!(
global_import,
r#"
(module
(global $g (import "seal0" "global") i32)
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Cannot import globals")
);
}
mod imports {
use super::*;
prepare_test!(
can_import_legit_function,
r#"
(module
(import "seal0" "nop" (func (param i64)))
(import "env" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Ok(_)
);
prepare_test!(
memory_not_in_seal0,
r#"
(module
(import "seal0" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Invalid module for imported memory")
);
prepare_test!(
memory_not_in_arbitrary_module,
r#"
(module
(import "any_module" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Invalid module for imported memory")
);
prepare_test!(
function_in_other_module_works,
r#"
(module
(import "seal1" "nop" (func (param i32)))
(import "env" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Ok(_)
);
prepare_test!(
wrong_signature,
r#"
(module
(import "seal0" "input" (func (param i64)))
(import "env" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("New code rejected on wasmi instantiation!")
);
prepare_test!(
unknown_func_name,
r#"
(module
(import "seal0" "unknown_func" (func))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("No memory import found in the module")
);
prepare_test!(
try_import_from_wrong_module,
r#"
(module
(import "env" "panic" (func))
(import "env" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("New code rejected on wasmi instantiation!")
);
}
mod entrypoints {
use super::*;
prepare_test!(
it_works,
r#"
(module
(import "env" "memory" (memory 1 1))
(func (export "call"))
(func (export "deploy"))
)
"#,
Ok(_)
);
prepare_test!(
signed_extension_works,
r#"
(module
(import "env" "memory" (memory 1 1))
(func (export "deploy"))
(func (export "call"))
(func (param i32) (result i32)
local.get 0
i32.extend8_s
)
)
"#,
Ok(_)
);
prepare_test!(
omit_memory,
r#"
(module
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("No memory import found in the module")
);
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")
);
prepare_test!(
try_sneak_export_as_entrypoint,
r#"
(module
(import "seal0" "panic" (func))
(import "env" "memory" (memory 1 1))
(func (export "deploy"))
(export "call" (func 0))
)
"#,
Ok(_)
);
prepare_test!(
try_sneak_export_as_global,
r#"
(module
(func (export "deploy"))
(global (export "call") i32 (i32.const 0))
)
"#,
Err("global export is forbidden")
);
prepare_test!(
wrong_signature,
r#"
(module
(func (export "deploy"))
(func (export "call") (param i32))
)
"#,
Err("entry point has wrong signature")
);
prepare_test!(
unknown_exports,
r#"
(module
(func (export "call"))
(func (export "deploy"))
(func (export "whatevs"))
)
"#,
Err("unknown function export: expecting only deploy and call functions")
);
prepare_test!(
global_float,
r#"
(module
(global $x f32 (f32.const 0))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Can't load the module into wasmi!")
);
prepare_test!(
local_float,
r#"
(module
(func $foo (local f32))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Can't load the module into wasmi!")
);
prepare_test!(
param_float,
r#"
(module
(func $foo (param f32))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Can't load the module into wasmi!")
);
prepare_test!(
result_float,
r#"
(module
(func $foo (result f32) (f32.const 0))
(func (export "call"))
(func (export "deploy"))
)
"#,
Err("Can't load the module into wasmi!")
);
}
}