referrerpolicy=no-referrer-when-downgrade

pallet_election_provider_multi_block/signed/
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 signed phase of the multi-block election system.
19//!
20//! Signed submissions work on the basis of keeping a queue of submissions from unknown signed
21//! accounts, and sorting them based on the best claimed score to the worst.
22//!
23//! Each submission must put a deposit down. This is parameterize-able by the runtime, and might be
24//! a constant, linear or exponential value. See [`signed::Config::DepositPerPage`] and
25//! [`signed::Config::DepositBase`]. The base deposit is charged once, at
26//! [`signed::Call::register`], and stored with the submission. The deposit held is that base plus
27//! the per-page deposit of the stored pages, at the current per-page price. Accounts in
28//! [`signed::Invulnerables`] have no per-page part.
29//!
30//! During the queuing time, if the queue is full, and a better solution comes in, the weakest
31//! deposit is said to be **Ejected**. Ejected solutions get [`signed::Config::EjectGraceRatio`] of
32//! their deposit back. This is because we have to delete any submitted pages from them on the spot.
33//! They don't get any refund of whatever tx-fee they have paid.
34//!
35//! Once the time to evaluate the signed phase comes (`Phase::SignedValidation`), the solutions are
36//! checked from best-to-worst claim, and they end up in either of the 3 buckets:
37//!
38//! 1. **Rewarded**: If they are the first correct solution (and consequently the best one, since we
39//!    start evaluating from the best claim), they are rewarded. Rewarded solutions always get both
40//!    their deposit and transaction fee back, the latter up to [`signed::Config::MaxFeeRefund`].
41//! 2. **Slashed**: Any invalid solution that wasted valuable blockchain time gets slashed for their
42//!    deposit.
43//! 3. **Discarded**: Any solution after the first correct solution is eligible to be peacefully
44//!    discarded. But, to delete their data, they have to call
45//!    [`signed::Call::clear_old_round_data`]. Once done, they get their full deposit back. Accounts
46//!    in [`signed::Invulnerables`] also get their tx-fee back, up to
47//!    [`signed::Config::MaxFeeRefund`]. Other submitters' tx-fees are not refunded.
48//!
49//! ## Future Plans:
50//!
51//! **Lazy Deletion In Eject**: While most deletion ops of the signed phase are now lazy, if someone
52//! is ejected from the list, we still remove their data in sync.
53//!
54//! **Metadata update**: imagine you mis-computed your score.
55//!
56//! **Permissionless `clear_old_round_data`**: Anyone can clean anyone else's data, and get a part
57//! of their deposit.
58
59use crate::{
60	types::SolutionOf,
61	verifier::{AsynchronousVerifier, SolutionDataProvider, Status, VerificationResult},
62};
63use alloc::{boxed::Box, vec::Vec};
64use codec::{Decode, Encode, MaxEncodedLen};
65use frame_election_provider_support::PageIndex;
66use frame_support::{
67	dispatch::{DispatchResultWithPostInfo, GetDispatchInfo},
68	pallet_prelude::{StorageDoubleMap, ValueQuery, *},
69	traits::{
70		tokens::{
71			fungible::{
72				BalancedHold, Credit as FungibleCredit, Inspect, Mutate, MutateHold, Unbalanced,
73			},
74			Imbalance, Precision, Preservation,
75		},
76		Defensive, DefensiveSaturating, EstimateCallFee, EstimateFee, OnUnbalanced,
77	},
78	BoundedVec, Twox64Concat,
79};
80use frame_system::{ensure_signed, pallet_prelude::*};
81use scale_info::TypeInfo;
82use sp_io::MultiRemovalResults;
83use sp_npos_elections::ElectionScore;
84use sp_runtime::{
85	traits::{Saturating, Zero},
86	Perbill,
87};
88
89/// Explore all weights
90pub use crate::weights::traits::pallet_election_provider_multi_block_signed::*;
91/// Exports of this pallet
92pub use pallet::*;
93
94#[cfg(feature = "runtime-benchmarks")]
95mod benchmarking;
96pub mod migrations;
97
98pub(crate) type SignedWeightsOf<T> = <T as crate::signed::Config>::WeightInfo;
99
100#[cfg(test)]
101mod tests;
102
103type BalanceOf<T> =
104	<<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
105
106/// All of the (meta) data around a signed submission
107#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, Default, DebugNoBound)]
108#[cfg_attr(test, derive(frame_support::PartialEqNoBound, frame_support::EqNoBound))]
109#[codec(mel_bound(T: Config))]
110#[scale_info(skip_type_params(T))]
111pub struct SubmissionMetadata<T: Config> {
112	/// The amount of deposit that has been held in reserve.
113	deposit: BalanceOf<T>,
114	/// The amount of transaction fee that this submission has cost for its submitter so far.
115	fee: BalanceOf<T>,
116	/// The amount of rewards that we expect to give to this submission, if deemed worthy.
117	reward: BalanceOf<T>,
118	/// The score that this submission is claiming to achieve.
119	claimed_score: ElectionScore,
120	/// A bounded-bool-vec of pages that have been submitted so far.
121	pages: BoundedVec<bool, T::Pages>,
122	/// The base deposit charged at registration, included in `deposit`.
123	base: BalanceOf<T>,
124}
125
126/// Maximum number of entries in [`UnpaidRewards`].
127///
128/// Deferrals require a depleted pot and at most one entry is created per round, so a small fixed
129/// bound suffices for every runtime. When full, the oldest entry is evicted.
130pub const MAX_UNPAID_REWARDS: u32 = 16;
131
132/// A round-winner reward that failed to pay, pending a permissionless claim via
133/// [`Pallet::claim_unpaid_reward`]. Rewards only, not fee refunds, so `round` is a unique key.
134#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, Clone, DebugNoBound)]
135#[cfg_attr(test, derive(frame_support::PartialEqNoBound, frame_support::EqNoBound))]
136#[codec(mel_bound(T: Config))]
137#[scale_info(skip_type_params(T))]
138pub struct UnpaidReward<T: Config> {
139	/// The round the reward was owed for; unique among [`UnpaidRewards`] entries.
140	round: u32,
141	/// The winner the reward is owed to.
142	who: T::AccountId,
143	/// The amount owed.
144	amount: BalanceOf<T>,
145}
146
147impl<T: Config> crate::types::SignedInterface for Pallet<T> {
148	fn has_leader(round: u32) -> bool {
149		Submissions::<T>::has_leader(round)
150	}
151}
152
153impl<T: Config> SolutionDataProvider for Pallet<T> {
154	type Solution = SolutionOf<T::MinerConfig>;
155
156	// `get_page` should only be called when a leader exists.
157	// The verifier only transitions to `Status::Ongoing` when a leader is confirmed to exist.
158	// During verification, the leader should remain unchanged - it's only removed when
159	// verification fails (which immediately stops the verifier) or completes successfully.
160	fn get_page(page: PageIndex) -> Self::Solution {
161		let current_round = Self::current_round();
162		Submissions::<T>::leader(current_round)
163			.defensive()
164			.and_then(|(who, _score)| {
165				sublog!(
166					debug,
167					"signed",
168					"returning page {} of {:?}'s submission as leader.",
169					page,
170					who
171				);
172				Submissions::<T>::get_page_of(current_round, &who, page)
173			})
174			.unwrap_or_default()
175	}
176
177	// `get_score` should only be called when a leader exists.
178	fn get_score() -> ElectionScore {
179		let current_round = Self::current_round();
180		Submissions::<T>::leader(current_round)
181			.defensive()
182			.inspect(|(_who, score)| {
183				sublog!(
184					debug,
185					"signed",
186					"returning score {:?} of current leader for round {}.",
187					score,
188					current_round
189				);
190			})
191			.map(|(_who, score)| score)
192			.unwrap_or_default()
193	}
194
195	fn report_result(result: crate::verifier::VerificationResult) {
196		// assumption of the trait.
197		debug_assert!(matches!(<T::Verifier as AsynchronousVerifier>::status(), Status::Nothing));
198		let current_round = Self::current_round();
199
200		match result {
201			VerificationResult::Queued => {
202				// defensive: if there is a result to be reported, then we must have had some
203				// leader.
204				if let Some((winner, metadata)) =
205					Submissions::<T>::take_leader_with_data(Self::current_round()).defensive()
206				{
207					// first, let's give them their reward.
208					let reward =
209						metadata.reward.saturating_add(metadata.fee.min(T::MaxFeeRefund::get()));
210					Self::pay_reward(current_round, &winner, reward);
211
212					// then, unreserve their deposit
213					let _res = T::Currency::release(
214						&HoldReason::SignedSubmission.into(),
215						&winner,
216						metadata.deposit,
217						Precision::BestEffort,
218					);
219					debug_assert!(_res.is_ok());
220				}
221			},
222			VerificationResult::Rejected => {
223				Self::handle_solution_rejection(current_round);
224			},
225		}
226	}
227}
228
229/// Something that can compute the base deposit that is collected upon `register`.
230///
231/// A blanket impl allows for any `Get` to be used as-is, which will always return the said balance
232/// as deposit.
233pub trait CalculateBaseDeposit<Balance> {
234	fn calculate_base_deposit(existing_submitters: usize) -> Balance;
235}
236
237impl<Balance, G: Get<Balance>> CalculateBaseDeposit<Balance> for G {
238	fn calculate_base_deposit(_existing_submitters: usize) -> Balance {
239		G::get()
240	}
241}
242
243/// Something that can calculate the deposit per-page upon `submit`.
244///
245/// A blanket impl allows for any `Get` to be used as-is, which will always return the said balance
246/// as deposit **per page**.
247pub trait CalculatePageDeposit<Balance> {
248	fn calculate_page_deposit(page_size: usize) -> Balance;
249}
250
251impl<Balance: From<u32> + Saturating, G: Get<Balance>> CalculatePageDeposit<Balance> for G {
252	fn calculate_page_deposit(page_size: usize) -> Balance {
253		let page_size: Balance = (page_size as u32).into();
254		G::get().saturating_mul(page_size)
255	}
256}
257
258/// Provides the account that reward payments and invulnerable fee refunds are drawn from.
259///
260/// `None` mints directly. `Some(account)` transfers from `account`, followed by a call to
261/// [`Self::paid`] for any bookkeeping the source needs to perform after a successful payout.
262pub trait RewardSource<AccountId, Balance> {
263	/// The pot account to draw the reward from, or `None` to mint directly.
264	fn account() -> Option<AccountId>;
265
266	/// Called after `amount` has been successfully transferred out of the pot.
267	fn paid(amount: Balance);
268}
269
270/// A [`RewardSource`] drawing from the account in `P`, with no issuance reactivation.
271///
272/// Correct only for pots holding *active* funds. A pot holding deactivated issuance, such as a
273/// DAP buffer, must use a source that reactivates in [`RewardSource::paid`].
274pub struct ActivePot<P>(core::marker::PhantomData<P>);
275
276impl<AccountId, Balance, P: Get<Option<AccountId>>> RewardSource<AccountId, Balance>
277	for ActivePot<P>
278{
279	fn account() -> Option<AccountId> {
280		P::get()
281	}
282
283	fn paid(_amount: Balance) {}
284}
285
286/// A [`RewardSource`] drawing from the account in `P`, reactivating the paid amount in
287/// `Currency` afterwards.
288///
289/// For pots holding previously-deactivated issuance, such as a DAP buffer.
290pub struct ReactivatingPot<P, Currency>(core::marker::PhantomData<(P, Currency)>);
291
292impl<AccountId, Balance, P, Currency> RewardSource<AccountId, Balance>
293	for ReactivatingPot<P, Currency>
294where
295	P: Get<Option<AccountId>>,
296	Currency: Unbalanced<AccountId, Balance = Balance>,
297{
298	fn account() -> Option<AccountId> {
299		P::get()
300	}
301
302	fn paid(amount: Balance) {
303		Currency::reactivate(amount);
304	}
305}
306
307/// A [`Config::MaxFeeRefund`] that is the fee of a full submission: one [`Pallet::register`], plus
308/// [`crate::Config::Pages`] [`Pallet::submit_page`] calls, each carrying a maximum-size solution
309/// page.
310///
311/// `F` is the fee model of the runtime, typically `pallet_transaction_payment::Pallet`. This is
312/// derived from the same inputs the pallet accrues from, so it follows any change to the page
313/// count, the solution type, or the fee model.
314pub struct FullSubmissionFee<T, F>(PhantomData<(T, F)>);
315
316impl<T: Config, F: EstimateFee<BalanceOf<T>>> Get<BalanceOf<T>> for FullSubmissionFee<T, F> {
317	fn get() -> BalanceOf<T> {
318		// top the length up with the largest page that `maybe_solution` could have carried.
319		let page_call = Call::<T>::submit_page { page: 0, maybe_solution: None };
320		let page_len = page_call
321			.encoded_size()
322			.saturating_add(SolutionOf::<T::MinerConfig>::max_encoded_len());
323		let per_page = F::estimate_fee(page_len as u32, &page_call.get_dispatch_info());
324
325		let register_call = Call::<T>::register { claimed_score: Default::default() };
326		let register = F::estimate_fee(
327			register_call.encoded_size() as u32,
328			&register_call.get_dispatch_info(),
329		);
330
331		register.saturating_add(per_page.saturating_mul(T::Pages::get().into()))
332	}
333}
334
335#[frame_support::pallet]
336pub mod pallet {
337	use super::*;
338
339	#[pallet::config]
340	#[pallet::disable_frame_system_supertrait_check]
341	pub trait Config: crate::Config {
342		/// Handler to the currency.
343		type Currency: Inspect<Self::AccountId>
344			+ Mutate<Self::AccountId>
345			+ MutateHold<Self::AccountId, Reason: From<HoldReason>>
346			+ BalancedHold<Self::AccountId>;
347
348		/// Base deposit amount for a submission.
349		type DepositBase: CalculateBaseDeposit<BalanceOf<Self>>;
350
351		/// Extra deposit per-page.
352		type DepositPerPage: CalculatePageDeposit<BalanceOf<Self>>;
353
354		/// The fixed deposit charged upon [`Pallet::register`] from [`Invulnerables`].
355		type InvulnerableDeposit: Get<BalanceOf<Self>>;
356
357		/// Base reward that is given to the winner.
358		type RewardBase: Get<BalanceOf<Self>>;
359
360		/// Maximum number of submissions. This, combined with `SignedValidationPhase` and `Pages`
361		/// dictates how many signed solutions we can verify.
362		type MaxSubmissions: Get<u32>;
363
364		/// The ratio of the deposit to return in case a signed account submits a solution via
365		/// [`Pallet::register`], but later calls [`Pallet::bail`].
366		///
367		/// This should be large enough to cover for the deletion cost of possible all pages. To be
368		/// safe, you can put it to 100% to begin with to fully dis-incentivize bailing.
369		type BailoutGraceRatio: Get<Perbill>;
370
371		/// The ratio of the deposit to return in case a signed account is ejected from the queue.
372		///
373		/// This value is assumed to be 100% for accounts that are in the invulnerable list,
374		/// which can only be set by governance.
375		type EjectGraceRatio: Get<Perbill>;
376
377		/// Handler to estimate the fee of a call. Useful to refund the transaction fee of the
378		/// submitter for the winner.
379		type EstimateCallFee: EstimateCallFee<Call<Self>, BalanceOf<Self>>;
380
381		/// Handler for slashed deposits. Use `()` to burn them, or redirect them elsewhere.
382		type Slash: OnUnbalanced<FungibleCredit<Self::AccountId, Self::Currency>>;
383
384		/// Source account for reward payments. `Some(pot)` transfers from that account; `None`
385		/// mints directly into the winner's account.
386		type RewardSource: RewardSource<Self::AccountId, BalanceOf<Self>>;
387
388		/// Ceiling on the transaction fee that is refunded to a submitter.
389		///
390		/// Each call that stores part of a submission accrues its transaction fee. That total is
391		/// refunded to the winner on top of [`Config::RewardBase`], and to an invulnerable whose
392		/// submission is discarded. This ceiling keeps that refund bounded by config.
393		///
394		/// Should cover one [`Pallet::register`] plus [`crate::Config::Pages`]
395		/// [`Pallet::submit_page`] calls at the maximum encoded page size. A smaller value
396		/// under-refunds a submitter that stores all of their pages.
397		type MaxFeeRefund: Get<BalanceOf<Self>>;
398
399		/// Provided weights of this pallet.
400		type WeightInfo: WeightInfo;
401	}
402
403	/// The hold reason of this palelt.
404	#[pallet::composite_enum]
405	pub enum HoldReason {
406		/// Because of submitting a signed solution.
407		#[codec(index = 0)]
408		SignedSubmission,
409	}
410
411	/// Accounts whitelisted by governance to always submit their solutions.
412	///
413	/// They are different in that:
414	///
415	/// * They always pay a fixed deposit for submission, specified by
416	///   [`Config::InvulnerableDeposit`]. They pay no page deposit.
417	/// * If _ejected_ by better solution from [`SortedScores`], they will get their full deposit
418	///   back.
419	/// * They always get their tx-fee back even if they are _discarded_, up to
420	///   [`Config::MaxFeeRefund`].
421	#[pallet::storage]
422	pub type Invulnerables<T: Config> =
423		StorageValue<_, BoundedVec<T::AccountId, ConstU32<16>>, ValueQuery>;
424
425	/// Round-winner rewards that failed to pay out of [`Config::RewardSource`], pending a
426	/// permissionless claim via [`Pallet::claim_unpaid_reward`].
427	///
428	/// Expected to stay empty in normal operation; only grows when the pot is depleted. Bounded
429	/// to [`MAX_UNPAID_REWARDS`] entries, pushed in round order, so if full, the oldest one is
430	/// evicted (see [`Pallet::pay_reward`]).
431	#[pallet::storage]
432	pub type UnpaidRewards<T: Config> =
433		StorageValue<_, BoundedVec<UnpaidReward<T>, ConstU32<MAX_UNPAID_REWARDS>>, ValueQuery>;
434
435	/// Wrapper type for signed submissions.
436	///
437	/// It handles 3 storage items:
438	///
439	/// 1. [`SortedScores`]: A flat vector of all submissions' `(submitter_id, claimed_score)`.
440	/// 2. [`SubmissionStorage`]: Paginated map of of all submissions, keyed by submitter and page.
441	/// 3. [`SubmissionMetadataStorage`]: Map from submitter to the metadata of their submission.
442	///
443	/// All storage items in this group are mapped, and their first key is the `round` to which they
444	/// belong to. In essence, we are storing multiple versions of each group.
445	///
446	/// ### Invariants:
447	///
448	/// This storage group is sane, clean, and consistent if the following invariants are held:
449	///
450	/// Among the submissions of each round:
451	/// - `SortedScores` should never contain duplicate account ids.
452	/// - For any account id in `SortedScores`, a corresponding value should exist in
453	/// `SubmissionMetadataStorage` under that account id's key.
454	///       - And the value of `metadata.score` must be equal to the score stored in
455	///         `SortedScores`.
456	/// - And visa versa: for any key existing in `SubmissionMetadataStorage`, an item must exist in
457	///   `SortedScores`.
458	/// - For any first key existing in `SubmissionStorage`, a key must exist in
459	///   `SubmissionMetadataStorage`.
460	/// - For any first key in `SubmissionStorage`, the number of second keys existing should be the
461	///   same as the `true` count of `pages` in [`SubmissionMetadata`] (this already implies the
462	///   former, since it uses the metadata).
463	///
464	/// All mutating functions are only allowed to transition into states where all of the above
465	/// conditions are met.
466	///
467	/// No particular invariant exists between data that related to different rounds. They are
468	/// purely independent.
469	pub(crate) struct Submissions<T: Config>(core::marker::PhantomData<T>);
470
471	#[pallet::storage]
472	pub type SortedScores<T: Config> = StorageMap<
473		_,
474		Twox64Concat,
475		u32,
476		BoundedVec<(T::AccountId, ElectionScore), T::MaxSubmissions>,
477		ValueQuery,
478	>;
479
480	/// Triple map from (round, account, page) to a solution page.
481	#[pallet::storage]
482	type SubmissionStorage<T: Config> = StorageNMap<
483		_,
484		(
485			NMapKey<Twox64Concat, u32>,
486			NMapKey<Twox64Concat, T::AccountId>,
487			NMapKey<Twox64Concat, PageIndex>,
488		),
489		SolutionOf<T::MinerConfig>,
490		OptionQuery,
491	>;
492
493	/// Map from account to the metadata of their submission.
494	///
495	/// invariant: for any Key1 of type `AccountId` in [`Submissions`], this storage map also has a
496	/// value.
497	#[pallet::storage]
498	pub(super) type SubmissionMetadataStorage<T: Config> =
499		StorageDoubleMap<_, Twox64Concat, u32, Twox64Concat, T::AccountId, SubmissionMetadata<T>>;
500
501	impl<T: Config> Submissions<T> {
502		// -- mutating functions
503
504		/// Generic checked mutation helper.
505		///
506		/// All mutating functions must be fulled through this bad boy. The round at which the
507		/// mutation happens must be provided
508		fn mutate_checked<R, F: FnOnce() -> R>(_round: u32, mutate: F) -> R {
509			let result = mutate();
510
511			#[cfg(debug_assertions)]
512			{
513				assert!(Self::sanity_check_round(_round).is_ok());
514				assert!(Self::sanity_check_round(_round + 1).is_ok());
515				assert!(Self::sanity_check_round(_round.saturating_sub(1)).is_ok());
516			}
517
518			result
519		}
520
521		/// *Fully* **TAKE** (i.e. get and remove) the leader from storage, with all of its
522		/// associated data.
523		///
524		/// This removes all associated data of the leader from storage, discarding the submission
525		/// data and score, returning the rest.
526		pub(crate) fn take_leader_with_data(
527			round: u32,
528		) -> Option<(T::AccountId, SubmissionMetadata<T>)> {
529			Self::mutate_checked(round, || {
530				SortedScores::<T>::mutate(round, |sorted| sorted.pop()).and_then(
531					|(submitter, _score)| {
532						// NOTE: safe to remove unbounded, as at most `Pages` pages are stored.
533						let r: MultiRemovalResults = SubmissionStorage::<T>::clear_prefix(
534							(round, &submitter),
535							u32::MAX,
536							None,
537						);
538						debug_assert!(r.unique <= T::Pages::get());
539
540						SubmissionMetadataStorage::<T>::take(round, &submitter)
541							.map(|metadata| (submitter, metadata))
542					},
543				)
544			})
545		}
546
547		/// *Fully* **TAKE** (i.e. get and remove) a submission from storage, with all of its
548		/// associated data.
549		///
550		/// This removes all associated data of the submitter from storage, discarding the
551		/// submission data and score, returning the metadata.
552		pub(crate) fn take_submission_with_data(
553			round: u32,
554			who: &T::AccountId,
555		) -> Option<SubmissionMetadata<T>> {
556			Self::mutate_checked(round, || {
557				let mut sorted_scores = SortedScores::<T>::get(round);
558				if let Some(index) = sorted_scores.iter().position(|(x, _)| x == who) {
559					sorted_scores.remove(index);
560				}
561				if sorted_scores.is_empty() {
562					SortedScores::<T>::remove(round);
563				} else {
564					SortedScores::<T>::insert(round, sorted_scores);
565				}
566
567				// Note: safe to remove unbounded, as at most `Pages` pages are stored.
568				let r = SubmissionStorage::<T>::clear_prefix((round, who), u32::MAX, None);
569				debug_assert!(r.unique <= T::Pages::get());
570
571				SubmissionMetadataStorage::<T>::take(round, who)
572			})
573		}
574
575		/// Try and register a new solution.
576		///
577		/// Registration can only happen for the current round.
578		///
579		/// registration might fail if the queue is already full, and the solution is not good
580		/// enough to eject the weakest.
581		fn try_register(
582			round: u32,
583			who: &T::AccountId,
584			metadata: SubmissionMetadata<T>,
585		) -> Result<bool, DispatchError> {
586			Self::mutate_checked(round, || Self::try_register_inner(round, who, metadata))
587		}
588
589		fn try_register_inner(
590			round: u32,
591			who: &T::AccountId,
592			metadata: SubmissionMetadata<T>,
593		) -> Result<bool, DispatchError> {
594			let mut sorted_scores = SortedScores::<T>::get(round);
595
596			let did_eject = if let Some(_) = sorted_scores.iter().position(|(x, _)| x == who) {
597				return Err(Error::<T>::Duplicate.into());
598			} else {
599				// must be new.
600				debug_assert!(!SubmissionMetadataStorage::<T>::contains_key(round, who));
601
602				let insert_idx = match sorted_scores
603					.binary_search_by_key(&metadata.claimed_score, |(_, y)| *y)
604				{
605					// an equal score exists, unlikely, but could very well happen. We just put them
606					// next to each other.
607					Ok(pos) => pos,
608					// new score, should be inserted in this pos.
609					Err(pos) => pos,
610				};
611
612				let mut record = (who.clone(), metadata.claimed_score);
613				if sorted_scores.is_full() {
614					let remove_idx = sorted_scores
615						.iter()
616						.position(|(x, _)| !Pallet::<T>::is_invulnerable(x))
617						.ok_or(Error::<T>::QueueFull)?;
618					if insert_idx > remove_idx {
619						// we have a better solution
620						core::mem::swap(&mut sorted_scores[remove_idx], &mut record);
621						// slicing safety note:
622						// - `insert_idx` is at most `sorted_scores.len()`, obtained from
623						//   `binary_search_by_key`, valid for the upper bound of slicing.
624						// - `remove_idx` is a valid index, less then `insert_idx`, obtained from
625						//   `.iter().position()`
626						sorted_scores[remove_idx..insert_idx].rotate_left(1);
627
628						let discarded = record.0;
629						let maybe_metadata =
630							SubmissionMetadataStorage::<T>::take(round, &discarded).defensive();
631						// Note: safe to remove unbounded, as at most `Pages` pages are stored.
632						let _r = SubmissionStorage::<T>::clear_prefix(
633							(round, &discarded),
634							u32::MAX,
635							None,
636						);
637						debug_assert!(_r.unique <= T::Pages::get());
638
639						if let Some(metadata) = maybe_metadata {
640							Pallet::<T>::settle_deposit(
641								round,
642								&discarded,
643								metadata.deposit,
644								T::EjectGraceRatio::get(),
645							);
646						}
647
648						Pallet::<T>::deposit_event(Event::<T>::Ejected(round, discarded));
649						true
650					} else {
651						// we don't have a better solution
652						return Err(Error::<T>::QueueFull.into());
653					}
654				} else {
655					sorted_scores
656						.try_insert(insert_idx, record)
657						.expect("length checked above; qed");
658					false
659				}
660			};
661
662			SortedScores::<T>::insert(round, sorted_scores);
663			SubmissionMetadataStorage::<T>::insert(round, who, metadata);
664			Ok(did_eject)
665		}
666
667		/// Submit a page of `solution` to the `page` index of `who`'s submission.
668		///
669		/// Updates the deposit in the metadata accordingly.
670		///
671		/// - If `maybe_solution` is `None`, then the given page is deleted.
672		/// - `who` must have already registered their submission.
673		/// - If the page is duplicate, it will replaced.
674		pub(crate) fn try_mutate_page(
675			round: u32,
676			who: &T::AccountId,
677			page: PageIndex,
678			maybe_solution: Option<Box<SolutionOf<T::MinerConfig>>>,
679		) -> DispatchResultWithPostInfo {
680			Self::mutate_checked(round, || {
681				Self::try_mutate_page_inner(round, who, page, maybe_solution)
682			})
683		}
684
685		/// Get the deposit of a registration with the given number of pages.
686		fn deposit_for(who: &T::AccountId, pages: usize) -> BalanceOf<T> {
687			Self::base_deposit_for(who).saturating_add(Self::page_deposit_for(who, pages))
688		}
689
690		/// Get the base deposit of a registration made now.
691		fn base_deposit_for(who: &T::AccountId) -> BalanceOf<T> {
692			if Pallet::<T>::is_invulnerable(who) {
693				T::InvulnerableDeposit::get()
694			} else {
695				let queue_size = Self::submitters_count(Pallet::<T>::current_round());
696				T::DepositBase::calculate_base_deposit(queue_size)
697			}
698		}
699
700		/// Get the per-page deposit for the given number of pages. Invulnerables have none.
701		fn page_deposit_for(who: &T::AccountId, pages: usize) -> BalanceOf<T> {
702			if Pallet::<T>::is_invulnerable(who) {
703				Zero::zero()
704			} else {
705				T::DepositPerPage::calculate_page_deposit(pages)
706			}
707		}
708
709		fn try_mutate_page_inner(
710			round: u32,
711			who: &T::AccountId,
712			page: PageIndex,
713			maybe_solution: Option<Box<SolutionOf<T::MinerConfig>>>,
714		) -> DispatchResultWithPostInfo {
715			let mut metadata =
716				SubmissionMetadataStorage::<T>::get(round, who).ok_or(Error::<T>::NotRegistered)?;
717			ensure!(page < T::Pages::get(), Error::<T>::BadPageIndex);
718
719			let was_set = metadata.pages.get(page as usize).copied().unwrap_or_default();
720
721			// defensive only: we resize `meta.pages` once to be `T::Pages` elements once, and never
722			// resize it again; `page` is checked here to be in bound; element must exist; qed.
723			if let Some(page_bit) = metadata.pages.get_mut(page as usize).defensive() {
724				*page_bit = maybe_solution.is_some();
725			}
726
727			// update deposit: the base charged at registration plus the per-page deposit of the
728			// stored pages. Invulnerables have no per-page part.
729			let new_pages = metadata.pages.iter().filter(|x| **x).count();
730			let new_deposit = metadata.base.saturating_add(Self::page_deposit_for(who, new_pages));
731			let old_deposit = metadata.deposit;
732			if new_deposit > old_deposit {
733				let to_reserve = new_deposit - old_deposit;
734				T::Currency::hold(&HoldReason::SignedSubmission.into(), who, to_reserve)?;
735			} else {
736				let to_unreserve = old_deposit - new_deposit;
737				let _res = T::Currency::release(
738					&HoldReason::SignedSubmission.into(),
739					who,
740					to_unreserve,
741					Precision::BestEffort,
742				);
743				debug_assert_eq!(_res, Ok(to_unreserve));
744			};
745			metadata.deposit = new_deposit;
746
747			// If a page is being added, we record the fee as well. For removals, we ignore the fee
748			// as it is negligible, and we don't want to encourage anyone to submit and remove
749			// anyways. For pages that are already stored, we ignore it too: the refund covers the
750			// cost of storing a submission once. Note that fee is only refunded for the winner
751			// anyways.
752			if maybe_solution.is_some() && !was_set {
753				let fee = T::EstimateCallFee::estimate_call_fee(
754					&Call::submit_page { page, maybe_solution: maybe_solution.clone() },
755					None.into(),
756				);
757				metadata.fee.saturating_accrue(fee);
758			}
759
760			SubmissionStorage::<T>::mutate_exists((round, who, page), |maybe_old_solution| {
761				*maybe_old_solution = maybe_solution.map(|s| *s)
762			});
763			SubmissionMetadataStorage::<T>::insert(round, who, metadata);
764			Ok(().into())
765		}
766
767		// -- getter functions
768		pub(crate) fn has_leader(round: u32) -> bool {
769			!SortedScores::<T>::get(round).is_empty()
770		}
771
772		pub(crate) fn leader(round: u32) -> Option<(T::AccountId, ElectionScore)> {
773			SortedScores::<T>::get(round).last().cloned()
774		}
775
776		pub(crate) fn submitters_count(round: u32) -> usize {
777			SortedScores::<T>::get(round).len()
778		}
779
780		pub(crate) fn get_page_of(
781			round: u32,
782			who: &T::AccountId,
783			page: PageIndex,
784		) -> Option<SolutionOf<T::MinerConfig>> {
785			SubmissionStorage::<T>::get((round, who, &page))
786		}
787	}
788
789	#[allow(unused)]
790	#[cfg(any(feature = "try-runtime", test, feature = "runtime-benchmarks", debug_assertions))]
791	impl<T: Config> Submissions<T> {
792		pub(crate) fn sorted_submitters(round: u32) -> BoundedVec<T::AccountId, T::MaxSubmissions> {
793			use frame_support::traits::TryCollect;
794			SortedScores::<T>::get(round).into_iter().map(|(x, _)| x).try_collect().unwrap()
795		}
796
797		pub fn submissions_iter(
798			round: u32,
799		) -> impl Iterator<Item = (T::AccountId, PageIndex, SolutionOf<T::MinerConfig>)> {
800			SubmissionStorage::<T>::iter_prefix((round,)).map(|((x, y), z)| (x, y, z))
801		}
802
803		pub fn metadata_iter(
804			round: u32,
805		) -> impl Iterator<Item = (T::AccountId, SubmissionMetadata<T>)> {
806			SubmissionMetadataStorage::<T>::iter_prefix(round)
807		}
808
809		pub fn metadata_of(round: u32, who: T::AccountId) -> Option<SubmissionMetadata<T>> {
810			SubmissionMetadataStorage::<T>::get(round, who)
811		}
812
813		pub fn pages_of(
814			round: u32,
815			who: T::AccountId,
816		) -> impl Iterator<Item = (PageIndex, SolutionOf<T::MinerConfig>)> {
817			SubmissionStorage::<T>::iter_prefix((round, who))
818		}
819
820		pub fn leaderboard(
821			round: u32,
822		) -> BoundedVec<(T::AccountId, ElectionScore), T::MaxSubmissions> {
823			SortedScores::<T>::get(round)
824		}
825
826		/// Ensure that all the storage items associated with the given round are in `killed` state,
827		/// meaning that in the expect state after an election is OVER.
828		pub(crate) fn ensure_killed(round: u32) -> DispatchResult {
829			ensure!(Self::metadata_iter(round).count() == 0, "metadata_iter not cleared.");
830			ensure!(Self::submissions_iter(round).count() == 0, "submissions_iter not cleared.");
831			ensure!(Self::sorted_submitters(round).len() == 0, "sorted_submitters not cleared.");
832
833			Ok(())
834		}
835
836		/// Ensure that no data associated with `who` exists for `round`.
837		pub(crate) fn ensure_killed_with(who: &T::AccountId, round: u32) -> DispatchResult {
838			ensure!(
839				SubmissionMetadataStorage::<T>::get(round, who).is_none(),
840				"metadata not cleared."
841			);
842			ensure!(
843				SubmissionStorage::<T>::iter_prefix((round, who)).count() == 0,
844				"submissions not cleared."
845			);
846			ensure!(
847				SortedScores::<T>::get(round).iter().all(|(x, _)| x != who),
848				"sorted_submitters not cleared."
849			);
850
851			Ok(())
852		}
853
854		/// Perform all the sanity checks of this storage item group at the given round.
855		pub(crate) fn sanity_check_round(round: u32) -> DispatchResult {
856			use alloc::collections::btree_set::BTreeSet;
857			let sorted_scores = SortedScores::<T>::get(round);
858			assert_eq!(
859				sorted_scores.clone().into_iter().map(|(x, _)| x).collect::<BTreeSet<_>>().len(),
860				sorted_scores.len()
861			);
862
863			let _ = SubmissionMetadataStorage::<T>::iter_prefix(round)
864				.map(|(submitter, meta)| {
865					let mut matches = SortedScores::<T>::get(round)
866						.into_iter()
867						.filter(|(who, _score)| who == &submitter)
868						.collect::<Vec<_>>();
869
870					ensure!(
871						matches.len() == 1,
872						"item existing in metadata but missing in sorted list.",
873					);
874
875					let (_, score) = matches.pop().expect("checked; qed");
876					ensure!(score == meta.claimed_score, "score mismatch");
877					ensure!(meta.deposit >= meta.base, "deposit below the registration base");
878					Ok(())
879				})
880				.collect::<Result<Vec<_>, &'static str>>()?;
881
882			ensure!(
883				SubmissionStorage::<T>::iter_key_prefix((round,)).map(|(k1, _k2)| k1).all(
884					|submitter| SubmissionMetadataStorage::<T>::contains_key(round, submitter)
885				),
886				"missing metadata of submitter"
887			);
888
889			for submitter in SubmissionStorage::<T>::iter_key_prefix((round,)).map(|(k1, _k2)| k1) {
890				let pages_count =
891					SubmissionStorage::<T>::iter_key_prefix((round, &submitter)).count();
892				let metadata = SubmissionMetadataStorage::<T>::get(round, submitter)
893					.expect("metadata checked to exist for all keys; qed");
894				let assumed_pages_count = metadata.pages.iter().filter(|x| **x).count();
895				ensure!(pages_count == assumed_pages_count, "wrong page count");
896			}
897
898			Ok(())
899		}
900	}
901
902	/// The in-code storage version.
903	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
904
905	#[pallet::pallet]
906	#[pallet::storage_version(STORAGE_VERSION)]
907	pub struct Pallet<T>(PhantomData<T>);
908
909	#[pallet::event]
910	#[pallet::generate_deposit(pub(super) fn deposit_event)]
911	pub enum Event<T: Config> {
912		/// Upcoming submission has been registered for the given account, with the given score.
913		Registered(u32, T::AccountId, ElectionScore),
914		/// A page of solution solution with the given index has been stored for the given account.
915		Stored(u32, T::AccountId, PageIndex),
916		/// The given account has been rewarded with the given amount.
917		Rewarded(u32, T::AccountId, BalanceOf<T>),
918		/// A reward payout failed and has been queued in [`UnpaidRewards`]; claimable via
919		/// [`Pallet::claim_unpaid_reward`] once the pot is refilled.
920		RewardPaymentDeferred(u32, T::AccountId, BalanceOf<T>),
921		/// [`UnpaidRewards`] was full, so this (the oldest) entry was evicted to make room for a
922		/// new deferral; no funds moved, the reward is now unrecoverable.
923		UnpaidRewardEvicted(u32, T::AccountId, BalanceOf<T>),
924		/// An invulnerable's transaction fee refund failed; no funds moved, no recovery.
925		FeeRefundFailed(u32, T::AccountId, BalanceOf<T>),
926		/// The given account has been slashed with the given amount.
927		Slashed(u32, T::AccountId, BalanceOf<T>),
928		/// The given solution, for the given round, was ejected.
929		Ejected(u32, T::AccountId),
930		/// The given account has been discarded.
931		Discarded(u32, T::AccountId),
932		/// The given account has bailed.
933		Bailed(u32, T::AccountId),
934	}
935
936	#[pallet::error]
937	pub enum Error<T> {
938		/// The phase is not signed.
939		PhaseNotSigned,
940		/// The submission is a duplicate.
941		Duplicate,
942		/// The queue is full.
943		QueueFull,
944		/// The page index is out of bounds.
945		BadPageIndex,
946		/// The account is not registered.
947		NotRegistered,
948		/// No submission found.
949		NoSubmission,
950		/// Round is not yet over.
951		RoundNotOver,
952		/// Bad witness data provided.
953		BadWitnessData,
954		/// Too many invulnerable accounts are provided,
955		TooManyInvulnerables,
956		/// No [`UnpaidRewards`] entry exists for the caller in the given round.
957		NoUnpaidReward,
958		/// The [`Config::RewardSource`] pot is still insufficient to pay the unpaid reward.
959		PotStillDepleted,
960	}
961
962	#[pallet::call]
963	impl<T: Config> Pallet<T> {
964		/// Register oneself for an upcoming signed election.
965		#[pallet::weight(SignedWeightsOf::<T>::register_eject())]
966		#[pallet::call_index(0)]
967		pub fn register(
968			origin: OriginFor<T>,
969			claimed_score: ElectionScore,
970		) -> DispatchResultWithPostInfo {
971			let who = ensure_signed(origin)?;
972			ensure!(crate::Pallet::<T>::current_phase().is_signed(), Error::<T>::PhaseNotSigned);
973
974			// note: we could already check if this is a duplicate here, but prefer keeping the code
975			// simple for now.
976
977			let deposit = Submissions::<T>::base_deposit_for(&who);
978			let reward = T::RewardBase::get();
979			let fee = T::EstimateCallFee::estimate_call_fee(
980				&Call::register { claimed_score },
981				None.into(),
982			);
983			let mut pages = BoundedVec::<_, _>::with_bounded_capacity(T::Pages::get() as usize);
984			pages.bounded_resize(T::Pages::get() as usize, false);
985
986			let new_metadata =
987				SubmissionMetadata { claimed_score, deposit, base: deposit, reward, fee, pages };
988
989			T::Currency::hold(&HoldReason::SignedSubmission.into(), &who, deposit)?;
990			let round = Self::current_round();
991			let discarded = Submissions::<T>::try_register(round, &who, new_metadata)?;
992			Self::deposit_event(Event::<T>::Registered(round, who, claimed_score));
993
994			// maybe refund.
995			if discarded {
996				Ok(().into())
997			} else {
998				Ok(Some(SignedWeightsOf::<T>::register_not_full()).into())
999			}
1000		}
1001
1002		/// Submit a single page of a solution.
1003		///
1004		/// Must always come after [`Pallet::register`].
1005		///
1006		/// `maybe_solution` can be set to `None` to erase the page.
1007		///
1008		/// The held deposit becomes the base deposit charged at [`Pallet::register`] plus the
1009		/// [`Config::DepositPerPage`] deposit of the stored pages. Invulnerables have no per-page
1010		/// part.
1011		#[pallet::weight(SignedWeightsOf::<T>::submit_page())]
1012		#[pallet::call_index(1)]
1013		pub fn submit_page(
1014			origin: OriginFor<T>,
1015			page: PageIndex,
1016			maybe_solution: Option<Box<SolutionOf<T::MinerConfig>>>,
1017		) -> DispatchResultWithPostInfo {
1018			let who = ensure_signed(origin)?;
1019			ensure!(crate::Pallet::<T>::current_phase().is_signed(), Error::<T>::PhaseNotSigned);
1020			let is_set = maybe_solution.is_some();
1021
1022			let round = Self::current_round();
1023			Submissions::<T>::try_mutate_page(round, &who, page, maybe_solution)?;
1024			Self::deposit_event(Event::<T>::Stored(round, who, page));
1025
1026			// maybe refund.
1027			if is_set {
1028				Ok(().into())
1029			} else {
1030				Ok(Some(SignedWeightsOf::<T>::unset_page()).into())
1031			}
1032		}
1033
1034		/// Retract a submission.
1035		///
1036		/// A portion of the deposit may be returned, based on the [`Config::EjectGraceRatio`].
1037		///
1038		/// This will fully remove the solution from storage.
1039		#[pallet::weight(SignedWeightsOf::<T>::bail())]
1040		#[pallet::call_index(2)]
1041		pub fn bail(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
1042			let who = ensure_signed(origin)?;
1043			ensure!(crate::Pallet::<T>::current_phase().is_signed(), Error::<T>::PhaseNotSigned);
1044			let round = Self::current_round();
1045			let metadata = Submissions::<T>::take_submission_with_data(round, &who)
1046				.ok_or(Error::<T>::NoSubmission)?;
1047
1048			let deposit = metadata.deposit;
1049			Self::settle_deposit(round, &who, deposit, T::BailoutGraceRatio::get());
1050			Self::deposit_event(Event::<T>::Bailed(round, who));
1051
1052			Ok(None.into())
1053		}
1054
1055		/// Clear the data of a submitter form an old round.
1056		///
1057		/// The dispatch origin of this call must be signed, and the original submitter.
1058		///
1059		/// This can only be called for submissions that end up being discarded, as in they are not
1060		/// processed and they end up lingering in the queue.
1061		#[pallet::call_index(3)]
1062		#[pallet::weight(SignedWeightsOf::<T>::clear_old_round_data(*witness_pages))]
1063		pub fn clear_old_round_data(
1064			origin: OriginFor<T>,
1065			round: u32,
1066			witness_pages: u32,
1067		) -> DispatchResultWithPostInfo {
1068			let discarded = ensure_signed(origin)?;
1069
1070			let current_round = Self::current_round();
1071			// we can only operate on old rounds.
1072			ensure!(round < current_round, Error::<T>::RoundNotOver);
1073
1074			let metadata = Submissions::<T>::take_submission_with_data(round, &discarded)
1075				.ok_or(Error::<T>::NoSubmission)?;
1076			ensure!(
1077				metadata.pages.iter().filter(|p| **p).count() as u32 <= witness_pages,
1078				Error::<T>::BadWitnessData
1079			);
1080
1081			// give back their deposit.
1082			let _res = T::Currency::release(
1083				&HoldReason::SignedSubmission.into(),
1084				&discarded,
1085				metadata.deposit,
1086				Precision::BestEffort,
1087			);
1088			debug_assert_eq!(_res, Ok(metadata.deposit));
1089
1090			// maybe give back their fees
1091			if Self::is_invulnerable(&discarded) {
1092				Self::refund_fee(round, &discarded, metadata.fee.min(T::MaxFeeRefund::get()));
1093			}
1094
1095			Self::deposit_event(Event::<T>::Discarded(round, discarded));
1096
1097			// IFF all good, this is free of charge.
1098			Ok(None.into())
1099		}
1100
1101		/// Set the invulnerable list.
1102		///
1103		/// Dispatch origin must the the same as [`crate::Config::AdminOrigin`].
1104		#[pallet::call_index(4)]
1105		#[pallet::weight(T::DbWeight::get().writes(1))]
1106		pub fn set_invulnerables(origin: OriginFor<T>, inv: Vec<T::AccountId>) -> DispatchResult {
1107			<T as crate::Config>::AdminOrigin::ensure_origin(origin)?;
1108			let bounded: BoundedVec<_, ConstU32<16>> =
1109				inv.try_into().map_err(|_| Error::<T>::TooManyInvulnerables)?;
1110			Invulnerables::<T>::set(bounded);
1111			Ok(())
1112		}
1113
1114		/// Pay out a round's [`UnpaidRewards`] entry to its winner. Permissionless: anyone may
1115		/// call it for any round. Free on success, normal fee on failure to discourage spam.
1116		#[pallet::call_index(5)]
1117		#[pallet::weight(SignedWeightsOf::<T>::claim_unpaid_reward())]
1118		pub fn claim_unpaid_reward(origin: OriginFor<T>, round: u32) -> DispatchResultWithPostInfo {
1119			let _ = ensure_signed(origin)?;
1120			let mut unpaid = UnpaidRewards::<T>::get();
1121			let idx = unpaid
1122				.iter()
1123				.position(|entry| entry.round == round)
1124				.ok_or(Error::<T>::NoUnpaidReward)?;
1125			let entry = unpaid[idx].clone();
1126
1127			Self::transfer_or_mint(&entry.who, entry.amount)
1128				.map_err(|_| Error::<T>::PotStillDepleted)?;
1129
1130			unpaid.remove(idx);
1131			UnpaidRewards::<T>::put(unpaid);
1132			Self::deposit_event(Event::<T>::Rewarded(entry.round, entry.who, entry.amount));
1133
1134			Ok(Pays::No.into())
1135		}
1136	}
1137
1138	#[pallet::view_functions]
1139	impl<T: Config> Pallet<T> {
1140		/// Get the deposit `who` would hold if it registered now and then submitted `pages` pages.
1141		///
1142		/// The base part is priced from the number of submitters currently registered, so the
1143		/// result only matches what `who` would pay if it has not registered in this round yet. A
1144		/// submitter that already registered holds the base charged at its registration, plus the
1145		/// per-page deposit of the pages it has stored.
1146		///
1147		/// It also takes into account whether `who` is in [`Invulnerables`].
1148		pub fn deposit_for(who: T::AccountId, pages: u32) -> BalanceOf<T> {
1149			Submissions::<T>::deposit_for(&who, pages as usize)
1150		}
1151	}
1152
1153	#[pallet::hooks]
1154	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
1155		#[cfg(feature = "try-runtime")]
1156		fn try_state(n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
1157			Self::do_try_state(n)
1158		}
1159	}
1160}
1161
1162impl<T: Config> Pallet<T> {
1163	#[cfg(any(feature = "try-runtime", test, feature = "runtime-benchmarks"))]
1164	pub(crate) fn do_try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
1165		Submissions::<T>::sanity_check_round(Self::current_round())
1166	}
1167
1168	fn current_round() -> u32 {
1169		crate::Pallet::<T>::round()
1170	}
1171
1172	fn is_invulnerable(who: &T::AccountId) -> bool {
1173		Invulnerables::<T>::get().contains(who)
1174	}
1175
1176	/// Transfer `amount` from [`Config::RewardSource`] pot to `to`, or mint if `None`.
1177	fn transfer_or_mint(to: &T::AccountId, amount: BalanceOf<T>) -> Result<(), ()> {
1178		if let Some(source) = T::RewardSource::account() {
1179			T::Currency::transfer(&source, to, amount, Preservation::Preserve).map_err(|_| ())?;
1180			T::RewardSource::paid(amount);
1181		} else {
1182			let _r = T::Currency::mint_into(to, amount);
1183			debug_assert!(_r.is_ok());
1184		}
1185		Ok(())
1186	}
1187
1188	/// Pay the round's winner. On success emits `Rewarded`. On failure, always defers into
1189	/// [`UnpaidRewards`] (`RewardPaymentDeferred`), evicting the oldest entry first
1190	/// (`UnpaidRewardEvicted`) if it's already full.
1191	fn pay_reward(round: u32, to: &T::AccountId, amount: BalanceOf<T>) {
1192		if Self::transfer_or_mint(to, amount).is_ok() {
1193			Self::deposit_event(Event::<T>::Rewarded(round, to.clone(), amount));
1194			return;
1195		}
1196
1197		sublog!(
1198			warn,
1199			"signed",
1200			"reward pot insufficient; deferring {:?} to {:?} for round {}",
1201			amount,
1202			to,
1203			round
1204		);
1205		let entry = UnpaidReward { round, who: to.clone(), amount };
1206		UnpaidRewards::<T>::mutate(|unpaid| {
1207			if unpaid.is_full() {
1208				// Entries are pushed in round order, so index 0 is the oldest.
1209				let evicted = unpaid.remove(0);
1210				Self::deposit_event(Event::<T>::UnpaidRewardEvicted(
1211					evicted.round,
1212					evicted.who,
1213					evicted.amount,
1214				));
1215			}
1216			let _ = unpaid.try_push(entry).defensive_proof("an element was just evicted; qed");
1217		});
1218		Self::deposit_event(Event::<T>::RewardPaymentDeferred(round, to.clone(), amount));
1219	}
1220
1221	/// Refund an invulnerable's tx fee on discard. Unlike `pay_reward`, a failure is not
1222	/// deferred: it is out of scope for [`UnpaidRewards`] (see its doc for why) and simply emits
1223	/// `FeeRefundFailed`, never `Rewarded`.
1224	fn refund_fee(round: u32, to: &T::AccountId, amount: BalanceOf<T>) {
1225		if Self::transfer_or_mint(to, amount).is_err() {
1226			sublog!(
1227				warn,
1228				"signed",
1229				"reward pot insufficient; fee refund of {:?} to {:?} not paid",
1230				amount,
1231				to
1232			);
1233			Self::deposit_event(Event::<T>::FeeRefundFailed(round, to.clone(), amount));
1234		}
1235	}
1236
1237	fn settle_deposit(round: u32, who: &T::AccountId, deposit: BalanceOf<T>, grace: Perbill) {
1238		let to_refund = grace * deposit;
1239		let to_slash = deposit.defensive_saturating_sub(to_refund);
1240
1241		let _res = T::Currency::release(
1242			&HoldReason::SignedSubmission.into(),
1243			who,
1244			to_refund,
1245			Precision::BestEffort,
1246		)
1247		.defensive();
1248		debug_assert_eq!(_res, Ok(to_refund));
1249
1250		let (credit, remainder) =
1251			T::Currency::slash(&HoldReason::SignedSubmission.into(), who, to_slash);
1252		debug_assert!(remainder.is_zero(), "the full deposit was held; slash must not be partial");
1253		let slashed = credit.peek();
1254		T::Slash::on_unbalanced(credit);
1255		if !slashed.is_zero() {
1256			Self::deposit_event(Event::<T>::Slashed(round, who.clone(), slashed));
1257		}
1258	}
1259
1260	/// Common logic for handling solution rejection - slash the submitter and try next solution
1261	fn handle_solution_rejection(current_round: u32) {
1262		if let Some((loser, metadata)) =
1263			Submissions::<T>::take_leader_with_data(current_round).defensive()
1264		{
1265			// Slash the deposit.
1266			// Note that an invulnerable is not expelled from the list despite the slashing.
1267			// Removal should occur only through governance, not automatically. An operational or
1268			// network issue that leads to an incomplete submission is much more likely than a bad
1269			// faith action from an invulnerable.
1270			let slash = metadata.deposit;
1271			let (credit, remainder) =
1272				T::Currency::slash(&HoldReason::SignedSubmission.into(), &loser, slash);
1273			debug_assert!(
1274				remainder.is_zero(),
1275				"the full deposit was held; slash must not be partial"
1276			);
1277			let slashed = credit.peek();
1278			T::Slash::on_unbalanced(credit);
1279			if !slashed.is_zero() {
1280				Self::deposit_event(Event::<T>::Slashed(current_round, loser.clone(), slashed));
1281			}
1282
1283			// Try to start verification again if we still have submissions
1284			if let crate::types::Phase::SignedValidation(remaining_blocks) =
1285				crate::Pallet::<T>::current_phase()
1286			{
1287				// Only start verification if there are sufficient blocks remaining
1288				// Note: SignedValidation(N) means N+1 blocks remaining in the phase
1289				if remaining_blocks >= T::Pages::get().into() {
1290					if Submissions::<T>::has_leader(current_round) {
1291						// defensive: verifier just reported back a result, it must be in clear
1292						// state.
1293						let _ = <T::Verifier as AsynchronousVerifier>::start().defensive();
1294					}
1295				} else {
1296					sublog!(
1297						warn,
1298						"signed",
1299						"SignedValidation phase has {:?} blocks remaining, which are insufficient for {} pages",
1300						remaining_blocks,
1301						T::Pages::get()
1302					);
1303				}
1304			}
1305		} else {
1306			// No leader to slash; nothing to do.
1307			sublog!(
1308				warn,
1309				"signed",
1310				"Tried to slash but no leader was present for round {}",
1311				current_round
1312			);
1313		}
1314	}
1315}