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 frame_election_provider_support::PageIndex;
80use impls::SupportsOfVerifier;
81pub use impls::{feasibility_check_page_inner_with_snapshot, pallet::*, Status};
82use sp_core::Get;
83use sp_npos_elections::ElectionScore;
84use sp_std::{fmt::Debug, prelude::*};
85
86/// Errors that can happen in the feasibility check.
87#[derive(
88 Debug,
89 Eq,
90 PartialEq,
91 codec::Encode,
92 codec::Decode,
93 codec::DecodeWithMemTracking,
94 scale_info::TypeInfo,
95 Clone,
96)]
97pub enum FeasibilityError {
98 /// Wrong number of winners presented.
99 WrongWinnerCount,
100 /// The snapshot is not available.
101 ///
102 /// Kinda defensive: The pallet should technically never attempt to do a feasibility check
103 /// when no snapshot is present.
104 SnapshotUnavailable,
105 /// A vote is invalid.
106 InvalidVote,
107 /// A voter is invalid.
108 InvalidVoter,
109 /// A winner is invalid.
110 InvalidWinner,
111 /// The given score was invalid.
112 InvalidScore,
113 /// The provided round is incorrect.
114 InvalidRound,
115 /// Solution does not have a good enough score.
116 ScoreTooLow,
117 /// The support type failed to be bounded.
118 ///
119 /// Relates to [`Config::MaxWinnersPerPage`], [`Config::MaxBackersPerWinner`] or
120 /// `MaxBackersPerWinnerFinal`
121 FailedToBoundSupport,
122 /// Internal error from the election crate.
123 NposElection(sp_npos_elections::Error),
124 /// The solution is incomplete, it has too few pages.
125 ///
126 /// This is (somewhat) synonym to `WrongPageCount` in other places.
127 Incomplete,
128}
129
130impl From<sp_npos_elections::Error> for FeasibilityError {
131 fn from(e: sp_npos_elections::Error) -> Self {
132 FeasibilityError::NposElection(e)
133 }
134}
135
136/// The interface of something that can verify solutions for other sub-pallets in the multi-block
137/// election pallet-network.
138pub trait Verifier {
139 /// The solution type.
140 type Solution;
141 /// The account if type.
142 type AccountId;
143
144 /// Maximum number of winners that can be represented in each page.
145 ///
146 /// A reasonable value for this should be the maximum number of winners that the election user
147 /// (e.g. the staking pallet) could ever desire.
148 type MaxWinnersPerPage: Get<u32>;
149
150 /// Maximum number of backers, per winner, among all pages of an election.
151 ///
152 /// This can only be checked at the very final step of verification.
153 type MaxBackersPerWinnerFinal: Get<u32>;
154
155 /// Maximum number of backers that each winner could have, per page.
156 type MaxBackersPerWinner: Get<u32>;
157
158 /// Set the minimum score that is acceptable for any solution.
159 ///
160 /// Henceforth, all solutions must have at least this degree of quality, single-page or
161 /// multi-page.
162 fn set_minimum_score(score: ElectionScore);
163
164 /// The score of the current best solution. `None` if there is none.
165 fn queued_score() -> Option<ElectionScore>;
166
167 /// Check if the claimed score is sufficient to challenge the current queued solution, if any.
168 fn ensure_claimed_score_improves(claimed_score: ElectionScore) -> bool;
169
170 /// Clear all storage items, there's nothing else to do until further notice.
171 fn kill();
172
173 /// Get a single page of the best verified solution, if any.
174 ///
175 /// It is the responsibility of the call site to call this function with all appropriate
176 /// `page` arguments.
177 fn get_queued_solution_page(page: PageIndex) -> Option<SupportsOfVerifier<Self>>;
178
179 /// Perform the feasibility check on the given single-page solution.
180 ///
181 /// This will perform:
182 ///
183 /// 1. feasibility-check
184 /// 2. claimed score is correct and an improvement.
185 /// 3. bounds are respected
186 ///
187 /// Corresponding snapshot (represented by `page`) is assumed to be available.
188 ///
189 /// If all checks pass, the solution is also queued.
190 fn verify_synchronous(
191 partial_solution: Self::Solution,
192 claimed_score: ElectionScore,
193 page: PageIndex,
194 ) -> Result<(), FeasibilityError> {
195 Self::verify_synchronous_multi(vec![partial_solution], vec![page], claimed_score)
196 }
197
198 /// Perform synchronous feasibility check on the given multi-page solution.
199 ///
200 /// Same semantics as [`Self::verify_synchronous`], but for multi-page solutions.
201 fn verify_synchronous_multi(
202 partial_solution: Vec<Self::Solution>,
203 pages: Vec<PageIndex>,
204 claimed_score: ElectionScore,
205 ) -> Result<(), FeasibilityError>;
206
207 /// Force set a single page solution as the valid one.
208 ///
209 /// Will erase any previous solution. Should only be used in case of emergency fallbacks,
210 /// trusted governance solutions and so on.
211 fn force_set_single_page_valid(
212 partial_supports: SupportsOfVerifier<Self>,
213 page: PageIndex,
214 score: ElectionScore,
215 );
216}
217
218/// Simple enum to encapsulate the result of the verification of a candidate solution.
219#[derive(Clone, Copy, Debug)]
220#[cfg_attr(test, derive(PartialEq, Eq))]
221pub enum VerificationResult {
222 /// Solution is valid and is queued.
223 Queued,
224 /// Solution is rejected, for whichever of the multiple reasons that it could be.
225 Rejected,
226}
227
228/// Something that can provide candidate solutions to the verifier.
229///
230/// In reality, this can be implemented by the [`crate::signed::Pallet`], where signed solutions are
231/// queued and sorted based on claimed score, and they are put forth one by one, from best to worse.
232pub trait SolutionDataProvider {
233 /// The opaque solution type.
234 type Solution;
235
236 /// Return the `page`th page of the current best solution that the data provider has in store.
237 ///
238 /// If no candidate solutions are available, an empty page is returned (i.e., a page that
239 /// contains no solutions and contributes zero to the final score).
240 fn get_page(page: PageIndex) -> Self::Solution;
241
242 /// Get the claimed score of the current best solution.
243 ///
244 /// If no score is available, a default/zero score should be returned defensively.
245 fn get_score() -> ElectionScore;
246
247 /// Hook to report back the results of the verification of the current candidate solution that
248 /// is being exposed via [`Self::get_page`] and [`Self::get_score`].
249 ///
250 /// Every time that this is called, the verifier [`AsynchronousVerifier`] goes back to the
251 /// [`Status::Nothing`] state, and it is the responsibility of [`Self`] to call `start` again,
252 /// if desired.
253 fn report_result(result: VerificationResult);
254}
255
256/// Something that can do the verification asynchronously.
257pub trait AsynchronousVerifier: Verifier {
258 /// The data provider that can provide the candidate solution, and to whom we report back the
259 /// results.
260 type SolutionDataProvider: SolutionDataProvider;
261
262 /// Get the current stage of the verification process.
263 fn status() -> Status;
264
265 /// Start a verification process.
266 ///
267 /// Returns `Ok(())` if verification started successfully, and `Err(..)` if a verification is
268 /// already ongoing and therefore a new one cannot be started.
269 ///
270 /// From the coming block onwards, the verifier will start and fetch the relevant information
271 /// and solution pages from [`SolutionDataProvider`]. It is expected that the
272 /// [`SolutionDataProvider`] is ready before calling [`Self::start`].
273 ///
274 /// Pages of the solution are fetched sequentially and in order from [`SolutionDataProvider`],
275 /// from `msp` to `lsp`.
276 ///
277 /// This ends in either of the two:
278 ///
279 /// 1. All pages, including the final checks (like score and other facts that can only be
280 /// derived from a full solution) are valid and the solution is verified. The solution is
281 /// queued and is ready for further export.
282 /// 2. The solution checks verification at one of the steps. Nothing is stored inside the
283 /// verifier pallet and all intermediary data is removed.
284 ///
285 /// In both cases, the [`SolutionDataProvider`] is informed via
286 /// [`SolutionDataProvider::report_result`]. It is sensible for the data provide to call `start`
287 /// again if the verification has failed, and nothing otherwise. Indeed, the
288 /// [`SolutionDataProvider`] must adjust its internal state such that it returns a new candidate
289 /// solution after each failure.
290 fn start() -> Result<(), &'static str>;
291}