referrerpolicy=no-referrer-when-downgrade

pallet_election_provider_multi_block/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Multi-phase, multi-block, election provider pallet.
19//!
20//! > This pallet is sometimes abbreviated as `EPMB`, and `pallet_election_provider_multi_phase` as
21//! > `EPM`.
22//!
23//! ## Overall idea
24//!
25//! `pallet_election_provider_multi_phase` provides the basic ability for NPoS solutions to be
26//! computed offchain (essentially anywhere) and submitted back to the chain as signed or unsigned
27//! transaction, with sensible configurations and fail-safe mechanisms to ensure system safety.
28//! Nonetheless, it has a limited capacity in terms of number of voters it can process in a **single
29//! block**.
30//!
31//! This pallet takes `EPM` system, keeps most of its ideas and core premises, and extends it to
32//! support paginated, multi-block operations. The final goal of this pallet is to scale linearly
33//! with the number of blocks allocated to the elections. Moreover, the amount of work that it does
34//! in one block should be bounded and measurable, making it suitable for a parachain. In principle,
35//! with large enough blocks (in a dedicated parachain), the number of voters included in the NPoS
36//! system can grow significantly (yet, obviously not indefinitely).
37//!
38//! Note that this pallet does not consider how the recipient is processing the results. To ensure
39//! scalability, the recipient of this pallet's data (i.e. `pallet-staking`) must also be capable of
40//! pagination and multi-block processing.
41//!
42//! ## Companion pallets
43//!
44//! This pallet will only function in a sensible way if it is peered with its companion pallets.
45//!
46//! - The [`verifier`] pallet provides a standard implementation of the [`verifier::Verifier`].
47//! - The [`unsigned`] module provides the implementation of unsigned submission by validators. If
48//!   this pallet is included, then [`Config::UnsignedPhase`] will determine its duration.
49//! - The [`signed`] module provides the implementation of the signed submission by any account. If
50//!   this pallet is included, the combined [`Config::SignedPhase`] and
51//!   [`Config::SignedValidationPhase`] will determine its duration
52//!
53//! These pallets are in fact hierarchical. This particular one is the top level one. It contains
54//! the shared information that all child pallets use. All child pallets depend on the top level
55//! pallet ONLY, but not the other way around. For those cases, traits are used.
56//!
57//! For reverse linking, or child-linking, only explicit traits with clear interfaces are used. For
58//! example, the following traits facilitate other communication:
59//!
60//! * [`crate::types::SignedInterface`]: Parent talking to signed.
61//! * [`crate::verifier::Verifier`]: Parent talking to verifier.
62//! * [`crate::verifier::SolutionDataProvider`]: Verifier talking to signed.
63
64//! ## Pagination
65//!
66//! Most of the external APIs of this pallet are paginated. All pagination follow a pattern where if
67//! `N` pages exist, the first paginated call is `function(N-1)` and the last one is `function(0)`.
68//! For example, with 3 pages, the `elect` of [`ElectionProvider`] is expected to be called as
69//! `elect(2) -> elect(1) -> elect(0)`. In essence, calling a paginated function with index 0 is
70//! always a signal of termination, meaning that no further calls will follow.
71//!
72//! The snapshot creation for voters (Nominators in staking), submission of signed pages, validation
73//! of signed solutions and exporting of pages are all paginated. Note that this pallet is yet to
74//! support paginated target (Validators in staking) snapshotting.
75//!
76//! ### Terminology Note: `msp` and `lsp`
77//!
78//! Stand for _most significant page_ (n-1) and _least significant page_ (0).
79//!
80//! See [`ElectionProvider::msp`] and [`ElectionProvider::lsp`], and their usage.
81//!
82//! ## Phases
83//!
84//! The operations in this pallet are divided into rounds, a `u32` number stored in [`Round`].
85//! This value helps this pallet organize itself, and leaves the door open for lazy deletion of any
86//! stale data. A round, under the happy path, starts by receiving the call to
87//! [`ElectionProvider::start`], and is terminated by receiving a call to
88//! [`ElectionProvider::elect`] with value 0.
89//!
90//! The timeline of pallet is overall as follows:
91//!
92//! ```ignore
93//!  <  Off  >
94//! 0 ------------ 12 13 14 15 ----------- 20 ---------25 ------- 30
95//! 	           |       |              |            |          |
96//! 	     Snapshot      Signed   SignedValidation  Unsigned   Elect
97//! ```
98//!
99//! * Duration of `Snapshot` is determined by [`Config::Pages`] + 1.
100//! 	* Whereby in the first page we take the "Targets" snapshot, and in the subsequent pages we take
101//!    the voter snapshot.
102//! 	* For example, with `Pages = 4`:
103//! 		* `Snapshot(4)` -> `Targets(all)`
104//! 		* `Snapshot(3)` -> `Voters(3)`
105//! 		* `Snapshot(2)` -> `Voters(2)`
106//! 		* `Snapshot(1)` -> `Voters(1)`
107//! 		* `Snapshot(0)` -> `Voters(0)`
108//! * Duration of `Signed`, `SignedValidation` and `Unsigned` are determined by
109//!   [`Config::SignedPhase`], [`Config::SignedValidationPhase`] and [`Config::UnsignedPhase`]
110//!   respectively.
111//! * [`Config::Pages`] calls to elect are expected, but all in all the pallet will close a round
112//!   once `elect(0)` is called.
113//!
114//! > Given this, it is rather important for the user of this pallet to ensure it always terminates
115//! > election via `elect` before requesting a new one.
116//!
117//! ### Phase Transition
118//!
119//! Within all 4 pallets only the parent pallet is allowed to move the phases forward. As of now,
120//! the transition happens `on-poll`, ensuring that we don't consume too much weight. The parent
121//! pallet is in charge of aggregating the work to be done by all pallets, checking if it can fit
122//! within the current block's weight limits, and executing it if so.
123//!
124//! Occasional phase transition stalling is not a critical issue. Every instance of phase transition
125//! failing is accompanied by a [`Event::UnexpectedPhaseTransitionOutOfWeight`] for visibility.
126//!
127//! Note this pallet transitions phases all the way into [`crate::types::Phase::Done`]. At this
128//! point, we will move to `Export` phase an onwards by calls into `elect`. A call to `elect(0)`
129//! rotates the round, as stated above.
130//!
131//! ## Feasible Solution (correct solution)
132//!
133//! All submissions must undergo a feasibility check. Signed solutions are checked one by one at the
134//! end of the signed phase, and the unsigned solutions are checked on the spot. A feasible solution
135//! is as follows:
136//!
137//! 0. **all** of the used indices must be correct.
138//! 1. present *exactly* correct number of winners.
139//! 2. any assignment is checked to match with `PagedVoterSnapshot`.
140//! 3. the claimed score is valid, based on the fixed point arithmetic accuracy.
141//!
142//! More about this in [`verifier`], who is responsible for doing all of the above.
143//!
144//! ### Fallback and Emergency
145//!
146//! If at any page, [`ElectionProvider::elect`] fails, a call with the same page-index is dispatched
147//! to [`Config::Fallback`]. [`Config::Fallback`] is itself (yet) another implementation of
148//! [`ElectionProvider`], and can decide to do anything, but a few reasonable options are provided
149//! here:
150//!
151//! 1. Do nothing: [`Continue`]
152//! 2. Force us into the emergency phase: [`crate::InitiateEmergencyPhase`]. This initiates
153//!    [`Phase::Emergency`], which will halt almost all operations of this pallet, and it can only
154//!    be recovered by [`AdminOperation`], dispatched via [`Call::manage`].
155//! 3. compute an onchain from the give page of snapshot.
156//!
157//! Note that configuring the fallback to be onchain computation is not recommended, unless for
158//! test-nets for a number of reasons:
159//!
160//! 1. The solution score of fallback is never checked to match the "minimum" score. That being
161//!    said, the computation happens onchain so we can trust it.
162//! 2. The onchain fallback runs on the same number of voters and targets that reside on a single
163//!    page of a snapshot, which will very likely be too much for actual onchain computation. Yet,
164//!    we don't have another choice as we cannot request another smaller snapshot from the data
165//!    provider mid-election without more bookkeeping on the staking side.
166//!
167//! If onchain solution is to be seriously considered, an improvement to this pallet should
168//! re-request a smaller set of voters from `T::DataProvider` in a stateless manner.
169//!
170//! ### Signed Phase
171//!
172//! Signed phase is when an offchain miner, aka, `polkadot-staking-miner` should operate upon. See
173//! [`signed`] for more information.
174//!
175//! ## Unsigned Phase
176//!
177//! Unsigned phase is a built-in fallback in which validators may submit a single page election,
178//! taking into account only the [`ElectionProvider::msp`] (_most significant page_). See
179//! [`crate::unsigned`] for more information.
180
181// Implementation notes:
182//
183// - Naming convention is: `${singular}_page` for singular, e.g. `voter_page` for `Vec<Voter>`.
184//   `paged_${plural}` for plural, e.g. `paged_voters` for `Vec<Vec<Voter>>`.
185//
186// - Since this crate has multiple `Pallet` and `Configs`, in each sub-pallet, we only reference the
187//   local `Pallet` without a prefix and allow it to be imported via `use`. Avoid `super::Pallet`
188//   except for the case of a modules that want to reference their local `Pallet` . The
189//   `crate::Pallet` is always reserved for the parent pallet. Other sibling pallets must be
190//   referenced with full path, e.g. `crate::Verifier::Pallet`. Do NOT write something like `use
191//   unsigned::Pallet as UnsignedPallet`.
192//
193// - Respecting private storage items with wrapper We move all implementations out of the `mod
194//   pallet` as much as possible to ensure we NEVER access the internal storage items directly. All
195//   operations should happen with the wrapper types.
196
197#![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
236/// The common logging prefix of all pallets in this crate.
237pub 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
246/// The signed pallet
247pub mod signed;
248/// Common types of the pallet
249pub mod types;
250/// The unsigned pallet
251pub mod unsigned;
252/// The verifier pallet
253pub mod verifier;
254/// The weight module
255pub mod weights;
256
257pub use pallet::*;
258pub use types::*;
259pub use weights::traits::pallet_election_provider_multi_block::WeightInfo;
260
261/// A fallback implementation that transitions the pallet to the emergency phase.
262pub 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
305/// A fallback implementation that silently continues into the next page.
306///
307/// This is suitable for onchain usage.
308pub 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
350/// A easy means to configure [`Config::AreWeDone`].
351///
352/// With this, you can say what to do if a solution is queued, or what to do if not.
353///
354/// Two common shorthands of this are provided:
355/// * [`ProceedRegardlessOf`]
356/// * [`RevertToSignedIfNotQueuedOf`]
357pub struct IfSolutionQueuedElse<T, Queued, NotQueued>(
358	core::marker::PhantomData<(T, Queued, NotQueued)>,
359);
360
361/// A `Get` impl for `Phase::Done`
362pub 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
369/// A `Get` impl for `Phase::Signed(T::SignedPhase::get())`
370pub 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
377/// A shorthand for [`IfSolutionQueuedElse`] that proceeds regardless of the solution being queued.
378pub type ProceedRegardlessOf<T> = IfSolutionQueuedElse<T, GetDone<T>, GetDone<T>>;
379
380/// A shorthand for [`IfSolutionQueuedElse`] that proceeds to `Phase::Done` if the solution is
381/// queued. Otherwise, it proceeds to `Phase::Signed`.
382pub 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/// Internal errors of the pallet. This is used in the implementation of [`ElectionProvider`].
415///
416/// Note that this is different from [`pallet::Error`].
417#[derive(
418	frame_support::DebugNoBound, frame_support::PartialEqNoBound, frame_support::EqNoBound,
419)]
420pub enum ElectionError<T: Config> {
421	/// An error happened in the feasibility check sub-system.
422	Feasibility(verifier::FeasibilityError),
423	/// An error in the fallback.
424	Fallback(FallbackErrorOf<T>),
425	/// An error in the onchain seq-phragmen implementation
426	OnChain(onchain::Error),
427	/// An error happened in the data provider.
428	DataProvider(&'static str),
429	/// the corresponding page in the queued supports is not available.
430	SupportPageNotAvailable,
431	/// The election is not ongoing and therefore no results may be queried.
432	NotOngoing,
433	/// The election is currently ongoing, and therefore we cannot start again.
434	Ongoing,
435	/// Called elect() with wrong page order or in wrong phase.
436	OutOfOrder,
437	/// Other misc error
438	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/// Different operations that only the [`Config::AdminOrigin`] can perform on the pallet.
454#[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	/// Set the given (single page) emergency solution.
469	///
470	/// Can only be called in emergency phase.
471	EmergencySetSolution(Box<BoundedSupportsOf<Pallet<T>>>, ElectionScore),
472	/// Set the minimum untrusted score. This is directly communicated to the verifier component to
473	/// be taken into account.
474	///
475	/// This is useful in preventing any serious issue where due to a bug we accept a very bad
476	/// solution.
477	SetMinUntrustedScore(ElectionScore),
478}
479
480/// Different operations that the [`Config::ManagerOrigin`] (or [`Config::AdminOrigin`]) can perform
481/// on the pallet.
482#[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	/// Forcefully go to the next round, starting from the Off Phase.
497	ForceRotateRound,
498	/// Force-set the phase to the given phase.
499	///
500	/// This can have many many combinations, use only with care and sufficient testing.
501	ForceSetPhase(Phase<T>),
502	/// Trigger the (single page) fallback in `instant` mode, with the given parameters, and
503	/// queue it if correct.
504	///
505	/// Can only be called in emergency phase.
506	EmergencyFallback,
507}
508
509/// Trait to notify other sub-systems that a round has ended.
510pub trait OnRoundRotation {
511	/// `ending` round has ended. Implies we are now at round `ending + 1`
512	fn on_round_rotation(ending: u32);
513}
514
515impl OnRoundRotation for () {
516	fn on_round_rotation(_: u32) {}
517}
518
519/// An implementation of [`OnRoundRotation`] that immediately deletes all the data in all the
520/// pallets, once the round is over.
521///
522/// This is intended to be phased out once we move to fully lazy deletion system to spare more PoV.
523/// In that case, simply use `()` on [`pallet::Config::OnRoundRotation`].
524pub struct CleanRound<T>(core::marker::PhantomData<T>);
525impl<T: Config> OnRoundRotation for CleanRound<T> {
526	fn on_round_rotation(_ending: u32) {
527		// Kill everything in the verifier.
528		T::Verifier::kill();
529
530		// Kill the snapshot.
531		pallet::Snapshot::<T>::kill();
532
533		// Nothing to do in the signed pallet -- it is already in lazy-deletion mode.
534	}
535}
536
537#[frame_support::pallet]
538pub mod pallet {
539	use super::*;
540
541	#[pallet::config]
542	pub trait Config: frame_system::Config {
543		/// Duration of the unsigned phase.
544		#[pallet::constant]
545		type UnsignedPhase: Get<BlockNumberFor<Self>>;
546		/// Duration of the signed phase.
547		#[pallet::constant]
548		type SignedPhase: Get<BlockNumberFor<Self>>;
549		/// Duration of the singed validation phase.
550		///
551		/// The duration of this should not be less than `T::Pages`, and there is no point in it
552		/// being more than `SignedPhase::MaxSubmission::get() * T::Pages`.
553		#[pallet::constant]
554		type SignedValidationPhase: Get<BlockNumberFor<Self>>;
555
556		/// The number of snapshot voters to fetch per block.
557		#[pallet::constant]
558		type VoterSnapshotPerBlock: Get<u32>;
559
560		/// The number of snapshot targets to fetch per block.
561		#[pallet::constant]
562		type TargetSnapshotPerBlock: Get<u32>;
563
564		/// The number of pages.
565		///
566		/// The snapshot is created with this many keys in the storage map.
567		///
568		/// The solutions may contain at MOST this many pages, but less pages are acceptable as
569		/// well.
570		#[pallet::constant]
571		type Pages: Get<PageIndex>;
572
573		/// Something that will provide the election data.
574		type DataProvider: ElectionDataProvider<
575			AccountId = Self::AccountId,
576			BlockNumber = BlockNumberFor<Self>,
577		>;
578
579		/// The miner configuration.
580		///
581		/// These configurations are passed to [`crate::unsigned::miner::BaseMiner`]. An external
582		/// miner implementation should implement this trait, and use the said `BaseMiner`.
583		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		/// The fallback type used for the election.
594		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		/// The verifier pallet's interface.
603		type Verifier: verifier::Verifier<
604				Solution = SolutionOf<Self::MinerConfig>,
605				AccountId = Self::AccountId,
606			> + verifier::AsynchronousVerifier;
607
608		/// Interface signed pallet's interface.
609		type Signed: SignedInterface;
610
611		/// The origin that can perform administration operations on this pallet.
612		///
613		/// This is the highest privilege origin of this pallet, and should be configured
614		/// restrictively.
615		type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
616
617		/// A less privileged origin than [`Config::AdminOrigin`], that can manage some election
618		/// aspects, without critical power.
619		type ManagerOrigin: EnsureOrigin<Self::RuntimeOrigin>;
620
621		/// An indicator of whether we should move to do the [`crate::types::Phase::Done`] or not?
622		/// This is called at the end of the election process.
623		///
624		/// Common implementation is [`ProceedRegardlessOf`] or [`RevertToSignedIfNotQueuedOf`].
625		type AreWeDone: Get<Phase<Self>>;
626
627		/// The weight of the pallet.
628		type WeightInfo: WeightInfo;
629
630		/// Single type that implement [`super::OnRoundRotation`] to do something when the round
631		/// ends.
632		type OnRoundRotation: super::OnRoundRotation;
633	}
634
635	#[pallet::call]
636	impl<T: Config> Pallet<T> {
637		/// Manage this pallet.
638		///
639		/// The origin of this call must be [`Config::ManagerOrigin`].
640		///
641		/// See [`ManagerOperation`] for various operations that are possible.
642		#[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				// try admin origin as well as admin is a superset.
647				T::AdminOrigin::ensure_origin(origin).map(|_| ())
648			})?;
649			match op {
650				ManagerOperation::EmergencyFallback => {
651					ensure!(Self::current_phase() == Phase::Emergency, Error::<T>::UnexpectedPhase);
652					// note: for now we run this on the msp, but we can make it configurable if need
653					// be.
654					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			// first check we can at least read one storage.
719			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			// if so, consume and prepare the next phase.
728			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			// The following will combine `Self::per_block_exec` and `T::Verifier::per_block_exec`
735			// into a single tuple of `(Weight, Box<_>)`. Can be moved into a reusable combinator
736			// function if we have this pattern in more places.
737			let (combined_weight, combined_exec) = (
738				// pre-exec weight is simply addition.
739				self_weight.saturating_add(verifier_weight),
740				// our new exec is..
741				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			// NOTE: why in here? because it is more accessible, for example `roll_to_with_ocw`.
767			#[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			// The index type of both voters and targets need to be smaller than that of usize (very
786			// unlikely to be the case, but anyhow).
787			assert!(size_of::<SolutionVoterIndexOf<T::MinerConfig>>() <= size_of::<usize>());
788			assert!(size_of::<SolutionTargetIndexOf<T::MinerConfig>>() <= size_of::<usize>());
789
790			// also, because `VoterSnapshotPerBlock` and `TargetSnapshotPerBlock` are in u32, we
791			// assert that both of these types are smaller than u32 as well.
792			assert!(size_of::<SolutionVoterIndexOf<T::MinerConfig>>() <= size_of::<u32>());
793			assert!(size_of::<SolutionTargetIndexOf<T::MinerConfig>>() <= size_of::<u32>());
794
795			// pages must be at least 1.
796			assert!(T::Pages::get() > 0);
797
798			// Based on the requirements of [`sp_npos_elections::Assignment::try_normalize`].
799			let max_vote: usize = <SolutionOf<T::MinerConfig> as NposSolution>::LIMIT;
800
801			// 2. Maximum sum of [SolutionAccuracy; 16] must fit into `UpperOf<OffchainAccuracy>`.
802			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			// We only accept data provider who's maximum votes per voter matches our
815			// `T::Solution`'s `LIMIT`.
816			//
817			// NOTE that this pallet does not really need to enforce this in runtime. The
818			// solution cannot represent any voters more than `LIMIT` anyhow.
819			assert_eq!(
820				<T::DataProvider as ElectionDataProvider>::MaxVotesPerVoter::get(),
821				<SolutionOf<T::MinerConfig> as NposSolution>::LIMIT as u32,
822			);
823
824			// Either (signed + signed validation) is non-zero, or unsigned is non-zero
825			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		/// A phase transition happened. Only checks major changes in the variants, not minor inner
852		/// values.
853		PhaseTransitioned {
854			/// the source phase
855			from: Phase<T>,
856			/// The target phase
857			to: Phase<T>,
858		},
859		/// Target snapshot creation failed.
860		UnexpectedTargetSnapshotFailed,
861		/// Voter snapshot creation failed.
862		UnexpectedVoterSnapshotFailed,
863		/// Phase transition could not proceed due to being out of weight.
864		UnexpectedPhaseTransitionOutOfWeight {
865			from: Phase<T>,
866			to: Phase<T>,
867			required: Weight,
868			had: Weight,
869		},
870		/// Phase transition could not even begin becaseu of being out of weight.
871		UnexpectedPhaseTransitionHalt { required: Weight, had: Weight },
872	}
873
874	/// Error of the pallet that can be returned in response to dispatches.
875	#[pallet::error]
876	pub enum Error<T> {
877		/// Triggering the `Fallback` failed.
878		Fallback,
879		/// Unexpected phase
880		UnexpectedPhase,
881		/// Snapshot was unavailable.
882		Snapshot,
883	}
884
885	/// Common errors in all sub-pallets and miner.
886	#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug)]
887	pub enum CommonError {
888		/// Submission is too early (or too late, depending on your point of reference).
889		EarlySubmission,
890		/// The round counter is wrong.
891		WrongRound,
892		/// Submission is too weak to be considered an improvement.
893		WeakSubmission,
894		/// Wrong number of pages in the solution.
895		WrongPageCount,
896		/// Wrong number of winners presented.
897		WrongWinnerCount,
898		/// The snapshot fingerprint is not a match. The solution is likely outdated.
899		WrongFingerprint,
900		/// Snapshot was not available.
901		Snapshot,
902	}
903
904	/// Internal counter for the number of rounds.
905	///
906	/// This is useful for de-duplication of transactions submitted to the pool, and general
907	/// diagnostics of the pallet.
908	///
909	/// This is merely incremented once per every time that an upstream `elect` is called.
910	#[pallet::storage]
911	#[pallet::getter(fn round)]
912	pub type Round<T: Config> = StorageValue<_, u32, ValueQuery>;
913
914	/// Current phase.
915	#[pallet::storage]
916	#[pallet::getter(fn current_phase)]
917	pub type CurrentPhase<T: Config> = StorageValue<_, Phase<T>, ValueQuery>;
918
919	/// Wrapper struct for working with snapshots.
920	///
921	/// It manages the following storage items:
922	///
923	/// - `DesiredTargets`: The number of targets that we wish to collect.
924	/// - `PagedVoterSnapshot`: Paginated map of voters.
925	/// - `PagedVoterSnapshotHash`: Hash of the aforementioned.
926	/// - `PagedTargetSnapshot`: Paginated map of targets.
927	/// - `PagedTargetSnapshotHash`: Hash of the aforementioned.
928	///
929	/// ### Round
930	///
931	/// All inner storage items are keyed by the round number. Yet, none of the interface in this
932	/// type expose this. This is because a snapshot is really only ever meaningful in the current
933	/// round. Moreover, doing this will allow us to possibly lazy-delete the old round data, such
934	/// as the sizeable snapshot, in a lazy manner. If any of these storage items, key-ed by a round
935	/// index, are in a round that has passed, now they can be lazy deleted.
936	///
937	/// ### Invariants
938	///
939	/// The following invariants must be met at **all times** for this storage item to be "correct".
940	///
941	/// - `PagedVoterSnapshotHash` must always contain the correct the same number of keys, and the
942	///   corresponding hash of the `PagedVoterSnapshot`.
943	/// - `PagedTargetSnapshotHash` must always contain the correct the same number of keys, and the
944	///   corresponding hash of the `PagedTargetSnapshot`.
945	///
946	/// - If any page from the paged voters/targets exists, then the aforementioned (desired
947	///   targets) must also exist.
948	///
949	/// The following invariants might need to hold based on the current phase.
950	///
951	///   - If `Phase` IS `Snapshot(_)`, then partial voter/target pages must exist from `msp` to
952	///     `lsp` based on the inner value.
953	///   - If `Phase` IS `Off`, then, no snapshot must exist.
954	///   - In all other phases, the snapshot must FULLY exist.
955	pub(crate) struct Snapshot<T>(core::marker::PhantomData<T>);
956	impl<T: Config> Snapshot<T> {
957		// ----------- mutable methods
958		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		/// Destroy the entire snapshot.
979		///
980		/// Should be called only once we transition to [`Phase::Off`].
981		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		// ----------- non-mutables
990		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			// NOTE: targets always have one index, which is 0, aka lsp.
1000			PagedTargetSnapshot::<T>::get(Self::round(), Pallet::<T>::msp())
1001		}
1002
1003		/// Get a fingerprint of the snapshot, from all the hashes that are stored for each page of
1004		/// the snapshot.
1005		///
1006		/// This is computed as: `(target_hash, voter_hash_n, voter_hash_(n-1), ..., voter_hash_0)`
1007		/// where `n` is `T::Pages - 1`. In other words, it is the concatenated hash of targets, and
1008		/// voters, from `msp` to `lsp`.
1009		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			// do some checks.
1028			debug_assert_eq!(buffer, data.encode());
1029			// buffer should have not re-allocated since.
1030			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		/// Ensure target snapshot exists.
1049		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			// and the hash is correct.
1055			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		/// Ensure voters exists, from page `T::Pages::get()` for `up_to_page` subsequent pages.
1063		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			// ensure that voter pages that should exist, indeed to exist..
1069			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			// ..and those that should not exist, indeed DON'T.
1088			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			// if any number of pages supposed to exist, these must also exist.
1110			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			// ensure that voter pages that should exist, indeed to exist..
1119			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			// check the snapshot existence based on the phase. This checks all of the needed
1145			// conditions except for the metadata values.
1146			let phase = Pallet::<T>::current_phase();
1147			let _ = match phase {
1148				// no page should exist in this phase.
1149				Phase::Off => Self::ensure_snapshot(false, T::Pages::get()),
1150
1151				// we will star the snapshot in the next phase.
1152				Phase::Snapshot(p) if p == T::Pages::get() => {
1153					Self::ensure_snapshot(false, T::Pages::get())
1154				},
1155				// we are mid voter snapshot.
1156				Phase::Snapshot(p) if p < T::Pages::get() && p > 0 => {
1157					Self::ensure_snapshot(true, T::Pages::get() - p - 1)
1158				},
1159				// we cannot check anything in this block -- we take the last page of the snapshot.
1160				Phase::Snapshot(_) => Ok(()),
1161
1162				// full snapshot must exist in these phases.
1163				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						// and update the hash.
1215						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	/// Desired number of targets to elect for this round.
1229	#[pallet::storage]
1230	pub type DesiredTargets<T> = StorageMap<_, Twox64Concat, u32, u32>;
1231	/// Paginated voter snapshot. At most [`T::Pages`] keys will exist.
1232	#[pallet::storage]
1233	pub type PagedVoterSnapshot<T: Config> = StorageDoubleMap<
1234		_,
1235		Twox64Concat,
1236		u32,
1237		Twox64Concat,
1238		PageIndex,
1239		VoterPageOf<T::MinerConfig>,
1240	>;
1241	/// Same as [`PagedVoterSnapshot`], but it will store the hash of the snapshot.
1242	///
1243	/// The hash is generated using [`frame_system::Config::Hashing`].
1244	#[pallet::storage]
1245	pub type PagedVoterSnapshotHash<T: Config> =
1246		StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, PageIndex, T::Hash>;
1247	/// Paginated target snapshot.
1248	///
1249	/// For the time being, since we assume one pages of targets, at most ONE key will exist.
1250	#[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	/// Same as [`PagedTargetSnapshot`], but it will store the hash of the snapshot.
1260	///
1261	/// The hash is generated using [`frame_system::Config::Hashing`].
1262	#[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	/// Returns the most significant page of the snapshot.
1272	///
1273	/// Based on the contract of `ElectionDataProvider`, this is the first page that is filled.
1274	fn msp() -> PageIndex {
1275		T::Pages::get().checked_sub(1).defensive_unwrap_or_default()
1276	}
1277
1278	/// Returns the least significant page of the snapshot.
1279	///
1280	/// Based on the contract of `ElectionDataProvider`, this is the last page that is filled.
1281	fn lsp() -> PageIndex {
1282		Zero::zero()
1283	}
1284
1285	/// > Note: Consider this a shared documentation block for [`Pallet::on_poll`] and this
1286	/// > function, as they work together.
1287	///
1288	/// The meta-phase transition logic that applies to all pallets. Includes the following:
1289	///
1290	/// * Creating snapshot once `ElectionProvider::start` has instructed us to do so.
1291	/// * Transition into `Phase::Signed`.
1292	/// * Upon last page of `Phase::Signed`, instruct the `Verifier` to start, if any solution
1293	///   exists.
1294	/// * And moving forward all other phases as necessary.
1295	///
1296	/// What it does not do:
1297	///
1298	/// * Instruct the verifier to move forward. This happens through
1299	///   [`verifier::Verifier::per_block_exec`], called in [`Pallet::on_poll`]. On each block,
1300	///   [`T::Verifier`] is given a chance to do something. Under the hood, if the `Status` is set,
1301	///   it will do something, regardless of which phase we are in. In this pallet we only move
1302	///   [`Phase::SignedValidation`] forward.
1303	/// * Move us forward if we are in either of `Phase::Done` or `Phase::Export`. These are
1304	///   controlled by the caller of our [`T::ElectionProvider`] implementation, i.e. staking. Note
1305	///   that this pallet always transitions us from `current_phase` to `current_phase.next()`, but
1306	///   the [`crate::types::Phase::next`] function is a noop for `Done` and `Export`.
1307	///
1308	/// ### Type
1309	///
1310	/// The commonly used `(Weight, Box<dyn Fn(&mut WeightMeter)>)` should be interpreted as such:
1311	///
1312	/// * The `Weight` is the pre-computed worst case weight of the operation that we are going to
1313	///   do.
1314	/// * The `Box<dyn Fn(&mut WeightMeter)>` is the function that represents that the work that
1315	///   will at most consume the said amount of weight. While executing, it will alter the given
1316	///   weight meter to consume the actual weight used. Indeed, the weight that is registered in
1317	///   the `WeightMeter` must never be more than the `Weight` returned as the first item of the
1318	///   tuple.
1319	///
1320	/// In essence, the caller must:
1321	///
1322	/// 1. given an existing `meter`, receive `(worst_weight, exec)`
1323	/// 2. ensure `meter` can consume up to `worst_weight`.
1324	/// 3. if so, call `exec(meter)`, knowing `meter` will accumulate at most `worst_weight` extra.
1325	///
1326	/// ### Returned Weight
1327	///
1328	/// The weights returned are as follows:
1329	///
1330	/// * `just_next_phase` returns a benchmarked weight that should be equal to only reading and
1331	///   writing the `Phase`. This is used for:
1332	/// 	* `Off` phase, which does not do anything `on_poll`.
1333	/// 	* `Signed` phase except last page, which starts the verifier.
1334	/// 	* `Unsigned` phase, which does not do anything `on_poll` and managed its own extrinsic
1335	///    weights.
1336	/// 	* `Emergency` phase, which does not do anything `on_poll`.
1337	/// 	* `Done` phase, which does not do anything `on_poll`.
1338	/// 	* `SignedValidation` phase, because in this pallet we only move the phase forward and we
1339	///    don't know (or want to know) how much weight `Verifier` is consuming. This is handled by
1340	///    combining the weight of [`T::Verifier::per_block_exec`] with this function in
1341	///    [`Pallet::on_poll`].
1342	/// 	* `Export` phase, which does not do anything `on_poll` on this pallet, yet we return the
1343	///    weight that [`Config::ElectionProvider`]'s caller should register via
1344	///    [`ElectionProvider::status`].
1345	///
1346	/// The only special cases, from the perspective of this pallet, are:
1347	/// 	* Last page of signed phase registers `per_block_start_signed_validation`.
1348	/// 	* The snapshots are handled by this pallet, which registers `per_block_snapshot_msp` and
1349	///    `per_block_snapshot_rest`.
1350	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				// Note `Phase.next` for some variants is a noop, for example `Done`.
1358				Self::phase_transition(next_phase);
1359			}),
1360		);
1361
1362		match current_phase {
1363			Phase::Snapshot(x) if x == T::Pages::get() => {
1364				// first snapshot
1365				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				// rest of the snapshot, incl last one.
1376				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				// Signed pallet should prep the best winner, and send the start signal, if some
1386				// exists.
1387				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						// defensive: signed phase has just began, verifier should be in a clear
1391						// state and ready to accept a solution.
1392						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	/// Return the `length` most significant pages.
1411	///
1412	/// For example, if `Pages = 4`, and `length = 2`, our full snapshot range would be [0,
1413	/// 1, 2, 3], with 3 being msp. But, in this case, then this returns `[2, 3]` two most
1414	/// significant pages, in the old order.
1415	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	/// Perform all the basic checks that are independent of the snapshot. To be more specific,
1435	/// these are all the checks that you can do without the need to read the massive blob of the
1436	/// actual snapshot. This function only contains a handful of storage reads, with bounded size.
1437	///
1438	/// A sneaky detail is that this does check the `DesiredTargets` aspect of the snapshot, but
1439	/// neither of the large storage items.
1440	///
1441	/// Moreover, we do optionally check the fingerprint of the snapshot, if provided.
1442	///
1443	/// These complement a feasibility-check, which is exactly the opposite: snapshot-dependent
1444	/// checks.
1445	pub(crate) fn snapshot_independent_checks(
1446		paged_solution: &PagedRawSolution<T::MinerConfig>,
1447		maybe_snapshot_fingerprint: Option<T::Hash>,
1448	) -> Result<(), CommonError> {
1449		// Note that the order of these checks are critical for the correctness and performance of
1450		// `restore_or_compute_then_maybe_submit`. We want to make sure that we always check round
1451		// first, so that if it has a wrong round, we can detect and delete it from the cache right
1452		// from the get go.
1453
1454		// ensure round is current
1455		ensure!(Self::round() == paged_solution.round, CommonError::WrongRound);
1456
1457		// ensure score is being improved, if the claim is even correct.
1458		ensure!(
1459			<T::Verifier as Verifier>::ensure_claimed_score_improves(paged_solution.score),
1460			CommonError::WeakSubmission,
1461		);
1462
1463		// ensure solution pages are no more than the snapshot
1464		ensure!(
1465			paged_solution.solution_pages.len().saturated_into::<PageIndex>() <= T::Pages::get(),
1466			CommonError::WrongPageCount
1467		);
1468
1469		// finally, check the winner count being correct.
1470		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		// check the snapshot fingerprint, if asked for.
1478		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	/// Creates the target snapshot.
1489	///
1490	/// If snapshot creation fails, emits `UnexpectedTargetSnapshotFailed` event
1491	/// and triggers defensive panic.
1492	pub(crate) fn create_targets_snapshot() {
1493		// if requested, get the targets as well.
1494		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	/// Creates the voter snapshot.
1524	///
1525	/// If snapshot creation fails, emits `UnexpectedVoterSnapshotFailed` event
1526	/// and triggers defensive panic.
1527	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	/// Perform the tasks to be done after a new `elect` has been triggered:
1548	///
1549	/// 1. Increment round.
1550	/// 2. Change phase to [`Phase::Off`]
1551	/// 3. Clear all snapshot data.
1552	pub(crate) fn rotate_round() {
1553		// Inc round.
1554		<Round<T>>::mutate(|r| {
1555			// Notify the rest of the world
1556			T::OnRoundRotation::on_round_rotation(*r);
1557			*r += 1
1558		});
1559
1560		// Phase is off now.
1561		Self::phase_transition(Phase::Off);
1562	}
1563
1564	/// Call fallback for the given page.
1565	///
1566	/// This uses the [`ElectionProvider::bother`] to check if the fallback is actually going to do
1567	/// anything. If so, it will re-collect the associated snapshot page and do the fallback. Else,
1568	/// it will early return without touching the snapshot.
1569	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	/// A reasonable next election block number.
1585	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		// we don't count the export.
1592		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	/// Helper function to check the weights of all significant operations of this this pallet
1643	/// against a runtime.
1644	///
1645	/// Will check the weights for:
1646	///
1647	/// * snapshot
1648	/// * signed submission and cleanip
1649	/// * unsigned solution submission
1650	/// * signed validation
1651	/// * export.
1652	///
1653	/// Arguments:
1654	///
1655	/// * `limit_weight` should be the maximum block weight (often obtained from `frame_system`).
1656	/// * `maybe_max_ratio` is the maximum ratio of `limit_weight` that we may consume, else we
1657	///   panic.
1658	/// * `maybe_max_warn_rati` has the same effect, but it emits a warning instead of panic.
1659	///
1660	/// A reasonable value for `maybe_max_weight` would be 75%, and 50% for `maybe_max_warn_ratio`.
1661	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		// -------------- snapshot
1675		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		// -------------- signed
1692		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		// -------------- unsigned
1708		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		// -------------- verification
1717		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		// -------------- export
1751		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))]
1771// helper code for testing and benchmarking
1772impl<T> Pallet<T>
1773where
1774	T: Config + crate::signed::Config + crate::unsigned::Config + crate::verifier::Config,
1775	BlockNumberFor<T>: From<u32>,
1776{
1777	/// Progress blocks until the criteria is met.
1778	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	/// Progress blocks until one block before the criteria is met.
1788	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		// ensure snapshot is full.
1820		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		// register alice
1831		let alice = crate::Pallet::<T>::funded_account("alice", 0);
1832		signed::Pallet::<T>::register(RawOrigin::Signed(alice.clone()).into(), score)?;
1833
1834		// submit pages
1835		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		// Calculate deposit for worst-case scenario: full queue + all pages submitted.
1860		// This accounts for the exponential deposit growth in GeometricDepositBase
1861		// where deposit = base * (1 + increase_factor)^queue_len.
1862		// We use maximum possible queue_len to ensure adequate funding regardless
1863		// of queue state changes during benchmark execution.
1864		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		// Transaction fees: assume as conservativ estimate that each operation costs ~1% of
1872		// minimum_balance
1873		let min_balance = T::Currency::minimum_balance();
1874		let num_operations = 1u32.saturating_add(T::Pages::get()); // 1 register + N submit_page
1875		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	/// Roll all pallets forward, for the given number of blocks.
1886	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			// remove previous weight usage in system.
1893			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			// register the new weight in system
1900			frame_system::Pallet::<T>::register_extra_weight_unchecked(
1901				meter.consumed(),
1902				DispatchClass::Mandatory,
1903			);
1904
1905			// invariants must hold at the end of each block.
1906			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	/// Roll to next block.
1918	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			// we allow `elect` to be called as long as we have received a start signal.
1936			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				// if any pages returns an error, we go into the emergency phase and don't do
1958				// anything else anymore. This will prevent any new submissions to signed and
1959				// unsigned pallet, and thus the verifier will also be almost stuck, except for the
1960				// submission of emergency solutions.
1961				log!(debug, "fallback also ({:?}) failed for page {:?}", err, remaining);
1962				err
1963			})
1964			.map(|supports| {
1965				// convert to bounded
1966				supports.into()
1967			});
1968
1969		// if fallback has possibly put us into the emergency phase, don't do anything else.
1970		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			// we're not doing anything.
2000			Phase::Off => Err(()),
2001
2002			// we're doing something but not ready.
2003			Phase::Signed(_) |
2004			Phase::SignedValidation(_) |
2005			Phase::Unsigned(_) |
2006			Phase::Snapshot(_) |
2007			Phase::Emergency => Ok(None),
2008
2009			// we're ready
2010			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		// prepare our snapshot so we can "hopefully" run a fallback.
2024		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				// 0 -------- 14 15 --------- 20 ------------- 25 ---------- 30
2046				//            |  |            |                |             |
2047				//    Snapshot Signed  SignedValidation    Unsigned       elect()
2048
2049				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				// We stay in done otherwise
2121				roll_to(32);
2122				assert!(MultiBlock::current_phase().is_done());
2123
2124				// We stay in done otherwise
2125				roll_to(33);
2126				assert!(MultiBlock::current_phase().is_done());
2127
2128				// We close when upstream tells us to elect.
2129				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				// 0 -------13 14 15 ------- 20 ---- 25 ------- 30
2152				//           |     |         |       |          |
2153				//    Snapshot    Signed SigValid  Unsigned   Elect
2154
2155				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				// We close when upstream tells us to elect.
2244				roll_to(33);
2245				assert_eq!(MultiBlock::current_phase(), Phase::Done);
2246
2247				// and even this one's coming from the fallback.
2248				MultiBlock::elect(0).unwrap();
2249				assert!(MultiBlock::current_phase().is_off());
2250
2251				// all snapshots are gone.
2252				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				// 0 ------- 12 13 14 15 ----------- 20 ---------25 ------- 30
2264				//            |       |              |            |          |
2265				//     Snapshot      Signed   SignedValidation  Unsigned   Elect
2266
2267				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				// no snapshot is take yet, we start at the next block
2279				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				// We close when upstream tells us to elect.
2346				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				// all snapshots are gone.
2353				assert_none_snapshot();
2354				assert_eq!(MultiBlock::round(), 1);
2355			})
2356	}
2357
2358	#[test]
2359	fn weights_registered() {
2360		// ensure we never forget to call `meter.consume` or similar in poll and alike.
2361		// Our mock setup is:
2362		//
2363		// * each db read or write is 1 ref time.
2364		// * each epmb op weight are:
2365		//   * snapshots: 5
2366		//   * validation: 3 to start, rest 7
2367		ExtBuilder::full().build_and_execute(|| {
2368			roll_to(10);
2369			assert!(MultiBlock::current_phase().is_off());
2370			// note: 2 becuase 1 read registered by the parent pallet, 1 by verifier.
2371			assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2372
2373			// roll to this phase, no weight meter is consumed yet other than 1 read + 1 write.
2374			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			// Now snapshot is done, and during signed phase we do a noop.
2390			roll_next_and_phase(Phase::Signed(SignedPhase::get() - 2));
2391			assert_eq!(System::remaining_block_weight().consumed(), Weight::from_parts(2, 0));
2392
2393			// but let's submit a signed solution to be verified while we're here
2394			{
2395				let paged = mine_full_solution().unwrap();
2396				load_signed_for_verification(999, paged.clone());
2397			}
2398
2399			// let's go forward to start of signed validation
2400			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			// we also don't do anything during unsigned phase.
2422			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			// Export weight is computed by us, but registered by whoever calls `elect`, not our
2430			// business to check.
2431		});
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				// 0 --------------------- 17 ------ 20 ---------25 ------- 30
2443				//            |            |         |            |          |
2444				//                     Snapshot    Signed  SignedValidation   Elect
2445
2446				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				// last block of signed validation
2495				roll_to(31);
2496				assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(0));
2497
2498				// we are done now
2499				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				// all snapshots are gone.
2509				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				// 0 ------------------------- 22 ------ 25 ------- 30
2525				//                             |         |          |
2526				//                         Snapshot   Unsigned   Elect
2527
2528				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				// eventually the call to elect comes, and we exit done phase.
2571				MultiBlock::elect(0).unwrap();
2572				assert!(MultiBlock::current_phase().is_off());
2573
2574				// all snapshots are gone.
2575				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				// This should panic during integrity test
2593			});
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 unsigned
2618				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				// we are back to signed phase
2639				roll_next_and_phase(Phase::Signed(SignedPhase::get() - 1));
2640				// round is still the same
2641				assert_eq!(MultiBlock::round(), 0);
2642
2643				// we proceed to normally again:
2644				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				// Test that on_initialize does NOT advance the phase when in Done
2661				roll_next_and_phase(Phase::Done);
2662
2663				// Start export by calling elect(max_page)
2664				assert_ok!(MultiBlock::elect(2)); // max_page = 2 for 3 pages
2665				assert_eq!(MultiBlock::current_phase(), Phase::Export(1));
2666
2667				// Test that on_initialize does NOT advance the phase when in Export
2668				roll_next_and_phase(Phase::Export(1));
2669
2670				// Only elect() should advance the Export phase
2671				assert_ok!(MultiBlock::elect(1));
2672				assert_eq!(MultiBlock::current_phase(), Phase::Export(0));
2673
2674				// Test Export(0) also blocks on_initialize transitions
2675				roll_next_and_phase(Phase::Export(0));
2676
2677				// Complete the export manually
2678				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				// Start export by calling elect(max_page)
2695				assert_ok!(MultiBlock::elect(2)); // max_page = 2 for 3 pages
2696				assert_eq!(MultiBlock::current_phase(), Phase::Export(1));
2697
2698				// Out of order: try to call elect(2) again, should fail
2699				assert_eq!(MultiBlock::elect(2), Err(ElectionError::OutOfOrder));
2700
2701				// Out of order: try to call elect(0) before elect(1), should fail
2702				assert_eq!(MultiBlock::elect(0), Err(ElectionError::OutOfOrder));
2703
2704				// Correct order: elect(1) works
2705				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					// Create way more targets than the TargetSnapshotPerBlock limit (4)
2718					// This will cause bounds.slice_exhausted(&targets) to return true
2719					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					// Clear any existing events
2726					let _ = multi_block_events_since_last_call();
2727
2728					// Roll to next block - on_initialize will be in Phase::Snapshot(2) where x == T::Pages::get()
2729					// This triggers target snapshot creation, which should fail due to too many targets
2730					roll_to(14);
2731
2732					// Verify that UnexpectedTargetSnapshotFailed event was emitted
2733					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					// Verify phase transition still happened despite the failure
2741					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	// This is probably the most important test of all, a basic, correct scenario. This test should
2759	// be studied in detail, and all of the branches of how it can go wrong or diverge from the
2760	// basic scenario assessed.
2761	#[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			// load a solution into the verifier
2768			let paged = OffchainWorkerMiner::<Runtime>::mine_solution(Pages::get(), false).unwrap();
2769			let score = paged.score;
2770
2771			// now let's submit this one by one, into the signed phase.
2772			load_signed_for_verification(99, paged);
2773
2774			// now the solution should start being verified.
2775			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			// there is no queued solution prior to the last page of the solution getting verified
2797			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			// next block, signed will start the verifier, although nothing is verified yet.
2804			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			// there is now a queued solution.
2817			assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), Some(score));
2818
2819			// now let's go to unsigned phase, but we don't expect anything to happen there since we
2820			// don't run OCWs.
2821			roll_to_unsigned_open();
2822
2823			// pre-elect state
2824			assert!(MultiBlock::current_phase().is_unsigned_opened_now());
2825			assert_eq!(MultiBlock::round(), 0);
2826			assert_full_snapshot();
2827
2828			// call elect for each page
2829			let _paged_solution = (MultiBlock::lsp()..MultiBlock::msp())
2830				.rev() // 2, 1, 0
2831				.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			// after the last elect, verifier is cleared,
2842			verifier::QueuedSolution::<Runtime>::assert_killed();
2843			// the phase is off,
2844			assert_eq!(MultiBlock::current_phase(), Phase::Off);
2845			// the round is incremented,
2846			assert_eq!(Round::<Runtime>::get(), 1);
2847			// and the snapshot is cleared,
2848			assert_storage_noop!(Snapshot::<Runtime>::kill());
2849			// signed pallet is clean.
2850			// NOTE: signed pallet lazily deletes all other solutions, except the winner, which is
2851			// actually deleted.
2852			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			// load a solution into the verifier
2864			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			// there is no queued solution prior to the last page of the solution getting verified
2869			assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), None);
2870
2871			// roll to the block it is finalized.
2872			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			// there is now a queued solution.
2887			assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), Some(score));
2888
2889			// not much impact, just for the sane-ness of the test.
2890			roll_to_unsigned_open();
2891
2892			// pre-elect state:
2893			assert!(MultiBlock::current_phase().is_unsigned_opened_now());
2894			assert_eq!(Round::<Runtime>::get(), 0);
2895			assert_full_snapshot();
2896
2897			// there are 3 pages (indexes 2..=0), but we short circuit by just calling 0.
2898			let _supports = crate::Pallet::<Runtime>::elect(0).unwrap();
2899
2900			// round is incremented.
2901			assert_eq!(MultiBlock::round(), round + 1);
2902			// after elect(0) is called, verifier is cleared,
2903			verifier::QueuedSolution::<Runtime>::assert_killed();
2904			// the phase is off,
2905			assert_eq!(MultiBlock::current_phase(), Phase::Off);
2906			// the round is incremented,
2907			assert_eq!(Round::<Runtime>::get(), 1);
2908			// the snapshot is cleared,
2909			assert_none_snapshot();
2910			// and signed pallet is clean.
2911			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			// load a solution into the verifier
2922			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			// there is no queued solution prior to the last page of the solution getting verified
2927			assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), None);
2928
2929			// roll to the block it is finalized. 1 block to start the verifier, and 3 to verify.
2930			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			// there is now a queued solution
2945			assert_eq!(<Runtime as crate::Config>::Verifier::queued_score(), Some(score));
2946
2947			// not much impact, just for the sane-ness of the test.
2948			roll_to_unsigned_open();
2949
2950			// pre-elect state:
2951			assert!(MultiBlock::current_phase().is_unsigned_opened_now());
2952			assert_eq!(Round::<Runtime>::get(), 0);
2953			assert_full_snapshot();
2954
2955			// call elect for page 2 and 1, but NOT 0
2956			let solutions = (1..=MultiBlock::msp())
2957				.rev() // 2, 1
2958				.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			// nothing changes from the prelect state, except phase is now export.
2966			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		// Use Continue fallback to avoid emergency phase when both primary and fallback fail.
2975		ExtBuilder::full().fallback_mode(FallbackModes::Continue).build_and_execute(|| {
2976			// Move to unsigned phase
2977			roll_to_unsigned_open();
2978
2979			// Note: our mock runtime is configured with 1 page for the unsigned phase
2980			let miner_pages = <Runtime as unsigned::Config>::MinerPages::get();
2981			// Mine an unsigned solution
2982			let unsigned_solution =
2983				OffchainWorkerMiner::<Runtime>::mine_solution(miner_pages, true).unwrap();
2984
2985			// Submit the unsigned solution
2986			assert_ok!(UnsignedPallet::submit_unsigned(
2987				RuntimeOrigin::from(frame_system::RawOrigin::Authorized),
2988				Box::new(unsigned_solution)
2989			));
2990
2991			// Move to Done phase
2992			roll_to_done();
2993
2994			// In the mock runtime Pages::get() = 3 so unsigned solution has 1 page but we go
2995			// through Done -> Export(2) -> Export(1) -> Export(0) -> Off via elect().
2996			// First elect call should succeed
2997			let result1 = MultiBlock::elect(2);
2998			assert!(result1.is_ok());
2999			assert_eq!(MultiBlock::current_phase(), Phase::Export(1));
3000
3001			// Second elect call should now fail because we have mined a solution with MinerPages
3002			// equal to 1.
3003			// Phase should advance even on error.
3004			let result2 = MultiBlock::elect(1);
3005			assert!(result2.is_err());
3006			assert_eq!(MultiBlock::current_phase(), Phase::Export(0));
3007
3008			// Third elect call should also fail but still advance to Off
3009			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			// load a solution into the verifier
3023			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			// and right here, in the middle of the signed verification phase, we close the round.
3028			// Everything should work fine.
3029			assert!(matches!(MultiBlock::current_phase(), Phase::SignedValidation(_)));
3030			assert_eq!(Round::<Runtime>::get(), 0);
3031			assert_full_snapshot();
3032
3033			// fetch all pages.
3034			let _paged_solution = (MultiBlock::lsp()..MultiBlock::msp())
3035				.rev() // 2, 1, 0
3036				.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			// round is incremented.
3047			assert_eq!(MultiBlock::round(), round + 1);
3048			// after elect(0) is called, verifier is cleared,
3049			verifier::QueuedSolution::<Runtime>::assert_killed();
3050			// the phase is off,
3051			assert_eq!(MultiBlock::current_phase(), Phase::Off);
3052			// the snapshot is cleared,
3053			assert_none_snapshot();
3054			// and signed pallet is clean.
3055			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			// load a solution into the verifier
3067			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			// fetch one page.
3073			assert!(MultiBlock::elect(MultiBlock::msp()).is_ok());
3074
3075			// try submit one signed page:
3076			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			// same targets, but voters from page 2 (1, 2, 3, 4, see `mock/staking`).
3099			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			// page 1 of voters
3113			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			// self votes
3127			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			// This will set us to emergency phase, because we don't know wtf to do.
3156			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			// but then we immediately call `elect`, this will work
3166			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			// This will set us to the off phase, since fallback saved us.
3187			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				// bad origin cannot call
3219				assert_noop!(
3220					MultiBlock::manage(
3221						RuntimeOrigin::signed(Manager::get() + 1),
3222						ManagerOperation::EmergencyFallback
3223					),
3224					DispatchError::BadOrigin
3225				);
3226
3227				// we get a call to elect(0). this will cause emergency, since no fallback is
3228				// allowed.
3229				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				// we can now set the solution to emergency, assuming fallback is set to onchain
3236				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	// This scenario have multiple outcomes:
3272	// 1. rotate in off => almost a noop
3273	// 2. rotate mid signed, validation, unsigned, done, but NOT export => clear all data, move to
3274	//    next round and be off. Note: all of the data in this pallet is indexed by the round index,
3275	//    so moving to the next round will implicitly make the old data unavaioable, even if not
3276	//    cleared out. This secnario needs further testing.
3277	// 3. rotate mid export: same as above, except staking will be out of sync and will also need
3278	//    governance intervention.
3279	//
3280	// This test is primarily checking the origin limits of this call, and will use scenario 2.
3281	#[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			// we have snapshot data now for this round.
3292			assert_full_snapshot();
3293			// there is some data in the verifier pallet
3294			assert!(verifier::QueuedSolution::<T>::queued_score().is_some());
3295			// phase is
3296			assert_eq!(MultiBlock::current_phase(), Phase::SignedValidation(2));
3297
3298			// force new round
3299
3300			// bad origin cannot submit
3301			assert_noop!(
3302				MultiBlock::manage(
3303					RuntimeOrigin::signed(Manager::get() + 1),
3304					ManagerOperation::ForceRotateRound
3305				),
3306				DispatchError::BadOrigin
3307			);
3308			// manager can submit
3309			assert_ok!(MultiBlock::manage(
3310				RuntimeOrigin::signed(Manager::get()),
3311				ManagerOperation::ForceRotateRound
3312			));
3313
3314			// phase is off again
3315			assert_eq!(MultiBlock::current_phase(), Phase::Off);
3316			// round is bumped
3317			assert_eq!(MultiBlock::round(), round + 1);
3318			// snapshot is wiped
3319			assert_none_snapshot();
3320			// verifier is in clean state
3321			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			// bad origin cannot submit
3332			assert_noop!(
3333				MultiBlock::manage(
3334					RuntimeOrigin::signed(Manager::get() + 1),
3335					ManagerOperation::ForceSetPhase(Phase::Done)
3336				),
3337				DispatchError::BadOrigin
3338			);
3339
3340			// manager can submit. They skip the signed phases.
3341			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			// admin can also submit
3349			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			// bad origin cannot call
3368			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			// manager (non-root) cannot call
3377			assert_noop!(
3378				MultiBlock::admin(
3379					RuntimeOrigin::signed(Manager::get()),
3380					AdminOperation::EmergencySetSolution(Default::default(), Default::default())
3381				),
3382				DispatchError::BadOrigin
3383			);
3384
3385			// we get a call to elect(0). this will cause emergency, since no fallback is allowed.
3386			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			// we can now set the solution to emergency.
3393			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			// bad origin cannot call
3432			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			// manager cannot call, only admin.
3444			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}