referrerpolicy=no-referrer-when-downgrade

pallet_election_provider_multi_block/verifier/
mod.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//! # The Verifier Pallet
19//!
20//! This pallet has no end-user functionality, and is only used internally by other pallets in the
21//! EPMB machinery to verify solutions.
22//!
23//! ### *Feasibility* Check
24//!
25//! Before explaining the pallet itself, it should be explained what a *verification* even means.
26//! Verification of a solution page ([`crate::unsigned::miner::MinerConfig::Solution`]) includes the
27//! process of checking all of its edges against a snapshot to be correct. For instance, all voters
28//! that are presented in a solution page must have actually voted for the winner that they are
29//! backing, based on the snapshot kept in the parent pallet.
30//!
31//! Such checks are bound to each page of the solution, and happen per-page. After checking all of
32//! the edges in each page, a handful of other checks are performed. These checks cannot happen
33//! per-page, and in order to do them we need to have the entire solution checked and verified.
34//!
35//! 1. Check that the total number of winners is sufficient (`DesiredTargets`).
36//! 2. Check that the claimed score ([`sp_npos_elections::ElectionScore`]) is correct,
37//!   * and more than the minimum score that can be specified via [`Verifier::set_minimum_score`].
38//! 3. Check that all of the bounds of the solution are respected, namely
39//!    [`Verifier::MaxBackersPerWinner`], [`Verifier::MaxWinnersPerPage`] and
40//!    [`Verifier::MaxBackersPerWinnerFinal`].
41//!
42//! Note that the common factor of all of the above checks is that they can ONLY be checked after
43//! all pages are already verified. So, in the case of a multi-page verification, these checks are
44//! performed at the last page.
45//!
46//! The errors that can arise while performing the feasibility check are encapsulated in
47//! [`verifier::FeasibilityError`].
48//!
49//! ## Modes of Verification
50//!
51//! The verifier pallet provide two modes of functionality:
52//!
53//! 1. Single or multi-page, synchronous verification. This is useful in the context of single-page,
54//!    emergency, or unsigned solutions that need to be verified on the fly. This is similar to how
55//!    the old school `multi-phase` pallet works. See [`Verifier::verify_synchronous`] and
56//!    [`Verifier::verify_synchronous_multi`].
57//! 2. Multi-page, asynchronous verification. This is useful in the context of multi-page, signed
58//!    solutions. See [`verifier::AsynchronousVerifier`] and [`verifier::SolutionDataProvider`].
59//!
60//! Both of this, plus some helper functions, is exposed via the [`verifier::Verifier`] trait.
61//!
62//! ## Queued Solution
63//!
64//! once a solution has been verified, it is called a *queued solution*. It is sitting in a queue,
65//! waiting for either of:
66//!
67//! 1. being challenged and potentially replaced by better solution, if any.
68//! 2. being exported as the final outcome of the election.
69
70#[cfg(feature = "runtime-benchmarks")]
71pub mod benchmarking;
72mod impls;
73#[cfg(test)]
74mod tests;
75
76// internal imports
77pub use crate::weights::traits::pallet_election_provider_multi_block_verifier::*;
78
79use alloc::{boxed::Box, vec, vec::Vec};
80use core::fmt::Debug;
81use frame_election_provider_support::PageIndex;
82use frame_support::weights::WeightMeter;
83use impls::SupportsOfVerifier;
84pub use impls::{feasibility_check_page_inner_with_snapshot, pallet::*, Status};
85use sp_core::Get;
86use sp_npos_elections::ElectionScore;
87use sp_runtime::Weight;
88
89/// Errors that can happen in the feasibility check.
90#[derive(
91	Debug,
92	Eq,
93	PartialEq,
94	codec::Encode,
95	codec::Decode,
96	codec::DecodeWithMemTracking,
97	scale_info::TypeInfo,
98	Clone,
99)]
100pub enum FeasibilityError {
101	/// Wrong number of winners presented.
102	WrongWinnerCount,
103	/// The snapshot is not available.
104	///
105	/// Kinda defensive: The pallet should technically never attempt to do a feasibility check
106	/// when no snapshot is present.
107	SnapshotUnavailable,
108	/// A vote is invalid.
109	InvalidVote,
110	/// A voter is invalid.
111	InvalidVoter,
112	/// A winner is invalid.
113	InvalidWinner,
114	/// The given score was invalid.
115	InvalidScore,
116	/// The provided round is incorrect.
117	InvalidRound,
118	/// Solution does not have a good enough score.
119	ScoreTooLow,
120	/// The support type failed to be bounded.
121	///
122	/// Relates to [`Config::MaxWinnersPerPage`], [`Config::MaxBackersPerWinner`] or
123	/// `MaxBackersPerWinnerFinal`
124	FailedToBoundSupport,
125	/// Internal error from the election crate.
126	NposElection(sp_npos_elections::Error),
127	/// The solution is incomplete, it has too few pages.
128	///
129	/// This is (somewhat) synonym to `WrongPageCount` in other places.
130	Incomplete,
131}
132
133impl From<sp_npos_elections::Error> for FeasibilityError {
134	fn from(e: sp_npos_elections::Error) -> Self {
135		FeasibilityError::NposElection(e)
136	}
137}
138
139/// The interface of something that can verify solutions for other sub-pallets in the multi-block
140/// election pallet-network.
141pub trait Verifier {
142	/// The solution type.
143	type Solution;
144	/// The account if type.
145	type AccountId;
146
147	/// Maximum number of winners that can be represented in each page.
148	///
149	/// A reasonable value for this should be the maximum number of winners that the election user
150	/// (e.g. the staking pallet) could ever desire.
151	type MaxWinnersPerPage: Get<u32>;
152
153	/// Maximum number of backers, per winner, among all pages of an election.
154	///
155	/// This can only be checked at the very final step of verification.
156	type MaxBackersPerWinnerFinal: Get<u32>;
157
158	/// Maximum number of backers that each winner could have, per page.
159	type MaxBackersPerWinner: Get<u32>;
160
161	/// Set the minimum score that is acceptable for any solution.
162	///
163	/// Henceforth, all solutions must have at least this degree of quality, single-page or
164	/// multi-page.
165	fn set_minimum_score(score: ElectionScore);
166
167	/// The score of the current best solution. `None` if there is none.
168	fn queued_score() -> Option<ElectionScore>;
169
170	/// Check if the claimed score is sufficient to challenge the current queued solution, if any.
171	fn ensure_claimed_score_improves(claimed_score: ElectionScore) -> bool;
172
173	/// Clear all storage items, there's nothing else to do until further notice.
174	fn kill();
175
176	/// Get a single page of the best verified solution, if any.
177	///
178	/// It is the responsibility of the call site to call this function with all appropriate
179	/// `page` arguments.
180	fn get_queued_solution_page(page: PageIndex) -> Option<SupportsOfVerifier<Self>>;
181
182	/// Perform the feasibility check on the given single-page solution.
183	///
184	/// This will perform:
185	///
186	/// 1. feasibility-check
187	/// 2. claimed score is correct and an improvement.
188	/// 3. bounds are respected
189	///
190	/// Corresponding snapshot (represented by `page`) is assumed to be available.
191	///
192	/// If all checks pass, the solution is also queued.
193	fn verify_synchronous(
194		partial_solution: Self::Solution,
195		claimed_score: ElectionScore,
196		page: PageIndex,
197	) -> Result<(), FeasibilityError> {
198		Self::verify_synchronous_multi(vec![partial_solution], vec![page], claimed_score)
199	}
200
201	/// Perform synchronous feasibility check on the given multi-page solution.
202	///
203	/// Same semantics as [`Self::verify_synchronous`], but for multi-page solutions.
204	fn verify_synchronous_multi(
205		partial_solution: Vec<Self::Solution>,
206		pages: Vec<PageIndex>,
207		claimed_score: ElectionScore,
208	) -> Result<(), FeasibilityError>;
209
210	/// Force set a single page solution as the valid one.
211	///
212	/// Will erase any previous solution. Should only be used in case of emergency fallbacks,
213	/// trusted governance solutions and so on.
214	fn force_set_single_page_valid(
215		partial_supports: SupportsOfVerifier<Self>,
216		page: PageIndex,
217		score: ElectionScore,
218	);
219
220	/// Return the execution schedule of this pallet's work to be done per-block (`on_poll`,
221	/// `on_init` independent).
222	///
223	/// Returns a `(Weight, ExecFn)` tuple in-line with `per_block_exec` of the parent block.
224	fn per_block_exec() -> (Weight, Box<dyn Fn(&mut WeightMeter)>);
225}
226
227/// Simple enum to encapsulate the result of the verification of a candidate solution.
228#[derive(Clone, Copy, Debug)]
229#[cfg_attr(test, derive(PartialEq, Eq))]
230pub enum VerificationResult {
231	/// Solution is valid and is queued.
232	Queued,
233	/// Solution is rejected, for whichever of the multiple reasons that it could be.
234	Rejected,
235}
236
237/// Something that can provide candidate solutions to the verifier.
238///
239/// In reality, this can be implemented by the [`crate::signed::Pallet`], where signed solutions are
240/// queued and sorted based on claimed score, and they are put forth one by one, from best to worse.
241pub trait SolutionDataProvider {
242	/// The opaque solution type.
243	type Solution;
244
245	/// Return the `page`th page of the current best solution that the data provider has in store.
246	///
247	/// If no candidate solutions are available, an empty page is returned (i.e., a page that
248	/// contains no solutions and contributes zero to the final score).
249	fn get_page(page: PageIndex) -> Self::Solution;
250
251	/// Get the claimed score of the current best solution.
252	///
253	/// If no score is available, a default/zero score should be returned defensively.
254	fn get_score() -> ElectionScore;
255
256	/// Hook to report back the results of the verification of the current candidate solution that
257	/// is being exposed via [`Self::get_page`] and [`Self::get_score`].
258	///
259	/// Every time that this is called, the verifier [`AsynchronousVerifier`] goes back to the
260	/// [`Status::Nothing`] state, and it is the responsibility of [`Self`] to call `start` again,
261	/// if desired.
262	fn report_result(result: VerificationResult);
263}
264
265/// Something that can do the verification asynchronously.
266pub trait AsynchronousVerifier: Verifier {
267	/// The data provider that can provide the candidate solution, and to whom we report back the
268	/// results.
269	type SolutionDataProvider: SolutionDataProvider;
270
271	/// Get the current stage of the verification process.
272	fn status() -> Status;
273
274	/// Start a verification process.
275	///
276	/// Returns `Ok(())` if verification started successfully, and `Err(..)` if a verification is
277	/// already ongoing and therefore a new one cannot be started.
278	///
279	/// From the coming block onwards, the verifier will start and fetch the relevant information
280	/// and solution pages from [`SolutionDataProvider`]. It is expected that the
281	/// [`SolutionDataProvider`] is ready before calling [`Self::start`].
282	///
283	/// Pages of the solution are fetched sequentially and in order from [`SolutionDataProvider`],
284	/// from `msp` to `lsp`.
285	///
286	/// This ends in either of the two:
287	///
288	/// 1. All pages, including the final checks (like score and other facts that can only be
289	///    derived from a full solution) are valid and the solution is verified. The solution is
290	///    queued and is ready for further export.
291	/// 2. The solution checks verification at one of the steps. Nothing is stored inside the
292	///    verifier pallet and all intermediary data is removed.
293	///
294	/// In both cases, the [`SolutionDataProvider`] is informed via
295	/// [`SolutionDataProvider::report_result`]. It is sensible for the data provide to call `start`
296	/// again if the verification has failed, and nothing otherwise. Indeed, the
297	/// [`SolutionDataProvider`] must adjust its internal state such that it returns a new candidate
298	/// solution after each failure.
299	fn start() -> Result<(), &'static str>;
300}