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 Defensive, EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get,
133 OneSessionHandler, ValidatorRegistration, ValidatorSet,
134 },
135 weights::Weight,
136 Parameter,
137};
138use frame_system::pallet_prelude::BlockNumberFor;
139use sp_runtime::{
140 traits::{AtLeast32BitUnsigned, Convert, Member, One, OpaqueKeys, Zero},
141 ConsensusEngineId, DispatchError, KeyTypeId, Permill, RuntimeAppPublic,
142};
143use sp_staking::{offence::OffenceSeverity, SessionIndex};
144
145pub use pallet::*;
146pub use weights::WeightInfo;
147
148#[cfg(any(feature = "try-runtime"))]
149use sp_runtime::TryRuntimeError;
150
151pub(crate) const LOG_TARGET: &str = "runtime::session";
152
153#[macro_export]
155macro_rules! log {
156 ($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
157 log::$level!(
158 target: crate::LOG_TARGET,
159 concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
160 )
161 };
162}
163
164pub trait ShouldEndSession<BlockNumber> {
166 fn should_end_session(now: BlockNumber) -> bool;
168}
169
170pub struct PeriodicSessions<Period, Offset>(PhantomData<(Period, Offset)>);
176
177impl<
178 BlockNumber: Rem<Output = BlockNumber> + Sub<Output = BlockNumber> + Zero + PartialOrd,
179 Period: Get<BlockNumber>,
180 Offset: Get<BlockNumber>,
181 > ShouldEndSession<BlockNumber> for PeriodicSessions<Period, Offset>
182{
183 fn should_end_session(now: BlockNumber) -> bool {
184 let offset = Offset::get();
185 now >= offset && ((now - offset) % Period::get()).is_zero()
186 }
187}
188
189impl<
190 BlockNumber: AtLeast32BitUnsigned + Clone,
191 Period: Get<BlockNumber>,
192 Offset: Get<BlockNumber>,
193 > EstimateNextSessionRotation<BlockNumber> for PeriodicSessions<Period, Offset>
194{
195 fn average_session_length() -> BlockNumber {
196 Period::get()
197 }
198
199 fn estimate_current_session_progress(now: BlockNumber) -> (Option<Permill>, Weight) {
200 let offset = Offset::get();
201 let period = Period::get();
202
203 let progress = if now >= offset {
207 let current = (now - offset) % period.clone() + One::one();
208 Some(Permill::from_rational(current, period))
209 } else {
210 Some(Permill::from_rational(now + One::one(), offset))
211 };
212
213 (progress, Zero::zero())
218 }
219
220 fn estimate_next_session_rotation(now: BlockNumber) -> (Option<BlockNumber>, Weight) {
221 let offset = Offset::get();
222 let period = Period::get();
223
224 let next_session = if now > offset {
225 let block_after_last_session = (now.clone() - offset) % period.clone();
226 if block_after_last_session > Zero::zero() {
227 now.saturating_add(period.saturating_sub(block_after_last_session))
228 } else {
229 now + period
234 }
235 } else {
236 offset
237 };
238
239 (Some(next_session), Zero::zero())
244 }
245}
246
247pub trait SessionManager<ValidatorId> {
249 fn new_session(new_index: SessionIndex) -> Option<Vec<ValidatorId>>;
263 fn new_session_genesis(new_index: SessionIndex) -> Option<Vec<ValidatorId>> {
268 Self::new_session(new_index)
269 }
270 fn end_session(end_index: SessionIndex);
275 fn start_session(start_index: SessionIndex);
279}
280
281impl<A> SessionManager<A> for () {
282 fn new_session(_: SessionIndex) -> Option<Vec<A>> {
283 None
284 }
285 fn start_session(_: SessionIndex) {}
286 fn end_session(_: SessionIndex) {}
287}
288
289pub trait SessionHandler<ValidatorId> {
291 const KEY_TYPE_IDS: &'static [KeyTypeId];
297
298 fn on_genesis_session<Ks: OpaqueKeys>(validators: &[(ValidatorId, Ks)]);
303
304 fn on_new_session<Ks: OpaqueKeys>(
314 changed: bool,
315 validators: &[(ValidatorId, Ks)],
316 queued_validators: &[(ValidatorId, Ks)],
317 );
318
319 fn on_before_session_ending() {}
324
325 fn on_disabled(validator_index: u32);
327}
328
329#[impl_trait_for_tuples::impl_for_tuples(1, 30)]
330#[tuple_types_custom_trait_bound(OneSessionHandler<AId>)]
331impl<AId> SessionHandler<AId> for Tuple {
332 for_tuples!(
333 const KEY_TYPE_IDS: &'static [KeyTypeId] = &[ #( <Tuple::Key as RuntimeAppPublic>::ID ),* ];
334 );
335
336 fn on_genesis_session<Ks: OpaqueKeys>(validators: &[(AId, Ks)]) {
337 for_tuples!(
338 #(
339 let our_keys: Box<dyn Iterator<Item=_>> = Box::new(validators.iter()
340 .filter_map(|k|
341 k.1.get::<Tuple::Key>(<Tuple::Key as RuntimeAppPublic>::ID).map(|k1| (&k.0, k1))
342 )
343 );
344
345 Tuple::on_genesis_session(our_keys);
346 )*
347 )
348 }
349
350 fn on_new_session<Ks: OpaqueKeys>(
351 changed: bool,
352 validators: &[(AId, Ks)],
353 queued_validators: &[(AId, Ks)],
354 ) {
355 for_tuples!(
356 #(
357 let our_keys: Box<dyn Iterator<Item=_>> = Box::new(validators.iter()
358 .filter_map(|k|
359 k.1.get::<Tuple::Key>(<Tuple::Key as RuntimeAppPublic>::ID).map(|k1| (&k.0, k1))
360 ));
361 let queued_keys: Box<dyn Iterator<Item=_>> = Box::new(queued_validators.iter()
362 .filter_map(|k|
363 k.1.get::<Tuple::Key>(<Tuple::Key as RuntimeAppPublic>::ID).map(|k1| (&k.0, k1))
364 ));
365 Tuple::on_new_session(changed, our_keys, queued_keys);
366 )*
367 )
368 }
369
370 fn on_before_session_ending() {
371 for_tuples!( #( Tuple::on_before_session_ending(); )* )
372 }
373
374 fn on_disabled(i: u32) {
375 for_tuples!( #( Tuple::on_disabled(i); )* )
376 }
377}
378
379pub struct TestSessionHandler;
381impl<AId> SessionHandler<AId> for TestSessionHandler {
382 const KEY_TYPE_IDS: &'static [KeyTypeId] = &[sp_runtime::key_types::DUMMY];
383 fn on_genesis_session<Ks: OpaqueKeys>(_: &[(AId, Ks)]) {}
384 fn on_new_session<Ks: OpaqueKeys>(_: bool, _: &[(AId, Ks)], _: &[(AId, Ks)]) {}
385 fn on_before_session_ending() {}
386 fn on_disabled(_: u32) {}
387}
388
389#[frame_support::pallet]
390pub mod pallet {
391 use super::*;
392 use frame_support::pallet_prelude::*;
393 use frame_system::pallet_prelude::*;
394
395 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
397
398 #[pallet::pallet]
399 #[pallet::storage_version(STORAGE_VERSION)]
400 #[pallet::without_storage_info]
401 pub struct Pallet<T>(_);
402
403 #[pallet::config]
404 pub trait Config: frame_system::Config {
405 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
407
408 type ValidatorId: Member
410 + Parameter
411 + MaybeSerializeDeserialize
412 + MaxEncodedLen
413 + TryFrom<Self::AccountId>;
414
415 type ValidatorIdOf: Convert<Self::AccountId, Option<Self::ValidatorId>>;
419
420 type ShouldEndSession: ShouldEndSession<BlockNumberFor<Self>>;
422
423 type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
427
428 type SessionManager: SessionManager<Self::ValidatorId>;
430
431 type SessionHandler: SessionHandler<Self::ValidatorId>;
433
434 type Keys: OpaqueKeys + Member + Parameter + MaybeSerializeDeserialize;
436
437 type DisablingStrategy: DisablingStrategy<Self>;
439
440 type WeightInfo: WeightInfo;
442 }
443
444 #[pallet::genesis_config]
445 #[derive(frame_support::DefaultNoBound)]
446 pub struct GenesisConfig<T: Config> {
447 pub keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>,
451 pub non_authority_keys: Vec<(T::AccountId, T::ValidatorId, T::Keys)>,
455 }
456
457 #[pallet::genesis_build]
458 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
459 fn build(&self) {
460 if T::SessionHandler::KEY_TYPE_IDS.len() != T::Keys::key_ids().len() {
461 panic!("Number of keys in session handler and session keys does not match");
462 }
463
464 T::SessionHandler::KEY_TYPE_IDS
465 .iter()
466 .zip(T::Keys::key_ids())
467 .enumerate()
468 .for_each(|(i, (sk, kk))| {
469 if sk != kk {
470 panic!(
471 "Session handler and session key expect different key type at index: {}",
472 i,
473 );
474 }
475 });
476
477 for (account, val, keys) in
478 self.keys.iter().chain(self.non_authority_keys.iter()).cloned()
479 {
480 Pallet::<T>::inner_set_keys(&val, keys)
481 .expect("genesis config must not contain duplicates; qed");
482 if frame_system::Pallet::<T>::inc_consumers_without_limit(&account).is_err() {
483 frame_system::Pallet::<T>::inc_providers(&account);
488 }
489 }
490
491 let initial_validators_0 =
492 T::SessionManager::new_session_genesis(0).unwrap_or_else(|| {
493 frame_support::print(
494 "No initial validator provided by `SessionManager`, use \
495 session config keys to generate initial validator set.",
496 );
497 self.keys.iter().map(|x| x.1.clone()).collect()
498 });
499
500 let initial_validators_1 = T::SessionManager::new_session_genesis(1)
501 .unwrap_or_else(|| initial_validators_0.clone());
502
503 let queued_keys: Vec<_> = initial_validators_1
504 .into_iter()
505 .filter_map(|v| Pallet::<T>::load_keys(&v).map(|k| (v, k)))
506 .collect();
507
508 T::SessionHandler::on_genesis_session::<T::Keys>(&queued_keys);
510
511 Validators::<T>::put(initial_validators_0);
512 QueuedKeys::<T>::put(queued_keys);
513
514 T::SessionManager::start_session(0);
515 }
516 }
517
518 #[pallet::storage]
520 pub type Validators<T: Config> = StorageValue<_, Vec<T::ValidatorId>, ValueQuery>;
521
522 #[pallet::storage]
524 pub type CurrentIndex<T> = StorageValue<_, SessionIndex, ValueQuery>;
525
526 #[pallet::storage]
529 pub type QueuedChanged<T> = StorageValue<_, bool, ValueQuery>;
530
531 #[pallet::storage]
534 pub type QueuedKeys<T: Config> = StorageValue<_, Vec<(T::ValidatorId, T::Keys)>, ValueQuery>;
535
536 #[pallet::storage]
542 pub type DisabledValidators<T> = StorageValue<_, Vec<(u32, OffenceSeverity)>, ValueQuery>;
543
544 #[pallet::storage]
546 pub type NextKeys<T: Config> =
547 StorageMap<_, Twox64Concat, T::ValidatorId, T::Keys, OptionQuery>;
548
549 #[pallet::storage]
551 pub type KeyOwner<T: Config> =
552 StorageMap<_, Twox64Concat, (KeyTypeId, Vec<u8>), T::ValidatorId, OptionQuery>;
553
554 #[pallet::event]
555 #[pallet::generate_deposit(pub(super) fn deposit_event)]
556 pub enum Event<T: Config> {
557 NewSession { session_index: SessionIndex },
560 ValidatorDisabled { validator: T::ValidatorId },
562 ValidatorReenabled { validator: T::ValidatorId },
564 }
565
566 #[pallet::error]
568 pub enum Error<T> {
569 InvalidProof,
571 NoAssociatedValidatorId,
573 DuplicatedKey,
575 NoKeys,
577 NoAccount,
579 }
580
581 #[pallet::hooks]
582 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
583 fn on_initialize(n: BlockNumberFor<T>) -> Weight {
586 if T::ShouldEndSession::should_end_session(n) {
587 Self::rotate_session();
588 T::BlockWeights::get().max_block
589 } else {
590 Weight::zero()
594 }
595 }
596
597 #[cfg(feature = "try-runtime")]
598 fn try_state(_n: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
599 Self::do_try_state()
600 }
601 }
602
603 #[pallet::call]
604 impl<T: Config> Pallet<T> {
605 #[pallet::call_index(0)]
615 #[pallet::weight(T::WeightInfo::set_keys())]
616 pub fn set_keys(origin: OriginFor<T>, keys: T::Keys, proof: Vec<u8>) -> DispatchResult {
617 let who = ensure_signed(origin)?;
618 ensure!(keys.ownership_proof_is_valid(&proof), Error::<T>::InvalidProof);
619
620 Self::do_set_keys(&who, keys)?;
621 Ok(())
622 }
623
624 #[pallet::call_index(1)]
637 #[pallet::weight(T::WeightInfo::purge_keys())]
638 pub fn purge_keys(origin: OriginFor<T>) -> DispatchResult {
639 let who = ensure_signed(origin)?;
640 Self::do_purge_keys(&who)?;
641 Ok(())
642 }
643 }
644}
645
646impl<T: Config> Pallet<T> {
647 pub fn validators() -> Vec<T::ValidatorId> {
649 Validators::<T>::get()
650 }
651
652 pub fn current_index() -> SessionIndex {
654 CurrentIndex::<T>::get()
655 }
656
657 pub fn queued_keys() -> Vec<(T::ValidatorId, T::Keys)> {
659 QueuedKeys::<T>::get()
660 }
661
662 pub fn disabled_validators() -> Vec<u32> {
664 DisabledValidators::<T>::get().iter().map(|(i, _)| *i).collect()
665 }
666
667 pub fn rotate_session() {
671 let session_index = CurrentIndex::<T>::get();
672 let changed = QueuedChanged::<T>::get();
673
674 T::SessionHandler::on_before_session_ending();
676 T::SessionManager::end_session(session_index);
677 log!(trace, "ending_session {:?}", session_index);
678
679 let session_keys = QueuedKeys::<T>::get();
681 let validators =
682 session_keys.iter().map(|(validator, _)| validator.clone()).collect::<Vec<_>>();
683 Validators::<T>::put(&validators);
684
685 if changed {
686 log!(trace, "resetting disabled validators");
687 DisabledValidators::<T>::take();
689 }
690
691 let session_index = session_index + 1;
693 CurrentIndex::<T>::put(session_index);
694 T::SessionManager::start_session(session_index);
695 log!(trace, "starting_session {:?}", session_index);
696
697 let maybe_next_validators = T::SessionManager::new_session(session_index + 1);
699 log!(
700 trace,
701 "planning_session {:?} with {:?} validators",
702 session_index + 1,
703 maybe_next_validators.as_ref().map(|v| v.len())
704 );
705 let (next_validators, next_identities_changed) =
706 if let Some(validators) = maybe_next_validators {
707 (validators, true)
711 } else {
712 (Validators::<T>::get(), false)
713 };
714
715 let (queued_amalgamated, next_changed) = {
717 let mut changed = next_identities_changed;
720
721 let mut now_session_keys = session_keys.iter();
722 let mut check_next_changed = |keys: &T::Keys| {
723 if changed {
724 return;
725 }
726 if let Some((_, old_keys)) = now_session_keys.next() {
730 if old_keys != keys {
731 changed = true;
732 }
733 }
734 };
735 let queued_amalgamated = next_validators
736 .into_iter()
737 .filter_map(|a| {
738 let k = Self::load_keys(&a)?;
739 check_next_changed(&k);
740 Some((a, k))
741 })
742 .collect::<Vec<_>>();
743
744 (queued_amalgamated, changed)
745 };
746
747 QueuedKeys::<T>::put(queued_amalgamated.clone());
748 QueuedChanged::<T>::put(next_changed);
749
750 Self::deposit_event(Event::NewSession { session_index });
752
753 T::SessionHandler::on_new_session::<T::Keys>(changed, &session_keys, &queued_amalgamated);
755 }
756
757 pub fn upgrade_keys<Old, F>(upgrade: F)
773 where
774 Old: OpaqueKeys + Member + Decode,
775 F: Fn(T::ValidatorId, Old) -> T::Keys,
776 {
777 let old_ids = Old::key_ids();
778 let new_ids = T::Keys::key_ids();
779
780 NextKeys::<T>::translate::<Old, _>(|val, old_keys| {
782 for i in old_ids.iter() {
785 Self::clear_key_owner(*i, old_keys.get_raw(*i));
786 }
787
788 let new_keys = upgrade(val.clone(), old_keys);
789
790 for i in new_ids.iter() {
792 Self::put_key_owner(*i, new_keys.get_raw(*i), &val);
793 }
794
795 Some(new_keys)
796 });
797
798 let _ = QueuedKeys::<T>::translate::<Vec<(T::ValidatorId, Old)>, _>(|k| {
799 k.map(|k| {
800 k.into_iter()
801 .map(|(val, old_keys)| (val.clone(), upgrade(val, old_keys)))
802 .collect::<Vec<_>>()
803 })
804 });
805 }
806
807 fn do_set_keys(account: &T::AccountId, keys: T::Keys) -> DispatchResult {
812 let who = T::ValidatorIdOf::convert(account.clone())
813 .ok_or(Error::<T>::NoAssociatedValidatorId)?;
814
815 ensure!(frame_system::Pallet::<T>::can_inc_consumer(account), Error::<T>::NoAccount);
816 let old_keys = Self::inner_set_keys(&who, keys)?;
817 if old_keys.is_none() {
818 let assertion = frame_system::Pallet::<T>::inc_consumers(account).is_ok();
819 debug_assert!(assertion, "can_inc_consumer() returned true; no change since; qed");
820 }
821
822 Ok(())
823 }
824
825 fn inner_set_keys(
832 who: &T::ValidatorId,
833 keys: T::Keys,
834 ) -> Result<Option<T::Keys>, DispatchError> {
835 let old_keys = Self::load_keys(who);
836
837 for id in T::Keys::key_ids() {
838 let key = keys.get_raw(*id);
839
840 ensure!(
842 Self::key_owner(*id, key).map_or(true, |owner| &owner == who),
843 Error::<T>::DuplicatedKey,
844 );
845 }
846
847 for id in T::Keys::key_ids() {
848 let key = keys.get_raw(*id);
849
850 if let Some(old) = old_keys.as_ref().map(|k| k.get_raw(*id)) {
851 if key == old {
852 continue
853 }
854
855 Self::clear_key_owner(*id, old);
856 }
857
858 Self::put_key_owner(*id, key, who);
859 }
860
861 Self::put_keys(who, &keys);
862 Ok(old_keys)
863 }
864
865 fn do_purge_keys(account: &T::AccountId) -> DispatchResult {
866 let who = T::ValidatorIdOf::convert(account.clone())
867 .or_else(|| T::ValidatorId::try_from(account.clone()).ok())
871 .ok_or(Error::<T>::NoAssociatedValidatorId)?;
872
873 let old_keys = Self::take_keys(&who).ok_or(Error::<T>::NoKeys)?;
874 for id in T::Keys::key_ids() {
875 let key_data = old_keys.get_raw(*id);
876 Self::clear_key_owner(*id, key_data);
877 }
878 frame_system::Pallet::<T>::dec_consumers(account);
879
880 Ok(())
881 }
882
883 fn load_keys(v: &T::ValidatorId) -> Option<T::Keys> {
884 NextKeys::<T>::get(v)
885 }
886
887 fn take_keys(v: &T::ValidatorId) -> Option<T::Keys> {
888 NextKeys::<T>::take(v)
889 }
890
891 fn put_keys(v: &T::ValidatorId, keys: &T::Keys) {
892 NextKeys::<T>::insert(v, keys);
893 }
894
895 pub fn key_owner(id: KeyTypeId, key_data: &[u8]) -> Option<T::ValidatorId> {
897 KeyOwner::<T>::get((id, key_data))
898 }
899
900 fn put_key_owner(id: KeyTypeId, key_data: &[u8], v: &T::ValidatorId) {
901 KeyOwner::<T>::insert((id, key_data), v)
902 }
903
904 fn clear_key_owner(id: KeyTypeId, key_data: &[u8]) {
905 KeyOwner::<T>::remove((id, key_data));
906 }
907
908 pub fn disable_index_with_severity(i: u32, severity: OffenceSeverity) -> bool {
914 if i >= Validators::<T>::decode_len().defensive_unwrap_or(0) as u32 {
915 return false;
916 }
917
918 DisabledValidators::<T>::mutate(|disabled| {
919 match disabled.binary_search_by_key(&i, |(index, _)| *index) {
920 Ok(index) => {
922 let current_severity = &mut disabled[index].1;
923 if severity > *current_severity {
924 log!(
925 trace,
926 "updating disablement severity of validator {:?} from {:?} to {:?}",
927 i,
928 *current_severity,
929 severity
930 );
931 *current_severity = severity;
932 }
933 true
934 },
935 Err(index) => {
937 log!(trace, "disabling validator {:?}", i);
938 Self::deposit_event(Event::ValidatorDisabled {
939 validator: Validators::<T>::get()[index as usize].clone(),
940 });
941 disabled.insert(index, (i, severity));
942 T::SessionHandler::on_disabled(i);
943 true
944 },
945 }
946 })
947 }
948
949 pub fn disable_index(i: u32) -> bool {
952 let default_severity = OffenceSeverity::default();
953 Self::disable_index_with_severity(i, default_severity)
954 }
955
956 pub fn disable(c: &T::ValidatorId) -> bool {
962 Validators::<T>::get()
963 .iter()
964 .position(|i| i == c)
965 .map(|i| Self::disable_index(i as u32))
966 .unwrap_or(false)
967 }
968
969 pub fn reenable_index(i: u32) -> bool {
971 if i >= Validators::<T>::decode_len().defensive_unwrap_or(0) as u32 {
972 return false;
973 }
974
975 DisabledValidators::<T>::mutate(|disabled| {
976 if let Ok(index) = disabled.binary_search_by_key(&i, |(index, _)| *index) {
977 log!(trace, "reenabling validator {:?}", i);
978 Self::deposit_event(Event::ValidatorReenabled {
979 validator: Validators::<T>::get()[index as usize].clone(),
980 });
981 disabled.remove(index);
982 return true;
983 }
984 false
985 })
986 }
987
988 pub fn validator_id_to_index(id: &T::ValidatorId) -> Option<u32> {
991 Validators::<T>::get().iter().position(|i| i == id).map(|i| i as u32)
992 }
993
994 pub fn report_offence(validator: T::ValidatorId, severity: OffenceSeverity) {
997 log!(trace, "reporting offence for {:?} with {:?}", validator, severity);
998 let decision =
999 T::DisablingStrategy::decision(&validator, severity, &DisabledValidators::<T>::get());
1000
1001 if let Some(offender_idx) = decision.disable {
1003 Self::disable_index_with_severity(offender_idx, severity);
1004 }
1005
1006 if let Some(reenable_idx) = decision.reenable {
1008 Self::reenable_index(reenable_idx);
1009 }
1010 }
1011
1012 #[cfg(any(test, feature = "try-runtime"))]
1013 pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
1014 ensure!(
1016 DisabledValidators::<T>::get().windows(2).all(|pair| pair[0].0 <= pair[1].0),
1017 "DisabledValidators is not sorted"
1018 );
1019 Ok(())
1020 }
1021}
1022
1023impl<T: Config> ValidatorRegistration<T::ValidatorId> for Pallet<T> {
1024 fn is_registered(id: &T::ValidatorId) -> bool {
1025 Self::load_keys(id).is_some()
1026 }
1027}
1028
1029impl<T: Config> ValidatorSet<T::AccountId> for Pallet<T> {
1030 type ValidatorId = T::ValidatorId;
1031 type ValidatorIdOf = T::ValidatorIdOf;
1032
1033 fn session_index() -> sp_staking::SessionIndex {
1034 CurrentIndex::<T>::get()
1035 }
1036
1037 fn validators() -> Vec<Self::ValidatorId> {
1038 Validators::<T>::get()
1039 }
1040}
1041
1042impl<T: Config> EstimateNextNewSession<BlockNumberFor<T>> for Pallet<T> {
1043 fn average_session_length() -> BlockNumberFor<T> {
1044 T::NextSessionRotation::average_session_length()
1045 }
1046
1047 fn estimate_next_new_session(now: BlockNumberFor<T>) -> (Option<BlockNumberFor<T>>, Weight) {
1050 T::NextSessionRotation::estimate_next_session_rotation(now)
1051 }
1052}
1053
1054impl<T: Config> frame_support::traits::DisabledValidators for Pallet<T> {
1055 fn is_disabled(index: u32) -> bool {
1056 DisabledValidators::<T>::get().binary_search_by_key(&index, |(i, _)| *i).is_ok()
1057 }
1058
1059 fn disabled_validators() -> Vec<u32> {
1060 Self::disabled_validators()
1061 }
1062}
1063
1064pub struct FindAccountFromAuthorIndex<T, Inner>(core::marker::PhantomData<(T, Inner)>);
1068
1069impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::ValidatorId>
1070 for FindAccountFromAuthorIndex<T, Inner>
1071{
1072 fn find_author<'a, I>(digests: I) -> Option<T::ValidatorId>
1073 where
1074 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
1075 {
1076 let i = Inner::find_author(digests)?;
1077
1078 let validators = Validators::<T>::get();
1079 validators.get(i as usize).cloned()
1080 }
1081}