* Implements dynamic nominations per nominator * Adds SnapshotBounds and ElectionSizeTracker * Changes the ElectionDataProvider interface to receive ElectionBounds as input * Implements get_npos_voters with ElectionBounds * Implements get_npos_targets with ElectionBounds * Adds comments * tests * Truncates nomninations that exceed nominations quota; Old tests passing * Uses DataProviderBounds and ElectionBounds (to continue) * Finishes conversions - tests passing * Refactor staking in babe mocks * Replaces MaxElectableTargets and MaxElectingVoters with ElectionBounds; Adds more tests * Fixes nits; node compiling * bechmarks * removes nomination_quota extrinsic to request the nomination quota * Lazy quota check, ie. at nominate time only * remove non-working test (for now) * tests lazy nominations quota when quota is lower than current number of nominated targets * Adds runtime API and custom RPC call for clients to query the nominations quota for a given balance * removes old rpc * Cosmetic touches * All mocks working * Fixes benchmarking mocks * nits * more tests * renames trait methods * nit * ".git/.scripts/commands/fmt/fmt.sh" * Fix V2 PoV benchmarking (#13485) * Bump default 'additional_trie_layers' to two The default here only works for extremely small runtimes, which have no more than 16 storage prefices. This is changed to a "sane" default of 2, which is save for runtimes with up to 4096 storage prefices (eg StorageValue). Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> * Update tests and test weights Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> * Fix PoV weights Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_balances * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_message_queue * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_glutton * ".git/.scripts/commands/bench/bench.sh" pallet dev pallet_glutton * Fix sanity check >0 would also do as a check, but let's try this. Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> --------- Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> Co-authored-by: command-bot <> * Move BEEFY code to consensus (#13484) * Move beefy primitives to consensus dir * Move beefy gadget to client consensus folder * Rename beefy crates * chore: move genesis block builder to chain-spec crate. (#13427) * chore: move genesis block builder to block builder crate. * add missing file * chore: move genesis block builder to sc-chain-spec * Update client/chain-spec/src/genesis.rs Co-authored-by: Bastian Köcher <git@kchr.de> * Update test-utils/runtime/src/genesismap.rs Co-authored-by: Bastian Köcher <git@kchr.de> * Update test-utils/runtime/client/src/lib.rs * fix warnings * fix warnings --------- Co-authored-by: Bastian Köcher <git@kchr.de> * Speed up storage iteration from within the runtime (#13479) * Speed up storage iteration from within the runtime * Move the cached iterator into an `Option` * Use `RefCell` in no_std * Simplify the code slightly * Use `Option::replace` * Update doc comment for `next_storage_key_slow` * Make unbounded channels size warning exact (part 1) (#13490) * Replace `futures-channel` with `async-channel` in `out_events` * Apply suggestions from code review Co-authored-by: Koute <koute@users.noreply.github.com> * Also print the backtrace of `send()` call * Switch from `backtrace` crate to `std::backtrace` * Remove outdated `backtrace` dependency * Remove `backtrace` from `Cargo.lock` --------- Co-authored-by: Koute <koute@users.noreply.github.com> * Removal of Prometheus alerting rules deployment in cloud-infra (#13499) * sp-consensus: remove unused error variants (#13495) * Expose `ChargedAmount` (#13488) * Expose `ChargedAmount` * Fix imports * sc-consensus-beefy: fix metrics: use correct names (#13494) Signed-off-by: acatangiu <adrian@parity.io> * clippy fix * removes NominationsQuotaExceeded event * Update frame/staking/src/lib.rs Co-authored-by: Ross Bulat <ross@parity.io> * adds back the npos_max_iter * remove duplicate imports added after merge * fmt * Adds comment in public struct; Refactors CountBound and SizeCount to struct * addresses various pr comments * PR comment reviews * Fixes on-chain election bounds and related code * EPM checks the size of the voter list returned by the data provider * cosmetic changes * updates e2e tests mock * Adds more tests for size tracker and refactors code * Adds back only_iterates_max_2_times_max_allowed_len test * Refactor * removes unecessary dependency * empty commit -- restart all stuck CI jobs * restarts ci jobs * Renames ElectionBounds -> Bounds in benchmarking mocks et al * updates mocks * Update frame/election-provider-support/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Update frame/staking/src/pallet/impls.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Update frame/election-provider-support/src/lib.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * Update frame/staking/src/tests.rs Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> * more checks in api_nominations_quota in tests * Improves docs * fixes e2e tests * Uses size_hint rather than mem::size_of in size tracker; Refactor size tracker to own module * nits from reviews * Refactors bounds to own module; improves docs * More tests and docs * fixes docs * Fixes benchmarks * Fixes rust docs * fixes bags-list remote-ext-tests * Simplify bound checks in create_snapshot_external * Adds target size check in get_npos_targets * ".git/.scripts/commands/fmt/fmt.sh" * restart ci * rust doc fixes and cosmetic nits * rollback upgrade on parity-scale-codec version (unecessary) * reset cargo lock, no need to update it --------- Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> Signed-off-by: acatangiu <adrian@parity.io> Co-authored-by: command-bot <> Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> Co-authored-by: Davide Galassi <davxy@datawok.net> Co-authored-by: yjh <yjh465402634@gmail.com> Co-authored-by: Bastian Köcher <git@kchr.de> Co-authored-by: Koute <koute@users.noreply.github.com> Co-authored-by: Dmitry Markin <dmitry@markin.tech> Co-authored-by: Anthony Lazam <lazam@users.noreply.github.com> Co-authored-by: André Silva <123550+andresilva@users.noreply.github.com> Co-authored-by: Piotr Mikołajczyk <piomiko41@gmail.com> Co-authored-by: Adrian Catangiu <adrian@parity.io> Co-authored-by: Ross Bulat <ross@parity.io> Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
Staking Module
The Staking module is used to manage funds at stake by network maintainers.
Overview
The Staking module is the means by which a set of network maintainers (known as authorities in some contexts and validators in others) are chosen based upon those who voluntarily place funds under deposit. Under deposit, those funds are rewarded under normal operation but are held at pain of slash (expropriation) should the staked maintainer be found not to be discharging its duties properly.
Terminology
- Staking: The process of locking up funds for some time, placing them at risk of slashing (loss) in order to become a rewarded maintainer of the network.
- Validating: The process of running a node to actively maintain the network, either by producing blocks or guaranteeing finality of the chain.
- Nominating: The process of placing staked funds behind one or more validators in order to share in any reward, and punishment, they take.
- Stash account: The account holding an owner's funds used for staking.
- Controller account: The account that controls an owner's funds for staking.
- Era: A (whole) number of sessions, which is the period that the validator set (and each validator's active nominator set) is recalculated and where rewards are paid out.
- Slash: The punishment of a staker by reducing its funds.
Goals
The staking system in Substrate NPoS is designed to make the following possible:
- Stake funds that are controlled by a cold wallet.
- Withdraw some, or deposit more, funds without interrupting the role of an entity.
- Switch between roles (nominator, validator, idle) with minimal overhead.
Scenarios
Staking
Almost any interaction with the Staking module requires a process of bonding (also known as being a staker). To become bonded, a fund-holding account known as the stash account, which holds some or all of the funds that become frozen in place as part of the staking process, is paired with an active controller account, which issues instructions on how they shall be used.
An account pair can become bonded using the bond call.
Stash accounts can update their associated controller back to their stash account using the
set_controller
call.
Note: Controller accounts are being deprecated in favor of proxy accounts, so it is no longer possible to set a unique address for a stash's controller.
There are three possible roles that any staked account pair can be in: Validator, Nominator
and Idle (defined in StakerStatus). There are three
corresponding instructions to change between roles, namely:
validate,
nominate, and chill.
Validating
A validator takes the role of either validating blocks or ensuring their finality, maintaining the veracity of the network. A validator should avoid both any sort of malicious misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT get immediately chosen as a validator. Instead, they are declared as a candidate and they might get elected at the next era as a validator. The result of the election is determined by nominators and their votes.
An account can become a validator candidate via the
validate call.
Nomination
A nominator does not take any direct role in maintaining the network, instead, it votes on a set of validators to be elected. Once interest in nomination is stated by an account, it takes effect at the next election round. The funds in the nominator's stash account indicate the weight of its vote. Both the rewards and any punishment that a validator earns are shared between the validator and its nominators. This rule incentivizes the nominators to NOT vote for the misbehaving/offline validators as much as possible, simply because the nominators will also lose funds if they vote poorly.
An account can become a nominator via the nominate call.
Rewards and Slash
The reward and slashing procedure is the core of the Staking module, attempting to embrace valid behavior while punishing any misbehavior or lack of availability.
Rewards must be claimed for each era before it gets too old by $HISTORY_DEPTH using the
payout_stakers call. Any account can call payout_stakers, which pays the reward to the
validator as well as its nominators. Only the [Config::MaxNominatorRewardedPerValidator]
biggest stakers can claim their reward. This is to limit the i/o cost to mutate storage for each
nominator's account.
Slashing can occur at any point in time, once misbehavior is reported. Once slashing is determined, a value is deducted from the balance of the validator and all the nominators who voted for this validator (values are deducted from the stash account of the slashed entity).
Slashing logic is further described in the documentation of the slashing module.
Similar to slashing, rewards are also shared among a validator and its associated nominators. Yet, the reward funds are not always transferred to the stash account and can be configured. See Reward Calculation for more details.
Chilling
Finally, any of the roles above can choose to step back temporarily and just chill for a while. This means that if they are a nominator, they will not be considered as voters anymore and if they are validators, they will no longer be a candidate for the next election.
An account can step back via the chill call.
Session managing
The module implement the trait SessionManager. Which is the only API to query new validator
set and allowing these validator set to be rewarded once their era is ended.
Interface
Dispatchable Functions
The dispatchable functions of the Staking module enable the steps needed for entities to accept and change their role, alongside some helper functions to get/set the metadata of the module.
Public Functions
The Staking module contains many public storage items and (im)mutable functions.
Usage
Example: Rewarding a validator by id.
use pallet_staking::{self as staking};
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + staking::Config {}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Reward a validator.
#[pallet::weight(0)]
pub fn reward_myself(origin: OriginFor<T>) -> DispatchResult {
let reported = ensure_signed(origin)?;
<staking::Pallet<T>>::reward_by_ids(vec![(reported, 10)]);
Ok(())
}
}
}
Implementation Details
Era payout
The era payout is computed using yearly inflation curve defined at
T::RewardCurve as such:
staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year
This payout is used to reward stakers as defined in next section
remaining_payout = max_yearly_inflation * total_tokens / era_per_year - staker_payout
The remaining reward is send to the configurable end-point
T::RewardRemainder.
Reward Calculation
Validators and nominators are rewarded at the end of each era. The total reward of an era is calculated using the era duration and the staking rate (the total amount of tokens staked by nominators and validators, divided by the total token supply). It aims to incentivize toward a defined staking rate. The full specification can be found here.
Total reward is split among validators and their nominators depending on the number of points
they received during the era. Points are added to a validator using
reward_by_ids or
reward_by_indices.
Module implements
pallet_authorship::EventHandler to add reward
points to block producer and block producer of referenced uncles.
The validator and its nominator split their reward as following:
The validator can declare an amount, named
commission, that does not get shared
with the nominators at each reward payout through its
ValidatorPrefs. This value gets deducted from the total reward
that is paid to the validator and its nominators. The remaining portion is split among the
validator and all of the nominators that nominated the validator, proportional to the value
staked behind this validator (i.e. dividing the
own or
others by
total in Exposure).
All entities who receive a reward have the option to choose their reward destination through the
Payee storage item (see
set_payee), to be one of the following:
- Controller account, (obviously) not increasing the staked value.
- Stash account, not increasing the staked value.
- Stash account, also increasing the staked value.
Additional Fund Management Operations
Any funds already placed into stash can be the target of the following operations:
The controller account can free a portion (or all) of the funds using the
unbond call. Note that the funds are not immediately
accessible. Instead, a duration denoted by BondingDuration
(in number of eras) must pass until the funds can actually be removed. Once the
BondingDuration is over, the withdraw_unbonded
call can be used to actually withdraw the funds.
Note that there is a limitation to the number of fund-chunks that can be scheduled to be
unlocked in the future via unbond. In case this maximum
(MAX_UNLOCKING_CHUNKS) is reached, the bonded account must first wait until a successful
call to withdraw_unbonded to remove some of the chunks.
Election Algorithm
The current election algorithm is implemented based on Phragmén. The reference implementation can be found here.
The election algorithm, aside from electing the validators with the most stake value and votes, tries to divide the nominator votes among candidates in an equal manner. To further assure this, an optional post-processing can be applied that iteratively normalizes the nominator staked values until the total difference among votes of a particular nominator are less than a threshold.
GenesisConfig
The Staking module depends on the GenesisConfig. The
GenesisConfig is optional and allow to set some initial stakers.
Related Modules
- Balances: Used to manage values at stake.
- Session: Used to manage sessions. Also, a list of new
validators is stored in the Session module's
Validatorsat the end of each era.
License: Apache-2.0