pezpallet_session/
lib.rs

1// This file is part of Bizinikiwi.
2
3// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Session Pezpallet
19//!
20//! The Session pezpallet allows validators to manage their session keys, provides a function for
21//! changing the session length, and handles session rotation.
22//!
23//! - [`Config`]
24//! - [`Call`]
25//! - [`Pezpallet`]
26//!
27//! ## Overview
28//!
29//! ### Terminology
30//! <!-- Original author of paragraph: @gavofyork -->
31//!
32//! - **Session:** A session is a period of time that has a constant set of validators. Validators
33//!   can only join or exit the validator set at a session change. It is measured in block numbers.
34//!   The block where a session is ended is determined by the `ShouldEndSession` trait. When the
35//!   session is ending, a new validator set can be chosen by `OnSessionEnding` implementations.
36//!
37//! - **Session key:** A session key is actually several keys kept together that provide the various
38//!   signing functions required by network authorities/validators in pursuit of their duties.
39//! - **Validator ID:** Every account has an associated validator ID. For some simple staking
40//!   systems, this may just be the same as the account ID. For staking systems using a
41//!   stash/controller model, the validator ID would be the stash account ID of the controller.
42//!
43//! - **Session key configuration process:** Session keys are set using `set_keys` for use not in
44//!   the next session, but the session after next. They are stored in `NextKeys`, a mapping between
45//!   the caller's `ValidatorId` and the session keys provided. `set_keys` allows users to set their
46//!   session key prior to being selected as validator. It is a public call since it uses
47//!   `ensure_signed`, which checks that the origin is a signed account. As such, the account ID of
48//!   the origin stored in `NextKeys` may not necessarily be associated with a block author or a
49//!   validator. The session keys of accounts are removed once their account balance is zero.
50//!
51//! - **Session length:** This pezpallet does not assume anything about the length of each session.
52//!   Rather, it relies on an implementation of `ShouldEndSession` to dictate a new session's start.
53//!   This pezpallet provides the `PeriodicSessions` struct for simple periodic sessions.
54//!
55//! - **Session rotation configuration:** Configure as either a 'normal' (rewardable session where
56//!   rewards are applied) or 'exceptional' (slashable) session rotation.
57//!
58//! - **Session rotation process:** At the beginning of each block, the `on_initialize` function
59//!   queries the provided implementation of `ShouldEndSession`. If the session is to end the newly
60//!   activated validator IDs and session keys are taken from storage and passed to the
61//!   `SessionHandler`. The validator set supplied by `SessionManager::new_session` and the
62//!   corresponding session keys, which may have been registered via `set_keys` during the previous
63//!   session, are written to storage where they will wait one session before being passed to the
64//!   `SessionHandler` themselves.
65//!
66//! ### Goals
67//!
68//! The Session pezpallet is designed to make the following possible:
69//!
70//! - Set session keys of the validator set for upcoming sessions.
71//! - Control the length of sessions.
72//! - Configure and switch between either normal or exceptional session rotations.
73//!
74//! ## Interface
75//!
76//! ### Dispatchable Functions
77//!
78//! - `set_keys` - Set a validator's session keys for upcoming sessions.
79//!
80//! ### Public Functions
81//!
82//! - `rotate_session` - Change to the next session. Register the new authority set. Queue changes
83//!   for next session rotation.
84//! - `disable_index` - Disable a validator by index.
85//! - `disable` - Disable a validator by Validator ID
86//!
87//! ## Usage
88//!
89//! ### Example from the FRAME
90//!
91//! The [Staking pezpallet](../pezpallet_staking/index.html) uses the Session pezpallet to get the
92//! validator set.
93//!
94//! ```
95//! use pezpallet_session as session;
96//!
97//! fn validators<T: pezpallet_session::Config>() -> Vec<<T as pezpallet_session::Config>::ValidatorId> {
98//! 	pezpallet_session::Validators::<T>::get()
99//! }
100//! # fn main(){}
101//! ```
102//!
103//! ## Related Pallets
104//!
105//! - [Staking](../pezpallet_staking/index.html)
106
107#![cfg_attr(not(feature = "std"), no_std)]
108
109pub mod disabling;
110#[cfg(feature = "historical")]
111pub mod historical;
112pub mod migrations;
113#[cfg(test)]
114mod mock;
115#[cfg(test)]
116mod tests;
117pub mod weights;
118
119extern crate alloc;
120
121use alloc::{boxed::Box, vec::Vec};
122use codec::{Decode, MaxEncodedLen};
123use core::{
124	marker::PhantomData,
125	ops::{Rem, Sub},
126};
127use disabling::DisablingStrategy;
128use pezframe_support::{
129	dispatch::DispatchResult,
130	ensure,
131	traits::{
132		fungible::{hold::Mutate as HoldMutate, Inspect, Mutate},
133		Defensive, EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get,
134		OneSessionHandler, ValidatorRegistration, ValidatorSet,
135	},
136	weights::Weight,
137	Parameter,
138};
139use pezframe_system::pezpallet_prelude::BlockNumberFor;
140use pezsp_runtime::{
141	traits::{AtLeast32BitUnsigned, Convert, Member, One, OpaqueKeys, Zero},
142	ConsensusEngineId, DispatchError, KeyTypeId, Permill, RuntimeAppPublic,
143};
144use pezsp_staking::{offence::OffenceSeverity, SessionIndex};
145
146pub use pezpallet::*;
147pub use weights::WeightInfo;
148
149#[cfg(any(feature = "try-runtime"))]
150use pezsp_runtime::TryRuntimeError;
151
152pub(crate) const LOG_TARGET: &str = "runtime::session";
153
154// syntactic sugar for logging.
155#[macro_export]
156macro_rules! log {
157	($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
158		log::$level!(
159			target: crate::LOG_TARGET,
160			concat!("[{:?}] 💸 ", $patter), <pezframe_system::Pezpallet<T>>::block_number() $(, $values)*
161		)
162	};
163}
164
165/// Decides whether the session should be ended.
166pub trait ShouldEndSession<BlockNumber> {
167	/// Return `true` if the session should be ended.
168	fn should_end_session(now: BlockNumber) -> bool;
169}
170
171/// Ends the session after a fixed period of blocks.
172///
173/// The first session will have length of `Offset`, and
174/// the following sessions will have length of `Period`.
175/// This may prove nonsensical if `Offset` >= `Period`.
176pub struct PeriodicSessions<Period, Offset>(PhantomData<(Period, Offset)>);
177
178impl<
179		BlockNumber: Rem<Output = BlockNumber> + Sub<Output = BlockNumber> + Zero + PartialOrd,
180		Period: Get<BlockNumber>,
181		Offset: Get<BlockNumber>,
182	> ShouldEndSession<BlockNumber> for PeriodicSessions<Period, Offset>
183{
184	fn should_end_session(now: BlockNumber) -> bool {
185		let offset = Offset::get();
186		now >= offset && ((now - offset) % Period::get()).is_zero()
187	}
188}
189
190impl<
191		BlockNumber: AtLeast32BitUnsigned + Clone,
192		Period: Get<BlockNumber>,
193		Offset: Get<BlockNumber>,
194	> EstimateNextSessionRotation<BlockNumber> for PeriodicSessions<Period, Offset>
195{
196	fn average_session_length() -> BlockNumber {
197		Period::get()
198	}
199
200	fn estimate_current_session_progress(now: BlockNumber) -> (Option<Permill>, Weight) {
201		let offset = Offset::get();
202		let period = Period::get();
203
204		// NOTE: we add one since we assume that the current block has already elapsed,
205		// i.e. when evaluating the last block in the session the progress should be 100%
206		// (0% is never returned).
207		let progress = if now >= offset {
208			let current = (now - offset) % period.clone() + One::one();
209			Some(Permill::from_rational(current, period))
210		} else {
211			Some(Permill::from_rational(now + One::one(), offset))
212		};
213
214		// Weight note: `estimate_current_session_progress` has no storage reads and trivial
215		// computational overhead. There should be no risk to the chain having this weight value be
216		// zero for now. However, this value of zero was not properly calculated, and so it would be
217		// reasonable to come back here and properly calculate the weight of this function.
218		(progress, Zero::zero())
219	}
220
221	fn estimate_next_session_rotation(now: BlockNumber) -> (Option<BlockNumber>, Weight) {
222		let offset = Offset::get();
223		let period = Period::get();
224
225		let next_session = if now > offset {
226			let block_after_last_session = (now.clone() - offset) % period.clone();
227			if block_after_last_session > Zero::zero() {
228				now.saturating_add(period.saturating_sub(block_after_last_session))
229			} else {
230				// this branch happens when the session is already rotated or will rotate in this
231				// block (depending on being called before or after `session::on_initialize`). Here,
232				// we assume the latter, namely that this is called after `session::on_initialize`,
233				// and thus we add period to it as well.
234				now + period
235			}
236		} else {
237			offset
238		};
239
240		// Weight note: `estimate_next_session_rotation` has no storage reads and trivial
241		// computational overhead. There should be no risk to the chain having this weight value be
242		// zero for now. However, this value of zero was not properly calculated, and so it would be
243		// reasonable to come back here and properly calculate the weight of this function.
244		(Some(next_session), Zero::zero())
245	}
246}
247
248/// A trait for managing creation of new validator set.
249pub trait SessionManager<ValidatorId> {
250	/// Plan a new session, and optionally provide the new validator set.
251	///
252	/// Even if the validator-set is the same as before, if any underlying economic conditions have
253	/// changed (i.e. stake-weights), the new validator set must be returned. This is necessary for
254	/// consensus engines making use of the session pezpallet to issue a validator-set change so
255	/// misbehavior can be provably associated with the new economic conditions as opposed to the
256	/// old. The returned validator set, if any, will not be applied until `new_index`. `new_index`
257	/// is strictly greater than from previous call.
258	///
259	/// The first session start at index 0.
260	///
261	/// `new_session(session)` is guaranteed to be called before `end_session(session-1)`. In other
262	/// words, a new session must always be planned before an ongoing one can be finished.
263	fn new_session(new_index: SessionIndex) -> Option<Vec<ValidatorId>>;
264	/// Same as `new_session`, but it this should only be called at genesis.
265	///
266	/// The session manager might decide to treat this in a different way. Default impl is simply
267	/// using [`new_session`](Self::new_session).
268	fn new_session_genesis(new_index: SessionIndex) -> Option<Vec<ValidatorId>> {
269		Self::new_session(new_index)
270	}
271	/// End the session.
272	///
273	/// Because the session pezpallet can queue validator set the ending session can be lower than
274	/// the last new session index.
275	fn end_session(end_index: SessionIndex);
276	/// Start an already planned session.
277	///
278	/// The session start to be used for validation.
279	fn start_session(start_index: SessionIndex);
280}
281
282impl<A> SessionManager<A> for () {
283	fn new_session(_: SessionIndex) -> Option<Vec<A>> {
284		None
285	}
286	fn start_session(_: SessionIndex) {}
287	fn end_session(_: SessionIndex) {}
288}
289
290/// Handler for session life cycle events.
291pub trait SessionHandler<ValidatorId> {
292	/// All the key type ids this session handler can process.
293	///
294	/// The order must be the same as it expects them in
295	/// [`on_new_session`](Self::on_new_session<Ks>) and
296	/// [`on_genesis_session`](Self::on_genesis_session<Ks>).
297	const KEY_TYPE_IDS: &'static [KeyTypeId];
298
299	/// The given validator set will be used for the genesis session.
300	/// It is guaranteed that the given validator set will also be used
301	/// for the second session, therefore the first call to `on_new_session`
302	/// should provide the same validator set.
303	fn on_genesis_session<Ks: OpaqueKeys>(validators: &[(ValidatorId, Ks)]);
304
305	/// Session set has changed; act appropriately. Note that this can be called
306	/// before initialization of your pezpallet.
307	///
308	/// `changed` is true whenever any of the session keys or underlying economic
309	/// identities or weightings behind `validators` keys has changed. `queued_validators`
310	/// could change without `validators` changing. Example of possible sequent calls:
311	///     Session N: on_new_session(false, unchanged_validators, unchanged_queued_validators)
312	///     Session N + 1: on_new_session(false, unchanged_validators, new_queued_validators)
313	/// 	Session N + 2: on_new_session(true, new_queued_validators, new_queued_validators)
314	fn on_new_session<Ks: OpaqueKeys>(
315		changed: bool,
316		validators: &[(ValidatorId, Ks)],
317		queued_validators: &[(ValidatorId, Ks)],
318	);
319
320	/// A notification for end of the session.
321	///
322	/// Note it is triggered before any [`SessionManager::end_session`] handlers,
323	/// so we can still affect the validator set.
324	fn on_before_session_ending() {}
325
326	/// A validator got disabled. Act accordingly until a new session begins.
327	fn on_disabled(validator_index: u32);
328}
329
330#[impl_trait_for_tuples::impl_for_tuples(1, 30)]
331#[tuple_types_custom_trait_bound(OneSessionHandler<AId>)]
332impl<AId> SessionHandler<AId> for Tuple {
333	for_tuples!(
334		const KEY_TYPE_IDS: &'static [KeyTypeId] = &[ #( <Tuple::Key as RuntimeAppPublic>::ID ),* ];
335	);
336
337	fn on_genesis_session<Ks: OpaqueKeys>(validators: &[(AId, Ks)]) {
338		for_tuples!(
339			#(
340				let our_keys: Box<dyn Iterator<Item=_>> = Box::new(validators.iter()
341					.filter_map(|k|
342						k.1.get::<Tuple::Key>(<Tuple::Key as RuntimeAppPublic>::ID).map(|k1| (&k.0, k1))
343					)
344				);
345
346				Tuple::on_genesis_session(our_keys);
347			)*
348		)
349	}
350
351	fn on_new_session<Ks: OpaqueKeys>(
352		changed: bool,
353		validators: &[(AId, Ks)],
354		queued_validators: &[(AId, Ks)],
355	) {
356		for_tuples!(
357			#(
358				let our_keys: Box<dyn Iterator<Item=_>> = Box::new(validators.iter()
359					.filter_map(|k|
360						k.1.get::<Tuple::Key>(<Tuple::Key as RuntimeAppPublic>::ID).map(|k1| (&k.0, k1))
361					));
362				let queued_keys: Box<dyn Iterator<Item=_>> = Box::new(queued_validators.iter()
363					.filter_map(|k|
364						k.1.get::<Tuple::Key>(<Tuple::Key as RuntimeAppPublic>::ID).map(|k1| (&k.0, k1))
365					));
366				Tuple::on_new_session(changed, our_keys, queued_keys);
367			)*
368		)
369	}
370
371	fn on_before_session_ending() {
372		for_tuples!( #( Tuple::on_before_session_ending(); )* )
373	}
374
375	fn on_disabled(i: u32) {
376		for_tuples!( #( Tuple::on_disabled(i); )* )
377	}
378}
379
380/// `SessionHandler` for tests that use `UintAuthorityId` as `Keys`.
381pub struct TestSessionHandler;
382impl<AId> SessionHandler<AId> for TestSessionHandler {
383	const KEY_TYPE_IDS: &'static [KeyTypeId] = &[pezsp_runtime::key_types::DUMMY];
384	fn on_genesis_session<Ks: OpaqueKeys>(_: &[(AId, Ks)]) {}
385	fn on_new_session<Ks: OpaqueKeys>(_: bool, _: &[(AId, Ks)], _: &[(AId, Ks)]) {}
386	fn on_before_session_ending() {}
387	fn on_disabled(_: u32) {}
388}
389
390#[pezframe_support::pezpallet]
391pub mod pezpallet {
392	use super::*;
393	use pezframe_support::pezpallet_prelude::*;
394	use pezframe_system::pezpallet_prelude::*;
395
396	/// The in-code storage version.
397	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
398
399	#[pezpallet::pezpallet]
400	#[pezpallet::storage_version(STORAGE_VERSION)]
401	#[pezpallet::without_storage_info]
402	pub struct Pezpallet<T>(_);
403
404	#[pezpallet::config]
405	pub trait Config: pezframe_system::Config {
406		/// The overarching event type.
407		#[allow(deprecated)]
408		type RuntimeEvent: From<Event<Self>>
409			+ IsType<<Self as pezframe_system::Config>::RuntimeEvent>;
410
411		/// A stable ID for a validator.
412		type ValidatorId: Member
413			+ Parameter
414			+ MaybeSerializeDeserialize
415			+ MaxEncodedLen
416			+ TryFrom<Self::AccountId>;
417
418		/// A conversion from account ID to validator ID.
419		///
420		/// It is also a means to check that an account id is eligible to set session keys, through
421		/// being associated with a validator id. To disable this check, use
422		/// [`pezsp_runtime::traits::ConvertInto`].
423		///
424		/// Its cost must be at most one storage read.
425		type ValidatorIdOf: Convert<Self::AccountId, Option<Self::ValidatorId>>;
426
427		/// Indicator for when to end the session.
428		type ShouldEndSession: ShouldEndSession<BlockNumberFor<Self>>;
429
430		/// Something that can predict the next session rotation. This should typically come from
431		/// the same logical unit that provides [`ShouldEndSession`], yet, it gives a best effort
432		/// estimate. It is helpful to implement [`EstimateNextNewSession`].
433		type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
434
435		/// Handler for managing new session.
436		type SessionManager: SessionManager<Self::ValidatorId>;
437
438		/// Handler when a session has changed.
439		type SessionHandler: SessionHandler<Self::ValidatorId>;
440
441		/// The keys.
442		type Keys: OpaqueKeys + Member + Parameter + MaybeSerializeDeserialize;
443
444		/// `DisablingStragegy` controls how validators are disabled
445		type DisablingStrategy: DisablingStrategy<Self>;
446
447		/// Weight information for extrinsics in this pezpallet.
448		type WeightInfo: WeightInfo;
449
450		/// The currency type for placing holds when setting keys.
451		type Currency: Mutate<Self::AccountId>
452			+ HoldMutate<Self::AccountId, Reason: From<HoldReason>>;
453
454		/// The amount to be held when setting keys.
455		#[pezpallet::constant]
456		type KeyDeposit: Get<
457			<<Self as Config>::Currency as Inspect<<Self as pezframe_system::Config>::AccountId>>::Balance,
458		>;
459	}
460
461	#[pezpallet::genesis_config]
462	#[derive(pezframe_support::DefaultNoBound)]
463	pub struct GenesisConfig<T: Config> {
464		/// Initial list of validator at genesis representing by their `(AccountId, ValidatorId,
465		/// Keys)`. These keys will be considered authorities for the first two sessions and they
466		/// will be valid at least until session 2
467		pub keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>,
468		/// List of (AccountId, ValidatorId, Keys) that will be registered at genesis, but not as
469		/// active validators. These keys are set, together with `keys`, as authority candidates
470		/// for future sessions (enactable from session 2 onwards)
471		pub non_authority_keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>,
472	}
473
474	#[pezpallet::genesis_build]
475	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
476		fn build(&self) {
477			if T::SessionHandler::KEY_TYPE_IDS.len() != T::Keys::key_ids().len() {
478				panic!("Number of keys in session handler and session keys does not match");
479			}
480
481			T::SessionHandler::KEY_TYPE_IDS
482				.iter()
483				.zip(T::Keys::key_ids())
484				.enumerate()
485				.for_each(|(i, (sk, kk))| {
486					if sk != kk {
487						panic!(
488							"Session handler and session key expect different key type at index: {}",
489							i,
490						);
491					}
492				});
493
494			for (account, val, keys) in
495				self.keys.iter().chain(self.non_authority_keys.iter()).cloned()
496			{
497				Pezpallet::<T>::inner_set_keys(&val, keys)
498					.expect("genesis config must not contain duplicates; qed");
499				if pezframe_system::Pezpallet::<T>::inc_consumers_without_limit(&account).is_err() {
500					// This will leak a provider reference, however it only happens once (at
501					// genesis) so it's really not a big deal and we assume that the user wants to
502					// do this since it's the only way a non-endowed account can contain a session
503					// key.
504					pezframe_system::Pezpallet::<T>::inc_providers(&account);
505				}
506			}
507
508			let initial_validators_0 =
509				T::SessionManager::new_session_genesis(0).unwrap_or_else(|| {
510					pezframe_support::print(
511						"No initial validator provided by `SessionManager`, use \
512						session config keys to generate initial validator set.",
513					);
514					self.keys.iter().map(|x| x.1.clone()).collect()
515				});
516
517			let initial_validators_1 = T::SessionManager::new_session_genesis(1)
518				.unwrap_or_else(|| initial_validators_0.clone());
519
520			let queued_keys: Vec<_> = initial_validators_1
521				.into_iter()
522				.filter_map(|v| Pezpallet::<T>::load_keys(&v).map(|k| (v, k)))
523				.collect();
524
525			// Tell everyone about the genesis session keys
526			T::SessionHandler::on_genesis_session::<T::Keys>(&queued_keys);
527
528			Validators::<T>::put(initial_validators_0);
529			QueuedKeys::<T>::put(queued_keys);
530
531			T::SessionManager::start_session(0);
532		}
533	}
534
535	/// A reason for the pezpallet placing a hold on funds.
536	#[pezpallet::composite_enum]
537	pub enum HoldReason {
538		// Funds are held when settings keys
539		#[codec(index = 0)]
540		Keys,
541	}
542
543	/// The current set of validators.
544	#[pezpallet::storage]
545	pub type Validators<T: Config> = StorageValue<_, Vec<T::ValidatorId>, ValueQuery>;
546
547	/// Current index of the session.
548	#[pezpallet::storage]
549	pub type CurrentIndex<T> = StorageValue<_, SessionIndex, ValueQuery>;
550
551	/// True if the underlying economic identities or weighting behind the validators
552	/// has changed in the queued validator set.
553	#[pezpallet::storage]
554	pub type QueuedChanged<T> = StorageValue<_, bool, ValueQuery>;
555
556	/// The queued keys for the next session. When the next session begins, these keys
557	/// will be used to determine the validator's session keys.
558	#[pezpallet::storage]
559	pub type QueuedKeys<T: Config> = StorageValue<_, Vec<(T::ValidatorId, T::Keys)>, ValueQuery>;
560
561	/// Indices of disabled validators.
562	///
563	/// The vec is always kept sorted so that we can find whether a given validator is
564	/// disabled using binary search. It gets cleared when `on_session_ending` returns
565	/// a new set of identities.
566	#[pezpallet::storage]
567	pub type DisabledValidators<T> = StorageValue<_, Vec<(u32, OffenceSeverity)>, ValueQuery>;
568
569	/// The next session keys for a validator.
570	#[pezpallet::storage]
571	pub type NextKeys<T: Config> =
572		StorageMap<_, Twox64Concat, T::ValidatorId, T::Keys, OptionQuery>;
573
574	/// The owner of a key. The key is the `KeyTypeId` + the encoded key.
575	#[pezpallet::storage]
576	pub type KeyOwner<T: Config> =
577		StorageMap<_, Twox64Concat, (KeyTypeId, Vec<u8>), T::ValidatorId, OptionQuery>;
578
579	#[pezpallet::event]
580	#[pezpallet::generate_deposit(pub(super) fn deposit_event)]
581	pub enum Event<T: Config> {
582		/// New session has happened. Note that the argument is the session index, not the
583		/// block number as the type might suggest.
584		NewSession { session_index: SessionIndex },
585		/// The `NewSession` event in the current block also implies a new validator set to be
586		/// queued.
587		NewQueued,
588		/// Validator has been disabled.
589		ValidatorDisabled { validator: T::ValidatorId },
590		/// Validator has been re-enabled.
591		ValidatorReenabled { validator: T::ValidatorId },
592	}
593
594	/// Error for the session pezpallet.
595	#[pezpallet::error]
596	pub enum Error<T> {
597		/// Invalid ownership proof.
598		InvalidProof,
599		/// No associated validator ID for account.
600		NoAssociatedValidatorId,
601		/// Registered duplicate key.
602		DuplicatedKey,
603		/// No keys are associated with this account.
604		NoKeys,
605		/// Key setting account is not live, so it's impossible to associate keys.
606		NoAccount,
607	}
608
609	#[pezpallet::hooks]
610	impl<T: Config> Hooks<BlockNumberFor<T>> for Pezpallet<T> {
611		/// Called when a block is initialized. Will rotate session if it is the last
612		/// block of the current session.
613		fn on_initialize(n: BlockNumberFor<T>) -> Weight {
614			if T::ShouldEndSession::should_end_session(n) {
615				Self::rotate_session();
616				T::BlockWeights::get().max_block
617			} else {
618				// NOTE: the non-database part of the weight for `should_end_session(n)` is
619				// included as weight for empty block, the database part is expected to be in
620				// cache.
621				Weight::zero()
622			}
623		}
624
625		#[cfg(feature = "try-runtime")]
626		fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
627			Self::do_try_state()
628		}
629	}
630
631	#[pezpallet::call]
632	impl<T: Config> Pezpallet<T> {
633		/// Sets the session key(s) of the function caller to `keys`.
634		/// Allows an account to set its session key prior to becoming a validator.
635		/// This doesn't take effect until the next session.
636		///
637		/// The dispatch origin of this function must be signed.
638		///
639		/// ## Complexity
640		/// - `O(1)`. Actual cost depends on the number of length of `T::Keys::key_ids()` which is
641		///   fixed.
642		#[pezpallet::call_index(0)]
643		#[pezpallet::weight(T::WeightInfo::set_keys())]
644		pub fn set_keys(origin: OriginFor<T>, keys: T::Keys, proof: Vec<u8>) -> DispatchResult {
645			let who = ensure_signed(origin)?;
646			ensure!(keys.ownership_proof_is_valid(&proof), Error::<T>::InvalidProof);
647
648			Self::do_set_keys(&who, keys)?;
649			Ok(())
650		}
651
652		/// Removes any session key(s) of the function caller.
653		///
654		/// This doesn't take effect until the next session.
655		///
656		/// The dispatch origin of this function must be Signed and the account must be either be
657		/// convertible to a validator ID using the chain's typical addressing system (this usually
658		/// means being a controller account) or directly convertible into a validator ID (which
659		/// usually means being a stash account).
660		///
661		/// ## Complexity
662		/// - `O(1)` in number of key types. Actual cost depends on the number of length of
663		///   `T::Keys::key_ids()` which is fixed.
664		#[pezpallet::call_index(1)]
665		#[pezpallet::weight(T::WeightInfo::purge_keys())]
666		pub fn purge_keys(origin: OriginFor<T>) -> DispatchResult {
667			let who = ensure_signed(origin)?;
668			Self::do_purge_keys(&who)?;
669			Ok(())
670		}
671	}
672
673	#[cfg(feature = "runtime-benchmarks")]
674	impl<T: Config> Pezpallet<T> {
675		/// Mint enough funds into `who`, such that they can pay the session key setting deposit.
676		///
677		/// Meant to be used if any pezpallet's benchmarking code wishes to set session keys, and
678		/// wants to make sure it will succeed.
679		pub fn ensure_can_pay_key_deposit(who: &T::AccountId) -> Result<(), DispatchError> {
680			use pezframe_support::traits::tokens::{Fortitude, Preservation};
681			let deposit = T::KeyDeposit::get();
682			let has = T::Currency::reducible_balance(who, Preservation::Protect, Fortitude::Force);
683			if let Some(deficit) = deposit.checked_sub(&has) {
684				T::Currency::mint_into(who, deficit.max(T::Currency::minimum_balance()))
685					.map(|_inc| ())
686			} else {
687				Ok(())
688			}
689		}
690	}
691}
692
693impl<T: Config> Pezpallet<T> {
694	/// Public function to access the current set of validators.
695	pub fn validators() -> Vec<T::ValidatorId> {
696		Validators::<T>::get()
697	}
698
699	/// Public function to access the current session index.
700	pub fn current_index() -> SessionIndex {
701		CurrentIndex::<T>::get()
702	}
703
704	/// Public function to access the queued keys.
705	pub fn queued_keys() -> Vec<(T::ValidatorId, T::Keys)> {
706		QueuedKeys::<T>::get()
707	}
708
709	/// Public function to access the disabled validators.
710	pub fn disabled_validators() -> Vec<u32> {
711		DisabledValidators::<T>::get().iter().map(|(i, _)| *i).collect()
712	}
713
714	/// Move on to next session. Register new validator set and session keys. Changes to the
715	/// validator set have a session of delay to take effect. This allows for equivocation
716	/// punishment after a fork.
717	pub fn rotate_session() {
718		let session_index = CurrentIndex::<T>::get();
719		let changed = QueuedChanged::<T>::get();
720
721		// Inform the session handlers that a session is going to end.
722		T::SessionHandler::on_before_session_ending();
723		T::SessionManager::end_session(session_index);
724		log!(trace, "ending_session {:?}", session_index);
725
726		// Get queued session keys and validators.
727		let session_keys = QueuedKeys::<T>::get();
728		let validators =
729			session_keys.iter().map(|(validator, _)| validator.clone()).collect::<Vec<_>>();
730		Validators::<T>::put(&validators);
731
732		if changed {
733			log!(trace, "resetting disabled validators");
734			// reset disabled validators if active set was changed
735			DisabledValidators::<T>::kill();
736		}
737
738		// Increment session index.
739		let session_index = session_index + 1;
740		CurrentIndex::<T>::put(session_index);
741		T::SessionManager::start_session(session_index);
742		log!(trace, "starting_session {:?}", session_index);
743
744		// Get next validator set.
745		let maybe_next_validators = T::SessionManager::new_session(session_index + 1);
746		log!(
747			trace,
748			"planning_session {:?} with {:?} validators",
749			session_index + 1,
750			maybe_next_validators.as_ref().map(|v| v.len())
751		);
752		let (next_validators, next_identities_changed) =
753			if let Some(validators) = maybe_next_validators {
754				// NOTE: as per the documentation on `OnSessionEnding`, we consider
755				// the validator set as having changed even if the validators are the
756				// same as before, as underlying economic conditions may have changed.
757				Self::deposit_event(Event::<T>::NewQueued);
758				(validators, true)
759			} else {
760				(Validators::<T>::get(), false)
761			};
762
763		// Queue next session keys.
764		let (queued_amalgamated, next_changed) = {
765			// until we are certain there has been a change, iterate the prior
766			// validators along with the current and check for changes
767			let mut changed = next_identities_changed;
768
769			let mut now_session_keys = session_keys.iter();
770			let mut check_next_changed = |keys: &T::Keys| {
771				if changed {
772					return;
773				}
774				// since a new validator set always leads to `changed` starting
775				// as true, we can ensure that `now_session_keys` and `next_validators`
776				// have the same length. this function is called once per iteration.
777				if let Some((_, old_keys)) = now_session_keys.next() {
778					if old_keys != keys {
779						changed = true;
780					}
781				}
782			};
783			let queued_amalgamated =
784				next_validators
785					.into_iter()
786					.filter_map(|a| {
787						let k =
788							Self::load_keys(&a).or_else(|| {
789								log!(warn, "failed to load session key for {:?}, skipping for next session, maybe you need to set session keys for them?", a);
790								None
791							})?;
792						check_next_changed(&k);
793						Some((a, k))
794					})
795					.collect::<Vec<_>>();
796
797			(queued_amalgamated, changed)
798		};
799
800		QueuedKeys::<T>::put(queued_amalgamated.clone());
801		QueuedChanged::<T>::put(next_changed);
802
803		// Record that this happened.
804		Self::deposit_event(Event::NewSession { session_index });
805
806		// Tell everyone about the new session keys.
807		T::SessionHandler::on_new_session::<T::Keys>(changed, &session_keys, &queued_amalgamated);
808	}
809
810	/// Upgrade the key type from some old type to a new type. Supports adding
811	/// and removing key types.
812	///
813	/// This function should be used with extreme care and only during an
814	/// `on_runtime_upgrade` block. Misuse of this function can put your blockchain
815	/// into an unrecoverable state.
816	///
817	/// Care should be taken that the raw versions of the
818	/// added keys are unique for every `ValidatorId, KeyTypeId` combination.
819	/// This is an invariant that the session pezpallet typically maintains internally.
820	///
821	/// As the actual values of the keys are typically not known at runtime upgrade,
822	/// it's recommended to initialize the keys to a (unique) dummy value with the expectation
823	/// that all validators should invoke `set_keys` before those keys are actually
824	/// required.
825	pub fn upgrade_keys<Old, F>(upgrade: F)
826	where
827		Old: OpaqueKeys + Member + Decode,
828		F: Fn(T::ValidatorId, Old) -> T::Keys,
829	{
830		let old_ids = Old::key_ids();
831		let new_ids = T::Keys::key_ids();
832
833		// Translate NextKeys, and key ownership relations at the same time.
834		NextKeys::<T>::translate::<Old, _>(|val, old_keys| {
835			// Clear all key ownership relations. Typically the overlap should
836			// stay the same, but no guarantees by the upgrade function.
837			for i in old_ids.iter() {
838				Self::clear_key_owner(*i, old_keys.get_raw(*i));
839			}
840
841			let new_keys = upgrade(val.clone(), old_keys);
842
843			// And now set the new ones.
844			for i in new_ids.iter() {
845				Self::put_key_owner(*i, new_keys.get_raw(*i), &val);
846			}
847
848			Some(new_keys)
849		});
850
851		let _ = QueuedKeys::<T>::translate::<Vec<(T::ValidatorId, Old)>, _>(|k| {
852			k.map(|k| {
853				k.into_iter()
854					.map(|(val, old_keys)| (val.clone(), upgrade(val, old_keys)))
855					.collect::<Vec<_>>()
856			})
857		});
858	}
859
860	/// Perform the set_key operation, checking for duplicates. Does not set `Changed`.
861	///
862	/// This ensures that the reference counter in system is incremented appropriately and as such
863	/// must accept an account ID, rather than a validator ID.
864	fn do_set_keys(account: &T::AccountId, keys: T::Keys) -> DispatchResult {
865		let who = T::ValidatorIdOf::convert(account.clone())
866			.ok_or(Error::<T>::NoAssociatedValidatorId)?;
867
868		ensure!(pezframe_system::Pezpallet::<T>::can_inc_consumer(account), Error::<T>::NoAccount);
869
870		let old_keys = Self::inner_set_keys(&who, keys)?;
871
872		// Place deposit on hold if this is a new registration (i.e. old_keys is None).
873		// The hold call itself will return an error if funds are insufficient.
874		if old_keys.is_none() {
875			let deposit = T::KeyDeposit::get();
876			if !deposit.is_zero() {
877				T::Currency::hold(&HoldReason::Keys.into(), account, deposit)?;
878			}
879
880			let assertion = pezframe_system::Pezpallet::<T>::inc_consumers(account).is_ok();
881			debug_assert!(assertion, "can_inc_consumer() returned true; no change since; qed");
882		}
883
884		Ok(())
885	}
886
887	/// Perform the set_key operation, checking for duplicates. Does not set `Changed`.
888	///
889	/// The old keys for this validator are returned, or `None` if there were none.
890	///
891	/// This does not ensure that the reference counter in system is incremented appropriately, it
892	/// must be done by the caller or the keys will be leaked in storage.
893	fn inner_set_keys(
894		who: &T::ValidatorId,
895		keys: T::Keys,
896	) -> Result<Option<T::Keys>, DispatchError> {
897		let old_keys = Self::load_keys(who);
898
899		for id in T::Keys::key_ids() {
900			let key = keys.get_raw(*id);
901
902			// ensure keys are without duplication.
903			ensure!(
904				Self::key_owner(*id, key).map_or(true, |owner| &owner == who),
905				Error::<T>::DuplicatedKey,
906			);
907		}
908
909		for id in T::Keys::key_ids() {
910			let key = keys.get_raw(*id);
911
912			if let Some(old) = old_keys.as_ref().map(|k| k.get_raw(*id)) {
913				if key == old {
914					continue;
915				}
916
917				Self::clear_key_owner(*id, old);
918			}
919
920			Self::put_key_owner(*id, key, who);
921		}
922
923		Self::put_keys(who, &keys);
924		Ok(old_keys)
925	}
926
927	fn do_purge_keys(account: &T::AccountId) -> DispatchResult {
928		let who = T::ValidatorIdOf::convert(account.clone())
929			// `purge_keys` may not have a controller-stash pair any more. If so then we expect the
930			// stash account to be passed in directly and convert that to a `ValidatorId` using the
931			// `TryFrom` trait if supported.
932			.or_else(|| T::ValidatorId::try_from(account.clone()).ok())
933			.ok_or(Error::<T>::NoAssociatedValidatorId)?;
934
935		let old_keys = Self::take_keys(&who).ok_or(Error::<T>::NoKeys)?;
936		for id in T::Keys::key_ids() {
937			let key_data = old_keys.get_raw(*id);
938			Self::clear_key_owner(*id, key_data);
939		}
940
941		// Use release_all to handle the case where the exact amount might not be available
942		let _ = T::Currency::release_all(
943			&HoldReason::Keys.into(),
944			account,
945			pezframe_support::traits::tokens::Precision::BestEffort,
946		);
947
948		pezframe_system::Pezpallet::<T>::dec_consumers(account);
949
950		Ok(())
951	}
952
953	pub fn load_keys(v: &T::ValidatorId) -> Option<T::Keys> {
954		NextKeys::<T>::get(v)
955	}
956
957	fn take_keys(v: &T::ValidatorId) -> Option<T::Keys> {
958		NextKeys::<T>::take(v)
959	}
960
961	fn put_keys(v: &T::ValidatorId, keys: &T::Keys) {
962		NextKeys::<T>::insert(v, keys);
963	}
964
965	/// Query the owner of a session key by returning the owner's validator ID.
966	pub fn key_owner(id: KeyTypeId, key_data: &[u8]) -> Option<T::ValidatorId> {
967		KeyOwner::<T>::get((id, key_data))
968	}
969
970	fn put_key_owner(id: KeyTypeId, key_data: &[u8], v: &T::ValidatorId) {
971		KeyOwner::<T>::insert((id, key_data), v)
972	}
973
974	fn clear_key_owner(id: KeyTypeId, key_data: &[u8]) {
975		KeyOwner::<T>::remove((id, key_data));
976	}
977
978	/// Disable the validator of index `i` with a specified severity,
979	/// returns `false` if the validator is not found.
980	///
981	/// Note: If validator is already disabled, the severity will
982	/// be updated if the new one is higher.
983	pub fn disable_index_with_severity(i: u32, severity: OffenceSeverity) -> bool {
984		if i >= Validators::<T>::decode_len().defensive_unwrap_or(0) as u32 {
985			return false;
986		}
987
988		DisabledValidators::<T>::mutate(|disabled| {
989			match disabled.binary_search_by_key(&i, |(index, _)| *index) {
990				// Validator is already disabled, update severity if the new one is higher
991				Ok(index) => {
992					let current_severity = &mut disabled[index].1;
993					if severity > *current_severity {
994						log!(
995							trace,
996							"updating disablement severity of validator {:?} from {:?} to {:?}",
997							i,
998							*current_severity,
999							severity
1000						);
1001						*current_severity = severity;
1002					}
1003					true
1004				},
1005				// Validator is not disabled, add to `DisabledValidators` and disable it
1006				Err(index) => {
1007					log!(trace, "disabling validator {:?}", i);
1008					Self::deposit_event(Event::ValidatorDisabled {
1009						validator: Validators::<T>::get()[i as usize].clone(),
1010					});
1011					disabled.insert(index, (i, severity));
1012					T::SessionHandler::on_disabled(i);
1013					true
1014				},
1015			}
1016		})
1017	}
1018
1019	/// Disable the validator of index `i` with a default severity (defaults to most severe),
1020	/// returns `false` if the validator is not found.
1021	pub fn disable_index(i: u32) -> bool {
1022		let default_severity = OffenceSeverity::default();
1023		Self::disable_index_with_severity(i, default_severity)
1024	}
1025
1026	/// Re-enable the validator of index `i`, returns `false` if the validator was not disabled.
1027	pub fn reenable_index(i: u32) -> bool {
1028		if i >= Validators::<T>::decode_len().defensive_unwrap_or(0) as u32 {
1029			return false;
1030		}
1031
1032		DisabledValidators::<T>::mutate(|disabled| {
1033			if let Ok(index) = disabled.binary_search_by_key(&i, |(index, _)| *index) {
1034				log!(trace, "reenabling validator {:?}", i);
1035				Self::deposit_event(Event::ValidatorReenabled {
1036					validator: Validators::<T>::get()[i as usize].clone(),
1037				});
1038				disabled.remove(index);
1039				return true;
1040			}
1041			false
1042		})
1043	}
1044
1045	/// Convert a validator ID to an index.
1046	/// (If using with the staking pezpallet, this would be their *stash* account.)
1047	pub fn validator_id_to_index(id: &T::ValidatorId) -> Option<u32> {
1048		Validators::<T>::get().iter().position(|i| i == id).map(|i| i as u32)
1049	}
1050
1051	/// Report an offence for the given validator and let disabling strategy decide
1052	/// what changes to disabled validators should be made.
1053	pub fn report_offence(validator: T::ValidatorId, severity: OffenceSeverity) {
1054		let decision =
1055			T::DisablingStrategy::decision(&validator, severity, &DisabledValidators::<T>::get());
1056		log!(
1057			debug,
1058			"reporting offence for {:?} with {:?}, decision: {:?}",
1059			validator,
1060			severity,
1061			decision
1062		);
1063
1064		// Disable
1065		if let Some(offender_idx) = decision.disable {
1066			Self::disable_index_with_severity(offender_idx, severity);
1067		}
1068
1069		// Re-enable
1070		if let Some(reenable_idx) = decision.reenable {
1071			Self::reenable_index(reenable_idx);
1072		}
1073	}
1074
1075	#[cfg(any(test, feature = "try-runtime"))]
1076	pub fn do_try_state() -> Result<(), pezsp_runtime::TryRuntimeError> {
1077		// Ensure that the validators are sorted
1078		ensure!(
1079			DisabledValidators::<T>::get().windows(2).all(|pair| pair[0].0 <= pair[1].0),
1080			"DisabledValidators is not sorted"
1081		);
1082		Ok(())
1083	}
1084}
1085
1086impl<T: Config> ValidatorRegistration<T::ValidatorId> for Pezpallet<T> {
1087	fn is_registered(id: &T::ValidatorId) -> bool {
1088		Self::load_keys(id).is_some()
1089	}
1090}
1091
1092impl<T: Config> ValidatorSet<T::AccountId> for Pezpallet<T> {
1093	type ValidatorId = T::ValidatorId;
1094	type ValidatorIdOf = T::ValidatorIdOf;
1095
1096	fn session_index() -> pezsp_staking::SessionIndex {
1097		CurrentIndex::<T>::get()
1098	}
1099
1100	fn validators() -> Vec<Self::ValidatorId> {
1101		Validators::<T>::get()
1102	}
1103}
1104
1105impl<T: Config> EstimateNextNewSession<BlockNumberFor<T>> for Pezpallet<T> {
1106	fn average_session_length() -> BlockNumberFor<T> {
1107		T::NextSessionRotation::average_session_length()
1108	}
1109
1110	/// This session pezpallet always calls new_session and next_session at the same time, hence we
1111	/// do a simple proxy and pass the function to next rotation.
1112	fn estimate_next_new_session(now: BlockNumberFor<T>) -> (Option<BlockNumberFor<T>>, Weight) {
1113		T::NextSessionRotation::estimate_next_session_rotation(now)
1114	}
1115}
1116
1117impl<T: Config> pezframe_support::traits::DisabledValidators for Pezpallet<T> {
1118	fn is_disabled(index: u32) -> bool {
1119		DisabledValidators::<T>::get().binary_search_by_key(&index, |(i, _)| *i).is_ok()
1120	}
1121
1122	fn disabled_validators() -> Vec<u32> {
1123		Self::disabled_validators()
1124	}
1125}
1126
1127/// Wraps the author-scraping logic for consensus engines that can recover
1128/// the canonical index of an author. This then transforms it into the
1129/// registering account-ID of that session key index.
1130pub struct FindAccountFromAuthorIndex<T, Inner>(core::marker::PhantomData<(T, Inner)>);
1131
1132impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::ValidatorId>
1133	for FindAccountFromAuthorIndex<T, Inner>
1134{
1135	fn find_author<'a, I>(digests: I) -> Option<T::ValidatorId>
1136	where
1137		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
1138	{
1139		let i = Inner::find_author(digests)?;
1140
1141		let validators = Validators::<T>::get();
1142		validators.get(i as usize).cloned()
1143	}
1144}