1#![cfg_attr(not(feature = "std"), no_std)]
78
79mod benchmarking;
80pub mod migration;
81mod mock;
82mod tests;
83pub mod weights;
84
85extern crate alloc;
86
87use alloc::{vec, vec::Vec};
88use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
89use frame_support::{
90 pallet_prelude::*,
91 traits::{
92 EstimateNextSessionRotation, Get, OneSessionHandler, ValidatorSet,
93 ValidatorSetWithIdentification,
94 },
95 BoundedSlice, WeakBoundedVec,
96};
97use frame_system::{
98 offchain::{CreateAuthorizedTransaction, SubmitTransaction},
99 pallet_prelude::*,
100};
101pub use pallet::*;
102use scale_info::TypeInfo;
103use sp_application_crypto::RuntimeAppPublic;
104use sp_runtime::{
105 offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef},
106 traits::{AtLeast32BitUnsigned, Convert, Saturating, TrailingZeroInput},
107 transaction_validity::TransactionValidityWithRefund,
108 Debug, PerThing, Perbill, Permill, SaturatedConversion,
109};
110use sp_staking::{
111 offence::{Kind, Offence, ReportOffence},
112 SessionIndex,
113};
114pub use weights::WeightInfo;
115
116pub mod sr25519 {
117 mod app_sr25519 {
118 use sp_application_crypto::{app_crypto, key_types::IM_ONLINE, sr25519};
119 app_crypto!(sr25519, IM_ONLINE);
120 }
121
122 sp_application_crypto::with_pair! {
123 pub type AuthorityPair = app_sr25519::Pair;
125 }
126
127 pub type AuthoritySignature = app_sr25519::Signature;
129
130 pub type AuthorityId = app_sr25519::Public;
132}
133
134pub mod ed25519 {
135 mod app_ed25519 {
136 use sp_application_crypto::{app_crypto, ed25519, key_types::IM_ONLINE};
137 app_crypto!(ed25519, IM_ONLINE);
138 }
139
140 sp_application_crypto::with_pair! {
141 pub type AuthorityPair = app_ed25519::Pair;
143 }
144
145 pub type AuthoritySignature = app_ed25519::Signature;
147
148 pub type AuthorityId = app_ed25519::Public;
150}
151
152const DB_PREFIX: &[u8] = b"parity/im-online-heartbeat/";
153const INCLUDE_THRESHOLD: u32 = 3;
156
157#[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo)]
163struct HeartbeatStatus<BlockNumber> {
164 pub session_index: SessionIndex,
166 pub sent_at: BlockNumber,
171}
172
173impl<BlockNumber: PartialEq + AtLeast32BitUnsigned + Copy> HeartbeatStatus<BlockNumber> {
174 fn is_recent(&self, session_index: SessionIndex, now: BlockNumber) -> bool {
187 self.session_index == session_index && self.sent_at + INCLUDE_THRESHOLD.into() > now
188 }
189}
190
191#[cfg_attr(test, derive(PartialEq))]
193enum OffchainErr<BlockNumber> {
194 TooEarly,
195 WaitingForInclusion(BlockNumber),
196 AlreadyOnline(u32),
197 FailedSigning,
198 FailedToAcquireLock,
199 SubmitTransaction,
200}
201
202impl<BlockNumber: core::fmt::Debug> core::fmt::Debug for OffchainErr<BlockNumber> {
203 fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
204 match *self {
205 OffchainErr::TooEarly => write!(fmt, "Too early to send heartbeat."),
206 OffchainErr::WaitingForInclusion(ref block) => {
207 write!(fmt, "Heartbeat already sent at {:?}. Waiting for inclusion.", block)
208 },
209 OffchainErr::AlreadyOnline(auth_idx) => {
210 write!(fmt, "Authority {} is already online", auth_idx)
211 },
212 OffchainErr::FailedSigning => write!(fmt, "Failed to sign heartbeat"),
213 OffchainErr::FailedToAcquireLock => write!(fmt, "Failed to acquire lock"),
214 OffchainErr::SubmitTransaction => write!(fmt, "Failed to submit transaction"),
215 }
216 }
217}
218
219pub type AuthIndex = u32;
220
221#[derive(Encode, Decode, DecodeWithMemTracking, Clone, PartialEq, Eq, Debug, TypeInfo)]
223pub struct Heartbeat<BlockNumber>
224where
225 BlockNumber: PartialEq + Eq + Decode + Encode,
226{
227 pub block_number: BlockNumber,
229 pub session_index: SessionIndex,
231 pub authority_index: AuthIndex,
233 pub validators_len: u32,
235}
236
237pub type ValidatorId<T> = <<T as Config>::ValidatorSet as ValidatorSet<
239 <T as frame_system::Config>::AccountId,
240>>::ValidatorId;
241
242pub type IdentificationTuple<T> = (
245 ValidatorId<T>,
246 <<T as Config>::ValidatorSet as ValidatorSetWithIdentification<
247 <T as frame_system::Config>::AccountId,
248 >>::Identification,
249);
250
251type OffchainResult<T, A> = Result<A, OffchainErr<BlockNumberFor<T>>>;
252
253#[frame_support::pallet]
254pub mod pallet {
255 use super::*;
256
257 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
259
260 #[pallet::pallet]
261 #[pallet::storage_version(STORAGE_VERSION)]
262 pub struct Pallet<T>(_);
263
264 #[pallet::config]
265 pub trait Config: CreateAuthorizedTransaction<Call<Self>> + frame_system::Config {
270 type AuthorityId: Member
272 + Parameter
273 + RuntimeAppPublic
274 + Ord
275 + MaybeSerializeDeserialize
276 + MaxEncodedLen;
277
278 type MaxKeys: Get<u32>;
280
281 type MaxPeerInHeartbeats: Get<u32>;
283
284 #[allow(deprecated)]
286 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
287
288 type ValidatorSet: ValidatorSetWithIdentification<Self::AccountId>;
290
291 type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
299
300 type ReportUnresponsiveness: ReportOffence<
302 Self::AccountId,
303 IdentificationTuple<Self>,
304 UnresponsivenessOffence<IdentificationTuple<Self>>,
305 >;
306
307 #[pallet::constant]
312 type UnsignedPriority: Get<TransactionPriority>;
313
314 type WeightInfo: WeightInfo;
316 }
317
318 #[pallet::event]
319 #[pallet::generate_deposit(pub(super) fn deposit_event)]
320 pub enum Event<T: Config> {
321 HeartbeatReceived { authority_id: T::AuthorityId },
323 AllGood,
325 SomeOffline { offline: Vec<IdentificationTuple<T>> },
327 }
328
329 #[pallet::error]
330 pub enum Error<T> {
331 InvalidKey,
333 DuplicatedHeartbeat,
335 }
336
337 #[pallet::storage]
349 pub type HeartbeatAfter<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
350
351 #[pallet::storage]
353 pub type Keys<T: Config> =
354 StorageValue<_, WeakBoundedVec<T::AuthorityId, T::MaxKeys>, ValueQuery>;
355
356 #[pallet::storage]
358 pub type ReceivedHeartbeats<T: Config> =
359 StorageDoubleMap<_, Twox64Concat, SessionIndex, Twox64Concat, AuthIndex, bool>;
360
361 #[pallet::storage]
364 pub type AuthoredBlocks<T: Config> = StorageDoubleMap<
365 _,
366 Twox64Concat,
367 SessionIndex,
368 Twox64Concat,
369 ValidatorId<T>,
370 u32,
371 ValueQuery,
372 >;
373
374 #[pallet::genesis_config]
375 #[derive(frame_support::DefaultNoBound)]
376 pub struct GenesisConfig<T: Config> {
377 pub keys: Vec<T::AuthorityId>,
378 }
379
380 #[pallet::genesis_build]
381 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
382 fn build(&self) {
383 Pallet::<T>::initialize_keys(&self.keys);
384 }
385 }
386
387 #[pallet::call]
388 impl<T: Config> Pallet<T> {
389 #[pallet::call_index(0)]
393 #[pallet::weight(<T as Config>::WeightInfo::heartbeat(
394 heartbeat.validators_len,
395 ))]
396 #[pallet::weight_of_authorize(<T as Config>::WeightInfo::authorize_heartbeat(
397 heartbeat.validators_len,
398 ))]
399 #[pallet::authorize(Self::authorize_heartbeat_call)]
400 pub fn heartbeat(
401 origin: OriginFor<T>,
402 heartbeat: Heartbeat<BlockNumberFor<T>>,
403 _signature: <T::AuthorityId as RuntimeAppPublic>::Signature,
406 ) -> DispatchResult {
407 ensure_authorized(origin)?;
408
409 let current_session = T::ValidatorSet::session_index();
410 let exists =
411 ReceivedHeartbeats::<T>::contains_key(current_session, heartbeat.authority_index);
412 let keys = Keys::<T>::get();
413 let public = keys.get(heartbeat.authority_index as usize);
414 if let (false, Some(public)) = (exists, public) {
415 Self::deposit_event(Event::<T>::HeartbeatReceived { authority_id: public.clone() });
416
417 ReceivedHeartbeats::<T>::insert(current_session, heartbeat.authority_index, true);
418
419 Ok(())
420 } else if exists {
421 Err(Error::<T>::DuplicatedHeartbeat.into())
422 } else {
423 Err(Error::<T>::InvalidKey.into())
424 }
425 }
426 }
427
428 #[pallet::hooks]
429 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
430 fn offchain_worker(now: BlockNumberFor<T>) {
431 if sp_io::offchain::is_validator() {
433 for res in Self::send_heartbeats(now).into_iter().flatten() {
434 if let Err(e) = res {
435 log::debug!(
436 target: "runtime::im-online",
437 "Skipping heartbeat at {:?}: {:?}",
438 now,
439 e,
440 )
441 }
442 }
443 } else {
444 log::trace!(
445 target: "runtime::im-online",
446 "Skipping heartbeat at {:?}. Not a validator.",
447 now,
448 )
449 }
450 }
451
452 #[cfg(feature = "try-runtime")]
453 fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
454 Self::do_try_state()
455 }
456 }
457
458 pub(crate) const INVALID_VALIDATORS_LEN: u8 = 10;
461}
462
463impl<T: Config + pallet_authorship::Config>
466 pallet_authorship::EventHandler<ValidatorId<T>, BlockNumberFor<T>> for Pallet<T>
467{
468 fn note_author(author: ValidatorId<T>) {
469 Self::note_authorship(author);
470 }
471}
472
473impl<T: Config> Pallet<T> {
474 pub fn is_online(authority_index: AuthIndex) -> bool {
479 let current_validators = T::ValidatorSet::validators();
480
481 if authority_index >= current_validators.len() as u32 {
482 return false;
483 }
484
485 let authority = ¤t_validators[authority_index as usize];
486
487 Self::is_online_aux(authority_index, authority)
488 }
489
490 fn is_online_aux(authority_index: AuthIndex, authority: &ValidatorId<T>) -> bool {
491 let current_session = T::ValidatorSet::session_index();
492
493 ReceivedHeartbeats::<T>::contains_key(current_session, authority_index) ||
494 AuthoredBlocks::<T>::get(current_session, authority) != 0
495 }
496
497 pub fn received_heartbeat_in_current_session(authority_index: AuthIndex) -> bool {
500 let current_session = T::ValidatorSet::session_index();
501 ReceivedHeartbeats::<T>::contains_key(current_session, authority_index)
502 }
503
504 fn note_authorship(author: ValidatorId<T>) {
506 let current_session = T::ValidatorSet::session_index();
507
508 AuthoredBlocks::<T>::mutate(current_session, author, |authored| *authored += 1);
509 }
510
511 pub(crate) fn send_heartbeats(
512 block_number: BlockNumberFor<T>,
513 ) -> OffchainResult<T, impl Iterator<Item = OffchainResult<T, ()>>> {
514 const START_HEARTBEAT_RANDOM_PERIOD: Permill = Permill::from_percent(10);
515 const START_HEARTBEAT_FINAL_PERIOD: Permill = Permill::from_percent(80);
516
517 let random_choice = |progress: Permill| {
521 let session_length = T::NextSessionRotation::average_session_length();
524 let residual = Permill::from_rational(1u32, session_length.saturated_into());
525 let threshold: Permill = progress.saturating_pow(6).saturating_add(residual);
526
527 let seed = sp_io::offchain::random_seed();
528 let random = <u32>::decode(&mut TrailingZeroInput::new(seed.as_ref()))
529 .expect("input is padded with zeroes; qed");
530 let random = Permill::from_parts(random % Permill::ACCURACY);
531
532 random <= threshold
533 };
534
535 let should_heartbeat = if let (Some(progress), _) =
536 T::NextSessionRotation::estimate_current_session_progress(block_number)
537 {
538 progress >= START_HEARTBEAT_FINAL_PERIOD ||
545 progress >= START_HEARTBEAT_RANDOM_PERIOD && random_choice(progress)
546 } else {
547 let heartbeat_after = <HeartbeatAfter<T>>::get();
550 block_number >= heartbeat_after
551 };
552
553 if !should_heartbeat {
554 return Err(OffchainErr::TooEarly);
555 }
556
557 let session_index = T::ValidatorSet::session_index();
558 let validators_len = Keys::<T>::decode_len().unwrap_or_default() as u32;
559
560 Ok(Self::local_authority_keys().map(move |(authority_index, key)| {
561 Self::send_single_heartbeat(
562 authority_index,
563 key,
564 session_index,
565 block_number,
566 validators_len,
567 )
568 }))
569 }
570
571 fn send_single_heartbeat(
572 authority_index: u32,
573 key: T::AuthorityId,
574 session_index: SessionIndex,
575 block_number: BlockNumberFor<T>,
576 validators_len: u32,
577 ) -> OffchainResult<T, ()> {
578 let prepare_heartbeat = || -> OffchainResult<T, Call<T>> {
580 let heartbeat =
581 Heartbeat { block_number, session_index, authority_index, validators_len };
582
583 let signature = key.sign(&heartbeat.encode()).ok_or(OffchainErr::FailedSigning)?;
584
585 Ok(Call::heartbeat { heartbeat, signature })
586 };
587
588 if Self::is_online(authority_index) {
589 return Err(OffchainErr::AlreadyOnline(authority_index));
590 }
591
592 Self::with_heartbeat_lock(authority_index, session_index, block_number, || {
595 let call = prepare_heartbeat()?;
596 log::info!(
597 target: "runtime::im-online",
598 "[index: {:?}] Reporting im-online at block: {:?} (session: {:?}): {:?}",
599 authority_index,
600 block_number,
601 session_index,
602 call,
603 );
604
605 let xt = T::create_authorized_transaction(call.into());
606 SubmitTransaction::<T, Call<T>>::submit_transaction(xt)
607 .map_err(|_| OffchainErr::SubmitTransaction)?;
608
609 Ok(())
610 })
611 }
612
613 fn local_authority_keys() -> impl Iterator<Item = (u32, T::AuthorityId)> {
614 let authorities = Keys::<T>::get();
620
621 let mut local_keys = T::AuthorityId::all();
625
626 local_keys.sort();
627
628 authorities.into_iter().enumerate().filter_map(move |(index, authority)| {
629 local_keys
630 .binary_search(&authority)
631 .ok()
632 .map(|location| (index as u32, local_keys[location].clone()))
633 })
634 }
635
636 fn with_heartbeat_lock<R>(
637 authority_index: u32,
638 session_index: SessionIndex,
639 now: BlockNumberFor<T>,
640 f: impl FnOnce() -> OffchainResult<T, R>,
641 ) -> OffchainResult<T, R> {
642 let key = {
643 let mut key = DB_PREFIX.to_vec();
644 key.extend(authority_index.encode());
645 key
646 };
647 let storage = StorageValueRef::persistent(&key);
648 let res = storage.mutate(
649 |status: Result<Option<HeartbeatStatus<BlockNumberFor<T>>>, StorageRetrievalError>| {
650 match status {
655 Ok(Some(status)) if status.is_recent(session_index, now) => {
657 Err(OffchainErr::WaitingForInclusion(status.sent_at))
658 },
659 _ => Ok(HeartbeatStatus { session_index, sent_at: now }),
661 }
662 },
663 );
664 if let Err(MutateStorageError::ValueFunctionFailed(err)) = res {
665 return Err(err);
666 }
667
668 let mut new_status = res.map_err(|_| OffchainErr::FailedToAcquireLock)?;
669
670 let res = f();
672
673 if res.is_err() {
675 new_status.sent_at = 0u32.into();
676 storage.set(&new_status);
677 }
678
679 res
680 }
681
682 fn initialize_keys(keys: &[T::AuthorityId]) {
683 if !keys.is_empty() {
684 assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
685 let bounded_keys = <BoundedSlice<'_, _, T::MaxKeys>>::try_from(keys)
686 .expect("More than the maximum number of keys provided");
687 Keys::<T>::put(bounded_keys);
688 }
689 }
690
691 fn authorize_heartbeat_call(
697 _source: TransactionSource,
698 heartbeat: &Heartbeat<BlockNumberFor<T>>,
699 signature: &<T::AuthorityId as RuntimeAppPublic>::Signature,
700 ) -> TransactionValidityWithRefund {
701 if Pallet::<T>::is_online(heartbeat.authority_index) {
702 return Err(InvalidTransaction::Stale.into());
704 }
705
706 let current_session = T::ValidatorSet::session_index();
708 if heartbeat.session_index != current_session {
709 return Err(InvalidTransaction::Stale.into());
710 }
711
712 let keys = Keys::<T>::get();
714 if keys.len() as u32 != heartbeat.validators_len {
715 return Err(InvalidTransaction::Custom(INVALID_VALIDATORS_LEN).into());
716 }
717 let authority_id = match keys.get(heartbeat.authority_index as usize) {
718 Some(id) => id,
719 None => return Err(InvalidTransaction::BadProof.into()),
720 };
721
722 let signature_valid = heartbeat
724 .using_encoded(|encoded_heartbeat| authority_id.verify(&encoded_heartbeat, signature));
725
726 if !signature_valid {
727 return Err(InvalidTransaction::BadProof.into());
728 }
729
730 ValidTransaction::with_tag_prefix("ImOnline")
731 .priority(T::UnsignedPriority::get())
732 .and_provides((current_session, authority_id))
733 .longevity(
734 TryInto::<u64>::try_into(
735 T::NextSessionRotation::average_session_length() / 2u32.into(),
736 )
737 .unwrap_or(64_u64),
738 )
739 .propagate(true)
740 .build()
741 .map(|v| (v, Weight::zero()))
742 }
743
744 #[cfg(test)]
745 fn set_keys(keys: Vec<T::AuthorityId>) {
746 let bounded_keys = WeakBoundedVec::<_, T::MaxKeys>::try_from(keys)
747 .expect("More than the maximum number of keys provided");
748 Keys::<T>::put(bounded_keys);
749 }
750}
751
752#[cfg(any(feature = "try-runtime", test))]
753impl<T: Config> Pallet<T> {
754 pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
758 Self::try_state_keys()?;
759 Self::try_state_received_heartbeats()?;
760 Self::try_state_authored_blocks()?;
761
762 Ok(())
763 }
764
765 fn try_state_keys() -> Result<(), sp_runtime::TryRuntimeError> {
771 ensure!(
772 Keys::<T>::decode_len().unwrap_or_default() as u32 <= T::MaxKeys::get(),
773 "`Keys` must not hold more authorities than `MaxKeys`"
774 );
775
776 Ok(())
777 }
778
779 fn try_state_received_heartbeats() -> Result<(), sp_runtime::TryRuntimeError> {
786 let current_session = T::ValidatorSet::session_index();
787 let keys_len = Keys::<T>::decode_len().unwrap_or_default() as u32;
788
789 for (session, authority_index, _) in ReceivedHeartbeats::<T>::iter() {
790 ensure!(
791 session == current_session,
792 "`ReceivedHeartbeats` must not hold a heartbeat of a past session"
793 );
794 ensure!(
795 authority_index < keys_len,
796 "`ReceivedHeartbeats` must not hold a heartbeat of an unknown authority"
797 );
798 }
799
800 Ok(())
801 }
802
803 fn try_state_authored_blocks() -> Result<(), sp_runtime::TryRuntimeError> {
810 let current_session = T::ValidatorSet::session_index();
811
812 for (session, _, authored_blocks) in AuthoredBlocks::<T>::iter() {
813 ensure!(
814 session == current_session,
815 "`AuthoredBlocks` must not hold the authored blocks of a past session"
816 );
817 ensure!(
818 authored_blocks > 0,
819 "`AuthoredBlocks` must not hold an authority that has not authored a block"
820 );
821 }
822
823 Ok(())
824 }
825}
826
827impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
828 type Public = T::AuthorityId;
829}
830
831impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
832 type Key = T::AuthorityId;
833
834 fn on_genesis_session<'a, I: 'a>(validators: I)
835 where
836 I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
837 {
838 let keys = validators.map(|x| x.1).collect::<Vec<_>>();
839 Self::initialize_keys(&keys);
840 }
841
842 fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, _queued_validators: I)
843 where
844 I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
845 {
846 let block_number = <frame_system::Pallet<T>>::block_number();
850 let half_session = T::NextSessionRotation::average_session_length() / 2u32.into();
851 <HeartbeatAfter<T>>::put(block_number + half_session);
852
853 let keys = validators.map(|x| x.1).collect::<Vec<_>>();
855 let bounded_keys = WeakBoundedVec::<_, T::MaxKeys>::force_from(
856 keys,
857 Some(
858 "Warning: The session has more keys than expected. \
859 A runtime configuration adjustment may be needed.",
860 ),
861 );
862 Keys::<T>::put(bounded_keys);
863 }
864
865 fn on_before_session_ending() {
866 let session_index = T::ValidatorSet::session_index();
867 let keys = Keys::<T>::get();
868 let current_validators = T::ValidatorSet::validators();
869
870 let offenders = current_validators
871 .into_iter()
872 .enumerate()
873 .filter(|(index, id)| !Self::is_online_aux(*index as u32, id))
874 .filter_map(|(_, id)| {
875 <T::ValidatorSet as ValidatorSetWithIdentification<T::AccountId>>::IdentificationOf::convert(
876 id.clone()
877 ).map(|full_id| (id, full_id))
878 })
879 .collect::<Vec<IdentificationTuple<T>>>();
880
881 #[allow(deprecated)]
885 ReceivedHeartbeats::<T>::remove_prefix(T::ValidatorSet::session_index(), None);
886 #[allow(deprecated)]
887 AuthoredBlocks::<T>::remove_prefix(T::ValidatorSet::session_index(), None);
888
889 if offenders.is_empty() {
890 Self::deposit_event(Event::<T>::AllGood);
891 } else {
892 Self::deposit_event(Event::<T>::SomeOffline { offline: offenders.clone() });
893
894 let validator_set_count = keys.len() as u32;
895 let offence = UnresponsivenessOffence { session_index, validator_set_count, offenders };
896 if let Err(e) = T::ReportUnresponsiveness::report_offence(vec![], offence) {
897 log::error!(target: "runtime::im-online", "Failed to report offence: {:?}", e);
898 }
899 }
900 }
901
902 fn on_disabled(_i: u32) {
903 }
905}
906
907#[derive(Debug, TypeInfo)]
909#[cfg_attr(feature = "std", derive(Clone, PartialEq, Eq))]
910pub struct UnresponsivenessOffence<Offender> {
911 pub session_index: SessionIndex,
916 pub validator_set_count: u32,
918 pub offenders: Vec<Offender>,
920}
921
922impl<Offender: Clone> Offence<Offender> for UnresponsivenessOffence<Offender> {
923 const ID: Kind = *b"im-online:offlin";
924 type Slot = SessionIndex;
925
926 fn offenders(&self) -> Vec<Offender> {
927 self.offenders.clone()
928 }
929
930 fn session_index(&self) -> SessionIndex {
931 self.session_index
932 }
933
934 fn validator_set_count(&self) -> u32 {
935 self.validator_set_count
936 }
937
938 fn slot(&self) -> Self::Slot {
939 self.session_index
940 }
941
942 fn slash_fraction(&self, offenders: u32) -> Perbill {
943 if let Some(threshold) = offenders.checked_sub(self.validator_set_count / 10 + 1) {
947 let x = Perbill::from_rational(3 * threshold, self.validator_set_count);
948 x.saturating_mul(Perbill::from_percent(7))
949 } else {
950 Perbill::default()
951 }
952 }
953}