1#![cfg_attr(not(feature = "std"), no_std)]
198
199extern crate alloc;
200
201#[cfg(any(feature = "runtime-benchmarks", test))]
202use crate::signed::{CalculateBaseDeposit, CalculatePageDeposit};
203use crate::verifier::{AsynchronousVerifier, Verifier};
204use alloc::{borrow::ToOwned, boxed::Box, vec::Vec};
205use codec::{Decode, Encode, MaxEncodedLen};
206use frame_election_provider_support::{
207 onchain, BoundedSupportsOf, DataProviderBounds, ElectionDataProvider, ElectionProvider,
208 InstantElectionProvider,
209};
210use frame_support::{
211 dispatch::PostDispatchInfo,
212 pallet_prelude::*,
213 traits::{Defensive, EnsureOrigin},
214 weights::WeightMeter,
215 DebugNoBound, Twox64Concat,
216};
217use frame_system::pallet_prelude::*;
218use scale_info::TypeInfo;
219use sp_arithmetic::{
220 traits::{CheckedAdd, Zero},
221 PerThing, UpperOf,
222};
223use sp_npos_elections::{EvaluateSupport, VoteWeight};
224use sp_runtime::{
225 traits::{Hash, Saturating},
226 SaturatedConversion,
227};
228
229#[cfg(test)]
230mod mock;
231#[macro_use]
232pub mod helpers;
233#[cfg(feature = "runtime-benchmarks")]
234pub mod benchmarking;
235
236pub const LOG_PREFIX: &'static str = "runtime::multiblock-election";
238
239macro_rules! clear_round_based_map {
240 ($map: ty, $round: expr) => {{
241 let __r = <$map>::clear_prefix($round, u32::MAX, None);
242 debug_assert!(__r.unique <= T::Pages::get(), "clearing map caused too many removals")
243 }};
244}
245
246pub mod signed;
248pub mod types;
250pub mod unsigned;
252pub mod verifier;
254pub mod weights;
256
257pub use pallet::*;
258pub use types::*;
259pub use weights::traits::pallet_election_provider_multi_block::WeightInfo;
260
261pub struct InitiateEmergencyPhase<T>(core::marker::PhantomData<T>);
263impl<T: Config> ElectionProvider for InitiateEmergencyPhase<T> {
264 type AccountId = T::AccountId;
265 type BlockNumber = BlockNumberFor<T>;
266 type DataProvider = T::DataProvider;
267 type Error = &'static str;
268 type Pages = T::Pages;
269 type MaxBackersPerWinner = <T::Verifier as Verifier>::MaxBackersPerWinner;
270 type MaxWinnersPerPage = <T::Verifier as Verifier>::MaxWinnersPerPage;
271 type MaxBackersPerWinnerFinal = <T::Verifier as Verifier>::MaxBackersPerWinnerFinal;
272
273 fn elect(_page: PageIndex) -> Result<BoundedSupportsOf<Self>, Self::Error> {
274 Pallet::<T>::phase_transition(Phase::Emergency);
275 Err("Emergency phase started.")
276 }
277
278 fn status() -> Result<Option<Weight>, ()> {
279 Ok(Some(Default::default()))
280 }
281
282 fn start() -> Result<(), Self::Error> {
283 Ok(())
284 }
285
286 fn duration() -> Self::BlockNumber {
287 Zero::zero()
288 }
289}
290
291impl<T: Config> InstantElectionProvider for InitiateEmergencyPhase<T> {
292 fn instant_elect(
293 _voters: Vec<VoterOf<T::MinerConfig>>,
294 _targets: Vec<Self::AccountId>,
295 _desired_targets: u32,
296 ) -> Result<BoundedSupportsOf<Self>, Self::Error> {
297 Self::elect(0)
298 }
299
300 fn bother() -> bool {
301 false
302 }
303}
304
305pub struct Continue<T>(core::marker::PhantomData<T>);
309impl<T: Config> ElectionProvider for Continue<T> {
310 type AccountId = T::AccountId;
311 type BlockNumber = BlockNumberFor<T>;
312 type DataProvider = T::DataProvider;
313 type Error = &'static str;
314 type Pages = T::Pages;
315 type MaxBackersPerWinner = <T::Verifier as Verifier>::MaxBackersPerWinner;
316 type MaxWinnersPerPage = <T::Verifier as Verifier>::MaxWinnersPerPage;
317 type MaxBackersPerWinnerFinal = <T::Verifier as Verifier>::MaxBackersPerWinnerFinal;
318
319 fn elect(_page: PageIndex) -> Result<BoundedSupportsOf<Self>, Self::Error> {
320 Err("'Continue' fallback will do nothing")
321 }
322
323 fn start() -> Result<(), Self::Error> {
324 Ok(())
325 }
326
327 fn duration() -> Self::BlockNumber {
328 Zero::zero()
329 }
330
331 fn status() -> Result<Option<Weight>, ()> {
332 Ok(Some(Default::default()))
333 }
334}
335
336impl<T: Config> InstantElectionProvider for Continue<T> {
337 fn instant_elect(
338 _voters: Vec<VoterOf<T::MinerConfig>>,
339 _targets: Vec<Self::AccountId>,
340 _desired_targets: u32,
341 ) -> Result<BoundedSupportsOf<Self>, Self::Error> {
342 Self::elect(0)
343 }
344
345 fn bother() -> bool {
346 false
347 }
348}
349
350pub struct IfSolutionQueuedElse<T, Queued, NotQueued>(
358 core::marker::PhantomData<(T, Queued, NotQueued)>,
359);
360
361pub struct GetDone<T>(core::marker::PhantomData<T>);
363impl<T: Config> Get<Phase<T>> for GetDone<T> {
364 fn get() -> Phase<T> {
365 Phase::Done
366 }
367}
368
369pub struct GetSigned<T>(core::marker::PhantomData<T>);
371impl<T: Config> Get<Phase<T>> for GetSigned<T> {
372 fn get() -> Phase<T> {
373 Phase::Signed(T::SignedPhase::get().saturating_sub(1u32.into()))
374 }
375}
376
377pub type ProceedRegardlessOf<T> = IfSolutionQueuedElse<T, GetDone<T>, GetDone<T>>;
379
380pub type RevertToSignedIfNotQueuedOf<T> = IfSolutionQueuedElse<T, GetDone<T>, GetSigned<T>>;
383
384impl<T: Config, Queued, NotQueued> IfSolutionQueuedElse<T, Queued, NotQueued> {
385 fn something_queued() -> bool {
386 let queued_score = <T::Verifier as verifier::Verifier>::queued_score().is_some();
387 #[cfg(debug_assertions)]
388 {
389 let any_pages_queued = (Pallet::<T>::lsp()..=Pallet::<T>::msp()).any(|p| {
390 <T::Verifier as verifier::Verifier>::get_queued_solution_page(p).is_some()
391 });
392 assert_eq!(
393 queued_score, any_pages_queued,
394 "queued score ({}) and queued pages ({}) must match",
395 queued_score, any_pages_queued
396 );
397 }
398 queued_score
399 }
400}
401
402impl<T: Config, Queued: Get<Phase<T>>, NotQueued: Get<Phase<T>>> Get<Phase<T>>
403 for IfSolutionQueuedElse<T, Queued, NotQueued>
404{
405 fn get() -> Phase<T> {
406 if Self::something_queued() {
407 Queued::get()
408 } else {
409 NotQueued::get()
410 }
411 }
412}
413
414#[derive(
418 frame_support::DebugNoBound, frame_support::PartialEqNoBound, frame_support::EqNoBound,
419)]
420pub enum ElectionError<T: Config> {
421 Feasibility(verifier::FeasibilityError),
423 Fallback(FallbackErrorOf<T>),
425 OnChain(onchain::Error),
427 DataProvider(&'static str),
429 SupportPageNotAvailable,
431 NotOngoing,
433 Ongoing,
435 OutOfOrder,
437 Other(&'static str),
439}
440
441impl<T: Config> From<onchain::Error> for ElectionError<T> {
442 fn from(e: onchain::Error) -> Self {
443 ElectionError::OnChain(e)
444 }
445}
446
447impl<T: Config> From<verifier::FeasibilityError> for ElectionError<T> {
448 fn from(e: verifier::FeasibilityError) -> Self {
449 ElectionError::Feasibility(e)
450 }
451}
452
453#[derive(
455 Encode,
456 Decode,
457 DecodeWithMemTracking,
458 MaxEncodedLen,
459 TypeInfo,
460 DebugNoBound,
461 CloneNoBound,
462 PartialEqNoBound,
463 EqNoBound,
464)]
465#[codec(mel_bound(T: Config))]
466#[scale_info(skip_type_params(T))]
467pub enum AdminOperation<T: Config> {
468 EmergencySetSolution(Box<BoundedSupportsOf<Pallet<T>>>, ElectionScore),
472 SetMinUntrustedScore(ElectionScore),
478}
479
480#[derive(
483 Encode,
484 Decode,
485 DecodeWithMemTracking,
486 MaxEncodedLen,
487 TypeInfo,
488 DebugNoBound,
489 CloneNoBound,
490 PartialEqNoBound,
491 EqNoBound,
492)]
493#[codec(mel_bound(T: Config))]
494#[scale_info(skip_type_params(T))]
495pub enum ManagerOperation<T: Config> {
496 ForceRotateRound,
498 ForceSetPhase(Phase<T>),
502 EmergencyFallback,
507}
508
509pub trait OnRoundRotation {
511 fn on_round_rotation(ending: u32);
513}
514
515impl OnRoundRotation for () {
516 fn on_round_rotation(_: u32) {}
517}
518
519pub struct CleanRound<T>(core::marker::PhantomData<T>);
525impl<T: Config> OnRoundRotation for CleanRound<T> {
526 fn on_round_rotation(_ending: u32) {
527 T::Verifier::kill();
529
530 pallet::Snapshot::<T>::kill();
532
533 }
535}
536
537#[frame_support::pallet]
538pub mod pallet {
539 use super::*;
540
541 #[pallet::config]
542 pub trait Config: frame_system::Config {
543 #[pallet::constant]
545 type UnsignedPhase: Get<BlockNumberFor<Self>>;
546 #[pallet::constant]
548 type SignedPhase: Get<BlockNumberFor<Self>>;
549 #[pallet::constant]
554 type SignedValidationPhase: Get<BlockNumberFor<Self>>;
555
556 #[pallet::constant]
558 type VoterSnapshotPerBlock: Get<u32>;
559
560 #[pallet::constant]
562 type TargetSnapshotPerBlock: Get<u32>;
563
564 #[pallet::constant]
571 type Pages: Get<PageIndex>;
572
573 type DataProvider: ElectionDataProvider<
575 AccountId = Self::AccountId,
576 BlockNumber = BlockNumberFor<Self>,
577 >;
578
579 type MinerConfig: crate::unsigned::miner::MinerConfig<
584 Pages = Self::Pages,
585 AccountId = <Self as frame_system::Config>::AccountId,
586 MaxVotesPerVoter = <Self::DataProvider as ElectionDataProvider>::MaxVotesPerVoter,
587 VoterSnapshotPerBlock = Self::VoterSnapshotPerBlock,
588 TargetSnapshotPerBlock = Self::TargetSnapshotPerBlock,
589 MaxBackersPerWinner = <Self::Verifier as verifier::Verifier>::MaxBackersPerWinner,
590 MaxWinnersPerPage = <Self::Verifier as verifier::Verifier>::MaxWinnersPerPage,
591 >;
592
593 type Fallback: InstantElectionProvider<
595 AccountId = Self::AccountId,
596 BlockNumber = BlockNumberFor<Self>,
597 DataProvider = Self::DataProvider,
598 MaxBackersPerWinner = <Self::Verifier as verifier::Verifier>::MaxBackersPerWinner,
599 MaxWinnersPerPage = <Self::Verifier as verifier::Verifier>::MaxWinnersPerPage,
600 >;
601
602 type Verifier: verifier::Verifier<
604 Solution = SolutionOf<Self::MinerConfig>,
605 AccountId = Self::AccountId,
606 > + verifier::AsynchronousVerifier;
607
608 type Signed: SignedInterface;
610
611 type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
616
617 type ManagerOrigin: EnsureOrigin<Self::RuntimeOrigin>;
620
621 type AreWeDone: Get<Phase<Self>>;
626
627 type WeightInfo: WeightInfo;
629
630 type OnRoundRotation: super::OnRoundRotation;
633 }
634
635 #[pallet::call]
636 impl<T: Config> Pallet<T> {
637 #[pallet::weight(T::WeightInfo::manage_fallback().max(T::WeightInfo::export_terminal()))]
643 #[pallet::call_index(0)]
644 pub fn manage(origin: OriginFor<T>, op: ManagerOperation<T>) -> DispatchResultWithPostInfo {
645 T::ManagerOrigin::ensure_origin(origin.clone()).map(|_| ()).or_else(|_| {
646 T::AdminOrigin::ensure_origin(origin).map(|_| ())
648 })?;
649 match op {
650 ManagerOperation::EmergencyFallback => {
651 ensure!(Self::current_phase() == Phase::Emergency, Error::<T>::UnexpectedPhase);
652 let voters = Snapshot::<T>::voters(Self::msp()).ok_or(Error::<T>::Snapshot)?;
655 let targets = Snapshot::<T>::targets().ok_or(Error::<T>::Snapshot)?;
656 let desired_targets =
657 Snapshot::<T>::desired_targets().ok_or(Error::<T>::Snapshot)?;
658 let fallback = T::Fallback::instant_elect(
659 voters.into_inner(),
660 targets.into_inner(),
661 desired_targets,
662 )
663 .map_err(|e| {
664 log!(warn, "Fallback failed: {:?}", e);
665 Error::<T>::Fallback
666 })?;
667 let score = fallback.evaluate();
668 T::Verifier::force_set_single_page_valid(fallback, 0, score);
669 Ok(PostDispatchInfo {
670 actual_weight: Some(T::WeightInfo::manage_fallback()),
671 pays_fee: Pays::No,
672 })
673 },
674 ManagerOperation::ForceSetPhase(phase) => {
675 Self::phase_transition(phase);
676 Ok(PostDispatchInfo {
677 actual_weight: Some(T::DbWeight::get().reads_writes(1, 1)),
678 pays_fee: Pays::No,
679 })
680 },
681 ManagerOperation::ForceRotateRound => {
682 Self::rotate_round();
683 Ok(PostDispatchInfo {
684 actual_weight: Some(T::WeightInfo::export_terminal()),
685 pays_fee: Pays::No,
686 })
687 },
688 }
689 }
690
691 #[pallet::call_index(1)]
692 #[pallet::weight(T::WeightInfo::admin_set())]
693 pub fn admin(origin: OriginFor<T>, op: AdminOperation<T>) -> DispatchResultWithPostInfo {
694 T::AdminOrigin::ensure_origin(origin)?;
695 match op {
696 AdminOperation::EmergencySetSolution(supports, score) => {
697 ensure!(Self::current_phase() == Phase::Emergency, Error::<T>::UnexpectedPhase);
698 T::Verifier::force_set_single_page_valid(*supports, 0, score);
699 Ok(PostDispatchInfo {
700 actual_weight: Some(T::WeightInfo::admin_set()),
701 pays_fee: Pays::No,
702 })
703 },
704 AdminOperation::SetMinUntrustedScore(score) => {
705 T::Verifier::set_minimum_score(score);
706 Ok(PostDispatchInfo {
707 actual_weight: Some(T::DbWeight::get().reads_writes(1, 1)),
708 pays_fee: Pays::No,
709 })
710 },
711 }
712 }
713 }
714
715 #[pallet::hooks]
716 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
717 fn on_poll(_now: BlockNumberFor<T>, weight_meter: &mut WeightMeter) {
718 if !weight_meter.can_consume(T::DbWeight::get().reads(1)) {
720 Self::deposit_event(Event::UnexpectedPhaseTransitionHalt {
721 required: T::DbWeight::get().reads(1),
722 had: weight_meter.remaining(),
723 });
724 return;
725 }
726
727 let current_phase = Self::current_phase();
729 weight_meter.consume(T::DbWeight::get().reads(1));
730
731 let (self_weight, self_exec) = Self::per_block_exec(current_phase);
732 let (verifier_weight, verifier_exc) = T::Verifier::per_block_exec();
733
734 let (combined_weight, combined_exec) = (
738 self_weight.saturating_add(verifier_weight),
740 Box::new(move |meter: &mut WeightMeter| {
742 self_exec(meter);
743 verifier_exc(meter);
744 }),
745 );
746
747 log!(
748 trace,
749 "worst-case required weight for transition from {:?} to {:?} is {:?}, has {:?}",
750 current_phase,
751 current_phase.next(),
752 combined_weight,
753 weight_meter.remaining()
754 );
755 if weight_meter.can_consume(combined_weight) {
756 combined_exec(weight_meter);
757 } else {
758 Self::deposit_event(Event::UnexpectedPhaseTransitionOutOfWeight {
759 from: current_phase,
760 to: current_phase.next(),
761 required: combined_weight,
762 had: weight_meter.remaining(),
763 });
764 }
765
766 #[cfg(test)]
768 {
769 if _now > 200u32.into() {
770 panic!("Looping to death: in case of errors in election start time in tests, we might loop \
771 infinitely. This panic is preventing you from that. Double check `mock::ElectionStart` or increase \
772 the 200 limit");
773 }
774 let test_election_start: BlockNumberFor<T> =
775 (crate::mock::ElectionStart::get() as u32).into();
776 if _now == test_election_start {
777 crate::log!(info, "TESTING: Starting election at block {}", _now);
778 crate::mock::MultiBlock::start().unwrap();
779 }
780 }
781 }
782
783 fn integrity_test() {
784 use core::mem::size_of;
785 assert!(size_of::<SolutionVoterIndexOf<T::MinerConfig>>() <= size_of::<usize>());
788 assert!(size_of::<SolutionTargetIndexOf<T::MinerConfig>>() <= size_of::<usize>());
789
790 assert!(size_of::<SolutionVoterIndexOf<T::MinerConfig>>() <= size_of::<u32>());
793 assert!(size_of::<SolutionTargetIndexOf<T::MinerConfig>>() <= size_of::<u32>());
794
795 assert!(T::Pages::get() > 0);
797
798 let max_vote: usize = <SolutionOf<T::MinerConfig> as NposSolution>::LIMIT;
800
801 let maximum_chain_accuracy: Vec<UpperOf<SolutionAccuracyOf<T::MinerConfig>>> = (0..
803 max_vote)
804 .map(|_| {
805 <UpperOf<SolutionAccuracyOf<T::MinerConfig>>>::from(
806 <SolutionAccuracyOf<T::MinerConfig>>::one().deconstruct(),
807 )
808 })
809 .collect();
810 let _: UpperOf<SolutionAccuracyOf<T::MinerConfig>> = maximum_chain_accuracy
811 .iter()
812 .fold(Zero::zero(), |acc, x| acc.checked_add(x).unwrap());
813
814 assert_eq!(
820 <T::DataProvider as ElectionDataProvider>::MaxVotesPerVoter::get(),
821 <SolutionOf<T::MinerConfig> as NposSolution>::LIMIT as u32,
822 );
823
824 let has_signed = !T::SignedPhase::get().is_zero();
826 let signed_validation = T::SignedValidationPhase::get();
827 let has_signed_validation = !signed_validation.is_zero();
828 let has_unsigned = !T::UnsignedPhase::get().is_zero();
829 assert!(
830 has_signed == has_signed_validation,
831 "Signed phase not set correct -- both should be set or unset"
832 );
833 assert!(
834 signed_validation.is_zero() ||
835 signed_validation % T::Pages::get().into() == Zero::zero(),
836 "signed validation phase should be a multiple of the number of pages."
837 );
838
839 assert!(has_signed || has_unsigned, "either signed or unsigned phase must be set");
840 }
841
842 #[cfg(feature = "try-runtime")]
843 fn try_state(now: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
844 Self::do_try_state(now).map_err(Into::into)
845 }
846 }
847
848 #[pallet::event]
849 #[pallet::generate_deposit(pub(super) fn deposit_event)]
850 pub enum Event<T: Config> {
851 PhaseTransitioned {
854 from: Phase<T>,
856 to: Phase<T>,
858 },
859 UnexpectedTargetSnapshotFailed,
861 UnexpectedVoterSnapshotFailed,
863 UnexpectedPhaseTransitionOutOfWeight {
865 from: Phase<T>,
866 to: Phase<T>,
867 required: Weight,
868 had: Weight,
869 },
870 UnexpectedPhaseTransitionHalt { required: Weight, had: Weight },
872 }
873
874 #[pallet::error]
876 pub enum Error<T> {
877 Fallback,
879 UnexpectedPhase,
881 Snapshot,
883 }
884
885 #[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
887 pub enum CommonError {
888 EarlySubmission,
890 WrongRound,
892 WeakSubmission,
894 WrongPageCount,
896 WrongWinnerCount,
898 WrongFingerprint,
900 Snapshot,
902 }
903
904 #[pallet::storage]
911 #[pallet::getter(fn round)]
912 pub type Round<T: Config> = StorageValue<_, u32, ValueQuery>;
913
914 #[pallet::storage]
916 #[pallet::getter(fn current_phase)]
917 pub type CurrentPhase<T: Config> = StorageValue<_, Phase<T>, ValueQuery>;
918
919 pub(crate) struct Snapshot<T>(core::marker::PhantomData<T>);
956 impl<T: Config> Snapshot<T> {
957 pub(crate) fn set_desired_targets(d: u32) {
959 DesiredTargets::<T>::insert(Self::round(), d);
960 }
961
962 pub(crate) fn set_targets(targets: BoundedVec<T::AccountId, T::TargetSnapshotPerBlock>) {
963 let hash = Self::write_storage_with_pre_allocate(
964 &PagedTargetSnapshot::<T>::hashed_key_for(Self::round(), Pallet::<T>::msp()),
965 targets,
966 );
967 PagedTargetSnapshotHash::<T>::insert(Self::round(), Pallet::<T>::msp(), hash);
968 }
969
970 pub(crate) fn set_voters(page: PageIndex, voters: VoterPageOf<T::MinerConfig>) {
971 let hash = Self::write_storage_with_pre_allocate(
972 &PagedVoterSnapshot::<T>::hashed_key_for(Self::round(), page),
973 voters,
974 );
975 PagedVoterSnapshotHash::<T>::insert(Self::round(), page, hash);
976 }
977
978 pub(crate) fn kill() {
982 DesiredTargets::<T>::remove(Self::round());
983 clear_round_based_map!(PagedVoterSnapshot::<T>, Self::round());
984 clear_round_based_map!(PagedVoterSnapshotHash::<T>, Self::round());
985 clear_round_based_map!(PagedTargetSnapshot::<T>, Self::round());
986 clear_round_based_map!(PagedTargetSnapshotHash::<T>, Self::round());
987 }
988
989 pub(crate) fn desired_targets() -> Option<u32> {
991 DesiredTargets::<T>::get(Self::round())
992 }
993
994 pub(crate) fn voters(page: PageIndex) -> Option<VoterPageOf<T::MinerConfig>> {
995 PagedVoterSnapshot::<T>::get(Self::round(), page)
996 }
997
998 pub(crate) fn targets() -> Option<BoundedVec<T::AccountId, T::TargetSnapshotPerBlock>> {
999 PagedTargetSnapshot::<T>::get(Self::round(), Pallet::<T>::msp())
1001 }
1002
1003 pub fn fingerprint() -> T::Hash {
1010 let mut hashed_target_and_voters =
1011 Self::targets_hash().unwrap_or_default().as_ref().to_vec();
1012 let hashed_voters = (Pallet::<T>::msp()..=Pallet::<T>::lsp())
1013 .map(|i| PagedVoterSnapshotHash::<T>::get(Self::round(), i).unwrap_or_default())
1014 .flat_map(|hash| <T::Hash as AsRef<[u8]>>::as_ref(&hash).to_owned())
1015 .collect::<Vec<u8>>();
1016 hashed_target_and_voters.extend(hashed_voters);
1017 T::Hashing::hash(&hashed_target_and_voters)
1018 }
1019
1020 fn write_storage_with_pre_allocate<E: Encode>(key: &[u8], data: E) -> T::Hash {
1021 let size = data.encoded_size();
1022 let mut buffer = Vec::with_capacity(size);
1023 data.encode_to(&mut buffer);
1024
1025 let hash = T::Hashing::hash(&buffer);
1026
1027 debug_assert_eq!(buffer, data.encode());
1029 debug_assert!(buffer.len() == size && size == buffer.capacity());
1031 sp_io::storage::set(key, &buffer);
1032
1033 hash
1034 }
1035
1036 pub(crate) fn targets_hash() -> Option<T::Hash> {
1037 PagedTargetSnapshotHash::<T>::get(Self::round(), Pallet::<T>::msp())
1038 }
1039
1040 fn round() -> u32 {
1041 Pallet::<T>::round()
1042 }
1043 }
1044
1045 #[allow(unused)]
1046 #[cfg(any(test, feature = "runtime-benchmarks", feature = "try-runtime"))]
1047 impl<T: Config> Snapshot<T> {
1048 pub(crate) fn ensure_target_snapshot(exists: bool) -> Result<(), &'static str> {
1050 ensure!(exists ^ Self::desired_targets().is_none(), "desired target mismatch");
1051 ensure!(exists ^ Self::targets().is_none(), "targets mismatch");
1052 ensure!(exists ^ Self::targets_hash().is_none(), "targets hash mismatch");
1053
1054 if let Some(targets) = Self::targets() {
1056 let hash = Self::targets_hash().expect("must exist; qed");
1057 ensure!(hash == T::Hashing::hash(&targets.encode()), "targets hash mismatch");
1058 }
1059 Ok(())
1060 }
1061
1062 pub(crate) fn ensure_voter_snapshot(
1064 exists: bool,
1065 mut up_to_page: PageIndex,
1066 ) -> Result<(), &'static str> {
1067 up_to_page = up_to_page.min(T::Pages::get());
1068 let mut sum_existing_voters: usize = 0;
1070 for p in (crate::Pallet::<T>::lsp()..=crate::Pallet::<T>::msp())
1071 .rev()
1072 .take(up_to_page as usize)
1073 {
1074 ensure!(
1075 (exists ^ Self::voters(p).is_none()) &&
1076 (exists ^ Self::voters_hash(p).is_none()),
1077 "voter page existence mismatch"
1078 );
1079
1080 if let Some(voters_page) = Self::voters(p) {
1081 sum_existing_voters = sum_existing_voters.saturating_add(voters_page.len());
1082 let hash = Self::voters_hash(p).expect("must exist; qed");
1083 ensure!(hash == T::Hashing::hash(&voters_page.encode()), "voter hash mismatch");
1084 }
1085 }
1086
1087 for p in (crate::Pallet::<T>::lsp()..=crate::Pallet::<T>::msp())
1089 .take((T::Pages::get() - up_to_page) as usize)
1090 {
1091 ensure!(
1092 (exists ^ Self::voters(p).is_some()) &&
1093 (exists ^ Self::voters_hash(p).is_some()),
1094 "voter page non-existence mismatch"
1095 );
1096 }
1097 Ok(())
1098 }
1099
1100 pub(crate) fn ensure_snapshot(
1101 exists: bool,
1102 mut up_to_page: PageIndex,
1103 ) -> Result<(), &'static str> {
1104 Self::ensure_target_snapshot(exists)
1105 .and_then(|_| Self::ensure_voter_snapshot(exists, up_to_page))
1106 }
1107
1108 pub(crate) fn ensure_full_snapshot() -> Result<(), &'static str> {
1109 ensure!(Self::desired_targets().is_some(), "desired target mismatch");
1111 ensure!(Self::targets_hash().is_some(), "targets hash mismatch");
1112 ensure!(
1113 Self::targets_decode_len().unwrap_or_default() as u32 ==
1114 T::TargetSnapshotPerBlock::get(),
1115 "targets decode length mismatch"
1116 );
1117
1118 for p in crate::Pallet::<T>::lsp()..=crate::Pallet::<T>::msp() {
1120 ensure!(
1121 Self::voters_hash(p).is_some() &&
1122 Self::voters_decode_len(p).unwrap_or_default() as u32 ==
1123 T::VoterSnapshotPerBlock::get(),
1124 "voter page existence mismatch"
1125 );
1126 }
1127
1128 Ok(())
1129 }
1130
1131 pub(crate) fn voters_decode_len(page: PageIndex) -> Option<usize> {
1132 PagedVoterSnapshot::<T>::decode_len(Self::round(), page)
1133 }
1134
1135 pub(crate) fn targets_decode_len() -> Option<usize> {
1136 PagedTargetSnapshot::<T>::decode_len(Self::round(), Pallet::<T>::msp())
1137 }
1138
1139 pub(crate) fn voters_hash(page: PageIndex) -> Option<T::Hash> {
1140 PagedVoterSnapshotHash::<T>::get(Self::round(), page)
1141 }
1142
1143 pub(crate) fn sanity_check() -> Result<(), &'static str> {
1144 let phase = Pallet::<T>::current_phase();
1147 let _ = match phase {
1148 Phase::Off => Self::ensure_snapshot(false, T::Pages::get()),
1150
1151 Phase::Snapshot(p) if p == T::Pages::get() => {
1153 Self::ensure_snapshot(false, T::Pages::get())
1154 },
1155 Phase::Snapshot(p) if p < T::Pages::get() && p > 0 => {
1157 Self::ensure_snapshot(true, T::Pages::get() - p - 1)
1158 },
1159 Phase::Snapshot(_) => Ok(()),
1161
1162 Phase::Emergency |
1164 Phase::Signed(_) |
1165 Phase::SignedValidation(_) |
1166 Phase::Export(_) |
1167 Phase::Done |
1168 Phase::Unsigned(_) => Self::ensure_snapshot(true, T::Pages::get()),
1169 }?;
1170
1171 Ok(())
1172 }
1173 }
1174
1175 #[cfg(test)]
1176 impl<T: Config> Snapshot<T> {
1177 pub(crate) fn voter_pages() -> PageIndex {
1178 use sp_runtime::SaturatedConversion;
1179 PagedVoterSnapshot::<T>::iter().count().saturated_into::<PageIndex>()
1180 }
1181
1182 pub(crate) fn target_pages() -> PageIndex {
1183 use sp_runtime::SaturatedConversion;
1184 PagedTargetSnapshot::<T>::iter().count().saturated_into::<PageIndex>()
1185 }
1186
1187 pub(crate) fn voters_iter_flattened() -> impl Iterator<Item = VoterOf<T::MinerConfig>> {
1188 let key_range =
1189 (crate::Pallet::<T>::lsp()..=crate::Pallet::<T>::msp()).collect::<Vec<_>>();
1190 key_range
1191 .into_iter()
1192 .flat_map(|k| PagedVoterSnapshot::<T>::get(Self::round(), k).unwrap_or_default())
1193 }
1194
1195 pub(crate) fn remove_voter_page(page: PageIndex) {
1196 PagedVoterSnapshot::<T>::remove(Self::round(), page);
1197 }
1198
1199 pub(crate) fn kill_desired_targets() {
1200 DesiredTargets::<T>::remove(Self::round());
1201 }
1202
1203 pub(crate) fn remove_target_page() {
1204 PagedTargetSnapshot::<T>::remove(Self::round(), Pallet::<T>::msp());
1205 }
1206
1207 pub(crate) fn remove_target(at: usize) {
1208 PagedTargetSnapshot::<T>::mutate(
1209 Self::round(),
1210 crate::Pallet::<T>::msp(),
1211 |maybe_targets| {
1212 if let Some(targets) = maybe_targets {
1213 targets.remove(at);
1214 PagedTargetSnapshotHash::<T>::insert(
1216 Self::round(),
1217 crate::Pallet::<T>::msp(),
1218 T::Hashing::hash(&targets.encode()),
1219 )
1220 } else {
1221 unreachable!();
1222 }
1223 },
1224 )
1225 }
1226 }
1227
1228 #[pallet::storage]
1230 pub type DesiredTargets<T> = StorageMap<_, Twox64Concat, u32, u32>;
1231 #[pallet::storage]
1233 pub type PagedVoterSnapshot<T: Config> = StorageDoubleMap<
1234 _,
1235 Twox64Concat,
1236 u32,
1237 Twox64Concat,
1238 PageIndex,
1239 VoterPageOf<T::MinerConfig>,
1240 >;
1241 #[pallet::storage]
1245 pub type PagedVoterSnapshotHash<T: Config> =
1246 StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, PageIndex, T::Hash>;
1247 #[pallet::storage]
1251 pub type PagedTargetSnapshot<T: Config> = StorageDoubleMap<
1252 _,
1253 Twox64Concat,
1254 u32,
1255 Twox64Concat,
1256 PageIndex,
1257 BoundedVec<T::AccountId, T::TargetSnapshotPerBlock>,
1258 >;
1259 #[pallet::storage]
1263 pub type PagedTargetSnapshotHash<T: Config> =
1264 StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, PageIndex, T::Hash>;
1265
1266 #[pallet::pallet]
1267 pub struct Pallet<T>(PhantomData<T>);
1268}
1269
1270impl<T: Config> Pallet<T> {
1271 fn msp() -> PageIndex {
1275 T::Pages::get().checked_sub(1).defensive_unwrap_or_default()
1276 }
1277
1278 fn lsp() -> PageIndex {
1282 Zero::zero()
1283 }
1284
1285 fn per_block_exec(current_phase: Phase<T>) -> (Weight, Box<dyn Fn(&mut WeightMeter)>) {
1351 type ExecuteFn = Box<dyn Fn(&mut WeightMeter)>;
1352 let next_phase = current_phase.next();
1353
1354 let just_next_phase: (Weight, ExecuteFn) = (
1355 T::WeightInfo::per_block_nothing(),
1356 Box::new(move |_| {
1357 Self::phase_transition(next_phase);
1359 }),
1360 );
1361
1362 match current_phase {
1363 Phase::Snapshot(x) if x == T::Pages::get() => {
1364 let weight = T::WeightInfo::per_block_snapshot_msp();
1366 let exec: ExecuteFn = Box::new(move |meter: &mut WeightMeter| {
1367 Self::create_targets_snapshot();
1368 Self::phase_transition(next_phase);
1369 meter.consume(weight)
1370 });
1371 (weight, exec)
1372 },
1373
1374 Phase::Snapshot(x) => {
1375 let weight = T::WeightInfo::per_block_snapshot_rest();
1377 let exec: ExecuteFn = Box::new(move |meter: &mut WeightMeter| {
1378 Self::create_voters_snapshot_paged(x);
1379 Self::phase_transition(next_phase);
1380 meter.consume(weight)
1381 });
1382 (weight, exec)
1383 },
1384 Phase::Signed(x) => {
1385 if x.is_zero() && T::Signed::has_leader(Self::round()) {
1388 let weight = T::WeightInfo::per_block_start_signed_validation();
1389 let exec: ExecuteFn = Box::new(move |meter: &mut WeightMeter| {
1390 let _ = T::Verifier::start().defensive();
1393 Self::phase_transition(next_phase);
1394 meter.consume(weight)
1395 });
1396 (weight, exec)
1397 } else {
1398 just_next_phase
1399 }
1400 },
1401 Phase::SignedValidation(_) |
1402 Phase::Unsigned(_) |
1403 Phase::Off |
1404 Phase::Emergency |
1405 Phase::Done |
1406 Phase::Export(_) => just_next_phase,
1407 }
1408 }
1409
1410 pub fn msp_range_for(length: usize) -> Vec<PageIndex> {
1416 (Self::lsp()..Self::msp() + 1).rev().take(length).rev().collect::<Vec<_>>()
1417 }
1418
1419 pub(crate) fn phase_transition(to: Phase<T>) {
1420 let from = Self::current_phase();
1421 if from == to {
1422 return;
1423 }
1424 use core::mem::discriminant;
1425 if discriminant(&from) != discriminant(&to) {
1426 log!(debug, "transitioning phase from {:?} to {:?}", from, to);
1427 Self::deposit_event(Event::PhaseTransitioned { from, to });
1428 } else {
1429 log!(trace, "transitioning phase from {:?} to {:?}", from, to);
1430 }
1431 <CurrentPhase<T>>::put(to);
1432 }
1433
1434 pub(crate) fn snapshot_independent_checks(
1446 paged_solution: &PagedRawSolution<T::MinerConfig>,
1447 maybe_snapshot_fingerprint: Option<T::Hash>,
1448 ) -> Result<(), CommonError> {
1449 ensure!(Self::round() == paged_solution.round, CommonError::WrongRound);
1456
1457 ensure!(
1459 <T::Verifier as Verifier>::ensure_claimed_score_improves(paged_solution.score),
1460 CommonError::WeakSubmission,
1461 );
1462
1463 ensure!(
1465 paged_solution.solution_pages.len().saturated_into::<PageIndex>() <= T::Pages::get(),
1466 CommonError::WrongPageCount
1467 );
1468
1469 if let Some(desired_targets) = Snapshot::<T>::desired_targets() {
1471 ensure!(
1472 desired_targets == paged_solution.winner_count_single_page_target_snapshot() as u32,
1473 CommonError::WrongWinnerCount
1474 )
1475 }
1476
1477 ensure!(
1479 maybe_snapshot_fingerprint
1480 .map_or(true, |snapshot_fingerprint| Snapshot::<T>::fingerprint() ==
1481 snapshot_fingerprint),
1482 CommonError::WrongFingerprint
1483 );
1484
1485 Ok(())
1486 }
1487
1488 pub(crate) fn create_targets_snapshot() {
1493 let desired_targets = match T::DataProvider::desired_targets() {
1495 Ok(targets) => targets,
1496 Err(e) => {
1497 Self::deposit_event(Event::UnexpectedTargetSnapshotFailed);
1498 defensive!("Failed to get desired targets: {:?}", e);
1499 return;
1500 },
1501 };
1502 Snapshot::<T>::set_desired_targets(desired_targets);
1503
1504 let count = T::TargetSnapshotPerBlock::get();
1505 let bounds = DataProviderBounds { count: Some(count.into()), size: None };
1506 let targets: BoundedVec<_, T::TargetSnapshotPerBlock> =
1507 match T::DataProvider::electable_targets(bounds, 0)
1508 .and_then(|v| v.try_into().map_err(|_| "try-into failed"))
1509 {
1510 Ok(targets) => targets,
1511 Err(e) => {
1512 Self::deposit_event(Event::UnexpectedTargetSnapshotFailed);
1513 defensive!("Failed to create target snapshot: {:?}", e);
1514 return;
1515 },
1516 };
1517
1518 let count = targets.len() as u32;
1519 log!(debug, "created target snapshot with {} targets.", count);
1520 Snapshot::<T>::set_targets(targets);
1521 }
1522
1523 pub(crate) fn create_voters_snapshot_paged(remaining: PageIndex) {
1528 let count = T::VoterSnapshotPerBlock::get();
1529 let bounds = DataProviderBounds { count: Some(count.into()), size: None };
1530 let voters: BoundedVec<_, T::VoterSnapshotPerBlock> =
1531 match T::DataProvider::electing_voters(bounds, remaining)
1532 .and_then(|v| v.try_into().map_err(|_| "try-into failed"))
1533 {
1534 Ok(voters) => voters,
1535 Err(e) => {
1536 Self::deposit_event(Event::UnexpectedVoterSnapshotFailed);
1537 defensive!("Failed to create voter snapshot: {:?}", e);
1538 return;
1539 },
1540 };
1541
1542 let count = voters.len() as u32;
1543 Snapshot::<T>::set_voters(remaining, voters);
1544 log!(debug, "created voter snapshot with {} voters, {} remaining.", count, remaining);
1545 }
1546
1547 pub(crate) fn rotate_round() {
1553 <Round<T>>::mutate(|r| {
1555 T::OnRoundRotation::on_round_rotation(*r);
1557 *r += 1
1558 });
1559
1560 Self::phase_transition(Phase::Off);
1562 }
1563
1564 fn fallback_for_page(page: PageIndex) -> Result<BoundedSupportsOf<Self>, ElectionError<T>> {
1570 use frame_election_provider_support::InstantElectionProvider;
1571 let (voters, targets, desired_targets) = if T::Fallback::bother() {
1572 (
1573 Snapshot::<T>::voters(page).ok_or(ElectionError::Other("snapshot!"))?,
1574 Snapshot::<T>::targets().ok_or(ElectionError::Other("snapshot!"))?,
1575 Snapshot::<T>::desired_targets().ok_or(ElectionError::Other("snapshot!"))?,
1576 )
1577 } else {
1578 (Default::default(), Default::default(), Default::default())
1579 };
1580 T::Fallback::instant_elect(voters.into_inner(), targets.into_inner(), desired_targets)
1581 .map_err(|fe| ElectionError::Fallback(fe))
1582 }
1583
1584 pub fn average_election_duration() -> u32 {
1586 let signed: u32 = T::SignedPhase::get().saturated_into();
1587 let unsigned: u32 = T::UnsignedPhase::get().saturated_into();
1588 let signed_validation: u32 = T::SignedValidationPhase::get().saturated_into();
1589 let snapshot = T::Pages::get();
1590
1591 let _export = T::Pages::get();
1593
1594 snapshot + signed + signed_validation + unsigned
1595 }
1596
1597 #[cfg(any(test, feature = "runtime-benchmarks", feature = "try-runtime"))]
1598 pub(crate) fn do_try_state(_: BlockNumberFor<T>) -> Result<(), &'static str> {
1599 Snapshot::<T>::sanity_check()
1600 }
1601}
1602
1603#[cfg(feature = "std")]
1604impl<T: Config> Pallet<T> {
1605 fn analyze_weight(
1606 op_name: &str,
1607 op_weight: Weight,
1608 limit_weight: Weight,
1609 maybe_max_ratio: Option<sp_runtime::Percent>,
1610 maybe_max_warn_ratio: Option<sp_runtime::Percent>,
1611 ) {
1612 use frame_support::weights::constants::{
1613 WEIGHT_PROOF_SIZE_PER_KB, WEIGHT_REF_TIME_PER_MILLIS,
1614 };
1615
1616 let ref_time_ms = op_weight.ref_time() / WEIGHT_REF_TIME_PER_MILLIS;
1617 let ref_time_ratio =
1618 sp_runtime::Percent::from_rational(op_weight.ref_time(), limit_weight.ref_time());
1619 let proof_size_kb = op_weight.proof_size() / WEIGHT_PROOF_SIZE_PER_KB;
1620 let proof_size_ratio =
1621 sp_runtime::Percent::from_rational(op_weight.proof_size(), limit_weight.proof_size());
1622 let limit_ms = limit_weight.ref_time() / WEIGHT_REF_TIME_PER_MILLIS;
1623 let limit_kb = limit_weight.proof_size() / WEIGHT_PROOF_SIZE_PER_KB;
1624 log::info!(
1625 target: crate::LOG_PREFIX,
1626 "weight of {op_name:?} is: ref-time: {ref_time_ms}ms, {ref_time_ratio:?} of total, proof-size: {proof_size_kb}KiB, {proof_size_ratio:?} of total (total: {limit_ms}ms, {limit_kb}KiB)",
1627 );
1628
1629 if let Some(max_ratio) = maybe_max_ratio {
1630 assert!(ref_time_ratio <= max_ratio && proof_size_ratio <= max_ratio,)
1631 }
1632 if let Some(warn_ratio) = maybe_max_warn_ratio {
1633 if ref_time_ratio > warn_ratio || proof_size_ratio > warn_ratio {
1634 log::warn!(
1635 target: crate::LOG_PREFIX,
1636 "weight of {op_name:?} is above {warn_ratio:?} of the block limit",
1637 );
1638 }
1639 }
1640 }
1641
1642 pub fn check_all_weights(
1662 limit_weight: Weight,
1663 maybe_max_ratio: Option<sp_runtime::Percent>,
1664 maybe_max_warn_ratio: Option<sp_runtime::Percent>,
1665 ) where
1666 T: crate::verifier::Config + crate::signed::Config + crate::unsigned::Config,
1667 {
1668 use crate::weights::traits::{
1669 pallet_election_provider_multi_block_signed::WeightInfo as _,
1670 pallet_election_provider_multi_block_unsigned::WeightInfo as _,
1671 pallet_election_provider_multi_block_verifier::WeightInfo as _,
1672 };
1673
1674 Self::analyze_weight(
1676 "snapshot_msp",
1677 <T as Config>::WeightInfo::per_block_snapshot_msp(),
1678 limit_weight,
1679 maybe_max_ratio,
1680 maybe_max_warn_ratio,
1681 );
1682
1683 Self::analyze_weight(
1684 "snapshot_rest",
1685 <T as Config>::WeightInfo::per_block_snapshot_rest(),
1686 limit_weight,
1687 maybe_max_ratio,
1688 maybe_max_warn_ratio,
1689 );
1690
1691 Self::analyze_weight(
1693 "signed_clear_all_pages",
1694 <T as crate::signed::Config>::WeightInfo::clear_old_round_data(T::Pages::get()),
1695 limit_weight,
1696 maybe_max_ratio,
1697 maybe_max_warn_ratio,
1698 );
1699 Self::analyze_weight(
1700 "signed_submit_single_pages",
1701 <T as crate::signed::Config>::WeightInfo::submit_page(),
1702 limit_weight,
1703 maybe_max_ratio,
1704 maybe_max_warn_ratio,
1705 );
1706
1707 Self::analyze_weight(
1709 "verify unsigned solution",
1710 <T as crate::unsigned::Config>::WeightInfo::submit_unsigned(),
1711 limit_weight,
1712 maybe_max_ratio,
1713 maybe_max_warn_ratio,
1714 );
1715
1716 Self::analyze_weight(
1718 "verifier valid terminal",
1719 <T as crate::verifier::Config>::WeightInfo::verification_valid_terminal(),
1720 limit_weight,
1721 maybe_max_ratio,
1722 maybe_max_warn_ratio,
1723 );
1724 Self::analyze_weight(
1725 "verifier invalid terminal",
1726 <T as crate::verifier::Config>::WeightInfo::verification_invalid_terminal(),
1727 limit_weight,
1728 maybe_max_ratio,
1729 maybe_max_warn_ratio,
1730 );
1731
1732 Self::analyze_weight(
1733 "verifier valid non terminal",
1734 <T as crate::verifier::Config>::WeightInfo::verification_valid_non_terminal(),
1735 limit_weight,
1736 maybe_max_ratio,
1737 maybe_max_warn_ratio,
1738 );
1739
1740 Self::analyze_weight(
1741 "verifier invalid non terminal",
1742 <T as crate::verifier::Config>::WeightInfo::verification_invalid_non_terminal(
1743 T::Pages::get(),
1744 ),
1745 limit_weight,
1746 maybe_max_ratio,
1747 maybe_max_warn_ratio,
1748 );
1749
1750 Self::analyze_weight(
1752 "export non-terminal",
1753 <T as Config>::WeightInfo::export_non_terminal(),
1754 limit_weight,
1755 maybe_max_ratio,
1756 maybe_max_warn_ratio,
1757 );
1758
1759 Self::analyze_weight(
1760 "export terminal",
1761 <T as Config>::WeightInfo::export_terminal(),
1762 limit_weight,
1763 maybe_max_ratio,
1764 maybe_max_warn_ratio,
1765 );
1766 }
1767}
1768
1769#[allow(unused)]
1770#[cfg(any(feature = "runtime-benchmarks", test))]
1771impl<T> Pallet<T>
1773where
1774 T: Config + crate::signed::Config + crate::unsigned::Config + crate::verifier::Config,
1775 BlockNumberFor<T>: From<u32>,
1776{
1777 pub(crate) fn roll_until_matches(criteria: impl FnOnce() -> bool + Copy) {
1779 loop {
1780 Self::roll_next(false);
1781 if criteria() {
1782 break;
1783 }
1784 }
1785 }
1786
1787 pub(crate) fn roll_until_before_matches(criteria: impl FnOnce() -> bool + Copy) {
1789 use frame_support::storage::TransactionOutcome;
1790 loop {
1791 let should_break = frame_support::storage::with_transaction(
1792 || -> TransactionOutcome<Result<_, DispatchError>> {
1793 Pallet::<T>::roll_next(false);
1794 if criteria() {
1795 TransactionOutcome::Rollback(Ok(true))
1796 } else {
1797 TransactionOutcome::Commit(Ok(false))
1798 }
1799 },
1800 )
1801 .unwrap();
1802
1803 if should_break {
1804 break;
1805 }
1806 }
1807 }
1808
1809 pub(crate) fn roll_to_signed_and_mine_full_solution() -> PagedRawSolution<T::MinerConfig> {
1810 use unsigned::miner::OffchainWorkerMiner;
1811 Self::roll_to_signed_and_mine_solution(T::Pages::get())
1812 }
1813
1814 pub(crate) fn roll_to_signed_and_mine_solution(
1815 pages: PageIndex,
1816 ) -> PagedRawSolution<T::MinerConfig> {
1817 use unsigned::miner::OffchainWorkerMiner;
1818 Self::roll_until_matches(|| Self::current_phase().is_signed());
1819 crate::Snapshot::<T>::ensure_full_snapshot().expect("Snapshot is not full");
1821 OffchainWorkerMiner::<T>::mine_solution(pages, false).expect("mine_solution failed")
1822 }
1823
1824 pub(crate) fn submit_full_solution(
1825 PagedRawSolution { score, solution_pages, .. }: PagedRawSolution<T::MinerConfig>,
1826 ) -> DispatchResultWithPostInfo {
1827 use frame_system::RawOrigin;
1828 use types::Pagify;
1829
1830 let alice = crate::Pallet::<T>::funded_account("alice", 0);
1832 signed::Pallet::<T>::register(RawOrigin::Signed(alice.clone()).into(), score)?;
1833
1834 for (index, page) in solution_pages.pagify(T::Pages::get()) {
1836 signed::Pallet::<T>::submit_page(
1837 RawOrigin::Signed(alice.clone()).into(),
1838 index,
1839 Some(Box::new(page.clone())),
1840 )
1841 .inspect_err(|&e| {
1842 log!(error, "submit_page {:?} failed: {:?}", page, e);
1843 })?;
1844 }
1845
1846 Ok(().into())
1847 }
1848
1849 pub(crate) fn roll_to_signed_and_submit_full_solution() -> DispatchResultWithPostInfo {
1850 Self::submit_full_solution(Self::roll_to_signed_and_mine_full_solution())
1851 }
1852
1853 fn funded_account(seed: &'static str, index: u32) -> T::AccountId {
1854 use frame_benchmarking::whitelist;
1855 use frame_support::traits::fungible::{Inspect, Mutate};
1856 let who: T::AccountId = frame_benchmarking::account(seed, index, 777);
1857 whitelist!(who);
1858
1859 let worst_case_deposit = {
1865 let max_queue_size = T::MaxSubmissions::get() as usize;
1866 let base = T::DepositBase::calculate_base_deposit(max_queue_size);
1867 let pages = T::DepositPerPage::calculate_page_deposit(T::Pages::get() as usize);
1868 base.saturating_add(pages)
1869 };
1870
1871 let min_balance = T::Currency::minimum_balance();
1874 let num_operations = 1u32.saturating_add(T::Pages::get()); let tx_fee_buffer = (min_balance / 100u32.into()).saturating_mul(num_operations.into());
1876
1877 let total_needed = worst_case_deposit
1878 .saturating_add(tx_fee_buffer)
1879 .saturating_add(T::Currency::minimum_balance());
1880
1881 T::Currency::mint_into(&who, total_needed).unwrap();
1882 who
1883 }
1884
1885 pub(crate) fn roll_to(n: BlockNumberFor<T>, try_state: bool) {
1887 let now = frame_system::Pallet::<T>::block_number();
1888 assert!(n > now, "cannot roll to current or past block");
1889 let one: BlockNumberFor<T> = 1u32.into();
1890 let mut i = now + one;
1891 while i <= n {
1892 frame_system::BlockWeight::<T>::kill();
1894
1895 frame_system::Pallet::<T>::set_block_number(i);
1896 let mut meter = frame_system::Pallet::<T>::remaining_block_weight();
1897 Pallet::<T>::on_poll(i, &mut meter);
1898
1899 frame_system::Pallet::<T>::register_extra_weight_unchecked(
1901 meter.consumed(),
1902 DispatchClass::Mandatory,
1903 );
1904
1905 if try_state {
1907 Pallet::<T>::do_try_state(i).unwrap();
1908 verifier::Pallet::<T>::do_try_state(i).unwrap();
1909 unsigned::Pallet::<T>::do_try_state(i).unwrap();
1910 signed::Pallet::<T>::do_try_state(i).unwrap();
1911 }
1912
1913 i += one;
1914 }
1915 }
1916
1917 pub(crate) fn roll_next(try_state: bool) {
1919 Self::roll_to(frame_system::Pallet::<T>::block_number() + 1u32.into(), try_state);
1920 }
1921}
1922
1923impl<T: Config> ElectionProvider for Pallet<T> {
1924 type AccountId = T::AccountId;
1925 type BlockNumber = BlockNumberFor<T>;
1926 type Error = ElectionError<T>;
1927 type DataProvider = T::DataProvider;
1928 type Pages = T::Pages;
1929 type MaxWinnersPerPage = <T::Verifier as Verifier>::MaxWinnersPerPage;
1930 type MaxBackersPerWinner = <T::Verifier as Verifier>::MaxBackersPerWinner;
1931 type MaxBackersPerWinnerFinal = <T::Verifier as Verifier>::MaxBackersPerWinnerFinal;
1932
1933 fn elect(remaining: PageIndex) -> Result<BoundedSupportsOf<Self>, Self::Error> {
1934 match Self::status() {
1935 Ok(_) => (),
1937 Err(_) => return Err(ElectionError::NotOngoing),
1938 }
1939
1940 let current_phase = CurrentPhase::<T>::get();
1941 if let Phase::Export(expected) = current_phase {
1942 ensure!(expected == remaining, ElectionError::OutOfOrder);
1943 }
1944
1945 let result = T::Verifier::get_queued_solution_page(remaining)
1946 .ok_or(ElectionError::SupportPageNotAvailable)
1947 .or_else(|err: ElectionError<T>| {
1948 log!(
1949 debug,
1950 "primary election for page {} failed due to: {:?}, trying fallback",
1951 remaining,
1952 err,
1953 );
1954 Self::fallback_for_page(remaining)
1955 })
1956 .map_err(|err| {
1957 log!(debug, "fallback also ({:?}) failed for page {:?}", err, remaining);
1962 err
1963 })
1964 .map(|supports| {
1965 supports.into()
1967 });
1968
1969 if CurrentPhase::<T>::get().is_emergency() && result.is_err() {
1971 log!(error, "Emergency phase triggered, halting the election.");
1972 } else {
1973 if remaining.is_zero() {
1974 Self::rotate_round()
1975 } else {
1976 Self::phase_transition(Phase::Export(remaining - 1))
1977 }
1978 }
1979
1980 result
1981 }
1982
1983 fn start() -> Result<(), Self::Error> {
1984 match Self::status() {
1985 Err(()) => (),
1986 Ok(_) => return Err(ElectionError::Ongoing),
1987 }
1988
1989 Self::phase_transition(Phase::<T>::start_phase());
1990 Ok(())
1991 }
1992
1993 fn duration() -> Self::BlockNumber {
1994 Self::average_election_duration().into()
1995 }
1996
1997 fn status() -> Result<Option<Weight>, ()> {
1998 match <CurrentPhase<T>>::get() {
1999 Phase::Off => Err(()),
2001
2002 Phase::Signed(_) |
2004 Phase::SignedValidation(_) |
2005 Phase::Unsigned(_) |
2006 Phase::Snapshot(_) |
2007 Phase::Emergency => Ok(None),
2008
2009 Phase::Done => Ok(Some(T::WeightInfo::export_non_terminal())),
2011 Phase::Export(p) => {
2012 if p.is_zero() {
2013 Ok(Some(T::WeightInfo::export_terminal()))
2014 } else {
2015 Ok(Some(T::WeightInfo::export_non_terminal()))
2016 }
2017 },
2018 }
2019 }
2020
2021 #[cfg(feature = "runtime-benchmarks")]
2022 fn asap() {
2023 Self::create_targets_snapshot();
2025 for p in (Self::lsp()..=Self::msp()).rev() {
2026 Self::create_voters_snapshot_paged(p)
2027 }
2028 }
2029}
2030
2031#[cfg(test)]
2032mod phase_rotation {
2033 use super::{Event, *};
2034 use crate::{mock::*, verifier::Status, Phase};
2035 use frame_election_provider_support::ElectionProvider;
2036 use frame_support::assert_ok;
2037
2038 #[test]
2039 fn single_page() {
2040 ExtBuilder::full()
2041 .pages(1)
2042 .election_start(13)
2043 .fallback_mode(FallbackModes::Onchain)
2044 .build_and_execute(|| {
2045 assert_eq!(System::block_number(), 0);
2050 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2051 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 1));
2052 assert_eq!(MultiBlock::round(), 0);
2053
2054 roll_to(4);
2055 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2056 assert_eq!(MultiBlock::round(), 0);
2057
2058 roll_to(13);
2059 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(1));
2060 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 3));
2061
2062 roll_to(14);
2063 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(0));
2064 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 0));
2065
2066 roll_to(15);
2067 assert_eq!(MultiBlock::current_phase(), Phase::Signed(SignedPhase::get() - 1));
2068 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 1));
2069 assert_eq!(MultiBlock::round(), 0);
2070
2071 assert_eq!(
2072 multi_block_events_since_last_call(),
2073 vec![
2074 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(1) },
2075 Event::PhaseTransitioned {
2076 from: Phase::Snapshot(0),
2077 to: Phase::Signed(SignedPhase::get() - 1)
2078 }
2079 ]
2080 );
2081
2082 roll_to(19);
2083 assert_eq!(MultiBlock::current_phase(), Phase::Signed(0));
2084 assert_eq!(MultiBlock::round(), 0);
2085
2086 roll_to(20);
2087 assert_eq!(
2088 MultiBlock::current_phase(),
2089 Phase::SignedValidation(SignedValidationPhase::get())
2090 );
2091 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 1));
2092 assert_eq!(MultiBlock::round(), 0);
2093
2094 assert_eq!(
2095 multi_block_events_since_last_call(),
2096 vec![Event::PhaseTransitioned {
2097 from: Phase::Signed(0),
2098 to: Phase::SignedValidation(SignedValidationPhase::get())
2099 }],
2100 );
2101
2102 roll_to(26);
2103 assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(0));
2104 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 1));
2105 assert_eq!(MultiBlock::round(), 0);
2106
2107 roll_to(27);
2108 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(UnsignedPhase::get() - 1));
2109 assert_eq!(
2110 multi_block_events_since_last_call(),
2111 vec![Event::PhaseTransitioned {
2112 from: Phase::SignedValidation(0),
2113 to: Phase::Unsigned(UnsignedPhase::get() - 1)
2114 }],
2115 );
2116
2117 roll_to(31);
2118 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(0));
2119
2120 roll_to(32);
2122 assert!(MultiBlock::current_phase().is_done());
2123
2124 roll_to(33);
2126 assert!(MultiBlock::current_phase().is_done());
2127
2128 roll_to(34);
2130 assert!(MultiBlock::current_phase().is_done());
2131 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 1));
2132
2133 MultiBlock::elect(0).unwrap();
2134
2135 assert!(MultiBlock::current_phase().is_off());
2136 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 1));
2137 assert_eq!(MultiBlock::round(), 1);
2138
2139 roll_to(42);
2140 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2141 })
2142 }
2143
2144 #[test]
2145 fn multi_page_2() {
2146 ExtBuilder::full()
2147 .pages(2)
2148 .fallback_mode(FallbackModes::Onchain)
2149 .election_start(12)
2150 .build_and_execute(|| {
2151 assert_eq!(System::block_number(), 0);
2156 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2157 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 2));
2158 assert_eq!(MultiBlock::round(), 0);
2159
2160 roll_to(4);
2161 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2162 assert_eq!(MultiBlock::round(), 0);
2163
2164 roll_to(11);
2165 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2166 assert_eq!(MultiBlock::round(), 0);
2167
2168 roll_to(12);
2169 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(2));
2170 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 2));
2171
2172 roll_to(13);
2173 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(1));
2174 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 0));
2175
2176 roll_to(14);
2177 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(0));
2178 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 1));
2179
2180 roll_to(15);
2181 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2182 assert_eq!(MultiBlock::round(), 0);
2183 assert_eq!(MultiBlock::current_phase(), Phase::Signed(SignedPhase::get() - 1));
2184
2185 assert_eq!(
2186 multi_block_events_since_last_call(),
2187 vec![
2188 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(2) },
2189 Event::PhaseTransitioned {
2190 from: Phase::Snapshot(0),
2191 to: Phase::Signed(SignedPhase::get() - 1)
2192 }
2193 ]
2194 );
2195
2196 roll_to(19);
2197 assert_eq!(MultiBlock::current_phase(), Phase::Signed(0));
2198 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2199 assert_eq!(MultiBlock::round(), 0);
2200
2201 roll_to(20);
2202 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2203 assert_eq!(MultiBlock::round(), 0);
2204 assert_eq!(
2205 MultiBlock::current_phase(),
2206 Phase::SignedValidation(SignedValidationPhase::get())
2207 );
2208
2209 assert_eq!(
2210 multi_block_events_since_last_call(),
2211 vec![Event::PhaseTransitioned {
2212 from: Phase::Signed(0),
2213 to: Phase::SignedValidation(SignedValidationPhase::get())
2214 }],
2215 );
2216
2217 roll_to(26);
2218 assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(0));
2219 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2220 assert_eq!(MultiBlock::round(), 0);
2221
2222 roll_to(27);
2223 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(UnsignedPhase::get() - 1));
2224 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2225 assert_eq!(MultiBlock::round(), 0);
2226
2227 assert_eq!(
2228 multi_block_events_since_last_call(),
2229 vec![Event::PhaseTransitioned {
2230 from: Phase::SignedValidation(0),
2231 to: Phase::Unsigned(UnsignedPhase::get() - 1)
2232 }],
2233 );
2234
2235 roll_to(31);
2236 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(0));
2237 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2238
2239 roll_to(32);
2240 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2241 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2242
2243 roll_to(33);
2245 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2246
2247 MultiBlock::elect(0).unwrap();
2249 assert!(MultiBlock::current_phase().is_off());
2250
2251 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 2));
2253 assert_eq!(MultiBlock::round(), 1);
2254 })
2255 }
2256
2257 #[test]
2258 fn multi_page_3() {
2259 ExtBuilder::full()
2260 .pages(3)
2261 .fallback_mode(FallbackModes::Onchain)
2262 .build_and_execute(|| {
2263 assert_eq!(System::block_number(), 0);
2268 assert!(MultiBlock::current_phase().is_off());
2269 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 3));
2270 assert_eq!(MultiBlock::round(), 0);
2271
2272 roll_to(10);
2273 assert!(MultiBlock::current_phase().is_off());
2274 assert_eq!(MultiBlock::round(), 0);
2275
2276 roll_to(11);
2277 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(3));
2278 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(false, 3));
2280
2281 roll_to(12);
2282 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(2));
2283 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 0));
2284
2285 roll_to(13);
2286 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(1));
2287 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 1));
2288
2289 roll_to(14);
2290 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(0));
2291 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, 2));
2292
2293 roll_to(15);
2294 assert_ok!(Snapshot::<Runtime>::ensure_snapshot(true, Pages::get()));
2295 assert_eq!(MultiBlock::current_phase(), Phase::Signed(4));
2296 assert_eq!(
2297 multi_block_events_since_last_call(),
2298 vec![
2299 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(3) },
2300 Event::PhaseTransitioned {
2301 from: Phase::Snapshot(0),
2302 to: Phase::Signed(SignedPhase::get() - 1)
2303 }
2304 ]
2305 );
2306 assert_eq!(MultiBlock::round(), 0);
2307
2308 roll_to(19);
2309 assert_eq!(MultiBlock::current_phase(), Phase::Signed(0));
2310 assert_eq!(MultiBlock::round(), 0);
2311
2312 roll_to(20);
2313 assert_eq!(
2314 MultiBlock::current_phase(),
2315 Phase::SignedValidation(SignedValidationPhase::get())
2316 );
2317 assert_eq!(
2318 multi_block_events_since_last_call(),
2319 vec![Event::PhaseTransitioned {
2320 from: Phase::Signed(0),
2321 to: Phase::SignedValidation(SignedValidationPhase::get())
2322 }]
2323 );
2324
2325 roll_to(26);
2326 assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(0));
2327 assert_eq!(MultiBlock::round(), 0);
2328
2329 roll_to(27);
2330 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(UnsignedPhase::get() - 1));
2331 assert_eq!(
2332 multi_block_events_since_last_call(),
2333 vec![Event::PhaseTransitioned {
2334 from: Phase::SignedValidation(0),
2335 to: Phase::Unsigned(UnsignedPhase::get() - 1)
2336 }]
2337 );
2338
2339 roll_to(31);
2340 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(0));
2341
2342 roll_to(32);
2343 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2344
2345 roll_to(33);
2347 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2348
2349 MultiBlock::elect(0).unwrap();
2350 assert!(MultiBlock::current_phase().is_off());
2351
2352 assert_none_snapshot();
2354 assert_eq!(MultiBlock::round(), 1);
2355 })
2356 }
2357
2358 #[test]
2359 fn weights_registered() {
2360 ExtBuilder::full().build_and_execute(|| {
2368 roll_to(10);
2369 assert!(MultiBlock::current_phase().is_off());
2370 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2372
2373 roll_next_and_phase(Phase::Snapshot(3));
2375 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2376
2377 roll_next_and_phase(Phase::Snapshot(2));
2378 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 5));
2379
2380 roll_next_and_phase(Phase::Snapshot(1));
2381 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 5));
2382
2383 roll_next_and_phase(Phase::Snapshot(0));
2384 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 5));
2385
2386 roll_next_and_phase(Phase::Signed(SignedPhase::get() - 1));
2387 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 5));
2388
2389 roll_next_and_phase(Phase::Signed(SignedPhase::get() - 2));
2391 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2392
2393 {
2395 let paged = mine_full_solution().unwrap();
2396 load_signed_for_verification(999, paged.clone());
2397 }
2398
2399 roll_to_signed_validation_open();
2401 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 3));
2402
2403 roll_next_and_phase_verifier(
2404 Phase::SignedValidation(SignedValidationPhase::get() - 1),
2405 Status::Ongoing(1),
2406 );
2407 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(1, 7));
2408
2409 roll_next_and_phase_verifier(
2410 Phase::SignedValidation(SignedValidationPhase::get() - 2),
2411 Status::Ongoing(0),
2412 );
2413 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(1, 7));
2414
2415 roll_next_and_phase_verifier(
2416 Phase::SignedValidation(SignedValidationPhase::get() - 3),
2417 Status::Nothing,
2418 );
2419 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(1, 7));
2420
2421 roll_to_unsigned_open();
2423 assert!(MultiBlock::current_phase().is_unsigned());
2424 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2425
2426 roll_next_and_phase(Phase::Unsigned(UnsignedPhase::get() - 2));
2427 assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2428
2429 });
2432 }
2433
2434 #[test]
2435 fn no_unsigned_phase() {
2436 ExtBuilder::full()
2437 .pages(3)
2438 .unsigned_phase(0)
2439 .election_start(16)
2440 .fallback_mode(FallbackModes::Onchain)
2441 .build_and_execute(|| {
2442 assert_eq!(System::block_number(), 0);
2447 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2448 assert_none_snapshot();
2449 assert_eq!(MultiBlock::round(), 0);
2450
2451 roll_to(4);
2452 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2453 assert_eq!(MultiBlock::round(), 0);
2454
2455 roll_to(16);
2456 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(3));
2457
2458 roll_to(17);
2459 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(2));
2460
2461 roll_to(18);
2462 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(1));
2463
2464 roll_to(19);
2465 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(0));
2466
2467 roll_to(20);
2468 assert_eq!(MultiBlock::current_phase(), Phase::Signed(SignedPhase::get() - 1));
2469
2470 assert_full_snapshot();
2471 assert_eq!(MultiBlock::round(), 0);
2472
2473 roll_to(25);
2474 assert_eq!(
2475 MultiBlock::current_phase(),
2476 Phase::SignedValidation(SignedValidationPhase::get())
2477 );
2478
2479 assert_eq!(
2480 multi_block_events_since_last_call(),
2481 vec![
2482 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(3) },
2483 Event::PhaseTransitioned {
2484 from: Phase::Snapshot(0),
2485 to: Phase::Signed(SignedPhase::get() - 1)
2486 },
2487 Event::PhaseTransitioned {
2488 from: Phase::Signed(0),
2489 to: Phase::SignedValidation(SignedValidationPhase::get())
2490 },
2491 ]
2492 );
2493
2494 roll_to(31);
2496 assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(0));
2497
2498 roll_to(32);
2500 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2501
2502 roll_to(33);
2503 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2504
2505 MultiBlock::elect(0).unwrap();
2506 assert!(MultiBlock::current_phase().is_off());
2507
2508 assert_none_snapshot();
2510 assert_eq!(MultiBlock::round(), 1);
2511 assert_ok!(signed::Submissions::<Runtime>::ensure_killed(0));
2512 verifier::QueuedSolution::<Runtime>::assert_killed();
2513 })
2514 }
2515
2516 #[test]
2517 fn no_signed_phase() {
2518 ExtBuilder::full()
2519 .pages(3)
2520 .signed_phase(0, 0)
2521 .election_start(21)
2522 .fallback_mode(FallbackModes::Onchain)
2523 .build_and_execute(|| {
2524 assert_eq!(System::block_number(), 0);
2529 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2530 assert_none_snapshot();
2531 assert_eq!(MultiBlock::round(), 0);
2532
2533 roll_to(20);
2534 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2535 assert_eq!(MultiBlock::round(), 0);
2536
2537 roll_to(21);
2538 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(3));
2539 roll_to(22);
2540 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(2));
2541 roll_to(23);
2542 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(1));
2543 roll_to(24);
2544 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(0));
2545
2546 roll_to(25);
2547 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(UnsignedPhase::get() - 1));
2548 assert_full_snapshot();
2549 assert_eq!(MultiBlock::round(), 0);
2550
2551 assert_eq!(
2552 multi_block_events(),
2553 vec![
2554 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(3) },
2555 Event::PhaseTransitioned {
2556 from: Phase::Snapshot(0),
2557 to: Phase::Unsigned(UnsignedPhase::get() - 1)
2558 },
2559 ]
2560 );
2561
2562 roll_to(29);
2563 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(0));
2564
2565 roll_to(30);
2566 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2567 roll_to(31);
2568 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2569
2570 MultiBlock::elect(0).unwrap();
2572 assert!(MultiBlock::current_phase().is_off());
2573
2574 assert_none_snapshot();
2576 assert_eq!(MultiBlock::round(), 1);
2577 assert_ok!(signed::Submissions::<Runtime>::ensure_killed(0));
2578 verifier::QueuedSolution::<Runtime>::assert_killed();
2579 })
2580 }
2581
2582 #[test]
2583 #[should_panic(expected = "either signed or unsigned phase must be set")]
2584 fn no_signed_and_unsigned_phase() {
2585 ExtBuilder::full()
2586 .pages(3)
2587 .signed_phase(0, 0)
2588 .unsigned_phase(0)
2589 .election_start(10)
2590 .fallback_mode(FallbackModes::Onchain)
2591 .build_and_execute(|| {
2592 });
2594 }
2595
2596 #[test]
2597 #[should_panic(
2598 expected = "signed validation phase should be a multiple of the number of pages."
2599 )]
2600 fn incorrect_signed_validation_phase_shorter_than_number_of_pages() {
2601 ExtBuilder::full().pages(3).signed_validation_phase(2).build_and_execute(|| {})
2602 }
2603
2604 #[test]
2605 #[should_panic(
2606 expected = "signed validation phase should be a multiple of the number of pages."
2607 )]
2608 fn incorret_signed_validation_phase_not_a_multiple_of_the_number_of_pages() {
2609 ExtBuilder::full().pages(3).signed_validation_phase(7).build_and_execute(|| {})
2610 }
2611
2612 #[test]
2613 fn are_we_done_back_to_signed() {
2614 ExtBuilder::full()
2615 .are_we_done(AreWeDoneModes::BackToSigned)
2616 .build_and_execute(|| {
2617 roll_to_last_unsigned();
2619
2620 assert_eq!(MultiBlock::round(), 0);
2621 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(0));
2622 assert_eq!(
2623 multi_block_events_since_last_call(),
2624 vec![
2625 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(3) },
2626 Event::PhaseTransitioned { from: Phase::Snapshot(0), to: Phase::Signed(4) },
2627 Event::PhaseTransitioned {
2628 from: Phase::Signed(0),
2629 to: Phase::SignedValidation(SignedValidationPhase::get())
2630 },
2631 Event::PhaseTransitioned {
2632 from: Phase::SignedValidation(0),
2633 to: Phase::Unsigned(4)
2634 }
2635 ]
2636 );
2637
2638 roll_next_and_phase(Phase::Signed(SignedPhase::get() - 1));
2640 assert_eq!(MultiBlock::round(), 0);
2642
2643 roll_next_and_phase(Phase::Signed(SignedPhase::get() - 2));
2645 roll_next_and_phase(Phase::Signed(SignedPhase::get() - 3));
2646 });
2647 }
2648
2649 #[test]
2650 fn export_phase_only_transitions_on_elect() {
2651 ExtBuilder::full()
2652 .pages(3)
2653 .election_start(13)
2654 .fallback_mode(FallbackModes::Onchain)
2655 .build_and_execute(|| {
2656 roll_to_done();
2657
2658 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2659
2660 roll_next_and_phase(Phase::Done);
2662
2663 assert_ok!(MultiBlock::elect(2)); assert_eq!(MultiBlock::current_phase(), Phase::Export(1));
2666
2667 roll_next_and_phase(Phase::Export(1));
2669
2670 assert_ok!(MultiBlock::elect(1));
2672 assert_eq!(MultiBlock::current_phase(), Phase::Export(0));
2673
2674 roll_next_and_phase(Phase::Export(0));
2676
2677 assert_ok!(MultiBlock::elect(0));
2679 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2680 });
2681 }
2682
2683 #[test]
2684 fn export_phase_out_of_order_elect_fails() {
2685 ExtBuilder::full()
2686 .pages(3)
2687 .election_start(13)
2688 .fallback_mode(FallbackModes::Onchain)
2689 .build_and_execute(|| {
2690 roll_to_done();
2691
2692 assert_eq!(MultiBlock::current_phase(), Phase::Done);
2693
2694 assert_ok!(MultiBlock::elect(2)); assert_eq!(MultiBlock::current_phase(), Phase::Export(1));
2697
2698 assert_eq!(MultiBlock::elect(2), Err(ElectionError::OutOfOrder));
2700
2701 assert_eq!(MultiBlock::elect(0), Err(ElectionError::OutOfOrder));
2703
2704 assert_ok!(MultiBlock::elect(1));
2706 assert_eq!(MultiBlock::current_phase(), Phase::Export(0));
2707 });
2708 }
2709
2710 #[test]
2711 #[cfg_attr(debug_assertions, should_panic(expected = "Defensive failure has been triggered!"))]
2712 fn target_snapshot_failed_event_emitted() {
2713 ExtBuilder::full()
2714 .pages(2)
2715 .election_start(13)
2716 .build_and_execute(|| {
2717 let too_many_targets: Vec<AccountId> = (1..=100).collect();
2720 Targets::set(too_many_targets);
2721
2722 roll_to(13);
2723 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(2));
2724
2725 let _ = multi_block_events_since_last_call();
2727
2728 roll_to(14);
2731
2732 let events = multi_block_events_since_last_call();
2734 assert!(
2735 events.contains(&Event::UnexpectedTargetSnapshotFailed),
2736 "UnexpectedTargetSnapshotFailed event should have been emitted when target snapshot creation fails. Events: {:?}",
2737 events
2738 );
2739
2740 assert_eq!(MultiBlock::current_phase(), Phase::Snapshot(1));
2742 });
2743 }
2744}
2745
2746#[cfg(test)]
2747mod election_provider {
2748 use super::*;
2749 use crate::{
2750 mock::*,
2751 unsigned::miner::OffchainWorkerMiner,
2752 verifier::{AsynchronousVerifier, Status, Verifier},
2753 Phase,
2754 };
2755 use frame_election_provider_support::{BoundedSupport, BoundedSupports, ElectionProvider};
2756 use frame_support::{assert_storage_noop, testing_prelude::bounded_vec};
2757
2758 #[test]
2762 fn multi_page_elect_simple_works() {
2763 ExtBuilder::full().build_and_execute(|| {
2764 roll_to_signed_open();
2765 assert!(MultiBlock::current_phase().is_signed());
2766
2767 let paged = OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false).unwrap();
2769 let score = paged.score;
2770
2771 load_signed_for_verification(99, paged);
2773
2774 roll_to_signed_validation_open();
2776
2777 assert_eq!(
2778 multi_block_events(),
2779 vec![
2780 Event::PhaseTransitioned {
2781 from: Phase::Off,
2782 to: Phase::Snapshot(Pages::get())
2783 },
2784 Event::PhaseTransitioned {
2785 from: Phase::Snapshot(0),
2786 to: Phase::Signed(SignedPhase::get() - 1)
2787 },
2788 Event::PhaseTransitioned {
2789 from: Phase::Signed(0),
2790 to: Phase::SignedValidation(SignedValidationPhase::get())
2791 }
2792 ]
2793 );
2794 assert_eq!(verifier_events_since_last_call(), vec![]);
2795
2796 assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), None);
2798 assert_eq!(
2799 <Runtime as crate::Config>::Verifier::status(),
2800 verifier::Status::Ongoing(2)
2801 );
2802
2803 roll_next_and_phase_verifier(Phase::SignedValidation(5), Status::Ongoing(1));
2805 assert_eq!(verifier_events_since_last_call(), vec![verifier::Event::Verified(2, 2)]);
2806
2807 roll_next_and_phase_verifier(Phase::SignedValidation(4), Status::Ongoing(0));
2808 assert_eq!(verifier_events_since_last_call(), vec![verifier::Event::Verified(1, 2)]);
2809
2810 roll_next_and_phase_verifier(Phase::SignedValidation(3), Status::Nothing);
2811 assert_eq!(
2812 verifier_events_since_last_call(),
2813 vec![verifier::Event::Verified(0, 2), verifier::Event::Queued(score, None)]
2814 );
2815
2816 assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), Some(score));
2818
2819 roll_to_unsigned_open();
2822
2823 assert!(MultiBlock::current_phase().is_unsigned_opened_now());
2825 assert_eq!(MultiBlock::round(), 0);
2826 assert_full_snapshot();
2827
2828 let _paged_solution = (MultiBlock::lsp()..MultiBlock::msp())
2830 .rev() .map(|page| {
2832 MultiBlock::elect(page as PageIndex).unwrap();
2833 if page == 0 {
2834 assert!(MultiBlock::current_phase().is_off())
2835 } else {
2836 assert_eq!(MultiBlock::current_phase(), Phase::Export(page - 1))
2837 }
2838 })
2839 .collect::<Vec<_>>();
2840
2841 verifier::QueuedSolution::<Runtime>::assert_killed();
2843 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2845 assert_eq!(Round::<Runtime>::get(), 1);
2847 assert_storage_noop!(Snapshot::<Runtime>::kill());
2849 assert_ok!(signed::Submissions::<Runtime>::ensure_killed(0));
2853 });
2854 }
2855
2856 #[test]
2857 fn multi_page_elect_fast_track() {
2858 ExtBuilder::full().build_and_execute(|| {
2859 roll_to_signed_open();
2860 let round = MultiBlock::round();
2861 assert!(MultiBlock::current_phase().is_signed());
2862
2863 let paged = OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false).unwrap();
2865 let score = paged.score;
2866 load_signed_for_verification_and_start(99, paged, 0);
2867
2868 assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), None);
2870
2871 roll_next_and_phase_verifier(Phase::SignedValidation(5), Status::Ongoing(1));
2873 roll_next_and_phase_verifier(Phase::SignedValidation(4), Status::Ongoing(0));
2874 roll_next_and_phase_verifier(Phase::SignedValidation(3), Status::Nothing);
2875
2876 assert_eq!(
2877 verifier_events_since_last_call(),
2878 vec![
2879 verifier::Event::Verified(2, 2),
2880 verifier::Event::Verified(1, 2),
2881 verifier::Event::Verified(0, 2),
2882 verifier::Event::Queued(score, None),
2883 ]
2884 );
2885
2886 assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), Some(score));
2888
2889 roll_to_unsigned_open();
2891
2892 assert!(MultiBlock::current_phase().is_unsigned_opened_now());
2894 assert_eq!(Round::<Runtime>::get(), 0);
2895 assert_full_snapshot();
2896
2897 let _supports = crate::Pallet::<Runtime>::elect(0).unwrap();
2899
2900 assert_eq!(MultiBlock::round(), round + 1);
2902 verifier::QueuedSolution::<Runtime>::assert_killed();
2904 assert_eq!(MultiBlock::current_phase(), Phase::Off);
2906 assert_eq!(Round::<Runtime>::get(), 1);
2908 assert_none_snapshot();
2910 assert_ok!(signed::Submissions::<Runtime>::ensure_killed(round));
2912 });
2913 }
2914
2915 #[test]
2916 fn elect_does_not_finish_without_call_of_page_0() {
2917 ExtBuilder::full().build_and_execute(|| {
2918 roll_to_signed_open();
2919 assert!(MultiBlock::current_phase().is_signed());
2920
2921 let paged = OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false).unwrap();
2923 let score = paged.score;
2924 load_signed_for_verification_and_start(99, paged, 0);
2925
2926 assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), None);
2928
2929 roll_next_and_phase_verifier(Phase::SignedValidation(5), Status::Ongoing(1));
2931 roll_next_and_phase_verifier(Phase::SignedValidation(4), Status::Ongoing(0));
2932 roll_next_and_phase_verifier(Phase::SignedValidation(3), Status::Nothing);
2933
2934 assert_eq!(
2935 verifier_events_since_last_call(),
2936 vec![
2937 verifier::Event::Verified(2, 2),
2938 verifier::Event::Verified(1, 2),
2939 verifier::Event::Verified(0, 2),
2940 verifier::Event::Queued(score, None),
2941 ]
2942 );
2943
2944 assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), Some(score));
2946
2947 roll_to_unsigned_open();
2949
2950 assert!(MultiBlock::current_phase().is_unsigned_opened_now());
2952 assert_eq!(Round::<Runtime>::get(), 0);
2953 assert_full_snapshot();
2954
2955 let solutions = (1..=MultiBlock::msp())
2957 .rev() .map(|page| {
2959 crate::Pallet::<Runtime>::elect(page as PageIndex).unwrap();
2960 assert!(MultiBlock::current_phase().is_export());
2961 })
2962 .collect::<Vec<_>>();
2963 assert_eq!(solutions.len(), 2);
2964
2965 assert!(MultiBlock::current_phase().is_export());
2967 assert_eq!(Round::<Runtime>::get(), 0);
2968 assert_full_snapshot();
2969 });
2970 }
2971
2972 #[test]
2973 fn continue_fallback_works() {
2974 ExtBuilder::full().fallback_mode(FallbackModes::Continue).build_and_execute(|| {
2976 roll_to_unsigned_open();
2978
2979 let miner_pages = <Runtime as unsigned::Config>::MinerPages::get();
2981 let unsigned_solution =
2983 OffchainWorkerMiner::<Runtime>::mine_solution(miner_pages, true).unwrap();
2984
2985 assert_ok!(UnsignedPallet::submit_unsigned(
2987 RuntimeOrigin::from(frame_system::RawOrigin::Authorized),
2988 Box::new(unsigned_solution)
2989 ));
2990
2991 roll_to_done();
2993
2994 let result1 = MultiBlock::elect(2);
2998 assert!(result1.is_ok());
2999 assert_eq!(MultiBlock::current_phase(), Phase::Export(1));
3000
3001 let result2 = MultiBlock::elect(1);
3005 assert!(result2.is_err());
3006 assert_eq!(MultiBlock::current_phase(), Phase::Export(0));
3007
3008 let result3 = MultiBlock::elect(0);
3010 assert!(result3.is_err());
3011 assert!(matches!(MultiBlock::current_phase(), Phase::Off));
3012 });
3013 }
3014
3015 #[test]
3016 fn skip_unsigned_phase() {
3017 ExtBuilder::full().build_and_execute(|| {
3018 roll_to_signed_open();
3019 assert!(MultiBlock::current_phase().is_signed());
3020 let round = MultiBlock::round();
3021
3022 let paged = OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false).unwrap();
3024
3025 load_signed_for_verification_and_start_and_roll_to_verified(99, paged, 0);
3026
3027 assert!(matches!(MultiBlock::current_phase(), Phase::SignedValidation(_)));
3030 assert_eq!(Round::<Runtime>::get(), 0);
3031 assert_full_snapshot();
3032
3033 let _paged_solution = (MultiBlock::lsp()..MultiBlock::msp())
3035 .rev() .map(|page| {
3037 MultiBlock::elect(page as PageIndex).unwrap();
3038 if page == 0 {
3039 assert!(MultiBlock::current_phase().is_off())
3040 } else {
3041 assert!(MultiBlock::current_phase().is_export())
3042 }
3043 })
3044 .collect::<Vec<_>>();
3045
3046 assert_eq!(MultiBlock::round(), round + 1);
3048 verifier::QueuedSolution::<Runtime>::assert_killed();
3050 assert_eq!(MultiBlock::current_phase(), Phase::Off);
3052 assert_none_snapshot();
3054 assert_ok!(signed::Submissions::<Runtime>::ensure_killed(round));
3056 });
3057 }
3058
3059 #[test]
3060 fn call_to_elect_should_prevent_any_submission() {
3061 use frame_support::{traits::Authorize, unsigned::TransactionSource};
3062 ExtBuilder::full().build_and_execute(|| {
3063 roll_to_signed_open();
3064 assert!(MultiBlock::current_phase().is_signed());
3065
3066 let paged = OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false).unwrap();
3068 load_signed_for_verification_and_start_and_roll_to_verified(99, paged, 0);
3069
3070 assert!(matches!(MultiBlock::current_phase(), Phase::SignedValidation(_)));
3071
3072 assert!(MultiBlock::elect(MultiBlock::msp()).is_ok());
3074
3075 assert_noop!(
3077 SignedPallet::submit_page(RuntimeOrigin::signed(999), 0, Default::default()),
3078 crate::signed::Error::<Runtime>::PhaseNotSigned,
3079 );
3080 assert_noop!(
3081 SignedPallet::register(RuntimeOrigin::signed(999), Default::default()),
3082 crate::signed::Error::<Runtime>::PhaseNotSigned,
3083 );
3084 assert_storage_noop!(assert!(unsigned::Call::<Runtime>::submit_unsigned {
3085 paged_solution: Default::default()
3086 }
3087 .authorize(TransactionSource::InBlock)
3088 .unwrap()
3089 .is_err()));
3090 });
3091 }
3092
3093 #[test]
3094 fn multi_page_onchain_elect_fallback_works() {
3095 ExtBuilder::full().fallback_mode(FallbackModes::Onchain).build_and_execute(|| {
3096 roll_to_signed_open();
3097
3098 assert_eq!(
3100 MultiBlock::elect(2).unwrap(),
3101 BoundedSupports(bounded_vec![
3102 (10, BoundedSupport { total: 15, voters: bounded_vec![(1, 10), (4, 5)] }),
3103 (
3104 40,
3105 BoundedSupport {
3106 total: 25,
3107 voters: bounded_vec![(2, 10), (3, 10), (4, 5)]
3108 }
3109 )
3110 ])
3111 );
3112 assert_eq!(
3114 MultiBlock::elect(1).unwrap(),
3115 BoundedSupports(bounded_vec![
3116 (10, BoundedSupport { total: 15, voters: bounded_vec![(5, 5), (8, 10)] }),
3117 (
3118 30,
3119 BoundedSupport {
3120 total: 25,
3121 voters: bounded_vec![(5, 5), (6, 10), (7, 10)]
3122 }
3123 )
3124 ])
3125 );
3126 assert_eq!(
3128 MultiBlock::elect(0).unwrap(),
3129 BoundedSupports(bounded_vec![
3130 (30, BoundedSupport { total: 30, voters: bounded_vec![(30, 30)] }),
3131 (40, BoundedSupport { total: 40, voters: bounded_vec![(40, 40)] })
3132 ])
3133 );
3134
3135 assert_eq!(
3136 multi_block_events(),
3137 vec![
3138 Event::PhaseTransitioned {
3139 from: Phase::Off,
3140 to: Phase::Snapshot(Pages::get())
3141 },
3142 Event::PhaseTransitioned {
3143 from: Phase::Snapshot(0),
3144 to: Phase::Signed(SignedPhase::get() - 1)
3145 },
3146 Event::PhaseTransitioned {
3147 from: Phase::Signed(SignedPhase::get() - 1),
3148 to: Phase::Export(1)
3149 },
3150 Event::PhaseTransitioned { from: Phase::Export(0), to: Phase::Off }
3151 ]
3152 );
3153 assert_eq!(verifier_events(), vec![]);
3154
3155 assert_eq!(MultiBlock::current_phase(), Phase::Off);
3157 });
3158 }
3159
3160 #[test]
3161 fn multi_page_fallback_shortcut_to_msp_works() {
3162 ExtBuilder::full().fallback_mode(FallbackModes::Onchain).build_and_execute(|| {
3163 roll_to_signed_open();
3164
3165 assert!(MultiBlock::elect(0).is_ok());
3167
3168 assert_eq!(
3169 multi_block_events(),
3170 vec![
3171 Event::PhaseTransitioned {
3172 from: Phase::Off,
3173 to: Phase::Snapshot(Pages::get())
3174 },
3175 Event::PhaseTransitioned {
3176 from: Phase::Snapshot(0),
3177 to: Phase::Signed(SignedPhase::get() - 1)
3178 },
3179 Event::PhaseTransitioned {
3180 from: Phase::Signed(SignedPhase::get() - 1),
3181 to: Phase::Off
3182 }
3183 ]
3184 );
3185
3186 assert_eq!(MultiBlock::current_phase(), Phase::Off);
3188 });
3189 }
3190
3191 #[test]
3192 fn elect_call_when_not_ongoing() {
3193 ExtBuilder::full().fallback_mode(FallbackModes::Onchain).build_and_execute(|| {
3194 roll_to_snapshot_created();
3195 assert_eq!(MultiBlock::status(), Ok(None));
3196 assert!(MultiBlock::elect(0).is_ok());
3197 });
3198 ExtBuilder::full().fallback_mode(FallbackModes::Onchain).build_and_execute(|| {
3199 roll_to(10);
3200 assert_eq!(MultiBlock::status(), Err(()));
3201 assert_eq!(MultiBlock::elect(0), Err(ElectionError::NotOngoing));
3202 });
3203 }
3204}
3205
3206#[cfg(test)]
3207mod manage_ops {
3208 use super::*;
3209 use crate::mock::*;
3210
3211 #[test]
3212 fn trigger_fallback_works() {
3213 ExtBuilder::full()
3214 .fallback_mode(FallbackModes::Emergency)
3215 .build_and_execute(|| {
3216 roll_to_signed_open();
3217
3218 assert_noop!(
3220 MultiBlock::manage(
3221 RuntimeOrigin::signed(Manager::get() + 1),
3222 ManagerOperation::EmergencyFallback
3223 ),
3224 DispatchError::BadOrigin
3225 );
3226
3227 assert_eq!(
3230 MultiBlock::elect(0),
3231 Err(ElectionError::Fallback("Emergency phase started.".to_string()))
3232 );
3233 assert_eq!(MultiBlock::current_phase(), Phase::Emergency);
3234
3235 FallbackMode::set(FallbackModes::Onchain);
3237 assert_ok!(MultiBlock::manage(
3238 RuntimeOrigin::signed(Manager::get()),
3239 ManagerOperation::EmergencyFallback
3240 ));
3241
3242 assert_eq!(MultiBlock::current_phase(), Phase::Emergency);
3243 assert_ok!(MultiBlock::elect(0));
3244 assert_eq!(MultiBlock::current_phase(), Phase::Off);
3245
3246 assert_eq!(
3247 multi_block_events(),
3248 vec![
3249 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(3) },
3250 Event::PhaseTransitioned {
3251 from: Phase::Snapshot(0),
3252 to: Phase::Signed(SignedPhase::get() - 1)
3253 },
3254 Event::PhaseTransitioned {
3255 from: Phase::Signed(SignedPhase::get() - 1),
3256 to: Phase::Emergency
3257 },
3258 Event::PhaseTransitioned { from: Phase::Emergency, to: Phase::Off }
3259 ]
3260 );
3261 assert_eq!(
3262 verifier_events(),
3263 vec![verifier::Event::Queued(
3264 ElectionScore { minimal_stake: 15, sum_stake: 40, sum_stake_squared: 850 },
3265 None
3266 )]
3267 );
3268 })
3269 }
3270
3271 #[test]
3282 fn force_rotate_round() {
3283 ExtBuilder::full().build_and_execute(|| {
3284 roll_to_signed_open();
3285 let round = MultiBlock::round();
3286 let paged =
3287 unsigned::miner::OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false)
3288 .unwrap();
3289 load_signed_for_verification_and_start_and_roll_to_verified(99, paged, 0);
3290
3291 assert_full_snapshot();
3293 assert!(verifier::QueuedSolution::<T>::queued_score().is_some());
3295 assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(2));
3297
3298 assert_noop!(
3302 MultiBlock::manage(
3303 RuntimeOrigin::signed(Manager::get() + 1),
3304 ManagerOperation::ForceRotateRound
3305 ),
3306 DispatchError::BadOrigin
3307 );
3308 assert_ok!(MultiBlock::manage(
3310 RuntimeOrigin::signed(Manager::get()),
3311 ManagerOperation::ForceRotateRound
3312 ));
3313
3314 assert_eq!(MultiBlock::current_phase(), Phase::Off);
3316 assert_eq!(MultiBlock::round(), round + 1);
3318 assert_none_snapshot();
3320 verifier::QueuedSolution::<T>::assert_killed();
3322 });
3323 }
3324
3325 #[test]
3326 fn force_set_phase() {
3327 ExtBuilder::full().build_and_execute(|| {
3328 roll_to_signed_open();
3329 assert_eq!(MultiBlock::current_phase(), Phase::Signed(SignedPhase::get() - 1));
3330
3331 assert_noop!(
3333 MultiBlock::manage(
3334 RuntimeOrigin::signed(Manager::get() + 1),
3335 ManagerOperation::ForceSetPhase(Phase::Done)
3336 ),
3337 DispatchError::BadOrigin
3338 );
3339
3340 assert_ok!(MultiBlock::manage(
3342 RuntimeOrigin::signed(Manager::get()),
3343 ManagerOperation::ForceSetPhase(Phase::Unsigned(UnsignedPhase::get() - 1))
3344 ));
3345
3346 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(UnsignedPhase::get() - 1));
3347
3348 assert_ok!(MultiBlock::manage(
3350 RuntimeOrigin::root(),
3351 ManagerOperation::ForceSetPhase(Phase::Unsigned(UnsignedPhase::get() - 2))
3352 ));
3353 assert_eq!(MultiBlock::current_phase(), Phase::Unsigned(UnsignedPhase::get() - 2));
3354 });
3355 }
3356}
3357#[cfg(test)]
3358mod admin_ops {
3359 use super::*;
3360 use crate::mock::*;
3361
3362 #[test]
3363 fn set_solution_emergency_works() {
3364 ExtBuilder::full().build_and_execute(|| {
3365 roll_to_signed_open();
3366
3367 assert_noop!(
3369 MultiBlock::admin(
3370 RuntimeOrigin::signed(Manager::get() + 1),
3371 AdminOperation::EmergencySetSolution(Default::default(), Default::default())
3372 ),
3373 DispatchError::BadOrigin
3374 );
3375
3376 assert_noop!(
3378 MultiBlock::admin(
3379 RuntimeOrigin::signed(Manager::get()),
3380 AdminOperation::EmergencySetSolution(Default::default(), Default::default())
3381 ),
3382 DispatchError::BadOrigin
3383 );
3384
3385 assert_eq!(
3387 MultiBlock::elect(0),
3388 Err(ElectionError::Fallback("Emergency phase started.".to_string()))
3389 );
3390 assert_eq!(MultiBlock::current_phase(), Phase::Emergency);
3391
3392 let (emergency, score) = emergency_solution();
3394 assert_ok!(MultiBlock::admin(
3395 RuntimeOrigin::root(),
3396 AdminOperation::EmergencySetSolution(Box::new(emergency), score)
3397 ));
3398
3399 assert_eq!(MultiBlock::current_phase(), Phase::Emergency);
3400 assert_ok!(MultiBlock::elect(0));
3401 assert_eq!(MultiBlock::current_phase(), Phase::Off);
3402
3403 assert_eq!(
3404 multi_block_events(),
3405 vec![
3406 Event::PhaseTransitioned { from: Phase::Off, to: Phase::Snapshot(3) },
3407 Event::PhaseTransitioned {
3408 from: Phase::Snapshot(0),
3409 to: Phase::Signed(SignedPhase::get() - 1)
3410 },
3411 Event::PhaseTransitioned {
3412 from: Phase::Signed(SignedPhase::get() - 1),
3413 to: Phase::Emergency
3414 },
3415 Event::PhaseTransitioned { from: Phase::Emergency, to: Phase::Off }
3416 ]
3417 );
3418 assert_eq!(
3419 verifier_events(),
3420 vec![verifier::Event::Queued(
3421 ElectionScore { minimal_stake: 55, sum_stake: 130, sum_stake_squared: 8650 },
3422 None
3423 )]
3424 );
3425 })
3426 }
3427
3428 #[test]
3429 fn set_minimum_solution_score() {
3430 ExtBuilder::full().build_and_execute(|| {
3431 assert_noop!(
3433 MultiBlock::admin(
3434 RuntimeOrigin::signed(Manager::get() + 1),
3435 AdminOperation::SetMinUntrustedScore(ElectionScore {
3436 minimal_stake: 100,
3437 ..Default::default()
3438 })
3439 ),
3440 DispatchError::BadOrigin
3441 );
3442
3443 assert_noop!(
3445 MultiBlock::admin(
3446 RuntimeOrigin::signed(Manager::get()),
3447 AdminOperation::SetMinUntrustedScore(ElectionScore {
3448 minimal_stake: 100,
3449 ..Default::default()
3450 })
3451 ),
3452 DispatchError::BadOrigin
3453 );
3454
3455 assert_eq!(VerifierPallet::minimum_score(), None);
3456 assert_ok!(MultiBlock::admin(
3457 RuntimeOrigin::root(),
3458 AdminOperation::SetMinUntrustedScore(ElectionScore {
3459 minimal_stake: 100,
3460 ..Default::default()
3461 })
3462 ));
3463 assert_eq!(
3464 VerifierPallet::minimum_score().unwrap(),
3465 ElectionScore { minimal_stake: 100, ..Default::default() }
3466 );
3467 });
3468 }
3469}