contracts: Add salt argument to contract instantiation (#7482)

* pallet-contracts: Fix seal_restore_to to output proper module errors

Those errors where part of the decl_error for some time but where
never actually returned. This allows proper debugging of failed
restorations. Previously, any error did return the misleading
`ContractTrapped`.

* Bind UncheckedFrom<T::Hash> + AsRef<[u8]> everywhere

This allows us to make assumptions about the AccoutId
that are necessary for testing and in order to benchmark
the module properly.

This also groups free standing functions into inherent functions
in order to minimize the places where the new bounds need to
be specified.

* Rework contract address determination

* Do not allow override by runtime author
* Instantiate gained a new parameter "salt"

This change is done now in expecation of the upcoming code rent
which needs to change the instantiation dispatchable and
host function anyways.

The situation in where we have only something that is like CREATE2
makes it impossible for UIs to help the user to create an arbitrary
amount of instantiations from the same code.

With this change we have the same functionality as ethereum with
a CREATE and CREATE2 instantation semantic.

* Remove TrieIdGenerator

The new trait bounds allows us to remove this workaround
from the configuration trait.

* Remove default parameters for config trait

It should be solely the responsiblity to determine proper values for
these parameter. As a matter of fact most runtime weren't using these
values anyways.

* Fix tests for new account id type

Because of the new bounds on the trait tests can't get away by using
u64 as accound id. Replacing the 8 byte value by a 32 byte value
creates out quite a bit of code churn.

* Fix benchmarks

The benchmarks need adaption to the new instantiate semantics.

* Fix compile errors caused by adding new trait bounds
* Fix compile errors caused by renaming storage and rent functions
* Adapt host functions and dispatchables to the new salt
* Add tests for instantiate host functions (was not possible before)

* Add benchmark results

* Adapt to the new WeightInfo

The new benchmarks add a new parameter for salt "s" to the instantiate weights
that needs to be applied.

* Fix deploying_wasm_contract_should_work integration test

This test is adapted to use the new instantiate signature.

* Break overlong line

* Break more long lines

Co-authored-by: Parity Benchmarking Bot <admin@parity.io>
This commit is contained in:
Alexander Theißen
2020-11-24 11:42:20 +01:00
committed by GitHub
parent 26830a20df
commit c3ca78fae3
26 changed files with 2186 additions and 2161 deletions
@@ -30,6 +30,7 @@ use crate::wasm::{prepare, runtime::Env, PrefabWasmModule};
use crate::{CodeHash, CodeStorage, PristineCode, Schedule, Trait};
use sp_std::prelude::*;
use sp_runtime::traits::Hash;
use sp_core::crypto::UncheckedFrom;
use frame_support::StorageMap;
/// Put code in the storage. The hash of code is used as a key and is returned
@@ -39,7 +40,7 @@ use frame_support::StorageMap;
pub fn save<T: Trait>(
original_code: Vec<u8>,
schedule: &Schedule<T>,
) -> Result<CodeHash<T>, &'static str> {
) -> Result<CodeHash<T>, &'static str> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
let prefab_module = prepare::prepare_contract::<Env, T>(&original_code, schedule)?;
let code_hash = T::Hashing::hash(&original_code);
@@ -57,7 +58,7 @@ pub fn save<T: Trait>(
pub fn save_raw<T: Trait>(
original_code: Vec<u8>,
schedule: &Schedule<T>,
) -> Result<CodeHash<T>, &'static str> {
) -> Result<CodeHash<T>, &'static str> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
let prefab_module = prepare::benchmarking::prepare_contract::<T>(&original_code, schedule)?;
let code_hash = T::Hashing::hash(&original_code);
@@ -75,7 +76,7 @@ pub fn save_raw<T: Trait>(
pub fn load<T: Trait>(
code_hash: &CodeHash<T>,
schedule: &Schedule<T>,
) -> Result<PrefabWasmModule, &'static str> {
) -> Result<PrefabWasmModule, &'static str> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
let mut prefab_module =
<CodeStorage<T>>::get(code_hash).ok_or_else(|| "code is not found")?;
@@ -127,7 +127,12 @@ macro_rules! define_func {
fn $name< E: $seal_ty >(
$ctx: &mut $crate::wasm::Runtime<E>,
args: &[sp_sandbox::Value],
) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError> {
) -> Result<sp_sandbox::ReturnValue, sp_sandbox::HostError>
where
<E::T as frame_system::Trait>::AccountId:
sp_core::crypto::UncheckedFrom<<E::T as frame_system::Trait>::Hash> +
AsRef<[u8]>
{
#[allow(unused)]
let mut args = args.iter();
@@ -183,7 +188,12 @@ macro_rules! define_env {
}
}
impl<E: Ext> $crate::wasm::env_def::FunctionImplProvider<E> for $init_name {
impl<E: Ext> $crate::wasm::env_def::FunctionImplProvider<E> for $init_name
where
<E::T as frame_system::Trait>::AccountId:
sp_core::crypto::UncheckedFrom<<E::T as frame_system::Trait>::Hash> +
AsRef<[u8]>
{
fn impls<F: FnMut(&[u8], $crate::wasm::env_def::HostFunc<E>)>(f: &mut F) {
register_func!(f, < E: $seal_ty > ; $( $name ( $ctx $( , $names : $params )* ) $( -> $returns)* => $body )* );
}
+113 -81
View File
@@ -23,6 +23,7 @@ use crate::exec::Ext;
use crate::gas::GasMeter;
use sp_std::prelude::*;
use sp_core::crypto::UncheckedFrom;
use codec::{Encode, Decode};
use sp_sandbox;
@@ -32,7 +33,7 @@ mod code_cache;
mod prepare;
mod runtime;
use self::runtime::{to_execution_result, Runtime};
use self::runtime::Runtime;
use self::code_cache::load as load_code;
use pallet_contracts_primitives::ExecResult;
@@ -71,13 +72,16 @@ pub struct WasmLoader<'a, T: Trait> {
schedule: &'a Schedule<T>,
}
impl<'a, T: Trait> WasmLoader<'a, T> {
impl<'a, T: Trait> WasmLoader<'a, T> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
pub fn new(schedule: &'a Schedule<T>) -> Self {
WasmLoader { schedule }
}
}
impl<'a, T: Trait> crate::exec::Loader<T> for WasmLoader<'a, T> {
impl<'a, T: Trait> crate::exec::Loader<T> for WasmLoader<'a, T>
where
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>
{
type Executable = WasmExecutable;
fn load_init(&self, code_hash: &CodeHash<T>) -> Result<WasmExecutable, &'static str> {
@@ -97,17 +101,20 @@ impl<'a, T: Trait> crate::exec::Loader<T> for WasmLoader<'a, T> {
}
/// Implementation of `Vm` that takes `WasmExecutable` and executes it.
pub struct WasmVm<'a, T: Trait> {
pub struct WasmVm<'a, T: Trait> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
schedule: &'a Schedule<T>,
}
impl<'a, T: Trait> WasmVm<'a, T> {
impl<'a, T: Trait> WasmVm<'a, T> where T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]> {
pub fn new(schedule: &'a Schedule<T>) -> Self {
WasmVm { schedule }
}
}
impl<'a, T: Trait> crate::exec::Vm<T> for WasmVm<'a, T> {
impl<'a, T: Trait> crate::exec::Vm<T> for WasmVm<'a, T>
where
T::AccountId: UncheckedFrom<T::Hash> + AsRef<[u8]>
{
type Executable = WasmExecutable;
fn execute<E: Ext<T = T>>(
@@ -147,20 +154,22 @@ impl<'a, T: Trait> crate::exec::Vm<T> for WasmVm<'a, T> {
// entrypoint.
let result = sp_sandbox::Instance::new(&exec.prefab_module.code, &imports, &mut runtime)
.and_then(|mut instance| instance.invoke(exec.entrypoint_name, &[], &mut runtime));
to_execution_result(runtime, result)
runtime.to_execution_result(result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
CodeHash, BalanceOf, Error, Module as Contracts,
exec::{Ext, StorageKey, AccountIdOf},
gas::{Gas, GasMeter},
tests::{Test, Call, ALICE, BOB},
wasm::prepare::prepare_contract,
};
use std::collections::HashMap;
use sp_core::H256;
use crate::exec::{Ext, StorageKey};
use crate::gas::{Gas, GasMeter};
use crate::tests::{Test, Call};
use crate::wasm::prepare::prepare_contract;
use crate::{CodeHash, BalanceOf, Error};
use hex_literal::hex;
use sp_runtime::DispatchError;
use frame_support::weights::Weight;
@@ -174,7 +183,7 @@ mod tests {
#[derive(Debug, PartialEq, Eq)]
struct RestoreEntry {
dest: u64,
dest: AccountIdOf<Test>,
code_hash: H256,
rent_allowance: u64,
delta: Vec<StorageKey>,
@@ -186,16 +195,17 @@ mod tests {
endowment: u64,
data: Vec<u8>,
gas_left: u64,
salt: Vec<u8>,
}
#[derive(Debug, PartialEq, Eq)]
struct TerminationEntry {
beneficiary: u64,
beneficiary: AccountIdOf<Test>,
}
#[derive(Debug, PartialEq, Eq)]
struct TransferEntry {
to: u64,
to: AccountIdOf<Test>,
value: u64,
data: Vec<u8>,
}
@@ -210,7 +220,6 @@ mod tests {
restores: Vec<RestoreEntry>,
// (topics, data)
events: Vec<(Vec<H256>, Vec<u8>)>,
next_account_id: u64,
}
impl Ext for MockExt {
@@ -228,18 +237,17 @@ mod tests {
endowment: u64,
gas_meter: &mut GasMeter<Test>,
data: Vec<u8>,
) -> Result<(u64, ExecReturnValue), ExecError> {
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError> {
self.instantiates.push(InstantiateEntry {
code_hash: code_hash.clone(),
endowment,
data: data.to_vec(),
gas_left: gas_meter.gas_left(),
salt: salt.to_vec(),
});
let address = self.next_account_id;
self.next_account_id += 1;
Ok((
address,
Contracts::<Test>::contract_address(&ALICE, code_hash, salt),
ExecReturnValue {
flags: ReturnFlags::empty(),
data: Vec::new(),
@@ -248,11 +256,11 @@ mod tests {
}
fn transfer(
&mut self,
to: &u64,
to: &AccountIdOf<Self::T>,
value: u64,
) -> Result<(), DispatchError> {
self.transfers.push(TransferEntry {
to: *to,
to: to.clone(),
value,
data: Vec::new(),
});
@@ -260,13 +268,13 @@ mod tests {
}
fn call(
&mut self,
to: &u64,
to: &AccountIdOf<Self::T>,
value: u64,
_gas_meter: &mut GasMeter<Test>,
data: Vec<u8>,
) -> ExecResult {
self.transfers.push(TransferEntry {
to: *to,
to: to.clone(),
value,
data: data,
});
@@ -276,20 +284,20 @@ mod tests {
}
fn terminate(
&mut self,
beneficiary: &u64,
beneficiary: &AccountIdOf<Self::T>,
) -> Result<(), DispatchError> {
self.terminations.push(TerminationEntry {
beneficiary: *beneficiary,
beneficiary: beneficiary.clone(),
});
Ok(())
}
fn restore_to(
&mut self,
dest: u64,
dest: AccountIdOf<Self::T>,
code_hash: H256,
rent_allowance: u64,
delta: Vec<StorageKey>,
) -> Result<(), &'static str> {
) -> Result<(), DispatchError> {
self.restores.push(RestoreEntry {
dest,
code_hash,
@@ -298,11 +306,11 @@ mod tests {
});
Ok(())
}
fn caller(&self) -> &u64 {
&42
fn caller(&self) -> &AccountIdOf<Self::T> {
&ALICE
}
fn address(&self) -> &u64 {
&69
fn address(&self) -> &AccountIdOf<Self::T> {
&BOB
}
fn balance(&self) -> u64 {
228
@@ -363,25 +371,26 @@ mod tests {
value: u64,
gas_meter: &mut GasMeter<Test>,
input_data: Vec<u8>,
) -> Result<(u64, ExecReturnValue), ExecError> {
(**self).instantiate(code, value, gas_meter, input_data)
salt: &[u8],
) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError> {
(**self).instantiate(code, value, gas_meter, input_data, salt)
}
fn transfer(
&mut self,
to: &u64,
to: &AccountIdOf<Self::T>,
value: u64,
) -> Result<(), DispatchError> {
(**self).transfer(to, value)
}
fn terminate(
&mut self,
beneficiary: &u64,
beneficiary: &AccountIdOf<Self::T>,
) -> Result<(), DispatchError> {
(**self).terminate(beneficiary)
}
fn call(
&mut self,
to: &u64,
to: &AccountIdOf<Self::T>,
value: u64,
gas_meter: &mut GasMeter<Test>,
input_data: Vec<u8>,
@@ -390,11 +399,11 @@ mod tests {
}
fn restore_to(
&mut self,
dest: u64,
dest: AccountIdOf<Self::T>,
code_hash: H256,
rent_allowance: u64,
delta: Vec<StorageKey>,
) -> Result<(), &'static str> {
) -> Result<(), DispatchError> {
(**self).restore_to(
dest,
code_hash,
@@ -402,10 +411,10 @@ mod tests {
delta,
)
}
fn caller(&self) -> &u64 {
fn caller(&self) -> &AccountIdOf<Self::T> {
(**self).caller()
}
fn address(&self) -> &u64 {
fn address(&self) -> &AccountIdOf<Self::T> {
(**self).address()
}
fn balance(&self) -> u64 {
@@ -451,7 +460,11 @@ mod tests {
input_data: Vec<u8>,
ext: E,
gas_meter: &mut GasMeter<E::T>,
) -> ExecResult {
) -> ExecResult
where
<E::T as frame_system::Trait>::AccountId:
UncheckedFrom<<E::T as frame_system::Trait>::Hash> + AsRef<[u8]>
{
use crate::exec::Vm;
let wasm = wat::parse_str(wat).unwrap();
@@ -485,21 +498,23 @@ mod tests {
(drop
(call $seal_transfer
(i32.const 4) ;; Pointer to "account" address.
(i32.const 8) ;; Length of "account" address.
(i32.const 12) ;; Pointer to the buffer with value to transfer
(i32.const 32) ;; Length of "account" address.
(i32.const 36) ;; Pointer to the buffer with value to transfer
(i32.const 8) ;; Length of the buffer with value to transfer.
)
)
)
(func (export "deploy"))
;; Destination AccountId to transfer the funds.
;; Represented by u64 (8 bytes long) in little endian.
(data (i32.const 4) "\07\00\00\00\00\00\00\00")
;; Destination AccountId (ALICE)
(data (i32.const 4)
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
)
;; Amount of value to transfer.
;; Represented by u64 (8 bytes long) in little endian.
(data (i32.const 12) "\99\00\00\00\00\00\00\00")
(data (i32.const 36) "\99\00\00\00\00\00\00\00")
)
"#;
@@ -516,7 +531,7 @@ mod tests {
assert_eq!(
&mock_ext.transfers,
&[TransferEntry {
to: 7,
to: ALICE,
value: 153,
data: Vec::new(),
}]
@@ -542,11 +557,11 @@ mod tests {
(drop
(call $seal_call
(i32.const 4) ;; Pointer to "callee" address.
(i32.const 8) ;; Length of "callee" address.
(i32.const 32) ;; 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 36) ;; 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 44) ;; Pointer to input data buffer address
(i32.const 4) ;; Length of input data buffer
(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
(i32.const 0) ;; Length is ignored in this case
@@ -555,14 +570,17 @@ mod tests {
)
(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")
;; Destination AccountId (ALICE)
(data (i32.const 4)
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
)
;; 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 36) "\06\00\00\00\00\00\00\00")
(data (i32.const 20) "\01\02\03\04")
(data (i32.const 44) "\01\02\03\04")
)
"#;
@@ -579,7 +597,7 @@ mod tests {
assert_eq!(
&mock_ext.transfers,
&[TransferEntry {
to: 9,
to: ALICE,
value: 6,
data: vec![1, 2, 3, 4],
}]
@@ -602,7 +620,9 @@ mod tests {
;; output_ptr: u32,
;; output_len_ptr: u32
;; ) -> u32
(import "seal0" "seal_instantiate" (func $seal_instantiate (param i32 i32 i64 i32 i32 i32 i32 i32 i32 i32 i32) (result i32)))
(import "seal0" "seal_instantiate" (func $seal_instantiate
(param i32 i32 i64 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32) (result i32)
))
(import "env" "memory" (memory 1 1))
(func (export "call")
(drop
@@ -618,11 +638,15 @@ mod tests {
(i32.const 0) ;; Length is ignored in this case
(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
(i32.const 0) ;; Length is ignored in this case
(i32.const 0) ;; salt_ptr
(i32.const 4) ;; salt_len
)
)
)
(func (export "deploy"))
;; Salt
(data (i32.const 0) "\42\43\44\45")
;; 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")
@@ -653,7 +677,11 @@ mod tests {
endowment: 3,
data,
gas_left: _,
}] if code_hash == &[0x11; 32].into() && data == &vec![1, 2, 3, 4]
salt,
}] if
code_hash == &[0x11; 32].into() &&
data == &vec![1, 2, 3, 4] &&
salt == &vec![0x42, 0x43, 0x44, 0x45]
);
}
@@ -668,14 +696,16 @@ mod tests {
(func (export "call")
(call $seal_terminate
(i32.const 4) ;; Pointer to "beneficiary" address.
(i32.const 8) ;; Length of "beneficiary" address.
(i32.const 32) ;; Length of "beneficiary" address.
)
)
(func (export "deploy"))
;; Beneficiary 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")
(data (i32.const 4)
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
)
)
"#;
@@ -692,7 +722,7 @@ mod tests {
assert_eq!(
&mock_ext.terminations,
&[TerminationEntry {
beneficiary: 0x09,
beneficiary: ALICE,
}]
);
}
@@ -716,11 +746,11 @@ mod tests {
(drop
(call $seal_call
(i32.const 4) ;; Pointer to "callee" address.
(i32.const 8) ;; Length of "callee" address.
(i32.const 32) ;; 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 36) ;; 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 44) ;; Pointer to input data buffer address
(i32.const 4) ;; Length of input data buffer
(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
(i32.const 0) ;; Length is ignored in this cas
@@ -730,13 +760,15 @@ mod tests {
(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")
(data (i32.const 4)
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
)
;; 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 36) "\06\00\00\00\00\00\00\00")
(data (i32.const 20) "\01\02\03\04")
(data (i32.const 44) "\01\02\03\04")
)
"#;
@@ -753,7 +785,7 @@ mod tests {
assert_eq!(
&mock_ext.transfers,
&[TransferEntry {
to: 9,
to: ALICE,
value: 6,
data: vec![1, 2, 3, 4],
}]
@@ -863,19 +895,19 @@ mod tests {
;; fill the buffer with the caller.
(call $seal_caller (i32.const 0) (i32.const 32))
;; assert len == 8
;; assert len == 32
(call $assert
(i32.eq
(i32.load (i32.const 32))
(i32.const 8)
(i32.const 32)
)
)
;; assert that contents of the buffer is equal to the i64 value of 42.
;; assert that the first 64 byte are the beginning of "ALICE"
(call $assert
(i64.eq
(i64.load (i32.const 0))
(i64.const 42)
(i64.const 0x0101010101010101)
)
)
)
@@ -916,19 +948,19 @@ mod tests {
;; fill the buffer with the self address.
(call $seal_address (i32.const 0) (i32.const 32))
;; assert size == 8
;; assert size == 32
(call $assert
(i32.eq
(i32.load (i32.const 32))
(i32.const 8)
(i32.const 32)
)
)
;; assert that contents of the buffer is equal to the i64 value of 69.
;; assert that the first 64 byte are the beginning of "BOB"
(call $assert
(i64.eq
(i64.load (i32.const 0))
(i64.const 69)
(i64.const 0x0202020202020202)
)
)
)
File diff suppressed because it is too large Load Diff