Analysis of stacking module of Substrate

Analysis of stacking module of Substrate

1. General

Pledge economy is also a kind of mining in essence, but it is different from what we usually call bitcoin mining and Ethereum mining.

  • Bitcoin, Wright coin, Ethereum, BCH and other digital currencies are proof of work (POW) digital currencies based on workload, and the generation of new currencies is a competitive power.
    • Stacking is another mining method. Usually based on * * proof of stake (POS) * * and nominated proof of stake (NPOS).
    • In this mining method, nodes in the blockchain system do not need too high computing power, but only need to pledge a certain number of tokens. After running for a period of time, new money can be generated, and the new money generated is the income obtained through pledge.
    • This is equivalent to that we can get a certain interest every year when we deposit our money in the bank.

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hA3l6rv8-1624415573828)(/Users/lzw/Desktop/20210615112905.png)]

Suppose that in the first year, Alice and Bob both have 1% online tokens on the network. Alice chose to maintain network security and participate in network construction through stacking, but Bob didn't.

By the fifth year, we saw that Alice's token (green solid line) increased with the growth of the overall token amount of the network (black solid line), while Bob (light green dotted line) remained in place. In fact, Bob's network share is declining, Alice's share is increasing, and part of the ownership is transferred from Bob to Alice.

  • Stacking is a module that manages the collateral funds of network maintainers.
  • Network maintainers are also called Authorities or Validators
  • They are selected based on pledged funds. They will be rewarded in the normal performance of their duties and punished (confiscating certain funds) if they misbehave.

2. NPoS process

The stacking module has two important roles: verifier and nominee:

  • Validator: a verifier whose role is to verify blocks, ensure the final consistency of blocks, and maintain the integrity of the network. Verifiers should avoid any malicious misbehavior and offline. Binding accounts that declare that they are interested in becoming verifiers will not be selected as verifiers immediately. On the contrary, they are declared candidates, and they may be selected as verifiers in the next election. The election results shall be determined by the nominees and their votes.
  • Nominator: a nominator does not assume any direct role in maintaining the network, but votes on a group of verifiers to be elected. Once the account has declared the interests of the nomination, it will take effect in the next round of elections. The assets in the nominee's stash account show the importance of their voting. The rewards and penalties received by the verifier are shared by the verifier and the nominee. This rule encourages nominees not to vote for misbehaving / offline verifiers as much as possible, because if nominees vote wrong, they will also lose their assets.

2.1 accounts

In order to ensure the security of users' funds, the stacking module has designed an independent key type with a two-tier structure and uses two different accounts to manage funds, which we call: the storage account and the Controller Account (just like the relationship between the landlord and the intermediary)

  • Stash: the storage account is mainly used to store the funds used for pledge. The storage account can specify a control account to delegate the functions such as application nominator and verifier to the control account. The key of the storage account can be stored in the cold wallet for a long time to ensure the security of users' funds.

  • Controller: the control account is the agent of the storage account. It has the right to apply for nominees and verifiers, set up collection accounts and commissions. If it is an authenticator, it can also set the session keys session key. It is only necessary to ensure that the control account has sufficient funds to pay the transaction handling fee.

2.2 pledged funds (fn bond)

Users need to pledge certain funds (the pledge amount shall not be less than the limited minimum amount) to obtain the qualification of becoming a verifier or nominee. The pledge behavior is initiated by the storage account. The pledge process can set the control account, pledge amount and collection account.

2.3 set the verifier (fn validate)

Setting the verifier includes setting the Commission of the verifier. The Commission is charged in proportion. When allocating the stacking reward, the verifier's Commission will be paid first, and the remaining reward will be allocated to the nominees.

Note: the same stash account can only be the verifier or nominee. The verifier can nominate himself by self mortgage, but not by nomination. A stash account that is already a nominee cannot be used as a verifier.

2.4 nomination of verifier (fn nominate)

The control account can submit a list of supported reputable candidate verifiers (there can only be 16 nominations at most, i.e. MAX_NOMINATIONS) as the nominees. In the next Era, a certain number of verifiers supported by the most nodes are selected. If the verifier supported by the nominee is selected, the verifier's reward or punishment can be shared. The nomination process can only take place at the election stage of non candidate verifiers.

Once the nomination stage is over, the NPoS election mechanism takes the nominees and their votes as inputs and outputs a limited number of verifiers to maximize the support of any verifier and distribute them as evenly as possible. The goal of this election mechanism is to maximize the security of the network and realize the fair representation of nominees.

2.5 freezing of witnesses or nominees (fn chill)

Freezing is the act of removing verifiers from the active verifier node pool, which means that if they are nominees, they will no longer be regarded as voters, and if they are verifiers, they will no longer be candidates for the next election.

2.6 slot/session/era

  • Slot: each slot will generate a new block - based on Babe consensus mechanism

  • Epoch: a set of slots of fixed length. Each epoch will update the verifier set

  • Era (ERA): a collection of multiple epoch s. After the end of an era, the reward will be settled

3. NPoS mechanism

NPoS (Nominated Proof of Stake) is a consensus algorithm designed by Polkadot based on PoS algorithm. The Validator runs the node to participate in the production and confirmation of blocks. The Nominator can mortgage his dot to obtain the nomination right, nominate his trusted verifier and obtain rewards.

3.1 why does NPoS occur

The so-called consensus is the agreement reached by each node in the blockchain to maintain the stable operation of the system. If there are more nodes, the stronger the consensus, and the safer the whole blockchain system will be.

In Boca's design idea, the relay chain is designed to maintain the consensus of parallel chain. In other words, join the parallel chain of Boca, and there is no need to keep accounts! Boca's relay chain will uniformly account for you and uniformly maintain the security of your blockchain!

In traditional PoS:

  • If the total amount is constant, if more and more hostages pledge money, the money will be less and less.
  • If the total amount is constant, the excavated coins will be pledged to accelerate the scarcity of coins.

How can we motivate those nodes when there is no money to dig or pledge in the back. Therefore, there must be inflation (additional issuance every year), which depends on the additional currency issued every year as the incentive of the node. This is the proof of equity POS, whose cost comes from its inflation.

In Boca's design idea, the relay chain is designed to maintain the consensus of parallel chain. In other words, the parallel chain of Boca does not need to be recorded. Boca's relay chain will uniformly account for you and uniformly maintain the security of your blockchain!

It can be seen that Boca gives people the greatest sense of security because of the ability of the relay chain to maintain consensus. How does the relay chain maintain consensus? If the nodes of the relay chain are not scattered enough and monopolized by some nodes, even if there are more nodes, there will be no sense of security.

How to make nodes decentralized and decentralized is the core element of Boca sharing security.

Boca's consensus mechanism is the proof of nomination rights and interests (NPOS), which is improved on the basis of POS, perfectly solves the problem of node monopoly, makes the network decentralized enough and eliminates the phenomenon of node channeling.

1. Benefits of a single node
2. Income of verifiers and Nominees

3. Market regulation

For the verifier, the commission can be set freely. Some nodes have high commission and some nodes have low commission. The market is free to compete. This results in the following situations:

If the Commission is small, the nominees will not vote for you. If you switch to the node divided into more verifiers, there is a risk of being out.

The market will adjust itself, and the verifier's Commission will gradually return to an appropriate range, for example, 5% - 10%. So the question is, if you are the nominee, which node will you vote for when the Commission of most verifier nodes is the same? Smart nominees will certainly vote for nodes with a low total number of pledged DOT.

Why? Because due to the average distribution, the daily income of a single node is the same, and the Commission of each verifier node is the same. If you invest in a node with a low total number of pledged DOT, your pledged DOT will account for a larger proportion and occupy an advantage in the distribution of all nominees.

Focus: it is precisely because nominees are more willing to vote for nodes with a low total number of pledges that a verifier node pool with equal pledge will be created, which is enough to be decentralized

3.2 Phragm é n election algorithm

Verifier election algorithm is the core of NPoS mechanism. The election process should have fair representation and security. Polkadot designed Phragm é n algorithm to ensure that every election has this nature.

Fair representation: any Nominee holding at least 1/n of the total shares guarantees that at least one verifier they trust will be elected

Security: we want to make it difficult for candidate verifiers to obtain a verifier as much as possible. They can do this only if they get high enough support. Therefore, we equate the security level of election results with the minimum number of selected witnesses.

4. Reward and punishment

Reward and punishment are the core of the mortgage module, trying to include effective behavior and punish any misconduct or lack of availability. Once misconduct is reported, punishment can occur at any point in time. Once the penalty is determined, the value of a penalty will be deducted from the balance of the verifier and from the balance of all nominees voting for the verifier. Similar to punishment, rewards are shared between verifiers and nominees. However, incentive funds are not always transferred to the stash account.

  • Staked: the reward is paid to the storage account and used for pledge
  • Stash: the reward is paid to the storage account, but the reward is not pledged
  • Contriller: the reward is paid to the control account
  • Account: rewards are paid to a designated account

4.1 award settlement

After each block is generated, authorship - > on_ Initialize will record ErasRewardPoints of the block producer and record them in each end_era for settlement.

Bonus point increase rules:

  • Main chain block producers increased by 20 points
  • The number of producers in the tertiary block increased by 2 points
  • Producers quoting uncle block increase by 1 point

4.2 reward distribution (fn do_payout_stakers)

Two verifiers get the same amount of DOT in the same work, that is, their remuneration is not proportional to the number of take pledges of each verifier

Part of the reward (commission is set according to the reward percentage) is preferentially used to pay the commission of the verifier, and the rest is paid to the nominees and verifiers in proportion (i.e. in proportion to take)

The verifier will be rewarded twice: once as the Commission for verification and once as the Commission for nominating himself with self mortgage

4.3 punishment (Slash)

If the verifier misbehaves in the network (such as offline, attacking the network or running modified software), a slash penalty will occur. They and their nominees will lose some DOT because of slash punishment. The authentication pool with a large number of total pledges will be subject to more severe slash penalties. At start_ Eras will clear slash.

Three violations are defined in the pallet offenses module:

  • Unresponsive offer

  • Grandpa equivocationoffer (duplicate signature, voting)

  • Babeequivocationoffer

If verifiers are reported for any violation, they will be removed from the verifier node pool (i.e. frozen) and will not be rewarded when they are removed. They will immediately be considered inactive validators and will lose their nominees. They need to reissue the verification intent and collect the support of the nominees.

5. Source code analysis

parameter_types! {
	pub const SessionsPerEra: sp_staking::SessionIndex = 6;
	pub const BondingDuration: pallet_staking::EraIndex = 24 * 28;
	pub const SlashDeferDuration: pallet_staking::EraIndex = 24 * 7; // 1/4 the bonding duration.
	pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE;
	pub const MaxNominatorRewardedPerValidator: u32 = 256;
	pub OffchainRepeat: BlockNumber = 5;
}

use frame_election_provider_support::onchain;
impl pallet_staking::Config for Runtime {
	const MAX_NOMINATIONS: u32 = MAX_NOMINATIONS;
	//Pledge balance
	//Call the Balances module
	type Currency = Balances;
	//It is used to calculate the duration of the cycle. It ensures that it is on when starting_ Finalize, which is not used in the creation module
	//Call Timestamp module
	type UnixTime = Timestamp;
	//Convert the balance to election figures
	type CurrencyToVote = U128CurrencyToVote;
	//Total reward of the mortgagor = annual inflation rate * total amount of tokens issued / number of cycles per year / / annual inflation rate = npos_token_staked / total_tokens
	// staker_payout = yearly_inflation(npos_token_staked / total_tokens) * total_tokens / era_per_year
	//Reward remainder remaining reward = maximum annual expansion rate * total number of tokens / number of cycles per year - total reward to the mortgagor
	//remaining_payout = max_yearly_inflation * total_tokens / era_per_year - staker_payout
	//If the maximum reward minus the actual reward still has the remaining reward, the remaining reward shall be returned to the State Treasury for supporting ecological development expenditure
	//Treasury module: it provides a fund pool that can be managed by the mortgagors. In this treasury system, it can initiate payment proposals from this fund pool.
	type RewardRemainder = Treasury;
	//Type time
	type Event = Event;
	//Collect the money of punishment into the Treasury
	type Slash = Treasury; // send the slashed funds to the treasury.
	//Reward. The reward will be performed in the main function
	type Reward = (); // rewards are minted from the void
	//Number of sessions per cycle
	type SessionsPerEra = SessionsPerEra;
	//Time that must be stored
	type BondingDuration = BondingDuration;
	//The penalty delay time must be less than BondingDuration. If it is set to 0, it will be punished immediately without time intervention
	type SlashDeferDuration = SlashDeferDuration;
	/// A super-majority of the council can cancel the slash.
	//The overwhelming majority in parliament agreed that the penalty for delay could be abolished
	type SlashCancelOrigin = EnsureOneOf<
		AccountId,
		EnsureRoot<AccountId>,
		pallet_collective::EnsureProportionAtLeast<_3, _4, AccountId, CouncilCollective>
	>;
	//Interface provided to session
	type SessionInterface = Self;
	//Cost per cycle
	type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
	//Accurately estimate the change of the next session, or make the best guess
	type NextNewSession = Session;
	//The maximum number of nominees awarded for each verifier.
	//For each verifier, only $maxnominator rewardedpervalidator. The largest stackers can apply for their reward. This is used to limit the I / O costs paid by the nominees.
	type MaxNominatorRewardedPerValidator = MaxNominatorRewardedPerValidator;
	//Provide election function
	type ElectionProvider = ElectionProviderMultiPhase;
	type GenesisElectionProvider =
		onchain::OnChainSequentialPhragmen<pallet_election_provider_multi_phase::OnChainConfig<Self>>;
	//Weight information
	type WeightInfo = pallet_staking::weights::SubstrateWeight<Runtime>;
}
//Basic module
		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
		Utility: pallet_utility::{Pallet, Call, Event},

		//session prerequisite pre module
		//BABE module realizes some functions of BABE consensus mechanism by collecting random factors on the chain from the output of VRF algorithm and effectively managing the periodic replacement of blocks.
		Babe: pallet_babe::{Pallet, Call, Storage, Config, ValidateUnsigned},
		//The Timestamp module provides the function of obtaining and setting the time on the chain.
		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},
		//Indexes: assigns indexes to newly created accounts. An index is an abbreviation for an address.
		Indices: pallet_indices::{Pallet, Call, Storage, Config<T>, Event<T>},
		//The Balances module provides account and balance management functions.
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
		//TransactionPayment: provides the basic logic for calculating the pre allocation transaction cost.
		TransactionPayment: pallet_transaction_payment::{Pallet, Storage},

		//Consensus module
		//The Authorship module is used to track the creator of the current block and the adjacent "Uncle blocks".
		Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent},
		//Election module
		ElectionProviderMultiPhase: pallet_election_provider_multi_phase::{Pallet, Call, Storage, Event<T>, ValidateUnsigned},
		//Pledge module
		Staking: pallet_staking::{Pallet, Call, Config<T>, Storage, Event<T>},
		//The Session module allows the authenticator to manage its Session key, and provides the functions of changing the Session length and handling Session rotation.
		Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
		//The GRANDPA module expands the consensus system of GRANDPA by maintaining a GRANDPA authority set serving native code.
		Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned},
		//History module
		Historical: pallet_session_historical::{Pallet},
		//The I'm Online module allows the authenticator to broadcast a heartbeat in each new session to indicate that the node is online.
		ImOnline: pallet_im_online::{Pallet, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
		//The core / Authority Discovery Library of Substrate uses the Authority Discovery module to obtain the current authority set, obtain the authority ID of this node, and sign and verify messages exchanged with this node and other authority nodes.
		AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config},
		//The offenses module is used to record reported violations.
		Offences: pallet_offences::{Pallet, Storage, Event},

		//Management module
		//Bonus module
		Bounties: pallet_bounties::{Pallet, Call, Storage, Event<T>},
		//
		Tips: pallet_tips::{Pallet, Call, Storage, Event<T>},
		//Treasury pallet provides a fund pool managed by system stakeholders and a structure for making expenditure proposals from the fund pool.
		Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>},
		//The Collective module enables some specified account sets to know their Collective information through function calls from some special sources.
		Council: pallet_collective::<Instance1>::{Pallet, Call, Storage, Origin<T>, Event<T>, Config<T>},
		TechnicalCommittee: pallet_collective::<Instance2>::{Pallet, Call, Storage, Origin<T>, Event<T>, Config<T>},
		//The Democracy module provides a democratic system to handle the voting of stakeholders.
		Democracy: pallet_democracy::{Pallet, Call, Storage, Config<T>, Event<T>},
		//Election module
		Elections: pallet_elections_phragmen::{Pallet, Call, Storage, Event<T>, Config<T>},
		//The Membership module allows you to control the Membership of a set of accountids, which is very useful for managing the Membership of collection types.
		TechnicalMembership: pallet_membership::<Instance1>::{Pallet, Call, Storage, Event<T>, Config<T>},


		//other
		//Sudo pallet is used to grant an account (called "sudo key") permission to execute the transaction function requiring Root permission, or specify a new account to replace the original sudo key.
		Sudo: pallet_sudo::{Pallet, Call, Config<T>, Storage, Event<T>},
		//The Contracts module provides the runtime with the ability to deploy and execute web assembly smart Contracts.
		Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>},
		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage},
		Identity: pallet_identity::{Pallet, Call, Storage, Event<T>},
		Society: pallet_society::{Pallet, Call, Storage, Event<T>, Config<T>},
		Recovery: pallet_recovery::{Pallet, Call, Storage, Event<T>},
		Vesting: pallet_vesting::{Pallet, Call, Storage, Event<T>, Config<T>},
		Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event<T>},
		Proxy: pallet_proxy::{Pallet, Call, Storage, Event<T>},
		Multisig: pallet_multisig::{Pallet, Call, Storage, Event<T>},
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>},
		Mmr: pallet_mmr::{Pallet, Storage},
		Lottery: pallet_lottery::{Pallet, Call, Storage, Event<T>},
		Gilt: pallet_gilt::{Pallet, Call, Storage, Event<T>, Config},
		Uniques: pallet_uniques::{Pallet, Call, Storage, Event<T>},
		TransactionStorage: pallet_transaction_storage::{Pallet, Call, Storage, Inherent, Config<T>, Event<T>},

Keywords: Blockchain

Added by rohithmr on Wed, 26 Jan 2022 21:37:23 +0200