referrerpolicy=no-referrer-when-downgrade

pallet_staking_async/pallet/
impls.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//! `pallet-staking-async`'s main `impl` blocks.
19
20use crate::{
21	asset,
22	election_size_tracker::StaticTracker,
23	log,
24	session_rotation::{self, Eras, Rotator},
25	slashing::OffenceRecord,
26	weights::WeightInfo,
27	BalanceOf, Exposure, Forcing, LedgerIntegrityState, MaxNominationsOf, Nominations,
28	NominationsQuota, PositiveImbalanceOf, RewardDestination, SnapshotStatus, StakingLedger,
29	ValidatorPrefs, STAKING_ID,
30};
31use alloc::{boxed::Box, vec, vec::Vec};
32use frame_election_provider_support::{
33	bounds::CountBound, data_provider, DataProviderBounds, ElectionDataProvider, ElectionProvider,
34	PageIndex, ScoreProvider, SortedListProvider, VoteWeight, VoterOf,
35};
36use frame_support::{
37	defensive,
38	dispatch::WithPostDispatchInfo,
39	pallet_prelude::*,
40	traits::{
41		Defensive, DefensiveSaturating, Get, Imbalance, InspectLockableCurrency, LockableCurrency,
42		OnUnbalanced,
43	},
44	weights::Weight,
45	StorageDoubleMap,
46};
47use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
48use pallet_staking_async_rc_client::{self as rc_client};
49use sp_runtime::{
50	traits::{CheckedAdd, Saturating, StaticLookup, Zero},
51	ArithmeticError, DispatchResult, Perbill,
52};
53use sp_staking::{
54	currency_to_vote::CurrencyToVote,
55	EraIndex, OnStakingUpdate, Page, SessionIndex, Stake,
56	StakingAccount::{self, Controller, Stash},
57	StakingInterface,
58};
59
60use super::pallet::*;
61
62#[cfg(feature = "try-runtime")]
63use frame_support::ensure;
64#[cfg(any(test, feature = "try-runtime"))]
65use sp_runtime::TryRuntimeError;
66
67/// The maximum number of iterations that we do whilst iterating over `T::VoterList` in
68/// `get_npos_voters`.
69///
70/// In most cases, if we want n items, we iterate exactly n times. In rare cases, if a voter is
71/// invalid (for any reason) the iteration continues. With this constant, we iterate at most 2 * n
72/// times and then give up.
73const NPOS_MAX_ITERATIONS_COEFFICIENT: u32 = 2;
74
75impl<T: Config> Pallet<T> {
76	/// Returns the minimum required bond for participation, considering nominators,
77	/// and the chain’s existential deposit.
78	///
79	/// This function computes the smallest allowed bond among `MinValidatorBond` and
80	/// `MinNominatorBond`, but ensures it is not below the existential deposit required to keep an
81	/// account alive.
82	pub(crate) fn min_chilled_bond() -> BalanceOf<T> {
83		MinValidatorBond::<T>::get()
84			.min(MinNominatorBond::<T>::get())
85			.max(asset::existential_deposit::<T>())
86	}
87
88	/// Returns the minimum required bond for participation in staking as a validator account.
89	pub(crate) fn min_validator_bond() -> BalanceOf<T> {
90		MinValidatorBond::<T>::get().max(asset::existential_deposit::<T>())
91	}
92
93	/// Returns the minimum required bond for participation in staking as a nominator account.
94	pub(crate) fn min_nominator_bond() -> BalanceOf<T> {
95		MinNominatorBond::<T>::get().max(asset::existential_deposit::<T>())
96	}
97
98	/// Fetches the ledger associated with a controller or stash account, if any.
99	pub fn ledger(account: StakingAccount<T::AccountId>) -> Result<StakingLedger<T>, Error<T>> {
100		StakingLedger::<T>::get(account)
101	}
102
103	pub fn payee(account: StakingAccount<T::AccountId>) -> Option<RewardDestination<T::AccountId>> {
104		StakingLedger::<T>::reward_destination(account)
105	}
106
107	/// Fetches the controller bonded to a stash account, if any.
108	pub fn bonded(stash: &T::AccountId) -> Option<T::AccountId> {
109		StakingLedger::<T>::paired_account(Stash(stash.clone()))
110	}
111
112	/// Inspects and returns the corruption state of a ledger and direct bond, if any.
113	///
114	/// Note: all operations in this method access directly the `Bonded` and `Ledger` storage maps
115	/// instead of using the [`StakingLedger`] API since the bond and/or ledger may be corrupted.
116	/// It is also meant to check state for direct bonds and may not work as expected for virtual
117	/// bonds.
118	pub(crate) fn inspect_bond_state(
119		stash: &T::AccountId,
120	) -> Result<LedgerIntegrityState, Error<T>> {
121		// look at any old unmigrated lock as well.
122		let hold_or_lock = asset::staked::<T>(&stash)
123			.max(T::OldCurrency::balance_locked(STAKING_ID, &stash).into());
124
125		let controller = <Bonded<T>>::get(stash).ok_or_else(|| {
126			if hold_or_lock == Zero::zero() {
127				Error::<T>::NotStash
128			} else {
129				Error::<T>::BadState
130			}
131		})?;
132
133		match Ledger::<T>::get(controller) {
134			Some(ledger) =>
135				if ledger.stash != *stash {
136					Ok(LedgerIntegrityState::Corrupted)
137				} else {
138					if hold_or_lock != ledger.total {
139						Ok(LedgerIntegrityState::LockCorrupted)
140					} else {
141						Ok(LedgerIntegrityState::Ok)
142					}
143				},
144			None => Ok(LedgerIntegrityState::CorruptedKilled),
145		}
146	}
147
148	/// The total balance that can be slashed from a stash account as of right now.
149	pub fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf<T> {
150		// Weight note: consider making the stake accessible through stash.
151		Self::ledger(Stash(stash.clone())).map(|l| l.active).unwrap_or_default()
152	}
153
154	/// Internal impl of [`Self::slashable_balance_of`] that returns [`VoteWeight`].
155	pub fn slashable_balance_of_vote_weight(
156		stash: &T::AccountId,
157		issuance: BalanceOf<T>,
158	) -> VoteWeight {
159		T::CurrencyToVote::to_vote(Self::slashable_balance_of(stash), issuance)
160	}
161
162	/// Returns a closure around `slashable_balance_of_vote_weight` that can be passed around.
163	///
164	/// This prevents call sites from repeatedly requesting `total_issuance` from backend. But it is
165	/// important to be only used while the total issuance is not changing.
166	pub fn weight_of_fn() -> Box<dyn Fn(&T::AccountId) -> VoteWeight> {
167		// NOTE: changing this to unboxed `impl Fn(..)` return type and the pallet will still
168		// compile, while some types in mock fail to resolve.
169		let issuance = asset::total_issuance::<T>();
170		Box::new(move |who: &T::AccountId| -> VoteWeight {
171			Self::slashable_balance_of_vote_weight(who, issuance)
172		})
173	}
174
175	/// Same as `weight_of_fn`, but made for one time use.
176	pub fn weight_of(who: &T::AccountId) -> VoteWeight {
177		let issuance = asset::total_issuance::<T>();
178		Self::slashable_balance_of_vote_weight(who, issuance)
179	}
180
181	/// Checks if a slash has been cancelled for the given era and slash parameters.
182	pub(crate) fn check_slash_cancelled(
183		era: EraIndex,
184		validator: &T::AccountId,
185		slash_fraction: Perbill,
186	) -> bool {
187		let cancelled_slashes = CancelledSlashes::<T>::get(&era);
188		cancelled_slashes.iter().any(|(cancelled_validator, cancel_fraction)| {
189			*cancelled_validator == *validator && *cancel_fraction >= slash_fraction
190		})
191	}
192
193	pub(super) fn do_bond_extra(stash: &T::AccountId, additional: BalanceOf<T>) -> DispatchResult {
194		let mut ledger = Self::ledger(StakingAccount::Stash(stash.clone()))?;
195
196		// for virtual stakers, we don't need to check the balance. Since they are only accessed
197		// via low level apis, we can assume that the caller has done the due diligence.
198		let extra = if Self::is_virtual_staker(stash) {
199			additional
200		} else {
201			// additional amount or actual balance of stash whichever is lower.
202			additional.min(asset::free_to_stake::<T>(stash))
203		};
204
205		ledger.total = ledger.total.checked_add(&extra).ok_or(ArithmeticError::Overflow)?;
206		ledger.active = ledger.active.checked_add(&extra).ok_or(ArithmeticError::Overflow)?;
207		// last check: the new active amount of ledger must be more than min bond.
208		ensure!(ledger.active >= Self::min_chilled_bond(), Error::<T>::InsufficientBond);
209
210		// NOTE: ledger must be updated prior to calling `Self::weight_of`.
211		ledger.update()?;
212		// update this staker in the sorted list, if they exist in it.
213		if T::VoterList::contains(stash) {
214			// This might fail if the voter list is locked.
215			let _ = T::VoterList::on_update(&stash, Self::weight_of(stash));
216		}
217
218		Self::deposit_event(Event::<T>::Bonded { stash: stash.clone(), amount: extra });
219
220		Ok(())
221	}
222
223	/// Calculate the earliest era that withdrawals are allowed for, considering:
224	/// - The current active era
225	/// - Any unprocessed offences in the queue
226	fn calculate_earliest_withdrawal_era(active_era: EraIndex) -> EraIndex {
227		// get lowest era for which all offences are processed and withdrawals can be allowed.
228		let earliest_unlock_era_by_offence_queue = OffenceQueueEras::<T>::get()
229			.as_ref()
230			.and_then(|eras| eras.first())
231			.copied()
232			// if nothing in queue, use the active era.
233			.unwrap_or(active_era)
234			// above returns earliest era for which offences are NOT processed yet, so we subtract
235			// one from it which gives us the oldest era for which all offences are processed.
236			.saturating_sub(1)
237			// Unlock chunks are keyed by the era they were initiated plus Bonding Duration.
238			// We do the same to processed offence era so they can be compared.
239			.saturating_add(T::BondingDuration::get());
240
241		// If there are unprocessed offences older than the active era, withdrawals are only
242		// allowed up to the last era for which offences have been processed.
243		// Note: This situation is extremely unlikely, since offences have `SlashDeferDuration` eras
244		// to be processed. If it ever occurs, it likely indicates offence spam and that we're
245		// struggling to keep up with processing.
246		active_era.min(earliest_unlock_era_by_offence_queue)
247	}
248
249	pub(super) fn do_withdraw_unbonded(controller: &T::AccountId) -> Result<Weight, DispatchError> {
250		let mut ledger = Self::ledger(Controller(controller.clone()))?;
251		let (stash, old_total) = (ledger.stash.clone(), ledger.total);
252		let active_era = Rotator::<T>::active_era();
253
254		// Ensure last era slashes are applied. Else we block the withdrawals.
255		if active_era > 1 {
256			Self::ensure_era_slashes_applied(active_era.saturating_sub(1))?;
257		}
258
259		let earliest_era_to_withdraw = Self::calculate_earliest_withdrawal_era(active_era);
260
261		log!(
262			debug,
263			"Withdrawing unbonded stake. Active_era is: {:?} | \
264			Earliest era we can allow withdrawing: {:?}",
265			active_era,
266			earliest_era_to_withdraw
267		);
268
269		// withdraw unbonded balance from the ledger until earliest_era_to_withdraw.
270		ledger = ledger.consolidate_unlocked(earliest_era_to_withdraw);
271
272		let new_total = ledger.total;
273		debug_assert!(
274			new_total <= old_total,
275			"consolidate_unlocked should never increase the total balance of the ledger"
276		);
277
278		let used_weight = if ledger.unlocking.is_empty() &&
279			(ledger.active < Self::min_chilled_bond() || ledger.active.is_zero())
280		{
281			// This account must have called `unbond()` with some value that caused the active
282			// portion to fall below existential deposit + will have no more unlocking chunks
283			// left. We can now safely remove all staking-related information.
284			Self::kill_stash(&ledger.stash)?;
285
286			T::WeightInfo::withdraw_unbonded_kill()
287		} else {
288			// This was the consequence of a partial unbond. just update the ledger and move on.
289			ledger.update()?;
290
291			// This is only an update, so we use less overall weight.
292			T::WeightInfo::withdraw_unbonded_update()
293		};
294
295		// `old_total` should never be less than the new total because
296		// `consolidate_unlocked` strictly subtracts balance.
297		if new_total < old_total {
298			// Already checked that this won't overflow by entry condition.
299			let value = old_total.defensive_saturating_sub(new_total);
300			Self::deposit_event(Event::<T>::Withdrawn { stash, amount: value });
301
302			// notify listeners.
303			T::EventListeners::on_withdraw(controller, value);
304		}
305
306		Ok(used_weight)
307	}
308
309	fn ensure_era_slashes_applied(era: EraIndex) -> Result<(), DispatchError> {
310		ensure!(
311			!UnappliedSlashes::<T>::contains_prefix(era),
312			Error::<T>::UnappliedSlashesInPreviousEra
313		);
314		Ok(())
315	}
316
317	pub(super) fn do_payout_stakers(
318		validator_stash: T::AccountId,
319		era: EraIndex,
320	) -> DispatchResultWithPostInfo {
321		let page = Eras::<T>::get_next_claimable_page(era, &validator_stash).ok_or_else(|| {
322			Error::<T>::AlreadyClaimed.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
323		})?;
324
325		Self::do_payout_stakers_by_page(validator_stash, era, page)
326	}
327
328	pub(super) fn do_payout_stakers_by_page(
329		validator_stash: T::AccountId,
330		era: EraIndex,
331		page: Page,
332	) -> DispatchResultWithPostInfo {
333		// Validate input data
334		let current_era = CurrentEra::<T>::get().ok_or_else(|| {
335			Error::<T>::InvalidEraToReward
336				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
337		})?;
338
339		let history_depth = T::HistoryDepth::get();
340
341		ensure!(
342			era <= current_era && era >= current_era.saturating_sub(history_depth),
343			Error::<T>::InvalidEraToReward
344				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
345		);
346
347		ensure!(
348			page < Eras::<T>::exposure_page_count(era, &validator_stash),
349			Error::<T>::InvalidPage.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
350		);
351
352		// Note: if era has no reward to be claimed, era may be future.
353		let era_payout = Eras::<T>::get_validators_reward(era).ok_or_else(|| {
354			Error::<T>::InvalidEraToReward
355				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
356		})?;
357
358		let account = StakingAccount::Stash(validator_stash.clone());
359		let ledger = Self::ledger(account.clone()).or_else(|_| {
360			if StakingLedger::<T>::is_bonded(account) {
361				Err(Error::<T>::NotController.into())
362			} else {
363				Err(Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
364			}
365		})?;
366
367		ledger.clone().update()?;
368
369		let stash = ledger.stash.clone();
370
371		if Eras::<T>::is_rewards_claimed(era, &stash, page) {
372			return Err(Error::<T>::AlreadyClaimed
373				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
374		}
375
376		Eras::<T>::set_rewards_as_claimed(era, &stash, page);
377
378		let exposure = Eras::<T>::get_paged_exposure(era, &stash, page).ok_or_else(|| {
379			Error::<T>::InvalidEraToReward
380				.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
381		})?;
382
383		// Input data seems good, no errors allowed after this point
384
385		// Get Era reward points. It has TOTAL and INDIVIDUAL
386		// Find the fraction of the era reward that belongs to the validator
387		// Take that fraction of the eras rewards to split to nominator and validator
388		//
389		// Then look at the validator, figure out the proportion of their reward
390		// which goes to them and each of their nominators.
391
392		let era_reward_points = Eras::<T>::get_reward_points(era);
393		let total_reward_points = era_reward_points.total;
394		let validator_reward_points =
395			era_reward_points.individual.get(&stash).copied().unwrap_or_else(Zero::zero);
396
397		// Nothing to do if they have no reward points.
398		if validator_reward_points.is_zero() {
399			return Ok(Some(T::WeightInfo::payout_stakers_alive_staked(0)).into())
400		}
401
402		// This is the fraction of the total reward that the validator and the
403		// nominators will get.
404		let validator_total_reward_part =
405			Perbill::from_rational(validator_reward_points, total_reward_points);
406
407		// This is how much validator + nominators are entitled to.
408		let validator_total_payout = validator_total_reward_part * era_payout;
409
410		let validator_commission = Eras::<T>::get_validator_commission(era, &ledger.stash);
411		// total commission validator takes across all nominator pages
412		let validator_total_commission_payout = validator_commission * validator_total_payout;
413
414		let validator_leftover_payout =
415			validator_total_payout.defensive_saturating_sub(validator_total_commission_payout);
416		// Now let's calculate how this is split to the validator.
417		let validator_exposure_part = Perbill::from_rational(exposure.own(), exposure.total());
418		let validator_staking_payout = validator_exposure_part * validator_leftover_payout;
419		let page_stake_part = Perbill::from_rational(exposure.page_total(), exposure.total());
420		// validator commission is paid out in fraction across pages proportional to the page stake.
421		let validator_commission_payout = page_stake_part * validator_total_commission_payout;
422
423		Self::deposit_event(Event::<T>::PayoutStarted {
424			era_index: era,
425			validator_stash: stash.clone(),
426			page,
427			next: Eras::<T>::get_next_claimable_page(era, &stash),
428		});
429
430		let mut total_imbalance = PositiveImbalanceOf::<T>::zero();
431		// We can now make total validator payout:
432		if let Some((imbalance, dest)) =
433			Self::make_payout(&stash, validator_staking_payout + validator_commission_payout)
434		{
435			Self::deposit_event(Event::<T>::Rewarded { stash, dest, amount: imbalance.peek() });
436			total_imbalance.subsume(imbalance);
437		}
438
439		// Track the number of payout ops to nominators. Note:
440		// `WeightInfo::payout_stakers_alive_staked` always assumes at least a validator is paid
441		// out, so we do not need to count their payout op.
442		let mut nominator_payout_count: u32 = 0;
443
444		// Lets now calculate how this is split to the nominators.
445		// Reward only the clipped exposures. Note this is not necessarily sorted.
446		for nominator in exposure.others().iter() {
447			let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total());
448
449			let nominator_reward: BalanceOf<T> =
450				nominator_exposure_part * validator_leftover_payout;
451			// We can now make nominator payout:
452			if let Some((imbalance, dest)) = Self::make_payout(&nominator.who, nominator_reward) {
453				// Note: this logic does not count payouts for `RewardDestination::None`.
454				nominator_payout_count += 1;
455				let e = Event::<T>::Rewarded {
456					stash: nominator.who.clone(),
457					dest,
458					amount: imbalance.peek(),
459				};
460				Self::deposit_event(e);
461				total_imbalance.subsume(imbalance);
462			}
463		}
464
465		T::Reward::on_unbalanced(total_imbalance);
466		debug_assert!(nominator_payout_count <= T::MaxExposurePageSize::get());
467
468		Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into())
469	}
470
471	/// Chill a stash account.
472	pub(crate) fn chill_stash(stash: &T::AccountId) {
473		let chilled_as_validator = Self::do_remove_validator(stash);
474		let chilled_as_nominator = Self::do_remove_nominator(stash);
475		if chilled_as_validator || chilled_as_nominator {
476			Self::deposit_event(Event::<T>::Chilled { stash: stash.clone() });
477		}
478	}
479
480	/// Actually make a payment to a staker. This uses the currency's reward function
481	/// to pay the right payee for the given staker account.
482	fn make_payout(
483		stash: &T::AccountId,
484		amount: BalanceOf<T>,
485	) -> Option<(PositiveImbalanceOf<T>, RewardDestination<T::AccountId>)> {
486		// noop if amount is zero
487		if amount.is_zero() {
488			return None
489		}
490		let dest = Self::payee(StakingAccount::Stash(stash.clone()))?;
491
492		let maybe_imbalance = match dest {
493			RewardDestination::Stash => asset::mint_into_existing::<T>(stash, amount),
494			RewardDestination::Staked => Self::ledger(Stash(stash.clone()))
495				.and_then(|mut ledger| {
496					ledger.active += amount;
497					ledger.total += amount;
498					let r = asset::mint_into_existing::<T>(stash, amount);
499
500					let _ = ledger
501						.update()
502						.defensive_proof("ledger fetched from storage, so it exists; qed.");
503
504					Ok(r)
505				})
506				.unwrap_or_default(),
507			RewardDestination::Account(ref dest_account) =>
508				Some(asset::mint_creating::<T>(&dest_account, amount)),
509			RewardDestination::None => None,
510			#[allow(deprecated)]
511			RewardDestination::Controller => Self::bonded(stash)
512					.map(|controller| {
513						defensive!("Paying out controller as reward destination which is deprecated and should be migrated.");
514						// This should never happen once payees with a `Controller` variant have been migrated.
515						// But if it does, just pay the controller account.
516						asset::mint_creating::<T>(&controller, amount)
517		}),
518		};
519		maybe_imbalance.map(|imbalance| (imbalance, dest))
520	}
521
522	/// Remove all associated data of a stash account from the staking system.
523	///
524	/// Assumes storage is upgraded before calling.
525	///
526	/// This is called:
527	/// - after a `withdraw_unbonded()` call that frees all of a stash's bonded balance.
528	/// - through `reap_stash()` if the balance has fallen to zero (through slashing).
529	pub(crate) fn kill_stash(stash: &T::AccountId) -> DispatchResult {
530		// removes controller from `Bonded` and staking ledger from `Ledger`, as well as reward
531		// setting of the stash in `Payee`.
532		StakingLedger::<T>::kill(&stash)?;
533
534		Self::do_remove_validator(&stash);
535		Self::do_remove_nominator(&stash);
536
537		Ok(())
538	}
539
540	#[cfg(test)]
541	pub(crate) fn reward_by_ids(validators_points: impl IntoIterator<Item = (T::AccountId, u32)>) {
542		Eras::<T>::reward_active_era(validators_points)
543	}
544
545	/// Helper to set a new `ForceEra` mode.
546	pub(crate) fn set_force_era(mode: Forcing) {
547		log!(info, "Setting force era mode {:?}.", mode);
548		ForceEra::<T>::put(mode);
549		Self::deposit_event(Event::<T>::ForceEra { mode });
550	}
551
552	#[cfg(feature = "runtime-benchmarks")]
553	pub fn add_era_stakers(
554		current_era: EraIndex,
555		stash: T::AccountId,
556		exposure: Exposure<T::AccountId, BalanceOf<T>>,
557	) {
558		Eras::<T>::upsert_exposure(current_era, &stash, exposure);
559	}
560
561	#[cfg(feature = "runtime-benchmarks")]
562	pub fn set_slash_reward_fraction(fraction: Perbill) {
563		SlashRewardFraction::<T>::put(fraction);
564	}
565
566	/// Get all the voters associated with `page` that are eligible for the npos election.
567	///
568	/// `bounds` can impose a cap on the number of voters returned per page.
569	///
570	/// Sets `MinimumActiveStake` to the minimum active nominator stake in the returned set of
571	/// nominators.
572	///
573	/// Note: in the context of the multi-page snapshot, we expect the *order* of `VoterList` and
574	/// `TargetList` not to change while the pages are being processed.
575	pub(crate) fn get_npos_voters(
576		bounds: DataProviderBounds,
577		status: &SnapshotStatus<T::AccountId>,
578	) -> Vec<VoterOf<Self>> {
579		let mut voters_size_tracker: StaticTracker<Self> = StaticTracker::default();
580
581		let page_len_prediction = {
582			let all_voter_count = T::VoterList::count();
583			bounds.count.unwrap_or(all_voter_count.into()).min(all_voter_count.into()).0
584		};
585
586		let mut all_voters = Vec::<_>::with_capacity(page_len_prediction as usize);
587
588		// cache a few things.
589		let weight_of = Self::weight_of_fn();
590
591		let mut voters_seen = 0u32;
592		let mut validators_taken = 0u32;
593		let mut nominators_taken = 0u32;
594		let mut min_active_stake = u64::MAX;
595
596		let mut sorted_voters = match status {
597			// start the snapshot processing from the beginning.
598			SnapshotStatus::Waiting => T::VoterList::iter(),
599			// snapshot continues, start from the last iterated voter in the list.
600			SnapshotStatus::Ongoing(account_id) => T::VoterList::iter_from(&account_id)
601				.defensive_unwrap_or(Box::new(vec![].into_iter())),
602			// all voters have been consumed already, return an empty iterator.
603			SnapshotStatus::Consumed => Box::new(vec![].into_iter()),
604		};
605
606		while all_voters.len() < page_len_prediction as usize &&
607			voters_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * page_len_prediction as u32)
608		{
609			let voter = match sorted_voters.next() {
610				Some(voter) => {
611					voters_seen.saturating_inc();
612					voter
613				},
614				None => break,
615			};
616
617			let voter_weight = weight_of(&voter);
618			// if voter weight is zero, do not consider this voter for the snapshot.
619			if voter_weight.is_zero() {
620				log!(debug, "voter's active balance is 0. skip this voter.");
621				continue
622			}
623
624			if let Some(Nominations { targets, .. }) = <Nominators<T>>::get(&voter) {
625				if !targets.is_empty() {
626					// Note on lazy nomination quota: we do not check the nomination quota of the
627					// voter at this point and accept all the current nominations. The nomination
628					// quota is only enforced at `nominate` time.
629
630					let voter = (voter, voter_weight, targets);
631					if voters_size_tracker.try_register_voter(&voter, &bounds).is_err() {
632						// no more space left for the election result, stop iterating.
633						Self::deposit_event(Event::<T>::SnapshotVotersSizeExceeded {
634							size: voters_size_tracker.size as u32,
635						});
636						break
637					}
638
639					all_voters.push(voter);
640					nominators_taken.saturating_inc();
641				} else {
642					defensive!("non-nominator fetched from voter list: {:?}", voter);
643					// technically should never happen, but not much we can do about it.
644				}
645				min_active_stake =
646					if voter_weight < min_active_stake { voter_weight } else { min_active_stake };
647			} else if Validators::<T>::contains_key(&voter) {
648				// if this voter is a validator:
649				let self_vote = (
650					voter.clone(),
651					voter_weight,
652					vec![voter.clone()]
653						.try_into()
654						.expect("`MaxVotesPerVoter` must be greater than or equal to 1"),
655				);
656
657				if voters_size_tracker.try_register_voter(&self_vote, &bounds).is_err() {
658					// no more space left for the election snapshot, stop iterating.
659					Self::deposit_event(Event::<T>::SnapshotVotersSizeExceeded {
660						size: voters_size_tracker.size as u32,
661					});
662					break
663				}
664				all_voters.push(self_vote);
665				validators_taken.saturating_inc();
666			} else {
667				// this can only happen if: 1. there a bug in the bags-list (or whatever is the
668				// sorted list) logic and the state of the two pallets is no longer compatible, or
669				// because the nominators is not decodable since they have more nomination than
670				// `T::NominationsQuota::get_quota`. The latter can rarely happen, and is not
671				// really an emergency or bug if it does.
672				defensive!(
673				    "invalid item in `VoterList`: {:?}, this nominator probably has too many nominations now",
674                    voter,
675                );
676			}
677		}
678
679		// all_voters should have not re-allocated.
680		debug_assert!(all_voters.capacity() == page_len_prediction as usize);
681
682		let min_active_stake: T::CurrencyBalance =
683			if all_voters.is_empty() { Zero::zero() } else { min_active_stake.into() };
684
685		MinimumActiveStake::<T>::put(min_active_stake);
686
687		all_voters
688	}
689
690	/// Get all the targets associated are eligible for the npos election.
691	///
692	/// The target snapshot is *always* single paged.
693	///
694	/// This function is self-weighing as [`DispatchClass::Mandatory`].
695	pub fn get_npos_targets(bounds: DataProviderBounds) -> Vec<T::AccountId> {
696		let mut targets_size_tracker: StaticTracker<Self> = StaticTracker::default();
697
698		let final_predicted_len = {
699			let all_target_count = T::TargetList::count();
700			bounds.count.unwrap_or(all_target_count.into()).min(all_target_count.into()).0
701		};
702
703		let mut all_targets = Vec::<T::AccountId>::with_capacity(final_predicted_len as usize);
704		let mut targets_seen = 0;
705
706		let mut targets_iter = T::TargetList::iter();
707		while all_targets.len() < final_predicted_len as usize &&
708			targets_seen < (NPOS_MAX_ITERATIONS_COEFFICIENT * final_predicted_len as u32)
709		{
710			let target = match targets_iter.next() {
711				Some(target) => {
712					targets_seen.saturating_inc();
713					target
714				},
715				None => break,
716			};
717
718			if targets_size_tracker.try_register_target(target.clone(), &bounds).is_err() {
719				// no more space left for the election snapshot, stop iterating.
720				log!(warn, "npos targets size exceeded, stopping iteration.");
721				Self::deposit_event(Event::<T>::SnapshotTargetsSizeExceeded {
722					size: targets_size_tracker.size as u32,
723				});
724				break
725			}
726
727			if Validators::<T>::contains_key(&target) {
728				all_targets.push(target);
729			}
730		}
731
732		log!(debug, "[bounds {:?}] generated {} npos targets", bounds, all_targets.len());
733
734		all_targets
735	}
736
737	/// This function will add a nominator to the `Nominators` storage map,
738	/// and `VoterList`.
739	///
740	/// If the nominator already exists, their nominations will be updated.
741	///
742	/// NOTE: you must ALWAYS use this function to add nominator or update their targets. Any access
743	/// to `Nominators` or `VoterList` outside of this function is almost certainly
744	/// wrong.
745	pub fn do_add_nominator(who: &T::AccountId, nominations: Nominations<T>) {
746		if !Nominators::<T>::contains_key(who) {
747			// maybe update sorted list.
748			let _ = T::VoterList::on_insert(who.clone(), Self::weight_of(who))
749				.defensive_unwrap_or_default();
750		}
751		Nominators::<T>::insert(who, nominations);
752	}
753
754	/// This function will remove a nominator from the `Nominators` storage map,
755	/// and `VoterList`.
756	///
757	/// Returns true if `who` was removed from `Nominators`, otherwise false.
758	///
759	/// NOTE: you must ALWAYS use this function to remove a nominator from the system. Any access to
760	/// `Nominators` or `VoterList` outside of this function is almost certainly
761	/// wrong.
762	pub fn do_remove_nominator(who: &T::AccountId) -> bool {
763		let outcome = if Nominators::<T>::contains_key(who) {
764			Nominators::<T>::remove(who);
765			let _ = T::VoterList::on_remove(who);
766			true
767		} else {
768			false
769		};
770
771		outcome
772	}
773
774	/// This function will add a validator to the `Validators` storage map.
775	///
776	/// If the validator already exists, their preferences will be updated.
777	///
778	/// NOTE: you must ALWAYS use this function to add a validator to the system. Any access to
779	/// `Validators` or `VoterList` outside of this function is almost certainly
780	/// wrong.
781	pub fn do_add_validator(who: &T::AccountId, prefs: ValidatorPrefs) {
782		if !Validators::<T>::contains_key(who) {
783			// maybe update sorted list.
784			let _ = T::VoterList::on_insert(who.clone(), Self::weight_of(who));
785		}
786		Validators::<T>::insert(who, prefs);
787	}
788
789	/// This function will remove a validator from the `Validators` storage map.
790	///
791	/// Returns true if `who` was removed from `Validators`, otherwise false.
792	///
793	/// NOTE: you must ALWAYS use this function to remove a validator from the system. Any access to
794	/// `Validators` or `VoterList` outside of this function is almost certainly
795	/// wrong.
796	pub fn do_remove_validator(who: &T::AccountId) -> bool {
797		let outcome = if Validators::<T>::contains_key(who) {
798			Validators::<T>::remove(who);
799			let _ = T::VoterList::on_remove(who);
800			true
801		} else {
802			false
803		};
804
805		outcome
806	}
807
808	/// Register some amount of weight directly with the system pallet.
809	///
810	/// This is always mandatory weight.
811	pub(crate) fn register_weight(weight: Weight) {
812		<frame_system::Pallet<T>>::register_extra_weight_unchecked(
813			weight,
814			DispatchClass::Mandatory,
815		);
816	}
817
818	/// Returns full exposure of a validator for a given era.
819	///
820	/// History note: This used to be a getter for old storage item `ErasStakers` deprecated in v14
821	/// and deleted in v17. Since this function is used in the codebase at various places, we kept
822	/// it as a custom getter that takes care of getting the full exposure of the validator in a
823	/// backward compatible way.
824	pub fn eras_stakers(
825		era: EraIndex,
826		account: &T::AccountId,
827	) -> Exposure<T::AccountId, BalanceOf<T>> {
828		Eras::<T>::get_full_exposure(era, account)
829	}
830
831	pub(super) fn do_migrate_currency(stash: &T::AccountId) -> DispatchResult {
832		if Self::is_virtual_staker(stash) {
833			return Self::do_migrate_virtual_staker(stash);
834		}
835
836		let ledger = Self::ledger(Stash(stash.clone()))?;
837		let staked: BalanceOf<T> = T::OldCurrency::balance_locked(STAKING_ID, stash).into();
838		ensure!(!staked.is_zero(), Error::<T>::AlreadyMigrated);
839		ensure!(ledger.total == staked, Error::<T>::BadState);
840
841		// remove old staking lock
842		T::OldCurrency::remove_lock(STAKING_ID, &stash);
843
844		// check if we can hold all stake.
845		let max_hold = asset::free_to_stake::<T>(&stash);
846		let force_withdraw = if max_hold >= staked {
847			// this means we can hold all stake. yay!
848			asset::update_stake::<T>(&stash, staked)?;
849			Zero::zero()
850		} else {
851			// if we are here, it means we cannot hold all user stake. We will do a force withdraw
852			// from ledger, but that's okay since anyways user do not have funds for it.
853			let force_withdraw = staked.saturating_sub(max_hold);
854
855			// we ignore if active is 0. It implies the locked amount is not actively staked. The
856			// account can still get away from potential slash but we can't do much better here.
857			StakingLedger {
858				total: max_hold,
859				active: ledger.active.saturating_sub(force_withdraw),
860				// we are not changing the stash, so we can keep the stash.
861				..ledger
862			}
863			.update()?;
864			force_withdraw
865		};
866
867		// Get rid of the extra consumer we used to have with OldCurrency.
868		frame_system::Pallet::<T>::dec_consumers(&stash);
869
870		Self::deposit_event(Event::<T>::CurrencyMigrated { stash: stash.clone(), force_withdraw });
871		Ok(())
872	}
873
874	fn do_migrate_virtual_staker(stash: &T::AccountId) -> DispatchResult {
875		// Funds for virtual stakers not managed/held by this pallet. We only need to clear
876		// the extra consumer we used to have with OldCurrency.
877		frame_system::Pallet::<T>::dec_consumers(&stash);
878
879		// The delegation system that manages the virtual staker needed to increment provider
880		// previously because of the consumer needed by this pallet. In reality, this stash
881		// is just a key for managing the ledger and the account does not need to hold any
882		// balance or exist. We decrement this provider.
883		let actual_providers = frame_system::Pallet::<T>::providers(stash);
884
885		let expected_providers =
886			// provider is expected to be 1 but someone can always transfer some free funds to
887			// these accounts, increasing the provider.
888			if asset::free_to_stake::<T>(&stash) >= asset::existential_deposit::<T>() {
889				2
890			} else {
891				1
892			};
893
894		// We should never have more than expected providers.
895		ensure!(actual_providers <= expected_providers, Error::<T>::BadState);
896
897		// if actual provider is less than expected, it is already migrated.
898		ensure!(actual_providers == expected_providers, Error::<T>::AlreadyMigrated);
899
900		// dec provider
901		let _ = frame_system::Pallet::<T>::dec_providers(&stash)?;
902
903		return Ok(())
904	}
905}
906
907impl<T: Config> Pallet<T> {
908	/// Returns the current nominations quota for nominators.
909	///
910	/// Used by the runtime API.
911	pub fn api_nominations_quota(balance: BalanceOf<T>) -> u32 {
912		T::NominationsQuota::get_quota(balance)
913	}
914
915	pub fn api_eras_stakers(
916		era: EraIndex,
917		account: T::AccountId,
918	) -> Exposure<T::AccountId, BalanceOf<T>> {
919		Self::eras_stakers(era, &account)
920	}
921
922	pub fn api_eras_stakers_page_count(era: EraIndex, account: T::AccountId) -> Page {
923		Eras::<T>::exposure_page_count(era, &account)
924	}
925
926	pub fn api_pending_rewards(era: EraIndex, account: T::AccountId) -> bool {
927		Eras::<T>::pending_rewards(era, &account)
928	}
929}
930
931impl<T: Config> ElectionDataProvider for Pallet<T> {
932	type AccountId = T::AccountId;
933	type BlockNumber = BlockNumberFor<T>;
934	type MaxVotesPerVoter = MaxNominationsOf<T>;
935
936	fn desired_targets() -> data_provider::Result<u32> {
937		Self::register_weight(T::DbWeight::get().reads(1));
938		Ok(ValidatorCount::<T>::get())
939	}
940
941	fn electing_voters(
942		bounds: DataProviderBounds,
943		page: PageIndex,
944	) -> data_provider::Result<Vec<VoterOf<Self>>> {
945		let mut status = VoterSnapshotStatus::<T>::get();
946		let voters = Self::get_npos_voters(bounds, &status);
947
948		// update the voter snapshot status.
949		match (page, &status) {
950			// last page, reset status for next round.
951			(0, _) => status = SnapshotStatus::Waiting,
952
953			(_, SnapshotStatus::Waiting) | (_, SnapshotStatus::Ongoing(_)) => {
954				let maybe_last = voters.last().map(|(x, _, _)| x).cloned();
955
956				if let Some(ref last) = maybe_last {
957					let has_next =
958						T::VoterList::iter_from(last).ok().and_then(|mut i| i.next()).is_some();
959					if has_next {
960						status = SnapshotStatus::Ongoing(last.clone());
961					} else {
962						status = SnapshotStatus::Consumed;
963					}
964				}
965			},
966			// do nothing.
967			(_, SnapshotStatus::Consumed) => (),
968		}
969
970		log!(
971			debug,
972			"[page {}, (next) status {:?}, bounds {:?}] generated {} npos voters [first: {:?}, last: {:?}]",
973			page,
974			status,
975			bounds,
976			voters.len(),
977			voters.first().map(|(x, y, _)| (x, y)),
978			voters.last().map(|(x, y, _)| (x, y)),
979		);
980
981		match status {
982			SnapshotStatus::Ongoing(_) => T::VoterList::lock(),
983			_ => T::VoterList::unlock(),
984		}
985
986		VoterSnapshotStatus::<T>::put(status);
987		debug_assert!(!bounds.slice_exhausted(&voters));
988
989		Ok(voters)
990	}
991
992	fn electing_voters_stateless(
993		bounds: DataProviderBounds,
994	) -> data_provider::Result<Vec<VoterOf<Self>>> {
995		let voters = Self::get_npos_voters(bounds, &SnapshotStatus::Waiting);
996		log!(debug, "[stateless, bounds {:?}] generated {} npos voters", bounds, voters.len(),);
997		Ok(voters)
998	}
999
1000	fn electable_targets(
1001		bounds: DataProviderBounds,
1002		page: PageIndex,
1003	) -> data_provider::Result<Vec<T::AccountId>> {
1004		if page > 0 {
1005			log!(warn, "multi-page target snapshot not supported, returning page 0.");
1006		}
1007
1008		let targets = Self::get_npos_targets(bounds);
1009		if bounds.exhausted(None, CountBound(targets.len() as u32).into()) {
1010			return Err("Target snapshot too big")
1011		}
1012
1013		debug_assert!(!bounds.slice_exhausted(&targets));
1014
1015		Ok(targets)
1016	}
1017
1018	fn next_election_prediction(_: BlockNumberFor<T>) -> BlockNumberFor<T> {
1019		debug_assert!(false, "this is deprecated and not used anymore");
1020		sp_runtime::traits::Bounded::max_value()
1021	}
1022
1023	#[cfg(feature = "runtime-benchmarks")]
1024	fn fetch_page(page: PageIndex) {
1025		session_rotation::EraElectionPlanner::<T>::do_elect_paged(page);
1026	}
1027
1028	#[cfg(feature = "runtime-benchmarks")]
1029	fn add_voter(
1030		voter: T::AccountId,
1031		weight: VoteWeight,
1032		targets: BoundedVec<T::AccountId, Self::MaxVotesPerVoter>,
1033	) {
1034		let stake = <BalanceOf<T>>::try_from(weight).unwrap_or_else(|_| {
1035			panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
1036		});
1037		<Bonded<T>>::insert(voter.clone(), voter.clone());
1038		<Ledger<T>>::insert(voter.clone(), StakingLedger::<T>::new(voter.clone(), stake));
1039
1040		Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
1041	}
1042
1043	#[cfg(feature = "runtime-benchmarks")]
1044	fn add_target(target: T::AccountId) {
1045		let stake = (Self::min_validator_bond() + 1u32.into()) * 100u32.into();
1046		<Bonded<T>>::insert(target.clone(), target.clone());
1047		<Ledger<T>>::insert(target.clone(), StakingLedger::<T>::new(target.clone(), stake));
1048		Self::do_add_validator(
1049			&target,
1050			ValidatorPrefs { commission: Perbill::zero(), blocked: false },
1051		);
1052	}
1053
1054	#[cfg(feature = "runtime-benchmarks")]
1055	fn clear() {
1056		#[allow(deprecated)]
1057		<Bonded<T>>::remove_all(None);
1058		#[allow(deprecated)]
1059		<Ledger<T>>::remove_all(None);
1060		#[allow(deprecated)]
1061		<Validators<T>>::remove_all();
1062		#[allow(deprecated)]
1063		<Nominators<T>>::remove_all();
1064
1065		T::VoterList::unsafe_clear();
1066	}
1067
1068	#[cfg(feature = "runtime-benchmarks")]
1069	fn put_snapshot(
1070		voters: Vec<VoterOf<Self>>,
1071		targets: Vec<T::AccountId>,
1072		target_stake: Option<VoteWeight>,
1073	) {
1074		targets.into_iter().for_each(|v| {
1075			let stake: BalanceOf<T> = target_stake
1076				.and_then(|w| <BalanceOf<T>>::try_from(w).ok())
1077				.unwrap_or_else(|| Self::min_nominator_bond() * 100u32.into());
1078			<Bonded<T>>::insert(v.clone(), v.clone());
1079			<Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
1080			Self::do_add_validator(
1081				&v,
1082				ValidatorPrefs { commission: Perbill::zero(), blocked: false },
1083			);
1084		});
1085
1086		voters.into_iter().for_each(|(v, s, t)| {
1087			let stake = <BalanceOf<T>>::try_from(s).unwrap_or_else(|_| {
1088				panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
1089			});
1090			<Bonded<T>>::insert(v.clone(), v.clone());
1091			<Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
1092			Self::do_add_nominator(
1093				&v,
1094				Nominations { targets: t, submitted_in: 0, suppressed: false },
1095			);
1096		});
1097	}
1098
1099	#[cfg(feature = "runtime-benchmarks")]
1100	fn set_desired_targets(count: u32) {
1101		ValidatorCount::<T>::put(count);
1102	}
1103}
1104
1105impl<T: Config> rc_client::AHStakingInterface for Pallet<T> {
1106	type AccountId = T::AccountId;
1107	type MaxValidatorSet = T::MaxValidatorSet;
1108
1109	/// When we receive a session report from the relay chain, it kicks off the next session.
1110	///
1111	/// There are three special types of things we can do in a session:
1112	/// 1. Plan a new era: We do this one session before the expected era rotation.
1113	/// 2. Kick off election: We do this based on the [`Config::PlanningEraOffset`] configuration.
1114	/// 3. Activate Next Era: When we receive an activation timestamp in the session report, it
1115	/// implies a new validator set has been applied, and we must increment the active era to keep
1116	/// the systems in sync.
1117	fn on_relay_session_report(report: rc_client::SessionReport<Self::AccountId>) -> Weight {
1118		log!(debug, "Received session report: {}", report,);
1119
1120		let rc_client::SessionReport {
1121			end_index,
1122			activation_timestamp,
1123			validator_points,
1124			leftover,
1125		} = report;
1126		debug_assert!(!leftover);
1127
1128		// note: weight for `reward_active_era` is taken care of inside `end_session`
1129		Eras::<T>::reward_active_era(validator_points.into_iter());
1130		session_rotation::Rotator::<T>::end_session(end_index, activation_timestamp)
1131	}
1132
1133	fn weigh_on_relay_session_report(
1134		_report: &rc_client::SessionReport<Self::AccountId>,
1135	) -> Weight {
1136		// worst case weight of this is always
1137		T::WeightInfo::rc_on_session_report()
1138	}
1139
1140	/// Accepts offences only if they are from era `active_era - (SlashDeferDuration - 1)` or newer.
1141	///
1142	/// Slashes for offences are applied `SlashDeferDuration` eras after the offence occurred.
1143	/// Accepting offences older than this range would not leave enough time for slashes to be
1144	/// applied.
1145	///
1146	/// Note: The validator set report that we send to the relay chain contains the pruning
1147	/// information for a relay chain, but we conservatively keep some extra sessions, so it is
1148	/// possible that an offence report is created for a session between SlashDeferDuration and
1149	/// BondingDuration eras before the active era. But they will be dropped here.
1150	fn on_new_offences(
1151		slash_session: SessionIndex,
1152		offences: Vec<rc_client::Offence<T::AccountId>>,
1153	) -> Weight {
1154		log!(debug, "🦹 on_new_offences: {:?}", offences);
1155		let weight = T::WeightInfo::rc_on_offence(offences.len() as u32);
1156
1157		// Find the era to which offence belongs.
1158		let Some(active_era) = ActiveEra::<T>::get() else {
1159			log!(warn, "🦹 on_new_offences: no active era; ignoring offence");
1160			return T::WeightInfo::rc_on_offence(0);
1161		};
1162
1163		let active_era_start_session = Rotator::<T>::active_era_start_session_index();
1164
1165		// Fast path for active-era report - most likely.
1166		// `slash_session` cannot be in a future active era. It must be in `active_era` or before.
1167		let offence_era = if slash_session >= active_era_start_session {
1168			active_era.index
1169		} else {
1170			match BondedEras::<T>::get()
1171				.iter()
1172				// Reverse because it's more likely to find reports from recent eras.
1173				.rev()
1174				.find_map(|&(era, sesh)| if sesh <= slash_session { Some(era) } else { None })
1175			{
1176				Some(era) => era,
1177				None => {
1178					// defensive: this implies offence is for a discarded era, and should already be
1179					// filtered out.
1180					log!(warn, "🦹 on_offence: no era found for slash_session; ignoring offence");
1181					return T::WeightInfo::rc_on_offence(0);
1182				},
1183			}
1184		};
1185
1186		let oldest_reportable_offence_era = if T::SlashDeferDuration::get() == 0 {
1187			// this implies that slashes are applied immediately, so we can accept any offence up to
1188			// bonding duration old.
1189			active_era.index.saturating_sub(T::BondingDuration::get())
1190		} else {
1191			// slashes are deffered, so we only accept offences that are not older than the
1192			// defferal duration.
1193			active_era.index.saturating_sub(T::SlashDeferDuration::get().saturating_sub(1))
1194		};
1195
1196		for o in offences {
1197			let slash_fraction = o.slash_fraction;
1198			let validator: <T as frame_system::Config>::AccountId = o.offender.into();
1199
1200			// ignore offence if too old to report.
1201			if offence_era < oldest_reportable_offence_era {
1202				log!(warn, "🦹 on_new_offences: offence era {:?} too old; Can only accept offences from era {:?} or newer", offence_era, oldest_reportable_offence_era);
1203				Self::deposit_event(Event::<T>::OffenceTooOld {
1204					validator: validator.clone(),
1205					fraction: slash_fraction,
1206					offence_era,
1207				});
1208				// will emit an event for each validator in the report.
1209				continue;
1210			}
1211			let Some(exposure_overview) = <ErasStakersOverview<T>>::get(&offence_era, &validator)
1212			else {
1213				// defensive: this implies offence is for a discarded era, and should already be
1214				// filtered out.
1215				log!(
1216					warn,
1217					"🦹 on_offence: no exposure found for {:?} in era {}; ignoring offence",
1218					validator,
1219					offence_era
1220				);
1221				continue;
1222			};
1223
1224			Self::deposit_event(Event::<T>::OffenceReported {
1225				validator: validator.clone(),
1226				fraction: slash_fraction,
1227				offence_era,
1228			});
1229
1230			let prior_slash_fraction = ValidatorSlashInEra::<T>::get(offence_era, &validator)
1231				.map_or(Zero::zero(), |(f, _)| f);
1232
1233			if let Some(existing) = OffenceQueue::<T>::get(offence_era, &validator) {
1234				if slash_fraction.deconstruct() > existing.slash_fraction.deconstruct() {
1235					OffenceQueue::<T>::insert(
1236						offence_era,
1237						&validator,
1238						OffenceRecord {
1239							reporter: o.reporters.first().cloned(),
1240							reported_era: active_era.index,
1241							slash_fraction,
1242							..existing
1243						},
1244					);
1245
1246					// update the slash fraction in the `ValidatorSlashInEra` storage.
1247					ValidatorSlashInEra::<T>::insert(
1248						offence_era,
1249						&validator,
1250						(slash_fraction, exposure_overview.own),
1251					);
1252
1253					log!(
1254						debug,
1255						"🦹 updated slash for {:?}: {:?} (prior: {:?})",
1256						validator,
1257						slash_fraction,
1258						prior_slash_fraction,
1259					);
1260				} else {
1261					log!(
1262						debug,
1263						"🦹 ignored slash for {:?}: {:?} (existing prior is larger: {:?})",
1264						validator,
1265						slash_fraction,
1266						prior_slash_fraction,
1267					);
1268				}
1269			} else if slash_fraction.deconstruct() > prior_slash_fraction.deconstruct() {
1270				ValidatorSlashInEra::<T>::insert(
1271					offence_era,
1272					&validator,
1273					(slash_fraction, exposure_overview.own),
1274				);
1275
1276				OffenceQueue::<T>::insert(
1277					offence_era,
1278					&validator,
1279					OffenceRecord {
1280						reporter: o.reporters.first().cloned(),
1281						reported_era: active_era.index,
1282						// there are cases of validator with no exposure, hence 0 page, so we
1283						// saturate to avoid underflow.
1284						exposure_page: exposure_overview.page_count.saturating_sub(1),
1285						slash_fraction,
1286						prior_slash_fraction,
1287					},
1288				);
1289
1290				OffenceQueueEras::<T>::mutate(|q| {
1291					if let Some(eras) = q {
1292						log!(debug, "🦹 inserting offence era {} into existing queue", offence_era);
1293						eras.binary_search(&offence_era).err().map(|idx| {
1294							eras.try_insert(idx, offence_era).defensive_proof(
1295								"Offence era must be present in the existing queue",
1296							)
1297						});
1298					} else {
1299						let mut eras = WeakBoundedVec::default();
1300						log!(debug, "🦹 inserting offence era {} into empty queue", offence_era);
1301						let _ = eras
1302							.try_push(offence_era)
1303							.defensive_proof("Failed to push offence era into empty queue");
1304						*q = Some(eras);
1305					}
1306				});
1307
1308				log!(
1309					debug,
1310					"🦹 queued slash for {:?}: {:?} (prior: {:?})",
1311					validator,
1312					slash_fraction,
1313					prior_slash_fraction,
1314				);
1315			} else {
1316				log!(
1317					debug,
1318					"🦹 ignored slash for {:?}: {:?} (already slashed in era with prior: {:?})",
1319					validator,
1320					slash_fraction,
1321					prior_slash_fraction,
1322				);
1323			}
1324		}
1325
1326		weight
1327	}
1328
1329	fn weigh_on_new_offences(offence_count: u32) -> Weight {
1330		T::WeightInfo::rc_on_offence(offence_count)
1331	}
1332
1333	fn active_era_start_session_index() -> SessionIndex {
1334		Rotator::<T>::active_era_start_session_index()
1335	}
1336}
1337
1338impl<T: Config> ScoreProvider<T::AccountId> for Pallet<T> {
1339	type Score = VoteWeight;
1340
1341	fn score(who: &T::AccountId) -> Option<Self::Score> {
1342		Self::ledger(Stash(who.clone()))
1343			.ok()
1344			.and_then(|l| {
1345				if Nominators::<T>::contains_key(&l.stash) ||
1346					Validators::<T>::contains_key(&l.stash)
1347				{
1348					Some(l.active)
1349				} else {
1350					None
1351				}
1352			})
1353			.map(|a| {
1354				let issuance = asset::total_issuance::<T>();
1355				T::CurrencyToVote::to_vote(a, issuance)
1356			})
1357	}
1358
1359	#[cfg(feature = "runtime-benchmarks")]
1360	fn set_score_of(who: &T::AccountId, weight: Self::Score) {
1361		// this will clearly results in an inconsistent state, but it should not matter for a
1362		// benchmark.
1363		let active: BalanceOf<T> = weight.try_into().map_err(|_| ()).unwrap();
1364		let mut ledger = match Self::ledger(StakingAccount::Stash(who.clone())) {
1365			Ok(l) => l,
1366			Err(_) => StakingLedger::default_from(who.clone()),
1367		};
1368		ledger.active = active;
1369
1370		<Ledger<T>>::insert(who, ledger);
1371		<Bonded<T>>::insert(who, who);
1372		// we also need to appoint this staker to be validator or nominator, such that their score
1373		// is actually there. Note that `fn score` above checks the role.
1374		<Validators<T>>::insert(who, ValidatorPrefs::default());
1375
1376		// also, we play a trick to make sure that a issuance based-`CurrencyToVote` behaves well:
1377		// This will make sure that total issuance is zero, thus the currency to vote will be a 1-1
1378		// conversion.
1379		let imbalance = asset::burn::<T>(asset::total_issuance::<T>());
1380		// kinda ugly, but gets the job done. The fact that this works here is a HUGE exception.
1381		// Don't try this pattern in other places.
1382		core::mem::forget(imbalance);
1383	}
1384}
1385
1386/// A simple sorted list implementation that does not require any additional pallets. Note, this
1387/// does not provide validators in sorted order. If you desire nominators in a sorted order take
1388/// a look at [`pallet-bags-list`].
1389pub struct UseValidatorsMap<T>(core::marker::PhantomData<T>);
1390impl<T: Config> SortedListProvider<T::AccountId> for UseValidatorsMap<T> {
1391	type Score = BalanceOf<T>;
1392	type Error = ();
1393
1394	/// Returns iterator over voter list, which can have `take` called on it.
1395	fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
1396		Box::new(Validators::<T>::iter().map(|(v, _)| v))
1397	}
1398	fn iter_from(
1399		start: &T::AccountId,
1400	) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
1401		if Validators::<T>::contains_key(start) {
1402			let start_key = Validators::<T>::hashed_key_for(start);
1403			Ok(Box::new(Validators::<T>::iter_from(start_key).map(|(n, _)| n)))
1404		} else {
1405			Err(())
1406		}
1407	}
1408	fn lock() {}
1409	fn unlock() {}
1410	fn count() -> u32 {
1411		Validators::<T>::count()
1412	}
1413	fn contains(id: &T::AccountId) -> bool {
1414		Validators::<T>::contains_key(id)
1415	}
1416	fn on_insert(_: T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1417		// nothing to do on insert.
1418		Ok(())
1419	}
1420	fn get_score(id: &T::AccountId) -> Result<Self::Score, Self::Error> {
1421		Ok(Pallet::<T>::weight_of(id).into())
1422	}
1423	fn on_update(_: &T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1424		// nothing to do on update.
1425		Ok(())
1426	}
1427	fn on_remove(_: &T::AccountId) -> Result<(), Self::Error> {
1428		// nothing to do on remove.
1429		Ok(())
1430	}
1431	fn unsafe_regenerate(
1432		_: impl IntoIterator<Item = T::AccountId>,
1433		_: Box<dyn Fn(&T::AccountId) -> Option<Self::Score>>,
1434	) -> u32 {
1435		// nothing to do upon regenerate.
1436		0
1437	}
1438	#[cfg(feature = "try-runtime")]
1439	fn try_state() -> Result<(), TryRuntimeError> {
1440		Ok(())
1441	}
1442
1443	fn unsafe_clear() {
1444		#[allow(deprecated)]
1445		Validators::<T>::remove_all();
1446	}
1447
1448	#[cfg(feature = "runtime-benchmarks")]
1449	fn score_update_worst_case(_who: &T::AccountId, _is_increase: bool) -> Self::Score {
1450		unimplemented!()
1451	}
1452}
1453
1454/// A simple voter list implementation that does not require any additional pallets. Note, this
1455/// does not provided nominators in sorted ordered. If you desire nominators in a sorted order take
1456/// a look at [`pallet-bags-list].
1457pub struct UseNominatorsAndValidatorsMap<T>(core::marker::PhantomData<T>);
1458impl<T: Config> SortedListProvider<T::AccountId> for UseNominatorsAndValidatorsMap<T> {
1459	type Error = ();
1460	type Score = VoteWeight;
1461
1462	fn iter() -> Box<dyn Iterator<Item = T::AccountId>> {
1463		Box::new(
1464			Validators::<T>::iter()
1465				.map(|(v, _)| v)
1466				.chain(Nominators::<T>::iter().map(|(n, _)| n)),
1467		)
1468	}
1469	fn iter_from(
1470		start: &T::AccountId,
1471	) -> Result<Box<dyn Iterator<Item = T::AccountId>>, Self::Error> {
1472		if Validators::<T>::contains_key(start) {
1473			let start_key = Validators::<T>::hashed_key_for(start);
1474			Ok(Box::new(
1475				Validators::<T>::iter_from(start_key)
1476					.map(|(n, _)| n)
1477					.chain(Nominators::<T>::iter().map(|(x, _)| x)),
1478			))
1479		} else if Nominators::<T>::contains_key(start) {
1480			let start_key = Nominators::<T>::hashed_key_for(start);
1481			Ok(Box::new(Nominators::<T>::iter_from(start_key).map(|(n, _)| n)))
1482		} else {
1483			Err(())
1484		}
1485	}
1486	fn lock() {}
1487	fn unlock() {}
1488	fn count() -> u32 {
1489		Nominators::<T>::count().saturating_add(Validators::<T>::count())
1490	}
1491	fn contains(id: &T::AccountId) -> bool {
1492		Nominators::<T>::contains_key(id) || Validators::<T>::contains_key(id)
1493	}
1494	fn on_insert(_: T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1495		// nothing to do on insert.
1496		Ok(())
1497	}
1498	fn get_score(id: &T::AccountId) -> Result<Self::Score, Self::Error> {
1499		Ok(Pallet::<T>::weight_of(id))
1500	}
1501	fn on_update(_: &T::AccountId, _weight: Self::Score) -> Result<(), Self::Error> {
1502		// nothing to do on update.
1503		Ok(())
1504	}
1505	fn on_remove(_: &T::AccountId) -> Result<(), Self::Error> {
1506		// nothing to do on remove.
1507		Ok(())
1508	}
1509	fn unsafe_regenerate(
1510		_: impl IntoIterator<Item = T::AccountId>,
1511		_: Box<dyn Fn(&T::AccountId) -> Option<Self::Score>>,
1512	) -> u32 {
1513		// nothing to do upon regenerate.
1514		0
1515	}
1516
1517	#[cfg(feature = "try-runtime")]
1518	fn try_state() -> Result<(), TryRuntimeError> {
1519		Ok(())
1520	}
1521
1522	fn unsafe_clear() {
1523		// NOTE: Caller must ensure this doesn't lead to too many storage accesses. This is a
1524		// condition of SortedListProvider::unsafe_clear.
1525		#[allow(deprecated)]
1526		Nominators::<T>::remove_all();
1527		#[allow(deprecated)]
1528		Validators::<T>::remove_all();
1529	}
1530
1531	#[cfg(feature = "runtime-benchmarks")]
1532	fn score_update_worst_case(_who: &T::AccountId, _is_increase: bool) -> Self::Score {
1533		unimplemented!()
1534	}
1535}
1536
1537impl<T: Config> StakingInterface for Pallet<T> {
1538	type AccountId = T::AccountId;
1539	type Balance = BalanceOf<T>;
1540	type CurrencyToVote = T::CurrencyToVote;
1541
1542	fn minimum_nominator_bond() -> Self::Balance {
1543		Self::min_nominator_bond()
1544	}
1545
1546	fn minimum_validator_bond() -> Self::Balance {
1547		Self::min_validator_bond()
1548	}
1549
1550	fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError> {
1551		Self::ledger(Controller(controller.clone()))
1552			.map(|l| l.stash)
1553			.map_err(|e| e.into())
1554	}
1555
1556	fn bonding_duration() -> EraIndex {
1557		T::BondingDuration::get()
1558	}
1559
1560	fn current_era() -> EraIndex {
1561		CurrentEra::<T>::get().unwrap_or(Zero::zero())
1562	}
1563
1564	fn stake(who: &Self::AccountId) -> Result<Stake<BalanceOf<T>>, DispatchError> {
1565		Self::ledger(Stash(who.clone()))
1566			.map(|l| Stake { total: l.total, active: l.active })
1567			.map_err(|e| e.into())
1568	}
1569
1570	fn bond_extra(who: &Self::AccountId, extra: Self::Balance) -> DispatchResult {
1571		Self::bond_extra(RawOrigin::Signed(who.clone()).into(), extra)
1572	}
1573
1574	fn unbond(who: &Self::AccountId, value: Self::Balance) -> DispatchResult {
1575		let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1576		Self::unbond(RawOrigin::Signed(ctrl).into(), value)
1577			.map_err(|with_post| with_post.error)
1578			.map(|_| ())
1579	}
1580
1581	fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult {
1582		// Since virtual stakers are not allowed to compound their rewards as this pallet does not
1583		// manage their locks, we do not allow reward account to be set same as stash. For
1584		// external pallets that manage the virtual bond, they can claim rewards and re-bond them.
1585		ensure!(
1586			!Self::is_virtual_staker(stash) || stash != reward_acc,
1587			Error::<T>::RewardDestinationRestricted
1588		);
1589
1590		let ledger = Self::ledger(Stash(stash.clone()))?;
1591		let _ = ledger
1592			.set_payee(RewardDestination::Account(reward_acc.clone()))
1593			.defensive_proof("ledger was retrieved from storage, thus its bonded; qed.")?;
1594
1595		Ok(())
1596	}
1597
1598	fn chill(who: &Self::AccountId) -> DispatchResult {
1599		// defensive-only: any account bonded via this interface has the stash set as the
1600		// controller, but we have to be sure. Same comment anywhere else that we read this.
1601		let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1602		Self::chill(RawOrigin::Signed(ctrl).into())
1603	}
1604
1605	fn withdraw_unbonded(
1606		who: Self::AccountId,
1607		_num_slashing_spans: u32,
1608	) -> Result<bool, DispatchError> {
1609		let ctrl = Self::bonded(&who).ok_or(Error::<T>::NotStash)?;
1610		Self::withdraw_unbonded(RawOrigin::Signed(ctrl.clone()).into(), 0)
1611			.map(|_| !StakingLedger::<T>::is_bonded(StakingAccount::Controller(ctrl)))
1612			.map_err(|with_post| with_post.error)
1613	}
1614
1615	fn bond(
1616		who: &Self::AccountId,
1617		value: Self::Balance,
1618		payee: &Self::AccountId,
1619	) -> DispatchResult {
1620		Self::bond(
1621			RawOrigin::Signed(who.clone()).into(),
1622			value,
1623			RewardDestination::Account(payee.clone()),
1624		)
1625	}
1626
1627	fn nominate(who: &Self::AccountId, targets: Vec<Self::AccountId>) -> DispatchResult {
1628		let ctrl = Self::bonded(who).ok_or(Error::<T>::NotStash)?;
1629		let targets = targets.into_iter().map(T::Lookup::unlookup).collect::<Vec<_>>();
1630		Self::nominate(RawOrigin::Signed(ctrl).into(), targets)
1631	}
1632
1633	fn desired_validator_count() -> u32 {
1634		ValidatorCount::<T>::get()
1635	}
1636
1637	fn election_ongoing() -> bool {
1638		<T::ElectionProvider as ElectionProvider>::status().is_ok()
1639	}
1640
1641	fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
1642		Self::force_unstake(RawOrigin::Root.into(), who.clone(), 0)
1643	}
1644
1645	fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
1646		ErasStakersPaged::<T>::iter_prefix((era,)).any(|((validator, _), exposure_page)| {
1647			validator == *who || exposure_page.others.iter().any(|i| i.who == *who)
1648		})
1649	}
1650
1651	fn status(
1652		who: &Self::AccountId,
1653	) -> Result<sp_staking::StakerStatus<Self::AccountId>, DispatchError> {
1654		if !StakingLedger::<T>::is_bonded(StakingAccount::Stash(who.clone())) {
1655			return Err(Error::<T>::NotStash.into())
1656		}
1657
1658		let is_validator = Validators::<T>::contains_key(&who);
1659		let is_nominator = Nominators::<T>::get(&who);
1660
1661		use sp_staking::StakerStatus;
1662		match (is_validator, is_nominator.is_some()) {
1663			(false, false) => Ok(StakerStatus::Idle),
1664			(true, false) => Ok(StakerStatus::Validator),
1665			(false, true) => Ok(StakerStatus::Nominator(
1666				is_nominator.expect("is checked above; qed").targets.into_inner(),
1667			)),
1668			(true, true) => {
1669				defensive!("cannot be both validators and nominator");
1670				Err(Error::<T>::BadState.into())
1671			},
1672		}
1673	}
1674
1675	/// Whether `who` is a virtual staker whose funds are managed by another pallet.
1676	///
1677	/// There is an assumption that, this account is keyless and managed by another pallet in the
1678	/// runtime. Hence, it can never sign its own transactions.
1679	fn is_virtual_staker(who: &T::AccountId) -> bool {
1680		frame_system::Pallet::<T>::account_nonce(who).is_zero() &&
1681			VirtualStakers::<T>::contains_key(who)
1682	}
1683
1684	fn slash_reward_fraction() -> Perbill {
1685		SlashRewardFraction::<T>::get()
1686	}
1687
1688	sp_staking::runtime_benchmarks_enabled! {
1689		fn nominations(who: &Self::AccountId) -> Option<Vec<T::AccountId>> {
1690			Nominators::<T>::get(who).map(|n| n.targets.into_inner())
1691		}
1692
1693		fn add_era_stakers(
1694			current_era: &EraIndex,
1695			stash: &T::AccountId,
1696			exposures: Vec<(Self::AccountId, Self::Balance)>,
1697		) {
1698			let others = exposures
1699				.iter()
1700				.map(|(who, value)| crate::IndividualExposure { who: who.clone(), value: *value })
1701				.collect::<Vec<_>>();
1702			let exposure = Exposure { total: Default::default(), own: Default::default(), others };
1703			Eras::<T>::upsert_exposure(*current_era, stash, exposure);
1704		}
1705
1706		fn set_current_era(era: EraIndex) {
1707			CurrentEra::<T>::put(era);
1708		}
1709
1710		fn max_exposure_page_size() -> Page {
1711			T::MaxExposurePageSize::get()
1712		}
1713	}
1714}
1715
1716impl<T: Config> sp_staking::StakingUnchecked for Pallet<T> {
1717	fn migrate_to_virtual_staker(who: &Self::AccountId) -> DispatchResult {
1718		asset::kill_stake::<T>(who)?;
1719		VirtualStakers::<T>::insert(who, ());
1720		Ok(())
1721	}
1722
1723	/// Virtually bonds `keyless_who` to `payee` with `value`.
1724	///
1725	/// The payee must not be the same as the `keyless_who`.
1726	fn virtual_bond(
1727		keyless_who: &Self::AccountId,
1728		value: Self::Balance,
1729		payee: &Self::AccountId,
1730	) -> DispatchResult {
1731		if StakingLedger::<T>::is_bonded(StakingAccount::Stash(keyless_who.clone())) {
1732			return Err(Error::<T>::AlreadyBonded.into())
1733		}
1734
1735		// check if payee not same as who.
1736		ensure!(keyless_who != payee, Error::<T>::RewardDestinationRestricted);
1737
1738		// mark who as a virtual staker.
1739		VirtualStakers::<T>::insert(keyless_who, ());
1740
1741		Self::deposit_event(Event::<T>::Bonded { stash: keyless_who.clone(), amount: value });
1742		let ledger = StakingLedger::<T>::new(keyless_who.clone(), value);
1743
1744		ledger.bond(RewardDestination::Account(payee.clone()))?;
1745
1746		Ok(())
1747	}
1748
1749	/// Only meant to be used in tests.
1750	#[cfg(feature = "runtime-benchmarks")]
1751	fn migrate_to_direct_staker(who: &Self::AccountId) {
1752		assert!(VirtualStakers::<T>::contains_key(who));
1753		let ledger = StakingLedger::<T>::get(Stash(who.clone())).unwrap();
1754		let _ = asset::update_stake::<T>(who, ledger.total)
1755			.expect("funds must be transferred to stash");
1756		VirtualStakers::<T>::remove(who);
1757	}
1758}
1759
1760#[cfg(any(test, feature = "try-runtime"))]
1761impl<T: Config> Pallet<T> {
1762	pub(crate) fn do_try_state(_now: BlockNumberFor<T>) -> Result<(), TryRuntimeError> {
1763		// If the pallet is not initialized (both ActiveEra and CurrentEra are None),
1764		// there's nothing to check, so return early.
1765		if ActiveEra::<T>::get().is_none() && CurrentEra::<T>::get().is_none() {
1766			return Ok(());
1767		}
1768
1769		session_rotation::Rotator::<T>::do_try_state()?;
1770		session_rotation::Eras::<T>::do_try_state()?;
1771
1772		use frame_support::traits::fungible::Inspect;
1773		if T::CurrencyToVote::will_downscale(T::Currency::total_issuance()).map_or(false, |x| x) {
1774			log!(warn, "total issuance will cause T::CurrencyToVote to downscale -- report to maintainers.")
1775		}
1776
1777		Self::check_ledgers()?;
1778		Self::check_bonded_consistency()?;
1779		Self::check_payees()?;
1780		Self::check_paged_exposures()?;
1781		Self::check_count()?;
1782		Self::check_slash_health()?;
1783
1784		Ok(())
1785	}
1786
1787	/// Invariants:
1788	/// * A controller should not be associated with more than one ledger.
1789	/// * A bonded (stash, controller) pair should have only one associated ledger. I.e. if the
1790	///   ledger is bonded by stash, the controller account must not bond a different ledger.
1791	/// * A bonded (stash, controller) pair must have an associated ledger.
1792	///
1793	/// NOTE: these checks result in warnings only. Once
1794	/// <https://github.com/paritytech/polkadot-sdk/issues/3245> is resolved, turn warns into check
1795	/// failures.
1796	fn check_bonded_consistency() -> Result<(), TryRuntimeError> {
1797		use alloc::collections::btree_set::BTreeSet;
1798
1799		let mut count_controller_double = 0;
1800		let mut count_double = 0;
1801		let mut count_none = 0;
1802		// sanity check to ensure that each controller in Bonded storage is associated with only one
1803		// ledger.
1804		let mut controllers = BTreeSet::new();
1805
1806		for (stash, controller) in <Bonded<T>>::iter() {
1807			if !controllers.insert(controller.clone()) {
1808				count_controller_double += 1;
1809			}
1810
1811			match (<Ledger<T>>::get(&stash), <Ledger<T>>::get(&controller)) {
1812				(Some(_), Some(_)) =>
1813				// if stash == controller, it means that the ledger has migrated to
1814				// post-controller. If no migration happened, we expect that the (stash,
1815				// controller) pair has only one associated ledger.
1816					if stash != controller {
1817						count_double += 1;
1818					},
1819				(None, None) => {
1820					count_none += 1;
1821				},
1822				_ => {},
1823			};
1824		}
1825
1826		if count_controller_double != 0 {
1827			log!(
1828				warn,
1829				"a controller is associated with more than one ledger ({} occurrences)",
1830				count_controller_double
1831			);
1832		};
1833
1834		if count_double != 0 {
1835			log!(warn, "single tuple of (stash, controller) pair bonds more than one ledger ({} occurrences)", count_double);
1836		}
1837
1838		if count_none != 0 {
1839			log!(warn, "inconsistent bonded state: (stash, controller) pair missing associated ledger ({} occurrences)", count_none);
1840		}
1841
1842		Ok(())
1843	}
1844
1845	/// Invariants:
1846	/// * A bonded ledger should always have an assigned `Payee`.
1847	/// * The number of entries in `Payee` and of bonded staking ledgers *must* match.
1848	/// * The stash account in the ledger must match that of the bonded account.
1849	fn check_payees() -> Result<(), TryRuntimeError> {
1850		for (stash, _) in Bonded::<T>::iter() {
1851			ensure!(Payee::<T>::get(&stash).is_some(), "bonded ledger does not have payee set");
1852		}
1853
1854		ensure!(
1855			(Ledger::<T>::iter().count() == Payee::<T>::iter().count()) &&
1856				(Ledger::<T>::iter().count() == Bonded::<T>::iter().count()),
1857			"number of entries in payee storage items does not match the number of bonded ledgers",
1858		);
1859
1860		Ok(())
1861	}
1862
1863	/// Invariants:
1864	/// * Number of voters in `VoterList` match that of the number of Nominators and Validators in
1865	/// the system (validator is both voter and target).
1866	/// * Number of targets in `TargetList` matches the number of validators in the system.
1867	/// * Current validator count is bounded by the election provider's max winners.
1868	fn check_count() -> Result<(), TryRuntimeError> {
1869		ensure!(
1870			<T as Config>::VoterList::count() ==
1871				Nominators::<T>::count() + Validators::<T>::count(),
1872			"wrong external count"
1873		);
1874		ensure!(
1875			<T as Config>::TargetList::count() == Validators::<T>::count(),
1876			"wrong external count"
1877		);
1878		let max_validators_bound = crate::MaxWinnersOf::<T>::get();
1879		let max_winners_per_page_bound = crate::MaxWinnersPerPageOf::<T::ElectionProvider>::get();
1880		ensure!(
1881			max_validators_bound >= max_winners_per_page_bound,
1882			"max validators should be higher than per page bounds"
1883		);
1884		ensure!(ValidatorCount::<T>::get() <= max_validators_bound, Error::<T>::TooManyValidators);
1885		Ok(())
1886	}
1887
1888	/// Invariants:
1889	/// * Stake consistency: ledger.total == ledger.active + sum(ledger.unlocking).
1890	/// * The ledger's controller and stash matches the associated `Bonded` tuple.
1891	/// * Staking locked funds for every bonded stash (non virtual stakers) should be the same as
1892	/// its ledger's total.
1893	/// * For virtual stakers, locked funds should be zero and payee should be non-stash account.
1894	/// * Staking ledger and bond are not corrupted.
1895	fn check_ledgers() -> Result<(), TryRuntimeError> {
1896		Bonded::<T>::iter()
1897			.map(|(stash, ctrl)| {
1898				// ensure locks consistency.
1899				if VirtualStakers::<T>::contains_key(stash.clone()) {
1900					ensure!(
1901						asset::staked::<T>(&stash) == Zero::zero(),
1902						"virtual stakers should not have any staked balance"
1903					);
1904					ensure!(
1905						<Bonded<T>>::get(stash.clone()).unwrap() == stash.clone(),
1906						"stash and controller should be same"
1907					);
1908					ensure!(
1909						Ledger::<T>::get(stash.clone()).unwrap().stash == stash,
1910						"ledger corrupted for virtual staker"
1911					);
1912					ensure!(
1913						frame_system::Pallet::<T>::account_nonce(&stash).is_zero(),
1914						"virtual stakers are keyless and should not have any nonce"
1915					);
1916					let reward_destination = <Payee<T>>::get(stash.clone()).unwrap();
1917					if let RewardDestination::Account(payee) = reward_destination {
1918						ensure!(
1919							payee != stash.clone(),
1920							"reward destination should not be same as stash for virtual staker"
1921						);
1922					} else {
1923						return Err(DispatchError::Other(
1924							"reward destination must be of account variant for virtual staker",
1925						));
1926					}
1927				} else {
1928					let integrity = Self::inspect_bond_state(&stash);
1929					if integrity != Ok(LedgerIntegrityState::Ok) {
1930						// NOTE: not using defensive! since we test these cases and it panics them
1931						log!(
1932							error,
1933							"defensive: bonded stash {:?} has inconsistent ledger state: {:?}",
1934							stash,
1935							integrity
1936						);
1937					}
1938				}
1939
1940				Self::ensure_ledger_consistent(&ctrl)?;
1941				Self::ensure_ledger_role_and_min_bond(&ctrl)?;
1942				Ok(())
1943			})
1944			.collect::<Result<Vec<_>, _>>()?;
1945		Ok(())
1946	}
1947
1948	/// Invariants:
1949	/// Nothing to do if ActiveEra is not set.
1950	/// For each page in `ErasStakersPaged`, `page_total` must be set.
1951	/// For each metadata:
1952	/// 	* page_count is correct
1953	/// 	* nominator_count is correct
1954	/// 	* total is own + sum of pages
1955	/// `ErasTotalStake`` must be correct
1956	fn check_paged_exposures() -> Result<(), TryRuntimeError> {
1957		let Some(era) = ActiveEra::<T>::get().map(|a| a.index) else { return Ok(()) };
1958		let overview_and_pages = ErasStakersOverview::<T>::iter_prefix(era)
1959			.map(|(validator, metadata)| {
1960				let pages = ErasStakersPaged::<T>::iter_prefix((era, validator))
1961					.map(|(_idx, page)| page)
1962					.collect::<Vec<_>>();
1963				(metadata, pages)
1964			})
1965			.collect::<Vec<_>>();
1966
1967		ensure!(
1968			overview_and_pages.iter().flat_map(|(_m, pages)| pages).all(|page| {
1969				let expected = page
1970					.others
1971					.iter()
1972					.map(|e| e.value)
1973					.fold(BalanceOf::<T>::zero(), |acc, x| acc + x);
1974				page.page_total == expected
1975			}),
1976			"found wrong page_total"
1977		);
1978
1979		ensure!(
1980			overview_and_pages.iter().all(|(metadata, pages)| {
1981				let page_count_good = metadata.page_count == pages.len() as u32;
1982				let nominator_count_good = metadata.nominator_count ==
1983					pages.iter().map(|p| p.others.len() as u32).fold(0u32, |acc, x| acc + x);
1984				let total_good = metadata.total ==
1985					metadata.own +
1986						pages
1987							.iter()
1988							.fold(BalanceOf::<T>::zero(), |acc, page| acc + page.page_total);
1989
1990				page_count_good && nominator_count_good && total_good
1991			}),
1992			"found bad metadata"
1993		);
1994
1995		ensure!(
1996			overview_and_pages
1997				.iter()
1998				.map(|(metadata, _pages)| metadata.total)
1999				.fold(BalanceOf::<T>::zero(), |acc, x| acc + x) ==
2000				ErasTotalStake::<T>::get(era),
2001			"found bad eras total stake"
2002		);
2003
2004		Ok(())
2005	}
2006
2007	/// Ensures offence pipeline and slashing is in a healthy state.
2008	fn check_slash_health() -> Result<(), TryRuntimeError> {
2009		// (1) Ensure offence queue is sorted
2010		let offence_queue_eras = OffenceQueueEras::<T>::get().unwrap_or_default().into_inner();
2011		let mut sorted_offence_queue_eras = offence_queue_eras.clone();
2012		sorted_offence_queue_eras.sort();
2013		ensure!(
2014			sorted_offence_queue_eras == offence_queue_eras,
2015			"Offence queue eras are not sorted"
2016		);
2017		drop(sorted_offence_queue_eras);
2018
2019		// (2) Ensure oldest offence queue era is old enough.
2020		let active_era = Rotator::<T>::active_era();
2021		let oldest_unprocessed_offence_era =
2022			offence_queue_eras.first().cloned().unwrap_or(active_era);
2023
2024		// how old is the oldest unprocessed offence era?
2025		// given bonding duration = 28, the ideal value is between 0 and 2 eras.
2026		// anything close to bonding duration is terrible.
2027		let oldest_unprocessed_offence_age =
2028			active_era.saturating_sub(oldest_unprocessed_offence_era);
2029
2030		// warn if less than 26 eras old.
2031		if oldest_unprocessed_offence_age > 2.min(T::BondingDuration::get()) {
2032			log!(
2033				warn,
2034				"Offence queue has unprocessed offences from older than 2 eras: oldest offence era in queue {:?} (active era: {:?})",
2035				oldest_unprocessed_offence_era,
2036				active_era
2037			);
2038		}
2039
2040		// error if the oldest unprocessed offence era closer to bonding duration.
2041		ensure!(
2042			oldest_unprocessed_offence_age < T::BondingDuration::get() - 1,
2043			"offences from era less than 3 eras old from active era not processed yet"
2044		);
2045
2046		// (3) Report count of offences in the queue.
2047		for e in offence_queue_eras {
2048			let count = OffenceQueue::<T>::iter_prefix(e).count();
2049			ensure!(count > 0, "Offence queue is empty for era listed in offence queue eras");
2050			log!(info, "Offence queue for era {:?} has {:?} offences queued", e, count);
2051		}
2052
2053		// (4) Ensure all slashes older than (active era - 1) are applied.
2054		// We will look at all eras before the active era as it can take 1 era for slashes
2055		// to be applied.
2056		for era in (active_era.saturating_sub(T::BondingDuration::get()))..(active_era) {
2057			// all unapplied slashes are expected to be applied until the active era. If this is not
2058			// the case, then we need to use a permissionless call to apply all of them.
2059			// See `Call::apply_slash` for more details.
2060			Self::ensure_era_slashes_applied(era)?;
2061		}
2062
2063		// (5) Ensure no canceled slashes exist in the past eras.
2064		for (era, _) in CancelledSlashes::<T>::iter() {
2065			ensure!(era >= active_era, "Found cancelled slashes for era before active era");
2066		}
2067
2068		Ok(())
2069	}
2070
2071	fn ensure_ledger_role_and_min_bond(ctrl: &T::AccountId) -> Result<(), TryRuntimeError> {
2072		let ledger = Self::ledger(StakingAccount::Controller(ctrl.clone()))?;
2073		let stash = ledger.stash;
2074
2075		let is_nominator = Nominators::<T>::contains_key(&stash);
2076		let is_validator = Validators::<T>::contains_key(&stash);
2077
2078		match (is_nominator, is_validator) {
2079			(false, false) => {
2080				if ledger.active < Self::min_chilled_bond() && !ledger.active.is_zero() {
2081					// chilled accounts allow to go to zero and fully unbond ^^^^^^^^^
2082					log!(
2083						warn,
2084						"Chilled stash {:?} has less stake ({:?}) than minimum role bond ({:?})",
2085						stash,
2086						ledger.active,
2087						Self::min_chilled_bond()
2088					);
2089				}
2090				// is chilled
2091			},
2092			(true, false) => {
2093				// Nominators must have a minimum bond.
2094				if ledger.active < Self::min_nominator_bond() {
2095					log!(
2096						warn,
2097						"Nominator {:?} has less stake ({:?}) than minimum role bond ({:?})",
2098						stash,
2099						ledger.active,
2100						Self::min_nominator_bond()
2101					);
2102				}
2103			},
2104			(false, true) => {
2105				// Validators must have a minimum bond.
2106				if ledger.active < Self::min_validator_bond() {
2107					log!(
2108						warn,
2109						"Validator {:?} has less stake ({:?}) than minimum role bond ({:?})",
2110						stash,
2111						ledger.active,
2112						Self::min_validator_bond()
2113					);
2114				}
2115			},
2116			(true, true) => {
2117				ensure!(false, "Stash cannot be both nominator and validator");
2118			},
2119		}
2120		Ok(())
2121	}
2122
2123	fn ensure_ledger_consistent(ctrl: &T::AccountId) -> Result<(), TryRuntimeError> {
2124		// ensures ledger.total == ledger.active + sum(ledger.unlocking).
2125		let ledger = Self::ledger(StakingAccount::Controller(ctrl.clone()))?;
2126
2127		let real_total: BalanceOf<T> =
2128			ledger.unlocking.iter().fold(ledger.active, |a, c| a + c.value);
2129		ensure!(real_total == ledger.total, "ledger.total corrupt");
2130
2131		Ok(())
2132	}
2133}