1#![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 frame_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 frame_system::pallet_prelude::BlockNumberFor;
140use sp_runtime::{
141 traits::{AtLeast32BitUnsigned, Convert, Member, One, OpaqueKeys, Zero},
142 ConsensusEngineId, DispatchError, KeyTypeId, Permill, RuntimeAppPublic,
143};
144use sp_staking::{offence::OffenceSeverity, SessionIndex};
145
146pub use pallet::*;
147pub use weights::WeightInfo;
148
149#[cfg(any(feature = "try-runtime"))]
150use sp_runtime::TryRuntimeError;
151
152pub(crate) const LOG_TARGET: &str = "runtime::session";
153
154#[macro_export]
156macro_rules! log {
157 ($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
158 log::$level!(
159 target: crate::LOG_TARGET,
160 concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
161 )
162 };
163}
164
165pub trait ShouldEndSession<BlockNumber> {
167 fn should_end_session(now: BlockNumber) -> bool;
169}
170
171pub 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 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 (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 now + period
235 }
236 } else {
237 offset
238 };
239
240 (Some(next_session), Zero::zero())
245 }
246}
247
248pub trait SessionManager<ValidatorId> {
250 fn new_session(new_index: SessionIndex) -> Option<Vec<ValidatorId>>;
264 fn new_session_genesis(new_index: SessionIndex) -> Option<Vec<ValidatorId>> {
269 Self::new_session(new_index)
270 }
271 fn end_session(end_index: SessionIndex);
276 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
290pub trait SessionHandler<ValidatorId> {
292 const KEY_TYPE_IDS: &'static [KeyTypeId];
298
299 fn on_genesis_session<Ks: OpaqueKeys>(validators: &[(ValidatorId, Ks)]);
304
305 fn on_new_session<Ks: OpaqueKeys>(
315 changed: bool,
316 validators: &[(ValidatorId, Ks)],
317 queued_validators: &[(ValidatorId, Ks)],
318 );
319
320 fn on_before_session_ending() {}
325
326 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
380pub struct TestSessionHandler;
382impl<AId> SessionHandler<AId> for TestSessionHandler {
383 const KEY_TYPE_IDS: &'static [KeyTypeId] = &[sp_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#[frame_support::pallet]
391pub mod pallet {
392 use super::*;
393 use frame_support::pallet_prelude::*;
394 use frame_system::pallet_prelude::*;
395
396 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
398
399 #[pallet::pallet]
400 #[pallet::storage_version(STORAGE_VERSION)]
401 #[pallet::without_storage_info]
402 pub struct Pallet<T>(_);
403
404 #[pallet::config]
405 pub trait Config: frame_system::Config {
406 #[allow(deprecated)]
408 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
409
410 type ValidatorId: Member
412 + Parameter
413 + MaybeSerializeDeserialize
414 + MaxEncodedLen
415 + TryFrom<Self::AccountId>;
416
417 type ValidatorIdOf: Convert<Self::AccountId, Option<Self::ValidatorId>>;
425
426 type ShouldEndSession: ShouldEndSession<BlockNumberFor<Self>>;
428
429 type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
433
434 type SessionManager: SessionManager<Self::ValidatorId>;
436
437 type SessionHandler: SessionHandler<Self::ValidatorId>;
439
440 type Keys: OpaqueKeys + Member + Parameter + MaybeSerializeDeserialize;
442
443 type DisablingStrategy: DisablingStrategy<Self>;
445
446 type WeightInfo: WeightInfo;
448
449 type Currency: Mutate<Self::AccountId>
451 + HoldMutate<Self::AccountId, Reason: From<HoldReason>>;
452
453 #[pallet::constant]
455 type KeyDeposit: Get<
456 <<Self as Config>::Currency as Inspect<<Self as frame_system::Config>::AccountId>>::Balance,
457 >;
458 }
459
460 #[pallet::genesis_config]
461 #[derive(frame_support::DefaultNoBound)]
462 pub struct GenesisConfig<T: Config> {
463 pub keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>,
467 pub non_authority_keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>,
471 }
472
473 #[pallet::genesis_build]
474 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
475 fn build(&self) {
476 if T::SessionHandler::KEY_TYPE_IDS.len() != T::Keys::key_ids().len() {
477 panic!("Number of keys in session handler and session keys does not match");
478 }
479
480 T::SessionHandler::KEY_TYPE_IDS
481 .iter()
482 .zip(T::Keys::key_ids())
483 .enumerate()
484 .for_each(|(i, (sk, kk))| {
485 if sk != kk {
486 panic!(
487 "Session handler and session key expect different key type at index: {}",
488 i,
489 );
490 }
491 });
492
493 for (account, val, keys) in
494 self.keys.iter().chain(self.non_authority_keys.iter()).cloned()
495 {
496 Pallet::<T>::inner_set_keys(&val, keys)
497 .expect("genesis config must not contain duplicates; qed");
498 if frame_system::Pallet::<T>::inc_consumers_without_limit(&account).is_err() {
499 frame_system::Pallet::<T>::inc_providers(&account);
504 }
505 }
506
507 let initial_validators_0 =
508 T::SessionManager::new_session_genesis(0).unwrap_or_else(|| {
509 frame_support::print(
510 "No initial validator provided by `SessionManager`, use \
511 session config keys to generate initial validator set.",
512 );
513 self.keys.iter().map(|x| x.1.clone()).collect()
514 });
515
516 let initial_validators_1 = T::SessionManager::new_session_genesis(1)
517 .unwrap_or_else(|| initial_validators_0.clone());
518
519 let queued_keys: Vec<_> = initial_validators_1
520 .into_iter()
521 .filter_map(|v| Pallet::<T>::load_keys(&v).map(|k| (v, k)))
522 .collect();
523
524 T::SessionHandler::on_genesis_session::<T::Keys>(&queued_keys);
526
527 Validators::<T>::put(initial_validators_0);
528 QueuedKeys::<T>::put(queued_keys);
529
530 T::SessionManager::start_session(0);
531 }
532 }
533
534 #[pallet::composite_enum]
536 pub enum HoldReason {
537 #[codec(index = 0)]
539 Keys,
540 }
541
542 #[pallet::storage]
544 pub type Validators<T: Config> = StorageValue<_, Vec<T::ValidatorId>, ValueQuery>;
545
546 #[pallet::storage]
548 pub type CurrentIndex<T> = StorageValue<_, SessionIndex, ValueQuery>;
549
550 #[pallet::storage]
553 pub type QueuedChanged<T> = StorageValue<_, bool, ValueQuery>;
554
555 #[pallet::storage]
558 pub type QueuedKeys<T: Config> = StorageValue<_, Vec<(T::ValidatorId, T::Keys)>, ValueQuery>;
559
560 #[pallet::storage]
566 pub type DisabledValidators<T> = StorageValue<_, Vec<(u32, OffenceSeverity)>, ValueQuery>;
567
568 #[pallet::storage]
570 pub type NextKeys<T: Config> =
571 StorageMap<_, Twox64Concat, T::ValidatorId, T::Keys, OptionQuery>;
572
573 #[pallet::storage]
575 pub type KeyOwner<T: Config> =
576 StorageMap<_, Twox64Concat, (KeyTypeId, Vec<u8>), T::ValidatorId, OptionQuery>;
577
578 #[pallet::event]
579 #[pallet::generate_deposit(pub(super) fn deposit_event)]
580 pub enum Event<T: Config> {
581 NewSession { session_index: SessionIndex },
584 NewQueued,
587 ValidatorDisabled { validator: T::ValidatorId },
589 ValidatorReenabled { validator: T::ValidatorId },
591 }
592
593 #[pallet::error]
595 pub enum Error<T> {
596 InvalidProof,
598 NoAssociatedValidatorId,
600 DuplicatedKey,
602 NoKeys,
604 NoAccount,
606 }
607
608 #[pallet::hooks]
609 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
610 fn on_initialize(n: BlockNumberFor<T>) -> Weight {
613 if T::ShouldEndSession::should_end_session(n) {
614 Self::rotate_session();
615 T::BlockWeights::get().max_block
616 } else {
617 Weight::zero()
621 }
622 }
623
624 #[cfg(feature = "try-runtime")]
625 fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
626 Self::do_try_state()
627 }
628 }
629
630 #[pallet::call]
631 impl<T: Config> Pallet<T> {
632 #[pallet::call_index(0)]
642 #[pallet::weight(T::WeightInfo::set_keys())]
643 pub fn set_keys(origin: OriginFor<T>, keys: T::Keys, proof: Vec<u8>) -> DispatchResult {
644 let who = ensure_signed(origin)?;
645 ensure!(keys.ownership_proof_is_valid(&proof), Error::<T>::InvalidProof);
646
647 Self::do_set_keys(&who, keys)?;
648 Ok(())
649 }
650
651 #[pallet::call_index(1)]
664 #[pallet::weight(T::WeightInfo::purge_keys())]
665 pub fn purge_keys(origin: OriginFor<T>) -> DispatchResult {
666 let who = ensure_signed(origin)?;
667 Self::do_purge_keys(&who)?;
668 Ok(())
669 }
670 }
671
672 #[cfg(feature = "runtime-benchmarks")]
673 impl<T: Config> Pallet<T> {
674 pub fn ensure_can_pay_key_deposit(who: &T::AccountId) -> Result<(), DispatchError> {
679 use frame_support::traits::tokens::{Fortitude, Preservation};
680 let deposit = T::KeyDeposit::get();
681 let has = T::Currency::reducible_balance(who, Preservation::Protect, Fortitude::Force);
682 if let Some(deficit) = deposit.checked_sub(&has) {
683 T::Currency::mint_into(who, deficit.max(T::Currency::minimum_balance()))
684 .map(|_inc| ())
685 } else {
686 Ok(())
687 }
688 }
689 }
690}
691
692impl<T: Config> Pallet<T> {
693 pub fn validators() -> Vec<T::ValidatorId> {
695 Validators::<T>::get()
696 }
697
698 pub fn current_index() -> SessionIndex {
700 CurrentIndex::<T>::get()
701 }
702
703 pub fn queued_keys() -> Vec<(T::ValidatorId, T::Keys)> {
705 QueuedKeys::<T>::get()
706 }
707
708 pub fn disabled_validators() -> Vec<u32> {
710 DisabledValidators::<T>::get().iter().map(|(i, _)| *i).collect()
711 }
712
713 pub fn rotate_session() {
717 let session_index = CurrentIndex::<T>::get();
718 let changed = QueuedChanged::<T>::get();
719
720 T::SessionHandler::on_before_session_ending();
722 T::SessionManager::end_session(session_index);
723 log!(trace, "ending_session {:?}", session_index);
724
725 let session_keys = QueuedKeys::<T>::get();
727 let validators =
728 session_keys.iter().map(|(validator, _)| validator.clone()).collect::<Vec<_>>();
729 Validators::<T>::put(&validators);
730
731 if changed {
732 log!(trace, "resetting disabled validators");
733 DisabledValidators::<T>::kill();
735 }
736
737 let session_index = session_index + 1;
739 CurrentIndex::<T>::put(session_index);
740 T::SessionManager::start_session(session_index);
741 log!(trace, "starting_session {:?}", session_index);
742
743 let maybe_next_validators = T::SessionManager::new_session(session_index + 1);
745 log!(
746 trace,
747 "planning_session {:?} with {:?} validators",
748 session_index + 1,
749 maybe_next_validators.as_ref().map(|v| v.len())
750 );
751 let (next_validators, next_identities_changed) =
752 if let Some(validators) = maybe_next_validators {
753 Self::deposit_event(Event::<T>::NewQueued);
757 (validators, true)
758 } else {
759 (Validators::<T>::get(), false)
760 };
761
762 let (queued_amalgamated, next_changed) = {
764 let mut changed = next_identities_changed;
767
768 let mut now_session_keys = session_keys.iter();
769 let mut check_next_changed = |keys: &T::Keys| {
770 if changed {
771 return;
772 }
773 if let Some((_, old_keys)) = now_session_keys.next() {
777 if old_keys != keys {
778 changed = true;
779 }
780 }
781 };
782 let queued_amalgamated =
783 next_validators
784 .into_iter()
785 .filter_map(|a| {
786 let k =
787 Self::load_keys(&a).or_else(|| {
788 log!(warn, "failed to load session key for {:?}, skipping for next session, maybe you need to set session keys for them?", a);
789 None
790 })?;
791 check_next_changed(&k);
792 Some((a, k))
793 })
794 .collect::<Vec<_>>();
795
796 (queued_amalgamated, changed)
797 };
798
799 QueuedKeys::<T>::put(queued_amalgamated.clone());
800 QueuedChanged::<T>::put(next_changed);
801
802 Self::deposit_event(Event::NewSession { session_index });
804
805 T::SessionHandler::on_new_session::<T::Keys>(changed, &session_keys, &queued_amalgamated);
807 }
808
809 pub fn upgrade_keys<Old, F>(upgrade: F)
825 where
826 Old: OpaqueKeys + Member + Decode,
827 F: Fn(T::ValidatorId, Old) -> T::Keys,
828 {
829 let old_ids = Old::key_ids();
830 let new_ids = T::Keys::key_ids();
831
832 NextKeys::<T>::translate::<Old, _>(|val, old_keys| {
834 for i in old_ids.iter() {
837 Self::clear_key_owner(*i, old_keys.get_raw(*i));
838 }
839
840 let new_keys = upgrade(val.clone(), old_keys);
841
842 for i in new_ids.iter() {
844 Self::put_key_owner(*i, new_keys.get_raw(*i), &val);
845 }
846
847 Some(new_keys)
848 });
849
850 let _ = QueuedKeys::<T>::translate::<Vec<(T::ValidatorId, Old)>, _>(|k| {
851 k.map(|k| {
852 k.into_iter()
853 .map(|(val, old_keys)| (val.clone(), upgrade(val, old_keys)))
854 .collect::<Vec<_>>()
855 })
856 });
857 }
858
859 fn do_set_keys(account: &T::AccountId, keys: T::Keys) -> DispatchResult {
864 let who = T::ValidatorIdOf::convert(account.clone())
865 .ok_or(Error::<T>::NoAssociatedValidatorId)?;
866
867 ensure!(frame_system::Pallet::<T>::can_inc_consumer(account), Error::<T>::NoAccount);
868
869 let old_keys = Self::inner_set_keys(&who, keys)?;
870
871 if old_keys.is_none() {
874 let deposit = T::KeyDeposit::get();
875 if !deposit.is_zero() {
876 T::Currency::hold(&HoldReason::Keys.into(), account, deposit)?;
877 }
878
879 let assertion = frame_system::Pallet::<T>::inc_consumers(account).is_ok();
880 debug_assert!(assertion, "can_inc_consumer() returned true; no change since; qed");
881 }
882
883 Ok(())
884 }
885
886 fn inner_set_keys(
893 who: &T::ValidatorId,
894 keys: T::Keys,
895 ) -> Result<Option<T::Keys>, DispatchError> {
896 let old_keys = Self::load_keys(who);
897
898 for id in T::Keys::key_ids() {
899 let key = keys.get_raw(*id);
900
901 ensure!(
903 Self::key_owner(*id, key).map_or(true, |owner| &owner == who),
904 Error::<T>::DuplicatedKey,
905 );
906 }
907
908 for id in T::Keys::key_ids() {
909 let key = keys.get_raw(*id);
910
911 if let Some(old) = old_keys.as_ref().map(|k| k.get_raw(*id)) {
912 if key == old {
913 continue
914 }
915
916 Self::clear_key_owner(*id, old);
917 }
918
919 Self::put_key_owner(*id, key, who);
920 }
921
922 Self::put_keys(who, &keys);
923 Ok(old_keys)
924 }
925
926 fn do_purge_keys(account: &T::AccountId) -> DispatchResult {
927 let who = T::ValidatorIdOf::convert(account.clone())
928 .or_else(|| T::ValidatorId::try_from(account.clone()).ok())
932 .ok_or(Error::<T>::NoAssociatedValidatorId)?;
933
934 let old_keys = Self::take_keys(&who).ok_or(Error::<T>::NoKeys)?;
935 for id in T::Keys::key_ids() {
936 let key_data = old_keys.get_raw(*id);
937 Self::clear_key_owner(*id, key_data);
938 }
939
940 let _ = T::Currency::release_all(
942 &HoldReason::Keys.into(),
943 account,
944 frame_support::traits::tokens::Precision::BestEffort,
945 );
946
947 frame_system::Pallet::<T>::dec_consumers(account);
948
949 Ok(())
950 }
951
952 pub fn load_keys(v: &T::ValidatorId) -> Option<T::Keys> {
953 NextKeys::<T>::get(v)
954 }
955
956 fn take_keys(v: &T::ValidatorId) -> Option<T::Keys> {
957 NextKeys::<T>::take(v)
958 }
959
960 fn put_keys(v: &T::ValidatorId, keys: &T::Keys) {
961 NextKeys::<T>::insert(v, keys);
962 }
963
964 pub fn key_owner(id: KeyTypeId, key_data: &[u8]) -> Option<T::ValidatorId> {
966 KeyOwner::<T>::get((id, key_data))
967 }
968
969 fn put_key_owner(id: KeyTypeId, key_data: &[u8], v: &T::ValidatorId) {
970 KeyOwner::<T>::insert((id, key_data), v)
971 }
972
973 fn clear_key_owner(id: KeyTypeId, key_data: &[u8]) {
974 KeyOwner::<T>::remove((id, key_data));
975 }
976
977 pub fn disable_index_with_severity(i: u32, severity: OffenceSeverity) -> bool {
983 if i >= Validators::<T>::decode_len().defensive_unwrap_or(0) as u32 {
984 return false;
985 }
986
987 DisabledValidators::<T>::mutate(|disabled| {
988 match disabled.binary_search_by_key(&i, |(index, _)| *index) {
989 Ok(index) => {
991 let current_severity = &mut disabled[index].1;
992 if severity > *current_severity {
993 log!(
994 trace,
995 "updating disablement severity of validator {:?} from {:?} to {:?}",
996 i,
997 *current_severity,
998 severity
999 );
1000 *current_severity = severity;
1001 }
1002 true
1003 },
1004 Err(index) => {
1006 log!(trace, "disabling validator {:?}", i);
1007 Self::deposit_event(Event::ValidatorDisabled {
1008 validator: Validators::<T>::get()[i as usize].clone(),
1009 });
1010 disabled.insert(index, (i, severity));
1011 T::SessionHandler::on_disabled(i);
1012 true
1013 },
1014 }
1015 })
1016 }
1017
1018 pub fn disable_index(i: u32) -> bool {
1021 let default_severity = OffenceSeverity::default();
1022 Self::disable_index_with_severity(i, default_severity)
1023 }
1024
1025 pub fn reenable_index(i: u32) -> bool {
1027 if i >= Validators::<T>::decode_len().defensive_unwrap_or(0) as u32 {
1028 return false;
1029 }
1030
1031 DisabledValidators::<T>::mutate(|disabled| {
1032 if let Ok(index) = disabled.binary_search_by_key(&i, |(index, _)| *index) {
1033 log!(trace, "reenabling validator {:?}", i);
1034 Self::deposit_event(Event::ValidatorReenabled {
1035 validator: Validators::<T>::get()[i as usize].clone(),
1036 });
1037 disabled.remove(index);
1038 return true;
1039 }
1040 false
1041 })
1042 }
1043
1044 pub fn validator_id_to_index(id: &T::ValidatorId) -> Option<u32> {
1047 Validators::<T>::get().iter().position(|i| i == id).map(|i| i as u32)
1048 }
1049
1050 pub fn report_offence(validator: T::ValidatorId, severity: OffenceSeverity) {
1053 let decision =
1054 T::DisablingStrategy::decision(&validator, severity, &DisabledValidators::<T>::get());
1055 log!(
1056 debug,
1057 "reporting offence for {:?} with {:?}, decision: {:?}",
1058 validator,
1059 severity,
1060 decision
1061 );
1062
1063 if let Some(offender_idx) = decision.disable {
1065 Self::disable_index_with_severity(offender_idx, severity);
1066 }
1067
1068 if let Some(reenable_idx) = decision.reenable {
1070 Self::reenable_index(reenable_idx);
1071 }
1072 }
1073
1074 #[cfg(any(test, feature = "try-runtime"))]
1075 pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1076 ensure!(
1078 DisabledValidators::<T>::get().windows(2).all(|pair| pair[0].0 <= pair[1].0),
1079 "DisabledValidators is not sorted"
1080 );
1081 Ok(())
1082 }
1083}
1084
1085impl<T: Config> ValidatorRegistration<T::ValidatorId> for Pallet<T> {
1086 fn is_registered(id: &T::ValidatorId) -> bool {
1087 Self::load_keys(id).is_some()
1088 }
1089}
1090
1091impl<T: Config> ValidatorSet<T::AccountId> for Pallet<T> {
1092 type ValidatorId = T::ValidatorId;
1093 type ValidatorIdOf = T::ValidatorIdOf;
1094
1095 fn session_index() -> sp_staking::SessionIndex {
1096 CurrentIndex::<T>::get()
1097 }
1098
1099 fn validators() -> Vec<Self::ValidatorId> {
1100 Validators::<T>::get()
1101 }
1102}
1103
1104impl<T: Config> EstimateNextNewSession<BlockNumberFor<T>> for Pallet<T> {
1105 fn average_session_length() -> BlockNumberFor<T> {
1106 T::NextSessionRotation::average_session_length()
1107 }
1108
1109 fn estimate_next_new_session(now: BlockNumberFor<T>) -> (Option<BlockNumberFor<T>>, Weight) {
1112 T::NextSessionRotation::estimate_next_session_rotation(now)
1113 }
1114}
1115
1116impl<T: Config> frame_support::traits::DisabledValidators for Pallet<T> {
1117 fn is_disabled(index: u32) -> bool {
1118 DisabledValidators::<T>::get().binary_search_by_key(&index, |(i, _)| *i).is_ok()
1119 }
1120
1121 fn disabled_validators() -> Vec<u32> {
1122 Self::disabled_validators()
1123 }
1124}
1125
1126pub struct FindAccountFromAuthorIndex<T, Inner>(core::marker::PhantomData<(T, Inner)>);
1130
1131impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::ValidatorId>
1132 for FindAccountFromAuthorIndex<T, Inner>
1133{
1134 fn find_author<'a, I>(digests: I) -> Option<T::ValidatorId>
1135 where
1136 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
1137 {
1138 let i = Inner::find_author(digests)?;
1139
1140 let validators = Validators::<T>::get();
1141 validators.get(i as usize).cloned()
1142 }
1143}