pallet_staking_async/lib.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//! # Staking Async Pallet
19//!
20//! This pallet is a fork of the original `pallet-staking`, with a number of key differences:
21//!
22//! * It no longer has access to a secure timestamp, previously used to calculate the duration of an
23//! era.
24//! * It no longer has access to a pallet-session.
25//! * It no longer has access to a pallet-authorship.
26//! * It is capable of working with a multi-page `ElectionProvider``, aka.
27//! `pallet-election-provider-multi-block`.
28//!
29//! While `pallet-staking` was somewhat general-purpose, this pallet is absolutely NOT right from
30//! the get-go: It is designed to be used ONLY in Polkadot/Kusama AssetHub system parachains.
31//!
32//! The workings of this pallet can be divided into a number of subsystems, as follows.
33//!
34//! ## User Interactions
35//!
36//! TODO
37//!
38//! ## Session and Era Rotation
39//!
40//! TODO
41//!
42//! ## Exposure Collection
43//!
44//! TODO
45//!
46//! ## Slashing Pipeline and Withdrawal Restrictions
47//!
48//! This pallet implements a robust slashing mechanism that ensures the integrity of the staking
49//! system while preventing stakers from withdrawing funds that might still be subject to slashing.
50//!
51//! ### Overview of the Slashing Pipeline
52//!
53//! The slashing process consists of multiple phases:
54//!
55//! 1. **Offence Reporting**: Offences are reported from the relay chain through `on_new_offences`
56//! 2. **Queuing**: Valid offences are added to the `OffenceQueue` for processing
57//! 3. **Processing**: Offences are processed incrementally over multiple blocks
58//! 4. **Application**: Slashes are either applied immediately or deferred based on configuration
59//!
60//! ### Phase 1: Offence Reporting
61//!
62//! Offences are reported from the relay chain (e.g., from BABE, GRANDPA, BEEFY, or parachain
63//! modules) through the `on_new_offences` function:
64//!
65//! ```text
66//! struct Offence {
67//! offender: AccountId, // The validator being slashed
68//! reporters: Vec<AccountId>, // Who reported the offence (may be empty)
69//! slash_fraction: Perbill, // Percentage of stake to slash
70//! }
71//! ```
72//!
73//! **Reporting Deadlines**:
74//! - With deferred slashing: Offences must be reported within `SlashDeferDuration - 1` eras
75//! - With immediate slashing: Offences can be reported up to `BondingDuration` eras old
76//!
77//! Example: If `SlashDeferDuration = 27` and current era is 100:
78//! - Oldest reportable offence: Era 74 (100 - 26)
79//! - Offences from era 73 or earlier are rejected
80//!
81//! ### Phase 2: Queuing
82//!
83//! When an offence passes validation, it's added to the queue:
84//!
85//! 1. **Storage**: Added to `OffenceQueue`: `(EraIndex, AccountId) -> OffenceRecord`
86//! 2. **Era Tracking**: Era added to `OffenceQueueEras` (sorted vector of eras with offences)
87//! 3. **Duplicate Handling**: If an offence already exists for the same validator in the same era,
88//! only the higher slash fraction is kept
89//!
90//! ### Phase 3: Processing
91//!
92//! Offences are processed incrementally in `on_initialize` each block:
93//!
94//! ```text
95//! 1. Load oldest offence from queue
96//! 2. Move to `ProcessingOffence` storage
97//! 3. For each exposure page (from last to first):
98//! - Calculate slash for validator's own stake
99//! - Calculate slash for each nominator (pro-rata based on exposure)
100//! - Track total slash and reward amounts
101//! 4. Once all pages processed, create `UnappliedSlash`
102//! ```
103//!
104//! **Key Features**:
105//! - **Page-by-page processing**: Large validator sets don't overwhelm a single block
106//! - **Pro-rata slashing**: Nominators slashed proportionally to their stake
107//! - **Reward calculation**: A portion goes to reporters (if any)
108//!
109//! ### Phase 4: Application
110//!
111//! Based on `SlashDeferDuration`, slashes are either:
112//!
113//! **Immediate (SlashDeferDuration = 0)**:
114//! - Applied right away in the same block
115//! - Funds deducted from staking ledger immediately
116//!
117//! **Deferred (SlashDeferDuration > 0)**:
118//! - Stored in `UnappliedSlashes` for future application
119//! - Applied at era: `offence_era + SlashDeferDuration`
120//! - Can be cancelled by governance before application
121//!
122//! ### Storage Items Involved
123//!
124//! - `OffenceQueue`: Pending offences to process
125//! - `OffenceQueueEras`: Sorted list of eras with offences
126//! - `ProcessingOffence`: Currently processing offence
127//! - `ValidatorSlashInEra`: Tracks highest slash per validator per era
128//! - `UnappliedSlashes`: Deferred slashes waiting for application
129//!
130//! ### Withdrawal Restrictions
131//!
132//! To maintain slashing guarantees, withdrawals are restricted:
133//!
134//! **Withdrawal Era Calculation**:
135//! ```text
136//! earliest_era_to_withdraw = min(
137//! active_era,
138//! last_fully_processed_offence_era + BondingDuration
139//! )
140//! ```
141//!
142//! **Example**:
143//! - Active era: 100
144//! - Oldest unprocessed offence: Era 70
145//! - BondingDuration: 28
146//! - Withdrawal allowed only for chunks with era ≤ 97 (70 - 1 + 28)
147//!
148//! **Withdrawal Timeline Example with an Offence**:
149//! ```text
150//! Era: 90 91 92 93 94 95 96 97 98 99 100 ... 117 118
151//! | | | | | | | | | | | | |
152//! Unbond: U
153//! Offence: X
154//! Reported: R
155//! Processed: P (within next few blocks)
156//! Slash Applied: S
157//! Withdraw: ❌ ✓
158//!
159//! With BondingDuration = 28 and SlashDeferDuration = 27:
160//! - User unbonds in era 90
161//! - Offence occurs in era 90
162//! - Reported in era 92 (typically within 2 days, but reportable until Era 116)
163//! - Processed in era 92 (within next few blocks after reporting)
164//! - Slash deferred for 27 eras, applied at era 117 (90 + 27)
165//! - Cannot withdraw unbonded chunks until era 118 (90 + 28)
166//!
167//! The 28-era bonding duration ensures that any offences committed before or during
168//! unbonding have time to be reported, processed, and applied before funds can be
169//! withdrawn. This provides a window for governance to cancel slashes that may have
170//! resulted from software bugs.
171//! ```
172//!
173//! **Key Restrictions**:
174//! 1. Cannot withdraw if previous era has unapplied slashes
175//! 2. Cannot withdraw funds from eras with unprocessed offences
176
177#![cfg_attr(not(feature = "std"), no_std)]
178#![recursion_limit = "256"]
179
180#[cfg(feature = "runtime-benchmarks")]
181pub mod benchmarking;
182#[cfg(any(feature = "runtime-benchmarks", test))]
183pub mod testing_utils;
184
185#[cfg(test)]
186pub(crate) mod mock;
187#[cfg(test)]
188mod tests;
189
190pub mod asset;
191pub mod election_size_tracker;
192pub mod ledger;
193mod pallet;
194pub mod session_rotation;
195pub mod slashing;
196pub mod weights;
197
198extern crate alloc;
199use alloc::{vec, vec::Vec};
200use codec::{Decode, DecodeWithMemTracking, Encode, HasCompact, MaxEncodedLen};
201use frame_election_provider_support::ElectionProvider;
202use frame_support::{
203 traits::{
204 tokens::fungible::{Credit, Debt},
205 ConstU32, Contains, Get, LockIdentifier,
206 },
207 BoundedVec, DebugNoBound, DefaultNoBound, EqNoBound, PartialEqNoBound, WeakBoundedVec,
208};
209use frame_system::pallet_prelude::BlockNumberFor;
210use ledger::LedgerIntegrityState;
211use scale_info::TypeInfo;
212use sp_runtime::{
213 traits::{AtLeast32BitUnsigned, One, StaticLookup, UniqueSaturatedInto},
214 BoundedBTreeMap, Debug, Perbill, Saturating,
215};
216use sp_staking::{EraIndex, ExposurePage, PagedExposureMetadata, SessionIndex};
217pub use sp_staking::{Exposure, IndividualExposure, StakerStatus};
218pub use weights::WeightInfo;
219
220// public exports
221pub use ledger::{StakingLedger, UnlockChunk};
222pub use pallet::{pallet::*, UseNominatorsAndValidatorsMap, UseValidatorsMap};
223
224pub(crate) const STAKING_ID: LockIdentifier = *b"staking ";
225pub(crate) const LOG_TARGET: &str = "runtime::staking-async";
226
227// syntactic sugar for logging.
228#[macro_export]
229macro_rules! log {
230 ($level:tt, $patter:expr $(, $values:expr)* $(,)?) => {
231 log::$level!(
232 target: crate::LOG_TARGET,
233 concat!("[{:?}] 💸 ", $patter), <frame_system::Pallet<T>>::block_number() $(, $values)*
234 )
235 };
236}
237
238/// Alias for a bounded set of exposures behind a validator, parameterized by this pallet's
239/// election provider.
240pub type BoundedExposuresOf<T> = BoundedVec<
241 (
242 <T as frame_system::Config>::AccountId,
243 Exposure<<T as frame_system::Config>::AccountId, BalanceOf<T>>,
244 ),
245 MaxWinnersPerPageOf<<T as Config>::ElectionProvider>,
246>;
247
248/// Alias for the maximum number of winners (aka. active validators), as defined in by this pallet's
249/// config.
250pub type MaxWinnersOf<T> = <T as Config>::MaxValidatorSet;
251
252/// Alias for the maximum number of winners per page, as expected by the election provider.
253pub type MaxWinnersPerPageOf<P> = <P as ElectionProvider>::MaxWinnersPerPage;
254
255/// Maximum number of nominations per nominator.
256pub type MaxNominationsOf<T> =
257 <<T as Config>::NominationsQuota as NominationsQuota<BalanceOf<T>>>::MaxNominations;
258
259/// Counter for the number of "reward" points earned by a given validator.
260pub type RewardPoint = u32;
261
262/// The balance type of this pallet.
263pub type BalanceOf<T> = <T as Config>::CurrencyBalance;
264
265type PositiveImbalanceOf<T> = Debt<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
266pub type NegativeImbalanceOf<T> =
267 Credit<<T as frame_system::Config>::AccountId, <T as Config>::Currency>;
268
269type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
270
271/// Information regarding the active era (era in used in session).
272#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen, PartialEq, Eq, Clone)]
273pub struct ActiveEraInfo {
274 /// Index of era.
275 pub index: EraIndex,
276 /// Moment of start expressed as millisecond from `$UNIX_EPOCH`.
277 ///
278 /// Start can be none if start hasn't been set for the era yet,
279 /// Start is set on the first on_finalize of the era to guarantee usage of `Time`.
280 pub start: Option<u64>,
281}
282
283/// Reward points of an era. Used to split era total payout between validators.
284///
285/// This points will be used to reward validators and their respective nominators.
286#[derive(
287 PartialEqNoBound, Encode, Decode, DebugNoBound, TypeInfo, MaxEncodedLen, DefaultNoBound,
288)]
289#[codec(mel_bound())]
290#[scale_info(skip_type_params(T))]
291pub struct EraRewardPoints<T: Config> {
292 /// Total number of points. Equals the sum of reward points for each validator.
293 pub total: RewardPoint,
294 /// The reward points earned by a given validator.
295 pub individual: BoundedBTreeMap<T::AccountId, RewardPoint, T::MaxValidatorSet>,
296}
297
298/// A destination account for payment.
299#[derive(
300 PartialEq,
301 Eq,
302 Copy,
303 Clone,
304 Encode,
305 Decode,
306 DecodeWithMemTracking,
307 Debug,
308 TypeInfo,
309 MaxEncodedLen,
310)]
311pub enum RewardDestination<AccountId> {
312 /// Pay into the stash account, increasing the amount at stake accordingly.
313 Staked,
314 /// Pay into the stash account, not increasing the amount at stake.
315 Stash,
316 #[deprecated(
317 note = "`Controller` will be removed after January 2024. Use `Account(controller)` instead."
318 )]
319 Controller,
320 /// Pay into a specified account.
321 Account(AccountId),
322 /// Receive no reward.
323 None,
324}
325
326/// Preference of what happens regarding validation.
327#[derive(
328 PartialEq,
329 Eq,
330 Clone,
331 Encode,
332 Decode,
333 DecodeWithMemTracking,
334 Debug,
335 TypeInfo,
336 Default,
337 MaxEncodedLen,
338)]
339pub struct ValidatorPrefs {
340 /// Reward that validator takes up-front; only the rest is split between themselves and
341 /// nominators.
342 #[codec(compact)]
343 pub commission: Perbill,
344 /// Whether or not this validator is accepting more nominations. If `true`, then no nominator
345 /// who is not already nominating this validator may nominate them. By default, validators
346 /// are accepting nominations.
347 pub blocked: bool,
348}
349
350/// Status of a paged snapshot progress.
351#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, Default)]
352pub enum SnapshotStatus<AccountId> {
353 /// Paged snapshot is in progress, the `AccountId` was the last staker iterated in the list.
354 Ongoing(AccountId),
355 /// All the stakers in the system have been consumed since the snapshot started.
356 Consumed,
357 /// Waiting for a new snapshot to be requested.
358 #[default]
359 Waiting,
360}
361
362/// A record of the nominations made by a specific account.
363#[derive(
364 PartialEqNoBound, EqNoBound, Clone, Encode, Decode, DebugNoBound, TypeInfo, MaxEncodedLen,
365)]
366#[codec(mel_bound())]
367#[scale_info(skip_type_params(T))]
368pub struct Nominations<T: Config> {
369 /// The targets of nomination.
370 pub targets: BoundedVec<T::AccountId, MaxNominationsOf<T>>,
371 /// The era the nominations were submitted.
372 ///
373 /// Except for initial nominations which are considered submitted at era 0.
374 pub submitted_in: EraIndex,
375 /// Whether the nominations have been suppressed. This can happen due to slashing of the
376 /// validators, or other events that might invalidate the nomination.
377 ///
378 /// NOTE: this for future proofing and is thus far not used.
379 pub suppressed: bool,
380}
381
382/// Facade struct to encapsulate `PagedExposureMetadata` and a single page of `ExposurePage`.
383///
384/// This is useful where we need to take into account the validator's own stake and total exposure
385/// in consideration, in addition to the individual nominators backing them.
386#[derive(Encode, Decode, Debug, TypeInfo, PartialEq, Eq)]
387pub struct PagedExposure<AccountId, Balance: HasCompact + codec::MaxEncodedLen> {
388 exposure_metadata: PagedExposureMetadata<Balance>,
389 exposure_page: ExposurePage<AccountId, Balance>,
390}
391
392impl<AccountId, Balance: HasCompact + Copy + AtLeast32BitUnsigned + codec::MaxEncodedLen>
393 PagedExposure<AccountId, Balance>
394{
395 /// Create a new instance of `PagedExposure` from legacy clipped exposures.
396 pub fn from_clipped(exposure: Exposure<AccountId, Balance>) -> Self {
397 Self {
398 exposure_metadata: PagedExposureMetadata {
399 total: exposure.total,
400 own: exposure.own,
401 nominator_count: exposure.others.len() as u32,
402 page_count: 1,
403 },
404 exposure_page: ExposurePage { page_total: exposure.total, others: exposure.others },
405 }
406 }
407
408 /// Returns total exposure of this validator across pages
409 pub fn total(&self) -> Balance {
410 self.exposure_metadata.total
411 }
412
413 /// Returns total exposure of this validator for the current page
414 pub fn page_total(&self) -> Balance {
415 self.exposure_page.page_total + self.exposure_metadata.own
416 }
417
418 /// Returns validator's own stake that is exposed
419 pub fn own(&self) -> Balance {
420 self.exposure_metadata.own
421 }
422
423 /// Returns the portions of nominators stashes that are exposed in this page.
424 pub fn others(&self) -> &Vec<IndividualExposure<AccountId, Balance>> {
425 &self.exposure_page.others
426 }
427}
428
429/// A pending slash record. The value of the slash has been computed but not applied yet,
430/// rather deferred for several eras.
431#[derive(Encode, Decode, DebugNoBound, TypeInfo, MaxEncodedLen, PartialEqNoBound, EqNoBound)]
432#[scale_info(skip_type_params(T))]
433pub struct UnappliedSlash<T: Config> {
434 /// The stash ID of the offending validator.
435 pub validator: T::AccountId,
436 /// The validator's own slash.
437 pub own: BalanceOf<T>,
438 /// All other slashed stakers and amounts.
439 pub others: WeakBoundedVec<(T::AccountId, BalanceOf<T>), T::MaxExposurePageSize>,
440 /// Reporters of the offence; bounty payout recipients.
441 pub reporter: Option<T::AccountId>,
442 /// The amount of payout.
443 pub payout: BalanceOf<T>,
444}
445
446/// Something that defines the maximum number of nominations per nominator based on a curve.
447///
448/// The method `curve` implements the nomination quota curve and should not be used directly.
449/// However, `get_quota` returns the bounded maximum number of nominations based on `fn curve` and
450/// the nominator's balance.
451pub trait NominationsQuota<Balance> {
452 /// Strict maximum number of nominations that caps the nominations curve. This value can be
453 /// used as the upper bound of the number of votes per nominator.
454 type MaxNominations: Get<u32>;
455
456 /// Returns the voter's nomination quota within reasonable bounds [`min`, `max`], where `min`
457 /// is 1 and `max` is `Self::MaxNominations`.
458 fn get_quota(balance: Balance) -> u32 {
459 Self::curve(balance).clamp(1, Self::MaxNominations::get())
460 }
461
462 /// Returns the voter's nomination quota based on its balance and a curve.
463 fn curve(balance: Balance) -> u32;
464}
465
466/// A nomination quota that allows up to MAX nominations for all validators.
467pub struct FixedNominationsQuota<const MAX: u32>;
468impl<Balance, const MAX: u32> NominationsQuota<Balance> for FixedNominationsQuota<MAX> {
469 type MaxNominations = ConstU32<MAX>;
470
471 fn curve(_: Balance) -> u32 {
472 MAX
473 }
474}
475
476/// Handler for determining how much of a balance should be paid out on the current era.
477pub trait EraPayout<Balance> {
478 /// Determine the payout for this era.
479 ///
480 /// Returns the amount to be paid to stakers in this era, as well as whatever else should be
481 /// paid out ("the rest").
482 fn era_payout(
483 total_staked: Balance,
484 total_issuance: Balance,
485 era_duration_millis: u64,
486 ) -> (Balance, Balance);
487}
488
489impl<Balance: Default> EraPayout<Balance> for () {
490 fn era_payout(
491 _total_staked: Balance,
492 _total_issuance: Balance,
493 _era_duration_millis: u64,
494 ) -> (Balance, Balance) {
495 (Default::default(), Default::default())
496 }
497}
498
499/// Mode of era-forcing.
500#[derive(
501 Copy,
502 Clone,
503 PartialEq,
504 Eq,
505 Encode,
506 Decode,
507 DecodeWithMemTracking,
508 Debug,
509 TypeInfo,
510 MaxEncodedLen,
511 serde::Serialize,
512 serde::Deserialize,
513)]
514pub enum Forcing {
515 /// Not forcing anything - just let whatever happen.
516 NotForcing,
517 /// Force a new era, then reset to `NotForcing` as soon as it is done.
518 /// Note that this will force to trigger an election until a new era is triggered, if the
519 /// election failed, the next session end will trigger a new election again, until success.
520 ForceNew,
521 /// Avoid a new era indefinitely.
522 ForceNone,
523 /// Force a new era at the end of all sessions indefinitely.
524 ForceAlways,
525}
526
527impl Default for Forcing {
528 fn default() -> Self {
529 Forcing::NotForcing
530 }
531}
532
533/// A utility struct that provides a way to check if a given account is a staker.
534///
535/// This struct implements the `Contains` trait, allowing it to determine whether
536/// a particular account is currently staking by checking if the account exists in
537/// the staking ledger.
538///
539/// Intended to be used in [`crate::Config::Filter`].
540pub struct AllStakers<T: Config>(core::marker::PhantomData<T>);
541
542impl<T: Config> Contains<T::AccountId> for AllStakers<T> {
543 /// Checks if the given account ID corresponds to a staker.
544 ///
545 /// # Returns
546 /// - `true` if the account has an entry in the staking ledger (indicating it is staking).
547 /// - `false` otherwise.
548 fn contains(account: &T::AccountId) -> bool {
549 Ledger::<T>::contains_key(account)
550 }
551}
552
553/// A smart type to determine the [`Config::PlanningEraOffset`], given:
554///
555/// * Expected relay session duration, `RS`
556/// * Time taking into consideration for XCM sending, `S`
557///
558/// It will use the estimated election duration, the relay session duration, and add one as it knows
559/// the relay chain will want to buffer validators for one session. This is needed because we use
560/// this in our calculation based on the "active era".
561pub struct PlanningEraOffsetOf<T, RS, S>(core::marker::PhantomData<(T, RS, S)>);
562impl<T: Config, RS: Get<BlockNumberFor<T>>, S: Get<BlockNumberFor<T>>> Get<SessionIndex>
563 for PlanningEraOffsetOf<T, RS, S>
564{
565 fn get() -> SessionIndex {
566 let election_duration = <T::ElectionProvider as ElectionProvider>::duration_with_export();
567 let sessions_needed = (election_duration + S::get()) / RS::get();
568 // add one, because we know the RC session pallet wants to buffer for one session, and
569 // another one cause we will receive activation report one session after that.
570 sessions_needed
571 .saturating_add(One::one())
572 .saturating_add(One::one())
573 .unique_saturated_into()
574 }
575}