[NPoS] Paging reward payouts in order to scale rewardable nominators (#1189)

helps https://github.com/paritytech/polkadot-sdk/issues/439.
closes https://github.com/paritytech/polkadot-sdk/issues/473.

PR link in the older substrate repository:
https://github.com/paritytech/substrate/pull/13498.

# Context
Rewards payout is processed today in a single block and limited to
`MaxNominatorRewardedPerValidator`. This number is currently 512 on both
Kusama and Polkadot.

This PR tries to scale the nominators payout to an unlimited count in a
multi-block fashion. Exposures are stored in pages, with each page
capped to a certain number (`MaxExposurePageSize`). Starting out, this
number would be the same as `MaxNominatorRewardedPerValidator`, but
eventually, this number can be lowered through new runtime upgrades to
limit the rewardeable nominators per dispatched call instruction.

The changes in the PR are backward compatible.

## How payouts would work like after this change
Staking exposes two calls, 1) the existing `payout_stakers` and 2)
`payout_stakers_by_page`.

### payout_stakers
This remains backward compatible with no signature change. If for a
given era a validator has multiple pages, they can call `payout_stakers`
multiple times. The pages are executed in an ascending sequence and the
runtime takes care of preventing double claims.

### payout_stakers_by_page
Very similar to `payout_stakers` but also accepts an extra param
`page_index`. An account can choose to payout rewards only for an
explicitly passed `page_index`.

**Lets look at an example scenario**
Given an active validator on Kusama had 1100 nominators,
`MaxExposurePageSize` set to 512 for Era e. In order to pay out rewards
to all nominators, the caller would need to call `payout_stakers` 3
times.

- `payout_stakers(origin, stash, e)` => will pay the first 512
nominators.
- `payout_stakers(origin, stash, e)` => will pay the second set of 512
nominators.
- `payout_stakers(origin, stash, e)` => will pay the last set of 76
nominators.
...
- `payout_stakers(origin, stash, e)` => calling it the 4th time would
return an error `InvalidPage`.

The above calls can also be replaced by `payout_stakers_by_page` and
passing a `page_index` explicitly.

## Commission note
Validator commission is paid out in chunks across all the pages where
each commission chunk is proportional to the total stake of the current
page. This implies higher the total stake of a page, higher will be the
commission. If all the pages of a validator's single era are paid out,
the sum of commission paid to the validator across all pages should be
equal to what the commission would have been if we had a non-paged
exposure.

### Migration Note
Strictly speaking, we did not need to bump our storage version since
there is no migration of storage in this PR. But it is still useful to
mark a storage upgrade for the following reasons:

- New storage items are introduced in this PR while some older storage
items are deprecated.
- For the next `HistoryDepth` eras, the exposure would be incrementally
migrated to its corresponding paged storage item.
- Runtimes using staking pallet would strictly need to wait at least
`HistoryDepth` eras with current upgraded version (14) for the migration
to complete. At some era `E` such that `E >
era_at_which_V14_gets_into_effect + HistoryDepth`, we will upgrade to
version X which will remove the deprecated storage items.
In other words, it is a strict requirement that E<sub>x</sub> -
E<sub>14</sub> > `HistoryDepth`, where
E<sub>x</sub> = Era at which deprecated storages are removed from
runtime,
E<sub>14</sub> = Era at which runtime is upgraded to version 14.
- For Polkadot and Kusama, there is a [tracker
ticket](https://github.com/paritytech/polkadot-sdk/issues/433) to clean
up the deprecated storage items.

### Storage Changes

#### Added
- ErasStakersOverview
- ClaimedRewards
- ErasStakersPaged

#### Deprecated
The following can be cleaned up after 84 eras which is tracked
[here](https://github.com/paritytech/polkadot-sdk/issues/433).

- ErasStakers.
- ErasStakersClipped.
- StakingLedger.claimed_rewards, renamed to
StakingLedger.legacy_claimed_rewards.

### Config Changes
- Renamed MaxNominatorRewardedPerValidator to MaxExposurePageSize.

### TODO
- [x] Tracker ticket for cleaning up the old code after 84 eras.
- [x] Add companion.
- [x] Redo benchmarks before merge.
- [x] Add Changelog for pallet_staking.
- [x] Pallet should be configurable to enable/disable paged rewards.
- [x] Commission payouts are distributed across pages.
- [x] Review documentation thoroughly.
- [x] Rename `MaxNominatorRewardedPerValidator` ->
`MaxExposurePageSize`.
- [x] NMap for `ErasStakersPaged`.
- [x] Deprecate ErasStakers.
- [x] Integrity tests.

### Followup issues
[Runtime api for deprecated ErasStakers storage
item](https://github.com/paritytech/polkadot-sdk/issues/426)

---------

Co-authored-by: Javier Viola <javier@parity.io>
Co-authored-by: Ross Bulat <ross@parity.io>
Co-authored-by: command-bot <>
This commit is contained in:
Ankan
2023-11-01 15:21:44 +01:00
committed by GitHub
parent f50054cffb
commit 00b85c51df
37 changed files with 3480 additions and 2194 deletions
+137 -91
View File
@@ -27,8 +27,8 @@ use frame_support::{
dispatch::WithPostDispatchInfo,
pallet_prelude::*,
traits::{
Currency, Defensive, DefensiveResult, EstimateNextNewSession, Get, Imbalance, OnUnbalanced,
TryCollect, UnixTime,
Currency, Defensive, EstimateNextNewSession, Get, Imbalance, Len, OnUnbalanced, TryCollect,
UnixTime,
},
weights::Weight,
};
@@ -41,7 +41,7 @@ use sp_runtime::{
use sp_staking::{
currency_to_vote::CurrencyToVote,
offence::{DisableStrategy, OffenceDetails, OnOffenceHandler},
EraIndex, SessionIndex, Stake,
EraIndex, Page, SessionIndex, Stake,
StakingAccount::{self, Controller, Stash},
StakingInterface,
};
@@ -49,9 +49,9 @@ use sp_std::prelude::*;
use crate::{
election_size_tracker::StaticTracker, log, slashing, weights::WeightInfo, ActiveEraInfo,
BalanceOf, EraPayout, Exposure, ExposureOf, Forcing, IndividualExposure, MaxNominationsOf,
MaxWinnersOf, Nominations, NominationsQuota, PositiveImbalanceOf, RewardDestination,
SessionInterface, StakingLedger, ValidatorPrefs,
BalanceOf, EraInfo, EraPayout, Exposure, ExposureOf, Forcing, IndividualExposure,
MaxNominationsOf, MaxWinnersOf, Nominations, NominationsQuota, PositiveImbalanceOf,
RewardDestination, SessionInterface, StakingLedger, ValidatorPrefs,
};
use super::pallet::*;
@@ -158,12 +158,31 @@ impl<T: Config> Pallet<T> {
pub(super) fn do_payout_stakers(
validator_stash: T::AccountId,
era: EraIndex,
) -> DispatchResultWithPostInfo {
let controller = Self::bonded(&validator_stash).ok_or_else(|| {
Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
})?;
let ledger = <Ledger<T>>::get(&controller).ok_or(Error::<T>::NotController)?;
let page = EraInfo::<T>::get_next_claimable_page(era, &validator_stash, &ledger)
.ok_or_else(|| {
Error::<T>::AlreadyClaimed
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
})?;
Self::do_payout_stakers_by_page(validator_stash, era, page)
}
pub(super) fn do_payout_stakers_by_page(
validator_stash: T::AccountId,
era: EraIndex,
page: Page,
) -> DispatchResultWithPostInfo {
// Validate input data
let current_era = CurrentEra::<T>::get().ok_or_else(|| {
Error::<T>::InvalidEraToReward
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
})?;
let history_depth = T::HistoryDepth::get();
ensure!(
era <= current_era && era >= current_era.saturating_sub(history_depth),
@@ -171,8 +190,13 @@ impl<T: Config> Pallet<T> {
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
);
ensure!(
page < EraInfo::<T>::get_page_count(era, &validator_stash),
Error::<T>::InvalidPage.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
);
// Note: if era has no reward to be claimed, era may be future. better not to update
// `ledger.claimed_rewards` in this case.
// `ledger.legacy_claimed_rewards` in this case.
let era_payout = <ErasValidatorReward<T>>::get(&era).ok_or_else(|| {
Error::<T>::InvalidEraToReward
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
@@ -186,31 +210,29 @@ impl<T: Config> Pallet<T> {
Err(Error::<T>::NotStash.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
}
})?;
// clean up older claimed rewards
ledger
.legacy_claimed_rewards
.retain(|&x| x >= current_era.saturating_sub(history_depth));
ledger.clone().update()?;
let stash = ledger.stash.clone();
ledger
.claimed_rewards
.retain(|&x| x >= current_era.saturating_sub(history_depth));
match ledger.claimed_rewards.binary_search(&era) {
Ok(_) =>
return Err(Error::<T>::AlreadyClaimed
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))),
Err(pos) => ledger
.claimed_rewards
.try_insert(pos, era)
// Since we retain era entries in `claimed_rewards` only upto
// `HistoryDepth`, following bound is always expected to be
// satisfied.
.defensive_map_err(|_| Error::<T>::BoundNotMet)?,
if EraInfo::<T>::is_rewards_claimed_with_legacy_fallback(era, &ledger, &stash, page) {
return Err(Error::<T>::AlreadyClaimed
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))
} else {
EraInfo::<T>::set_rewards_as_claimed(era, &stash, page);
}
let exposure = <ErasStakersClipped<T>>::get(&era, &stash);
let exposure = EraInfo::<T>::get_paged_exposure(era, &stash, page).ok_or_else(|| {
Error::<T>::InvalidEraToReward
.with_weight(T::WeightInfo::payout_stakers_alive_staked(0))
})?;
// Input data seems good, no errors allowed after this point
ledger.update()?;
// Get Era reward points. It has TOTAL and INDIVIDUAL
// Find the fraction of the era reward that belongs to the validator
// Take that fraction of the eras rewards to split to nominator and validator
@@ -236,15 +258,17 @@ impl<T: Config> Pallet<T> {
// This is how much validator + nominators are entitled to.
let validator_total_payout = validator_total_reward_part * era_payout;
let validator_prefs = Self::eras_validator_prefs(&era, &validator_stash);
// Validator first gets a cut off the top.
let validator_commission = validator_prefs.commission;
let validator_commission_payout = validator_commission * validator_total_payout;
let validator_commission = EraInfo::<T>::get_validator_commission(era, &ledger.stash);
// total commission validator takes across all nominator pages
let validator_total_commission_payout = validator_commission * validator_total_payout;
let validator_leftover_payout = validator_total_payout - validator_commission_payout;
let validator_leftover_payout = validator_total_payout - validator_total_commission_payout;
// Now let's calculate how this is split to the validator.
let validator_exposure_part = Perbill::from_rational(exposure.own, exposure.total);
let validator_exposure_part = Perbill::from_rational(exposure.own(), exposure.total());
let validator_staking_payout = validator_exposure_part * validator_leftover_payout;
let page_stake_part = Perbill::from_rational(exposure.page_total(), exposure.total());
// validator commission is paid out in fraction across pages proportional to the page stake.
let validator_commission_payout = page_stake_part * validator_total_commission_payout;
Self::deposit_event(Event::<T>::PayoutStarted {
era_index: era,
@@ -267,8 +291,8 @@ impl<T: Config> Pallet<T> {
// Lets now calculate how this is split to the nominators.
// Reward only the clipped exposures. Note this is not necessarily sorted.
for nominator in exposure.others.iter() {
let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total);
for nominator in exposure.others().iter() {
let nominator_exposure_part = Perbill::from_rational(nominator.value, exposure.total());
let nominator_reward: BalanceOf<T> =
nominator_exposure_part * validator_leftover_payout;
@@ -287,7 +311,8 @@ impl<T: Config> Pallet<T> {
}
T::Reward::on_unbalanced(total_imbalance);
debug_assert!(nominator_payout_count <= T::MaxNominatorRewardedPerValidator::get());
debug_assert!(nominator_payout_count <= T::MaxExposurePageSize::get());
Ok(Some(T::WeightInfo::payout_stakers_alive_staked(nominator_payout_count)).into())
}
@@ -306,6 +331,11 @@ impl<T: Config> Pallet<T> {
stash: &T::AccountId,
amount: BalanceOf<T>,
) -> Option<(PositiveImbalanceOf<T>, RewardDestination<T::AccountId>)> {
// noop if amount is zero
if amount.is_zero() {
return None
}
let dest = Self::payee(StakingAccount::Stash(stash.clone()));
let maybe_imbalance = match dest {
RewardDestination::Controller => Self::bonded(stash)
@@ -587,31 +617,24 @@ impl<T: Config> Pallet<T> {
>,
new_planned_era: EraIndex,
) -> BoundedVec<T::AccountId, MaxWinnersOf<T>> {
let elected_stashes: BoundedVec<_, MaxWinnersOf<T>> = exposures
.iter()
.cloned()
.map(|(x, _)| x)
.collect::<Vec<_>>()
.try_into()
.expect("since we only map through exposures, size of elected_stashes is always same as exposures; qed");
// Populate stakers, exposures, and the snapshot of validator prefs.
// Populate elected stash, stakers, exposures, and the snapshot of validator prefs.
let mut total_stake: BalanceOf<T> = Zero::zero();
exposures.into_iter().for_each(|(stash, exposure)| {
total_stake = total_stake.saturating_add(exposure.total);
<ErasStakers<T>>::insert(new_planned_era, &stash, &exposure);
let mut elected_stashes = Vec::with_capacity(exposures.len());
let mut exposure_clipped = exposure;
let clipped_max_len = T::MaxNominatorRewardedPerValidator::get() as usize;
if exposure_clipped.others.len() > clipped_max_len {
exposure_clipped.others.sort_by(|a, b| a.value.cmp(&b.value).reverse());
exposure_clipped.others.truncate(clipped_max_len);
}
<ErasStakersClipped<T>>::insert(&new_planned_era, &stash, exposure_clipped);
exposures.into_iter().for_each(|(stash, exposure)| {
// build elected stash
elected_stashes.push(stash.clone());
// accumulate total stake
total_stake = total_stake.saturating_add(exposure.total);
// store staker exposure for this era
EraInfo::<T>::set_exposure(new_planned_era, &stash, exposure);
});
// Insert current era staking information
<ErasTotalStake<T>>::insert(&new_planned_era, total_stake);
let elected_stashes: BoundedVec<_, MaxWinnersOf<T>> = elected_stashes
.try_into()
.expect("elected_stashes.len() always equal to exposures.len(); qed");
EraInfo::<T>::set_total_stake(new_planned_era, total_stake);
// Collect the pref of all winners.
for stash in &elected_stashes {
@@ -692,12 +715,21 @@ impl<T: Config> Pallet<T> {
/// Clear all era information for given era.
pub(crate) fn clear_era_information(era_index: EraIndex) {
// FIXME: We can possibly set a reasonable limit since we do this only once per era and
// clean up state across multiple blocks.
let mut cursor = <ErasStakers<T>>::clear_prefix(era_index, u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
cursor = <ErasStakersClipped<T>>::clear_prefix(era_index, u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
cursor = <ErasValidatorPrefs<T>>::clear_prefix(era_index, u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
cursor = <ClaimedRewards<T>>::clear_prefix(era_index, u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
cursor = <ErasStakersPaged<T>>::clear_prefix((era_index,), u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
cursor = <ErasStakersOverview<T>>::clear_prefix(era_index, u32::MAX, None);
debug_assert!(cursor.maybe_cursor.is_none());
<ErasValidatorReward<T>>::remove(era_index);
<ErasRewardPoints<T>>::remove(era_index);
<ErasTotalStake<T>>::remove(era_index);
@@ -1036,6 +1068,18 @@ impl<T: Config> Pallet<T> {
DispatchClass::Mandatory,
);
}
/// Returns full exposure of a validator for a given era.
///
/// History note: This used to be a getter for old storage item `ErasStakers` deprecated in v14.
/// Since this function is used in the codebase at various places, we kept it as a custom getter
/// that takes care of getting the full exposure of the validator in a backward compatible way.
pub fn eras_stakers(
era: EraIndex,
account: &T::AccountId,
) -> Exposure<T::AccountId, BalanceOf<T>> {
EraInfo::<T>::get_full_exposure(era, account)
}
}
impl<T: Config> Pallet<T> {
@@ -1045,6 +1089,17 @@ impl<T: Config> Pallet<T> {
pub fn api_nominations_quota(balance: BalanceOf<T>) -> u32 {
T::NominationsQuota::get_quota(balance)
}
pub fn api_eras_stakers(
era: EraIndex,
account: T::AccountId,
) -> Exposure<T::AccountId, BalanceOf<T>> {
Self::eras_stakers(era, &account)
}
pub fn api_eras_stakers_page_count(era: EraIndex, account: T::AccountId) -> Page {
EraInfo::<T>::get_page_count(era, &account)
}
}
impl<T: Config> ElectionDataProvider for Pallet<T> {
@@ -1129,10 +1184,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
});
<Bonded<T>>::insert(voter.clone(), voter.clone());
<Ledger<T>>::insert(
voter.clone(),
StakingLedger::<T>::new(voter.clone(), stake, Default::default()),
);
<Ledger<T>>::insert(voter.clone(), StakingLedger::<T>::new(voter.clone(), stake));
Self::do_add_nominator(&voter, Nominations { targets, submitted_in: 0, suppressed: false });
}
@@ -1141,10 +1193,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
fn add_target(target: T::AccountId) {
let stake = MinValidatorBond::<T>::get() * 100u32.into();
<Bonded<T>>::insert(target.clone(), target.clone());
<Ledger<T>>::insert(
target.clone(),
StakingLedger::<T>::new(target.clone(), stake, Default::default()),
);
<Ledger<T>>::insert(target.clone(), StakingLedger::<T>::new(target.clone(), stake));
Self::do_add_validator(
&target,
ValidatorPrefs { commission: Perbill::zero(), blocked: false },
@@ -1176,10 +1225,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
.and_then(|w| <BalanceOf<T>>::try_from(w).ok())
.unwrap_or_else(|| MinNominatorBond::<T>::get() * 100u32.into());
<Bonded<T>>::insert(v.clone(), v.clone());
<Ledger<T>>::insert(
v.clone(),
StakingLedger::<T>::new(v.clone(), stake, Default::default()),
);
<Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
Self::do_add_validator(
&v,
ValidatorPrefs { commission: Perbill::zero(), blocked: false },
@@ -1191,10 +1237,7 @@ impl<T: Config> ElectionDataProvider for Pallet<T> {
panic!("cannot convert a VoteWeight into BalanceOf, benchmark needs reconfiguring.")
});
<Bonded<T>>::insert(v.clone(), v.clone());
<Ledger<T>>::insert(
v.clone(),
StakingLedger::<T>::new(v.clone(), stake, Default::default()),
);
<Ledger<T>>::insert(v.clone(), StakingLedger::<T>::new(v.clone(), stake));
Self::do_add_nominator(
&v,
Nominations { targets: t, submitted_in: 0, suppressed: false },
@@ -1622,31 +1665,12 @@ impl<T: Config> StakingInterface for Pallet<T> {
MinValidatorBond::<T>::get()
}
fn desired_validator_count() -> u32 {
ValidatorCount::<T>::get()
}
fn election_ongoing() -> bool {
T::ElectionProvider::ongoing()
}
fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
let num_slashing_spans = Self::slashing_spans(&who).map_or(0, |s| s.iter().count() as u32);
Self::force_unstake(RawOrigin::Root.into(), who.clone(), num_slashing_spans)
}
fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError> {
Self::ledger(Controller(controller.clone()))
.map(|l| l.stash)
.map_err(|e| e.into())
}
fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
ErasStakers::<T>::iter_prefix(era).any(|(validator, exposures)| {
validator == *who || exposures.others.iter().any(|i| i.who == *who)
})
}
fn bonding_duration() -> EraIndex {
T::BondingDuration::get()
}
@@ -1707,6 +1731,24 @@ impl<T: Config> StakingInterface for Pallet<T> {
Self::nominate(RawOrigin::Signed(ctrl).into(), targets)
}
fn desired_validator_count() -> u32 {
ValidatorCount::<T>::get()
}
fn election_ongoing() -> bool {
T::ElectionProvider::ongoing()
}
fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult {
let num_slashing_spans = Self::slashing_spans(&who).map_or(0, |s| s.iter().count() as u32);
Self::force_unstake(RawOrigin::Root.into(), who.clone(), num_slashing_spans)
}
fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool {
ErasStakers::<T>::iter_prefix(era).any(|(validator, exposures)| {
validator == *who || exposures.others.iter().any(|i| i.who == *who)
})
}
fn status(
who: &Self::AccountId,
) -> Result<sp_staking::StakerStatus<Self::AccountId>, DispatchError> {
@@ -1746,12 +1788,16 @@ impl<T: Config> StakingInterface for Pallet<T> {
.map(|(who, value)| IndividualExposure { who: who.clone(), value: value.clone() })
.collect::<Vec<_>>();
let exposure = Exposure { total: Default::default(), own: Default::default(), others };
<ErasStakers<T>>::insert(&current_era, &stash, &exposure);
EraInfo::<T>::set_exposure(*current_era, stash, exposure);
}
fn set_current_era(era: EraIndex) {
CurrentEra::<T>::put(era);
}
fn max_exposure_page_size() -> Page {
T::MaxExposurePageSize::get()
}
}
}