Convert spaces to tabs (#6799)

This commit is contained in:
Ashley
2020-08-03 15:48:32 +02:00
committed by GitHub
parent 1a84ad87c0
commit 07facb13c2
11 changed files with 262 additions and 262 deletions
+12 -12
View File
@@ -93,26 +93,26 @@ pub enum Mode {
}
impl std::str::FromStr for Mode {
type Err = &'static str;
fn from_str(day: &str) -> Result<Self, Self::Err> {
match day {
"regular" => Ok(Mode::Regular),
"profile" => Ok(Mode::Profile),
_ => Err("Could not parse mode"),
}
}
type Err = &'static str;
fn from_str(day: &str) -> Result<Self, Self::Err> {
match day {
"regular" => Ok(Mode::Regular),
"profile" => Ok(Mode::Profile),
_ => Err("Could not parse mode"),
}
}
}
impl fmt::Display for BenchmarkOutput {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}: avg {}, w_avg {}",
self.name,
NsFormatter(self.raw_average),
NsFormatter(self.average),
)
}
}
}
pub fn run_benchmark(
@@ -159,4 +159,4 @@ macro_rules! matrix(
}
};
() => { vec![] }
);
);
+3 -3
View File
@@ -32,7 +32,7 @@ use sp_transaction_pool::{TransactionPool, TransactionSource};
use crate::core::{self, Path, Mode};
pub struct PoolBenchmarkDescription {
pub database_type: DatabaseType,
pub database_type: DatabaseType,
}
pub struct PoolBenchmark {
@@ -41,7 +41,7 @@ pub struct PoolBenchmark {
impl core::BenchmarkDescription for PoolBenchmarkDescription {
fn path(&self) -> Path {
Path::new(&["node", "txpool"])
Path::new(&["node", "txpool"])
}
fn setup(self: Box<Self>) -> Box<dyn core::Benchmark> {
@@ -55,7 +55,7 @@ impl core::BenchmarkDescription for PoolBenchmarkDescription {
}
fn name(&self) -> Cow<'static, str> {
"Transaction pool benchmark".into()
"Transaction pool benchmark".into()
}
}
+22 -22
View File
@@ -37,34 +37,34 @@ use serde::de::DeserializeOwned;
wasm_bindgen_test_configure!(run_in_browser);
fn rpc_call(method: &str) -> String {
serde_json::to_string(&MethodCall {
jsonrpc: Some(Version::V2),
method: method.into(),
params: Params::None,
id: Id::Num(1)
}).unwrap()
serde_json::to_string(&MethodCall {
jsonrpc: Some(Version::V2),
method: method.into(),
params: Params::None,
id: Id::Num(1)
}).unwrap()
}
fn deserialize_rpc_result<T: DeserializeOwned>(js_value: JsValue) -> T {
let string = js_value.as_string().unwrap();
let value = serde_json::from_str::<Success>(&string).unwrap().result;
// We need to convert a `Value::Object` into a proper type.
let value_string = serde_json::to_string(&value).unwrap();
serde_json::from_str(&value_string).unwrap()
let string = js_value.as_string().unwrap();
let value = serde_json::from_str::<Success>(&string).unwrap().result;
// We need to convert a `Value::Object` into a proper type.
let value_string = serde_json::to_string(&value).unwrap();
serde_json::from_str(&value_string).unwrap()
}
#[wasm_bindgen_test]
async fn runs() {
let mut client = node_cli::start_client(None, "info".into())
.await
.unwrap();
let mut client = node_cli::start_client(None, "info".into())
.await
.unwrap();
// Check that the node handles rpc calls.
// TODO: Re-add the code that checks if the node is syncing.
let chain_name: String = deserialize_rpc_result(
JsFuture::from(client.rpc_send(&rpc_call("system_chain")))
.await
.unwrap()
);
assert_eq!(chain_name, "Development");
// Check that the node handles rpc calls.
// TODO: Re-add the code that checks if the node is syncing.
let chain_name: String = deserialize_rpc_result(
JsFuture::from(client.rpc_send(&rpc_call("system_chain")))
.await
.unwrap()
);
assert_eq!(chain_name, "Development");
}
+11 -11
View File
@@ -41,8 +41,8 @@ impl MetricsLink {
/// Authorship metrics.
#[derive(Clone)]
pub struct Metrics {
pub block_constructed: Histogram,
pub number_of_transactions: Gauge<U64>,
pub block_constructed: Histogram,
pub number_of_transactions: Gauge<U64>,
}
impl Metrics {
@@ -54,14 +54,14 @@ impl Metrics {
"Histogram of time taken to construct new block",
))?,
registry,
)?,
number_of_transactions: register(
Gauge::new(
"proposer_number_of_transactions",
"Number of transactions included in block",
)?,
registry,
)?,
)?,
number_of_transactions: register(
Gauge::new(
"proposer_number_of_transactions",
"Number of transactions included in block",
)?,
registry,
)?,
})
}
}
}
@@ -686,7 +686,7 @@ fn changes_proof_is_generated_and_checked_when_headers_are_not_pruned() {
match local_result == expected_result {
true => (),
false => panic!(format!("Failed test {}: local = {:?}, expected = {:?}",
index, local_result, expected_result)),
index, local_result, expected_result)),
}
}
}
@@ -843,7 +843,7 @@ fn check_changes_tries_proof_fails_if_proof_is_wrong() {
Box::new(TaskExecutor::new()),
);
assert!(local_checker.check_changes_tries_proof(4, &remote_proof.roots,
remote_proof.roots_proof.clone()).is_err());
remote_proof.roots_proof.clone()).is_err());
// fails when proof is broken
let mut local_storage = DummyStorage::new();
+179 -179
View File
@@ -28,21 +28,21 @@ use parity_wasm::elements::FuncBody;
use sp_runtime::traits::Hash;
macro_rules! load_module {
($name:expr) => {{
let code = include_bytes!(concat!("../fixtures/benchmarks/", $name, ".wat"));
compile_module::<T>(code)
}};
($name:expr) => {{
let code = include_bytes!(concat!("../fixtures/benchmarks/", $name, ".wat"));
compile_module::<T>(code)
}};
}
fn compile_module<T: Trait>(code: &[u8]) -> (Vec<u8>, <T::Hashing as Hash>::Output) {
let code = sp_std::str::from_utf8(code).expect("Invalid utf8 in wat file.");
let binary = wat::parse_str(code).expect("Failed to compile wat file.");
let hash = T::Hashing::hash(&binary);
(binary, hash)
let code = sp_std::str::from_utf8(code).expect("Invalid utf8 in wat file.");
let binary = wat::parse_str(code).expect("Failed to compile wat file.");
let hash = T::Hashing::hash(&binary);
(binary, hash)
}
fn funding<T: Trait>() -> BalanceOf<T> {
T::Currency::minimum_balance() * 10_000.into()
T::Currency::minimum_balance() * 10_000.into()
}
fn create_funded_user<T: Trait>(string: &'static str, n: u32) -> T::AccountId {
@@ -52,55 +52,55 @@ fn create_funded_user<T: Trait>(string: &'static str, n: u32) -> T::AccountId {
}
fn contract_with_call_body<T: Trait>(body: FuncBody) -> (Vec<u8>, <T::Hashing as Hash>::Output) {
use parity_wasm::elements::{
Instructions, Instruction::End,
};
let contract = parity_wasm::builder::ModuleBuilder::new()
// deploy function (idx 0)
.function()
.signature().with_params(vec![]).with_return_type(None).build()
.body().with_instructions(Instructions::new(vec![End])).build()
.build()
// call function (idx 1)
.function()
.signature().with_params(vec![]).with_return_type(None).build()
.with_body(body)
.build()
.export().field("deploy").internal().func(0).build()
.export().field("call").internal().func(1).build()
.build();
let bytes = contract.to_bytes().unwrap();
let hash = T::Hashing::hash(&bytes);
(bytes, hash)
use parity_wasm::elements::{
Instructions, Instruction::End,
};
let contract = parity_wasm::builder::ModuleBuilder::new()
// deploy function (idx 0)
.function()
.signature().with_params(vec![]).with_return_type(None).build()
.body().with_instructions(Instructions::new(vec![End])).build()
.build()
// call function (idx 1)
.function()
.signature().with_params(vec![]).with_return_type(None).build()
.with_body(body)
.build()
.export().field("deploy").internal().func(0).build()
.export().field("call").internal().func(1).build()
.build();
let bytes = contract.to_bytes().unwrap();
let hash = T::Hashing::hash(&bytes);
(bytes, hash)
}
fn expanded_contract<T: Trait>(target_bytes: u32) -> (Vec<u8>, <T::Hashing as Hash>::Output) {
use parity_wasm::elements::{
Instruction::{self, If, I32Const, Return, End},
BlockType, Instructions,
};
// Base size of a contract is 47 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 `put_code`.
let expansions = (target_bytes.saturating_sub(47) / 6).saturating_sub(1) as usize;
const EXPANSION: [Instruction; 4] = [
I32Const(0),
If(BlockType::NoResult),
Return,
End,
];
let instructions = Instructions::new(
EXPANSION
.iter()
.cycle()
.take(EXPANSION.len() * expansions)
.cloned()
.chain(sp_std::iter::once(End))
.collect()
);
contract_with_call_body::<T>(FuncBody::new(Vec::new(), instructions))
use parity_wasm::elements::{
Instruction::{self, If, I32Const, Return, End},
BlockType, Instructions,
};
// Base size of a contract is 47 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 `put_code`.
let expansions = (target_bytes.saturating_sub(47) / 6).saturating_sub(1) as usize;
const EXPANSION: [Instruction; 4] = [
I32Const(0),
If(BlockType::NoResult),
Return,
End,
];
let instructions = Instructions::new(
EXPANSION
.iter()
.cycle()
.take(EXPANSION.len() * expansions)
.cloned()
.chain(sp_std::iter::once(End))
.collect()
);
contract_with_call_body::<T>(FuncBody::new(Vec::new(), instructions))
}
fn advance_block<T: Trait>(num: <T as frame_system::Trait>::BlockNumber) {
@@ -109,161 +109,161 @@ fn advance_block<T: Trait>(num: <T as frame_system::Trait>::BlockNumber) {
}
benchmarks! {
_ {
}
_ {
}
// This extrinsic is pretty much constant as it is only a simple setter.
update_schedule {
let schedule = Schedule {
version: 1,
.. Default::default()
};
}: _(RawOrigin::Root, schedule)
// This extrinsic is pretty much constant as it is only a simple setter.
update_schedule {
let schedule = Schedule {
version: 1,
.. Default::default()
};
}: _(RawOrigin::Root, schedule)
// This constructs a contract that is maximal expensive to instrument.
// It creates a maximum number of metering blocks per byte.
put_code {
let n in 0 .. Contracts::<T>::current_schedule().max_code_size;
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = expanded_contract::<T>(n);
}: _(RawOrigin::Signed(caller), binary)
// This constructs a contract that is maximal expensive to instrument.
// It creates a maximum number of metering blocks per byte.
put_code {
let n in 0 .. Contracts::<T>::current_schedule().max_code_size;
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = expanded_contract::<T>(n);
}: _(RawOrigin::Signed(caller), binary)
// Instantiate uses a dummy contract constructor to measure the overhead of the instantiate.
// The size of the data has no influence on the costs of this extrinsic as long as the contract
// won't call `ext_input` in its constructor to copy the data to contract memory.
// The dummy contract used here does not do this. The costs for the data copy is billed as
// part of `ext_input`.
instantiate {
let data = vec![0u8; 128];
let endowment = Config::<T>::subsistence_threshold_uncached();
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = load_module!("dummy");
Contracts::<T>::put_code(RawOrigin::Signed(caller.clone()).into(), binary.to_vec())
.unwrap();
// Instantiate uses a dummy contract constructor to measure the overhead of the instantiate.
// The size of the data has no influence on the costs of this extrinsic as long as the contract
// won't call `ext_input` in its constructor to copy the data to contract memory.
// The dummy contract used here does not do this. The costs for the data copy is billed as
// part of `ext_input`.
instantiate {
let data = vec![0u8; 128];
let endowment = Config::<T>::subsistence_threshold_uncached();
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = load_module!("dummy");
Contracts::<T>::put_code(RawOrigin::Signed(caller.clone()).into(), binary.to_vec())
.unwrap();
}: _(
RawOrigin::Signed(caller.clone()),
endowment,
Weight::max_value(),
hash,
data
)
verify {
assert_eq!(
funding::<T>() - endowment,
T::Currency::free_balance(&caller),
)
}
}: _(
RawOrigin::Signed(caller.clone()),
endowment,
Weight::max_value(),
hash,
data
)
verify {
assert_eq!(
funding::<T>() - endowment,
T::Currency::free_balance(&caller),
)
}
// We just call a dummy contract to measure to overhead of the call extrinsic.
// As for instantiate the size of the data does not influence the costs.
call {
let data = vec![0u8; 128];
let endowment = Config::<T>::subsistence_threshold_uncached();
let value = T::Currency::minimum_balance() * 100.into();
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = load_module!("dummy");
let addr = T::DetermineContractAddress::contract_address_for(&hash, &[], &caller);
Contracts::<T>::put_code(RawOrigin::Signed(caller.clone()).into(), binary.to_vec())
.unwrap();
Contracts::<T>::instantiate(
RawOrigin::Signed(caller.clone()).into(),
endowment,
Weight::max_value(),
hash,
vec![],
).unwrap();
}: _(
RawOrigin::Signed(caller.clone()),
T::Lookup::unlookup(addr),
value,
Weight::max_value(),
data
)
verify {
assert_eq!(
funding::<T>() - endowment - value,
T::Currency::free_balance(&caller),
)
}
// We just call a dummy contract to measure to overhead of the call extrinsic.
// As for instantiate the size of the data does not influence the costs.
call {
let data = vec![0u8; 128];
let endowment = Config::<T>::subsistence_threshold_uncached();
let value = T::Currency::minimum_balance() * 100.into();
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = load_module!("dummy");
let addr = T::DetermineContractAddress::contract_address_for(&hash, &[], &caller);
Contracts::<T>::put_code(RawOrigin::Signed(caller.clone()).into(), binary.to_vec())
.unwrap();
Contracts::<T>::instantiate(
RawOrigin::Signed(caller.clone()).into(),
endowment,
Weight::max_value(),
hash,
vec![],
).unwrap();
}: _(
RawOrigin::Signed(caller.clone()),
T::Lookup::unlookup(addr),
value,
Weight::max_value(),
data
)
verify {
assert_eq!(
funding::<T>() - endowment - value,
T::Currency::free_balance(&caller),
)
}
// We benchmark the costs for sucessfully evicting an empty contract.
// The actual costs are depending on how many storage items the evicted contract
// does have. However, those costs are not to be payed by the sender but
// will be distributed over multiple blocks using a scheduler. Otherwise there is
// no incentive to remove large contracts when the removal is more expensive than
// the reward for removing them.
claim_surcharge {
let endowment = Config::<T>::subsistence_threshold_uncached();
let value = T::Currency::minimum_balance() * 100.into();
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = load_module!("dummy");
let addr = T::DetermineContractAddress::contract_address_for(&hash, &[], &caller);
Contracts::<T>::put_code(RawOrigin::Signed(caller.clone()).into(), binary.to_vec())
.unwrap();
Contracts::<T>::instantiate(
RawOrigin::Signed(caller.clone()).into(),
endowment,
Weight::max_value(),
hash,
vec![],
).unwrap();
// We benchmark the costs for sucessfully evicting an empty contract.
// The actual costs are depending on how many storage items the evicted contract
// does have. However, those costs are not to be payed by the sender but
// will be distributed over multiple blocks using a scheduler. Otherwise there is
// no incentive to remove large contracts when the removal is more expensive than
// the reward for removing them.
claim_surcharge {
let endowment = Config::<T>::subsistence_threshold_uncached();
let value = T::Currency::minimum_balance() * 100.into();
let caller = create_funded_user::<T>("caller", 0);
let (binary, hash) = load_module!("dummy");
let addr = T::DetermineContractAddress::contract_address_for(&hash, &[], &caller);
Contracts::<T>::put_code(RawOrigin::Signed(caller.clone()).into(), binary.to_vec())
.unwrap();
Contracts::<T>::instantiate(
RawOrigin::Signed(caller.clone()).into(),
endowment,
Weight::max_value(),
hash,
vec![],
).unwrap();
// instantiate should leave us with an alive contract
ContractInfoOf::<T>::get(addr.clone()).unwrap().get_alive().unwrap();
// instantiate should leave us with an alive contract
ContractInfoOf::<T>::get(addr.clone()).unwrap().get_alive().unwrap();
// generate some rent
advance_block::<T>(<T as Trait>::SignedClaimHandicap::get() + 1.into());
// generate some rent
advance_block::<T>(<T as Trait>::SignedClaimHandicap::get() + 1.into());
}: _(RawOrigin::Signed(caller.clone()), addr.clone(), None)
verify {
// the claim surcharge should have evicted the contract
ContractInfoOf::<T>::get(addr.clone()).unwrap().get_tombstone().unwrap();
}: _(RawOrigin::Signed(caller.clone()), addr.clone(), None)
verify {
// the claim surcharge should have evicted the contract
ContractInfoOf::<T>::get(addr.clone()).unwrap().get_tombstone().unwrap();
// the caller should get the reward for being a good snitch
assert_eq!(
funding::<T>() - endowment + <T as Trait>::SurchargeReward::get(),
T::Currency::free_balance(&caller),
);
}
// the caller should get the reward for being a good snitch
assert_eq!(
funding::<T>() - endowment + <T as Trait>::SurchargeReward::get(),
T::Currency::free_balance(&caller),
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{ExtBuilder, Test};
use frame_support::assert_ok;
use super::*;
use crate::tests::{ExtBuilder, Test};
use frame_support::assert_ok;
#[test]
fn update_schedule() {
#[test]
fn update_schedule() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(test_benchmark_update_schedule::<Test>());
});
}
}
#[test]
fn put_code() {
#[test]
fn put_code() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(test_benchmark_put_code::<Test>());
});
}
}
#[test]
fn instantiate() {
#[test]
fn instantiate() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(test_benchmark_instantiate::<Test>());
});
}
}
#[test]
fn call() {
#[test]
fn call() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(test_benchmark_call::<Test>());
});
}
}
#[test]
fn claim_surcharge() {
#[test]
fn claim_surcharge() {
ExtBuilder::default().build().execute_with(|| {
assert_ok!(test_benchmark_claim_surcharge::<Test>());
});
+3 -3
View File
@@ -2861,9 +2861,9 @@ mod offchain_phragmen {
let (offchain, offchain_state) = TestOffchainExt::new();
let (pool, pool_state) = TestTransactionPoolExt::new();
let mut seed = [0_u8; 32];
seed[0..4].copy_from_slice(&iterations.to_le_bytes());
offchain_state.write().seed = seed;
let mut seed = [0_u8; 32];
seed[0..4].copy_from_slice(&iterations.to_le_bytes());
offchain_state.write().seed = seed;
ext.register_extension(OffchainExt::new(offchain));
ext.register_extension(TransactionPoolExt::new(pool));
@@ -48,7 +48,7 @@ impl Metrics {
&["result"],
)?,
registry,
)?,
)?,
})
}
+6 -6
View File
@@ -399,15 +399,15 @@ impl TraitPublic for Public {
}
impl From<Public> for CryptoTypePublicPair {
fn from(key: Public) -> Self {
(&key).into()
}
fn from(key: Public) -> Self {
(&key).into()
}
}
impl From<&Public> for CryptoTypePublicPair {
fn from(key: &Public) -> Self {
CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
}
fn from(key: &Public) -> Self {
CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
}
}
#[cfg(feature = "std")]
@@ -560,34 +560,34 @@ mod tests {
offchain::sleep_until(offchain::timestamp().add(Duration::from_millis(200)));
// the lock is still active, extend it successfully
assert_eq!(guard.extend_lock().is_ok(), true);
assert_eq!(guard.extend_lock().is_ok(), true);
// sleep_until < deadline
offchain::sleep_until(offchain::timestamp().add(Duration::from_millis(200)));
// sleep_until < deadline
offchain::sleep_until(offchain::timestamp().add(Duration::from_millis(200)));
// the lock is still active, try_lock will fail
let mut lock = StorageLock::<'_, Time>::with_deadline(b"lock_4", lock_expiration);
let res = lock.try_lock();
assert_eq!(res.is_ok(), false);
// the lock is still active, try_lock will fail
let mut lock = StorageLock::<'_, Time>::with_deadline(b"lock_4", lock_expiration);
let res = lock.try_lock();
assert_eq!(res.is_ok(), false);
// sleep again untill sleep_until > deadline
offchain::sleep_until(offchain::timestamp().add(Duration::from_millis(200)));
// sleep again untill sleep_until > deadline
offchain::sleep_until(offchain::timestamp().add(Duration::from_millis(200)));
// the lock has expired, failed to extend it
assert_eq!(guard.extend_lock().is_ok(), false);
guard.forget();
// the lock has expired, failed to extend it
assert_eq!(guard.extend_lock().is_ok(), false);
guard.forget();
// try_lock will succeed
let mut lock = StorageLock::<'_, Time>::with_deadline(b"lock_4", lock_expiration);
let res = lock.try_lock();
assert!(res.is_ok());
let guard = res.unwrap();
// try_lock will succeed
let mut lock = StorageLock::<'_, Time>::with_deadline(b"lock_4", lock_expiration);
let res = lock.try_lock();
assert!(res.is_ok());
let guard = res.unwrap();
guard.forget();
});
guard.forget();
});
// lock must have been cleared at this point
let opt = state.read().persistent_storage.get(b"", b"lock_4");
assert_eq!(opt.unwrap(), vec![132_u8, 3u8, 0, 0, 0, 0, 0, 0]); // 132 + 256 * 3 = 900
// lock must have been cleared at this point
let opt = state.read().persistent_storage.get(b"", b"lock_4");
assert_eq!(opt.unwrap(), vec![132_u8, 3u8, 0, 0, 0, 0, 0, 0]); // 132 + 256 * 3 = 900
}
}
+1 -1
View File
@@ -132,7 +132,7 @@ impl<H, N, V> ForkTree<H, N, V> where
let mut root = root
.expect("find_node_index_where will return array with at least one index; \
this results in at least one item in removed; qed");
this results in at least one item in removed; qed");
let mut removed = old_roots;