diff --git a/polkadot/node/service/src/chain_spec.rs b/polkadot/node/service/src/chain_spec.rs index 2eee6b5f4c..5bb0af0ad9 100644 --- a/polkadot/node/service/src/chain_spec.rs +++ b/polkadot/node/service/src/chain_spec.rs @@ -975,7 +975,6 @@ fn rococo_staging_testnet_config_genesis(wasm_binary: &[u8]) -> rococo_runtime:: }, paras: rococo_runtime::ParasConfig { paras: vec![], - _phdata: Default::default(), }, hrmp: Default::default(), parachains_configuration: rococo_runtime::ParachainsConfigurationConfig { @@ -1516,7 +1515,6 @@ pub fn rococo_testnet_genesis( hrmp: Default::default(), paras: rococo_runtime::ParasConfig { paras: vec![], - _phdata: Default::default(), }, bridge_rococo_grandpa: rococo_runtime::BridgeRococoGrandpaConfig { owner: Some(root_key.clone()), diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index dfca5f5cbc..0fb3b7ea1b 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -65,7 +65,7 @@ frame_support::construct_runtime!( // Parachains Runtime Configuration: configuration::{Pallet, Call, Storage, Config}, - Paras: paras::{Pallet, Origin, Call, Storage, Event, Config}, + Paras: paras::{Pallet, Origin, Call, Storage, Event, Config}, // Para Onboarding Pallets Registrar: paras_registrar::{Pallet, Call, Storage, Event}, diff --git a/polkadot/runtime/common/src/paras_registrar.rs b/polkadot/runtime/common/src/paras_registrar.rs index 26c3ce20d2..30a97bf769 100644 --- a/polkadot/runtime/common/src/paras_registrar.rs +++ b/polkadot/runtime/common/src/paras_registrar.rs @@ -572,7 +572,7 @@ mod tests { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, ParachainsConfiguration: configuration::{Pallet, Call, Storage, Config}, - Parachains: paras::{Pallet, Origin, Call, Storage, Config, Event}, + Parachains: paras::{Pallet, Origin, Call, Storage, Config, Event}, Registrar: paras_registrar::{Pallet, Call, Storage, Event}, } ); diff --git a/polkadot/runtime/kusama/src/lib.rs b/polkadot/runtime/kusama/src/lib.rs index af1fa6fe21..ccf90b90a0 100644 --- a/polkadot/runtime/kusama/src/lib.rs +++ b/polkadot/runtime/kusama/src/lib.rs @@ -1486,7 +1486,7 @@ construct_runtime! { ParasInclusion: parachains_inclusion::{Pallet, Call, Storage, Event} = 53, ParasInherent: parachains_paras_inherent::{Pallet, Call, Storage, Inherent} = 54, ParasScheduler: parachains_scheduler::{Pallet, Call, Storage} = 55, - Paras: parachains_paras::{Pallet, Call, Storage, Event, Config} = 56, + Paras: parachains_paras::{Pallet, Call, Storage, Event, Config} = 56, ParasInitializer: parachains_initializer::{Pallet, Call, Storage} = 57, ParasDmp: parachains_dmp::{Pallet, Call, Storage} = 58, ParasUmp: parachains_ump::{Pallet, Call, Storage, Event} = 59, diff --git a/polkadot/runtime/parachains/src/hrmp.rs b/polkadot/runtime/parachains/src/hrmp.rs index a04fd465dd..e1d7d3d57c 100644 --- a/polkadot/runtime/parachains/src/hrmp.rs +++ b/polkadot/runtime/parachains/src/hrmp.rs @@ -573,8 +573,8 @@ impl Module { ); if request.confirmed { - if >::is_valid_para(channel_id.sender) - && >::is_valid_para(channel_id.recipient) + if >::is_valid_para(channel_id.sender) + && >::is_valid_para(channel_id.recipient) { ::HrmpChannels::insert( &channel_id, @@ -972,7 +972,7 @@ impl Module { ) -> DispatchResult { ensure!(origin != recipient, Error::::OpenHrmpChannelToSelf); ensure!( - >::is_valid_para(recipient), + >::is_valid_para(recipient), Error::::OpenHrmpChannelInvalidRecipient, ); @@ -1010,7 +1010,7 @@ impl Module { let egress_cnt = ::HrmpEgressChannelsIndex::decode_len(&origin).unwrap_or(0) as u32; let open_req_cnt = ::HrmpOpenChannelRequestCount::get(&origin); - let channel_num_limit = if >::is_parathread(origin) { + let channel_num_limit = if >::is_parathread(origin) { config.hrmp_max_parathread_outbound_channels } else { config.hrmp_max_parachain_outbound_channels @@ -1080,7 +1080,7 @@ impl Module { // check if by accepting this open channel request, this parachain would exceed the // number of inbound channels. let config = >::config(); - let channel_num_limit = if >::is_parathread(origin) { + let channel_num_limit = if >::is_parathread(origin) { config.hrmp_max_parathread_inbound_channels } else { config.hrmp_max_parachain_inbound_channels diff --git a/polkadot/runtime/parachains/src/inclusion.rs b/polkadot/runtime/parachains/src/inclusion.rs index 79b682a4d1..eb58f315a0 100644 --- a/polkadot/runtime/parachains/src/inclusion.rs +++ b/polkadot/runtime/parachains/src/inclusion.rs @@ -453,7 +453,7 @@ impl Module { ); let validation_code_hash = - >::validation_code_hash_at(para_id, now, None) + >::validation_code_hash_at(para_id, now, None) // A candidate for a parachain without current validation code is not scheduled. .ok_or_else(|| Error::::UnscheduledCandidate)?; ensure!( @@ -679,7 +679,7 @@ impl Module { // initial weight is config read. let mut weight = T::DbWeight::get().reads_writes(1, 0); if let Some(new_code) = commitments.new_validation_code { - weight += >::schedule_code_upgrade( + weight += >::schedule_code_upgrade( receipt.descriptor.para_id, new_code, relay_parent_number + config.validation_upgrade_delay, @@ -708,7 +708,7 @@ impl Module { Event::::CandidateIncluded(plain, commitments.head_data.clone(), core_index, backing_group) ); - weight + >::note_new_head( + weight + >::note_new_head( receipt.descriptor.para_id, commitments.head_data, relay_parent_number, @@ -869,7 +869,7 @@ impl CandidateCheckContext { // if any, the code upgrade attempt is allowed. if let Some(new_validation_code) = new_validation_code { - let valid_upgrade_attempt = >::last_code_upgrade(para_id, true) + let valid_upgrade_attempt = >::last_code_upgrade(para_id, true) .map_or(true, |last| { last <= self.relay_parent_number && self.relay_parent_number.saturating_sub(last) diff --git a/polkadot/runtime/parachains/src/initializer.rs b/polkadot/runtime/parachains/src/initializer.rs index 9eb441fd8c..12e404575b 100644 --- a/polkadot/runtime/parachains/src/initializer.rs +++ b/polkadot/runtime/parachains/src/initializer.rs @@ -131,7 +131,7 @@ decl_module! { // - HRMP let total_weight = configuration::Module::::initializer_initialize(now) + shared::Module::::initializer_initialize(now) + - paras::Module::::initializer_initialize(now) + + paras::Pallet::::initializer_initialize(now) + scheduler::Module::::initializer_initialize(now) + inclusion::Module::::initializer_initialize(now) + session_info::Module::::initializer_initialize(now) + @@ -152,7 +152,7 @@ decl_module! { session_info::Module::::initializer_finalize(); inclusion::Module::::initializer_finalize(); scheduler::Module::::initializer_finalize(); - paras::Module::::initializer_finalize(); + paras::Pallet::::initializer_finalize(); shared::Module::::initializer_finalize(); configuration::Module::::initializer_finalize(); @@ -224,7 +224,7 @@ impl Module { session_index, }; - let outgoing_paras = paras::Module::::initializer_on_new_session(¬ification); + let outgoing_paras = paras::Pallet::::initializer_on_new_session(¬ification); scheduler::Module::::initializer_on_new_session(¬ification); inclusion::Module::::initializer_on_new_session(¬ification); session_info::Module::::initializer_on_new_session(¬ification); diff --git a/polkadot/runtime/parachains/src/lib.rs b/polkadot/runtime/parachains/src/lib.rs index b486d82958..98014340f2 100644 --- a/polkadot/runtime/parachains/src/lib.rs +++ b/polkadot/runtime/parachains/src/lib.rs @@ -52,20 +52,20 @@ pub fn schedule_para_initialize( id: ParaId, genesis: paras::ParaGenesisArgs, ) -> Result<(), ()> { - >::schedule_para_initialize(id, genesis).map_err(|_| ()) + >::schedule_para_initialize(id, genesis).map_err(|_| ()) } /// Schedule a para to be cleaned up at the start of the next session. pub fn schedule_para_cleanup(id: primitives::v1::Id) -> Result<(), ()> { - >::schedule_para_cleanup(id).map_err(|_| ()) + >::schedule_para_cleanup(id).map_err(|_| ()) } /// Schedule a parathread to be upgraded to a parachain. pub fn schedule_parathread_upgrade(id: ParaId) -> Result<(), ()> { - paras::Module::::schedule_parathread_upgrade(id).map_err(|_| ()) + paras::Pallet::::schedule_parathread_upgrade(id).map_err(|_| ()) } /// Schedule a parachain to be downgraded to a parathread. pub fn schedule_parachain_downgrade(id: ParaId) -> Result<(), ()> { - paras::Module::::schedule_parachain_downgrade(id).map_err(|_| ()) + paras::Pallet::::schedule_parachain_downgrade(id).map_err(|_| ()) } diff --git a/polkadot/runtime/parachains/src/mock.rs b/polkadot/runtime/parachains/src/mock.rs index 82d17a9e0b..ccf25104ee 100644 --- a/polkadot/runtime/parachains/src/mock.rs +++ b/polkadot/runtime/parachains/src/mock.rs @@ -23,6 +23,7 @@ use sp_runtime::traits::{ }; use primitives::v1::{AuthorityDiscoveryId, Balance, BlockNumber, Header, ValidatorIndex}; use frame_support::parameter_types; +use frame_support::traits::GenesisBuild; use frame_support_test::TestRandomness; use std::cell::RefCell; use std::collections::HashMap; @@ -42,7 +43,7 @@ frame_support::construct_runtime!( { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - Paras: paras::{Pallet, Origin, Call, Storage, Event, Config}, + Paras: paras::{Pallet, Origin, Call, Storage, Event, Config}, Configuration: configuration::{Pallet, Call, Storage, Config}, Shared: shared::{Pallet, Call, Storage}, Inclusion: inclusion::{Pallet, Call, Storage, Event}, @@ -208,7 +209,7 @@ pub fn new_test_ext(state: MockGenesisConfig) -> TestExternalities { let mut t = state.system.build_storage::().unwrap(); state.configuration.assimilate_storage(&mut t).unwrap(); - state.paras.assimilate_storage(&mut t).unwrap(); + GenesisBuild::::assimilate_storage(&state.paras, &mut t).unwrap(); t.into() } @@ -217,5 +218,5 @@ pub fn new_test_ext(state: MockGenesisConfig) -> TestExternalities { pub struct MockGenesisConfig { pub system: frame_system::GenesisConfig, pub configuration: crate::configuration::GenesisConfig, - pub paras: crate::paras::GenesisConfig, + pub paras: crate::paras::GenesisConfig, } diff --git a/polkadot/runtime/parachains/src/paras.rs b/polkadot/runtime/parachains/src/paras.rs index 2d64721b83..ce407963fc 100644 --- a/polkadot/runtime/parachains/src/paras.rs +++ b/polkadot/runtime/parachains/src/paras.rs @@ -14,29 +14,23 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! The paras module is responsible for storing data on parachains and parathreads. +//! The paras pallet is responsible for storing data on parachains and parathreads. //! //! It tracks which paras are parachains, what their current head data is in //! this fork of the relay chain, what their validation code is, and what their past and upcoming //! validation code is. //! -//! A para is not considered live until it is registered and activated in this module. Activation can +//! A para is not considered live until it is registered and activated in this pallet. Activation can //! only occur at session boundaries. use sp_std::prelude::*; use sp_std::result; -#[cfg(feature = "std")] -use sp_std::marker::PhantomData; use primitives::v1::{ Id as ParaId, ValidationCode, ValidationCodeHash, HeadData, SessionIndex, ConsensusLog, }; use sp_runtime::{traits::One, DispatchResult, SaturatedConversion}; -use frame_system::ensure_root; -use frame_support::{ - decl_storage, decl_module, decl_error, decl_event, ensure, - traits::Get, - weights::Weight, -}; +use frame_system::pallet_prelude::*; +use frame_support::pallet_prelude::*; use parity_scale_codec::{Encode, Decode}; use crate::{configuration, shared, initializer::SessionChangeNotification}; use sp_core::RuntimeDebug; @@ -44,20 +38,9 @@ use sp_core::RuntimeDebug; #[cfg(feature = "std")] use serde::{Serialize, Deserialize}; -pub use crate::Origin; +pub use crate::Origin as ParachainOrigin; -pub trait Config: - frame_system::Config + - configuration::Config + - shared::Config -{ - /// The outer origin type. - type Origin: From - + From<::Origin> - + Into::Origin>>; - - type Event: From + Into<::Event>; -} +pub use pallet::*; // the two key times necessary to track for every code replacement. #[derive(Default, Encode, Decode)] @@ -279,105 +262,30 @@ pub struct ParaGenesisArgs { pub parachain: bool, } -decl_storage! { - trait Store for Module as Paras { - /// All parachains. Ordered ascending by ParaId. Parathreads are not included. - Parachains get(fn parachains): Vec; - /// The current lifecycle of a all known Para IDs. - ParaLifecycles: map hasher(twox_64_concat) ParaId => Option; - /// The head-data of every registered para. - Heads get(fn para_head): map hasher(twox_64_concat) ParaId => Option; - /// The validation code hash of every live para. - /// - /// Corresponding code can be retrieved with [`CodeByHash`]. - CurrentCodeHash: map hasher(twox_64_concat) ParaId => Option; - /// Actual past code hash, indicated by the para id as well as the block number at which it - /// became outdated. - /// - /// Corresponding code can be retrieved with [`CodeByHash`]. - PastCodeHash: map hasher(twox_64_concat) (ParaId, T::BlockNumber) => Option; - /// Past code of parachains. The parachains themselves may not be registered anymore, - /// but we also keep their code on-chain for the same amount of time as outdated code - /// to keep it available for secondary checkers. - PastCodeMeta get(fn past_code_meta): - map hasher(twox_64_concat) ParaId => ParaPastCodeMeta; - /// Which paras have past code that needs pruning and the relay-chain block at which the code was replaced. - /// Note that this is the actual height of the included block, not the expected height at which the - /// code upgrade would be applied, although they may be equal. - /// This is to ensure the entire acceptance period is covered, not an offset acceptance period starting - /// from the time at which the parachain perceives a code upgrade as having occurred. - /// Multiple entries for a single para are permitted. Ordered ascending by block number. - PastCodePruning: Vec<(ParaId, T::BlockNumber)>; - /// The block number at which the planned code change is expected for a para. - /// The change will be applied after the first parablock for this ID included which executes - /// in the context of a relay chain block with a number >= `expected_at`. - FutureCodeUpgrades get(fn future_code_upgrade_at): map hasher(twox_64_concat) ParaId => Option; - /// The actual future code hash of a para. - /// - /// Corresponding code can be retrieved with [`CodeByHash`]. - FutureCodeHash: map hasher(twox_64_concat) ParaId => Option; - /// The actions to perform during the start of a specific session index. - ActionsQueue get(fn actions_queue): map hasher(twox_64_concat) SessionIndex => Vec; - /// Upcoming paras instantiation arguments. - UpcomingParasGenesis: map hasher(twox_64_concat) ParaId => Option; - /// The number of reference on the validation code in [`CodeByHash`] storage. - CodeByHashRefs: map hasher(identity) ValidationCodeHash => u32; - /// Validation code stored by its hash. - /// - /// This storage is consistent with [`FutureCodeHash`], [`CurrentCodeHash`] and - /// [`PastCodeHash`]. - CodeByHash get(fn code_by_hash): map hasher(identity) ValidationCodeHash => Option; +#[frame_support::pallet] +pub mod pallet { + use super::*; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: + frame_system::Config + + configuration::Config + + shared::Config + { + /// The outer origin type. + type Origin: From + + From<::Origin> + + Into::Origin>>; + + type Event: From + IsType<::Event>; } - add_extra_genesis { - config(paras): Vec<(ParaId, ParaGenesisArgs)>; - config(_phdata): PhantomData; - build(build::); - } -} -#[cfg(feature = "std")] -fn build(config: &GenesisConfig) { - let mut parachains: Vec<_> = config.paras - .iter() - .filter(|(_, args)| args.parachain) - .map(|&(ref id, _)| id) - .cloned() - .collect(); - - parachains.sort(); - parachains.dedup(); - - Parachains::put(¶chains); - - for (id, genesis_args) in &config.paras { - let code_hash = genesis_args.validation_code.hash(); - >::increase_code_ref(&code_hash, &genesis_args.validation_code); - as Store>::CurrentCodeHash::insert(&id, &code_hash); - as Store>::Heads::insert(&id, &genesis_args.genesis_head); - if genesis_args.parachain { - ParaLifecycles::insert(&id, ParaLifecycle::Parachain); - } else { - ParaLifecycles::insert(&id, ParaLifecycle::Parathread); - } - } -} - -decl_error! { - pub enum Error for Module { - /// Para is not registered in our system. - NotRegistered, - /// Para cannot be onboarded because it is already tracked by our system. - CannotOnboard, - /// Para cannot be offboarded at this time. - CannotOffboard, - /// Para cannot be upgraded to a parachain. - CannotUpgrade, - /// Para cannot be downgraded to a parathread. - CannotDowngrade, - } -} - -decl_event! { + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Current code has been updated for a Para. \[para_id\] CurrentCodeUpdated(ParaId), @@ -390,18 +298,160 @@ decl_event! { /// A para has been queued to execute pending actions. \[para_id\] ActionQueued(ParaId, SessionIndex), } -} -decl_module! { - /// The parachains configuration module. - pub struct Module for enum Call where origin: ::Origin { - type Error = Error; + #[pallet::error] + pub enum Error { + /// Para is not registered in our system. + NotRegistered, + /// Para cannot be onboarded because it is already tracked by our system. + CannotOnboard, + /// Para cannot be offboarded at this time. + CannotOffboard, + /// Para cannot be upgraded to a parachain. + CannotUpgrade, + /// Para cannot be downgraded to a parathread. + CannotDowngrade, + } - fn deposit_event() = default; + /// All parachains. Ordered ascending by ParaId. Parathreads are not included. + #[pallet::storage] + #[pallet::getter(fn parachains)] + pub(super) type Parachains = StorageValue<_, Vec, ValueQuery>; + /// The current lifecycle of a all known Para IDs. + #[pallet::storage] + pub(super) type ParaLifecycles = StorageMap<_, Twox64Concat, ParaId, ParaLifecycle>; + + /// The head-data of every registered para. + #[pallet::storage] + #[pallet::getter(fn para_head)] + pub(super) type Heads = StorageMap<_, Twox64Concat, ParaId, HeadData>; + + /// The validation code hash of every live para. + /// + /// Corresponding code can be retrieved with [`CodeByHash`]. + #[pallet::storage] + pub(super) type CurrentCodeHash = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; + + /// Actual past code hash, indicated by the para id as well as the block number at which it + /// became outdated. + /// + /// Corresponding code can be retrieved with [`CodeByHash`]. + #[pallet::storage] + pub(super) type PastCodeHash = StorageMap< + _, + Twox64Concat, + (ParaId, T::BlockNumber), + ValidationCodeHash + >; + + /// Past code of parachains. The parachains themselves may not be registered anymore, + /// but we also keep their code on-chain for the same amount of time as outdated code + /// to keep it available for secondary checkers. + #[pallet::storage] + #[pallet::getter(fn past_code_meta)] + pub(super) type PastCodeMeta = StorageMap< + _, + Twox64Concat, + ParaId, + ParaPastCodeMeta, + ValueQuery + >; + + /// Which paras have past code that needs pruning and the relay-chain block at which the code was replaced. + /// Note that this is the actual height of the included block, not the expected height at which the + /// code upgrade would be applied, although they may be equal. + /// This is to ensure the entire acceptance period is covered, not an offset acceptance period starting + /// from the time at which the parachain perceives a code upgrade as having occurred. + /// Multiple entries for a single para are permitted. Ordered ascending by block number. + #[pallet::storage] + pub(super) type PastCodePruning = StorageValue<_, Vec<(ParaId, T::BlockNumber)>, ValueQuery>; + + /// The block number at which the planned code change is expected for a para. + /// The change will be applied after the first parablock for this ID included which executes + /// in the context of a relay chain block with a number >= `expected_at`. + #[pallet::storage] + #[pallet::getter(fn future_code_upgrade_at)] + pub(super) type FutureCodeUpgrades = StorageMap<_, Twox64Concat, ParaId, T::BlockNumber>; + + /// The actual future code hash of a para. + /// + /// Corresponding code can be retrieved with [`CodeByHash`]. + #[pallet::storage] + pub(super) type FutureCodeHash = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>; + + /// The actions to perform during the start of a specific session index. + #[pallet::storage] + #[pallet::getter(fn actions_queue)] + pub(super) type ActionsQueue = StorageMap<_, Twox64Concat, SessionIndex, Vec, ValueQuery>; + + /// Upcoming paras instantiation arguments. + #[pallet::storage] + pub(super) type UpcomingParasGenesis = StorageMap<_, Twox64Concat, ParaId, ParaGenesisArgs>; + + /// The number of reference on the validation code in [`CodeByHash`] storage. + #[pallet::storage] + pub(super) type CodeByHashRefs = StorageMap<_, Identity, ValidationCodeHash, u32, ValueQuery>; + + /// Validation code stored by its hash. + /// + /// This storage is consistent with [`FutureCodeHash`], [`CurrentCodeHash`] and + /// [`PastCodeHash`]. + #[pallet::storage] + #[pallet::getter(fn code_by_hash)] + pub(super) type CodeByHash = StorageMap<_, Identity, ValidationCodeHash, ValidationCode>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub paras: Vec<(ParaId, ParaGenesisArgs)>, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + GenesisConfig { + paras: Default::default(), + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + let mut parachains: Vec<_> = self.paras + .iter() + .filter(|(_, args)| args.parachain) + .map(|&(ref id, _)| id) + .cloned() + .collect(); + + parachains.sort(); + parachains.dedup(); + + Parachains::::put(¶chains); + + for (id, genesis_args) in &self.paras { + let code_hash = genesis_args.validation_code.hash(); + >::increase_code_ref(&code_hash, &genesis_args.validation_code); + as Store>::CurrentCodeHash::insert(&id, &code_hash); + as Store>::Heads::insert(&id, &genesis_args.genesis_head); + if genesis_args.parachain { + ParaLifecycles::::insert(&id, ParaLifecycle::Parachain); + } else { + ParaLifecycles::::insert(&id, ParaLifecycle::Parathread); + } + } + } + } + + #[pallet::origin] + pub type Origin = ParachainOrigin; + + #[pallet::call] + impl Pallet { /// Set the storage for the parachain validation code immediately. - #[weight = 0] - fn force_set_current_code(origin, para: ParaId, new_code: ValidationCode) { + #[pallet::weight(0)] + pub fn force_set_current_code(origin: OriginFor, para: ParaId, new_code: ValidationCode) -> DispatchResult { ensure_root(origin)?; let prior_code_hash = ::CurrentCodeHash::get(¶).unwrap_or_default(); let new_code_hash = new_code.hash(); @@ -411,57 +461,67 @@ decl_module! { let now = frame_system::Pallet::::block_number(); Self::note_past_code(para, now, now, prior_code_hash); Self::deposit_event(Event::CurrentCodeUpdated(para)); + Ok(()) } /// Set the storage for the current parachain head data immediately. - #[weight = 0] - fn force_set_current_head(origin, para: ParaId, new_head: HeadData) { + #[pallet::weight(0)] + pub fn force_set_current_head(origin: OriginFor, para: ParaId, new_head: HeadData) -> DispatchResult { ensure_root(origin)?; ::Heads::insert(¶, new_head); Self::deposit_event(Event::CurrentHeadUpdated(para)); + Ok(()) } /// Schedule a code upgrade for block `expected_at`. - #[weight = 0] - fn force_schedule_code_upgrade(origin, para: ParaId, new_code: ValidationCode, expected_at: T::BlockNumber) { + #[pallet::weight(0)] + pub fn force_schedule_code_upgrade( + origin: OriginFor, + para: ParaId, + new_code: ValidationCode, + expected_at: T::BlockNumber + ) -> DispatchResult { ensure_root(origin)?; Self::schedule_code_upgrade(para, new_code, expected_at); Self::deposit_event(Event::CodeUpgradeScheduled(para)); + Ok(()) } /// Note a new block head for para within the context of the current block. - #[weight = 0] - fn force_note_new_head(origin, para: ParaId, new_head: HeadData) { + #[pallet::weight(0)] + pub fn force_note_new_head(origin: OriginFor, para: ParaId, new_head: HeadData) -> DispatchResult { ensure_root(origin)?; let now = frame_system::Pallet::::block_number(); Self::note_new_head(para, new_head, now); Self::deposit_event(Event::NewHeadNoted(para)); + Ok(()) } /// Put a parachain directly into the next session's action queue. /// We can't queue it any sooner than this without going into the /// initializer... - #[weight = 0] - fn force_queue_action(origin, para: ParaId) { + #[pallet::weight(0)] + pub fn force_queue_action(origin: OriginFor, para: ParaId) -> DispatchResult { ensure_root(origin)?; - let next_session = shared::Module::::session_index().saturating_add(One::one()); - ActionsQueue::mutate(next_session, |v| { + let next_session = shared::Pallet::::session_index().saturating_add(One::one()); + ActionsQueue::::mutate(next_session, |v| { if let Err(i) = v.binary_search(¶) { v.insert(i, para); } }); Self::deposit_event(Event::ActionQueued(para, next_session)); + Ok(()) } } } -impl Module { - /// Called by the initializer to initialize the configuration module. +impl Pallet { + /// Called by the initializer to initialize the configuration pallet. pub(crate) fn initializer_initialize(now: T::BlockNumber) -> Weight { Self::prune_old_code(now) } - /// Called by the initializer to finalize the configuration module. + /// Called by the initializer to finalize the configuration pallet. pub(crate) fn initializer_finalize() { } /// Called by the initializer to note that a new session has started. @@ -474,8 +534,8 @@ impl Module { /// The validation code of live para. pub(crate) fn current_code(para_id: &ParaId) -> Option { - CurrentCodeHash::get(para_id).and_then(|code_hash| { - let code = CodeByHash::get(&code_hash); + CurrentCodeHash::::get(para_id).and_then(|code_hash| { + let code = CodeByHash::::get(&code_hash); if code.is_none() { log::error!( "Pallet paras storage is inconsistent, code not found for hash {}", @@ -496,13 +556,13 @@ impl Module { // // Returns the list of outgoing paras from the actions queue. fn apply_actions_queue(session: SessionIndex) -> Vec { - let actions = ActionsQueue::take(session); + let actions = ActionsQueue::::take(session); let mut parachains = ::Parachains::get(); let now = >::block_number(); let mut outgoing = Vec::new(); for para in actions { - let lifecycle = ParaLifecycles::get(¶); + let lifecycle = ParaLifecycles::::get(¶); match lifecycle { None | Some(ParaLifecycle::Parathread) | Some(ParaLifecycle::Parachain) => { /* Nothing to do... */ }, // Onboard a new parathread or parachain. @@ -512,9 +572,9 @@ impl Module { if let Err(i) = parachains.binary_search(¶) { parachains.insert(i, para); } - ParaLifecycles::insert(¶, ParaLifecycle::Parachain); + ParaLifecycles::::insert(¶, ParaLifecycle::Parachain); } else { - ParaLifecycles::insert(¶, ParaLifecycle::Parathread); + ParaLifecycles::::insert(¶, ParaLifecycle::Parathread); } let code_hash = genesis_data.validation_code.hash(); @@ -528,14 +588,14 @@ impl Module { if let Err(i) = parachains.binary_search(¶) { parachains.insert(i, para); } - ParaLifecycles::insert(¶, ParaLifecycle::Parachain); + ParaLifecycles::::insert(¶, ParaLifecycle::Parachain); }, // Downgrade a parachain to a parathread Some(ParaLifecycle::DowngradingParachain) => { if let Ok(i) = parachains.binary_search(¶) { parachains.remove(i); } - ParaLifecycles::insert(¶, ParaLifecycle::Parathread); + ParaLifecycles::::insert(¶, ParaLifecycle::Parathread); }, // Offboard a parathread or parachain from the system Some(ParaLifecycle::OffboardingParachain) | Some(ParaLifecycle::OffboardingParathread) => { @@ -545,7 +605,7 @@ impl Module { ::Heads::remove(¶); ::FutureCodeUpgrades::remove(¶); - ParaLifecycles::remove(¶); + ParaLifecycles::::remove(¶); let removed_future_code_hash = ::FutureCodeHash::take(¶); if let Some(removed_future_code_hash) = removed_future_code_hash { Self::decrease_code_ref(&removed_future_code_hash); @@ -599,7 +659,7 @@ impl Module { // looks at old code metadata, compares them to the current acceptance window, and prunes those // that are too old. fn prune_old_code(now: T::BlockNumber) -> Weight { - let config = configuration::Module::::config(); + let config = configuration::Pallet::::config(); let code_retention_period = config.code_retention_period; if now <= code_retention_period { let weight = T::DbWeight::get().reads_writes(1, 0); @@ -658,7 +718,7 @@ impl Module { /// /// Returns false if para is already registered in the system. pub fn can_schedule_para_initialize(id: &ParaId, _: &ParaGenesisArgs) -> bool { - let lifecycle = ParaLifecycles::get(id); + let lifecycle = ParaLifecycles::::get(id); lifecycle.is_none() } @@ -671,9 +731,9 @@ impl Module { // Make sure parachain isn't already in our system. ensure!(Self::can_schedule_para_initialize(&id, &genesis), Error::::CannotOnboard); - ParaLifecycles::insert(&id, ParaLifecycle::Onboarding); - UpcomingParasGenesis::insert(&id, genesis); - ActionsQueue::mutate(scheduled_session, |v| { + ParaLifecycles::::insert(&id, ParaLifecycle::Onboarding); + UpcomingParasGenesis::::insert(&id, genesis); + ActionsQueue::::mutate(scheduled_session, |v| { if let Err(i) = v.binary_search(&id) { v.insert(i, id); } @@ -688,23 +748,23 @@ impl Module { /// /// No-op if para is not registered at all. pub(crate) fn schedule_para_cleanup(id: ParaId) -> DispatchResult { - let lifecycle = ParaLifecycles::get(&id); + let lifecycle = ParaLifecycles::::get(&id); match lifecycle { // If para is not registered, nothing to do! None => { return Ok(()) }, Some(ParaLifecycle::Parathread) => { - ParaLifecycles::insert(&id, ParaLifecycle::OffboardingParathread); + ParaLifecycles::::insert(&id, ParaLifecycle::OffboardingParathread); }, Some(ParaLifecycle::Parachain) => { - ParaLifecycles::insert(&id, ParaLifecycle::OffboardingParachain); + ParaLifecycles::::insert(&id, ParaLifecycle::OffboardingParachain); }, _ => return Err(Error::::CannotOffboard)?, } let scheduled_session = Self::scheduled_session(); - ActionsQueue::mutate(scheduled_session, |v| { + ActionsQueue::::mutate(scheduled_session, |v| { if let Err(i) = v.binary_search(&id) { v.insert(i, id); } @@ -718,12 +778,12 @@ impl Module { /// Will return error if `ParaLifecycle` is not `Parathread`. pub(crate) fn schedule_parathread_upgrade(id: ParaId) -> DispatchResult { let scheduled_session = Self::scheduled_session(); - let lifecycle = ParaLifecycles::get(&id).ok_or(Error::::NotRegistered)?; + let lifecycle = ParaLifecycles::::get(&id).ok_or(Error::::NotRegistered)?; ensure!(lifecycle == ParaLifecycle::Parathread, Error::::CannotUpgrade); - ParaLifecycles::insert(&id, ParaLifecycle::UpgradingParathread); - ActionsQueue::mutate(scheduled_session, |v| { + ParaLifecycles::::insert(&id, ParaLifecycle::UpgradingParathread); + ActionsQueue::::mutate(scheduled_session, |v| { if let Err(i) = v.binary_search(&id) { v.insert(i, id); } @@ -737,12 +797,12 @@ impl Module { /// Noop if `ParaLifecycle` is not `Parachain`. pub(crate) fn schedule_parachain_downgrade(id: ParaId) -> DispatchResult { let scheduled_session = Self::scheduled_session(); - let lifecycle = ParaLifecycles::get(&id).ok_or(Error::::NotRegistered)?; + let lifecycle = ParaLifecycles::::get(&id).ok_or(Error::::NotRegistered)?; ensure!(lifecycle == ParaLifecycle::Parachain, Error::::CannotDowngrade); - ParaLifecycles::insert(&id, ParaLifecycle::DowngradingParachain); - ActionsQueue::mutate(scheduled_session, |v| { + ParaLifecycles::::insert(&id, ParaLifecycle::DowngradingParachain); + ActionsQueue::::mutate(scheduled_session, |v| { if let Err(i) = v.binary_search(&id) { v.insert(i, id); } @@ -773,7 +833,7 @@ impl Module { >::deposit_log(log.into()); let (reads, writes) = Self::increase_code_ref(&new_code_hash, &new_code); - FutureCodeHash::insert(&id, new_code_hash); + FutureCodeHash::::insert(&id, new_code_hash); T::DbWeight::get().reads_writes(1 + reads, 2 + writes) } }) @@ -787,16 +847,16 @@ impl Module { new_head: HeadData, execution_context: T::BlockNumber, ) -> Weight { - Heads::insert(&id, new_head); + Heads::::insert(&id, new_head); if let Some(expected_at) = ::FutureCodeUpgrades::get(&id) { if expected_at <= execution_context { ::FutureCodeUpgrades::remove(&id); // Both should always be `Some` in this case, since a code upgrade is scheduled. - let new_code_hash = FutureCodeHash::take(&id).unwrap_or_default(); - let prior_code_hash = CurrentCodeHash::get(&id).unwrap_or_default(); - CurrentCodeHash::insert(&id, &new_code_hash); + let new_code_hash = FutureCodeHash::::take(&id).unwrap_or_default(); + let prior_code_hash = CurrentCodeHash::::get(&id).unwrap_or_default(); + CurrentCodeHash::::insert(&id, &new_code_hash); let log = ConsensusLog::ParaUpgradeCode(id, new_code_hash); >::deposit_log(log.into()); @@ -847,11 +907,11 @@ impl Module { }; if upgrade_applied_intermediate { - FutureCodeHash::get(&id) + FutureCodeHash::::get(&id) } else { match Self::past_code_meta(&id).code_at(at) { None => None, - Some(UseCodeAt::Current) => CurrentCodeHash::get(&id), + Some(UseCodeAt::Current) => CurrentCodeHash::::get(&id), Some(UseCodeAt::ReplacedAt(replaced)) => ::PastCodeHash::get(&(id, replaced)), } } @@ -859,14 +919,14 @@ impl Module { /// Returns the current lifecycle state of the para. pub fn lifecycle(id: ParaId) -> Option { - ParaLifecycles::get(&id) + ParaLifecycles::::get(&id) } /// Returns whether the given ID refers to a valid para. /// /// Paras that are onboarding or offboarding are not included. pub fn is_valid_para(id: ParaId) -> bool { - if let Some(state) = ParaLifecycles::get(&id) { + if let Some(state) = ParaLifecycles::::get(&id) { !state.is_onboarding() && !state.is_offboarding() } else { false @@ -877,7 +937,7 @@ impl Module { /// /// Includes parachains which will downgrade to a parathread in the future. pub fn is_parachain(id: ParaId) -> bool { - if let Some(state) = ParaLifecycles::get(&id) { + if let Some(state) = ParaLifecycles::::get(&id) { state.is_parachain() } else { false @@ -888,7 +948,7 @@ impl Module { /// /// Includes parathreads which will upgrade to parachains in the future. pub fn is_parathread(id: ParaId) -> bool { - if let Some(state) = ParaLifecycles::get(&id) { + if let Some(state) = ParaLifecycles::::get(&id) { state.is_parathread() } else { false @@ -909,7 +969,7 @@ impl Module { /// Return the session index that should be used for any future scheduled changes. fn scheduled_session() -> SessionIndex { - shared::Module::::scheduled_session() + shared::Pallet::::scheduled_session() } /// Store the validation code if not already stored, and increase the number of reference. @@ -944,7 +1004,7 @@ impl Module { #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] pub fn test_on_new_session() { Self::initializer_on_new_session(&SessionChangeNotification { - session_index: shared::Module::::session_index(), + session_index: shared::Pallet::::session_index(), ..Default::default() }); } @@ -954,10 +1014,7 @@ impl Module { mod tests { use super::*; use primitives::v1::BlockNumber; - use frame_support::{ - assert_ok, - traits::{OnFinalize, OnInitialize} - }; + use frame_support::assert_ok; use crate::mock::{new_test_ext, Paras, Shared, System, MockGenesisConfig}; use crate::configuration::HostConfiguration; @@ -1613,9 +1670,9 @@ mod tests { ); // Lifecycle is tracked correctly - assert_eq!(ParaLifecycles::get(&a), Some(ParaLifecycle::Onboarding)); - assert_eq!(ParaLifecycles::get(&b), Some(ParaLifecycle::Onboarding)); - assert_eq!(ParaLifecycles::get(&c), Some(ParaLifecycle::Onboarding)); + assert_eq!(::ParaLifecycles::get(&a), Some(ParaLifecycle::Onboarding)); + assert_eq!(::ParaLifecycles::get(&b), Some(ParaLifecycle::Onboarding)); + assert_eq!(::ParaLifecycles::get(&c), Some(ParaLifecycle::Onboarding)); // run to block without session change. run_to_block(2, None); @@ -1627,9 +1684,9 @@ mod tests { ); // Lifecycle is tracked correctly - assert_eq!(ParaLifecycles::get(&a), Some(ParaLifecycle::Onboarding)); - assert_eq!(ParaLifecycles::get(&b), Some(ParaLifecycle::Onboarding)); - assert_eq!(ParaLifecycles::get(&c), Some(ParaLifecycle::Onboarding)); + assert_eq!(::ParaLifecycles::get(&a), Some(ParaLifecycle::Onboarding)); + assert_eq!(::ParaLifecycles::get(&b), Some(ParaLifecycle::Onboarding)); + assert_eq!(::ParaLifecycles::get(&c), Some(ParaLifecycle::Onboarding)); // Two sessions pass, so action queue is triggered @@ -1639,9 +1696,9 @@ mod tests { assert_eq!(::ActionsQueue::get(Paras::scheduled_session()), Vec::new()); // Lifecycle is tracked correctly - assert_eq!(ParaLifecycles::get(&a), Some(ParaLifecycle::Parathread)); - assert_eq!(ParaLifecycles::get(&b), Some(ParaLifecycle::Parachain)); - assert_eq!(ParaLifecycles::get(&c), Some(ParaLifecycle::Parachain)); + assert_eq!(::ParaLifecycles::get(&a), Some(ParaLifecycle::Parathread)); + assert_eq!(::ParaLifecycles::get(&b), Some(ParaLifecycle::Parachain)); + assert_eq!(::ParaLifecycles::get(&c), Some(ParaLifecycle::Parachain)); assert_eq!(Paras::current_code(&a), Some(vec![2].into())); assert_eq!(Paras::current_code(&b), Some(vec![1].into())); @@ -1777,18 +1834,18 @@ mod tests { Paras::increase_code_ref(&code.hash(), &code); Paras::increase_code_ref(&code.hash(), &code); - assert!(CodeByHash::contains_key(code.hash())); - assert_eq!(CodeByHashRefs::get(code.hash()), 2); + assert!(::CodeByHash::contains_key(code.hash())); + assert_eq!(::CodeByHashRefs::get(code.hash()), 2); Paras::decrease_code_ref(&code.hash()); - assert!(CodeByHash::contains_key(code.hash())); - assert_eq!(CodeByHashRefs::get(code.hash()), 1); + assert!(::CodeByHash::contains_key(code.hash())); + assert_eq!(::CodeByHashRefs::get(code.hash()), 1); Paras::decrease_code_ref(&code.hash()); - assert!(!CodeByHash::contains_key(code.hash())); - assert!(!CodeByHashRefs::contains_key(code.hash())); + assert!(!::CodeByHash::contains_key(code.hash())); + assert!(!::CodeByHashRefs::contains_key(code.hash())); }); } } diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/v1.rs b/polkadot/runtime/parachains/src/runtime_api_impl/v1.rs index c91095a775..d51e980c93 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/v1.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/v1.rs @@ -51,7 +51,7 @@ pub fn validator_groups() -> ( /// Implementation for the `availability_cores` function of the runtime API. pub fn availability_cores() -> Vec> { let cores = >::availability_cores(); - let parachains = >::parachains(); + let parachains = >::parachains(); let config = >::config(); let now = >::block_number() + One::one(); @@ -270,7 +270,7 @@ pub fn validation_code( with_assumption::( para_id, assumption, - || >::current_code(¶_id), + || >::current_code(¶_id), ) } @@ -327,5 +327,5 @@ pub fn inbound_hrmp_channels_contents( pub fn validation_code_by_hash( hash: ValidationCodeHash, ) -> Option { - >::code_by_hash(hash) + >::code_by_hash(hash) } diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index 32c7e169e7..44e03b7016 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -228,7 +228,7 @@ impl Module { let config = new_config; let mut thread_queue = ParathreadQueue::get(); - let n_parachains = >::parachains().len() as u32; + let n_parachains = >::parachains().len() as u32; let n_cores = core::cmp::max( n_parachains + config.parathread_cores, match config.max_validators_per_core { @@ -297,7 +297,7 @@ impl Module { // prune out all entries beyond retry or that no longer correspond to live parathread. thread_queue.queue.retain(|queued| { let will_keep = queued.claim.retries <= config.parathread_retries - && >::is_parathread(queued.claim.claim.0); + && >::is_parathread(queued.claim.claim.0); if !will_keep { let claim_para = queued.claim.claim.0; @@ -333,7 +333,7 @@ impl Module { /// Fails if the claim does not correspond to any live parathread. #[allow(unused)] pub fn add_parathread_claim(claim: ParathreadClaim) { - if !>::is_parathread(claim.0) { return } + if !>::is_parathread(claim.0) { return } let config = >::config(); let queue_max_size = config.parathread_cores * config.scheduling_lookahead; @@ -399,7 +399,7 @@ impl Module { } } - let parachains = >::parachains(); + let parachains = >::parachains(); let mut scheduled = Scheduled::get(); let mut parathread_queue = ParathreadQueue::get(); @@ -537,7 +537,7 @@ impl Module { match cores.get(core_index.0 as usize).and_then(|c| c.as_ref()) { None => None, Some(CoreOccupied::Parachain) => { - let parachains = >::parachains(); + let parachains = >::parachains(); Some(parachains[core_index.0 as usize]) } Some(CoreOccupied::Parathread(ref entry)) => Some(entry.claim.0), @@ -647,7 +647,7 @@ impl Module { /// For parathreads, this is based on the next item in the ParathreadQueue assigned to that /// core, and is None if there isn't one. pub(crate) fn next_up_on_available(core: CoreIndex) -> Option { - let parachains = >::parachains(); + let parachains = >::parachains(); if (core.0 as usize) < parachains.len() { Some(ScheduledCore { para_id: parachains[core.0 as usize], @@ -671,7 +671,7 @@ impl Module { /// core, or if there isn't one, the claim that is currently occupying the core, as long /// as the claim's retries would not exceed the limit. Otherwise None. pub(crate) fn next_up_on_time_out(core: CoreIndex) -> Option { - let parachains = >::parachains(); + let parachains = >::parachains(); if (core.0 as usize) < parachains.len() { Some(ScheduledCore { para_id: parachains[core.0 as usize], @@ -712,7 +712,7 @@ impl Module { ParathreadQueue::mutate(|queue| { for core_assignment in Scheduled::take() { if let AssignmentKind::Parathread(collator, retries) = core_assignment.kind { - if !>::is_parathread(core_assignment.para_id) { continue } + if !>::is_parathread(core_assignment.para_id) { continue } let entry = ParathreadEntry { claim: ParathreadClaim(core_assignment.para_id, collator), diff --git a/polkadot/runtime/parachains/src/util.rs b/polkadot/runtime/parachains/src/util.rs index 6cada4dd65..45b5781668 100644 --- a/polkadot/runtime/parachains/src/util.rs +++ b/polkadot/runtime/parachains/src/util.rs @@ -34,7 +34,7 @@ pub fn make_persisted_validation_data( let config = >::config(); Some(PersistedValidationData { - parent_head: >::para_head(¶_id)?, + parent_head: >::para_head(¶_id)?, relay_parent_number, relay_parent_storage_root, max_pov_size: config.max_pov_size, diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 7b48f2c033..9bb541ed9f 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -214,7 +214,7 @@ construct_runtime! { Inclusion: parachains_inclusion::{Pallet, Call, Storage, Event}, ParasInherent: parachains_paras_inherent::{Pallet, Call, Storage, Inherent}, Scheduler: parachains_scheduler::{Pallet, Call, Storage}, - Paras: parachains_paras::{Pallet, Call, Storage, Event, Config}, + Paras: parachains_paras::{Pallet, Call, Storage, Event, Config}, Initializer: parachains_initializer::{Pallet, Call, Storage}, Dmp: parachains_dmp::{Pallet, Call, Storage}, Ump: parachains_ump::{Pallet, Call, Storage, Event}, diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 227e1496c4..80b48258c5 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -1077,7 +1077,7 @@ construct_runtime! { ParasInclusion: parachains_inclusion::{Pallet, Call, Storage, Event} = 44, ParasInherent: parachains_paras_inherent::{Pallet, Call, Storage, Inherent} = 45, ParasScheduler: parachains_scheduler::{Pallet, Call, Storage} = 46, - Paras: parachains_paras::{Pallet, Call, Storage, Event, Config} = 47, + Paras: parachains_paras::{Pallet, Call, Storage, Event, Config} = 47, ParasInitializer: parachains_initializer::{Pallet, Call, Storage} = 48, ParasDmp: parachains_dmp::{Pallet, Call, Storage} = 49, ParasUmp: parachains_ump::{Pallet, Call, Storage, Event} = 50,