diff --git a/frame/babe/src/mock.rs b/frame/babe/src/mock.rs index 40ee782e721d6..04832d492310e 100644 --- a/frame/babe/src/mock.rs +++ b/frame/babe/src/mock.rs @@ -28,7 +28,7 @@ use sp_runtime::{ use frame_system::InitKind; use frame_support::{ parameter_types, - traits::{KeyOwnerProofSystem, OnInitialize}, + traits::{KeyOwnerProofSystem, OnInitialize, GenesisBuild}, }; use sp_io; use sp_core::{H256, U256, crypto::{IsWrappedBy, KeyTypeId, Pair}}; diff --git a/frame/grandpa/src/lib.rs b/frame/grandpa/src/lib.rs index 6c78b2c8d01f4..eba9379faab51 100644 --- a/frame/grandpa/src/lib.rs +++ b/frame/grandpa/src/lib.rs @@ -598,7 +598,7 @@ impl OneSessionHandler for Module // if we didn't issue a change, we update the mapping to note that the current // set corresponds to the latest equivalent session (i.e. now). - let session_index = >::current_index(); + let session_index = >::current_index(); SetIdSession::insert(current_set_id, &session_index); } diff --git a/frame/grandpa/src/mock.rs b/frame/grandpa/src/mock.rs index e26020b600348..b78658509fb80 100644 --- a/frame/grandpa/src/mock.rs +++ b/frame/grandpa/src/mock.rs @@ -24,7 +24,7 @@ use ::grandpa as finality_grandpa; use codec::Encode; use frame_support::{ parameter_types, - traits::{KeyOwnerProofSystem, OnFinalize, OnInitialize}, + traits::{KeyOwnerProofSystem, OnFinalize, OnInitialize, GenesisBuild}, }; use pallet_staking::EraIndex; use sp_core::{crypto::KeyTypeId, H256}; diff --git a/frame/session/README.md b/frame/session/README.md index e1f8b7f8e0238..fcc9c1cf0f98c 100644 --- a/frame/session/README.md +++ b/frame/session/README.md @@ -72,7 +72,7 @@ The [Staking pallet](https://docs.rs/pallet-staking/latest/pallet_staking/) uses use pallet_session as session; fn validators() -> Vec<::ValidatorId> { - >::validators() + >::validators() } ``` diff --git a/frame/session/benchmarking/src/lib.rs b/frame/session/benchmarking/src/lib.rs index fff3717607f8f..49cd519bd2930 100644 --- a/frame/session/benchmarking/src/lib.rs +++ b/frame/session/benchmarking/src/lib.rs @@ -32,7 +32,7 @@ use frame_support::{ traits::{KeyOwnerProofSystem, OnInitialize}, }; use frame_system::RawOrigin; -use pallet_session::{historical::Module as Historical, Module as Session, *}; +use pallet_session::{historical::Pallet as Historical, Pallet as Session, *}; use pallet_staking::{ benchmarking::create_validator_with_nominators, testing_utils::create_validators, RewardDestination, @@ -41,12 +41,12 @@ use sp_runtime::traits::{One, StaticLookup}; const MAX_VALIDATORS: u32 = 1000; -pub struct Pallet(pallet_session::Module); +pub struct Pallet(pallet_session::Pallet); pub trait Config: pallet_session::Config + pallet_session::historical::Config + pallet_staking::Config {} impl OnInitialize for Pallet { fn on_initialize(n: T::BlockNumber) -> frame_support::weights::Weight { - pallet_session::Module::::on_initialize(n) + pallet_session::Pallet::::on_initialize(n) } } diff --git a/frame/session/src/historical/mod.rs b/frame/session/src/historical/mod.rs index 8902ebe551f6c..d499a91fec04f 100644 --- a/frame/session/src/historical/mod.rs +++ b/frame/session/src/historical/mod.rs @@ -32,55 +32,71 @@ use sp_runtime::KeyTypeId; use sp_runtime::traits::{Convert, OpaqueKeys}; use sp_session::{MembershipProof, ValidatorCount}; use frame_support::{ - decl_module, decl_storage, Parameter, print, + Parameter, print, traits::{ValidatorSet, ValidatorSetWithIdentification}, }; use sp_trie::{MemoryDB, Trie, TrieMut, Recorder, EMPTY_PREFIX}; use sp_trie::trie_types::{TrieDBMut, TrieDB}; -use super::{SessionIndex, Module as SessionModule}; +use super::{SessionIndex, Pallet as SessionModule, pallet as pallet_session}; +pub use pallet::*; mod shared; pub mod offchain; pub mod onchain; -/// Config necessary for the historical module. -pub trait Config: super::Config { - /// Full identification of the validator. - type FullIdentification: Parameter; - - /// A conversion from validator ID to full identification. - /// - /// This should contain any references to economic actors associated with the - /// validator, since they may be outdated by the time this is queried from a - /// historical trie. - /// - /// It must return the identification for the current session index. - type FullIdentificationOf: Convert>; -} - -decl_storage! { - trait Store for Module as Session { - /// Mapping from historical session indices to session-data root hash and validator count. - HistoricalSessions get(fn historical_root): - map hasher(twox_64_concat) SessionIndex => Option<(T::Hash, ValidatorCount)>; - /// The range of historical sessions we store. [first, last) - StoredRange: Option<(SessionIndex, SessionIndex)>; - /// Deprecated. - CachedObsolete: - map hasher(twox_64_concat) SessionIndex - => Option>; +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); + + /// Config necessary for the historical module. + #[pallet::config] + pub trait Config: pallet_session::Config + frame_system::Config { + /// Full identification of the validator. + type FullIdentification: Parameter; + + /// A conversion from validator ID to full identification. + /// + /// This should contain any references to economic actors associated with the + /// validator, since they may be outdated by the time this is queried from a + /// historical trie. + /// + /// It must return the identification for the current session index. + type FullIdentificationOf: Convert>; } -} -decl_module! { - pub struct Module for enum Call where origin: T::Origin {} + /// Mapping from historical session indices to session-data root hash and validator count. + #[pallet::storage] + #[pallet::getter(fn historical_root)] + pub type HistoricalSessions = + StorageMap<_, Twox64Concat, SessionIndex, (T::Hash, ValidatorCount)>; + + /// The range of historical sessions we store. [first, last) + #[pallet::storage] + pub type StoredRange = StorageValue<_, (SessionIndex, SessionIndex)>; + + #[pallet::storage] + pub type CachedObsolete = + StorageMap<_, Twox64Concat, SessionIndex, (T::ValidatorId, T::FullIdentification)>; + + #[pallet::hooks] + /// Deprecated. + impl Hooks> for Pallet {} + + #[pallet::call] + impl Pallet {} } -impl Module { +impl Pallet { /// Prune historical stored session roots up to (but not including) /// `up_to`. pub fn prune_up_to(up_to: SessionIndex) { - ::StoredRange::mutate(|range| { + <::StoredRange>::mutate(|range| { let (start, end) = match *range { Some(range) => range, None => return, // nothing to prune. @@ -104,20 +120,20 @@ impl Module { } } -impl ValidatorSet for Module { +impl ValidatorSet for Pallet { type ValidatorId = T::ValidatorId; type ValidatorIdOf = T::ValidatorIdOf; fn session_index() -> sp_staking::SessionIndex { - super::Module::::current_index() + super::Pallet::::current_index() } fn validators() -> Vec { - super::Module::::validators() + super::Pallet::::validators() } } -impl ValidatorSetWithIdentification for Module { +impl ValidatorSetWithIdentification for Pallet { type Identification = T::FullIdentification; type IdentificationOf = T::FullIdentificationOf; } @@ -141,7 +157,7 @@ impl crate::SessionManager for NoteHistoricalRoot< { fn new_session(new_index: SessionIndex) -> Option> { - StoredRange::mutate(|range| { + StoredRange::::mutate(|range| { range.get_or_insert_with(|| (new_index, new_index)).1 = new_index + 1; }); @@ -180,7 +196,8 @@ impl crate::SessionManager for NoteHistoricalRoot< } /// A tuple of the validator's ID and their full identification. -pub type IdentificationTuple = (::ValidatorId, ::FullIdentification); +pub type IdentificationTuple = (::ValidatorId, + ::FullIdentification); /// A trie instance for checking and generating proofs. pub struct ProvingTrie { @@ -281,7 +298,7 @@ impl ProvingTrie { } impl> frame_support::traits::KeyOwnerProofSystem<(KeyTypeId, D)> - for Module + for Pallet { type Proof = MembershipProof; type IdentificationTuple = IdentificationTuple; @@ -346,10 +363,10 @@ pub(crate) mod tests { NEXT_VALIDATORS, force_new_session, set_next_validators, Test, System, Session, }; - use frame_support::traits::{KeyOwnerProofSystem, OnInitialize}; + use frame_support::traits::{KeyOwnerProofSystem, OnInitialize, GenesisBuild}; use frame_support::BasicExternalities; - type Historical = Module; + type Historical = Pallet; pub(crate) fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default().build_storage::().unwrap(); @@ -412,27 +429,27 @@ pub(crate) mod tests { } - assert_eq!(StoredRange::get(), Some((0, 100))); + assert_eq!(StoredRange::::get(), Some((0, 100))); for i in 0..100 { assert!(Historical::historical_root(i).is_some()) } Historical::prune_up_to(10); - assert_eq!(StoredRange::get(), Some((10, 100))); + assert_eq!(StoredRange::::get(), Some((10, 100))); Historical::prune_up_to(9); - assert_eq!(StoredRange::get(), Some((10, 100))); + assert_eq!(StoredRange::::get(), Some((10, 100))); for i in 10..100 { assert!(Historical::historical_root(i).is_some()) } Historical::prune_up_to(99); - assert_eq!(StoredRange::get(), Some((99, 100))); + assert_eq!(StoredRange::::get(), Some((99, 100))); Historical::prune_up_to(100); - assert_eq!(StoredRange::get(), None); + assert_eq!(StoredRange::::get(), None); for i in 99..199u64 { set_next_validators(vec![i]); @@ -443,14 +460,14 @@ pub(crate) mod tests { } - assert_eq!(StoredRange::get(), Some((100, 200))); + assert_eq!(StoredRange::::get(), Some((100, 200))); for i in 100..200 { assert!(Historical::historical_root(i).is_some()) } Historical::prune_up_to(9999); - assert_eq!(StoredRange::get(), None); + assert_eq!(StoredRange::::get(), None); for i in 100..200 { assert!(Historical::historical_root(i).is_none()) diff --git a/frame/session/src/historical/offchain.rs b/frame/session/src/historical/offchain.rs index f675d878c1e28..030026e33dc9b 100644 --- a/frame/session/src/historical/offchain.rs +++ b/frame/session/src/historical/offchain.rs @@ -137,13 +137,13 @@ pub fn keep_newest(n_to_keep: usize) { #[cfg(test)] mod tests { - use super::super::{onchain, Module}; + use super::super::{onchain, Pallet}; use super::*; use crate::mock::{ force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS, }; use codec::Encode; - use frame_support::traits::{KeyOwnerProofSystem, OnInitialize}; + use frame_support::traits::{KeyOwnerProofSystem, OnInitialize, GenesisBuild}; use sp_core::crypto::key_types::DUMMY; use sp_core::offchain::{ testing::TestOffchainExt, @@ -155,7 +155,7 @@ mod tests { use sp_runtime::testing::UintAuthorityId; use frame_support::BasicExternalities; - type Historical = Module; + type Historical = Pallet; pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() diff --git a/frame/session/src/lib.rs b/frame/session/src/lib.rs index cbe70598a91b3..a0f6e0c32c558 100644 --- a/frame/session/src/lib.rs +++ b/frame/session/src/lib.rs @@ -15,14 +15,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! # Session Module +//! # Session Pallet //! -//! The Session module allows validators to manage their session keys, provides a function for +//! The Session Pallet allows validators to manage their session keys, provides a function for //! changing the session length, and handles session rotation. //! //! - [`Config`] //! - [`Call`] -//! - [`Module`] +//! - [`Pallet`] //! //! ## Overview //! @@ -95,12 +95,12 @@ //! use pallet_session as session; //! //! fn validators() -> Vec<::ValidatorId> { -//! >::validators() +//! >::validators() //! } //! # fn main(){} //! ``` //! -//! ## Related Modules +//! ## Related Pallets //! //! - [Staking](../pallet_staking/index.html) @@ -122,7 +122,7 @@ use sp_runtime::{ }; use sp_staking::SessionIndex; use frame_support::{ - ensure, decl_module, decl_event, decl_storage, decl_error, ConsensusEngineId, Parameter, + ensure, ConsensusEngineId, Parameter, traits::{ Get, FindAuthor, ValidatorRegistration, EstimateNextSessionRotation, EstimateNextNewSession, OneSessionHandler, ValidatorSet, @@ -132,6 +132,7 @@ use frame_support::{ }; use frame_system::ensure_signed; pub use weights::WeightInfo; +pub use pallet::*; /// Decides whether the session should be ended. pub trait ShouldEndSession { @@ -228,7 +229,7 @@ pub trait SessionManager { /// /// Even if the validator-set is the same as before, if any underlying economic conditions have /// changed (i.e. stake-weights), the new validator set must be returned. This is necessary for - /// consensus engines making use of the session module to issue a validator-set change so + /// consensus engines making use of the session Pallet to issue a validator-set change so /// misbehavior can be provably associated with the new economic conditions as opposed to the /// old. The returned validator set, if any, will not be applied until `new_index`. `new_index` /// is strictly greater than from previous call. @@ -270,7 +271,7 @@ pub trait SessionHandler { fn on_genesis_session(validators: &[(ValidatorId, Ks)]); /// Session set has changed; act appropriately. Note that this can be called - /// before initialization of your module. + /// before initialization of your Pallet. /// /// `changed` is true whenever any of the session keys or underlying economic /// identities or weightings behind those keys has changed. @@ -350,86 +351,123 @@ impl SessionHandler for TestSessionHandler { fn on_disabled(_: usize) {} } -impl ValidatorRegistration for Module { +impl ValidatorRegistration for Pallet { fn is_registered(id: &T::ValidatorId) -> bool { Self::load_keys(id).is_some() } } -pub trait Config: frame_system::Config { - /// The overarching event type. - type Event: From + Into<::Event>; +#[frame_support::pallet] +pub mod pallet { + use super::*; + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; - /// A stable ID for a validator. - type ValidatorId: Member + Parameter; + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); - /// A conversion from account ID to validator ID. - /// - /// Its cost must be at most one storage read. - type ValidatorIdOf: Convert>; + /// The pallet's config trait. + #[pallet::config] + pub trait Config: frame_system::Config { + /// The overarching event type. + type Event: From + IsType<::Event>; - /// Indicator for when to end the session. - type ShouldEndSession: ShouldEndSession; + /// A stable ID for a validator. + type ValidatorId: Member + Parameter + MaybeSerializeDeserialize; - /// Something that can predict the next session rotation. This should typically come from the - /// same logical unit that provides [`ShouldEndSession`], yet, it gives a best effort estimate. - /// It is helpful to implement [`EstimateNextNewSession`]. - type NextSessionRotation: EstimateNextSessionRotation; + /// A conversion from account ID to validator ID. + /// + /// Its cost must be at most one storage read. + type ValidatorIdOf: Convert>; - /// Handler for managing new session. - type SessionManager: SessionManager; + /// Indicator for when to end the session. + type ShouldEndSession: ShouldEndSession; - /// Handler when a session has changed. - type SessionHandler: SessionHandler; + /// Something that can predict the next session rotation. This should typically come from the + /// same logical unit that provides [`ShouldEndSession`], yet, it gives a best effort estimate. + /// It is helpful to implement [`EstimateNextNewSession`]. + type NextSessionRotation: EstimateNextSessionRotation; - /// The keys. - type Keys: OpaqueKeys + Member + Parameter + Default; + /// Handler for managing new session. + type SessionManager: SessionManager; - /// The fraction of validators set that is safe to be disabled. - /// - /// After the threshold is reached `disabled` method starts to return true, - /// which in combination with `pallet_staking` forces a new era. - type DisabledValidatorsThreshold: Get; + /// Handler when a session has changed. + type SessionHandler: SessionHandler; - /// Weight information for extrinsics in this pallet. - type WeightInfo: WeightInfo; -} + /// The keys. + type Keys: OpaqueKeys + Member + Parameter + Default + MaybeSerializeDeserialize; -decl_storage! { - trait Store for Module as Session { - /// The current set of validators. - Validators get(fn validators): Vec; + /// The fraction of validators set that is safe to be disabled. + /// + /// After the threshold is reached `disabled` method starts to return true, + /// which in combination with `pallet_staking` forces a new era. + type DisabledValidatorsThreshold: Get; - /// Current index of the session. - CurrentIndex get(fn current_index): SessionIndex; + /// Weight information for extrinsics in this pallet. + type WeightInfo: WeightInfo; + } - /// True if the underlying economic identities or weighting behind the validators - /// has changed in the queued validator set. - QueuedChanged: bool; + /// The current set of validators. + #[pallet::storage] + #[pallet::getter(fn validators)] + pub type Validators = StorageValue<_, Vec, ValueQuery>; - /// The queued keys for the next session. When the next session begins, these keys - /// will be used to determine the validator's session keys. - QueuedKeys get(fn queued_keys): Vec<(T::ValidatorId, T::Keys)>; + /// Current index of the session. + #[pallet::storage] + #[pallet::getter(fn current_index)] + pub type CurrentIndex = StorageValue<_, SessionIndex, ValueQuery>; - /// Indices of disabled validators. - /// - /// The set is cleared when `on_session_ending` returns a new set of identities. - DisabledValidators get(fn disabled_validators): Vec; + /// True if the underlying economic identities or weighting behind the validators + /// has changed in the queued validator set. + #[pallet::storage] + pub type QueuedChanged = StorageValue<_, bool, ValueQuery>; - /// The next session keys for a validator. - NextKeys: map hasher(twox_64_concat) T::ValidatorId => Option; + /// The queued keys for the next session. When the next session begins, these keys + /// will be used to determine the validator's session keys. + #[pallet::storage] + #[pallet::getter(fn queued_keys)] + pub type QueuedKeys = StorageValue<_, Vec<(T::ValidatorId, T::Keys)>, ValueQuery>; - /// The owner of a key. The key is the `KeyTypeId` + the encoded key. - KeyOwner: map hasher(twox_64_concat) (KeyTypeId, Vec) => Option; + /// Indices of disabled validators. + /// + /// The set is cleared when `on_session_ending` returns a new set of identities. + #[pallet::storage] + #[pallet::getter(fn disabled_validators)] + pub type DisabledValidators = StorageValue<_, Vec, ValueQuery>; + + /// The next session keys for a validator. + #[pallet::storage] + pub type NextKeys = StorageMap<_, Twox64Concat, T::ValidatorId, T::Keys>; + + /// The owner of a key. The key is the `KeyTypeId` + the encoded key. + #[pallet::storage] + pub type KeyOwner = + StorageMap<_, Twox64Concat, (KeyTypeId, Vec), T::ValidatorId>; + + #[pallet::genesis_config] + pub struct GenesisConfig { + pub keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>, } - add_extra_genesis { - config(keys): Vec<(T::AccountId, T::ValidatorId, T::Keys)>; - build(|config: &GenesisConfig| { + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { keys: Vec::new() } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { if T::SessionHandler::KEY_TYPE_IDS.len() != T::Keys::key_ids().len() { panic!("Number of keys in session handler and session keys does not match"); } - T::SessionHandler::KEY_TYPE_IDS.iter().zip(T::Keys::key_ids()).enumerate() + T::SessionHandler::KEY_TYPE_IDS + .iter() + .zip(T::Keys::key_ids()) + .enumerate() .for_each(|(i, (sk, kk))| { if sk != kk { panic!( @@ -439,8 +477,8 @@ decl_storage! { } }); - for (account, val, keys) in config.keys.iter().cloned() { - >::inner_set_keys(&val, keys) + for (account, val, keys) in self.keys.iter().cloned() { + >::inner_set_keys(&val, keys) .expect("genesis config must not contain duplicates; qed"); assert!( frame_system::Pallet::::inc_consumers(&account).is_ok(), @@ -449,25 +487,29 @@ decl_storage! { ); } - let initial_validators_0 = T::SessionManager::new_session(0) - .unwrap_or_else(|| { - frame_support::print("No initial validator provided by `SessionManager`, use \ - session config keys to generate initial validator set."); - config.keys.iter().map(|x| x.1.clone()).collect() - }); - assert!(!initial_validators_0.is_empty(), "Empty validator set for session 0 in genesis block!"); + let initial_validators_0 = T::SessionManager::new_session(0).unwrap_or_else(|| { + frame_support::print( + "No initial validator provided by `SessionManager`, use \ + session config keys to generate initial validator set.", + ); + self.keys.iter().map(|x| x.1.clone()).collect() + }); + assert!( + !initial_validators_0.is_empty(), + "Empty validator set for session 0 in genesis block!" + ); - let initial_validators_1 = T::SessionManager::new_session(1) - .unwrap_or_else(|| initial_validators_0.clone()); - assert!(!initial_validators_1.is_empty(), "Empty validator set for session 1 in genesis block!"); + let initial_validators_1 = + T::SessionManager::new_session(1).unwrap_or_else(|| initial_validators_0.clone()); + assert!( + !initial_validators_1.is_empty(), + "Empty validator set for session 1 in genesis block!" + ); let queued_keys: Vec<_> = initial_validators_1 .iter() .cloned() - .map(|v| ( - v.clone(), - >::load_keys(&v).unwrap_or_default(), - )) + .map(|v| (v.clone(), >::load_keys(&v).unwrap_or_default())) .collect(); // Tell everyone about the genesis session keys @@ -477,21 +519,38 @@ decl_storage! { >::put(queued_keys); T::SessionManager::start_session(0); - }); + } } -} -decl_event!( + /// Events type. + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// New session has happened. Note that the argument is the \[session_index\], not the block /// number as the type might suggest. NewSession(SessionIndex), } -); -decl_error! { - /// Error for the session module. - pub enum Error for Module { + #[pallet::hooks] + impl Hooks> for Pallet { + /// Called when a block is initialized. Will rotate session if it is the last + /// block of the current session. + fn on_initialize(n: T::BlockNumber) -> Weight { + if T::ShouldEndSession::should_end_session(n) { + Self::rotate_session(); + T::BlockWeights::get().max_block + } else { + // NOTE: the non-database part of the weight for `should_end_session(n)` is + // included as weight for empty block, the database part is expected to be in + // cache. + 0 + } + } + } + + /// Error for the session pallet. + #[pallet::error] + pub enum Error { /// Invalid ownership proof. InvalidProof, /// No associated validator ID for account. @@ -503,14 +562,9 @@ decl_error! { /// Key setting account is not live, so it's impossible to associate keys. NoAccount, } -} - -decl_module! { - pub struct Module for enum Call where origin: T::Origin { - type Error = Error; - - fn deposit_event() = default; + #[pallet::call] + impl Pallet { /// Sets the session key(s) of the function caller to `keys`. /// Allows an account to set its session key prior to becoming a validator. /// This doesn't take effect until the next session. @@ -525,11 +579,18 @@ decl_module! { /// - DbReads per key id: `KeyOwner` /// - DbWrites per key id: `KeyOwner` /// # - #[weight = T::WeightInfo::set_keys()] - pub fn set_keys(origin, keys: T::Keys, proof: Vec) -> dispatch::DispatchResult { + #[pallet::weight(T::WeightInfo::set_keys())] + pub fn set_keys( + origin: OriginFor, + keys: T::Keys, + proof: Vec, + ) -> DispatchResult { let who = ensure_signed(origin)?; - ensure!(keys.ownership_proof_is_valid(&proof), Error::::InvalidProof); + ensure!( + keys.ownership_proof_is_valid(&proof), + Error::::InvalidProof + ); Self::do_set_keys(&who, keys)?; @@ -548,36 +609,24 @@ decl_module! { /// - DbWrites: `NextKeys`, `origin account` /// - DbWrites per key id: `KeyOwnder` /// # - #[weight = T::WeightInfo::purge_keys()] - pub fn purge_keys(origin) { + #[pallet::weight(T::WeightInfo::purge_keys())] + pub fn purge_keys(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; Self::do_purge_keys(&who)?; + Ok(()) } - /// Called when a block is initialized. Will rotate session if it is the last - /// block of the current session. - fn on_initialize(n: T::BlockNumber) -> Weight { - if T::ShouldEndSession::should_end_session(n) { - Self::rotate_session(); - T::BlockWeights::get().max_block - } else { - // NOTE: the non-database part of the weight for `should_end_session(n)` is - // included as weight for empty block, the database part is expected to be in - // cache. - 0 - } - } } } -impl Module { +impl Pallet { /// Move on to next session. Register new validator set and session keys. Changes /// to the validator set have a session of delay to take effect. This allows for /// equivocation punishment after a fork. pub fn rotate_session() { - let session_index = CurrentIndex::get(); + let session_index = CurrentIndex::::get(); - let changed = QueuedChanged::get(); + let changed = QueuedChanged::::get(); // Inform the session handlers that a session is going to end. T::SessionHandler::on_before_session_ending(); @@ -593,12 +642,12 @@ impl Module { if changed { // reset disabled validators - DisabledValidators::take(); + DisabledValidators::::take(); } // Increment session index. let session_index = session_index + 1; - CurrentIndex::put(session_index); + CurrentIndex::::put(session_index); T::SessionManager::start_session(session_index); @@ -646,7 +695,7 @@ impl Module { }; >::put(queued_amalgamated.clone()); - QueuedChanged::put(next_changed); + QueuedChanged::::put(next_changed); // Record that this happened. Self::deposit_event(Event::NewSession(session_index)); @@ -664,7 +713,7 @@ impl Module { /// Returns `true` if this causes a `DisabledValidatorsThreshold` of validators /// to be already disabled. pub fn disable_index(i: usize) -> bool { - let (fire_event, threshold_reached) = DisabledValidators::mutate(|disabled| { + let (fire_event, threshold_reached) = DisabledValidators::::mutate(|disabled| { let i = i as u32; if let Err(index) = disabled.binary_search(&i) { let count = >::decode_len().unwrap_or(0) as u32; @@ -683,12 +732,12 @@ impl Module { threshold_reached } - /// Disable the validator identified by `c`. (If using with the staking module, + /// Disable the validator identified by `c`. (If using with the staking Pallet, /// this would be their *stash* account.) /// /// Returns `Ok(true)` if more than `DisabledValidatorsThreshold` validators in current /// session is already disabled. - /// If used with the staking module it allows to force a new era in such case. + /// If used with the staking Pallet it allows to force a new era in such case. pub fn disable(c: &T::ValidatorId) -> sp_std::result::Result { Self::validators().iter().position(|i| i == c).map(Self::disable_index).ok_or(()) } @@ -702,7 +751,7 @@ impl Module { /// /// Care should be taken that the raw versions of the /// added keys are unique for every `ValidatorId, KeyTypeId` combination. - /// This is an invariant that the session module typically maintains internally. + /// This is an invariant that the session Pallet typically maintains internally. /// /// As the actual values of the keys are typically not known at runtime upgrade, /// it's recommended to initialize the keys to a (unique) dummy value with the expectation @@ -837,16 +886,16 @@ impl Module { } } -impl ValidatorSet for Module { +impl ValidatorSet for Pallet { type ValidatorId = T::ValidatorId; type ValidatorIdOf = T::ValidatorIdOf; fn session_index() -> sp_staking::SessionIndex { - Module::::current_index() + Pallet::::current_index() } fn validators() -> Vec { - Module::::validators() + Pallet::::validators() } } @@ -863,17 +912,17 @@ impl> FindAuthor { let i = Inner::find_author(digests)?; - let validators = >::validators(); + let validators = >::validators(); validators.get(i as usize).map(|k| k.clone()) } } -impl EstimateNextNewSession for Module { +impl EstimateNextNewSession for Pallet { fn average_session_length() -> T::BlockNumber { T::NextSessionRotation::average_session_length() } - /// This session module always calls new_session and next_session at the same time, hence we + /// This session Pallet always calls new_session and next_session at the same time, hence we /// do a simple proxy and pass the function to next rotation. fn estimate_next_new_session(now: T::BlockNumber) -> (Option, Weight) { T::NextSessionRotation::estimate_next_session_rotation(now) diff --git a/frame/session/src/mock.rs b/frame/session/src/mock.rs index 3459ab73d6afe..1f0543d75ef63 100644 --- a/frame/session/src/mock.rs +++ b/frame/session/src/mock.rs @@ -19,7 +19,7 @@ use super::*; use std::cell::RefCell; -use frame_support::{parameter_types, BasicExternalities}; +use frame_support::{parameter_types, BasicExternalities, traits::GenesisBuild}; use sp_core::{crypto::key_types::DUMMY, H256}; use sp_runtime::{ Perbill, impl_opaque_keys, diff --git a/frame/staking/src/lib.rs b/frame/staking/src/lib.rs index 67726f69228f7..652099b21e165 100644 --- a/frame/staking/src/lib.rs +++ b/frame/staking/src/lib.rs @@ -654,15 +654,15 @@ impl SessionInterface<::AccountId> for T w Convert<::AccountId, Option<::AccountId>>, { fn disable_validator(validator: &::AccountId) -> Result { - >::disable(validator) + >::disable(validator) } fn validators() -> Vec<::AccountId> { - >::validators() + >::validators() } fn prune_historical_up_to(up_to: SessionIndex) { - >::prune_up_to(up_to); + >::prune_up_to(up_to); } } diff --git a/frame/staking/src/mock.rs b/frame/staking/src/mock.rs index 4027ac1f670bc..d80ab5837aa27 100644 --- a/frame/staking/src/mock.rs +++ b/frame/staking/src/mock.rs @@ -21,7 +21,7 @@ use crate::*; use crate as staking; use frame_support::{ assert_ok, parameter_types, - traits::{Currency, FindAuthor, Get, OnFinalize, OnInitialize, OneSessionHandler}, + traits::{Currency, FindAuthor, Get, OnFinalize, OnInitialize, OneSessionHandler, GenesisBuild}, weights::constants::RocksDbWeight, IterableStorageMap, StorageDoubleMap, StorageMap, StorageValue, }; @@ -35,6 +35,7 @@ use sp_runtime::{ use sp_staking::offence::{OffenceDetails, OnOffenceHandler}; use std::{cell::RefCell, collections::HashSet}; use frame_election_provider_support::onchain; +use pallet_session::historical as pallet_session_historical; pub const INIT_TIMESTAMP: u64 = 30_000; pub const BLOCK_TIME: u64 = 1000; @@ -101,6 +102,7 @@ frame_support::construct_runtime!( Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, Staking: staking::{Pallet, Call, Config, Storage, Event}, Session: pallet_session::{Pallet, Call, Storage, Event, Config}, + Historical: pallet_session_historical::{Pallet}, } );