1use 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
89pub use crate::weights::traits::pallet_election_provider_multi_block_signed::*;
91pub 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#[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 deposit: BalanceOf<T>,
114 fee: BalanceOf<T>,
116 reward: BalanceOf<T>,
118 claimed_score: ElectionScore,
120 pages: BoundedVec<bool, T::Pages>,
122 base: BalanceOf<T>,
124}
125
126pub const MAX_UNPAID_REWARDS: u32 = 16;
131
132#[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 round: u32,
141 who: T::AccountId,
143 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 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 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 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 if let Some((winner, metadata)) =
205 Submissions::<T>::take_leader_with_data(Self::current_round()).defensive()
206 {
207 let reward =
209 metadata.reward.saturating_add(metadata.fee.min(T::MaxFeeRefund::get()));
210 Self::pay_reward(current_round, &winner, reward);
211
212 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
229pub 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
243pub 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
258pub trait RewardSource<AccountId, Balance> {
263 fn account() -> Option<AccountId>;
265
266 fn paid(amount: Balance);
268}
269
270pub 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
286pub 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
307pub 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 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 ®ister_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 type Currency: Inspect<Self::AccountId>
344 + Mutate<Self::AccountId>
345 + MutateHold<Self::AccountId, Reason: From<HoldReason>>
346 + BalancedHold<Self::AccountId>;
347
348 type DepositBase: CalculateBaseDeposit<BalanceOf<Self>>;
350
351 type DepositPerPage: CalculatePageDeposit<BalanceOf<Self>>;
353
354 type InvulnerableDeposit: Get<BalanceOf<Self>>;
356
357 type RewardBase: Get<BalanceOf<Self>>;
359
360 type MaxSubmissions: Get<u32>;
363
364 type BailoutGraceRatio: Get<Perbill>;
370
371 type EjectGraceRatio: Get<Perbill>;
376
377 type EstimateCallFee: EstimateCallFee<Call<Self>, BalanceOf<Self>>;
380
381 type Slash: OnUnbalanced<FungibleCredit<Self::AccountId, Self::Currency>>;
383
384 type RewardSource: RewardSource<Self::AccountId, BalanceOf<Self>>;
387
388 type MaxFeeRefund: Get<BalanceOf<Self>>;
398
399 type WeightInfo: WeightInfo;
401 }
402
403 #[pallet::composite_enum]
405 pub enum HoldReason {
406 #[codec(index = 0)]
408 SignedSubmission,
409 }
410
411 #[pallet::storage]
422 pub type Invulnerables<T: Config> =
423 StorageValue<_, BoundedVec<T::AccountId, ConstU32<16>>, ValueQuery>;
424
425 #[pallet::storage]
432 pub type UnpaidRewards<T: Config> =
433 StorageValue<_, BoundedVec<UnpaidReward<T>, ConstU32<MAX_UNPAID_REWARDS>>, ValueQuery>;
434
435 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 #[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 #[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 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 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 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 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 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 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 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 Ok(pos) => pos,
608 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 core::mem::swap(&mut sorted_scores[remove_idx], &mut record);
621 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 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 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 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 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 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 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 if let Some(page_bit) = metadata.pages.get_mut(page as usize).defensive() {
724 *page_bit = maybe_solution.is_some();
725 }
726
727 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 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 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 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 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 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 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 Registered(u32, T::AccountId, ElectionScore),
914 Stored(u32, T::AccountId, PageIndex),
916 Rewarded(u32, T::AccountId, BalanceOf<T>),
918 RewardPaymentDeferred(u32, T::AccountId, BalanceOf<T>),
921 UnpaidRewardEvicted(u32, T::AccountId, BalanceOf<T>),
924 FeeRefundFailed(u32, T::AccountId, BalanceOf<T>),
926 Slashed(u32, T::AccountId, BalanceOf<T>),
928 Ejected(u32, T::AccountId),
930 Discarded(u32, T::AccountId),
932 Bailed(u32, T::AccountId),
934 }
935
936 #[pallet::error]
937 pub enum Error<T> {
938 PhaseNotSigned,
940 Duplicate,
942 QueueFull,
944 BadPageIndex,
946 NotRegistered,
948 NoSubmission,
950 RoundNotOver,
952 BadWitnessData,
954 TooManyInvulnerables,
956 NoUnpaidReward,
958 PotStillDepleted,
960 }
961
962 #[pallet::call]
963 impl<T: Config> Pallet<T> {
964 #[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 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 if discarded {
996 Ok(().into())
997 } else {
998 Ok(Some(SignedWeightsOf::<T>::register_not_full()).into())
999 }
1000 }
1001
1002 #[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 if is_set {
1028 Ok(().into())
1029 } else {
1030 Ok(Some(SignedWeightsOf::<T>::unset_page()).into())
1031 }
1032 }
1033
1034 #[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 #[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 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 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 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 Ok(None.into())
1099 }
1100
1101 #[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 #[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 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 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 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 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 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 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 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 if let crate::types::Phase::SignedValidation(remaining_blocks) =
1285 crate::Pallet::<T>::current_phase()
1286 {
1287 if remaining_blocks >= T::Pages::get().into() {
1290 if Submissions::<T>::has_leader(current_round) {
1291 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 sublog!(
1308 warn,
1309 "signed",
1310 "Tried to slash but no leader was present for round {}",
1311 current_round
1312 );
1313 }
1314 }
1315}