Make a test crate to make the runtime-test usable (#1258)

Fixes #833
This commit is contained in:
Cecile Tonglet
2020-07-09 15:12:52 +02:00
committed by GitHub
parent 8696788747
commit a4fa71ed17
16 changed files with 1161 additions and 357 deletions
+7
View File
@@ -14,9 +14,11 @@ serde = { version = "1.0.102", default-features = false }
serde_derive = { version = "1.0.102", optional = true }
smallvec = "1.4.1"
authority-discovery-primitives = { package = "sp-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
babe-primitives = { package = "sp-consensus-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
inherents = { package = "sp-inherents", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
offchain-primitives = { package = "sp-offchain", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
rstd = { package = "sp-std", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
@@ -27,6 +29,7 @@ version = { package = "sp-version", git = "https://github.com/paritytech/substra
tx-pool-api = { package = "sp-transaction-pool", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
block-builder-api = { package = "sp-block-builder", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
authority-discovery = { package = "pallet-authority-discovery", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
authorship = { package = "pallet-authorship", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
babe = { package = "pallet-babe", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
balances = { package = "pallet-balances", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
@@ -46,6 +49,7 @@ pallet-staking-reward-curve = { git = "https://github.com/paritytech/substrate",
system = { package = "frame-system", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
system_rpc_runtime_api = { package = "frame-system-rpc-runtime-api", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
timestamp = { package = "pallet-timestamp", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
sudo = { package = "pallet-sudo", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
vesting = { package = "pallet-vesting", git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
runtime-common = { package = "polkadot-runtime-common", path = "../common", default-features = false }
@@ -68,6 +72,8 @@ default = ["std"]
no_std = []
only-staking = []
std = [
"authority-discovery-primitives/std",
"authority-discovery/std",
"bitvec/std",
"primitives/std",
"rustc-hex/std",
@@ -78,6 +84,7 @@ std = [
"sp-api/std",
"tx-pool-api/std",
"block-builder-api/std",
"offchain-primitives/std",
"rstd/std",
"sp-io/std",
"frame-support/std",
+15 -10
View File
@@ -6,19 +6,24 @@ edition = "2018"
license = "GPL-3.0"
[dependencies]
futures = "0.3.1"
codec = { package = "parity-scale-codec", version = "1.0.0" }
# Polkadot dependencies
polkadot-primitives = { path = "../../../primitives" }
polkadot-runtime-common = { path = "../../common" }
polkadot-test-runtime = { path = ".." }
polkadot-test-service = { path = "../../../node/test-service" }
# Substrate dependencies
pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-block-builder = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-consensus = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-light = { git = "https://github.com/paritytech/substrate", branch = "master" }
sc-service = { git = "https://github.com/paritytech/substrate", branch = "master", features = ["test-helpers"], default-features = false }
substrate-test-client = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
polkadot-test-runtime = { path = ".." }
polkadot-runtime-common = { path = "../../common" }
polkadot-primitives = { path = "../../../primitives" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-blockchain = { git = "https://github.com/paritytech/substrate", branch = "master" }
codec = { package = "parity-scale-codec", version = "1.0.0" }
sc-client-api = { git = "https://github.com/paritytech/substrate", branch = "master" }
pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "master" }
futures = "0.3.1"
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" }
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master" }
substrate-test-client = { git = "https://github.com/paritytech/substrate", branch = "master" }
+27 -20
View File
@@ -20,13 +20,18 @@
use std::sync::Arc;
use std::collections::BTreeMap;
use std::convert::TryFrom;
pub use substrate_test_client::*;
pub use polkadot_test_runtime as runtime;
use sp_core::{sr25519, ChangesTrieConfiguration, map, twox_128};
use sp_core::{ChangesTrieConfiguration, map, twox_128};
use sp_core::storage::{ChildInfo, Storage, StorageChild};
use polkadot_test_runtime::genesismap::GenesisConfig;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Hash as HashT, HashFor};
use polkadot_test_runtime::GenesisConfig;
use polkadot_test_service::polkadot_local_testnet_genesis;
use sp_runtime::{
traits::{Block as BlockT, Header as HeaderT, Hash as HashT, HashFor},
BuildStorage,
};
use sc_consensus::LongestChain;
use sc_client_api::light::{RemoteCallRequest, RemoteBodyRequest};
use sc_service::client::{
@@ -89,16 +94,10 @@ pub struct GenesisParameters {
impl GenesisParameters {
fn genesis_config(&self) -> GenesisConfig {
GenesisConfig::new(
self.changes_trie_config.clone(),
vec![
sr25519::Public::from(Sr25519Keyring::Alice).into(),
sr25519::Public::from(Sr25519Keyring::Bob).into(),
sr25519::Public::from(Sr25519Keyring::Charlie).into(),
],
1000,
self.extra_storage.clone(),
)
let config = polkadot_local_testnet_genesis(self.changes_trie_config.clone());
config.assimilate_storage(&mut self.extra_storage.clone()).expect("Adding `system::GensisConfig` to the genesis");
config
}
}
@@ -112,7 +111,7 @@ impl substrate_test_client::GenesisInit for GenesisParameters {
fn genesis_storage(&self) -> Storage {
use codec::Encode;
let mut storage = self.genesis_config().genesis_map();
let mut storage = self.genesis_config().build_storage().unwrap();
let child_roots = storage.children_default.iter().map(|(sk, child_content)| {
let state_root = <<<runtime::Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
@@ -323,20 +322,28 @@ pub fn new_native_executor() -> sc_executor::NativeExecutor<LocalExecutor> {
}
/// Extrinsics that must be included in each block.
pub fn needed_extrinsics(heads: Vec<polkadot_primitives::parachain::AttestedCandidate>) -> Vec<polkadot_test_runtime::UncheckedExtrinsic> {
///
/// The index of the block must be provided to calculate a valid timestamp for the block. The value starts at 0 and
/// should be incremented by one for every block produced.
pub fn needed_extrinsics(
heads: Vec<polkadot_primitives::parachain::AttestedCandidate>,
i: u64,
) -> Vec<polkadot_test_runtime::UncheckedExtrinsic> {
use polkadot_runtime_common::parachains;
let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
.expect("now always later than unix epoch; qed")
.as_millis() + (i * polkadot_test_runtime::constants::time::SLOT_DURATION / 2) as u128;
vec![
polkadot_test_runtime::UncheckedExtrinsic {
function: polkadot_test_runtime::Call::Parachains(parachains::Call::set_heads(heads)),
signature: None,
},
polkadot_test_runtime::UncheckedExtrinsic {
function: polkadot_test_runtime::Call::Timestamp(pallet_timestamp::Call::set({
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)
.expect("now always later than unix epoch; qed")
.as_millis() as u64
})),
function: polkadot_test_runtime::Call::Timestamp(pallet_timestamp::Call::set(
u64::try_from(timestamp).expect("unexpected big timestamp"),
)),
signature: None,
}
]
@@ -1,75 +0,0 @@
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate 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.
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
//! Tool for creating the genesis block.
use std::collections::BTreeMap;
use super::{AccountId, WASM_BINARY, constants::currency};
use sp_core::ChangesTrieConfiguration;
use sp_core::storage::Storage;
use sp_runtime::BuildStorage;
/// Configuration of a general Substrate test genesis block.
pub struct GenesisConfig {
changes_trie_config: Option<ChangesTrieConfiguration>,
balances: Vec<(AccountId, u128)>,
/// Additional storage key pairs that will be added to the genesis map.
extra_storage: Storage,
}
impl GenesisConfig {
pub fn new(
changes_trie_config: Option<ChangesTrieConfiguration>,
endowed_accounts: Vec<AccountId>,
balance: u128,
extra_storage: Storage,
) -> Self {
GenesisConfig {
changes_trie_config,
balances: endowed_accounts.into_iter().map(|a| (a, balance * currency::DOLLARS)).collect(),
extra_storage,
}
}
pub fn genesis_map(&self) -> Storage {
// Assimilate the system genesis config.
let mut storage = Storage {
top: BTreeMap::new(),
children_default: self.extra_storage.children_default.clone(),
};
let config = crate::GenesisConfig {
system: Some(system::GenesisConfig {
changes_trie_config: self.changes_trie_config.clone(),
code: WASM_BINARY.to_vec(),
}),
babe: None,
indices: None,
balances: Some(balances::GenesisConfig {
balances: self.balances.clone()
}),
staking: None,
session: None,
grandpa: None,
claims: None,
parachains: None,
registrar: None,
vesting: None,
};
config.assimilate_storage(&mut storage).expect("Adding `system::GensisConfig` to the genesis");
storage
}
}
+53 -30
View File
@@ -55,6 +55,7 @@ use frame_support::{
traits::{KeyOwnerProofSystem, Randomness},
weights::Weight,
};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo;
use session::historical as session_historical;
@@ -69,8 +70,6 @@ pub use parachains::Call as ParachainsCall;
/// Constant values used within the runtime.
pub mod constants;
#[cfg(feature = "std")]
pub mod genesismap;
use constants::{time::*, currency::*, fee::*};
// Make the WASM binary available.
@@ -166,8 +165,8 @@ impl<C> system::offchain::SendTransactionTypes<C> for Runtime where
}
parameter_types! {
pub const EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;
pub const ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
pub storage EpochDuration: u64 = EPOCH_DURATION_IN_BLOCKS as u64;
pub storage ExpectedBlockTime: Moment = MILLISECS_PER_BLOCK;
}
impl babe::Trait for Runtime {
@@ -193,7 +192,7 @@ impl babe::Trait for Runtime {
}
parameter_types! {
pub const IndexDeposit: Balance = 1 * DOLLARS;
pub storage IndexDeposit: Balance = 1 * DOLLARS;
}
impl indices::Trait for Runtime {
@@ -205,7 +204,7 @@ impl indices::Trait for Runtime {
}
parameter_types! {
pub const ExistentialDeposit: Balance = 1 * CENTS;
pub storage ExistentialDeposit: Balance = 1 * CENTS;
}
impl balances::Trait for Runtime {
@@ -218,7 +217,7 @@ impl balances::Trait for Runtime {
}
parameter_types! {
pub const TransactionByteFee: Balance = 10 * MILLICENTS;
pub storage TransactionByteFee: Balance = 10 * MILLICENTS;
}
impl transaction_payment::Trait for Runtime {
@@ -230,7 +229,8 @@ impl transaction_payment::Trait for Runtime {
}
parameter_types! {
pub const MinimumPeriod: u64 = 0;
pub storage SlotDuration: u64 = SLOT_DURATION;
pub storage MinimumPeriod: u64 = SlotDuration::get() / 2;
}
impl timestamp::Trait for Runtime {
type Moment = u64;
@@ -240,7 +240,7 @@ impl timestamp::Trait for Runtime {
}
parameter_types! {
pub const UncleGenerations: u32 = 0;
pub storage UncleGenerations: u32 = 0;
}
// TODO: substrate#2986 implement this properly
@@ -252,8 +252,8 @@ impl authorship::Trait for Runtime {
}
parameter_types! {
pub const Period: BlockNumber = 10 * MINUTES;
pub const Offset: BlockNumber = 0;
pub storage Period: BlockNumber = 10 * MINUTES;
pub storage Offset: BlockNumber = 0;
}
impl_opaque_keys! {
@@ -265,7 +265,7 @@ impl_opaque_keys! {
}
parameter_types! {
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
pub storage DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17);
}
impl session::Trait for Runtime {
@@ -299,16 +299,16 @@ pallet_staking_reward_curve::build! {
parameter_types! {
// Six sessions in an era (6 hours).
pub const SessionsPerEra: SessionIndex = 6;
pub storage SessionsPerEra: SessionIndex = 6;
// 28 eras for unbonding (7 days).
pub const BondingDuration: staking::EraIndex = 28;
pub storage BondingDuration: staking::EraIndex = 28;
// 28 eras in which slashes can be cancelled (7 days).
pub const SlashDeferDuration: staking::EraIndex = 28;
pub storage SlashDeferDuration: staking::EraIndex = 28;
pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
pub const MaxNominatorRewardedPerValidator: u32 = 64;
pub const ElectionLookahead: BlockNumber = 0;
pub const StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2;
pub const MaxIterations: u32 = 10;
pub storage MaxNominatorRewardedPerValidator: u32 = 64;
pub storage ElectionLookahead: BlockNumber = 0;
pub storage StakingUnsignedPriority: TransactionPriority = TransactionPriority::max_value() / 2;
pub storage MaxIterations: u32 = 10;
pub MinSolutionScoreBump: Perbill = Perbill::from_rational_approximation(5u32, 10_000);
}
@@ -366,12 +366,12 @@ impl attestations::Trait for Runtime {
}
parameter_types! {
pub const MaxCodeSize: u32 = 10 * 1024 * 1024; // 10 MB
pub const MaxHeadDataSize: u32 = 20 * 1024; // 20 KB
pub storage MaxCodeSize: u32 = 10 * 1024 * 1024; // 10 MB
pub storage MaxHeadDataSize: u32 = 20 * 1024; // 20 KB
pub const ValidationUpgradeFrequency: BlockNumber = 2;
pub const ValidationUpgradeDelay: BlockNumber = 1;
pub const SlashPeriod: BlockNumber = 1 * MINUTES;
pub storage ValidationUpgradeFrequency: BlockNumber = 2;
pub storage ValidationUpgradeDelay: BlockNumber = 1;
pub storage SlashPeriod: BlockNumber = 1 * MINUTES;
}
impl parachains::Trait for Runtime {
@@ -447,7 +447,7 @@ impl system::offchain::SigningTypes for Runtime {
}
parameter_types! {
pub OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * MaximumBlockWeight::get();
pub storage OffencesWeightSoftLimit: Weight = Perbill::from_percent(60) * MaximumBlockWeight::get();
}
impl offences::Trait for Runtime {
@@ -458,10 +458,12 @@ impl offences::Trait for Runtime {
type WeightInfo = ();
}
impl authority_discovery::Trait for Runtime {}
parameter_types! {
pub const ParathreadDeposit: Balance = 5 * DOLLARS;
pub storage ParathreadDeposit: Balance = 5 * DOLLARS;
pub const QueueSize: usize = 2;
pub const MaxRetries: u32 = 3;
pub storage MaxRetries: u32 = 3;
}
impl registrar::Trait for Runtime {
@@ -475,8 +477,8 @@ impl registrar::Trait for Runtime {
}
parameter_types! {
pub const LeasePeriod: BlockNumber = 100_000;
pub const EndingPeriod: BlockNumber = 1000;
pub storage LeasePeriod: BlockNumber = 100_000;
pub storage EndingPeriod: BlockNumber = 1000;
}
impl slots::Trait for Runtime {
@@ -500,7 +502,7 @@ impl claims::Trait for Runtime {
}
parameter_types! {
pub const MinVestedTransfer: Balance = 100 * DOLLARS;
pub storage MinVestedTransfer: Balance = 100 * DOLLARS;
}
impl vesting::Trait for Runtime {
@@ -511,6 +513,11 @@ impl vesting::Trait for Runtime {
type WeightInfo = ();
}
impl sudo::Trait for Runtime {
type Event = Event;
type Call = Call;
}
construct_runtime! {
pub enum Runtime where
Block = Block,
@@ -536,6 +543,7 @@ construct_runtime! {
Historical: session_historical::{Module},
Session: session::{Module, Call, Storage, Event, Config<T>},
Grandpa: grandpa::{Module, Call, Storage, Config, Event},
AuthorityDiscovery: authority_discovery::{Module, Call, Config},
// Claims. Usable initially.
Claims: claims::{Module, Call, Storage, Event<T>, Config<T>, ValidateUnsigned},
@@ -549,6 +557,9 @@ construct_runtime! {
// Vesting. Usable initially, but removed once all vesting is finished.
Vesting: vesting::{Module, Call, Storage, Event<T>, Config<T>},
// Sudo. Last module.
Sudo: sudo::{Module, Call, Storage, Config<T>, Event<T>},
}
}
@@ -642,6 +653,18 @@ sp_api::impl_runtime_apis! {
}
}
impl offchain_primitives::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl authority_discovery_primitives::AuthorityDiscoveryApi<Block> for Runtime {
fn authorities() -> Vec<AuthorityDiscoveryId> {
Vec::new()
}
}
impl parachain::ParachainHost<Block> for Runtime {
fn validators() -> Vec<parachain::ValidatorId> {
Parachains::authorities()