[][src]Crate srml_staking

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

Goals

The staking system in Substrate NPoS is designed to make the following possible:

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 change their associated controller using the set_controller call.

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.

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).

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.

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: Reporting Misbehavior

use srml_support::{decl_module, dispatch::Result};
use system::ensure_signed;
use srml_staking::{self as staking};

pub trait Trait: staking::Trait {}

decl_module! {
	pub struct Module<T: Trait> for enum Call where origin: T::Origin {
		/// Report whoever calls this function as offline once.
		pub fn report_sender(origin) -> Result {
			let reported = ensure_signed(origin)?;
			<staking::Module<T>>::on_offline_validator(reported, 1);
			Ok(())
		}
	}
}

Implementation Details

Slot Stake

The term SlotStake will be used throughout this section. It refers to a value calculated at the end of each era, containing the minimum value at stake among all validators. Note that a validator's value at stake might be a combination of the validator's own stake and the votes it received. See Exposure for more details.

Reward Calculation

Rewards are recorded per-session and paid per-era. The value of the reward for each session is calculated at the end of the session based on the timeliness of the session, then accumulated to be paid later. The value of the new per-session-reward is calculated at the end of each era by multiplying SlotStake and SessionReward (SessionReward is the multiplication factor, represented by a number between 0 and 1). Once a new era is triggered, rewards are paid to the validators and their associated nominators.

The validator can declare an amount, named validator_payment, that does not get shared with the nominators at each reward payout through its ValidatorPrefs. This value gets deducted from the total reward that can be paid. 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:

Slashing details

A validator can be reported to be offline at any point via the public function on_offline_validator. Each validator declares how many times it can be reported before it actually gets slashed via its ValidatorPrefs::unstake_threshold.

On top of this, the Staking module also introduces an OfflineSlashGrace, which applies to all validators and prevents them from getting immediately slashed.

Essentially, a validator gets slashed once they have been reported more than OfflineSlashGrace + ValidatorPrefs::unstake_threshold times. Getting slashed due to offline report always leads to being unstaked (i.e. removed as a validator candidate) as the consequence.

The base slash value is computed per slash-event by multiplying OfflineSlash and the total Exposure. This value is then multiplied by 2.pow(unstake_threshold) to obtain the final slash value. All individual accounts' punishments are capped at their total stake (NOTE: This cap should never come into force in a correctly implemented, non-corrupted, well-configured system).

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.

Structs

Bonded

Map from all locked "stash" accounts to the controller account.

CurrentElected

The currently elected validator set keyed by stash account ID.

CurrentEra

The current era index.

CurrentEraReward

The accumulated reward for the current era. Reset to zero at the beginning of the era and increased for every successfully finished session.

CurrentSessionReward

Maximum reward, per validator, that is provided per acceptable session.

Exposure

A snapshot of the stake backing a single validator in the system.

ForceNewEra

True if the next session change will be a new era regardless of index.

GenesisConfig
IndividualExposure

The amount of exposure (to slashing) than an individual nominator has.

Invulnerables

Any validators that may never be slashed or forcibly kicked. It's a Vec since they're easy to initialize and the performance hit is minimal (we expect no more than four invulnerables) and restricted to testnets.

Ledger

Map from all (unlocked) "controller" accounts to the info regarding the staking.

MinimumValidatorCount

Minimum number of staking participants before emergency conditions are imposed.

Module
Nominators

The map from nominator stash key to the set of stash keys of all validators to nominate.

OfflineSlash

Slash, per validator that is taken for the first time they are found to be offline.

OfflineSlashGrace

Number of instances of offline reports before slashing begins for validators.

Payee

Where the reward payment should be made. Keyed by stash.

RecentlyOffline

Most recent RECENT_OFFLINE_COUNT instances. (Who it was, when it was reported, how many instances they were offline for).

SessionReward

Maximum reward, per validator, that is provided per acceptable session.

SlashCount

The number of times a given validator has been reported offline. This gets decremented by one each era that passes.

SlotStake

The amount of balance actively at stake for each validator slot, currently.

Stakers

Nominators for a particular account that is in action right now. You can't iterate through validators here, but you can find them in the Session module.

StakingLedger

The ledger of a (bonded) stash.

UnlockChunk

Just a Balance/BlockNumber tuple to encode when a chunk of funds will be unlocked.

ValidatorCount

The ideal number of staking participants.

ValidatorPrefs

Preference of what happens on a slash event.

Validators

The map from (wannabe) validator stash key to the preferences of that validator.

Enums

Call
RawEvent

Events for this module.

RewardDestination

A destination account for payment.

StakerStatus

Indicates the initial status of the staker.

Traits

Trait

Type Definitions

EraIndex

Counter for the number of eras that have passed.

Event

RawEvent specialized for the configuration Trait