Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+133 -134
View File
@@ -25,21 +25,20 @@
//! compiles it down into a `WasmModule` that can be used as a contract's code.
use crate::Config;
use frame_support::traits::Get;
use pwasm_utils::{
stack_height::inject_limiter,
parity_wasm::{
elements::{
self, Instruction, Instructions, FuncBody, ValueType, BlockType, Section,
CustomSection,
},
builder,
elements::{
self, BlockType, CustomSection, FuncBody, Instruction, Instructions, Section, ValueType,
},
},
stack_height::inject_limiter,
};
use sp_core::crypto::UncheckedFrom;
use sp_runtime::traits::Hash;
use sp_sandbox::{EnvironmentDefinitionBuilder, Memory};
use sp_std::{prelude::*, convert::TryFrom, borrow::ToOwned};
use frame_support::traits::Get;
use sp_std::{borrow::ToOwned, convert::TryFrom, prelude::*};
/// Pass to `create_code` in order to create a compiled `WasmModule`.
///
@@ -117,7 +116,7 @@ pub struct ImportedFunction {
/// A wasm module ready to be put on chain.
#[derive(Clone)]
pub struct WasmModule<T:Config> {
pub struct WasmModule<T: Config> {
pub code: Vec<u8>,
pub hash: <T::Hashing as Hash>::Output,
memory: Option<ImportedMemory>,
@@ -136,27 +135,37 @@ where
let mut contract = builder::module()
// deploy function (first internal function)
.function()
.signature().build()
.with_body(def.deploy_body.unwrap_or_else(||
FuncBody::new(Vec::new(), Instructions::empty())
))
.build()
.signature()
.build()
.with_body(
def.deploy_body
.unwrap_or_else(|| FuncBody::new(Vec::new(), Instructions::empty())),
)
.build()
// call function (second internal function)
.function()
.signature().build()
.with_body(def.call_body.unwrap_or_else(||
FuncBody::new(Vec::new(), Instructions::empty())
))
.build()
.export().field("deploy").internal().func(func_offset).build()
.export().field("call").internal().func(func_offset + 1).build();
.signature()
.build()
.with_body(
def.call_body
.unwrap_or_else(|| FuncBody::new(Vec::new(), Instructions::empty())),
)
.build()
.export()
.field("deploy")
.internal()
.func(func_offset)
.build()
.export()
.field("call")
.internal()
.func(func_offset + 1)
.build();
// If specified we add an additional internal function
if let Some(body) = def.aux_body {
let mut signature = contract
.function()
.signature();
for _ in 0 .. def.aux_arg_num {
let mut signature = contract.function().signature();
for _ in 0..def.aux_arg_num {
signature = signature.with_param(ValueType::I64);
}
contract = signature.build().with_body(body).build();
@@ -164,9 +173,12 @@ where
// Grant access to linear memory.
if let Some(memory) = &def.memory {
contract = contract.import()
.module("env").field("memory")
.external().memory(memory.min_pages, Some(memory.max_pages))
contract = contract
.import()
.module("env")
.field("memory")
.external()
.memory(memory.min_pages, Some(memory.max_pages))
.build();
}
@@ -177,7 +189,8 @@ where
.with_results(func.return_type.into_iter().collect())
.build_sig();
let sig = contract.push_signature(sig);
contract = contract.import()
contract = contract
.import()
.module(func.module)
.field(func.name)
.with_external(elements::External::Function(sig))
@@ -186,7 +199,8 @@ where
// Initialize memory
for data in def.data_segments {
contract = contract.data()
contract = contract
.data()
.offset(Instruction::I32Const(data.offset as i32))
.value(data.value)
.build()
@@ -194,12 +208,13 @@ where
// Add global variables
if def.num_globals > 0 {
use rand::{prelude::*, distributions::Standard};
use rand::{distributions::Standard, prelude::*};
let rng = rand_pcg::Pcg32::seed_from_u64(3112244599778833558);
for val in rng.sample_iter(Standard).take(def.num_globals as usize) {
contract = contract
.global()
.value_type().i64()
.value_type()
.i64()
.mutable()
.init_expr(Instruction::I64Const(val))
.build()
@@ -218,31 +233,22 @@ where
// Add the dummy section
if def.dummy_section > 0 {
contract = contract.with_section(
Section::Custom(
CustomSection::new("dummy".to_owned(), vec![42; def.dummy_section as usize])
)
);
contract = contract.with_section(Section::Custom(CustomSection::new(
"dummy".to_owned(),
vec![42; def.dummy_section as usize],
)));
}
let mut code = contract.build();
// Inject stack height metering
if def.inject_stack_metering {
code = inject_limiter(
code,
T::Schedule::get().limits.stack_height
)
.unwrap();
code = inject_limiter(code, T::Schedule::get().limits.stack_height).unwrap();
}
let code = code.to_bytes().unwrap();
let hash = T::Hashing::hash(&code);
Self {
code,
hash,
memory: def.memory,
}
Self { code, hash, memory: def.memory }
}
}
@@ -266,7 +272,7 @@ where
ModuleDefinition {
memory: Some(ImportedMemory::max::<T>()),
dummy_section: dummy_bytes.saturating_sub(module_overhead),
.. Default::default()
..Default::default()
}
.into()
}
@@ -275,23 +281,18 @@ where
/// `instantiate_with_code` for different sizes of wasm modules. The generated module maximizes
/// instrumentation runtime by nesting blocks as deeply as possible given the byte budget.
pub fn sized(target_bytes: u32) -> Self {
use self::elements::Instruction::{If, I32Const, Return, End};
use self::elements::Instruction::{End, I32Const, If, Return};
// Base size of a contract is 63 bytes and each expansion adds 6 bytes.
// We do one expansion less to account for the code section and function body
// size fields inside the binary wasm module representation which are leb128 encoded
// and therefore grow in size when the contract grows. We are not allowed to overshoot
// because of the maximum code size that is enforced by `instantiate_with_code`.
let expansions = (target_bytes.saturating_sub(63) / 6).saturating_sub(1);
const EXPANSION: [Instruction; 4] = [
I32Const(0),
If(BlockType::NoResult),
Return,
End,
];
const EXPANSION: [Instruction; 4] = [I32Const(0), If(BlockType::NoResult), Return, End];
ModuleDefinition {
call_body: Some(body::repeated(expansions, &EXPANSION)),
memory: Some(ImportedMemory::max::<T>()),
.. Default::default()
..Default::default()
}
.into()
}
@@ -317,12 +318,15 @@ where
offset: 0,
value: (pages * 64 * 1024 - 4).to_le_bytes().to_vec(),
}],
call_body: Some(body::repeated(repeat, &[
Instruction::I32Const(4), // ptr where to store output
Instruction::I32Const(0), // ptr to length
Instruction::Call(0), // call the imported function
])),
.. Default::default()
call_body: Some(body::repeated(
repeat,
&[
Instruction::I32Const(4), // ptr where to store output
Instruction::I32Const(0), // ptr to length
Instruction::Call(0), // call the imported function
],
)),
..Default::default()
}
.into()
}
@@ -339,13 +343,16 @@ where
params: vec![ValueType::I32, ValueType::I32, ValueType::I32],
return_type: None,
}],
call_body: Some(body::repeated(repeat, &[
Instruction::I32Const(0), // input_ptr
Instruction::I32Const(data_size as i32), // input_len
Instruction::I32Const(0), // output_ptr
Instruction::Call(0),
])),
.. Default::default()
call_body: Some(body::repeated(
repeat,
&[
Instruction::I32Const(0), // input_ptr
Instruction::I32Const(data_size as i32), // input_len
Instruction::I32Const(0), // output_ptr
Instruction::Call(0),
],
)),
..Default::default()
}
.into()
}
@@ -354,11 +361,7 @@ where
/// and adds it to `env`. A reference to that memory is returned so that it can be used to
/// access the memory contents from the supervisor.
pub fn add_memory<S>(&self, env: &mut EnvironmentDefinitionBuilder<S>) -> Option<Memory> {
let memory = if let Some(memory) = &self.memory {
memory
} else {
return None;
};
let memory = if let Some(memory) = &self.memory { memory } else { return None };
let memory = Memory::new(memory.min_pages, Some(memory.max_pages)).unwrap();
env.add_memory("env", "memory", memory.clone());
Some(memory)
@@ -367,25 +370,25 @@ where
pub fn unary_instr(instr: Instruction, repeat: u32) -> Self {
use body::DynInstr::{RandomI64Repeated, Regular};
ModuleDefinition {
call_body: Some(body::repeated_dyn(repeat, vec![
RandomI64Repeated(1),
Regular(instr),
Regular(Instruction::Drop),
])),
.. Default::default()
}.into()
call_body: Some(body::repeated_dyn(
repeat,
vec![RandomI64Repeated(1), Regular(instr), Regular(Instruction::Drop)],
)),
..Default::default()
}
.into()
}
pub fn binary_instr(instr: Instruction, repeat: u32) -> Self {
use body::DynInstr::{RandomI64Repeated, Regular};
ModuleDefinition {
call_body: Some(body::repeated_dyn(repeat, vec![
RandomI64Repeated(2),
Regular(instr),
Regular(Instruction::Drop),
])),
.. Default::default()
}.into()
call_body: Some(body::repeated_dyn(
repeat,
vec![RandomI64Repeated(2), Regular(instr), Regular(Instruction::Drop)],
)),
..Default::default()
}
.into()
}
}
@@ -426,7 +429,7 @@ pub mod body {
RandomGetGlobal(u32, u32),
/// Insert a SetGlobal with a random offset in [low, high).
/// (low, high)
RandomSetGlobal(u32, u32)
RandomSetGlobal(u32, u32),
}
pub fn plain(instructions: Vec<Instruction>) -> FuncBody {
@@ -441,13 +444,13 @@ pub mod body {
.take(instructions.len() * usize::try_from(repetitions).unwrap())
.cloned()
.chain(sp_std::iter::once(Instruction::End))
.collect()
.collect(),
);
FuncBody::new(Vec::new(), instructions)
}
pub fn repeated_dyn(repetitions: u32, mut instructions: Vec<DynInstr>) -> FuncBody {
use rand::{prelude::*, distributions::Standard};
use rand::{distributions::Standard, prelude::*};
// We do not need to be secure here.
let mut rng = rand_pcg::Pcg32::seed_from_u64(8446744073709551615);
@@ -456,50 +459,46 @@ pub mod body {
let body = (0..instructions.len())
.cycle()
.take(instructions.len() * usize::try_from(repetitions).unwrap())
.flat_map(|idx|
match &mut instructions[idx] {
DynInstr::Regular(instruction) => vec![instruction.clone()],
DynInstr::Counter(offset, increment_by) => {
let current = *offset;
*offset += *increment_by;
vec![Instruction::I32Const(current as i32)]
},
DynInstr::RandomUnaligned(low, high) => {
let unaligned = rng.gen_range(*low..*high) | 1;
vec![Instruction::I32Const(unaligned as i32)]
},
DynInstr::RandomI32(low, high) => {
vec![Instruction::I32Const(rng.gen_range(*low..*high))]
},
DynInstr::RandomI32Repeated(num) => {
(&mut rng).sample_iter(Standard).take(*num).map(|val|
Instruction::I32Const(val)
)
.collect()
},
DynInstr::RandomI64Repeated(num) => {
(&mut rng).sample_iter(Standard).take(*num).map(|val|
Instruction::I64Const(val)
)
.collect()
},
DynInstr::RandomGetLocal(low, high) => {
vec![Instruction::GetLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomSetLocal(low, high) => {
vec![Instruction::SetLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomTeeLocal(low, high) => {
vec![Instruction::TeeLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomGetGlobal(low, high) => {
vec![Instruction::GetGlobal(rng.gen_range(*low..*high))]
},
DynInstr::RandomSetGlobal(low, high) => {
vec![Instruction::SetGlobal(rng.gen_range(*low..*high))]
},
}
)
.flat_map(|idx| match &mut instructions[idx] {
DynInstr::Regular(instruction) => vec![instruction.clone()],
DynInstr::Counter(offset, increment_by) => {
let current = *offset;
*offset += *increment_by;
vec![Instruction::I32Const(current as i32)]
},
DynInstr::RandomUnaligned(low, high) => {
let unaligned = rng.gen_range(*low..*high) | 1;
vec![Instruction::I32Const(unaligned as i32)]
},
DynInstr::RandomI32(low, high) => {
vec![Instruction::I32Const(rng.gen_range(*low..*high))]
},
DynInstr::RandomI32Repeated(num) => (&mut rng)
.sample_iter(Standard)
.take(*num)
.map(|val| Instruction::I32Const(val))
.collect(),
DynInstr::RandomI64Repeated(num) => (&mut rng)
.sample_iter(Standard)
.take(*num)
.map(|val| Instruction::I64Const(val))
.collect(),
DynInstr::RandomGetLocal(low, high) => {
vec![Instruction::GetLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomSetLocal(low, high) => {
vec![Instruction::SetLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomTeeLocal(low, high) => {
vec![Instruction::TeeLocal(rng.gen_range(*low..*high))]
},
DynInstr::RandomGetGlobal(low, high) => {
vec![Instruction::GetGlobal(rng.gen_range(*low..*high))]
},
DynInstr::RandomSetGlobal(low, high) => {
vec![Instruction::SetGlobal(rng.gen_range(*low..*high))]
},
})
.chain(sp_std::iter::once(Instruction::End))
.collect();
FuncBody::new(Vec::new(), Instructions::new(body))
@@ -22,28 +22,28 @@
mod code;
mod sandbox;
use self::{
code::{
body::{self, DynInstr::*},
DataSegment, ImportedFunction, ImportedMemory, ModuleDefinition, WasmModule,
},
sandbox::Sandbox,
};
use crate::{
*, Pallet as Contracts,
exec::StorageKey,
rent::Rent,
schedule::{API_BENCHMARK_BATCH_SIZE, INSTR_BENCHMARK_BATCH_SIZE},
storage::Storage,
};
use self::{
code::{
body::{self, DynInstr::*},
ModuleDefinition, DataSegment, ImportedMemory, ImportedFunction, WasmModule,
},
sandbox::Sandbox,
Pallet as Contracts, *,
};
use codec::Encode;
use frame_benchmarking::{benchmarks, account, whitelisted_caller, impl_benchmark_test_suite};
use frame_system::{Pallet as System, RawOrigin};
use pwasm_utils::parity_wasm::elements::{Instruction, ValueType, BlockType, BrTableData};
use sp_runtime::traits::{Hash, Bounded, Zero};
use sp_std::{default::Default, convert::{TryInto}, vec::Vec, vec};
use pallet_contracts_primitives::RentProjection;
use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, whitelisted_caller};
use frame_support::weights::Weight;
use frame_system::{Pallet as System, RawOrigin};
use pallet_contracts_primitives::RentProjection;
use pwasm_utils::parity_wasm::elements::{BlockType, BrTableData, Instruction, ValueType};
use sp_runtime::traits::{Bounded, Hash, Zero};
use sp_std::{convert::TryInto, default::Default, vec, vec::Vec};
/// How many batches we do per API benchmark.
const API_BENCHMARK_BATCHES: u32 = 20;
@@ -74,7 +74,7 @@ impl Endow {
/// The maximum amount of balance a caller can transfer without being brought below
/// the existential deposit. This assumes that every caller is funded with the amount
/// returned by `caller_funding`.
fn max<T:Config>() -> BalanceOf<T> {
fn max<T: Config>() -> BalanceOf<T> {
caller_funding::<T>().saturating_sub(T::Currency::minimum_balance())
}
}
@@ -109,8 +109,7 @@ where
module: WasmModule<T>,
data: Vec<u8>,
endowment: Endow,
) -> Result<Contract<T>, &'static str>
{
) -> Result<Contract<T>, &'static str> {
let (storage_size, endowment) = match endowment {
Endow::CollectRent => {
// storage_size cannot be zero because otherwise a contract that is just above
@@ -182,7 +181,8 @@ where
/// Get the `AliveContractInfo` of the `addr` or an error if it is no longer alive.
fn address_alive_info(addr: &T::AccountId) -> Result<AliveContractInfo<T>, &'static str> {
ContractInfoOf::<T>::get(addr).and_then(|c| c.get_alive())
ContractInfoOf::<T>::get(addr)
.and_then(|c| c.get_alive())
.ok_or("Expected contract to be alive at this point.")
}
@@ -193,7 +193,8 @@ where
/// Return an error if this contract is no tombstone.
fn ensure_tombstone(&self) -> Result<(), &'static str> {
ContractInfoOf::<T>::get(&self.account_id).and_then(|c| c.get_tombstone())
ContractInfoOf::<T>::get(&self.account_id)
.and_then(|c| c.get_tombstone())
.ok_or("Expected contract to be a tombstone at this point.")
.map(|_| ())
}
@@ -236,16 +237,13 @@ where
let contract = Contract::<T>::new(code, vec![], Endow::CollectRent)?;
let storage_items = create_storage::<T>(stor_num, stor_size)?;
contract.store(&storage_items)?;
Ok(Self {
contract,
storage: storage_items,
})
Ok(Self { contract, storage: storage_items })
}
/// Increase the system block number so that this contract is eligible for eviction.
fn set_block_num_for_eviction(&self) -> Result<(), &'static str> {
fn set_block_num_for_eviction(&self) -> Result<(), &'static str> {
System::<T>::set_block_number(
self.contract.eviction_at()? + T::SignedClaimHandicap::get() + 5u32.into()
self.contract.eviction_at()? + T::SignedClaimHandicap::get() + 5u32.into(),
);
Ok(())
}
@@ -261,15 +259,17 @@ where
/// Generate `stor_num` storage items. Each has the size `stor_size`.
fn create_storage<T: Config>(
stor_num: u32,
stor_size: u32
stor_size: u32,
) -> Result<Vec<(StorageKey, Vec<u8>)>, &'static str> {
(0..stor_num).map(|i| {
let hash = T::Hashing::hash_of(&i)
.as_ref()
.try_into()
.map_err(|_| "Hash too big for storage key")?;
Ok((hash, vec![42u8; stor_size as usize]))
}).collect::<Result<Vec<_>, &'static str>>()
(0..stor_num)
.map(|i| {
let hash = T::Hashing::hash_of(&i)
.as_ref()
.try_into()
.map_err(|_| "Hash too big for storage key")?;
Ok((hash, vec![42u8; stor_size as usize]))
})
.collect::<Result<Vec<_>, &'static str>>()
}
/// The funding that each account that either calls or instantiates contracts is funded with.
@@ -15,14 +15,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.
///! For instruction benchmarking we do no instantiate a full contract but merely the
///! sandbox to execute the wasm code. This is because we do not need the full
///! environment that provides the seal interface as imported functions.
use super::{
Config,
code::WasmModule,
};
/// ! For instruction benchmarking we do no instantiate a full contract but merely the
/// ! sandbox to execute the wasm code. This is because we do not need the full
/// ! environment that provides the seal interface as imported functions.
use super::{code::WasmModule, Config};
use sp_core::crypto::UncheckedFrom;
use sp_sandbox::{EnvironmentDefinitionBuilder, Instance, Memory};
@@ -51,9 +47,6 @@ where
let memory = module.add_memory(&mut env_builder);
let instance = Instance::new(&module.code, &env_builder, &mut ())
.expect("Failed to create benchmarking Sandbox instance");
Self {
instance,
_memory: memory,
}
Self { instance, _memory: memory }
}
}