Convert unnecessary storage item to static. (#3093)

* Convert unnecessary storage item to static.

* Polish

* 6 second blocks.

* Compile fixes

* Bump runtime

* Fix

* Another fix

* Import `srml_support::traits::Get`

* Export MinimumPeriod from `decl_module!`

* Remove `config` from Timestamp

* Clean up warnings
This commit is contained in:
Gavin Wood
2019-07-11 23:03:33 +02:00
committed by GitHub
parent b3dc472a9b
commit e4d4548121
15 changed files with 65 additions and 90 deletions
+5 -2
View File
@@ -33,7 +33,6 @@ pub use runtime_primitives::BuildStorage;
pub use timestamp::Call as TimestampCall;
pub use balances::Call as BalancesCall;
pub use runtime_primitives::{Permill, Perbill};
pub use timestamp::BlockPeriod;
pub use support::{StorageValue, construct_runtime, parameter_types};
/// Alias to the signature scheme used for Aura authority signatures.
@@ -155,10 +154,14 @@ impl indices::Trait for Runtime {
type Event = Event;
}
parameter_types! {
pub const MinimumPeriod: u64 = 5;
}
impl timestamp::Trait for Runtime {
/// A timestamp: seconds since the unix epoch.
type Moment = u64;
type OnTimestampSet = Aura;
type MinimumPeriod = MinimumPeriod;
}
parameter_types! {
@@ -207,7 +210,7 @@ construct_runtime!(
UncheckedExtrinsic = UncheckedExtrinsic
{
System: system::{Module, Call, Storage, Config, Event},
Timestamp: timestamp::{Module, Call, Storage, Config<T>, Inherent},
Timestamp: timestamp::{Module, Call, Storage, Inherent},
Aura: aura::{Module, Config<T>, Inherent(Timestamp)},
Indices: indices::{default, Config<T>},
Balances: balances,
+1 -4
View File
@@ -1,6 +1,6 @@
use primitives::{ed25519, sr25519, Pair};
use node_template_runtime::{
AccountId, GenesisConfig, AuraConfig, TimestampConfig, BalancesConfig,
AccountId, GenesisConfig, AuraConfig, BalancesConfig,
SudoConfig, IndicesConfig, SystemConfig, WASM_BINARY, AuraId
};
use substrate_service;
@@ -97,9 +97,6 @@ fn testnet_genesis(initial_authorities: Vec<AuraId>, endowed_accounts: Vec<Accou
aura: Some(AuraConfig {
authorities: initial_authorities.clone(),
}),
timestamp: Some(TimestampConfig {
minimum_period: 5, // 10 second block time.
}),
indices: Some(IndicesConfig {
ids: endowed_accounts.clone(),
}),
+5 -19
View File
@@ -21,8 +21,8 @@ use node_primitives::{AccountId, AuraId, Balance};
use node_runtime::{
GrandpaConfig, BalancesConfig, ContractsConfig, ElectionsConfig, DemocracyConfig, CouncilConfig,
AuraConfig, IndicesConfig, SessionConfig, StakingConfig, SudoConfig, TechnicalCommitteeConfig,
SystemConfig, TimestampConfig, WASM_BINARY, Perbill, SessionKeys, StakerStatus, DAYS, DOLLARS,
MILLICENTS, SECS_PER_BLOCK,
SystemConfig, WASM_BINARY, Perbill, SessionKeys, StakerStatus, DAYS, DOLLARS,
MILLICENTS,
};
pub use node_runtime::GenesisConfig;
use substrate_service;
@@ -144,9 +144,6 @@ fn staging_testnet_config_genesis() -> GenesisConfig {
term_duration: 28 * DAYS,
desired_seats: 0,
}),
timestamp: Some(TimestampConfig {
minimum_period: SECS_PER_BLOCK / 2, // due to the nature of aura the slots are 2*period
}),
contracts: Some(ContractsConfig {
current_schedule: Default::default(),
gas_price: 1 * MILLICENTS,
@@ -281,9 +278,6 @@ pub fn testnet_genesis(
term_duration: 1000000,
desired_seats: desired_seats,
}),
timestamp: Some(TimestampConfig {
minimum_period: 2, // 2*2=4 second block time.
}),
contracts: Some(ContractsConfig {
current_schedule: contracts::Schedule {
enable_println, // this should only be enabled on development chains
@@ -342,23 +336,15 @@ pub(crate) mod tests {
use service_test;
use crate::service::Factory;
fn local_testnet_genesis_instant() -> GenesisConfig {
let mut genesis = local_testnet_genesis();
genesis.timestamp = Some(TimestampConfig { minimum_period: 1 });
genesis
}
fn local_testnet_genesis_instant_single() -> GenesisConfig {
let mut genesis = testnet_genesis(
testnet_genesis(
vec![
get_authority_keys_from_seed("Alice"),
],
get_account_id_from_seed("Alice"),
None,
false,
);
genesis.timestamp = Some(TimestampConfig { minimum_period: 1 });
genesis
)
}
/// Local testnet config (single validator - Alice)
@@ -377,7 +363,7 @@ pub(crate) mod tests {
/// Local testnet config (multivalidator Alice + Bob)
pub fn integration_test_config_with_two_authorities() -> ChainSpec {
ChainSpec::from_genesis("Integration Test", "test", local_testnet_genesis_instant, vec![], None, None, None, None)
ChainSpec::from_genesis("Integration Test", "test", local_testnet_genesis, vec![], None, None, None, None)
}
#[test]
+1 -1
View File
@@ -38,7 +38,7 @@ use inherents::InherentData;
use timestamp;
use finality_tracker;
// TODO get via api: <timestamp::Module<T>>::minimum_period(). See #2587.
// TODO get via api: <T as timestamp::Trait>::MinimumPeriod::get(). See #2587.
const MINIMUM_PERIOD: u64 = 99;
pub struct FactoryState<N> {
-1
View File
@@ -346,7 +346,6 @@ mod tests {
collective_Instance1: Some(Default::default()),
collective_Instance2: Some(Default::default()),
elections: Some(Default::default()),
timestamp: Some(Default::default()),
contracts: Some(ContractsConfig {
current_schedule: Default::default(),
gas_price: 1 * MILLICENTS,
+6 -2
View File
@@ -69,7 +69,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// and set impl_version to equal spec_version. If only runtime
// implementation changes and behavior does not, then leave spec_version as
// is and increment impl_version.
spec_version: 109,
spec_version: 110,
impl_version: 110,
apis: RUNTIME_API_VERSIONS,
};
@@ -161,9 +161,13 @@ impl balances::Trait for Runtime {
type TransactionByteFee = TransactionByteFee;
}
parameter_types! {
pub const MinimumPeriod: u64 = SECS_PER_BLOCK / 2;
}
impl timestamp::Trait for Runtime {
type Moment = Moment;
type OnTimestampSet = Aura;
type MinimumPeriod = MinimumPeriod;
}
parameter_types! {
@@ -407,7 +411,7 @@ construct_runtime!(
{
System: system::{Module, Call, Storage, Config, Event},
Aura: aura::{Module, Call, Storage, Config<T>, Inherent(Timestamp)},
Timestamp: timestamp::{Module, Call, Storage, Config<T>, Inherent},
Timestamp: timestamp::{Module, Call, Storage, Inherent},
Authorship: authorship::{Module, Call, Storage},
Indices: indices,
Balances: balances,
+2 -2
View File
@@ -52,7 +52,7 @@ pub use timestamp;
use rstd::{result, prelude::*};
use parity_codec::Encode;
use srml_support::{decl_storage, decl_module, Parameter, storage::StorageValue};
use srml_support::{decl_storage, decl_module, Parameter, storage::StorageValue, traits::Get};
use primitives::{
traits::{SaturatedConversion, Saturating, Zero, One, Member, TypedKey},
generic::DigestItem,
@@ -243,7 +243,7 @@ impl<T: Trait> Module<T> {
pub fn slot_duration() -> T::Moment {
// we double the minimum block-period so each author can always propose within
// the majority of its slot.
<timestamp::Module<T>>::minimum_period().saturating_mul(2.into())
<T as timestamp::Trait>::MinimumPeriod::get().saturating_mul(2.into())
}
fn on_timestamp_set<H: HandleReport>(now: T::Moment, slot_duration: T::Moment) {
+2 -3
View File
@@ -37,6 +37,7 @@ pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MinimumPeriod: u64 = 1;
}
impl system::Trait for Test {
@@ -55,6 +56,7 @@ impl system::Trait for Test {
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = Aura;
type MinimumPeriod = MinimumPeriod;
}
impl Trait for Test {
@@ -64,9 +66,6 @@ impl Trait for Test {
pub fn new_test_ext(authorities: Vec<u64>) -> runtime_io::TestExternalities<Blake2Hasher> {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap().0;
t.extend(timestamp::GenesisConfig::<Test>{
minimum_period: 1,
}.build_storage().unwrap().0);
t.extend(GenesisConfig::<Test>{
authorities: authorities.into_iter().map(|a| UintAuthorityId(a)).collect(),
}.build_storage().unwrap().0);
+2 -2
View File
@@ -21,7 +21,7 @@
pub use timestamp;
use rstd::{result, prelude::*};
use srml_support::{decl_storage, decl_module, StorageValue, traits::FindAuthor};
use srml_support::{decl_storage, decl_module, StorageValue, traits::FindAuthor, traits::Get};
use timestamp::{OnTimestampSet, Trait};
use primitives::{generic::DigestItem, traits::{SaturatedConversion, Saturating, RandomnessBeacon}};
use primitives::ConsensusEngineId;
@@ -193,7 +193,7 @@ impl<T: Trait> Module<T> {
pub fn slot_duration() -> T::Moment {
// we double the minimum block-period so each author can always propose within
// the majority of their slot.
<timestamp::Module<T>>::minimum_period().saturating_mul(2.into())
<T as timestamp::Trait>::MinimumPeriod::get().saturating_mul(2.into())
}
fn change_authorities(new: Vec<AuthorityId>) {
+4
View File
@@ -127,9 +127,13 @@ impl balances::Trait for Test {
type TransactionBaseFee = BalancesTransactionBaseFee;
type TransactionByteFee = BalancesTransactionByteFee;
}
parameter_types! {
pub const MinimumPeriod: u64 = 1;
}
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
}
parameter_types! {
pub const SignedClaimHandicap: u64 = 2;
-3
View File
@@ -327,9 +327,6 @@ mod tests {
fn new_test_ext() -> runtime_io::TestExternalities<Blake2Hasher> {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap().0;
t.extend(timestamp::GenesisConfig::<Test> {
minimum_period: 5,
}.build_storage().unwrap().0);
let (storage, _child_storage) = crate::GenesisConfig::<Test> {
keys: NEXT_VALIDATORS.with(|l|
l.borrow().iter().cloned().map(|i| (i, UintAuthorityId(i))).collect()
-3
View File
@@ -565,9 +565,6 @@ mod tests {
fn new_test_ext() -> runtime_io::TestExternalities<Blake2Hasher> {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
timestamp::GenesisConfig::<Test> {
minimum_period: 5,
}.assimilate_storage(&mut t.0, &mut t.1).unwrap();
GenesisConfig::<Test> {
keys: NEXT_VALIDATORS.with(|l|
l.borrow().iter().cloned().map(|i| (i, UintAuthorityId(i))).collect()
+2
View File
@@ -109,6 +109,7 @@ pub fn set_next_validators(next: Vec<u64>) {
pub struct Test;
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MinimumPeriod: u64 = 5;
}
impl system::Trait for Test {
type Origin = Origin;
@@ -125,6 +126,7 @@ impl system::Trait for Test {
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
}
+4 -4
View File
@@ -140,9 +140,13 @@ impl session::historical::Trait for Test {
type FullIdentificationOf = crate::ExposureOf<Test>;
}
parameter_types! {
pub const MinimumPeriod: u64 = 5;
}
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
}
parameter_types! {
pub const SessionsPerEra: session::SessionIndex = 3;
@@ -279,10 +283,6 @@ impl ExtBuilder {
invulnerables: vec![],
}.assimilate_storage(&mut t, &mut c);
let _ = timestamp::GenesisConfig::<Test>{
minimum_period: 5,
}.assimilate_storage(&mut t, &mut c);
let _ = session::GenesisConfig::<Test> {
keys: validators.iter().map(|x| (*x, UintAuthorityId(*x))).collect(),
}.assimilate_storage(&mut t, &mut c);
+31 -44
View File
@@ -44,7 +44,10 @@
//!
//! * `get` - Gets the current time for the current block. If this function is called prior to
//! setting the timestamp, it will return the timestamp of the previous block.
//! * `minimum_period` - Gets the minimum (and advised) period between blocks for the chain.
//!
//! ### Trait Getters
//!
//! * `MinimumPeriod` - Gets the minimum (and advised) period between blocks for the chain.
//!
//! ## Usage
//!
@@ -93,8 +96,7 @@ use parity_codec::Encode;
use parity_codec::Decode;
#[cfg(feature = "std")]
use inherents::ProvideInherentData;
use srml_support::{StorageValue, Parameter, decl_storage, decl_module};
use srml_support::for_each_tuple;
use srml_support::{StorageValue, Parameter, decl_storage, decl_module, for_each_tuple, traits::Get};
use runtime_primitives::traits::{SimpleArithmetic, Zero, SaturatedConversion};
use system::ensure_none;
use inherents::{RuntimeString, InherentIdentifier, ProvideInherent, IsFatalError, InherentData};
@@ -208,23 +210,36 @@ pub trait Trait: system::Trait {
/// Something which can be notified when the timestamp is set. Set this to `()` if not needed.
type OnTimestampSet: OnTimestampSet<Self::Moment>;
/// The minimum period between blocks. Beware that this is different to the *expected* period
/// that the block production apparatus provides. Your chosen consensus system will generally
/// work with this to determine a sensible block time. e.g. For Aura, it will be double this
/// period on default settings.
type MinimumPeriod: Get<Self::Moment>;
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// The minimum period between blocks. Beware that this is different to the *expected* period
/// that the block production apparatus provides. Your chosen consensus system will generally
/// work with this to determine a sensible block time. e.g. For Aura, it will be double this
/// period on default settings.
const MinimumPeriod: T::Moment = T::MinimumPeriod::get();
/// Set the current time.
///
/// This call should be invoked exactly once per block. It will panic at the finalization phase,
/// if this call hasn't been invoked by that time.
/// This call should be invoked exactly once per block. It will panic at the finalization
/// phase, if this call hasn't been invoked by that time.
///
/// The timestamp should be greater than the previous one by the amount specified by `minimum_period`.
/// The timestamp should be greater than the previous one by the amount specified by
/// `MinimumPeriod`.
///
/// The dispatch origin for this call must be `Inherent`.
fn set(origin, #[compact] now: T::Moment) {
ensure_none(origin)?;
assert!(!<Self as Store>::DidUpdate::exists(), "Timestamp must be updated only once in the block");
assert!(
Self::now().is_zero() || now >= Self::now() + <MinimumPeriod<T>>::get(),
Self::now().is_zero() || now >= Self::now() + T::MinimumPeriod::get(),
"Timestamp must increment by at least <MinimumPeriod> between sequential blocks"
);
<Self as Store>::Now::put(now.clone());
@@ -233,16 +248,6 @@ decl_module! {
<T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
}
// Manage upgrade. Remove after all networks upgraded.
// TODO: #2133
fn on_initialize() {
if let Some(period) = <BlockPeriod<T>>::take() {
if !<MinimumPeriod<T>>::exists() {
<MinimumPeriod<T>>::put(period)
}
}
}
fn on_finalize() {
assert!(<Self as Store>::DidUpdate::take(), "Timestamp must be updated once in the block");
}
@@ -254,16 +259,6 @@ decl_storage! {
/// Current time for the current block.
pub Now get(now) build(|_| 0.into()): T::Moment;
/// Old storage item provided for compatibility. Remove after all networks upgraded.
// TODO: #2133
pub BlockPeriod: Option<T::Moment>;
/// The minimum period between blocks. Beware that this is different to the *expected* period
/// that the block production apparatus provides. Your chosen consensus system will generally
/// work with this to determine a sensible block time. e.g. For Aura, it will be double this
/// period on default settings.
pub MinimumPeriod get(minimum_period) config(): T::Moment = 3.into();
/// Did the timestamp get updated in this block?
DidUpdate: bool;
}
@@ -301,7 +296,7 @@ impl<T: Trait> ProvideInherent for Module<T> {
.expect("Gets and decodes timestamp inherent data")
.saturated_into();
let next_time = cmp::max(data, Self::now() + <MinimumPeriod<T>>::get());
let next_time = cmp::max(data, Self::now() + T::MinimumPeriod::get());
Some(Call::set(next_time.into()))
}
@@ -315,7 +310,7 @@ impl<T: Trait> ProvideInherent for Module<T> {
let data = extract_inherent_data(data).map_err(|e| InherentError::Other(e))?;
let minimum = (Self::now() + <MinimumPeriod<T>>::get()).saturated_into::<u64>();
let minimum = (Self::now() + T::MinimumPeriod::get()).saturated_into::<u64>();
if t > data + MAX_TIMESTAMP_DRIFT {
Err(InherentError::Other("Timestamp too far in future to accept".into()))
} else if t < minimum {
@@ -356,19 +351,19 @@ mod tests {
type Event = ();
type BlockHashCount = BlockHashCount;
}
parameter_types! {
pub const MinimumPeriod: u64 = 5;
}
impl Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
}
type Timestamp = Module<Test>;
#[test]
fn timestamp_works() {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
GenesisConfig::<Test> {
minimum_period: 5,
}.assimilate_storage(&mut t.0, &mut t.1).unwrap();
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
with_externalities(&mut TestExternalities::new_with_children(t), || {
Timestamp::set_timestamp(42);
assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE));
@@ -379,11 +374,7 @@ mod tests {
#[test]
#[should_panic(expected = "Timestamp must be updated only once in the block")]
fn double_timestamp_should_fail() {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
GenesisConfig::<Test> {
minimum_period: 5,
}.assimilate_storage(&mut t.0, &mut t.1).unwrap();
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
with_externalities(&mut TestExternalities::new_with_children(t), || {
Timestamp::set_timestamp(42);
assert_ok!(Timestamp::dispatch(Call::set(69), Origin::NONE));
@@ -394,11 +385,7 @@ mod tests {
#[test]
#[should_panic(expected = "Timestamp must increment by at least <MinimumPeriod> between sequential blocks")]
fn block_period_minimum_enforced() {
let mut t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
GenesisConfig::<Test> {
minimum_period: 5,
}.assimilate_storage(&mut t.0, &mut t.1).unwrap();
let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
with_externalities(&mut TestExternalities::new_with_children(t), || {
Timestamp::set_timestamp(42);
let _ = Timestamp::dispatch(Call::set(46), Origin::NONE);