1#![cfg_attr(not(feature = "std"), no_std)]
22#![warn(unused_must_use, unsafe_code, unused_variables, unused_must_use)]
23
24extern crate alloc;
25
26use alloc::{boxed::Box, vec, vec::Vec};
27use codec::{Decode, Encode};
28use frame_support::{
29 dispatch::{DispatchResultWithPostInfo, Pays},
30 ensure,
31 traits::{ConstU32, DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler},
32 weights::Weight,
33 BoundedVec, WeakBoundedVec,
34};
35use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor};
36use sp_consensus_babe::{
37 digests::{NextConfigDescriptor, NextEpochDescriptor, PreDigest},
38 AllowedSlots, BabeAuthorityWeight, BabeEpochConfiguration, ConsensusLog, Epoch,
39 EquivocationProof, Randomness as BabeRandomness, Slot, BABE_ENGINE_ID, RANDOMNESS_LENGTH,
40 RANDOMNESS_VRF_CONTEXT,
41};
42use sp_core::crypto::Wraps;
43use sp_runtime::{
44 generic::DigestItem,
45 traits::{IsMember, One, SaturatedConversion, Saturating, Zero},
46 ConsensusEngineId, Permill,
47};
48use sp_session::{GetSessionNumber, GetValidatorCount};
49use sp_staking::{offence::OffenceReportSystem, SessionIndex};
50
51pub use sp_consensus_babe::AuthorityId;
52
53const LOG_TARGET: &str = "runtime::babe";
54
55mod default_weights;
56mod equivocation;
57mod randomness;
58
59#[cfg(any(feature = "runtime-benchmarks", test))]
60mod benchmarking;
61#[cfg(all(feature = "std", test))]
62mod mock;
63#[cfg(all(feature = "std", test))]
64mod tests;
65
66pub use equivocation::{EquivocationOffence, EquivocationReportSystem};
67#[allow(deprecated)]
68pub use randomness::CurrentBlockRandomness;
69pub use randomness::{
70 ParentBlockRandomness, RandomnessFromOneEpochAgo, RandomnessFromTwoEpochsAgo,
71};
72
73pub use pallet::*;
74
75pub trait WeightInfo {
76 fn plan_config_change() -> Weight;
77 fn report_equivocation(validator_count: u32, max_nominators_per_validator: u32) -> Weight;
78}
79
80pub trait EpochChangeTrigger {
82 fn trigger<T: Config>(now: BlockNumberFor<T>);
85}
86
87pub struct ExternalTrigger;
90
91impl EpochChangeTrigger for ExternalTrigger {
92 fn trigger<T: Config>(_: BlockNumberFor<T>) {} }
94
95pub struct SameAuthoritiesForever;
98
99impl EpochChangeTrigger for SameAuthoritiesForever {
100 fn trigger<T: Config>(now: BlockNumberFor<T>) {
101 if Pallet::<T>::should_epoch_change(now) {
102 let authorities = Authorities::<T>::get();
103 let next_authorities = authorities.clone();
104
105 Pallet::<T>::enact_epoch_change(authorities, next_authorities, None);
106 }
107 }
108}
109
110const UNDER_CONSTRUCTION_SEGMENT_LENGTH: u32 = 256;
111
112#[frame_support::pallet]
113pub mod pallet {
114 use super::*;
115 use frame_support::pallet_prelude::*;
116 use frame_system::pallet_prelude::*;
117
118 #[pallet::pallet]
120 pub struct Pallet<T>(_);
121
122 #[pallet::config]
123 #[pallet::disable_frame_system_supertrait_check]
124 pub trait Config: pallet_timestamp::Config {
125 #[pallet::constant]
129 type EpochDuration: Get<u64>;
130
131 #[pallet::constant]
137 type ExpectedBlockTime: Get<Self::Moment>;
138
139 type EpochChangeTrigger: EpochChangeTrigger;
145
146 type DisabledValidators: DisabledValidators;
150
151 type WeightInfo: WeightInfo;
153
154 #[pallet::constant]
156 type MaxAuthorities: Get<u32>;
157
158 #[pallet::constant]
160 type MaxNominators: Get<u32>;
161
162 type KeyOwnerProof: Parameter + GetSessionNumber + GetValidatorCount;
166
167 type EquivocationReportSystem: OffenceReportSystem<
171 Option<Self::AccountId>,
172 (EquivocationProof<HeaderFor<Self>>, Self::KeyOwnerProof),
173 >;
174 }
175
176 #[pallet::error]
177 pub enum Error<T> {
178 InvalidEquivocationProof,
180 InvalidKeyOwnershipProof,
182 DuplicateOffenceReport,
184 InvalidConfiguration,
186 }
187
188 #[pallet::storage]
190 pub type EpochIndex<T> = StorageValue<_, u64, ValueQuery>;
191
192 #[pallet::storage]
194 pub type Authorities<T: Config> = StorageValue<
195 _,
196 WeakBoundedVec<(AuthorityId, BabeAuthorityWeight), T::MaxAuthorities>,
197 ValueQuery,
198 >;
199
200 #[pallet::storage]
203 pub type GenesisSlot<T> = StorageValue<_, Slot, ValueQuery>;
204
205 #[pallet::storage]
207 pub type CurrentSlot<T> = StorageValue<_, Slot, ValueQuery>;
208
209 #[pallet::storage]
223 pub type Randomness<T> = StorageValue<_, BabeRandomness, ValueQuery>;
224
225 #[pallet::storage]
227 pub type PendingEpochConfigChange<T> = StorageValue<_, NextConfigDescriptor>;
228
229 #[pallet::storage]
231 pub type NextRandomness<T> = StorageValue<_, BabeRandomness, ValueQuery>;
232
233 #[pallet::storage]
235 pub type NextAuthorities<T: Config> = StorageValue<
236 _,
237 WeakBoundedVec<(AuthorityId, BabeAuthorityWeight), T::MaxAuthorities>,
238 ValueQuery,
239 >;
240
241 #[pallet::storage]
251 pub type SegmentIndex<T> = StorageValue<_, u32, ValueQuery>;
252
253 #[pallet::storage]
255 pub type UnderConstruction<T: Config> = StorageMap<
256 _,
257 Twox64Concat,
258 u32,
259 BoundedVec<BabeRandomness, ConstU32<UNDER_CONSTRUCTION_SEGMENT_LENGTH>>,
260 ValueQuery,
261 >;
262
263 #[pallet::storage]
266 pub type Initialized<T> = StorageValue<_, Option<PreDigest>>;
267
268 #[pallet::storage]
273 pub type AuthorVrfRandomness<T> = StorageValue<_, Option<BabeRandomness>, ValueQuery>;
274
275 #[pallet::storage]
281 pub type EpochStart<T: Config> =
282 StorageValue<_, (BlockNumberFor<T>, BlockNumberFor<T>), ValueQuery>;
283
284 #[pallet::storage]
290 pub type Lateness<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
291
292 #[pallet::storage]
295 pub type EpochConfig<T> = StorageValue<_, BabeEpochConfiguration>;
296
297 #[pallet::storage]
300 pub type NextEpochConfig<T> = StorageValue<_, BabeEpochConfiguration>;
301
302 #[pallet::storage]
311 pub type SkippedEpochs<T> =
312 StorageValue<_, BoundedVec<(u64, SessionIndex), ConstU32<100>>, ValueQuery>;
313
314 #[derive(frame_support::DefaultNoBound)]
315 #[pallet::genesis_config]
316 pub struct GenesisConfig<T: Config> {
317 pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
318 pub epoch_config: BabeEpochConfiguration,
319 #[serde(skip)]
320 pub _config: core::marker::PhantomData<T>,
321 }
322
323 #[pallet::genesis_build]
324 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
325 fn build(&self) {
326 SegmentIndex::<T>::put(0);
327 Pallet::<T>::initialize_genesis_authorities(&self.authorities);
328 EpochConfig::<T>::put(&self.epoch_config);
329 }
330 }
331
332 #[pallet::hooks]
333 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
334 fn on_initialize(now: BlockNumberFor<T>) -> Weight {
336 Self::initialize(now);
337 Weight::zero()
338 }
339
340 fn on_finalize(_now: BlockNumberFor<T>) {
342 if let Some(pre_digest) = Initialized::<T>::take().flatten() {
348 let authority_index = pre_digest.authority_index();
349
350 if T::DisabledValidators::is_disabled(authority_index) {
351 panic!(
352 "Validator with index {:?} is disabled and should not be attempting to author blocks.",
353 authority_index,
354 );
355 }
356
357 if let Some(signature) = pre_digest.vrf_signature() {
358 let randomness: Option<BabeRandomness> = Authorities::<T>::get()
359 .get(authority_index as usize)
360 .and_then(|(authority, _)| {
361 let public = authority.as_inner_ref();
362 let transcript = sp_consensus_babe::make_vrf_transcript(
363 &Randomness::<T>::get(),
364 CurrentSlot::<T>::get(),
365 EpochIndex::<T>::get(),
366 );
367
368 debug_assert!({
372 use sp_core::crypto::VrfPublic;
373 public.vrf_verify(&transcript.clone().into_sign_data(), &signature)
374 });
375
376 public
377 .make_bytes(
378 RANDOMNESS_VRF_CONTEXT,
379 &transcript,
380 &signature.pre_output,
381 )
382 .ok()
383 });
384
385 if let Some(randomness) = pre_digest.is_primary().then(|| randomness).flatten()
386 {
387 Self::deposit_randomness(&randomness);
388 }
389
390 AuthorVrfRandomness::<T>::put(randomness);
391 }
392 }
393
394 Lateness::<T>::kill();
396 }
397 }
398
399 #[pallet::call]
400 impl<T: Config> Pallet<T> {
401 #[pallet::call_index(0)]
406 #[pallet::weight(<T as Config>::WeightInfo::report_equivocation(
407 key_owner_proof.validator_count(),
408 T::MaxNominators::get(),
409 ))]
410 pub fn report_equivocation(
411 origin: OriginFor<T>,
412 equivocation_proof: Box<EquivocationProof<HeaderFor<T>>>,
413 key_owner_proof: T::KeyOwnerProof,
414 ) -> DispatchResultWithPostInfo {
415 let reporter = ensure_signed(origin)?;
416 T::EquivocationReportSystem::process_evidence(
417 Some(reporter),
418 (*equivocation_proof, key_owner_proof),
419 )?;
420 Ok(Pays::No.into())
422 }
423
424 #[pallet::call_index(1)]
433 #[pallet::weight(<T as Config>::WeightInfo::report_equivocation(
434 key_owner_proof.validator_count(),
435 T::MaxNominators::get(),
436 ))]
437 pub fn report_equivocation_unsigned(
438 origin: OriginFor<T>,
439 equivocation_proof: Box<EquivocationProof<HeaderFor<T>>>,
440 key_owner_proof: T::KeyOwnerProof,
441 ) -> DispatchResultWithPostInfo {
442 ensure_none(origin)?;
443 T::EquivocationReportSystem::process_evidence(
444 None,
445 (*equivocation_proof, key_owner_proof),
446 )?;
447 Ok(Pays::No.into())
448 }
449
450 #[pallet::call_index(2)]
455 #[pallet::weight(<T as Config>::WeightInfo::plan_config_change())]
456 pub fn plan_config_change(
457 origin: OriginFor<T>,
458 config: NextConfigDescriptor,
459 ) -> DispatchResult {
460 ensure_root(origin)?;
461 match config {
462 NextConfigDescriptor::V1 { c, allowed_slots } => {
463 ensure!(
464 (c.0 != 0 || allowed_slots != AllowedSlots::PrimarySlots) && c.1 != 0,
465 Error::<T>::InvalidConfiguration
466 );
467 },
468 }
469 PendingEpochConfigChange::<T>::put(config);
470 Ok(())
471 }
472 }
473
474 #[pallet::validate_unsigned]
475 impl<T: Config> ValidateUnsigned for Pallet<T> {
476 type Call = Call<T>;
477 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
478 Self::validate_unsigned(source, call)
479 }
480
481 fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
482 Self::pre_dispatch(call)
483 }
484 }
485}
486
487impl<T: Config> FindAuthor<u32> for Pallet<T> {
488 fn find_author<'a, I>(digests: I) -> Option<u32>
489 where
490 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
491 {
492 for (id, mut data) in digests.into_iter() {
493 if id == BABE_ENGINE_ID {
494 let pre_digest: PreDigest = PreDigest::decode(&mut data).ok()?;
495 return Some(pre_digest.authority_index())
496 }
497 }
498
499 None
500 }
501}
502
503impl<T: Config> IsMember<AuthorityId> for Pallet<T> {
504 fn is_member(authority_id: &AuthorityId) -> bool {
505 Authorities::<T>::get().iter().any(|id| &id.0 == authority_id)
506 }
507}
508
509impl<T: Config> pallet_session::ShouldEndSession<BlockNumberFor<T>> for Pallet<T> {
510 fn should_end_session(now: BlockNumberFor<T>) -> bool {
511 Self::initialize(now);
516 Self::should_epoch_change(now)
517 }
518}
519
520impl<T: Config> Pallet<T> {
521 pub fn epoch_index() -> u64 {
523 EpochIndex::<T>::get()
524 }
525 pub fn authorities() -> WeakBoundedVec<(AuthorityId, BabeAuthorityWeight), T::MaxAuthorities> {
527 Authorities::<T>::get()
528 }
529 pub fn genesis_slot() -> Slot {
531 GenesisSlot::<T>::get()
532 }
533 pub fn current_slot() -> Slot {
535 CurrentSlot::<T>::get()
536 }
537 pub fn randomness() -> BabeRandomness {
539 Randomness::<T>::get()
540 }
541 pub fn initialized() -> Option<Option<PreDigest>> {
543 Initialized::<T>::get()
544 }
545 pub fn author_vrf_randomness() -> Option<BabeRandomness> {
547 AuthorVrfRandomness::<T>::get()
548 }
549 pub fn lateness() -> BlockNumberFor<T> {
551 Lateness::<T>::get()
552 }
553 pub fn epoch_config() -> Option<BabeEpochConfiguration> {
555 EpochConfig::<T>::get()
556 }
557 pub fn skipped_epochs() -> BoundedVec<(u64, SessionIndex), ConstU32<100>> {
559 SkippedEpochs::<T>::get()
560 }
561
562 pub fn slot_duration() -> T::Moment {
564 <T as pallet_timestamp::Config>::MinimumPeriod::get().saturating_mul(2u32.into())
567 }
568
569 pub fn should_epoch_change(now: BlockNumberFor<T>) -> bool {
572 now != One::one() && {
581 let diff = CurrentSlot::<T>::get().saturating_sub(Self::current_epoch_start());
582 *diff >= T::EpochDuration::get()
583 }
584 }
585
586 pub fn next_expected_epoch_change(now: BlockNumberFor<T>) -> Option<BlockNumberFor<T>> {
602 let next_slot = Self::current_epoch_start().saturating_add(T::EpochDuration::get());
603 next_slot.checked_sub(*CurrentSlot::<T>::get()).map(|slots_remaining| {
604 let blocks_remaining: BlockNumberFor<T> = slots_remaining.saturated_into();
606 now.saturating_add(blocks_remaining)
607 })
608 }
609
610 pub fn enact_epoch_change(
618 authorities: WeakBoundedVec<(AuthorityId, BabeAuthorityWeight), T::MaxAuthorities>,
619 next_authorities: WeakBoundedVec<(AuthorityId, BabeAuthorityWeight), T::MaxAuthorities>,
620 session_index: Option<SessionIndex>,
621 ) {
622 debug_assert!(Initialized::<T>::get().is_some());
625
626 if authorities.is_empty() {
627 log::warn!(target: LOG_TARGET, "Ignoring empty epoch change.");
628 return
629 }
630
631 let epoch_index = sp_consensus_babe::epoch_index(
640 CurrentSlot::<T>::get(),
641 GenesisSlot::<T>::get(),
642 T::EpochDuration::get(),
643 );
644
645 let current_epoch_index = EpochIndex::<T>::get();
646 if current_epoch_index.saturating_add(1) != epoch_index {
647 if let Some(session_index) = session_index {
650 SkippedEpochs::<T>::mutate(|skipped_epochs| {
651 if epoch_index < session_index as u64 {
652 log::warn!(
653 target: LOG_TARGET,
654 "Current epoch index {} is lower than session index {}.",
655 epoch_index,
656 session_index,
657 );
658
659 return
660 }
661
662 if skipped_epochs.is_full() {
663 skipped_epochs.remove(0);
667 }
668
669 skipped_epochs.force_push((epoch_index, session_index));
670 })
671 }
672 }
673
674 EpochIndex::<T>::put(epoch_index);
675 Authorities::<T>::put(authorities);
676
677 let next_epoch_index = epoch_index
679 .checked_add(1)
680 .expect("epoch indices will never reach 2^64 before the death of the universe; qed");
681
682 let randomness = Self::randomness_change_epoch(next_epoch_index);
685 Randomness::<T>::put(randomness);
686
687 NextAuthorities::<T>::put(&next_authorities);
689
690 EpochStart::<T>::mutate(|(previous_epoch_start_block, current_epoch_start_block)| {
692 *previous_epoch_start_block = core::mem::take(current_epoch_start_block);
693 *current_epoch_start_block = <frame_system::Pallet<T>>::block_number();
694 });
695
696 let next_randomness = NextRandomness::<T>::get();
699
700 let next_epoch = NextEpochDescriptor {
701 authorities: next_authorities.into_inner(),
702 randomness: next_randomness,
703 };
704 Self::deposit_consensus(ConsensusLog::NextEpochData(next_epoch));
705
706 if let Some(next_config) = NextEpochConfig::<T>::get() {
707 EpochConfig::<T>::put(next_config);
708 }
709
710 if let Some(pending_epoch_config_change) = PendingEpochConfigChange::<T>::take() {
711 let next_epoch_config: BabeEpochConfiguration =
712 pending_epoch_config_change.clone().into();
713 NextEpochConfig::<T>::put(next_epoch_config);
714
715 Self::deposit_consensus(ConsensusLog::NextConfigData(pending_epoch_config_change));
716 }
717 }
718
719 pub fn current_epoch_start() -> Slot {
724 sp_consensus_babe::epoch_start_slot(
725 EpochIndex::<T>::get(),
726 GenesisSlot::<T>::get(),
727 T::EpochDuration::get(),
728 )
729 }
730
731 pub fn current_epoch() -> Epoch {
733 Epoch {
734 epoch_index: EpochIndex::<T>::get(),
735 start_slot: Self::current_epoch_start(),
736 duration: T::EpochDuration::get(),
737 authorities: Authorities::<T>::get().into_inner(),
738 randomness: Randomness::<T>::get(),
739 config: EpochConfig::<T>::get()
740 .expect("EpochConfig is initialized in genesis; we never `take` or `kill` it; qed"),
741 }
742 }
743
744 pub fn next_epoch() -> Epoch {
747 let next_epoch_index = EpochIndex::<T>::get().checked_add(1).expect(
748 "epoch index is u64; it is always only incremented by one; \
749 if u64 is not enough we should crash for safety; qed.",
750 );
751
752 let start_slot = sp_consensus_babe::epoch_start_slot(
753 next_epoch_index,
754 GenesisSlot::<T>::get(),
755 T::EpochDuration::get(),
756 );
757
758 Epoch {
759 epoch_index: next_epoch_index,
760 start_slot,
761 duration: T::EpochDuration::get(),
762 authorities: NextAuthorities::<T>::get().into_inner(),
763 randomness: NextRandomness::<T>::get(),
764 config: NextEpochConfig::<T>::get().unwrap_or_else(|| {
765 EpochConfig::<T>::get().expect(
766 "EpochConfig is initialized in genesis; we never `take` or `kill` it; qed",
767 )
768 }),
769 }
770 }
771
772 fn deposit_consensus<U: Encode>(new: U) {
773 let log = DigestItem::Consensus(BABE_ENGINE_ID, new.encode());
774 <frame_system::Pallet<T>>::deposit_log(log)
775 }
776
777 fn deposit_randomness(randomness: &BabeRandomness) {
778 let segment_idx = SegmentIndex::<T>::get();
779 let mut segment = UnderConstruction::<T>::get(&segment_idx);
780 if segment.try_push(*randomness).is_ok() {
781 UnderConstruction::<T>::insert(&segment_idx, &segment);
783 } else {
784 let segment_idx = segment_idx + 1;
786 let bounded_randomness =
787 BoundedVec::<_, ConstU32<UNDER_CONSTRUCTION_SEGMENT_LENGTH>>::try_from(vec![
788 *randomness,
789 ])
790 .expect("UNDER_CONSTRUCTION_SEGMENT_LENGTH >= 1");
791 UnderConstruction::<T>::insert(&segment_idx, bounded_randomness);
792 SegmentIndex::<T>::put(&segment_idx);
793 }
794 }
795
796 fn initialize_genesis_authorities(authorities: &[(AuthorityId, BabeAuthorityWeight)]) {
797 if !authorities.is_empty() {
798 assert!(Authorities::<T>::get().is_empty(), "Authorities are already initialized!");
799 let bounded_authorities =
800 WeakBoundedVec::<_, T::MaxAuthorities>::try_from(authorities.to_vec())
801 .expect("Initial number of authorities should be lower than T::MaxAuthorities");
802 Authorities::<T>::put(&bounded_authorities);
803 NextAuthorities::<T>::put(&bounded_authorities);
804 }
805 }
806
807 fn initialize_genesis_epoch(genesis_slot: Slot) {
808 GenesisSlot::<T>::put(genesis_slot);
809 debug_assert_ne!(*GenesisSlot::<T>::get(), 0);
810
811 let next = NextEpochDescriptor {
815 authorities: Authorities::<T>::get().into_inner(),
816 randomness: Randomness::<T>::get(),
817 };
818
819 Self::deposit_consensus(ConsensusLog::NextEpochData(next));
820 }
821
822 fn initialize(now: BlockNumberFor<T>) {
823 let initialized = Initialized::<T>::get().is_some();
826 if initialized {
827 return
828 }
829
830 let pre_digest =
831 <frame_system::Pallet<T>>::digest()
832 .logs
833 .iter()
834 .filter_map(|s| s.as_pre_runtime())
835 .filter_map(|(id, mut data)| {
836 if id == BABE_ENGINE_ID {
837 PreDigest::decode(&mut data).ok()
838 } else {
839 None
840 }
841 })
842 .next();
843
844 if let Some(ref pre_digest) = pre_digest {
845 let current_slot = pre_digest.slot();
847
848 if *GenesisSlot::<T>::get() == 0 {
852 Self::initialize_genesis_epoch(current_slot)
853 }
854
855 let lateness = current_slot.saturating_sub(CurrentSlot::<T>::get() + 1);
857 let lateness = BlockNumberFor::<T>::from(*lateness as u32);
858
859 Lateness::<T>::put(lateness);
860 CurrentSlot::<T>::put(current_slot);
861 }
862
863 Initialized::<T>::put(pre_digest);
864
865 T::EpochChangeTrigger::trigger::<T>(now);
867 }
868
869 fn randomness_change_epoch(next_epoch_index: u64) -> BabeRandomness {
872 let this_randomness = NextRandomness::<T>::get();
873 let segment_idx: u32 = SegmentIndex::<T>::mutate(|s| core::mem::replace(s, 0));
874
875 let rho_size = (segment_idx.saturating_add(1) * UNDER_CONSTRUCTION_SEGMENT_LENGTH) as usize;
877
878 let next_randomness = compute_randomness(
879 this_randomness,
880 next_epoch_index,
881 (0..segment_idx).flat_map(|i| UnderConstruction::<T>::take(&i)),
882 Some(rho_size),
883 );
884 NextRandomness::<T>::put(&next_randomness);
885 this_randomness
886 }
887
888 pub(crate) fn session_index_for_epoch(epoch_index: u64) -> SessionIndex {
895 let skipped_epochs = SkippedEpochs::<T>::get();
896 match skipped_epochs.binary_search_by_key(&epoch_index, |(epoch_index, _)| *epoch_index) {
897 Ok(index) => skipped_epochs[index].1,
899 Err(0) => epoch_index.saturated_into::<u32>(),
902 Err(index) => {
904 let closest_skipped_epoch = skipped_epochs[index - 1];
907
908 let skipped_epochs = closest_skipped_epoch.0 - closest_skipped_epoch.1 as u64;
913 epoch_index.saturating_sub(skipped_epochs).saturated_into::<u32>()
914 },
915 }
916 }
917
918 pub fn submit_unsigned_equivocation_report(
923 equivocation_proof: EquivocationProof<HeaderFor<T>>,
924 key_owner_proof: T::KeyOwnerProof,
925 ) -> Option<()> {
926 T::EquivocationReportSystem::publish_evidence((equivocation_proof, key_owner_proof)).ok()
927 }
928}
929
930impl<T: Config> OnTimestampSet<T::Moment> for Pallet<T> {
931 fn on_timestamp_set(moment: T::Moment) {
932 let slot_duration = Self::slot_duration();
933 assert!(!slot_duration.is_zero(), "Babe slot duration cannot be zero.");
934
935 let timestamp_slot = moment / slot_duration;
936 let timestamp_slot = Slot::from(timestamp_slot.saturated_into::<u64>());
937
938 assert_eq!(
939 CurrentSlot::<T>::get(),
940 timestamp_slot,
941 "Timestamp slot must match `CurrentSlot`"
942 );
943 }
944}
945
946impl<T: Config> frame_support::traits::EstimateNextSessionRotation<BlockNumberFor<T>>
947 for Pallet<T>
948{
949 fn average_session_length() -> BlockNumberFor<T> {
950 T::EpochDuration::get().saturated_into()
951 }
952
953 fn estimate_current_session_progress(_now: BlockNumberFor<T>) -> (Option<Permill>, Weight) {
954 let elapsed = CurrentSlot::<T>::get().saturating_sub(Self::current_epoch_start()) + 1;
955
956 (
957 Some(Permill::from_rational(*elapsed, T::EpochDuration::get())),
958 T::DbWeight::get().reads(3),
960 )
961 }
962
963 fn estimate_next_session_rotation(
964 now: BlockNumberFor<T>,
965 ) -> (Option<BlockNumberFor<T>>, Weight) {
966 (
967 Self::next_expected_epoch_change(now),
968 T::DbWeight::get().reads(3),
970 )
971 }
972}
973
974impl<T: Config> frame_support::traits::Lateness<BlockNumberFor<T>> for Pallet<T> {
975 fn lateness(&self) -> BlockNumberFor<T> {
976 Lateness::<T>::get()
977 }
978}
979
980impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
981 type Public = AuthorityId;
982}
983
984impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T>
985where
986 T: pallet_session::Config,
987{
988 type Key = AuthorityId;
989
990 fn on_genesis_session<'a, I: 'a>(validators: I)
991 where
992 I: Iterator<Item = (&'a T::AccountId, AuthorityId)>,
993 {
994 let authorities = validators.map(|(_, k)| (k, 1)).collect::<Vec<_>>();
995 Self::initialize_genesis_authorities(&authorities);
996 }
997
998 fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, queued_validators: I)
999 where
1000 I: Iterator<Item = (&'a T::AccountId, AuthorityId)>,
1001 {
1002 let authorities = validators.map(|(_account, k)| (k, 1)).collect::<Vec<_>>();
1003 let bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::force_from(
1004 authorities,
1005 Some(
1006 "Warning: The session has more validators than expected. \
1007 A runtime configuration adjustment may be needed.",
1008 ),
1009 );
1010
1011 let next_authorities = queued_validators.map(|(_account, k)| (k, 1)).collect::<Vec<_>>();
1012 let next_bounded_authorities = WeakBoundedVec::<_, T::MaxAuthorities>::force_from(
1013 next_authorities,
1014 Some(
1015 "Warning: The session has more queued validators than expected. \
1016 A runtime configuration adjustment may be needed.",
1017 ),
1018 );
1019
1020 let session_index = <pallet_session::Pallet<T>>::current_index();
1021
1022 Self::enact_epoch_change(bounded_authorities, next_bounded_authorities, Some(session_index))
1023 }
1024
1025 fn on_disabled(i: u32) {
1026 Self::deposit_consensus(ConsensusLog::OnDisabled(i))
1027 }
1028}
1029
1030fn compute_randomness(
1035 last_epoch_randomness: BabeRandomness,
1036 epoch_index: u64,
1037 rho: impl Iterator<Item = BabeRandomness>,
1038 rho_size_hint: Option<usize>,
1039) -> BabeRandomness {
1040 let mut s = Vec::with_capacity(40 + rho_size_hint.unwrap_or(0) * RANDOMNESS_LENGTH);
1041 s.extend_from_slice(&last_epoch_randomness);
1042 s.extend_from_slice(&epoch_index.to_le_bytes());
1043
1044 for vrf_output in rho {
1045 s.extend_from_slice(&vrf_output[..]);
1046 }
1047
1048 sp_io::hashing::blake2_256(&s)
1049}
1050
1051pub mod migrations {
1052 use super::*;
1053 use frame_support::pallet_prelude::{StorageValue, ValueQuery};
1054
1055 pub trait BabePalletPrefix: Config {
1057 fn pallet_prefix() -> &'static str;
1058 }
1059
1060 struct __OldNextEpochConfig<T>(core::marker::PhantomData<T>);
1061 impl<T: BabePalletPrefix> frame_support::traits::StorageInstance for __OldNextEpochConfig<T> {
1062 fn pallet_prefix() -> &'static str {
1063 T::pallet_prefix()
1064 }
1065 const STORAGE_PREFIX: &'static str = "NextEpochConfig";
1066 }
1067
1068 type OldNextEpochConfig<T> =
1069 StorageValue<__OldNextEpochConfig<T>, Option<NextConfigDescriptor>, ValueQuery>;
1070
1071 pub fn add_epoch_configuration<T: BabePalletPrefix>(
1074 epoch_config: BabeEpochConfiguration,
1075 ) -> Weight {
1076 let mut writes = 0;
1077 let mut reads = 0;
1078
1079 if let Some(pending_change) = OldNextEpochConfig::<T>::get() {
1080 PendingEpochConfigChange::<T>::put(pending_change);
1081
1082 writes += 1;
1083 }
1084
1085 reads += 1;
1086
1087 OldNextEpochConfig::<T>::kill();
1088
1089 EpochConfig::<T>::put(epoch_config.clone());
1090 NextEpochConfig::<T>::put(epoch_config);
1091
1092 writes += 3;
1093
1094 T::DbWeight::get().reads_writes(reads, writes)
1095 }
1096}