Prepare stuff for Kusama (i.e. disable most things) (#362)

* Prepare stuff for Kusama (i.e. disable most things)

* Fix service (hopefully)

* Remove curated grandpa.

* Block unwanted transactions a cleaner way.

* Add feature for restricting tx types

* Cleanups

* Make blocktime 1/10th of normal

* Fix ordering in construct_runtime

* Restore original timing

* Revert name change
This commit is contained in:
Gavin Wood
2019-08-13 20:36:27 +02:00
committed by GitHub
parent 10fc88f6b1
commit 7bd46ffbcb
9 changed files with 151 additions and 197 deletions
+1 -2
View File
@@ -29,7 +29,6 @@ pub mod currency {
pub mod time {
use primitives::{Moment, BlockNumber};
pub const MILLISECS_PER_BLOCK: Moment = 6000;
pub const SECS_PER_BLOCK: Moment = MILLISECS_PER_BLOCK / 1000;
pub const SLOT_DURATION: Moment = 1650;
@@ -41,7 +40,7 @@ pub mod time {
};
// These time units are defined in number of blocks.
pub const MINUTES: BlockNumber = 60 / (SECS_PER_BLOCK as BlockNumber);
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
}
-103
View File
@@ -1,103 +0,0 @@
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! A module for manually curated GRANDPA set.
use {grandpa, system};
use codec::Decode;
use sr_primitives::traits::{Hash as HashT, BlakeTwo256, Zero};
use sr_primitives::weights::SimpleDispatchInfo;
use rstd::prelude::*;
use srml_support::{decl_storage, decl_module};
pub trait Trait: grandpa::Trait {}
decl_storage! {
trait Store for Module<T: Trait> as CuratedGrandpa {
/// How often to shuffle the GRANDPA sets.
///
/// 0 means never.
pub ShufflePeriod get(shuffle_period) config(shuffle_period): T::BlockNumber;
}
}
decl_module! {
/// curated GRANDPA set.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// Changes the GRANDPA voter set.
#[weight = SimpleDispatchInfo::FixedOperational(10_000)]
fn set_voters(origin, voters: Vec<(grandpa::AuthorityId, u64)>) {
system::ensure_root(origin)?;
grandpa::Module::<T>::schedule_change(voters, T::BlockNumber::zero(), None)?;
}
fn on_finalize(block_number: T::BlockNumber) {
let shuffle_period = Self::shuffle_period();
// every so often shuffle the voters and issue a change.
if shuffle_period.is_zero() { return }
if (block_number % shuffle_period).is_zero() {
let mut voters = grandpa::Module::<T>::grandpa_authorities();
let voter_count = voters.len();
if voter_count == 0 { return }
let mut seed = {
let phrase = b"grandpa_shuffling";
let seed = system::Module::<T>::random(&phrase[..]);
let seed_len = seed.as_ref().len();
let needed_bytes = voter_count * 4;
// hash only the needed bits of the random seed.
// if earlier bits are influencable, they will not factor into
// the seed used here.
let seed_off = if needed_bytes >= seed_len {
0
} else {
seed_len - needed_bytes
};
BlakeTwo256::hash(&seed.as_ref()[seed_off..])
};
for i in 0..(voter_count - 1) {
// 4 bytes of entropy used per cycle, 32 bytes entropy per hash
let offset = (i * 4 % 32) as usize;
// number of roles remaining to select from.
let remaining = rstd::cmp::max(1, (voter_count - i) as usize);
// 8 32-bit ints per 256-bit seed.
let voter_index = u32::decode(&mut &seed[offset..offset + 4]).expect("using 4 bytes for a 32-bit quantity") as usize % remaining;
if offset == 28 {
// into the last 4 bytes - rehash to gather new entropy
seed = BlakeTwo256::hash(seed.as_ref());
}
// exchange last item with randomly chosen first.
voters.swap(remaining - 1, voter_index);
}
// finalization order is undefined, so grandpa's on_finalize might
// have already been called. calling it again is OK though.
let _ = grandpa::Module::<T>::schedule_change(voters, T::BlockNumber::zero(), None);
grandpa::Module::<T>::on_finalize(block_number);
}
}
}
}
+76 -20
View File
@@ -22,12 +22,12 @@
mod attestations;
mod claims;
mod curated_grandpa;
mod parachains;
mod slot_range;
mod slots;
use rstd::prelude::*;
use codec::{Encode, Decode};
use substrate_primitives::u32_trait::{_1, _2, _3, _4};
use primitives::{
AccountId, AccountIndex, Balance, BlockNumber, Hash, Nonce, Signature, Moment,
@@ -38,9 +38,10 @@ use client::{
runtime_api as client_api, impl_runtime_apis,
};
use sr_primitives::{
ApplyResult, generic, transaction_validity::TransactionValidity, create_runtime_str, key_types,
traits::{BlakeTwo256, Block as BlockT, DigestFor, StaticLookup},
impl_opaque_keys, weights::Weight,
ApplyResult, generic, transaction_validity::{ValidTransaction, TransactionValidity},
impl_opaque_keys, weights::{Weight, DispatchInfo}, create_runtime_str, key_types, traits::{
BlakeTwo256, Block as BlockT, DigestFor, StaticLookup, DispatchError, SignedExtension,
},
};
use version::RuntimeVersion;
use grandpa::{AuthorityId as GrandpaId, fg_primitives::{self, ScheduledChange}};
@@ -77,7 +78,9 @@ use constants::{time::*, currency::*};
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
/// Runtime version.
/*
// KUSAMA: Polkadot version identifier; may be uncommented for Polkadot mainnet.
/// Runtime version (Polkadot).
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("polkadot"),
impl_name: create_runtime_str!("parity-polkadot"),
@@ -86,6 +89,18 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
};
*/
// KUSAMA: Kusama version identifier; may be removed for Polkadot mainnet.
/// Runtime version (Kusama).
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("kusama"),
impl_name: create_runtime_str!("parity-kusama"),
authoring_version: 1,
spec_version: 1000,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
};
/// Native version.
#[cfg(any(feature = "std", test))]
@@ -96,6 +111,29 @@ pub fn native_version() -> NativeVersion {
}
}
/// Avoid processing transactions that are anything except staking and claims.
///
/// RELEASE: This is only relevant for the initial PoA run-in period and may be removed
/// from the release runtime.
#[derive(Default, Encode, Decode, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct OnlyStakingAndClaims;
impl SignedExtension for OnlyStakingAndClaims {
type AccountId = AccountId;
type Call = Call;
type AdditionalSigned = ();
type Pre = ();
fn additional_signed(&self) -> rstd::result::Result<(), &'static str> { Ok(()) }
fn validate(&self, _: &Self::AccountId, call: &Self::Call, _: DispatchInfo, _: usize)
-> Result<ValidTransaction, DispatchError>
{
match call {
Call::Staking(_) | Call::Claims(_) => Ok(Default::default()),
_ => Err(DispatchError::NoPermission),
}
}
}
type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
parameter_types! {
@@ -191,7 +229,7 @@ impl authorship::Trait for Runtime {
type FindAuthor = session::FindAccountFromAuthorIndex<Self, Babe>;
type UncleGenerations = UncleGenerations;
type FilterUncle = ();
type EventHandler = ();
type EventHandler = Staking;
}
parameter_types! {
@@ -412,10 +450,11 @@ impl slots::Trait for Runtime {
type EndingPeriod = EndingPeriod;
}
impl curated_grandpa::Trait for Runtime { }
parameter_types!{
// KUSAMA: for mainnet this should be removed.
pub const Prefix: &'static [u8] = b"Pay KSMs to the Kusama account:";
// KUSAMA: for mainnet this should be uncommented.
//pub const Prefix: &'static [u8] = b"Pay DOTs to the Polkadot account:";
}
impl claims::Trait for Runtime {
@@ -435,29 +474,44 @@ construct_runtime!(
NodeBlock = primitives::Block,
UncheckedExtrinsic = UncheckedExtrinsic
{
// Basic stuff; balances is uncallable initially.
System: system::{Module, Call, Storage, Config, Event},
Timestamp: timestamp::{Module, Call, Storage, Inherent},
// Must be before session.
Babe: babe::{Module, Call, Storage, Config, Inherent(Timestamp)},
Authorship: authorship::{Module, Call, Storage},
Timestamp: timestamp::{Module, Call, Storage, Inherent},
Indices: indices,
Balances: balances,
Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},
// Consensus support.
Authorship: authorship::{Module, Call, Storage},
Staking: staking::{default, OfflineWorker},
Session: session::{Module, Call, Storage, Event, Config<T>},
FinalityTracker: finality_tracker::{Module, Call, Inherent},
Grandpa: grandpa::{Module, Call, Storage, Config, Event},
ImOnline: im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config<T>},
// Governance stuff; uncallable initially.
Democracy: democracy::{Module, Call, Storage, Config, Event<T>},
Council: collective::<Instance1>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>},
TechnicalCommittee: collective::<Instance2>::{Module, Call, Storage, Origin<T>, Event<T>, Config<T>},
Elections: elections::{Module, Call, Storage, Event<T>, Config<T>},
TechnicalMembership: membership::<Instance1>::{Module, Call, Storage, Event<T>, Config<T>},
FinalityTracker: finality_tracker::{Module, Call, Inherent},
Grandpa: grandpa::{Module, Call, Storage, Config, Event},
CuratedGrandpa: curated_grandpa::{Module, Call, Config<T>, Storage},
Treasury: treasury::{Module, Call, Storage, Event<T>},
// Claims. Usable initially.
Claims: claims::{Module, Call, Storage, Event<T>, Config<T>, ValidateUnsigned},
// Sudo. Usable initially.
// RELEASE: remove this for release build.
Sudo: sudo,
// Parachains stuff; slots are disabled (no auctions initially). The rest are safe as they
// have no public dispatchables.
Parachains: parachains::{Module, Call, Storage, Config<T>, Inherent, Origin},
Attestations: attestations::{Module, Call, Storage},
Slots: slots::{Module, Call, Storage, Event<T>},
Claims: claims::{Module, Call, Storage, Event<T>, Config<T>, ValidateUnsigned},
Sudo: sudo,
ImOnline: im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config<T>},
}
);
@@ -473,11 +527,13 @@ pub type SignedBlock = generic::SignedBlock<Block>;
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
// RELEASE: remove this for release build.
OnlyStakingAndClaims,
system::CheckGenesis<Runtime>,
system::CheckEra<Runtime>,
system::CheckNonce<Runtime>,
system::CheckWeight<Runtime>,
balances::TakeFees<Runtime>
balances::TakeFees<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
@@ -569,10 +625,10 @@ impl_runtime_apis! {
Grandpa::pending_change(digest)
}
fn grandpa_forced_change(_digest: &DigestFor<Block>)
fn grandpa_forced_change(digest: &DigestFor<Block>)
-> Option<(BlockNumber, ScheduledChange<BlockNumber>)>
{
None // disable forced changes.
Grandpa::forced_change(digest)
}
fn grandpa_authorities() -> Vec<(GrandpaId, u64)> {
+1
View File
@@ -1095,6 +1095,7 @@ mod tests {
offline_slash: Perbill::from_percent(5),
offline_slash_grace: 0,
invulnerables: vec![],
.. Default::default()
}.assimilate_storage(&mut t).unwrap();
t.into()