Unverified Commit eba3eeae authored by Gavin Wood's avatar Gavin Wood Committed by GitHub
Browse files

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
parent af0d87af
Pipeline #49061 passed with stages
in 18 minutes and 47 seconds
This diff is collapsed.
......@@ -25,9 +25,9 @@ use std::ops::Deref;
use chain_spec::ChainSpec;
use futures::Future;
use tokio::runtime::Runtime;
use service::Service as BareService;
use service::{Service as BareService, Error as ServiceError};
use std::sync::Arc;
use log::info;
use log::{info, error};
use structopt::StructOpt;
pub use service::{
......@@ -127,7 +127,7 @@ fn run_until_exit<T, C, W>(
worker: W,
) -> error::Result<()>
where
T: Deref<Target=BareService<C>> + Future<Item = (), Error = ()> + Send + 'static,
T: Deref<Target=BareService<C>> + Future<Item = (), Error = ServiceError> + Send + 'static,
C: service::Components,
BareService<C>: PolkadotService,
W: Worker,
......@@ -143,6 +143,7 @@ fn run_until_exit<T, C, W>(
let _telemetry = service.telemetry();
let work = worker.work(&*service, Arc::new(executor));
let service = service.map_err(|err| error!("Error while running Service: {}", err));
let _ = runtime.block_on(service.select(work));
exit_send.fire();
......
......@@ -59,6 +59,7 @@ wasm-builder-runner = { package = "substrate-wasm-builder-runner", version = "1.
[features]
default = ["std"]
no_std = []
only-staking = []
std = [
"bitvec/std",
"primitives/std",
......
......@@ -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;
}
......
// 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);
}
}
}
}
......@@ -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)> {
......
......@@ -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()
......
......@@ -30,7 +30,8 @@ service = { package = "substrate-service", git = "https://github.com/paritytech/
telemetry = { package = "substrate-telemetry", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
transaction_pool = { package = "substrate-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
substrate-keystore = { git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
srml_babe = { package = "srml-babe", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
srml-babe = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
srml-staking = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
im-online = { package = "srml-im-online", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
babe = { package = "substrate-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "polkadot-master" }
babe-primitives = { package = "substrate-consensus-babe-primitives", git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-master" }
......@@ -21,7 +21,7 @@ use polkadot_primitives::{AccountId, parachain::ValidatorId};
use polkadot_runtime::{
GenesisConfig, CouncilConfig, ElectionsConfig, DemocracyConfig, SystemConfig, BabeConfig,
SessionConfig, StakingConfig, BalancesConfig, Perbill, SessionKeys, TechnicalCommitteeConfig,
GrandpaConfig, SudoConfig, IndicesConfig, CuratedGrandpaConfig, StakerStatus, WASM_BINARY,
GrandpaConfig, SudoConfig, IndicesConfig, StakerStatus, WASM_BINARY,
ClaimsConfig, ImOnlineConfig, ParachainsConfig
};
use polkadot_runtime::constants::{currency::DOTS, time::*};
......@@ -30,6 +30,7 @@ use hex_literal::hex;
use babe_primitives::AuthorityId as BabeId;
use grandpa::AuthorityId as GrandpaId;
use im_online::AuthorityId as ImOnlineId;
use srml_staking::Forcing;
const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
const DEFAULT_PROTOCOL_ID: &str = "dot";
......@@ -125,6 +126,7 @@ fn staging_testnet_config_genesis() -> GenesisConfig {
minimum_validator_count: 4,
stakers: initial_authorities.iter().map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)).collect(),
invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
force_era: Forcing::ForceNone,
}),
democracy: Some(Default::default()),
collective_Instance1: Some(CouncilConfig {
......@@ -160,9 +162,6 @@ fn staging_testnet_config_genesis() -> GenesisConfig {
sudo: Some(SudoConfig {
key: endowed_accounts[0].clone(),
}),
curated_grandpa: Some(CuratedGrandpaConfig {
shuffle_period: 1024,
}),
claims: Some(ClaimsConfig {
claims: vec![],
})
......@@ -267,6 +266,7 @@ pub fn testnet_genesis(
.map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator))
.collect(),
invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(),
force_era: Forcing::NotForcing,
}),
democracy: Some(DemocracyConfig::default()),
collective_Instance1: Some(CouncilConfig {
......@@ -306,9 +306,6 @@ pub fn testnet_genesis(
sudo: Some(SudoConfig {
key: root_key,
}),
curated_grandpa: Some(CuratedGrandpaConfig {
shuffle_period: 1024,
}),
claims: Some(ClaimsConfig {
claims: vec![],
})
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment