Unverified Commit ae5990c7 authored by asynchronous rob's avatar asynchronous rob Committed by GitHub
Browse files

Remove v0 parachains runtime (#1501)

* remove v0 parachains modules and switch to v1 primitives

* get tests compiling for runtime-common

* remove registrar module

* Add a dummy module

* remove runtime-parachains

* mostly remove old parachains code from polkadot-runtime

* remove slots::Trait implementation

* remove sp_std prelude import

* add a ZeroSizedTypeDifferentiator to dummy

* finish porting over polkadot runtime

* ZeroSizedTypeDifferentiator was actually unnecessary

* westend

* kusama

* test-runtime (no dummy modules)

* fix warning

* fix chain-specs

* fix test-service

* test-client

* remove dead import

* remove unused needed_extrinsics parameter

* runtimes compile

* remove rococo-v0

* remove remaining references to Rococo

* bump versions
parent 2d454326
Pipeline #103826 passed with stages
in 20 minutes and 12 seconds
......@@ -5182,7 +5182,6 @@ dependencies = [
"polkadot-runtime",
"polkadot-test-runtime-client",
"polkadot-validation",
"rococo-runtime",
"sc-authority-discovery",
"sc-block-builder",
"sc-chain-spec",
......@@ -6138,81 +6137,6 @@ dependencies = [
"librocksdb-sys",
]
[[package]]
name = "rococo-runtime"
version = "0.8.22"
dependencies = [
"bitvec",
"frame-benchmarking",
"frame-executive",
"frame-support",
"frame-system",
"frame-system-benchmarking",
"frame-system-rpc-runtime-api",
"hex-literal",
"libsecp256k1",
"log 0.3.9",
"pallet-authority-discovery",
"pallet-authorship",
"pallet-babe",
"pallet-balances",
"pallet-collective",
"pallet-democracy",
"pallet-elections-phragmen",
"pallet-finality-tracker",
"pallet-grandpa",
"pallet-identity",
"pallet-im-online",
"pallet-indices",
"pallet-membership",
"pallet-multisig",
"pallet-nicks",
"pallet-offences",
"pallet-offences-benchmarking",
"pallet-proxy",
"pallet-randomness-collective-flip",
"pallet-recovery",
"pallet-scheduler",
"pallet-session",
"pallet-session-benchmarking",
"pallet-staking",
"pallet-staking-reward-curve",
"pallet-sudo",
"pallet-timestamp",
"pallet-transaction-payment",
"pallet-transaction-payment-rpc-runtime-api",
"pallet-treasury",
"pallet-utility",
"pallet-vesting",
"parity-scale-codec",
"polkadot-parachain",
"polkadot-primitives",
"polkadot-runtime-common",
"rustc-hex",
"serde",
"serde_derive",
"serde_json",
"smallvec 1.4.1",
"sp-api",
"sp-authority-discovery",
"sp-block-builder",
"sp-consensus-babe",
"sp-core",
"sp-inherents",
"sp-io",
"sp-keyring",
"sp-offchain",
"sp-runtime",
"sp-session",
"sp-std",
"sp-transaction-pool",
"sp-trie",
"sp-version",
"static_assertions",
"substrate-wasm-builder-runner 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
"tiny-keccak 1.5.0",
]
[[package]]
name = "rococo-v1-runtime"
version = "0.8.22"
......
......@@ -37,7 +37,6 @@ members = [
"runtime/kusama",
"runtime/rococo-v1",
"runtime/westend",
"runtime/rococo",
"runtime/test-runtime",
"runtime/test-runtime/client",
"service",
......
......@@ -59,10 +59,6 @@ pub struct RunCmd {
#[structopt(long = "force-westend")]
pub force_westend: bool,
/// Force using Rococo native runtime.
#[structopt(long)]
pub force_rococo: bool,
/// Enable the authority discovery module on validator or sentry nodes.
///
/// When enabled:
......
......@@ -47,7 +47,7 @@ impl SubstrateCli for Cli {
fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> {
let id = if id == "" {
let n = get_exec_name().unwrap_or_default();
["polkadot", "kusama", "westend", "rococo"].iter()
["polkadot", "kusama", "westend"].iter()
.cloned()
.find(|&chain| n.starts_with(chain))
.unwrap_or("polkadot")
......@@ -65,9 +65,6 @@ impl SubstrateCli for Cli {
"westend-dev" => Box::new(service::chain_spec::westend_development_config()?),
"westend-local" => Box::new(service::chain_spec::westend_local_testnet_config()?),
"westend-staging" => Box::new(service::chain_spec::westend_staging_testnet_config()?),
"rococo-staging" => Box::new(service::chain_spec::rococo_staging_testnet_config()?),
"rococo-local" => Box::new(service::chain_spec::rococo_local_testnet_config()?),
"rococo" => Box::new(service::chain_spec::rococo_config()?),
path => {
let path = std::path::PathBuf::from(path);
......@@ -77,9 +74,7 @@ impl SubstrateCli for Cli {
// When `force_*` is given or the file name starts with the name of one of the known chains,
// we use the chain spec for the specific chain.
if self.run.force_rococo || starts_with("rococo") {
Box::new(service::RococoChainSpec::from_json_file(path)?)
} else if self.run.force_kusama || starts_with("kusama") {
if self.run.force_kusama || starts_with("kusama") {
Box::new(service::KusamaChainSpec::from_json_file(path)?)
} else if self.run.force_westend || starts_with("westend") {
Box::new(service::WestendChainSpec::from_json_file(path)?)
......@@ -95,8 +90,6 @@ impl SubstrateCli for Cli {
&service::kusama_runtime::VERSION
} else if spec.is_westend() {
&service::westend_runtime::VERSION
} else if spec.is_rococo() {
&service::rococo_runtime::VERSION
} else {
&service::polkadot_runtime::VERSION
}
......
......@@ -29,7 +29,7 @@ fn prepare_good_block() -> (TestClient, Hash, u64, PeerId, IncomingBlock<Block>)
let mut client = polkadot_test_runtime_client::new();
let mut builder = client.new_block(Default::default()).unwrap();
let extrinsics = polkadot_test_runtime_client::needed_extrinsics(vec![], 0);
let extrinsics = polkadot_test_runtime_client::needed_extrinsics(0);
for extrinsic in &extrinsics {
builder.push(extrinsic.clone()).unwrap();
......
......@@ -180,13 +180,6 @@ fn polkadot_staging_testnet_config_genesis(wasm_binary: &[u8]) -> polkadot::Gene
pallet_authority_discovery: Some(polkadot::AuthorityDiscoveryConfig {
keys: vec![],
}),
parachains: Some(polkadot::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(polkadot::RegistrarConfig {
parachains: vec![],
_phdata: Default::default(),
}),
claims: Some(polkadot::ClaimsConfig {
claims: vec![],
vesting: vec![],
......@@ -321,13 +314,6 @@ fn westend_staging_testnet_config_genesis(wasm_binary: &[u8]) -> westend::Genesi
pallet_authority_discovery: Some(westend::AuthorityDiscoveryConfig {
keys: vec![],
}),
parachains: Some(westend::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(westend::RegistrarConfig {
parachains: vec![],
_phdata: Default::default(),
}),
pallet_vesting: Some(westend::VestingConfig {
vesting: vec![],
}),
......@@ -472,13 +458,6 @@ fn kusama_staging_testnet_config_genesis(wasm_binary: &[u8]) -> kusama::GenesisC
pallet_authority_discovery: Some(kusama::AuthorityDiscoveryConfig {
keys: vec![],
}),
parachains: Some(kusama::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(kusama::RegistrarConfig {
parachains: vec![],
_phdata: Default::default(),
}),
claims: Some(kusama::ClaimsConfig {
claims: vec![],
vesting: vec![],
......@@ -657,13 +636,6 @@ pub fn polkadot_testnet_genesis(
pallet_authority_discovery: Some(polkadot::AuthorityDiscoveryConfig {
keys: vec![],
}),
parachains: Some(polkadot::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(polkadot::RegistrarConfig{
parachains: vec![],
_phdata: Default::default(),
}),
claims: Some(polkadot::ClaimsConfig {
claims: vec![],
vesting: vec![],
......@@ -732,13 +704,6 @@ pub fn kusama_testnet_genesis(
pallet_authority_discovery: Some(kusama::AuthorityDiscoveryConfig {
keys: vec![],
}),
parachains: Some(kusama::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(kusama::RegistrarConfig{
parachains: vec![],
_phdata: Default::default(),
}),
claims: Some(kusama::ClaimsConfig {
claims: vec![],
vesting: vec![],
......@@ -796,13 +761,6 @@ pub fn westend_testnet_genesis(
pallet_authority_discovery: Some(westend::AuthorityDiscoveryConfig {
keys: vec![],
}),
parachains: Some(westend::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(westend::RegistrarConfig{
parachains: vec![],
_phdata: Default::default(),
}),
pallet_vesting: Some(westend::VestingConfig {
vesting: vec![],
}),
......
......@@ -256,7 +256,7 @@ mod tests {
for i in 0..n {
let mut builder = client.new_block(Default::default()).unwrap();
for extrinsic in polkadot_test_runtime_client::needed_extrinsics(vec![], base + i) {
for extrinsic in polkadot_test_runtime_client::needed_extrinsics(base + i) {
builder.push(extrinsic).unwrap()
}
......
......@@ -155,13 +155,6 @@ fn polkadot_testnet_genesis(
pallet_babe: Some(Default::default()),
pallet_grandpa: Some(Default::default()),
pallet_authority_discovery: Some(polkadot::AuthorityDiscoveryConfig { keys: vec![] }),
parachains: Some(polkadot::ParachainsConfig {
authorities: vec![],
}),
registrar: Some(polkadot::RegistrarConfig {
parachains: vec![],
_phdata: Default::default(),
}),
claims: Some(polkadot::ClaimsConfig {
claims: vec![],
vesting: vec![],
......
......@@ -25,9 +25,11 @@ use futures::future::Future;
use polkadot_primitives::v0::{
Block, Hash, CollatorId, Id as ParaId,
};
use polkadot_runtime_common::{parachains, registrar, BlockHashCount};
use polkadot_service::{new_full, FullNodeHandles, AbstractClient, ClientHandle, ExecuteWithClient};
use polkadot_test_runtime::{RestrictFunctionality, Runtime, SignedExtra, SignedPayload, VERSION};
use polkadot_runtime_common::BlockHashCount;
use polkadot_service::{
new_full, FullNodeHandles, AbstractClient, ClientHandle, ExecuteWithClient,
};
use polkadot_test_runtime::{Runtime, SignedExtra, SignedPayload, VERSION};
use sc_chain_spec::ChainSpec;
use sc_client_api::{execution_extensions::ExecutionStrategies, BlockchainEvents};
use sc_executor::native_executor_instance;
......@@ -258,7 +260,6 @@ where
.unwrap_or(2) as u64;
let tip = 0;
let extra: SignedExtra = (
RestrictFunctionality,
frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(),
......@@ -266,14 +267,11 @@ where
frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
registrar::LimitParathreadCommits::<Runtime>::new(),
parachains::ValidateDoubleVoteReports::<Runtime>::new(),
);
let raw_payload = SignedPayload::from_raw(
function.clone(),
extra.clone(),
(
(),
VERSION.spec_version,
VERSION.transaction_version,
genesis_block,
......@@ -281,8 +279,6 @@ where
(),
(),
(),
(),
(),
),
);
let signature = raw_payload.using_encoded(|e| caller.sign(e));
......
......@@ -705,6 +705,25 @@ sp_api::decl_runtime_apis! {
}
}
/// Custom validity errors used in Polkadot while validating transactions.
#[repr(u8)]
pub enum ValidityError {
/// The Ethereum signature is invalid.
InvalidEthereumSignature = 0,
/// The signer has no claim.
SignerHasNoClaim = 1,
/// No permission to execute the call.
NoPermission = 2,
/// An invalid statement was made for a claim.
InvalidStatement = 3,
}
impl From<ValidityError> for u8 {
fn from(err: ValidityError) -> Self {
err as u8
}
}
#[cfg(test)]
mod tests {
use super::*;
......
// Copyright 2019-2020 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 tracking all attestations that fell on a given candidate receipt.
//!
//! In the future, it is planned that this module will handle dispute resolution
//! as well.
use sp_std::prelude::*;
use codec::{Encode, Decode};
use frame_support::{
decl_storage, decl_module, decl_error, ensure,
dispatch::DispatchResult,
traits::Get,
weights::DispatchClass,
};
use primitives::v0::{Hash, AttestedCandidate, AbridgedCandidateReceipt, Id as ParaId};
use sp_runtime::RuntimeDebug;
use sp_staking::SessionIndex;
use inherents::{ProvideInherent, InherentData, MakeFatalError, InherentIdentifier};
use frame_system::ensure_none;
/// Parachain blocks included in a recent relay-chain block.
#[derive(Encode, Decode)]
pub struct IncludedBlocks<T: Trait> {
/// The actual relay chain block number where blocks were included.
pub actual_number: T::BlockNumber,
/// The session index at this block.
pub session: SessionIndex,
/// The randomness seed at this block.
pub random_seed: [u8; 32],
/// All parachain IDs active at this block.
pub active_parachains: Vec<ParaId>,
/// Hashes of the parachain candidates included at this block.
pub para_blocks: Vec<Hash>,
}
/// Attestations kept over time on a parachain block.
#[derive(Encode, Decode)]
pub struct BlockAttestations<T: Trait> {
receipt: AbridgedCandidateReceipt,
valid: Vec<T::AccountId>, // stash account ID of voter.
invalid: Vec<T::AccountId>, // stash account ID of voter.
}
/// Additional attestations on a parachain block, after it was included.
#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug)]
pub struct MoreAttestations;
/// Something which processes rewards for received attestations.
pub trait RewardAttestation {
/// Reward immediate attestations on parachain blocks. The argument is an iterable of
/// validator indices of the attesting validators.
fn reward_immediate(validator_indices: impl IntoIterator<Item=u32>);
}
impl RewardAttestation for () {
fn reward_immediate(validator_indices: impl IntoIterator<Item=u32>) {
// ensure side-effecting iterators do work.
for _ in validator_indices {}
}
}
impl<T: pallet_staking::Trait> RewardAttestation for pallet_staking::Module<T> {
fn reward_immediate(validator_indices: impl IntoIterator<Item=u32>) {
use pallet_staking::SessionInterface;
// The number of points to reward for a validity statement.
// https://research.web3.foundation/en/latest/polkadot/Token%20Economics/#payment-details
const STAKING_REWARD_POINTS: u32 = 20;
let validators = T::SessionInterface::validators();
let validator_rewards = validator_indices.into_iter()
.filter_map(|i| validators.get(i as usize).cloned())
.map(|v| (v, STAKING_REWARD_POINTS));
Self::reward_by_ids(validator_rewards);
}
}
pub trait Trait: pallet_session::Trait {
/// How many blocks ago we're willing to accept attestations for.
type AttestationPeriod: Get<Self::BlockNumber>;
/// Get a list of the validators' underlying identities.
type ValidatorIdentities: Get<Vec<Self::AccountId>>;
/// Hook for rewarding validators upon attesting.
type RewardAttestation: RewardAttestation;
}
decl_storage! {
trait Store for Module<T: Trait> as Attestations {
/// A mapping from modular block number (n % AttestationPeriod)
/// to session index and the list of candidate hashes.
pub RecentParaBlocks: map hasher(twox_64_concat) T::BlockNumber => Option<IncludedBlocks<T>>;
/// Attestations on a recent parachain block.
pub ParaBlockAttestations:
double_map hasher(twox_64_concat) T::BlockNumber, hasher(identity) Hash
=> Option<BlockAttestations<T>>;
// Did we already have more attestations included in this block?
DidUpdate: bool;
}
}
decl_error! {
pub enum Error for Module<T: Trait> {
/// More attestations can be added only once in a block.
TooManyAttestations,
}
}
decl_module! {
/// Parachain-attestations module.
pub struct Module<T: Trait> for enum Call where origin: <T as frame_system::Trait>::Origin {
type Error = Error<T>;
/// Provide candidate receipts for parachains, in ascending order by id.
#[weight = (0, DispatchClass::Mandatory)]
fn more_attestations(origin, _more: MoreAttestations) -> DispatchResult {
ensure_none(origin)?;
ensure!(!DidUpdate::exists(), Error::<T>::TooManyAttestations);
DidUpdate::put(true);
Ok(())
}
fn on_finalize(_n: T::BlockNumber) {
DidUpdate::kill();
}
}
}
impl<T: Trait> Module<T> {
/// Update recent candidates to contain the already-checked parachain candidates.
pub(crate) fn note_included(heads: &[AttestedCandidate], para_blocks: IncludedBlocks<T>) {
let attestation_period = T::AttestationPeriod::get();
let mod_num = para_blocks.actual_number % attestation_period;
// clear old entry that was in this place.
if let Some(old_entry) = <RecentParaBlocks<T>>::take(&mod_num) {
<ParaBlockAttestations<T>>::remove_prefix(&old_entry.actual_number);
}
let validators = T::ValidatorIdentities::get();
// make new entry.
for (head, hash) in heads.iter().zip(&para_blocks.para_blocks) {
let mut valid = Vec::new();
let invalid = Vec::new();
{
let attesting_indices = head.validator_indices
.iter()
.enumerate()
.filter(|(_, bit)| **bit)
.inspect(|&(auth_index, _)| {
if let Some(stash_id) = validators.get(auth_index) {
valid.push(stash_id.clone());
}
})
.map(|(i, _)| i as u32);
T::RewardAttestation::reward_immediate(attesting_indices);
}
let summary = BlockAttestations {
receipt: head.candidate().clone(),
valid,
invalid,
};
<ParaBlockAttestations<T>>::insert(&para_blocks.actual_number, hash, &summary);
}
<RecentParaBlocks<T>>::insert(&mod_num, &para_blocks);
}
}
/// An identifier for inherent data that provides after-the-fact attestations
/// on already included parachain blocks.
pub const MORE_ATTESTATIONS_IDENTIFIER: InherentIdentifier = *b"par-atts";
pub type InherentType = MoreAttestations;
impl<T: Trait> ProvideInherent for Module<T> {
type Call = Call<T>;
type Error = MakeFatalError<inherents::Error>;
const INHERENT_IDENTIFIER: InherentIdentifier = MORE_ATTESTATIONS_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
data.get_data::<InherentType>(&MORE_ATTESTATIONS_IDENTIFIER)
.ok()
.and_then(|x| x.map(Call::more_attestations))
}
}
......@@ -35,7 +35,7 @@ use sp_runtime::{
TransactionSource, TransactionValidityError,
},
};
use primitives::v0::ValidityError;
use primitives::v1::ValidityError;
type CurrencyOf<T> = <<T as Trait>::VestingSchedule as VestingSchedule<<T as frame_system::Trait>::AccountId>>::Currency;
type BalanceOf<T> = <CurrencyOf<T> as Currency<<T as frame_system::Trait>::AccountId>>::Balance;
......
......@@ -79,7 +79,7 @@ use sp_runtime::{ModuleId,
use crate::slots;
use codec::{Encode, Decode};
use sp_std::vec::Vec;
use primitives::v0::{Id as ParaId, HeadData};
use primitives::v1::{Id as ParaId, HeadData};
pub type BalanceOf<T> =
<<T as slots::Trait>::Currency as Currency<<T as frame_system::Trait>::AccountId>>::Balance;
......@@ -568,14 +568,14 @@ mod tests {
};
use frame_support::traits::{Contains, ContainsLengthBound};
use sp_core::H256;
use primitives::v0::{Info as ParaInfo, Id as ParaId, Scheduling, ValidationCode};
use primitives::v1::{Id as ParaId, ValidationCode};
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
use sp_runtime::{
Perbill, Permill, Percent, testing::Header, DispatchResult,
traits::{BlakeTwo256, IdentityLookup},
};
use crate::registrar::Registrar;
use crate::slots::Registrar;
impl_outer_origin! {
pub enum Origin for Test {}
......@@ -699,13 +699,9 @@ mod tests {
code_size <= MAX_CODE_SIZE
}
fn para_info(_id: ParaId) -> Option<ParaInfo> {
Some(ParaInfo { scheduling: Scheduling::Always })
}
fn register_para(
id: ParaId,
_info: ParaInfo,
_parachain: bool,
code: ValidationCode,
initial_head_data: HeadData,
) -> DispatchResult {
......
// Copyright 2020 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Substrate is free software: you can redistribute it and/or modify
// Polkadot is free software: you can redistribute it and/or modify