diff --git a/Cargo.lock b/Cargo.lock index 21fdf12ddb199..52eec67507ffb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3300,6 +3300,7 @@ name = "srml-session" version = "0.1.0" dependencies = [ "hex-literal 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec 3.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "parity-codec-derive 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "safe-mix 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm b/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm index 6e4e047e40f25..c4df3f06b5bb1 100644 Binary files a/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm and b/core/test-runtime/wasm/target/wasm32-unknown-unknown/release/substrate_test_runtime.compact.wasm differ diff --git a/node/cli/src/chain_spec.rs b/node/cli/src/chain_spec.rs index 927e5595d1822..7edec08b43664 100644 --- a/node/cli/src/chain_spec.rs +++ b/node/cli/src/chain_spec.rs @@ -107,7 +107,6 @@ fn staging_testnet_config_genesis() -> GenesisConfig { current_era: 0, offline_slash: Perbill::from_billionths(1_000_000), session_reward: Perbill::from_billionths(2_065), - current_offline_slash: 0, current_session_reward: 0, validator_count: 7, sessions_per_era: 12, @@ -263,7 +262,6 @@ pub fn testnet_genesis( bonding_duration: 2 * 60 * 12, offline_slash: Perbill::zero(), session_reward: Perbill::zero(), - current_offline_slash: 0, current_session_reward: 0, offline_slash_grace: 0, stakers: initial_authorities.iter().map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)).collect(), diff --git a/node/executor/src/lib.rs b/node/executor/src/lib.rs index 1a96b8067f9c6..22bf1a9b799af 100644 --- a/node/executor/src/lib.rs +++ b/node/executor/src/lib.rs @@ -308,7 +308,6 @@ mod tests { bonding_duration: 0, offline_slash: Perbill::zero(), session_reward: Perbill::zero(), - current_offline_slash: 0, current_session_reward: 0, offline_slash_grace: 0, invulnerables: vec![alice(), bob(), charlie()], @@ -443,13 +442,7 @@ mod tests { ] ); - // let mut digest = generic::Digest::::default(); - // digest.push(Log::from(::grandpa::RawLog::AuthoritiesChangeSignal(0, vec![ - // (Keyring::Charlie.to_raw_public().into(), 1), - // (Keyring::Bob.to_raw_public().into(), 1), - // (Keyring::Alice.to_raw_public().into(), 1), - // ]))); - let digest = generic::Digest::::default(); // TODO test this + let digest = generic::Digest::::default(); assert_eq!(Header::decode(&mut &block2.0[..]).unwrap().digest, digest); (block1, block2) @@ -578,14 +571,6 @@ mod tests { phase: Phase::Finalization, event: Event::session(session::RawEvent::NewSession(1)) }, - // EventRecord { // TODO: this might be wrong. - // phase: Phase::Finalization, - // event: Event::grandpa(::grandpa::RawEvent::NewAuthorities(vec![ - // (Keyring::Charlie.to_raw_public().into(), 1), - // (Keyring::Bob.to_raw_public().into(), 1), - // (Keyring::Alice.to_raw_public().into(), 1), - // ])), - // }, EventRecord { phase: Phase::Finalization, event: Event::treasury(treasury::RawEvent::Spending(0)) diff --git a/node/runtime/src/lib.rs b/node/runtime/src/lib.rs index c069bed172d24..80260801efe83 100644 --- a/node/runtime/src/lib.rs +++ b/node/runtime/src/lib.rs @@ -58,8 +58,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("node"), impl_name: create_runtime_str!("substrate-node"), authoring_version: 10, - spec_version: 38, - impl_version: 40, + spec_version: 39, + impl_version: 39, apis: RUNTIME_API_VERSIONS, }; diff --git a/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm b/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm index 36103fef20f90..3af4c1768d944 100644 Binary files a/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm and b/node/runtime/wasm/target/wasm32-unknown-unknown/release/node_runtime.compact.wasm differ diff --git a/srml/consensus/src/lib.rs b/srml/consensus/src/lib.rs index 3da15255ae695..ef90c61f42a3b 100644 --- a/srml/consensus/src/lib.rs +++ b/srml/consensus/src/lib.rs @@ -244,6 +244,12 @@ impl Module { } } + /// Set a single authority by index. + pub fn set_authority_count(count: u32) { + Self::save_original_authorities(None); + AuthorityStorageVec::::set_count(count); + } + /// Set a single authority by index. pub fn set_authority(index: u32, key: &T::SessionKey) { let current_authority = AuthorityStorageVec::::item(index); diff --git a/srml/session/Cargo.toml b/srml/session/Cargo.toml index 84b49b77882ff..4f1fe086cffda 100644 --- a/srml/session/Cargo.toml +++ b/srml/session/Cargo.toml @@ -20,6 +20,7 @@ timestamp = { package = "srml-timestamp", path = "../timestamp", default-feature [dev-dependencies] substrate-primitives = { path = "../../core/primitives" } runtime_io = { package = "sr-io", path = "../../core/sr-io" } +lazy_static = "1.0" [features] default = ["std"] diff --git a/srml/session/src/lib.rs b/srml/session/src/lib.rs index d7d48e27f270f..956c8e03fed4a 100644 --- a/srml/session/src/lib.rs +++ b/srml/session/src/lib.rs @@ -184,8 +184,12 @@ impl Module { >::put(block_number); } + T::OnSessionChange::on_session_change(time_elapsed, apply_rewards); + // Update any changes in session keys. - for (i, v) in Self::validators().into_iter().enumerate() { + let v = Self::validators(); + >::set_authority_count(v.len() as u32); + for (i, v) in v.into_iter().enumerate() { >::set_authority( i as u32, &>::get(&v) @@ -193,8 +197,6 @@ impl Module { .unwrap_or_default() ); }; - - T::OnSessionChange::on_session_change(time_elapsed, apply_rewards); } /// Get the time that should have elapsed over a session if everything was working perfectly. @@ -224,6 +226,7 @@ impl OnFreeBalanceZero for Module { #[cfg(test)] mod tests { use super::*; + use std::cell::RefCell; use srml_support::{impl_outer_origin, assert_ok}; use runtime_io::with_externalities; use substrate_primitives::{H256, Blake2Hasher}; @@ -235,6 +238,17 @@ mod tests { pub enum Origin for Test {} } + thread_local!{ + static NEXT_VALIDATORS: RefCell> = RefCell::new(vec![1, 2, 3]); + } + + pub struct TestOnSessionChange; + impl OnSessionChange for TestOnSessionChange { + fn on_session_change(_elapsed: u64, _should_reward: bool) { + NEXT_VALIDATORS.with(|v| Session::set_validators(&*v.borrow())); + } + } + #[derive(Clone, Eq, PartialEq)] pub struct Test; impl consensus::Trait for Test { @@ -261,7 +275,7 @@ mod tests { } impl Trait for Test { type ConvertAccountIdToSessionKey = ConvertUintAuthorityId; - type OnSessionChange = (); + type OnSessionChange = TestOnSessionChange; type Event = (); } @@ -273,14 +287,14 @@ mod tests { let mut t = system::GenesisConfig::::default().build_storage().unwrap().0; t.extend(consensus::GenesisConfig::{ code: vec![], - authorities: vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)], + authorities: NEXT_VALIDATORS.with(|l| l.borrow().iter().cloned().map(UintAuthorityId).collect()), }.build_storage().unwrap().0); t.extend(timestamp::GenesisConfig::{ period: 5, }.build_storage().unwrap().0); t.extend(GenesisConfig::{ session_length: 2, - validators: vec![1, 2, 3], + validators: NEXT_VALIDATORS.with(|l| l.borrow().clone()), keys: vec![], }.build_storage().unwrap().0); runtime_io::TestExternalities::new(t) @@ -289,12 +303,35 @@ mod tests { #[test] fn simple_setup_should_work() { with_externalities(&mut new_test_ext(), || { - assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1).into(), UintAuthorityId(2).into(), UintAuthorityId(3).into()]); + assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); assert_eq!(Session::length(), 2); assert_eq!(Session::validators(), vec![1, 2, 3]); }); } + #[test] + fn authorities_should_track_validators() { + with_externalities(&mut new_test_ext(), || { + NEXT_VALIDATORS.with(|v| *v.borrow_mut() = vec![1, 2]); + assert_ok!(Session::force_new_session(false)); + Session::check_rotate_session(1); + assert_eq!(Session::validators(), vec![1, 2]); + assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]); + + NEXT_VALIDATORS.with(|v| *v.borrow_mut() = vec![1, 2, 4]); + assert_ok!(Session::force_new_session(false)); + Session::check_rotate_session(2); + assert_eq!(Session::validators(), vec![1, 2, 4]); + assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(4)]); + + NEXT_VALIDATORS.with(|v| *v.borrow_mut() = vec![1, 2, 3]); + assert_ok!(Session::force_new_session(false)); + Session::check_rotate_session(3); + assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); + }); + } + #[test] fn should_work_with_early_exit() { with_externalities(&mut new_test_ext(), || { diff --git a/srml/staking/src/lib.rs b/srml/staking/src/lib.rs index 151668f691be5..aa3ef1d4b2f47 100644 --- a/srml/staking/src/lib.rs +++ b/srml/staking/src/lib.rs @@ -14,7 +14,205 @@ // You should have received a copy of the GNU General Public License // along with Substrate. If not, see . -//! Staking manager: Periodically determines the best set of validators. +//! # Staking Module +//! +//! +//! 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 their duties properly. +//! You can start using the Staking module by implementing the staking [`Trait`]. +//! +//! ## Overview +//! +//! ### 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 which 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 their funds ([reference](#references)). +//! +//! ### Goals +//! +//! +//! The staking system in Substrate NPoS is designed to achieve three goals: +//! - It should be possible to stake funds that are controlled by a cold wallet. +//! - It should be possible to withdraw some, or deposit more, funds without interrupting the role of an entity. +//! - It should be possible to switch between roles (nominator, validator, idle) with minimal overhead. +//! +//! ### Scenarios +//! +//! #### Staking +//! +//! Almost any interaction with the staking module requires at least one account to become **bonded**, also known as +//! being a **staker**. For this, all that it is needed is a secondary _**stash account**_ which will hold the staked funds. +//! Henceforth, the former account that initiated the interest is called the **controller** and the latter, holding the +//! funds, is named the **stash**. Also, note that this implies that entering the staking process requires an _account +//! pair_, one to take the role of the controller and one to be the frozen stash account (any value locked in +//! stash cannot be used, hence called _frozen_). This process in the public API is mostly referred to as _bonding_ via +//! the `bond()` function. +//! +//! Any account pair successfully placed at stake can accept three possible roles, namely: `validate`, `nominate` or +//! simply `chill`. Note that during the process of accepting these roles, the _controller_ account is always responsible +//! for declaring interest and the _stash_ account stays untouched, without directly interacting in any operation. +//! +//! #### 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 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 _immediately_, meaning that its +//! votes will be taken into account at the next election round. As mentioned above, a nominator must also place some +//! funds in a stash account, essentially indicating the _weight_ of its vote. In some sense, the nominator bets on the +//! honesty of a set of validators by voting for them, with the goal of having a share of the reward granted to them. +//! Any rewards given to a validator is shared among that validator and all of the nominators that voted for it. The +//! same logic applies to the slash of a validator; if a validator misbehaves all of its nominators also get slashed. +//! 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 are 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. One such misbehavior is a validator being detected as offline more than a certain number of +//! times. Once slashing is determined, a value is deducted from the balance of the validator and all the nominators who +//! voted for this validator. Same rules apply to the rewards in the sense of being shared among a validator and its +//! associated nominators. +//! +//! 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 (again, both effects apply at the beginning of the next era). An account can +//! step back via the `chill()` call. +//! +//! ## Interface +//! +//! ### Types +//! +//! - `Currency`: Used as the measurement means of staking and funds management. +//! +//! ### Dispatchable +//! +//! 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. +//! +//! Please refer to the [`Call`] enum and its associated variants for a detailed list of dispatchable functions. +//! +//! ### Public +//! The staking module contains many public storage items and (im)mutable functions. Please refer to the [struct list](#structs) +//! below and the [`Module`](https://crates.parity.io/srml_staking/struct.Module.html) struct definition for more details. +//! +//! ## Usage +//! +//! +//! ### Snippet: Bonding and Accepting Roles +//! +//! An arbitrary account pair, given that the associated stash has the required funds, can become stakers via the following call: +//! +//! ```rust,ignore +//! // bond account 3 as stash +//! // account 4 as controller +//! // with stash value 1500 units +//! // while the rewards get transferred to the controller account. +//! Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller); +//! ``` +//! +//! To state desire to become a validator: +//! +//! ```rust,ignore +//! // controller account 4 states desire for validation with the given preferences. +//! Staking::validate(Origin::signed(4), ValidatorPrefs::default()); +//! ``` +//! +//! Note that, as mentioned, the stash account is transparent in such calls and only the controller initiates the function calls. +//! +//! Similarly, to state desire in nominating: +//! +//! ```rust,ignore +//! // controller account 4 nominates for account 10 and 20. +//! Staking::nominate(Origin::signed(4), vec![20, 10]); +//! ``` +//! +//! Finally, account 4 can withdraw from any of the above roles via +//! +//! ```rust,ignore +//! Staking::chill(Origin::signed(4)); +//! ``` +//! +//! ## Implementation Details +//! +//! ### Slot Stake +//! +//! The term `slot_stake` 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._ +//! +//! ### 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 `slot_stake` and a configuration +//! storage item named `SessionReward`. +//! - Once a new era is triggered, rewards are paid to the validators and the associated nominators. +//! - The validator can declare an amount, named `validator_payment`, that does not get shared with the nominators at +//! each reward payout through their `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 who had a vote for this validator, +//! proportional to their staked value. +//! - 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. +//! - Stash account, not increasing the staked value. +//! - Stash account, also increasing the staked value. +//! +//! ### Slashing details +//! +//! - A validator can be _reported_ to be offline at any point via `on_offline_validator` public function. +//! - Each validator declares how many times it can be _reported_ before it actually gets slashed via the +//! `unstake_threshold` in `ValidatorPrefs`. On top of this, the module also introduces an `OfflineSlashGrace`, +//! which applies to all validators and prevents them from getting immediately slashed. +//! - Similar to the reward value, the slash value is updated at the end of each era by multiplying `slot_stake` and a +//! configuration storage item, `OfflineSlash`. +//! - Once a validator has been reported a sufficient number of times, the actual value that gets deducted from that +//! validator, and every single nominator that voted for it is calculated by multiplying the result of the above point +//! by `2.pow(unstake_threshold)`. +//! - If the previous overflows, then `slot_stake` is used. +//! - If the previous is more than what the validator/nominator has in stake, all of its stake is slashed (`.max(total_stake)`). +//! +//! ### 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. +//! - To actually remove the funds, once the bonding duration is over, `withdraw_unbonded()` can be used. +//! - As opposed to the above, additional funds can be added to the stash account via the `bond_extra()` transaction call. +//! +//! ### Election algorithm details. +//! +//! The current election algorithm is implemented based on Phragmén. The reference implementation can be found [here](https://github.com/w3f/consensus/tree/master/NPoS). +//! +//! ## GenesisConfig +//! +//! See the [`GensisConfig`] for a list of attributes that can be provided. +//! +//! ## Related Modules +//! +//! - [**Balances**](https://crates.parity.io/srml_balances/index.html): Used to manage values at stake. +//! - [**Sessions**](https://crates.parity.io/srml_session/index.html): Used to manage sessions. Also, a list of new validators is also stored in the sessions module's `Validators` at the end of each era. +//! - [**System**](https://crates.parity.io/srml_system/index.html): Used to obtain block number and time, among other details. +//! +//! # References +//! +//! 1. This document is written as a more verbose version of the original [Staking.md](../Staking.md) file. Some sections, are taken directly from the aforementioned document. + #![cfg_attr(not(feature = "std"), no_std)] @@ -39,14 +237,23 @@ mod mock; mod tests; mod phragmen; +use phragmen::{elect, ElectionConfig}; + const RECENT_OFFLINE_COUNT: usize = 32; const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4; const MAX_NOMINATIONS: usize = 16; const MAX_UNSTAKE_THRESHOLD: u32 = 10; -// Indicates the initial status of the staker +/// Indicates the initial status of the staker. #[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))] -pub enum StakerStatus { Idle, Validator, Nominator(Vec), } +pub enum StakerStatus { + /// Chilling. + Idle, + /// Declared state in validating or already participating in it. + Validator, + /// Nominating for a group of other stakers. + Nominator(Vec), +} /// A destination account for payment. #[derive(PartialEq, Eq, Copy, Clone, Encode, Decode)] @@ -143,7 +350,7 @@ impl< #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode)] #[cfg_attr(feature = "std", derive(Debug))] pub struct IndividualExposure { - /// Which nominator. + /// The stash account of the nominator in question. who: AccountId, /// Amount of funds exposed. #[codec(compact)] @@ -207,9 +414,6 @@ decl_storage! { /// The length of the bonding duration in blocks. pub BondingDuration get(bonding_duration) config(): T::BlockNumber = T::BlockNumber::sa(1000); - // TODO: remove once Alex/CC updated #1785 - pub Invulerables get(invulerables): Vec; - /// Any validators that may never be slashed or forcibly kicked. It's a Vec since they're easy to initialise /// and the performance hit is minimal (we expect no more than four invulnerables) and restricted to testnets. pub Invulnerables get(invulnerables) config(): Vec; @@ -219,21 +423,19 @@ decl_storage! { /// Map from all (unlocked) "controller" accounts to the info regarding the staking. pub Ledger get(ledger): map T::AccountId => Option, T::BlockNumber>>; - /// Where the reward payment should be made. + /// Where the reward payment should be made. Keyed by stash. pub Payee get(payee): map T::AccountId => RewardDestination; - /// The set of keys are all controllers that want to validate. - /// - /// The values are the preferences that a validator has. + /// The map from (wannabe) validator stash key to the preferences of that validator. pub Validators get(validators): linked_map T::AccountId => ValidatorPrefs>; - /// The set of keys are all controllers that want to nominate. - /// - /// The value are the nominations. + /// The map from nominator stash key to the set of stash keys of all validators to nominate. pub Nominators get(nominators): linked_map T::AccountId => Vec; /// 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 `sessions` module. + /// + /// This is keyed by the stash account. pub Stakers get(stakers): map T::AccountId => Exposure>; // The historical validators and their nominations for a given era. Stored as a trie root of the mapping @@ -244,13 +446,14 @@ decl_storage! { // entry removed down to a specific number of entries (probably around 90 for a 3 month history). // pub HistoricalStakers get(historical_stakers): map T::BlockNumber => Option; + /// The currently elected validator set keyed by stash account ID. + pub CurrentElected get(current_elected): Vec; + /// The current era index. pub CurrentEra get(current_era) config(): T::BlockNumber; /// Maximum reward, per validator, that is provided per acceptable session. pub CurrentSessionReward get(current_session_reward) config(): BalanceOf; - /// Slash, per validator that is taken for the first time they are found to be offline. - pub CurrentOfflineSlash get(current_offline_slash) config(): BalanceOf; /// The accumulated reward for the current era. Reset to zero at the beginning of the era and /// increased for every successfully finished session. @@ -282,6 +485,7 @@ decl_storage! { build(|storage: &mut primitives::StorageOverlay, _: &mut primitives::ChildrenStorageOverlay, config: &GenesisConfig| { with_storage(storage, || { for &(ref stash, ref controller, balance, ref status) in &config.stakers { + assert!(T::Currency::free_balance(&stash) >= balance); let _ = >::bond( T::Origin::from(Some(stash.clone()).into()), T::Lookup::unlookup(controller.clone()), @@ -315,6 +519,8 @@ decl_module! { /// Take the origin account as a stash and lock up `value` of its balance. `controller` will be the /// account that controls it. + /// + /// The dispatch origin for this call must be _Signed_. fn bond(origin, controller: ::Source, #[compact] value: BalanceOf, payee: RewardDestination) { let stash = ensure_signed(origin)?; @@ -324,15 +530,18 @@ decl_module! { let controller = T::Lookup::lookup(controller)?; + if >::exists(&controller) { + return Err("controller already paired") + } + // You're auto-bonded forever, here. We might improve this by only bonding when // you actually validate/nominate. >::insert(&stash, controller.clone()); + >::insert(&stash, payee); let stash_balance = T::Currency::free_balance(&stash); let value = value.min(stash_balance); - - Self::update_ledger(&controller, StakingLedger { stash, total: value, active: value, unlocking: vec![] }); - >::insert(&controller, payee); + Self::update_ledger(&controller, &StakingLedger { stash, total: value, active: value, unlocking: vec![] }); } /// Add some extra amount that have appeared in the stash `free_balance` into the balance up for @@ -340,7 +549,7 @@ decl_module! { /// /// Use this if there are additional funds in your stash account that you wish to bond. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. fn bond_extra(origin, max_additional: BalanceOf) { let controller = ensure_signed(origin)?; let mut ledger = Self::ledger(&controller).ok_or("not a controller")?; @@ -350,7 +559,7 @@ decl_module! { let extra = (stash_balance - ledger.total).min(max_additional); ledger.total += extra; ledger.active += extra; - Self::update_ledger(&controller, ledger); + Self::update_ledger(&controller, &ledger); } } @@ -361,7 +570,7 @@ decl_module! { /// Once the unlock period is done, you can call `withdraw_unbonded` to actually move /// the funds out of management ready for transfer. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. /// /// See also [`Call::withdraw_unbonded`]. fn unbond(origin, #[compact] value: BalanceOf) { @@ -382,7 +591,7 @@ decl_module! { let era = Self::current_era() + Self::bonding_duration(); ledger.unlocking.push(UnlockChunk { value, era }); - Self::update_ledger(&controller, ledger); + Self::update_ledger(&controller, &ledger); } } @@ -391,68 +600,90 @@ decl_module! { /// This essentially frees up that balance to be used by the stash account to do /// whatever it wants. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. /// /// See also [`Call::unbond`]. fn withdraw_unbonded(origin) { let controller = ensure_signed(origin)?; let ledger = Self::ledger(&controller).ok_or("not a controller")?; let ledger = ledger.consolidate_unlocked(Self::current_era()); - Self::update_ledger(&controller, ledger); + Self::update_ledger(&controller, &ledger); } /// Declare the desire to validate for the origin controller. /// /// Effects will be felt at the beginning of the next era. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. fn validate(origin, prefs: ValidatorPrefs>) { let controller = ensure_signed(origin)?; - let _ledger = Self::ledger(&controller).ok_or("not a controller")?; + let ledger = Self::ledger(&controller).ok_or("not a controller")?; + let stash = &ledger.stash; ensure!(prefs.unstake_threshold <= MAX_UNSTAKE_THRESHOLD, "unstake threshold too large"); - >::remove(&controller); - >::insert(controller, prefs); + >::remove(stash); + >::insert(stash, prefs); } /// Declare the desire to nominate `targets` for the origin controller. /// /// Effects will be felt at the beginning of the next era. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. fn nominate(origin, targets: Vec<::Source>) { let controller = ensure_signed(origin)?; - let _ledger = Self::ledger(&controller).ok_or("not a controller")?; + let ledger = Self::ledger(&controller).ok_or("not a controller")?; + let stash = &ledger.stash; ensure!(!targets.is_empty(), "targets cannot be empty"); let targets = targets.into_iter() .take(MAX_NOMINATIONS) .map(T::Lookup::lookup) .collect::, &'static str>>()?; - >::remove(&controller); - >::insert(controller, targets); + >::remove(stash); + >::insert(stash, targets); } /// Declare no desire to either validate or nominate. /// /// Effects will be felt at the beginning of the next era. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. fn chill(origin) { let controller = ensure_signed(origin)?; - let _ledger = Self::ledger(&controller).ok_or("not a controller")?; - >::remove(&controller); - >::remove(&controller); + let ledger = Self::ledger(&controller).ok_or("not a controller")?; + let stash = &ledger.stash; + >::remove(stash); + >::remove(stash); } /// (Re-)set the payment target for a controller. /// /// Effects will be felt at the beginning of the next era. /// - /// NOTE: This call must be made by the controller, not the stash. + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. fn set_payee(origin, payee: RewardDestination) { let controller = ensure_signed(origin)?; - let _ledger = Self::ledger(&controller).ok_or("not a controller")?; - >::insert(&controller, payee); + let ledger = Self::ledger(&controller).ok_or("not a controller")?; + let stash = &ledger.stash; + >::insert(stash, payee); + } + + /// (Re-)set the payment target for a controller. + /// + /// Effects will be felt at the beginning of the next era. + /// + /// The dispatch origin for this call must be _Signed_ by the controller, not the stash. + fn set_controller(origin, controller: ::Source) { + let stash = ensure_signed(origin)?; + let old_controller = Self::bonded(&stash).ok_or("not a stash")?; + let controller = T::Lookup::lookup(controller)?; + if >::exists(&controller) { + return Err("controller already paired") + } + if controller != old_controller { + >::insert(&stash, &controller); + if let Some(l) = >::take(&old_controller) { >::insert(&controller, l) }; + } } /// Set the number of sessions in an era. @@ -488,7 +719,7 @@ decl_module! { } } -/// An event in this module. +// An event in this module. decl_event!( pub enum Event where Balance = BalanceOf, ::AccountId { /// All validators have been rewarded by the given balance. @@ -515,13 +746,6 @@ impl Module { Self::sessions_per_era() * >::length() } - /// The stashed funds whose staking activities are controlled by `controller` and - /// which are actively in stake right now. - pub fn stash_balance(controller: &T::AccountId) -> BalanceOf { - Self::ledger(controller) - .map_or_else(Zero::zero, |l| l.active) - } - /// The total balance that can be slashed from a validator controller account as of /// right now. pub fn slashable_balance(who: &T::AccountId) -> BalanceOf { @@ -531,21 +755,21 @@ impl Module { // MUTABLES (DANGEROUS) /// Update the ledger for a controller. This will also update the stash lock. - fn update_ledger(controller: &T::AccountId, ledger: StakingLedger, T::BlockNumber>) { + fn update_ledger(controller: &T::AccountId, ledger: &StakingLedger, T::BlockNumber>) { T::Currency::set_lock(STAKING_ID, &ledger.stash, ledger.total, T::BlockNumber::max_value(), WithdrawReasons::all()); >::insert(controller, ledger); } /// Slash a given validator by a specific amount. Removes the slash from their balance by preference, /// and reduces the nominators' balance if needed. - fn slash_validator(v: &T::AccountId, slash: BalanceOf) { + fn slash_validator(stash: &T::AccountId, slash: BalanceOf) { // The exposure (backing stake) information of the validator to be slashed. - let exposure = Self::stakers(v); + let exposure = Self::stakers(stash); // The amount we are actually going to slash (can't be bigger than their total exposure) let slash = slash.min(exposure.total); // The amount we'll slash from the validator's stash directly. let own_slash = exposure.own.min(slash); - let (mut imbalance, missing) = T::Currency::slash(v, own_slash); + let (mut imbalance, missing) = T::Currency::slash(stash, own_slash); let own_slash = own_slash - missing; // The amount remaining that we can't slash from the validator, that must be taken from the nominators. let rest_slash = slash - own_slash; @@ -565,17 +789,22 @@ impl Module { /// Actually make a payment to a staker. This uses the currency's reward function /// to pay the right payee for the given staker account. - fn make_payout(who: &T::AccountId, amount: BalanceOf) -> Option> { - match Self::payee(who) { - RewardDestination::Controller => T::Currency::deposit_into_existing(&who, amount).ok(), - RewardDestination::Stash => Self::ledger(who) - .and_then(|l| T::Currency::deposit_into_existing(&l.stash, amount).ok()), - RewardDestination::Staked => - Self::ledger(who).and_then(|mut l| { + fn make_payout(stash: &T::AccountId, amount: BalanceOf) -> Option> { + let dest = Self::payee(stash); + match dest { + RewardDestination::Controller => Self::bonded(stash) + .and_then(|controller| + T::Currency::deposit_into_existing(&controller, amount).ok() + ), + RewardDestination::Stash => + T::Currency::deposit_into_existing(stash, amount).ok(), + RewardDestination::Staked => Self::bonded(stash) + .and_then(|c| Self::ledger(&c).map(|l| (c, l))) + .and_then(|(controller, mut l)| { l.active += amount; l.total += amount; - let r = T::Currency::deposit_into_existing(&l.stash, amount).ok(); - Self::update_ledger(who, l); + let r = T::Currency::deposit_into_existing(stash, amount).ok(); + Self::update_ledger(&controller, &l); r }), } @@ -583,22 +812,23 @@ impl Module { /// Reward a given validator by a specific amount. Add the reward to their, and their nominators' /// balance, pro-rata based on their exposure, after having removed the validator's pre-payout cut. - fn reward_validator(who: &T::AccountId, reward: BalanceOf) { - let off_the_table = reward.min(Self::validators(who).validator_payment); + fn reward_validator(stash: &T::AccountId, reward: BalanceOf) { + let off_the_table = reward.min(Self::validators(stash).validator_payment); let reward = reward - off_the_table; let mut imbalance = >::zero(); let validator_cut = if reward.is_zero() { Zero::zero() } else { - let exposure = Self::stakers(who); + let exposure = Self::stakers(stash); let total = exposure.total.max(One::one()); let safe_mul_rational = |b| b * reward / total;// FIXME #1572: avoid overflow for i in &exposure.others { - imbalance.maybe_subsume(Self::make_payout(&i.who, safe_mul_rational(i.value))); + let nom_payout = safe_mul_rational(i.value); + imbalance.maybe_subsume(Self::make_payout(&i.who, nom_payout)); } safe_mul_rational(exposure.own) }; - imbalance.maybe_subsume(Self::make_payout(who, validator_cut + off_the_table)); + imbalance.maybe_subsume(Self::make_payout(stash, validator_cut + off_the_table)); T::Reward::on_unbalanced(imbalance); } @@ -637,7 +867,7 @@ impl Module { // Payout let reward = >::take(); if !reward.is_zero() { - let validators = >::validators(); + let validators = Self::current_elected(); for v in validators.iter() { Self::reward_validator(v, reward); } @@ -661,58 +891,71 @@ impl Module { // Reassign all Stakers. let slot_stake = Self::select_validators(); - // Update the balances for slashing/rewarding according to the stakes. - >::put(Self::offline_slash() * slot_stake); + // Update the balances for rewarding according to the stakes. >::put(Self::session_reward() * slot_stake); } + fn slashable_balance_of(stash: &T::AccountId) -> BalanceOf { + Self::bonded(stash).and_then(Self::ledger).map(|l| l.total).unwrap_or_default() + } + /// Select a new validator set from the assembled stakers and their role preferences. /// - /// @returns the new SlotStake value. + /// Returns the new SlotStake value. fn select_validators() -> BalanceOf { - // Map of (would-be) validator account to amount of stake backing it. - let rounds = || >::get() as usize; let validators = || >::enumerate(); let nominators = || >::enumerate(); - let stash_of = |w| Self::stash_balance(&w); let min_validator_count = Self::minimum_validator_count() as usize; - let elected_candidates = phragmen::elect::( + let maybe_elected_candidates = elect::( rounds, validators, nominators, - stash_of, - min_validator_count + Self::slashable_balance_of, + min_validator_count, + ElectionConfig::> { + equalise: false, + tolerance: >::sa(10 as u64), + iterations: 10, + } ); - // Figure out the minimum stake behind a slot. - let slot_stake = elected_candidates - .iter() - .min_by_key(|c| c.exposure.total) - .map(|c| c.exposure.total) - .unwrap_or_default(); - >::put(&slot_stake); - - // Clear Stakers and reduce their slash_count. - for v in >::validators().iter() { - >::remove(v); - let slash_count = >::take(v); - if slash_count > 1 { - >::insert(v, slash_count - 1); + if let Some(elected_candidates) = maybe_elected_candidates { + // Clear Stakers and reduce their slash_count. + for v in Self::current_elected().iter() { + >::remove(v); + let slash_count = >::take(v); + if slash_count > 1 { + >::insert(v, slash_count - 1); + } } - } - // Populate Stakers. - for candidate in &elected_candidates { - >::insert(candidate.who.clone(), candidate.exposure.clone()); - } + // Populate Stakers and figure out the minimum stake behind a slot. + let mut slot_stake = elected_candidates[0].exposure.total; + for c in &elected_candidates { + if c.exposure.total < slot_stake { + slot_stake = c.exposure.total; + } + >::insert(c.who.clone(), c.exposure.clone()); + } + >::put(&slot_stake); - // Set the new validator set. - >::set_validators( - &elected_candidates.into_iter().map(|i| i.who).collect::>() - ); - - slot_stake + // Set the new validator set. + let elected_stashes = elected_candidates.into_iter().map(|i| i.who).collect::>(); + >::put(&elected_stashes); + >::set_validators( + &elected_stashes.into_iter().map(|s| Self::bonded(s).unwrap_or_default()).collect::>() + ); + + slot_stake + } else { + // There were not enough candidates for even our minimal level of functionality. + // This is bad. + // We should probably disable all functionality except for block production + // and let the chain keep producing blocks until we can decide on a sufficiently + // substantial set. + Self::slot_stake() + } } /// Call when a validator is determined to be offline. `count` is the @@ -724,10 +967,6 @@ impl Module { if Self::invulnerables().contains(&v) { return } - // TODO: remove once Alex/CC updated #1785 - if Self::invulerables().contains(&v) { - return - } let slash_count = Self::slash_count(&v); let new_slash_count = slash_count + count as u32; @@ -753,13 +992,14 @@ impl Module { let max_slashes = grace + unstake_threshold; let event = if new_slash_count > max_slashes { - let slot_stake = Self::slot_stake(); + let slash_exposure = Self::stakers(&v).total; + let offline_slash_base = Self::offline_slash() * slash_exposure; // They're bailing. - let slash = Self::current_offline_slash() - // Multiply current_offline_slash by 2^(unstake_threshold with upper bound) + let slash = offline_slash_base + // Multiply slash_mantissa by 2^(unstake_threshold with upper bound) .checked_shl(unstake_threshold) - .map(|x| x.min(slot_stake)) - .unwrap_or(slot_stake); + .map(|x| x.min(slash_exposure)) + .unwrap_or(slash_exposure); let _ = Self::slash_validator(&v, slash); >::remove(&v); let _ = Self::apply_force_new_era(false); @@ -780,14 +1020,14 @@ impl OnSessionChange for Module { } impl OnFreeBalanceZero for Module { - fn on_free_balance_zero(who: &T::AccountId) { - if let Some(controller) = >::take(who) { + fn on_free_balance_zero(stash: &T::AccountId) { + if let Some(controller) = >::take(stash) { >::remove(&controller); - >::remove(&controller); - >::remove(&controller); - >::remove(&controller); - >::remove(&controller); } + >::remove(stash); + >::remove(stash); + >::remove(stash); + >::remove(stash); } } diff --git a/srml/staking/src/mock.rs b/srml/staking/src/mock.rs index c52baa06db9cc..30427f22f75fa 100644 --- a/srml/staking/src/mock.rs +++ b/srml/staking/src/mock.rs @@ -84,12 +84,12 @@ pub struct ExtBuilder { session_length: u64, sessions_per_era: u64, current_era: u64, - monied: bool, reward: u64, validator_pool: bool, nominate: bool, validator_count: u32, minimum_validator_count: u32, + fare: bool, } impl Default for ExtBuilder { @@ -99,12 +99,12 @@ impl Default for ExtBuilder { session_length: 1, sessions_per_era: 1, current_era: 0, - monied: true, reward: 10, validator_pool: false, nominate: true, validator_count: 2, minimum_validator_count: 0, + fare: true } } } @@ -126,16 +126,7 @@ impl ExtBuilder { self.current_era = current_era; self } - pub fn _monied(mut self, monied: bool) -> Self { - self.monied = monied; - self - } - pub fn reward(mut self, reward: u64) -> Self { - self.reward = reward; - self - } - pub fn validator_pool(mut self, validator_pool: bool) -> Self { - // NOTE: this should only be set to true with monied = false. + pub fn validator_pool(mut self, validator_pool: bool) -> Self { self.validator_pool = validator_pool; self } @@ -152,6 +143,10 @@ impl ExtBuilder { self.minimum_validator_count = count; self } + pub fn fare(mut self, is_fare: bool) -> Self { + self.fare = is_fare; + self + } pub fn build(self) -> runtime_io::TestExternalities { let (mut t, mut c) = system::GenesisConfig::::default().build_storage().unwrap(); let balance_factor = if self.existential_deposit > 0 { @@ -170,34 +165,22 @@ impl ExtBuilder { keys: vec![], }.assimilate_storage(&mut t, &mut c); let _ = balances::GenesisConfig::{ - balances: if self.monied { - if self.reward > 0 { - vec![ - (1, 10 * balance_factor), - (2, 20 * balance_factor), - (3, 300 * balance_factor), - (4, 400 * balance_factor), - (10, balance_factor), - (11, balance_factor * 1000), - (20, balance_factor), - (21, balance_factor * 2000), - (100, 2000 * balance_factor), - (101, 2000 * balance_factor), - ] - } else { - vec![ - (1, 10 * balance_factor), (2, 20 * balance_factor), - (3, 300 * balance_factor), (4, 400 * balance_factor) - ] - } - } else { - vec![ - (10, balance_factor), (11, balance_factor * 10), - (20, balance_factor), (21, balance_factor * 20), - (30, balance_factor), (31, balance_factor * 30), - (40, balance_factor), (41, balance_factor * 40) - ] - }, + balances: vec![ + (1, 10 * balance_factor), + (2, 20 * balance_factor), + (3, 300 * balance_factor), + (4, 400 * balance_factor), + (10, balance_factor), + (11, balance_factor * 1000), + (20, balance_factor), + (21, balance_factor * 2000), + (30, balance_factor), + (31, balance_factor * 2000), + (40, balance_factor), + (41, balance_factor * 2000), + (100, 2000 * balance_factor), + (101, 2000 * balance_factor), + ], transaction_base_fee: 0, transaction_byte_fee: 0, existential_deposit: self.existential_deposit, @@ -211,27 +194,26 @@ impl ExtBuilder { stakers: if self.validator_pool { vec![ (11, 10, balance_factor * 1000, StakerStatus::::Validator), - (21, 20, balance_factor * 2000, StakerStatus::::Validator), - (31, 30, balance_factor * 3000, if self.validator_pool { StakerStatus::::Validator } else { StakerStatus::::Idle }), - (41, 40, balance_factor * 4000, if self.validator_pool { StakerStatus::::Validator } else { StakerStatus::::Idle }), + (21, 20, balance_factor * if self.fare { 1000 } else { 2000 }, StakerStatus::::Validator), + (31, 30, balance_factor * 1000, if self.validator_pool { StakerStatus::::Validator } else { StakerStatus::::Idle }), + (41, 40, balance_factor * 1000, if self.validator_pool { StakerStatus::::Validator } else { StakerStatus::::Idle }), // nominator - (101, 100, balance_factor * 500, if self.nominate { StakerStatus::::Nominator(vec![10, 20]) } else { StakerStatus::::Nominator(vec![]) }) + (101, 100, balance_factor * 500, if self.nominate { StakerStatus::::Nominator(vec![11, 21]) } else { StakerStatus::::Nominator(vec![]) }) ] } else { vec![ (11, 10, balance_factor * 1000, StakerStatus::::Validator), - (21, 20, balance_factor * 2000, StakerStatus::::Validator), + (21, 20, balance_factor * if self.fare { 1000 } else { 2000 }, StakerStatus::::Validator), // nominator - (101, 100, balance_factor * 500, if self.nominate { StakerStatus::::Nominator(vec![10, 20]) } else { StakerStatus::::Nominator(vec![]) }) + (101, 100, balance_factor * 500, if self.nominate { StakerStatus::::Nominator(vec![11, 21]) } else { StakerStatus::::Nominator(vec![]) }) ] }, validator_count: self.validator_count, minimum_validator_count: self.minimum_validator_count, bonding_duration: self.sessions_per_era * self.session_length * 3, session_reward: Perbill::from_millionths((1000000 * self.reward / balance_factor) as u32), - offline_slash: if self.monied { Perbill::from_percent(40) } else { Perbill::zero() }, + offline_slash: Perbill::from_percent(5), current_session_reward: self.reward, - current_offline_slash: 20, offline_slash_grace: 0, invulnerables: vec![], }.assimilate_storage(&mut t, &mut c); diff --git a/srml/staking/src/phragmen.rs b/srml/staking/src/phragmen.rs index bdaed1fee9760..5d6548bfd0378 100644 --- a/srml/staking/src/phragmen.rs +++ b/srml/staking/src/phragmen.rs @@ -1,4 +1,4 @@ -// Copyright 2017-2019 Parity Technologies (UK) Ltd. +// Copyright 2019 Parity Technologies (UK) Ltd. // This file is part of Substrate. // Substrate is free software: you can redistribute it and/or modify @@ -16,208 +16,342 @@ //! Rust implementation of the Phragmén election algorithm. -use rstd::{prelude::*}; +use rstd::prelude::*; use primitives::Perquintill; -use primitives::traits::{Zero, As}; +use primitives::traits::{Zero, As, Bounded, CheckedMul, CheckedSub}; use parity_codec::{HasCompact, Encode, Decode}; use crate::{Exposure, BalanceOf, Trait, ValidatorPrefs, IndividualExposure}; + +// Configure the behavior of the Phragmen election. +// Might be deprecated. +pub struct ElectionConfig { + // Perform equalise?. + pub equalise: bool, + // Number of equalise iterations. + pub iterations: usize, + // Tolerance of max change per equalise iteration. + pub tolerance: Balance, +} + // Wrapper around validation candidates some metadata. -#[derive(Clone, Encode, Decode)] +#[derive(Clone, Encode, Decode, Default)] #[cfg_attr(feature = "std", derive(Debug))] pub struct Candidate { // The validator's account pub who: AccountId, // Exposure struct, holding info about the value that the validator has in stake. pub exposure: Exposure, - // Accumulator of the stake of this candidate based on received votes. - approval_stake: Balance, // Intermediary value used to sort candidates. - // See Phragmén reference implementation. pub score: Perquintill, + // Accumulator of the stake of this candidate based on received votes. + approval_stake: Balance, + // Flag for being elected. + elected: bool, + // This is most often equal to `Exposure.total` but not always. Needed for [`equalise`] + backing_stake: Balance } // Wrapper around the nomination info of a single nominator for a group of validators. -#[derive(Clone, Encode, Decode)] +#[derive(Clone, Encode, Decode, Default)] #[cfg_attr(feature = "std", derive(Debug))] -pub struct Nominations { +pub struct Nominator { // The nominator's account. who: AccountId, // List of validators proposed by this nominator. - nominees: Vec>, + edges: Vec>, // the stake amount proposed by the nominator as a part of the vote. - // Same as `nom.budget` in Phragmén reference. - stake: Balance, + budget: Balance, // Incremented each time a nominee that this nominator voted for has been elected. load: Perquintill, } // Wrapper around a nominator vote and the load of that vote. -// Referred to as 'edge' in the Phragmén reference implementation. -#[derive(Clone, Encode, Decode)] +#[derive(Clone, Encode, Decode, Default)] #[cfg_attr(feature = "std", derive(Debug))] -pub struct Vote { +pub struct Edge { // Account being voted for who: AccountId, // Load of this vote. load: Perquintill, // Final backing stake of this vote. - backing_stake: Balance + backing_stake: Balance, + // Index of the candidate stored in the 'candidates' vector + candidate_index: usize, + // Index of the candidate stored in the 'elected_candidates' vector. Used only with equalise. + elected_idx: usize, + // Indicates if this edge is a vote for an elected candidate. Used only with equalise. + elected: bool, } /// Perform election based on Phragmén algorithm. /// /// Reference implementation: https://github.com/w3f/consensus /// -/// @returns a vector of elected candidates +/// Returns a vector of elected candidates pub fn elect( get_rounds: FR, get_validators: FV, get_nominators: FN, stash_of: FS, minimum_validator_count: usize, - ) -> Vec>> where - FR: Fn() -> usize, - FV: Fn() -> Box>) - >>, - FN: Fn() -> Box) - >>, - FS: Fn(T::AccountId) -> BalanceOf, + config: ElectionConfig>, +) -> Option>>> where + FR: Fn() -> usize, + FV: Fn() -> Box>) + >>, + FN: Fn() -> Box) + >>, + for <'r> FS: Fn(&'r T::AccountId) -> BalanceOf, { let rounds = get_rounds(); - let mut elected_candidates = vec![]; - + let mut elected_candidates; + // 1- Pre-process candidates and place them in a container let mut candidates = get_validators().map(|(who, _)| { - let stash_balance = stash_of(who.clone()); + let stash_balance = stash_of(&who); Candidate { who, - approval_stake: BalanceOf::::zero(), - score: Perquintill::zero(), exposure: Exposure { total: stash_balance, own: stash_balance, others: vec![] }, + ..Default::default() } }).collect::>>>(); - // Just to be used when we are below minimum validator count - let original_candidates = candidates.clone(); - + // 1.1- Add phantom votes. + let mut nominators: Vec>> = Vec::with_capacity(candidates.len()); + candidates.iter_mut().enumerate().for_each(|(idx, c)| { + c.approval_stake += c.exposure.total; + nominators.push(Nominator { + who: c.who.clone(), + edges: vec![ Edge { who: c.who.clone(), candidate_index: idx, ..Default::default() }], + budget: c.exposure.total, + load: Perquintill::zero(), + }) + }); + // 2- Collect the nominators with the associated votes. // Also collect approval stake along the way. - let mut nominations = get_nominators().map(|(who, nominees)| { - let nominator_stake = stash_of(who.clone()); + nominators.extend(get_nominators().map(|(who, nominees)| { + let nominator_stake = stash_of(&who); + let mut edges: Vec>> = Vec::with_capacity(nominees.len()); for n in &nominees { - candidates.iter_mut().filter(|i| i.who == *n).for_each(|c| { - c.approval_stake += nominator_stake; - }); + if let Some(idx) = candidates.iter_mut().position(|i| i.who == *n) { + candidates[idx].approval_stake += nominator_stake; + edges.push(Edge { who: n.clone(), candidate_index: idx, ..Default::default() }); + } } - Nominations { + Nominator { who, - nominees: nominees.into_iter() - .map(|n| Vote {who: n, load: Perquintill::zero(), backing_stake: BalanceOf::::zero()}) - .collect::>>>(), - stake: nominator_stake, - load : Perquintill::zero(), + edges: edges, + budget: nominator_stake, + load: Perquintill::zero(), } - }).collect::>>>(); - + })); + + // 3- optimization: // Candidates who have 0 stake => have no votes or all null-votes. Kick them out not. let mut candidates = candidates.into_iter().filter(|c| c.approval_stake > BalanceOf::::zero()) .collect::>>>(); // 4- If we have more candidates then needed, run Phragmén. - if candidates.len() > rounds { + if candidates.len() >= rounds { + elected_candidates = Vec::with_capacity(rounds); // Main election loop for _round in 0..rounds { // Loop 1: initialize score - for nominaotion in &nominations { - for vote in &nominaotion.nominees { - let candidate = &vote.who; - if let Some(c) = candidates.iter_mut().find(|i| i.who == *candidate) { - let approval_stake = c.approval_stake; - c.score = Perquintill::from_xth(approval_stake.as_()); - } + for c in &mut candidates { + if !c.elected { + c.score = Perquintill::from_xth(c.approval_stake.as_()); } } // Loop 2: increment score. - for nominaotion in &nominations { - for vote in &nominaotion.nominees { - let candidate = &vote.who; - if let Some(c) = candidates.iter_mut().find(|i| i.who == *candidate) { - let approval_stake = c.approval_stake; - let temp = - nominaotion.stake.as_() - * *nominaotion.load - / approval_stake.as_(); + for n in &nominators { + for e in &n.edges { + let c = &mut candidates[e.candidate_index]; + if !c.elected { + let temp = n.budget.as_() * *n.load / c.approval_stake.as_(); c.score = Perquintill::from_quintillionths(*c.score + temp); } } } // Find the best - let (winner_index, _) = candidates.iter().enumerate().min_by_key(|&(_i, c)| *c.score) + let winner = candidates + .iter_mut() + .filter(|c| !c.elected) + .min_by_key(|c| *c.score) .expect("candidates length is checked to be >0; qed"); - // loop 3: update nominator and vote load - let winner = candidates.remove(winner_index); - for n in &mut nominations { - for v in &mut n.nominees { - if v.who == winner.who { - v.load = - Perquintill::from_quintillionths( - *winner.score - - *n.load - ); + // loop 3: update nominator and edge load + winner.elected = true; + for n in &mut nominators { + for e in &mut n.edges { + if e.who == winner.who { + e.load = Perquintill::from_quintillionths(*winner.score - *n.load); n.load = winner.score; } } } - elected_candidates.push(winner); - + elected_candidates.push(winner.clone()); } // end of all rounds // 4.1- Update backing stake of candidates and nominators - for n in &mut nominations { - for v in &mut n.nominees { + for n in &mut nominators { + for e in &mut n.edges { // if the target of this vote is among the winners, otherwise let go. - if let Some(c) = elected_candidates.iter_mut().find(|c| c.who == v.who) { - v.backing_stake = as As>::sa( - n.stake.as_() - * *v.load - / *n.load - ); - c.exposure.total += v.backing_stake; - // Update IndividualExposure of those who nominated and their vote won - c.exposure.others.push( - IndividualExposure {who: n.who.clone(), value: v.backing_stake } - ); + if let Some(c) = elected_candidates.iter_mut().find(|c| c.who == e.who) { + e.elected = true; + // NOTE: for now, always divide last to avoid collapse to zero. + e.backing_stake = >::sa((n.budget.as_() * *e.load) / *n.load); + c.backing_stake += e.backing_stake; + if c.who != n.who { + // Only update the exposure if this vote is from some other account. + c.exposure.total += e.backing_stake; + c.exposure.others.push( + IndividualExposure { who: n.who.clone(), value: e.backing_stake } + ); + } + } + } + } + + // Optionally perform equalise post-processing. + if config.equalise { + let tolerance = config.tolerance; + let equalise_iterations = config.iterations; + + // Fix indexes + nominators.iter_mut().for_each(|n| { + n.edges.iter_mut().for_each(|e| { + if let Some(idx) = elected_candidates.iter().position(|c| c.who == e.who) { + e.elected_idx = idx; + } + }); + }); + + for _i in 0..equalise_iterations { + let mut max_diff = >::zero(); + nominators.iter_mut().for_each(|mut n| { + let diff = equalise::(&mut n, &mut elected_candidates, tolerance); + if diff > max_diff { + max_diff = diff; + } + }); + if max_diff < tolerance { + break; } } } + } else { if candidates.len() > minimum_validator_count { // if we don't have enough candidates, just choose all that have some vote. elected_candidates = candidates; - // `Exposure.others` still needs an update - for n in &mut nominations { - for v in &mut n.nominees { - if let Some(c) = elected_candidates.iter_mut().find(|c| c.who == v.who) { - c.exposure.total += n.stake; + for n in &mut nominators { + let nominator = n.who.clone(); + for e in &mut n.edges { + if let Some(c) = elected_candidates.iter_mut().find(|c| c.who == e.who && c.who != nominator) { + c.exposure.total += n.budget; c.exposure.others.push( - IndividualExposure {who: n.who.clone(), value: n.stake } + IndividualExposure { who: n.who.clone(), value: n.budget } ); } } } } else { // if we have less than minimum, use the previous validator set. - elected_candidates = original_candidates; + return None + } + } + Some(elected_candidates) +} + +pub fn equalise( + nominator: &mut Nominator>, + elected_candidates: &mut Vec>>, + tolerance: BalanceOf +) -> BalanceOf { + + let mut elected_edges = nominator.edges + .iter_mut() + .filter(|e| e.elected) + .collect::>>>(); + if elected_edges.len() == 0 { return >::zero(); } + let stake_used = elected_edges + .iter() + .fold(>::zero(), |s, e| s + e.backing_stake); + let backed_stakes = elected_edges + .iter() + .map(|e| elected_candidates[e.elected_idx].backing_stake) + .collect::>>(); + let backing_backed_stake = elected_edges + .iter() + .filter(|e| e.backing_stake > >::zero()) + .map(|e| elected_candidates[e.elected_idx].backing_stake) + .collect::>>(); + + let mut difference; + if backing_backed_stake.len() > 0 { + let max_stake = *backing_backed_stake + .iter() + .max() + .expect("vector with positive length will have a max; qed"); + let min_stake = *backed_stakes + .iter() + .min() + .expect("vector with positive length will have a max; qed"); + difference = max_stake - min_stake; + difference += nominator.budget - stake_used; + if difference < tolerance { + return difference; } + } else { + difference = nominator.budget; } - elected_candidates -} \ No newline at end of file + // Undo updates to exposure + elected_edges.iter_mut().for_each(|e| { + // NOTE: no assertions in the runtime, but this should nonetheless be indicative. + //assert_eq!(elected_candidates[e.elected_idx].who, e.who); + elected_candidates[e.elected_idx].backing_stake -= e.backing_stake; + elected_candidates[e.elected_idx].exposure.total -= e.backing_stake; + e.backing_stake = >::zero(); + }); + + elected_edges.sort_unstable_by_key(|e| elected_candidates[e.elected_idx].backing_stake); + + let mut cumulative_stake = >::zero(); + let mut last_index = elected_edges.len() - 1; + let budget = nominator.budget; + elected_edges.iter_mut().enumerate().for_each(|(idx, e)| { + let stake = elected_candidates[e.elected_idx].backing_stake; + + let stake_mul = stake.checked_mul(&>::sa(idx as u64)).unwrap_or(>::max_value()); + let stake_sub = stake_mul.checked_sub(&cumulative_stake).unwrap_or_default(); + if stake_sub > budget { + last_index = idx.clone().checked_sub(1).unwrap_or(0); + return + } + cumulative_stake += stake; + }); + + let last_stake = elected_candidates[elected_edges[last_index].elected_idx].backing_stake; + let split_ways = last_index + 1; + let excess = nominator.budget + cumulative_stake - last_stake * >::sa(split_ways as u64); + let nominator_address = nominator.who.clone(); + elected_edges.iter_mut().take(split_ways).for_each(|e| { + let c = &mut elected_candidates[e.elected_idx]; + e.backing_stake = excess / >::sa(split_ways as u64) + last_stake - c.backing_stake; + c.exposure.total += e.backing_stake; + c.backing_stake += e.backing_stake; + if let Some(i_expo) = c.exposure.others.iter_mut().find(|i| i.who == nominator_address) { + i_expo.value = e.backing_stake; + } + }); + difference +} diff --git a/srml/staking/src/tests.rs b/srml/staking/src/tests.rs index 527e82cf97156..50c5772985925 100644 --- a/srml/staking/src/tests.rs +++ b/srml/staking/src/tests.rs @@ -39,23 +39,24 @@ fn basic_setup_works() { // Account 10 controls the stash from account 11, which is 100 * balance_factor units assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000, active: 1000, unlocking: vec![] })); // Account 20 controls the stash from account 21, which is 200 * balance_factor units - assert_eq!(Staking::ledger(&20), Some(StakingLedger { stash: 21, total: 2000, active: 2000, unlocking: vec![] })); + assert_eq!(Staking::ledger(&20), Some(StakingLedger { stash: 21, total: 1000, active: 1000, unlocking: vec![] })); // Account 1 does not control any stash assert_eq!(Staking::ledger(&1), None); // ValidatorPrefs are default, thus unstake_threshold is 3, other values are default for their type assert_eq!(>::enumerate().collect::>(), vec![ - (20, ValidatorPrefs { unstake_threshold: 3, validator_payment: 0 }), - (10, ValidatorPrefs { unstake_threshold: 3, validator_payment: 0 }) + (21, ValidatorPrefs { unstake_threshold: 3, validator_payment: 0 }), + (11, ValidatorPrefs { unstake_threshold: 3, validator_payment: 0 }) ]); // Account 100 is the default nominator assert_eq!(Staking::ledger(100), Some(StakingLedger { stash: 101, total: 500, active: 500, unlocking: vec![] })); - assert_eq!(Staking::nominators(100), vec![10, 20]); + assert_eq!(Staking::nominators(101), vec![11, 21]); - // Account 10 is exposed by 100 * balance_factor from their own stash in account 11 - assert_eq!(Staking::stakers(10), Exposure { total: 1500, own: 1000, others: vec![ IndividualExposure { who: 100, value: 500 }] }); - assert_eq!(Staking::stakers(20), Exposure { total: 2500, own: 2000, others: vec![ IndividualExposure { who: 100, value: 500 }] }); + // Account 10 is exposed by 1000 * balance_factor from their own stash in account 11 + the default nominator vote + assert_eq!(Staking::stakers(11), Exposure { total: 1125, own: 1000, others: vec![ IndividualExposure { who: 101, value: 125 }] }); + // Account 20 is exposed by 1000 * balance_factor from their own stash in account 21 + the default nominator vote + assert_eq!(Staking::stakers(21), Exposure { total: 1375, own: 1000, others: vec![ IndividualExposure { who: 101, value: 375 }] }); // The number of validators required. assert_eq!(Staking::validator_count(), 2); @@ -68,11 +69,12 @@ fn basic_setup_works() { assert_eq!(Staking::current_session_reward(), 10); // initial slot_stake - assert_eq!(Staking::slot_stake(), 1500); + assert_eq!(Staking::slot_stake(), 1125); // Naive + // assert_eq!(Staking::slot_stake(), 1250); // Post-process - // initial slash_count of validators - assert_eq!(Staking::slash_count(&10), 0); - assert_eq!(Staking::slash_count(&20), 0); + // initial slash_count of validators + assert_eq!(Staking::slash_count(&11), 0); + assert_eq!(Staking::slash_count(&21), 0); }); } @@ -100,27 +102,27 @@ fn invulnerability_should_work() { // Test that users can be invulnerable from slashing and being kicked with_externalities(&mut ExtBuilder::default().build(), || { - // Make account 10 invulnerable - assert_ok!(Staking::set_invulnerables(vec![10])); - // Give account 10 some funds - let _ = Balances::deposit_creating(&10, 69); + // Make account 11 invulnerable + assert_ok!(Staking::set_invulnerables(vec![11])); + // Give account 11 some funds + let _ = Balances::ensure_free_balance_is(&11, 70); // There is no slash grace -- slash immediately. assert_eq!(Staking::offline_slash_grace(), 0); - // Account 10 has not been slashed - assert_eq!(Staking::slash_count(&10), 0); - // Account 10 has the 70 funds we gave it above - assert_eq!(Balances::free_balance(&10), 70); - // Account 10 should be a validator - assert!(>::exists(&10)); - - // Set account 10 as an offline validator with a large number of reports + // Account 11 has not been slashed + assert_eq!(Staking::slash_count(&11), 0); + // Account 11 has the 70 funds we gave it above + assert_eq!(Balances::free_balance(&11), 70); + // Account 11 should be a validator + assert!(>::exists(&11)); + + // Set account 11 as an offline validator with a large number of reports // Should exit early if invulnerable - Staking::on_offline_validator(10, 100); + Staking::on_offline_validator(11, 100); - // Show that account 10 has not been touched - assert_eq!(Staking::slash_count(&10), 0); - assert_eq!(Balances::free_balance(&10), 70); - assert!(>::exists(&10)); + // Show that account 11 has not been touched + assert_eq!(Staking::slash_count(&11), 0); + assert_eq!(Balances::free_balance(&11), 70); + assert!(>::exists(&11)); // New era not being forced // NOTE: new era is always forced once slashing happens -> new validators need to be chosen. assert!(Staking::forcing_new_era().is_none()); @@ -132,27 +134,26 @@ fn offline_should_slash_and_kick() { // Test that an offline validator gets slashed and kicked with_externalities(&mut ExtBuilder::default().build(), || { // Give account 10 some balance - let _ = Balances::deposit_creating(&10, 999); + let _ = Balances::ensure_free_balance_is(&11, 1000); // Confirm account 10 is a validator - assert!(>::exists(&10)); + assert!(>::exists(&11)); // Validators get slashed immediately assert_eq!(Staking::offline_slash_grace(), 0); // Unstake threshold is 3 - assert_eq!(Staking::validators(&10).unstake_threshold, 3); + assert_eq!(Staking::validators(&11).unstake_threshold, 3); // Account 10 has not been slashed before - assert_eq!(Staking::slash_count(&10), 0); + assert_eq!(Staking::slash_count(&11), 0); // Account 10 has the funds we just gave it - assert_eq!(Balances::free_balance(&10), 1000); + assert_eq!(Balances::free_balance(&11), 1000); // Report account 10 as offline, one greater than unstake threshold - Staking::on_offline_validator(10, 4); + Staking::on_offline_validator(11, 4); // Confirm user has been reported - assert_eq!(Staking::slash_count(&10), 4); - // Confirm `slot_stake` is greater than exponential punishment, else math below will be different - assert!(Staking::slot_stake() > 2_u64.pow(3) * 20); - // Confirm balance has been reduced by 2^unstake_threshold * current_offline_slash() - assert_eq!(Balances::free_balance(&10), 1000 - 2_u64.pow(3) * 20); + assert_eq!(Staking::slash_count(&11), 4); + // Confirm balance has been reduced by 2^unstake_threshold * offline_slash() * amount_at_stake. + let slash_base = Staking::offline_slash() * Staking::stakers(11).total; + assert_eq!(Balances::free_balance(&11), 1000 - 2_u64.pow(3) * slash_base); // Confirm account 10 has been removed as a validator - assert!(!>::exists(&10)); + assert!(!>::exists(&11)); // A new era is forced due to slashing assert!(Staking::forcing_new_era().is_some()); }); @@ -163,9 +164,9 @@ fn offline_grace_should_delay_slashing() { // Tests that with grace, slashing is delayed with_externalities(&mut ExtBuilder::default().build(), || { // Initialize account 10 with balance - let _ = Balances::deposit_creating(&10, 69); - // Verify account 10 has balance - assert_eq!(Balances::free_balance(&10), 70); + let _ = Balances::ensure_free_balance_is(&11, 70); + // Verify account 11 has balance + assert_eq!(Balances::free_balance(&11), 70); // Set offline slash grace let offline_slash_grace = 1; @@ -174,24 +175,24 @@ fn offline_grace_should_delay_slashing() { // Check unstaked_threshold is 3 (default) let default_unstake_threshold = 3; - assert_eq!(Staking::validators(&10), ValidatorPrefs { unstake_threshold: default_unstake_threshold, validator_payment: 0 }); + assert_eq!(Staking::validators(&11), ValidatorPrefs { unstake_threshold: default_unstake_threshold, validator_payment: 0 }); // Check slash count is zero - assert_eq!(Staking::slash_count(&10), 0); + assert_eq!(Staking::slash_count(&11), 0); // Report account 10 up to the threshold - Staking::on_offline_validator(10, default_unstake_threshold as usize + offline_slash_grace as usize); + Staking::on_offline_validator(11, default_unstake_threshold as usize + offline_slash_grace as usize); // Confirm slash count - assert_eq!(Staking::slash_count(&10), 4); + assert_eq!(Staking::slash_count(&11), 4); // Nothing should happen - assert_eq!(Balances::free_balance(&10), 70); + assert_eq!(Balances::free_balance(&11), 70); // Report account 10 one more time - Staking::on_offline_validator(10, 1); - assert_eq!(Staking::slash_count(&10), 5); + Staking::on_offline_validator(11, 1); + assert_eq!(Staking::slash_count(&11), 5); // User gets slashed - assert_eq!(Balances::free_balance(&10), 0); + assert_eq!(Balances::free_balance(&11), 0); // New era is forced assert!(Staking::forcing_new_era().is_some()); }); @@ -204,19 +205,17 @@ fn max_unstake_threshold_works() { with_externalities(&mut ExtBuilder::default().build(), || { const MAX_UNSTAKE_THRESHOLD: u32 = 10; // Two users with maximum possible balance - let _ = Balances::deposit_creating(&10, u64::max_value() - 1); - let _ = Balances::deposit_creating(&20, u64::max_value() - 1); + let _ = Balances::ensure_free_balance_is(&11, u64::max_value()); + let _ = Balances::ensure_free_balance_is(&21, u64::max_value()); - // Give them full exposer as a staker - >::insert(&10, Exposure { total: u64::max_value(), own: u64::max_value(), others: vec![]}); - >::insert(&20, Exposure { total: u64::max_value(), own: u64::max_value(), others: vec![]}); + // Give them full exposure as a staker + >::insert(&11, Exposure { total: 1000000, own: 1000000, others: vec![]}); + >::insert(&21, Exposure { total: 2000000, own: 2000000, others: vec![]}); // Check things are initialized correctly - assert_eq!(Balances::free_balance(&10), u64::max_value()); - assert_eq!(Balances::free_balance(&20), u64::max_value()); - assert_eq!(Balances::free_balance(&10), Balances::free_balance(&20)); + assert_eq!(Balances::free_balance(&11), u64::max_value()); + assert_eq!(Balances::free_balance(&21), u64::max_value()); assert_eq!(Staking::offline_slash_grace(), 0); - assert_eq!(Staking::current_offline_slash(), 20); // Account 10 will have max unstake_threshold assert_ok!(Staking::validate(Origin::signed(10), ValidatorPrefs { unstake_threshold: MAX_UNSTAKE_THRESHOLD, @@ -224,28 +223,26 @@ fn max_unstake_threshold_works() { })); // Account 20 could not set their unstake_threshold past 10 assert_noop!(Staking::validate(Origin::signed(20), ValidatorPrefs { - unstake_threshold: 11, + unstake_threshold: MAX_UNSTAKE_THRESHOLD + 1, validator_payment: 0}), "unstake threshold too large" ); // Give Account 20 unstake_threshold 11 anyway, should still be limited to 10 - >::insert(20, ValidatorPrefs { - unstake_threshold: 11, + >::insert(21, ValidatorPrefs { + unstake_threshold: MAX_UNSTAKE_THRESHOLD + 1, validator_payment: 0, }); - // Make slot_stake really large, as to not affect punishment curve - >::put(u64::max_value()); - // Confirm `slot_stake` is greater than exponential punishment, else math below will be different - assert!(Staking::slot_stake() > 2_u64.pow(MAX_UNSTAKE_THRESHOLD) * 20); + >::put(Perbill::from_fraction(0.0001)); // Report each user 1 more than the max_unstake_threshold - Staking::on_offline_validator(10, MAX_UNSTAKE_THRESHOLD as usize + 1); - Staking::on_offline_validator(20, MAX_UNSTAKE_THRESHOLD as usize + 1); + Staking::on_offline_validator(11, MAX_UNSTAKE_THRESHOLD as usize + 1); + Staking::on_offline_validator(21, MAX_UNSTAKE_THRESHOLD as usize + 1); - // Show that each balance only gets reduced by 2^max_unstake_threshold - assert_eq!(Balances::free_balance(&10), u64::max_value() - 2_u64.pow(MAX_UNSTAKE_THRESHOLD) * 20); - assert_eq!(Balances::free_balance(&20), u64::max_value() - 2_u64.pow(MAX_UNSTAKE_THRESHOLD) * 20); + // Show that each balance only gets reduced by 2^max_unstake_threshold times 10% + // of their total stake. + assert_eq!(Balances::free_balance(&11), u64::max_value() - 2_u64.pow(MAX_UNSTAKE_THRESHOLD) * 100); + assert_eq!(Balances::free_balance(&21), u64::max_value() - 2_u64.pow(MAX_UNSTAKE_THRESHOLD) * 200); }); } @@ -254,11 +251,11 @@ fn slashing_does_not_cause_underflow() { // Tests that slashing more than a user has does not underflow with_externalities(&mut ExtBuilder::default().build(), || { // Verify initial conditions - assert_eq!(Balances::free_balance(&10), 1); + assert_eq!(Balances::free_balance(&11), 1000); assert_eq!(Staking::offline_slash_grace(), 0); // Set validator preference so that 2^unstake_threshold would cause overflow (greater than 64) - >::insert(10, ValidatorPrefs { + >::insert(11, ValidatorPrefs { unstake_threshold: 10, validator_payment: 0, }); @@ -267,9 +264,9 @@ fn slashing_does_not_cause_underflow() { Session::check_rotate_session(System::block_number()); // Should not panic - Staking::on_offline_validator(10, 100); + Staking::on_offline_validator(11, 100); // Confirm that underflow has not occurred, and account balance is set to zero - assert_eq!(Balances::free_balance(&10), 0); + assert_eq!(Balances::free_balance(&11), 0); }); } @@ -285,7 +282,7 @@ fn rewards_should_work() { .sessions_per_era(3) .build(), || { - let delay = 2; + let delay = 0; // this test is only in the scope of one era. Since this variable changes // at the last block/new era, we'll save it. let session_reward = 10; @@ -299,36 +296,38 @@ fn rewards_should_work() { assert_eq!(Staking::last_era_length_change(), 0); assert_eq!(Staking::current_era(), 0); assert_eq!(Session::current_index(), 0); - assert_eq!(Staking::current_session_reward(), 10); // check the balance of a validator accounts. - assert_eq!(Balances::total_balance(&10), 1); + assert_eq!(Balances::total_balance(&11), 1000); // and the nominator (to-be) - assert_eq!(Balances::total_balance(&2), 20); + let _ = Balances::ensure_free_balance_is(&2, 500); + assert_eq!(Balances::total_balance(&2), 500); // add a dummy nominator. // NOTE: this nominator is being added 'manually'. a Further test (nomination_and_reward..) will add it via '.nominate()' - >::insert(&10, Exposure { + >::insert(&11, Exposure { own: 500, // equal division indicates that the reward will be equally divided among validator and nominator. total: 1000, others: vec![IndividualExposure {who: 2, value: 500 }] }); - >::insert(&2, RewardDestination::Controller); + >::insert(&2, RewardDestination::Stash); + assert_eq!(Staking::payee(2), RewardDestination::Stash); + assert_eq!(Staking::payee(11), RewardDestination::Controller); let mut block = 3; // Block 3 => Session 1 => Era 0 System::set_block_number(block); Timestamp::set_timestamp(block*5); // on time. - Session::check_rotate_session(System::block_number()); + Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 0); assert_eq!(Session::current_index(), 1); // session triggered: the reward value stashed should be 10 -- defined in ExtBuilder genesis. assert_eq!(Staking::current_session_reward(), session_reward); assert_eq!(Staking::current_era_reward(), session_reward); - + block = 6; // Block 6 => Session 2 => Era 0 System::set_block_number(block); Timestamp::set_timestamp(block*5 + delay); // a little late. @@ -343,13 +342,13 @@ fn rewards_should_work() { block = 9; // Block 9 => Session 3 => Era 1 System::set_block_number(block); - Timestamp::set_timestamp(block*5); // back to being punktlisch. no delayss + Timestamp::set_timestamp(block*5); // back to being on time. no delays Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 1); assert_eq!(Session::current_index(), 3); assert_eq!(Balances::total_balance(&10), 1 + (3*session_reward - delay)/2); - assert_eq!(Balances::total_balance(&2), 20 + (3*session_reward - delay)/2); + assert_eq!(Balances::total_balance(&2), 500 + (3*session_reward - delay)/2); }); } @@ -387,7 +386,7 @@ fn multi_era_reward_should_work() { // session triggered: the reward value stashed should be 10 -- defined in ExtBuilder genesis. assert_eq!(Staking::current_session_reward(), session_reward); assert_eq!(Staking::current_era_reward(), session_reward); - + block = 6; // Block 6 => Session 2 => Era 0 System::set_block_number(block); Timestamp::set_timestamp(block*5 + delay); // a little late. @@ -408,7 +407,7 @@ fn multi_era_reward_should_work() { // 1 + sum of of the session rewards accumulated let recorded_balance = 1 + 3*session_reward - delay; assert_eq!(Balances::total_balance(&10), recorded_balance); - + // the reward for next era will be: session_reward * slot_stake let new_session_reward = Staking::session_reward() * Staking::slot_stake(); assert_eq!(Staking::current_session_reward(), new_session_reward); @@ -416,13 +415,13 @@ fn multi_era_reward_should_work() { // fast forward to next era: block=12;System::set_block_number(block);Timestamp::set_timestamp(block*5);Session::check_rotate_session(System::block_number()); block=15;System::set_block_number(block);Timestamp::set_timestamp(block*5);Session::check_rotate_session(System::block_number()); - + // intermediate test. assert_eq!(Staking::current_era_reward(), 2*new_session_reward); - + // new era is triggered here. block=18;System::set_block_number(block);Timestamp::set_timestamp(block*5);Session::check_rotate_session(System::block_number()); - + // pay time assert_eq!(Balances::total_balance(&10), 3*new_session_reward + recorded_balance); }); @@ -437,42 +436,35 @@ fn staking_should_work() { with_externalities(&mut ExtBuilder::default() .sessions_per_era(3) .nominate(false) + .fare(false) // to give 20 more staked value .build(), || { - assert_eq!(Staking::era_length(), 3); // remember + compare this along with the test. assert_eq!(Session::validators(), vec![20, 10]); + assert_ok!(Staking::set_bonding_duration(2)); assert_eq!(Staking::bonding_duration(), 2); // put some money in account that we'll use. - for i in 1..5 { let _ = Balances::deposit_creating(&i, 1000); } - - // bond one account pair and state interest in nomination. - // this is needed to keep 10 and 20 in the validator list with phragmen - assert_ok!(Staking::bond(Origin::signed(1), 2, 500, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(2), vec![20, 4])); + for i in 1..5 { let _ = Balances::ensure_free_balance_is(&i, 2000); } // --- Block 1: System::set_block_number(1); - - // add a new candidate for being a validator. account 3 controlled by 4. - assert_ok!(Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller)); // balance of 3 = 3000, stashed = 1500 - Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 0); - // No effects will be seen so far.s + + // add a new candidate for being a validator. account 3 controlled by 4. + assert_ok!(Staking::bond(Origin::signed(3), 4, 1500, RewardDestination::Controller)); + assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default())); + + // No effects will be seen so far. assert_eq!(Session::validators(), vec![20, 10]); - // --- Block 2: System::set_block_number(2); - // Explicitly state the desire to validate - // note that the controller account will state interest as representative of the stash-controller pair. - assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default())); - Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 0); + // No effects will be seen so far. Era has not been yet triggered. assert_eq!(Session::validators(), vec![20, 10]); @@ -483,32 +475,26 @@ fn staking_should_work() { // 2 only voted for 4 and 20 assert_eq!(Session::validators().len(), 2); - assert_eq!(Session::validators(), vec![4, 20]); + assert_eq!(Session::validators(), vec![20, 4]); assert_eq!(Staking::current_era(), 1); // --- Block 4: Unstake 4 as a validator, freeing up the balance stashed in 3 System::set_block_number(4); + Session::check_rotate_session(System::block_number()); - // unlock the entire stashed value. - // Note that this will ne be enough to remove 4 as a validator candidate! - Staking::unbond(Origin::signed(4), Staking::ledger(&4).unwrap().active).unwrap(); - // explicit chill indicated that 4 no longer wants to be a validator. + // 4 will chill Staking::chill(Origin::signed(4)).unwrap(); - - // nominator votes for 10 - assert_ok!(Staking::nominate(Origin::signed(2), vec![20, 10])); - - Session::check_rotate_session(System::block_number()); + // nothing should be changed so far. - assert_eq!(Session::validators(), vec![4, 20]); + assert_eq!(Session::validators(), vec![20, 4]); assert_eq!(Staking::current_era(), 1); - - + + // --- Block 5: nothing. 4 is still there. System::set_block_number(5); Session::check_rotate_session(System::block_number()); - assert_eq!(Session::validators(), vec![4, 20]); + assert_eq!(Session::validators(), vec![20, 4]); assert_eq!(Staking::current_era(), 1); @@ -518,6 +504,12 @@ fn staking_should_work() { assert_eq!(Staking::current_era(), 2); assert_eq!(Session::validators().contains(&4), false); assert_eq!(Session::validators(), vec![20, 10]); + + // Note: the stashed value of 4 is still lock + assert_eq!(Staking::ledger(&4), Some(StakingLedger { stash: 3, total: 1500, active: 1500, unlocking: vec![] })); + // e.g. it cannot spend more than 500 that it has free from the total 2000 + assert_noop!(Balances::reserve(&3, 501), "account liquidity restrictions prevent withdrawal"); + assert_ok!(Balances::reserve(&3, 409)); }); } @@ -529,21 +521,14 @@ fn less_than_needed_candidates_works() { .minimum_validator_count(1) .validator_count(3) .nominate(false) - .validator_pool(true) - .build(), + .build(), || { assert_eq!(Staking::era_length(), 1); assert_eq!(Staking::validator_count(), 3); - assert_eq!(Staking::minimum_validator_count(), 1); - assert_eq!(Staking::validator_count(), 3); - // initial validators - assert_eq!(Session::validators(), vec![40, 30, 20, 10]); - - // only one nominator will exist and it will - assert_ok!(Staking::bond(Origin::signed(1), 2, 500, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(2), vec![10, 20])); + // initial validators + assert_eq!(Session::validators(), vec![20, 10]); // 10 and 20 are now valid candidates. // trigger era @@ -554,9 +539,9 @@ fn less_than_needed_candidates_works() { // both validators will be chosen again. NO election algorithm is even executed. assert_eq!(Session::validators(), vec![20, 10]); - // But the exposure is updated in a simple way. Each nominators vote is applied - assert_eq!(Staking::stakers(10).others.iter().map(|e| e.who).collect::>>(), vec![2]); - assert_eq!(Staking::stakers(20).others.iter().map(|e| e.who).collect::>>(), vec![2]); + // But the exposure is updated in a simple way. No external votes exists. This is purely self-vote. + assert_eq!(Staking::stakers(10).others.iter().map(|e| e.who).collect::>>(), vec![]); + assert_eq!(Staking::stakers(20).others.iter().map(|e| e.who).collect::>>(), vec![]); }); } @@ -565,20 +550,17 @@ fn no_candidate_emergency_condition() { // Test the situation where the number of validators are less than `ValidatorCount` and less than // The expected behavior is to choose all candidates from the previous era. with_externalities(&mut ExtBuilder::default() - .minimum_validator_count(1) - .validator_count(3) - .nominate(false) + .minimum_validator_count(10) + .validator_count(15) .validator_pool(true) - .build(), + .nominate(false) + .build(), || { assert_eq!(Staking::era_length(), 1); - assert_eq!(Staking::validator_count(), 3); - - assert_eq!(Staking::minimum_validator_count(), 1); - assert_eq!(Staking::validator_count(), 3); + assert_eq!(Staking::validator_count(), 15); - // initial validators - assert_eq!(Session::validators(), vec![40, 30, 20, 10]); + // initial validators + assert_eq!(Session::validators(), vec![10, 20, 30, 40]); // trigger era System::set_block_number(1); @@ -586,7 +568,7 @@ fn no_candidate_emergency_condition() { assert_eq!(Staking::current_era(), 1); // No one nominates => no one has a proper vote => no change - assert_eq!(Session::validators(), vec![40, 30, 20, 10]); + assert_eq!(Session::validators(), vec![10, 20, 30, 40]); }); } @@ -597,27 +579,54 @@ fn nominating_and_rewards_should_work() { // // PHRAGMEN OUTPUT: running this test with the reference impl gives: // - // Votes [('2', 500, ['10', '20', '30']), ('4', 500, ['10', '20', '40'])] + // Votes [('10', 1000, ['10']), ('20', 1000, ['20']), ('30', 1000, ['30']), ('40', 1000, ['40']), ('2', 1000, ['10', '20', '30']), ('4', 1000, ['10', '20', '40'])] // Sequential Phragmén gives - // 10 is elected with stake 500.0 and score 0.001 - // 20 is elected with stake 500.0 and score 0.002 - // - // 2 has load 0.002 and supported - // 10 with stake 250.0 20 with stake 250.0 30 with stake 0.0 - // 4 has load 0.002 and supported - // 10 with stake 250.0 20 with stake 250.0 40 with stake 0.0 + // 10 is elected with stake 2200.0 and score 0.0003333333333333333 + // 20 is elected with stake 1800.0 and score 0.0005555555555555556 + + // 10 has load 0.0003333333333333333 and supported + // 10 with stake 1000.0 + // 20 has load 0.0005555555555555556 and supported + // 20 with stake 1000.0 + // 30 has load 0 and supported + // 30 with stake 0 + // 40 has load 0 and supported + // 40 with stake 0 + // 2 has load 0.0005555555555555556 and supported + // 10 with stake 600.0 20 with stake 400.0 30 with stake 0.0 + // 4 has load 0.0005555555555555556 and supported + // 10 with stake 600.0 20 with stake 400.0 40 with stake 0.0 + + // Sequential Phragmén with post processing gives + // 10 is elected with stake 2000.0 and score 0.0003333333333333333 + // 20 is elected with stake 2000.0 and score 0.0005555555555555556 + + // 10 has load 0.0003333333333333333 and supported + // 10 with stake 1000.0 + // 20 has load 0.0005555555555555556 and supported + // 20 with stake 1000.0 + // 30 has load 0 and supported + // 30 with stake 0 + // 40 has load 0 and supported + // 40 with stake 0 + // 2 has load 0.0005555555555555556 and supported + // 10 with stake 400.0 20 with stake 600.0 30 with stake 0 + // 4 has load 0.0005555555555555556 and supported + // 10 with stake 600.0 20 with stake 400.0 40 with stake 0.0 with_externalities(&mut ExtBuilder::default() .nominate(false) .validator_pool(true) .build(), || { - // initial validators - assert_eq!(Session::validators(), vec![40, 30, 20, 10]); + // initial validators -- everyone is actually even. + assert_eq!(Session::validators(), vec![40, 30]); // Set payee to controller assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(30), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(40), RewardDestination::Controller)); // default reward for the first session. let session_reward = 10; @@ -625,8 +634,8 @@ fn nominating_and_rewards_should_work() { // give the man some money let initial_balance = 1000; - for i in [1, 2, 3, 4, 5, 10, 20].iter() { - let _ = Balances::deposit_creating(i, initial_balance - Balances::total_balance(i)); + for i in [1, 2, 3, 4, 5, 10, 11, 20, 21].iter() { + let _ = Balances::ensure_free_balance_is(i, initial_balance); } // record their balances. @@ -634,53 +643,59 @@ fn nominating_and_rewards_should_work() { // bond two account pairs and state interest in nomination. // 2 will nominate for 10, 20, 30 - assert_ok!(Staking::bond(Origin::signed(1), 2, 500, RewardDestination::Controller)); - assert_ok!(Staking::nominate(Origin::signed(2), vec![10, 20, 30])); + assert_ok!(Staking::bond(Origin::signed(1), 2, 1000, RewardDestination::Controller)); + assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21, 31])); // 4 will nominate for 10, 20, 40 - assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Stash)); - assert_ok!(Staking::nominate(Origin::signed(4), vec![10, 20, 40])); - + assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::Controller)); + assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 21, 41])); + System::set_block_number(1); Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 1); + // 10 and 20 have more votes, they will be chosen by phragmen. assert_eq!(Session::validators(), vec![20, 10]); - // validators must have already received some rewards. - assert_eq!(Balances::total_balance(&10), initial_balance + session_reward); - assert_eq!(Balances::total_balance(&20), initial_balance + session_reward); + + // OLD validators must have already received some rewards. + assert_eq!(Balances::total_balance(&40), 1 + session_reward); + assert_eq!(Balances::total_balance(&30), 1 + session_reward); // ------ check the staked value of all parties. - // total expo of 10, with 500 coming from nominators (externals), according to phragmen. - assert_eq!(Staking::stakers(10).own, 1000); - assert_eq!(Staking::stakers(10).total, 1000 + 500); - // 2 and 4 supported 10, each with stake 250, according to phragmen. - assert_eq!(Staking::stakers(10).others.iter().map(|e| e.value).collect::>>(), vec![250, 250]); - assert_eq!(Staking::stakers(10).others.iter().map(|e| e.who).collect::>>(), vec![4, 2]); + + // total expo of 10, with 1200 coming from nominators (externals), according to phragmen. + assert_eq!(Staking::stakers(11).own, 1000); + assert_eq!(Staking::stakers(11).total, 1000 + 800); + // 2 and 4 supported 10, each with stake 600, according to phragmen. + assert_eq!(Staking::stakers(11).others.iter().map(|e| e.value).collect::>>(), vec![400, 400]); + assert_eq!(Staking::stakers(11).others.iter().map(|e| e.who).collect::>>(), vec![3, 1]); // total expo of 20, with 500 coming from nominators (externals), according to phragmen. - assert_eq!(Staking::stakers(20).own, 2000); - assert_eq!(Staking::stakers(20).total, 2000 + 500); + assert_eq!(Staking::stakers(21).own, 1000); + assert_eq!(Staking::stakers(21).total, 1000 + 1200); // 2 and 4 supported 20, each with stake 250, according to phragmen. - assert_eq!(Staking::stakers(20).others.iter().map(|e| e.value).collect::>>(), vec![250, 250]); - assert_eq!(Staking::stakers(20).others.iter().map(|e| e.who).collect::>>(), vec![4, 2]); - + assert_eq!(Staking::stakers(21).others.iter().map(|e| e.value).collect::>>(), vec![600, 600]); + assert_eq!(Staking::stakers(21).others.iter().map(|e| e.who).collect::>>(), vec![3, 1]); + + // They are not chosen anymore + assert_eq!(Staking::stakers(31).total, 0); + assert_eq!(Staking::stakers(41).total, 0); + System::set_block_number(2); + Session::check_rotate_session(System::block_number()); // next session reward. let new_session_reward = Staking::session_reward() * Staking::slot_stake(); // nothing else will happen, era ends and rewards are paid again, // it is expected that nominators will also be paid. See below - Session::check_rotate_session(System::block_number()); - // Nominator 2: has [250/1500 ~ 1/6 from 10] + [250/2500 ~ 1/10 from 20]'s reward. ==> 1/6 + 1/10 - assert_eq!(Balances::total_balance(&2), initial_balance + (new_session_reward/6 + new_session_reward/10)); - // The Associated validator will get the other 4/6 --> 1500(total) minus 1/6(250) by each nominator -> 6/6 - 1/6 - 1/6 - assert_eq!(Balances::total_balance(&10), initial_balance + session_reward + 4*new_session_reward/6) ; + // Nominator 2: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 + assert_eq!(Balances::total_balance(&2), initial_balance + (2*new_session_reward/9 + 3*new_session_reward/11)); + // Nominator 4: has [400/1800 ~ 2/9 from 10] + [600/2200 ~ 3/11 from 20]'s reward. ==> 2/9 + 3/11 + assert_eq!(Balances::total_balance(&4), initial_balance + (2*new_session_reward/9 + 3*new_session_reward/11)); - // Nominator 4: has [250/1500 ~ 1/6 from 10] + [250/2500 ~ 1/10 from 20]'s reward. ==> 1/6 + 1/10 - // This nominator chose stash as the reward destination. This means that the reward will go to 3, which is bonded as the stash of 4. - assert_eq!(Balances::total_balance(&3), initial_balance + (new_session_reward/6 + new_session_reward/10)); - // The Associated validator will get the other 8/10 --> 2500(total) minus 1/10(250) by each nominator -> 10/10 - 1/10 - 1/10 - assert_eq!(Balances::total_balance(&20), initial_balance + session_reward + 8*new_session_reward/10); + // 10 got 800 / 1800 external stake => 8/18 =? 4/9 => Validator's share = 5/9 + assert_eq!(Balances::total_balance(&10), initial_balance + 5*new_session_reward/9) ; + // 10 got 1200 / 2200 external stake => 12/22 =? 6/11 => Validator's share = 5/11 + assert_eq!(Balances::total_balance(&20), initial_balance + 5*new_session_reward/11); }); } @@ -696,6 +711,7 @@ fn nominators_also_get_slashed() { assert_eq!(Staking::slash_count(&10), 0); // initial validators assert_eq!(Session::validators(), vec![20, 10]); + >::put(Perbill::from_percent(12)); // Set payee to controller assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); @@ -703,7 +719,7 @@ fn nominators_also_get_slashed() { // give the man some money. let initial_balance = 1000; for i in [1, 2, 3, 10].iter() { - let _ = Balances::deposit_creating(i, initial_balance - Balances::total_balance(i)); + let _ = Balances::ensure_free_balance_is(i, initial_balance); } // 2 will nominate for 10 @@ -715,15 +731,20 @@ fn nominators_also_get_slashed() { System::set_block_number(2); Session::check_rotate_session(System::block_number()); + // Nominator stash didn't collect any. + assert_eq!(Balances::total_balance(&2), initial_balance); + // 10 goes offline Staking::on_offline_validator(10, 4); - let slash_value = 2_u64.pow(3) * Staking::current_offline_slash(); let expo = Staking::stakers(10); - let actual_slash = expo.own.min(slash_value); - let nominator_actual_slash = nominator_stake.min(expo.total - actual_slash); + let slash_value = Staking::offline_slash() * expo.total * 2_u64.pow(3); + let total_slash = expo.total.min(slash_value); + let validator_slash = expo.own.min(total_slash); + let nominator_slash = nominator_stake.min(total_slash - validator_slash); + // initial + first era reward + slash - assert_eq!(Balances::total_balance(&10), initial_balance + 10 - actual_slash); - assert_eq!(Balances::total_balance(&2), initial_balance - nominator_actual_slash); + assert_eq!(Balances::total_balance(&10), initial_balance + 10 - validator_slash); + assert_eq!(Balances::total_balance(&2), initial_balance - nominator_slash); // Because slashing happened. assert!(Staking::forcing_new_era().is_some()); }); @@ -739,27 +760,44 @@ fn double_staking_should_fail() { with_externalities(&mut ExtBuilder::default() .sessions_per_era(2) .build(), - || { - let arbitrary_value = 5; - System::set_block_number(1); - // 2 = controller, 1 stashed => ok - assert_ok!(Staking::bond(Origin::signed(1), 2, arbitrary_value, RewardDestination::default())); - // 2 = controller, 3 stashed (Note that 2 is reused.) => ok - assert_ok!(Staking::bond(Origin::signed(3), 2, arbitrary_value, RewardDestination::default())); - // 4 = not used so far, 1 stashed => not allowed. - assert_noop!(Staking::bond(Origin::signed(1), 4, arbitrary_value, RewardDestination::default()), "stash already bonded"); - // 1 = stashed => attempting to nominate should fail. - assert_noop!(Staking::nominate(Origin::signed(1), vec![1]), "not a controller"); - // 2 = controller => nominating should work. - assert_ok!(Staking::nominate(Origin::signed(2), vec![1])); - }); + || { + let arbitrary_value = 5; + System::set_block_number(1); + // 2 = controller, 1 stashed => ok + assert_ok!(Staking::bond(Origin::signed(1), 2, arbitrary_value, RewardDestination::default())); + // 4 = not used so far, 1 stashed => not allowed. + assert_noop!(Staking::bond(Origin::signed(1), 4, arbitrary_value, RewardDestination::default()), "stash already bonded"); + // 1 = stashed => attempting to nominate should fail. + assert_noop!(Staking::nominate(Origin::signed(1), vec![1]), "not a controller"); + // 2 = controller => nominating should work. + assert_ok!(Staking::nominate(Origin::signed(2), vec![1])); + }); +} + +#[test] +fn double_controlling_should_fail() { + // should test (in the same order): + // * an account already bonded as controller CAN be reused as the controller of another account. + // * an account already bonded as stash cannot be the controller of another account. + // * an account already bonded as stash cannot nominate. + // * an account already bonded as controller can nominate. + with_externalities(&mut ExtBuilder::default() + .sessions_per_era(2) + .build(), + || { + let arbitrary_value = 5; + System::set_block_number(1); + // 2 = controller, 1 stashed => ok + assert_ok!(Staking::bond(Origin::signed(1), 2, arbitrary_value, RewardDestination::default())); + // 2 = controller, 3 stashed (Note that 2 is reused.) => no-op + assert_noop!(Staking::bond(Origin::signed(3), 2, arbitrary_value, RewardDestination::default()), "controller already paired"); + }); } #[test] fn session_and_eras_work() { with_externalities(&mut ExtBuilder::default() .sessions_per_era(2) - .reward(10) .build(), || { assert_eq!(Staking::era_length(), 2); @@ -830,23 +868,45 @@ fn session_and_eras_work() { #[test] fn cannot_transfer_staked_balance() { // Tests that a stash account cannot transfer funds - with_externalities(&mut ExtBuilder::default().build(), || { + with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { // Confirm account 11 is stashed assert_eq!(Staking::bonded(&11), Some(10)); // Confirm account 11 has some free balance assert_eq!(Balances::free_balance(&11), 1000); // Confirm account 11 (via controller 10) is totally staked - assert_eq!(Staking::stakers(&10).total, 1000 + 500); + assert_eq!(Staking::stakers(&11).total, 1000); // Confirm account 11 cannot transfer as a result assert_noop!(Balances::transfer(Origin::signed(11), 20, 1), "account liquidity restrictions prevent withdrawal"); // Give account 11 extra free balance - let _ = Balances::deposit_creating(&11, 9999); + let _ = Balances::ensure_free_balance_is(&11, 10000); // Confirm that account 11 can now transfer some balance assert_ok!(Balances::transfer(Origin::signed(11), 20, 1)); }); } +#[test] +fn cannot_transfer_staked_balance_2() { + // Tests that a stash account cannot transfer funds + // Same test as above but with 20 + // 21 has 2000 free balance but 1000 at stake + with_externalities(&mut ExtBuilder::default() + .nominate(false) + .fare(true) + .build(), + || { + // Confirm account 21 is stashed + assert_eq!(Staking::bonded(&21), Some(20)); + // Confirm account 21 has some free balance + assert_eq!(Balances::free_balance(&21), 2000); + // Confirm account 21 (via controller 20) is totally staked + assert_eq!(Staking::stakers(&21).total, 1000); + // Confirm account 21 can transfer at most 1000 + assert_noop!(Balances::transfer(Origin::signed(21), 20, 1001), "account liquidity restrictions prevent withdrawal"); + assert_ok!(Balances::transfer(Origin::signed(21), 20, 1000)); + }); +} + #[test] fn cannot_reserve_staked_balance() { // Checks that a bonded account cannot reserve balance from free balance @@ -856,12 +916,12 @@ fn cannot_reserve_staked_balance() { // Confirm account 11 has some free balance assert_eq!(Balances::free_balance(&11), 1000); // Confirm account 11 (via controller 10) is totally staked - assert_eq!(Staking::stakers(&10).total, 1000 + 500); + assert_eq!(Staking::stakers(&11).total, 1125); // Confirm account 11 cannot transfer as a result assert_noop!(Balances::reserve(&11, 1), "account liquidity restrictions prevent withdrawal"); // Give account 11 extra free balance - let _ = Balances::deposit_creating(&11, 9990); + let _ = Balances::ensure_free_balance_is(&11, 10000); // Confirm account 11 can now reserve balance assert_ok!(Balances::reserve(&11, 1)); }); @@ -870,9 +930,11 @@ fn cannot_reserve_staked_balance() { #[test] fn reward_destination_works() { // Rewards go to the correct destination as determined in Payee - with_externalities(&mut ExtBuilder::default().build(), || { - // Check that account 10 is a validator - assert!(>::exists(10)); + with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { + // Check that account 11 is a validator + assert!(>::exists(11)); + // Check that account 11 is a validator + assert!(Staking::current_elected().contains(&11)); // Check the balance of the validator account assert_eq!(Balances::free_balance(&10), 1); // Check the balance of the stash account @@ -890,20 +952,18 @@ fn reward_destination_works() { Session::check_rotate_session(System::block_number()); // Check that RewardDestination is Staked (default) - assert_eq!(Staking::payee(&10), RewardDestination::Staked); + assert_eq!(Staking::payee(&11), RewardDestination::Staked); // Check current session reward is 10 assert_eq!(current_session_reward, 10); // Check that reward went to the stash account of validator - // 1/3 of the reward is for the nominator. - let validator_reward = (10. * (2./3.)) as u64; // = 6 - assert_eq!(Balances::free_balance(&11), 1000 + validator_reward); + assert_eq!(Balances::free_balance(&11), 1000 + current_session_reward); // Check that amount at stake increased accordingly - assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 6, active: 1000 + 6, unlocking: vec![] })); + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 10, active: 1000 + 10, unlocking: vec![] })); // Update current session reward - current_session_reward = Staking::current_session_reward(); + current_session_reward = Staking::current_session_reward(); // 1010 (1* slot_stake) //Change RewardDestination to Stash - >::insert(&10, RewardDestination::Stash); + >::insert(&11, RewardDestination::Stash); // Move forward the system for payment System::set_block_number(2); @@ -911,32 +971,34 @@ fn reward_destination_works() { Session::check_rotate_session(System::block_number()); // Check that RewardDestination is Stash - assert_eq!(Staking::payee(&10), RewardDestination::Stash); + assert_eq!(Staking::payee(&11), RewardDestination::Stash); // Check that reward went to the stash account - let new_validator_reward = ((1000 + 6) as f64 / ( (1000 + 6) + (500 + 4) ) as f64) * current_session_reward as f64; - assert_eq!(Balances::free_balance(&11), 1000 + validator_reward + new_validator_reward as u64); - // Check that amount at stake is not increased - assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1006, active: 1006, unlocking: vec![] })); + assert_eq!(Balances::free_balance(&11), 1000 + 10 + current_session_reward); + // Record this value + let recorded_stash_balance = 1000 + 10 + current_session_reward; - //Change RewardDestination to Controller - >::insert(&10, RewardDestination::Controller); + // Check that amount at stake is NOT increased + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 10, active: 1000 + 10, unlocking: vec![] })); + + // Change RewardDestination to Controller + >::insert(&11, RewardDestination::Controller); // Check controller balance assert_eq!(Balances::free_balance(&10), 1); - // Move forward the system for payment System::set_block_number(3); Timestamp::set_timestamp(15); Session::check_rotate_session(System::block_number()); // Check that RewardDestination is Controller - assert_eq!(Staking::payee(&10), RewardDestination::Controller); + assert_eq!(Staking::payee(&11), RewardDestination::Controller); // Check that reward went to the controller account - let reward_of = |w| Staking::stakers(w).own * Staking::current_session_reward() / Staking::stakers(w).total; - assert_eq!(Balances::free_balance(&10), 1 + reward_of(&10)); - // Check that amount at stake is not increased - assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1006, active: 1006, unlocking: vec![] })); + assert_eq!(Balances::free_balance(&10), 1 + 1010); + // Check that amount at stake is NOT increased + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 10, active: 1000 + 10, unlocking: vec![] })); + // Check that amount in staked account is NOT increased. + assert_eq!(Balances::free_balance(&11), recorded_stash_balance); }); } @@ -967,17 +1029,17 @@ fn validator_payment_prefs_work() { // check the balance of a validator's stash accounts. assert_eq!(Balances::total_balance(&11), validator_initial_balance); // and the nominator (to-be) - assert_eq!(Balances::total_balance(&2), 20); + let _ = Balances::ensure_free_balance_is(&2, 500); // add a dummy nominator. // NOTE: this nominator is being added 'manually', use '.nominate()' to do it realistically. - >::insert(&10, Exposure { + >::insert(&11, Exposure { own: 500, // equal division indicates that the reward will be equally divided among validator and nominator. total: 1000, others: vec![IndividualExposure {who: 2, value: 500 }] }); - >::insert(&2, RewardDestination::Controller); - >::insert(&10, ValidatorPrefs { + >::insert(&2, RewardDestination::Stash); + >::insert(&11, ValidatorPrefs { unstake_threshold: 3, validator_payment: validator_cut }); @@ -994,7 +1056,7 @@ fn validator_payment_prefs_work() { // session triggered: the reward value stashed should be 10 -- defined in ExtBuilder genesis. assert_eq!(Staking::current_session_reward(), session_reward); assert_eq!(Staking::current_era_reward(), session_reward); - + block = 6; // Block 6 => Session 2 => Era 0 System::set_block_number(block); Timestamp::set_timestamp(block*5); // a little late. @@ -1019,7 +1081,7 @@ fn validator_payment_prefs_work() { // Controller account will not get any reward. assert_eq!(Balances::total_balance(&10), 1); // Rest of the reward will be shared and paid to the nominator in stake. - assert_eq!(Balances::total_balance(&2), 20 + shared_cut/2); + assert_eq!(Balances::total_balance(&2), 500 + shared_cut/2); }); } @@ -1027,21 +1089,19 @@ fn validator_payment_prefs_work() { #[test] fn bond_extra_works() { // Tests that extra `free_balance` in the stash can be added to stake - // NOTE: this tests only verifies `StakingLedger` for correct updates. + // NOTE: this tests only verifies `StakingLedger` for correct updates // See `bond_extra_and_withdraw_unbonded_works` for more details and updates on `Exposure`. with_externalities(&mut ExtBuilder::default().build(), || { // Check that account 10 is a validator - assert!(>::exists(10)); + assert!(>::exists(11)); // Check that account 10 is bonded to account 11 assert_eq!(Staking::bonded(&11), Some(10)); // Check how much is at stake assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000, active: 1000, unlocking: vec![] })); // Give account 11 some large free balance greater than total - let _ = Balances::deposit_creating(&11, 999000); - // Check the balance of the stash account - assert_eq!(Balances::free_balance(&11), 1000000); + let _ = Balances::ensure_free_balance_is(&11, 1000000); // Call the bond_extra function from controller, add only 100 assert_ok!(Staking::bond_extra(Origin::signed(10), 100)); @@ -1064,9 +1124,8 @@ fn bond_extra_and_withdraw_unbonded_works() { // * it can unbond a portion of its funds from the stash account. // * Once the unbonding period is done, it can actually take the funds out of the stash. with_externalities(&mut ExtBuilder::default() - .reward(10) // it is the default, just for verbosity .nominate(false) - .build(), + .build(), || { // Set payee to controller. avoids confusion assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); @@ -1075,15 +1134,12 @@ fn bond_extra_and_withdraw_unbonded_works() { assert_ok!(Staking::set_bonding_duration(2)); // Give account 11 some large free balance greater than total - let _ = Balances::deposit_creating(&11, 999000); - // Check the balance of the stash account - assert_eq!(Balances::free_balance(&11), 1000000); + let _ = Balances::ensure_free_balance_is(&11, 1000000); // Initial config should be correct assert_eq!(Staking::sessions_per_era(), 1); assert_eq!(Staking::current_era(), 0); assert_eq!(Session::current_index(), 0); - assert_eq!(Staking::current_session_reward(), 10); // check the balance of a validator accounts. @@ -1092,7 +1148,7 @@ fn bond_extra_and_withdraw_unbonded_works() { // confirm that 10 is a normal validator and gets paid at the end of the era. System::set_block_number(1); Timestamp::set_timestamp(5); - Session::check_rotate_session(System::block_number()); + Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 1); assert_eq!(Session::current_index(), 1); @@ -1102,56 +1158,55 @@ fn bond_extra_and_withdraw_unbonded_works() { // Initial state of 10 assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000, active: 1000, unlocking: vec![] })); - assert_eq!(Staking::stakers(&10), Exposure { total: 1000, own: 1000, others: vec![] }); - + assert_eq!(Staking::stakers(&11), Exposure { total: 1000, own: 1000, others: vec![] }); - // deposit the extra 100 units + // deposit the extra 100 units Staking::bond_extra(Origin::signed(10), 100).unwrap(); assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, active: 1000 + 100, unlocking: vec![] })); // Exposure is a snapshot! only updated after the next era update. - assert_ne!(Staking::stakers(&10), Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] }); + assert_ne!(Staking::stakers(&11), Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] }); // trigger next era. - System::set_block_number(2);Timestamp::set_timestamp(10);Session::check_rotate_session(System::block_number()); + System::set_block_number(2);Timestamp::set_timestamp(10);Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 2); assert_eq!(Session::current_index(), 2); // ledger should be the same. assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, active: 1000 + 100, unlocking: vec![] })); // Exposure is now updated. - assert_eq!(Staking::stakers(&10), Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] }); + assert_eq!(Staking::stakers(&11), Exposure { total: 1000 + 100, own: 1000 + 100, others: vec![] }); // Note that by this point 10 also have received more rewards, but we don't care now. // assert_eq!(Balances::total_balance(&10), 1 + 10 + MORE_REWARD); // Unbond almost all of the funds in stash. Staking::unbond(Origin::signed(10), 1000).unwrap(); - assert_eq!(Staking::ledger(&10), Some(StakingLedger { + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, active: 100, unlocking: vec![UnlockChunk{ value: 1000, era: 2 + 2}] })); // Attempting to free the balances now will fail. 2 eras need to pass. Staking::withdraw_unbonded(Origin::signed(10)).unwrap(); - assert_eq!(Staking::ledger(&10), Some(StakingLedger { + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, active: 100, unlocking: vec![UnlockChunk{ value: 1000, era: 2 + 2}] })); // trigger next era. - System::set_block_number(3);Timestamp::set_timestamp(15);Session::check_rotate_session(System::block_number()); + System::set_block_number(3);Timestamp::set_timestamp(15);Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 3); assert_eq!(Session::current_index(), 3); // nothing yet Staking::withdraw_unbonded(Origin::signed(10)).unwrap(); - assert_eq!(Staking::ledger(&10), Some(StakingLedger { + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000 + 100, active: 100, unlocking: vec![UnlockChunk{ value: 1000, era: 2 + 2}] })); // trigger next era. - System::set_block_number(4);Timestamp::set_timestamp(20);Session::check_rotate_session(System::block_number()); + System::set_block_number(4);Timestamp::set_timestamp(20);Session::check_rotate_session(System::block_number()); assert_eq!(Staking::current_era(), 4); assert_eq!(Session::current_index(), 4); - + Staking::withdraw_unbonded(Origin::signed(10)).unwrap(); // Now the value is free and the staking ledger is updated. - assert_eq!(Staking::ledger(&10), Some(StakingLedger { + assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 100, active: 100, unlocking: vec![] })); }) } @@ -1162,30 +1217,30 @@ fn slot_stake_is_least_staked_validator_and_limits_maximum_punishment() { // Test that slot_stake is the maximum punishment that can happen to a validator // Note that rewardDestination is the stash account by default // Note that unlike reward slash will affect free_balance, not the stash account. - with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { + with_externalities(&mut ExtBuilder::default() + .nominate(false) + .fare(false) + .build(), + || { + // Give the man some money. // Confirm validator count is 2 assert_eq!(Staking::validator_count(), 2); // Confirm account 10 and 20 are validators - assert!(>::exists(&10) && >::exists(&20)); - // Confirm 10 has less stake than 20 - assert!(Staking::stakers(&10).total < Staking::stakers(&20).total); - assert_eq!(Staking::stakers(&10).total, 1000); - assert_eq!(Staking::stakers(&20).total, 2000); + assert!(>::exists(&11) && >::exists(&21)); - // Give the man some money. - let _ = Balances::deposit_creating(&10, 999); - let _ = Balances::deposit_creating(&20, 999); + assert_eq!(Staking::stakers(&11).total, 1000); + assert_eq!(Staking::stakers(&21).total, 2000); - // Confirm initial free balance. - assert_eq!(Balances::free_balance(&10), 1000); - assert_eq!(Balances::free_balance(&20), 1000); + // Give the man some money. + let _ = Balances::ensure_free_balance_is(&10, 1000); + let _ = Balances::ensure_free_balance_is(&20, 1000); // We confirm initialized slot_stake is this value - assert_eq!(Staking::slot_stake(), Staking::stakers(&10).total); - + assert_eq!(Staking::slot_stake(), Staking::stakers(&11).total); + // Now lets lower account 20 stake - >::insert(&20, Exposure { total: 69, own: 69, others: vec![] }); - assert_eq!(Staking::stakers(&20).total, 69); + >::insert(&21, Exposure { total: 69, own: 69, others: vec![] }); + assert_eq!(Staking::stakers(&21).total, 69); >::insert(&20, StakingLedger { stash: 22, total: 69, active: 69, unlocking: vec![] }); // New era --> rewards are paid --> stakes are changed @@ -1195,8 +1250,8 @@ fn slot_stake_is_least_staked_validator_and_limits_maximum_punishment() { assert_eq!(Staking::current_era(), 1); // -- new balances + reward - assert_eq!(Staking::stakers(&10).total, 1000 + 10); - assert_eq!(Staking::stakers(&20).total, 69 + 10); + assert_eq!(Staking::stakers(&11).total, 1000 + 10); + assert_eq!(Staking::stakers(&21).total, 69 + 10); // -- Note that rewards are going directly to stash, not as free balance. assert_eq!(Balances::free_balance(&10), 1000); @@ -1206,12 +1261,11 @@ fn slot_stake_is_least_staked_validator_and_limits_maximum_punishment() { assert_eq!(Staking::slot_stake(), 79); // // If 10 gets slashed now, despite having +1000 in stash, it will be slashed byt 79, which is the slot stake - Staking::on_offline_validator(10, 4); + Staking::on_offline_validator(11, 4); // // Confirm user has been reported - assert_eq!(Staking::slash_count(&10), 4); + assert_eq!(Staking::slash_count(&11), 4); // // check the balance of 10 (slash will be deducted from free balance.) - assert_eq!(Balances::free_balance(&10), 1000 - 79); - + assert_eq!(Balances::free_balance(&11), 1000 + 10 - 50 /*5% of 1000*/ * 8 /*2**3*/); }); } @@ -1224,7 +1278,7 @@ fn on_free_balance_zero_stash_removes_validator() { .build(), || { // Check that account 10 is a validator - assert!(>::exists(10)); + assert!(>::exists(11)); // Check the balance of the validator account assert_eq!(Balances::free_balance(&10), 256); // Check the balance of the stash account @@ -1234,20 +1288,19 @@ fn on_free_balance_zero_stash_removes_validator() { // Set some storage items which we expect to be cleaned up // Initiate slash count storage item - Staking::on_offline_validator(10, 1); + Staking::on_offline_validator(11, 1); // Set payee information assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Stash)); // Check storage items that should be cleaned up assert!(>::exists(&10)); - assert!(>::exists(&10)); - assert!(>::exists(&10)); - assert!(>::exists(&10)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); // Reduce free_balance of controller to 0 Balances::slash(&10, u64::max_value()); - // Check total balance of account 10 - assert_eq!(Balances::total_balance(&10), 0); // Check the balance of the stash account has not been touched assert_eq!(Balances::free_balance(&11), 256000); @@ -1256,9 +1309,10 @@ fn on_free_balance_zero_stash_removes_validator() { // Check storage items have not changed assert!(>::exists(&10)); - assert!(>::exists(&10)); - assert!(>::exists(&10)); - assert!(>::exists(&10)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); // Reduce free_balance of stash to 0 Balances::slash(&11, u64::max_value()); @@ -1267,11 +1321,11 @@ fn on_free_balance_zero_stash_removes_validator() { // Check storage items do not exist assert!(!>::exists(&10)); - assert!(!>::exists(&10)); - assert!(!>::exists(&10)); - assert!(!>::exists(&10)); - assert!(!>::exists(&10)); assert!(!>::exists(&11)); + assert!(!>::exists(&11)); + assert!(!>::exists(&11)); + assert!(!>::exists(&11)); + assert!(!>::exists(&11)); }); } @@ -1286,7 +1340,7 @@ fn on_free_balance_zero_stash_removes_nominator() { // Make 10 a nominator assert_ok!(Staking::nominate(Origin::signed(10), vec![20])); // Check that account 10 is a nominator - assert!(>::exists(10)); + assert!(>::exists(11)); // Check the balance of the nominator account assert_eq!(Balances::free_balance(&10), 256); // Check the balance of the stash account @@ -1300,8 +1354,9 @@ fn on_free_balance_zero_stash_removes_nominator() { // Check storage items that should be cleaned up assert!(>::exists(&10)); - assert!(>::exists(&10)); - assert!(>::exists(&10)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); // Reduce free_balance of controller to 0 Balances::slash(&10, u64::max_value()); @@ -1315,8 +1370,9 @@ fn on_free_balance_zero_stash_removes_nominator() { // Check storage items have not changed assert!(>::exists(&10)); - assert!(>::exists(&10)); - assert!(>::exists(&10)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); + assert!(>::exists(&11)); // Reduce free_balance of stash to 0 Balances::slash(&11, u64::max_value()); @@ -1325,11 +1381,11 @@ fn on_free_balance_zero_stash_removes_nominator() { // Check storage items do not exist assert!(!>::exists(&10)); - assert!(!>::exists(&10)); - assert!(!>::exists(&10)); - assert!(!>::exists(&10)); - assert!(!>::exists(&10)); assert!(!>::exists(&11)); + assert!(!>::exists(&11)); + assert!(!>::exists(&11)); + assert!(!>::exists(&11)); + assert!(!>::exists(&11)); }); } @@ -1337,92 +1393,105 @@ fn on_free_balance_zero_stash_removes_nominator() { fn phragmen_poc_works() { // Tests the POC test of the phragmen, mentioned in the paper and reference implementation. // Initial votes: - // vote_list = [ - // ("A", 10.0, ["X", "Y"]), - // ("B", 20.0, ["X", "Z"]), - // ("C", 30.0, ["Y", "Z"]) - // ] + // Votes [ + // ('2', 500, ['10', '20', '30']), + // ('4', 500, ['10', '20', '40']), + // ('10', 1000, ['10']), + // ('20', 1000, ['20']), + // ('30', 1000, ['30']), + // ('40', 1000, ['40'])] // // Sequential Phragmén gives - // Z is elected with stake 35.0 and score 0.02 - // Y is elected with stake 25.0 and score 0.04 + // 10 is elected with stake 1666.6666666666665 and score 0.0005 + // 20 is elected with stake 1333.3333333333333 and score 0.00075 + + // 2 has load 0.00075 and supported + // 10 with stake 333.3333333333333 20 with stake 166.66666666666666 30 with stake 0.0 + // 4 has load 0.00075 and supported + // 10 with stake 333.3333333333333 20 with stake 166.66666666666666 40 with stake 0.0 + // 10 has load 0.0005 and supported + // 10 with stake 1000.0 + // 20 has load 0.00075 and supported + // 20 with stake 1000.0 + // 30 has load 0 and supported + // 30 with stake 0 + // 40 has load 0 and supported + // 40 with stake 0 + + // Sequential Phragmén with post processing gives + // 10 is elected with stake 1500.0 and score 0.0005 + // 20 is elected with stake 1500.0 and score 0.00075 // - // A has load 0.04 and supported - // X with stake 0.0 Y with stake 10.0 - // B has load 0.02 and supported - // X with stake 0.0 Z with stake 20.0 - // C has load 0.04 and supported - // Y with stake 15.0 Z with stake 15.0 - // - // NOTE: doesn't X/Y/Z's stash value make a difference here in phragmen? + // 10 has load 0.0005 and supported + // 10 with stake 1000.0 + // 20 has load 0.00075 and supported + // 20 with stake 1000.0 + // 30 has load 0 and supported + // 30 with stake 0 + // 40 has load 0 and supported + // 40 with stake 0 + // 2 has load 0.00075 and supported + // 10 with stake 166.66666666666674 20 with stake 333.33333333333326 30 with stake 0 + // 4 has load 0.00075 and supported + // 10 with stake 333.3333333333333 20 with stake 166.66666666666666 40 with stake 0.0 + + with_externalities(&mut ExtBuilder::default() .nominate(false) + .validator_pool(true) .build(), || { - // initial setup of 10 and 20, both validators. - assert_eq!(Session::validators(), vec![20, 10]); + // We don't really care about this. At this point everything is even. + // assert_eq!(Session::validators(), vec![40, 30]); assert_eq!(Staking::ledger(&10), Some(StakingLedger { stash: 11, total: 1000, active: 1000, unlocking: vec![] })); - assert_eq!(Staking::ledger(&20), Some(StakingLedger { stash: 21, total: 2000, active: 2000, unlocking: vec![] })); + assert_eq!(Staking::ledger(&20), Some(StakingLedger { stash: 21, total: 1000, active: 1000, unlocking: vec![] })); + assert_eq!(Staking::ledger(&30), Some(StakingLedger { stash: 31, total: 1000, active: 1000, unlocking: vec![] })); + assert_eq!(Staking::ledger(&40), Some(StakingLedger { stash: 41, total: 1000, active: 1000, unlocking: vec![] })); - assert_eq!(Staking::validators(10), ValidatorPrefs::default()); - assert_eq!(Staking::validators(20), ValidatorPrefs::default()); + assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(30), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(40), RewardDestination::Controller)); - assert_eq!(Balances::free_balance(10), 1); - assert_eq!(Balances::free_balance(20), 1); - // no one is a nominator assert_eq!(>::enumerate().count(), 0 as usize); - // Bond [30, 31] as the third validator - assert_ok!(Staking::bond(Origin::signed(31), 30, 1000, RewardDestination::default())); - assert_ok!(Staking::validate(Origin::signed(30), ValidatorPrefs::default())); - - // bond [2,1](A), [4,3](B), [6,5](C) as the 3 nominators - // Give all of them some balance to be able to bond properly. - for i in &[1, 3, 5] { let _ = Balances::deposit_creating(i, 50); } - // Linking names to the above test: - // 10 => X - // 20 => Y - // 30 => Z - assert_ok!(Staking::bond(Origin::signed(1), 2, 10, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(2), vec![10, 20])); + // bond [2,1] / [4,3] a nominator + let _ = Balances::deposit_creating(&1, 1000); + let _ = Balances::deposit_creating(&3, 1000); - assert_ok!(Staking::bond(Origin::signed(3), 4, 20, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(4), vec![10, 30])); + assert_ok!(Staking::bond(Origin::signed(1), 2, 500, RewardDestination::default())); + assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21, 31])); - assert_ok!(Staking::bond(Origin::signed(5), 6, 30, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(6), vec![20, 30])); + assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::default())); + assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 21, 41])); // New era => election algorithm will trigger System::set_block_number(1); Session::check_rotate_session(System::block_number()); - // Z and Y are chosen - assert_eq!(Session::validators(), vec![30, 20]); - - // with stake 35 and 25 respectively - - // This is only because 30 has been bonded on the fly, exposures are stored at the very end of the era. - // 35 is the point, not 'own' Exposure. - assert_eq!(Staking::stakers(30).own, 0); - assert_eq!(Staking::stakers(30).total, 0 + 35); - // same as above. +25 is the point - assert_eq!(Staking::stakers(20).own, 2010); - assert_eq!(Staking::stakers(20).total, 2010 + 25); - - // 30(Z) was supported by B-4 and C-6 with stake 20 and 15 respectively. - assert_eq!(Staking::stakers(30).others.iter().map(|e| e.value).collect::>>(), vec![15, 20]); - assert_eq!(Staking::stakers(30).others.iter().map(|e| e.who).collect::>>(), vec![6, 4]); - - // 20(Y) was supported by A-2 and C-6 with stake 10 and 15 respectively. - assert_eq!(Staking::stakers(20).others.iter().map(|e| e.value).collect::>>(), vec![15, 10]); - assert_eq!(Staking::stakers(20).others.iter().map(|e| e.who).collect::>>(), vec![6, 2]); + assert_eq!(Session::validators(), vec![20, 10]); + + // with stake 1666 and 1333 respectively + assert_eq!(Staking::stakers(11).own, 1000); + assert_eq!(Staking::stakers(11).total, 1000 + 332); + assert_eq!(Staking::stakers(21).own, 1000); + assert_eq!(Staking::stakers(21).total, 1000 + 666); + + // Nominator's stake distribution. + assert_eq!(Staking::stakers(11).others.iter().map(|e| e.value).collect::>>(), vec![166, 166]); + assert_eq!(Staking::stakers(11).others.iter().map(|e| e.value).sum::>(), 332); + assert_eq!(Staking::stakers(11).others.iter().map(|e| e.who).collect::>>(), vec![3, 1]); + + assert_eq!(Staking::stakers(21).others.iter().map(|e| e.value).collect::>>(), vec![333, 333]); + assert_eq!(Staking::stakers(21).others.iter().map(|e| e.value).sum::>(), 666); + assert_eq!(Staking::stakers(21).others.iter().map(|e| e.who).collect::>>(), vec![3, 1]); }); } #[test] -fn phragmen_election_works() { +fn phragmen_election_works_example_2() { // tests the encapsulated phragmen::elect function. with_externalities(&mut ExtBuilder::default().nominate(false).build(), || { // initial setup of 10 and 20, both validators @@ -1437,52 +1506,89 @@ fn phragmen_election_works() { // bond [2,1](A), [4,3](B), as 2 nominators // Give all of them some balance to be able to bond properly. - for i in &[1, 3] { let _ = Balances::deposit_creating(i, 50); } - assert_ok!(Staking::bond(Origin::signed(1), 2, 5, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(2), vec![10, 20])); + for i in &[1, 3] { let _ = Balances::deposit_creating(i, 2000); } + assert_ok!(Staking::bond(Origin::signed(1), 2, 50, RewardDestination::default())); + assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 21])); - assert_ok!(Staking::bond(Origin::signed(3), 4, 45, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(4), vec![10, 30])); + assert_ok!(Staking::bond(Origin::signed(3), 4, 1000, RewardDestination::default())); + assert_ok!(Staking::nominate(Origin::signed(4), vec![11, 31])); let rounds = || 2 as usize; let validators = || >::enumerate(); let nominators = || >::enumerate(); - let stash_of = |w| Staking::stash_balance(&w); let min_validator_count = Staking::minimum_validator_count() as usize; let winners = phragmen::elect::( rounds, validators, nominators, - stash_of, - min_validator_count + Staking::slashable_balance_of, + min_validator_count, + ElectionConfig::> { + equalise: true, + tolerance: >::sa(10 as u64), + iterations: 10, + } ); + let winners = winners.unwrap(); + // 10 and 30 must be the winners - assert_eq!(winners.iter().map(|w| w.who).collect::>>(), vec![10, 30]); + assert_eq!(winners.iter().map(|w| w.who).collect::>>(), vec![11, 31]); - let winner_10 = winners.iter().filter(|w| w.who == 10).nth(0).unwrap(); - let winner_30 = winners.iter().filter(|w| w.who == 30).nth(0).unwrap(); + let winner_10 = winners.iter().filter(|w| w.who == 11).nth(0).unwrap(); + let winner_30 = winners.iter().filter(|w| w.who == 31).nth(0).unwrap(); // python implementation output: /* - 10 is elected with stake 26.31578947368421 and score 0.02 - 30 is elected with stake 23.684210526315788 and score 0.042222222222222223 + Votes [ + ('10', 1000, ['10']), + ('20', 1000, ['20']), + ('30', 1000, ['30']), + ('2', 50, ['10', '20']), + ('4', 1000, ['10', '30']) + ] + Sequential Phragmén gives + 10 is elected with stake 1705.7377049180327 and score 0.0004878048780487805 + 30 is elected with stake 1344.2622950819673 and score 0.0007439024390243903 + + 10 has load 0.0004878048780487805 and supported + 10 with stake 1000.0 + 20 has load 0 and supported + 20 with stake 0 + 30 has load 0.0007439024390243903 and supported + 30 with stake 1000.0 + 2 has load 0.0004878048780487805 and supported + 10 with stake 50.0 20 with stake 0.0 + 4 has load 0.0007439024390243903 and supported + 10 with stake 655.7377049180328 30 with stake 344.26229508196724 + + Sequential Phragmén with post processing gives + 10 is elected with stake 1525.0 and score 0.0004878048780487805 + 30 is elected with stake 1525.0 and score 0.0007439024390243903 + + 10 has load 0.0004878048780487805 and supported + 10 with stake 1000.0 + 20 has load 0 and supported + 20 with stake 0 + 30 has load 0.0007439024390243903 and supported + 30 with stake 1000.0 + 2 has load 0.0004878048780487805 and supported + 10 with stake 50.0 20 with stake 0.0 + 4 has load 0.0007439024390243903 and supported + 10 with stake 475.0 30 with stake 525.0 + - 2 has load 0.02 and supported - 10 with stake 5.0 20 with stake 0.0 - 4 has load 0.042222222222222223 and supported - 10 with stake 21.31578947368421 30 with stake 23.684210526315788 */ - assert_eq!(winner_10.exposure.total, 1000 + 26); - assert_eq!(winner_10.score, Perquintill::from_fraction(0.02)); - assert_eq!(winner_10.exposure.others[0].value, 21); - assert_eq!(winner_10.exposure.others[1].value, 5); + assert_eq!(winner_10.exposure.total, 1000 + 525); + assert_eq!(winner_10.score, Perquintill::from_quintillionths(487804878048780)); + assert_eq!(winner_10.exposure.others[0].value, 475); + assert_eq!(winner_10.exposure.others[1].value, 50); - assert_eq!(winner_30.exposure.total, 23); - assert_eq!(winner_30.score, Perquintill::from_quintillionths(42222222222222222)); - assert_eq!(winner_30.exposure.others[0].value, 23); + assert_eq!(winner_30.exposure.total, 1000 + 525); + assert_eq!(winner_30.score, Perquintill::from_quintillionths(743902439024390)); + assert_eq!(winner_30.exposure.others[0].value, 525); }) } @@ -1494,47 +1600,52 @@ fn switching_roles() { .sessions_per_era(3) .build(), || { + // Reset reward destination + for i in &[10, 20] { assert_ok!(Staking::set_payee(Origin::signed(*i), RewardDestination::Controller)); } + assert_eq!(Session::validators(), vec![20, 10]); // put some money in account that we'll use. for i in 1..7 { let _ = Balances::deposit_creating(&i, 5000); } // add 2 nominators - assert_ok!(Staking::bond(Origin::signed(1), 2, 2000, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(2), vec![10, 6])); + assert_ok!(Staking::bond(Origin::signed(1), 2, 2000, RewardDestination::Controller)); + assert_ok!(Staking::nominate(Origin::signed(2), vec![11, 5])); + + assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Controller)); + assert_ok!(Staking::nominate(Origin::signed(4), vec![21, 1])); - assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::default())); - assert_ok!(Staking::nominate(Origin::signed(4), vec![20, 2])); - // add a new validator candidate - assert_ok!(Staking::bond(Origin::signed(5), 6, 1500, RewardDestination::Controller)); + assert_ok!(Staking::bond(Origin::signed(5), 6, 1000, RewardDestination::Controller)); assert_ok!(Staking::validate(Origin::signed(6), ValidatorPrefs::default())); - // new block + // new block System::set_block_number(1); Session::check_rotate_session(System::block_number()); - // no change + // no change assert_eq!(Session::validators(), vec![20, 10]); - // new block + // new block System::set_block_number(2); Session::check_rotate_session(System::block_number()); - // no change + // no change assert_eq!(Session::validators(), vec![20, 10]); // new block --> ne era --> new validators System::set_block_number(3); Session::check_rotate_session(System::block_number()); - // with current nominators 10 and 4 have the most stake + // with current nominators 10 and 5 have the most stake assert_eq!(Session::validators(), vec![6, 10]); - // 2 decides to be a validator. Consequences: - // 6 will not be chosen in the next round (no votes) - // 2 itself will be chosen + 20 who now has the higher votes - // 10 wil have no votes. + // 2 decides to be a validator. Consequences: + // new stakes: + // 10: 1000 self vote + // 6: 1000 self vote + // 20: 1000 self vote + 500 vote + // 2: 2000 self vote + 500 vote. assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); System::set_block_number(4); @@ -1545,7 +1656,7 @@ fn switching_roles() { Session::check_rotate_session(System::block_number()); assert_eq!(Session::validators(), vec![6, 10]); - // ne era + // ne era System::set_block_number(6); Session::check_rotate_session(System::block_number()); assert_eq!(Session::validators(), vec![2, 20]); @@ -1555,14 +1666,11 @@ fn switching_roles() { #[test] fn wrong_vote_is_null() { with_externalities(&mut ExtBuilder::default() - .session_length(1) - .sessions_per_era(1) .nominate(false) .validator_pool(true) .build(), || { - // from the first era onward, only two will be chosen - assert_eq!(Session::validators(), vec![40, 30, 20, 10]); + assert_eq!(Session::validators(), vec![40, 30]); // put some money in account that we'll use. for i in 1..3 { let _ = Balances::deposit_creating(&i, 5000); } @@ -1570,14 +1678,210 @@ fn wrong_vote_is_null() { // add 1 nominators assert_ok!(Staking::bond(Origin::signed(1), 2, 2000, RewardDestination::default())); assert_ok!(Staking::nominate(Origin::signed(2), vec![ - 10, 20, // good votes + 11, 21, // good votes 1, 2, 15, 1000, 25 // crap votes. No effect. ])); - // new block + // new block + System::set_block_number(1); + Session::check_rotate_session(System::block_number()); + + assert_eq!(Session::validators(), vec![20, 10]); + }); +} + +#[test] +fn bond_with_no_staked_value() { + // Behavior when someone bonds with no staked value. + // Particularly when she votes and the candidate is elected. + with_externalities(&mut ExtBuilder::default() + .validator_count(3) + .nominate(false) + .minimum_validator_count(1) + .build(), || { + // setup + assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller)); + let _ = Balances::deposit_creating(&3, 1000); + let initial_balance_2 = Balances::free_balance(&2); + let initial_balance_4 = Balances::free_balance(&4); + + // initial validators + assert_eq!(Session::validators(), vec![20, 10]); + + // Stingy validator. + assert_ok!(Staking::bond(Origin::signed(1), 2, 0, RewardDestination::Controller)); + assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); + System::set_block_number(1); Session::check_rotate_session(System::block_number()); + // Not elected even though we want 3. + assert_eq!(Session::validators(), vec![20, 10]); + + // min of 10 and 20. + assert_eq!(Staking::slot_stake(), 1000); + + // let's make the stingy one elected. + assert_ok!(Staking::bond(Origin::signed(3), 4, 500, RewardDestination::Controller)); + assert_ok!(Staking::nominate(Origin::signed(4), vec![1])); + + assert_eq!(Staking::ledger(4), Some(StakingLedger { stash: 3, active: 500, total: 500, unlocking: vec![]})); + + assert_eq!(Balances::free_balance(&2), initial_balance_2); + assert_eq!(Balances::free_balance(&4), initial_balance_4); + + System::set_block_number(2); + Session::check_rotate_session(System::block_number()); + + assert_eq!(Session::validators(), vec![20, 10, 2]); + assert_eq!(Staking::stakers(1), Exposure { own: 0, total: 500, others: vec![IndividualExposure { who: 3, value: 500}]}); + + assert_eq!(Staking::slot_stake(), 500); + + // no rewards paid to 2 and 4 yet + assert_eq!(Balances::free_balance(&2), initial_balance_2); + assert_eq!(Balances::free_balance(&4), initial_balance_4); + + System::set_block_number(3); + Session::check_rotate_session(System::block_number()); + + let reward = Staking::current_session_reward(); + // 2 will not get any reward + // 4 will get all the reward share + assert_eq!(Balances::free_balance(&2), initial_balance_2); + // assert_eq!(Balances::free_balance(&4), initial_balance_4 + reward); + assert_eq!(Balances::free_balance(&4), initial_balance_4 + reward); + }); +} + +#[test] +fn bond_with_little_staked_value() { + // Behavior when someone bonds with little staked value. + // Particularly when she votes and the candidate is elected. + with_externalities(&mut ExtBuilder::default() + .validator_count(3) + .nominate(false) + .minimum_validator_count(1) + .build(), + || { + // setup + assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller)); + assert_ok!(Staking::set_payee(Origin::signed(20), RewardDestination::Controller)); + let initial_balance_2 = Balances::free_balance(&2); + + // initial validators assert_eq!(Session::validators(), vec![20, 10]); + + // Stingy validator. + assert_ok!(Staking::bond(Origin::signed(1), 2, 1, RewardDestination::Controller)); + assert_ok!(Staking::validate(Origin::signed(2), ValidatorPrefs::default())); + + System::set_block_number(1); + Session::check_rotate_session(System::block_number()); + + // 2 is elected. + // and fucks up the slot stake. + assert_eq!(Session::validators(), vec![20, 10, 2]); + assert_eq!(Staking::slot_stake(), 1); + + // Old ones are rewarded. + assert_eq!(Balances::free_balance(&10), 1 + 10); + assert_eq!(Balances::free_balance(&20), 1 + 10); + // no rewards paid to 2. This was initial election. + assert_eq!(Balances::free_balance(&2), initial_balance_2); + + System::set_block_number(2); + Session::check_rotate_session(System::block_number()); + + assert_eq!(Session::validators(), vec![20, 10, 2]); + assert_eq!(Staking::slot_stake(), 1); + + let reward = Staking::current_session_reward(); + // 2 will not get the full reward, practically 1 + assert_eq!(Balances::free_balance(&2), initial_balance_2 + reward.max(1)); }); } + + +#[test] +#[ignore] // Enable this once post-processing is on. +fn phragmen_linear_worse_case_equalise() { + with_externalities(&mut ExtBuilder::default() + .nominate(false) + .validator_pool(true) + .fare(true) + .build(), + || { + let bond_validator = |a, b| { + let _ = Balances::deposit_creating(&(a-1), b); + assert_ok!(Staking::bond(Origin::signed(a-1), a, b, RewardDestination::Controller)); + assert_ok!(Staking::validate(Origin::signed(a), ValidatorPrefs::default())); + }; + let bond_nominator = |a, b, v| { + let _ = Balances::deposit_creating(&(a-1), b); + assert_ok!(Staking::bond(Origin::signed(a-1), a, b, RewardDestination::Controller)); + assert_ok!(Staking::nominate(Origin::signed(a), v)); + }; + + for i in &[10, 20, 30, 40] { assert_ok!(Staking::set_payee(Origin::signed(*i), RewardDestination::Controller)); } + + bond_validator(50, 1000); + bond_validator(60, 1000); + bond_validator(70, 1000); + + bond_nominator(2, 2000, vec![11]); + bond_nominator(4, 1000, vec![11, 21]); + bond_nominator(6, 1000, vec![21, 31]); + bond_nominator(8, 1000, vec![31, 41]); + bond_nominator(110, 1000, vec![41, 51]); + bond_nominator(112, 1000, vec![51, 61]); + bond_nominator(114, 1000, vec![61, 71]); + + assert_eq!(Session::validators(), vec![40, 30]); + assert_ok!(Staking::set_validator_count(7)); + + System::set_block_number(1); + Session::check_rotate_session(System::block_number()); + + assert_eq!(Session::validators(), vec![10, 60, 40, 20, 50, 30, 70]); + + // Sequential Phragmén with post processing gives + // 10 is elected with stake 3000.0 and score 0.00025 + // 30 is elected with stake 2008.8712884829595 and score 0.0003333333333333333 + // 50 is elected with stake 2000.0001049958742 and score 0.0003333333333333333 + // 60 is elected with stake 1991.128921508789 and score 0.0004444444444444444 + // 20 is elected with stake 2017.7421569824219 and score 0.0005277777777777777 + // 40 is elected with stake 2000.0001049958742 and score 0.0005555555555555556 + // 70 is elected with stake 1982.2574230340813 and score 0.0007222222222222222 + + assert_eq!(Staking::stakers(11).total, 3000); + assert_eq!(Staking::stakers(31).total, 2035); + assert_eq!(Staking::stakers(51).total, 2000); + assert_eq!(Staking::stakers(61).total, 1968); + assert_eq!(Staking::stakers(21).total, 2035); + assert_eq!(Staking::stakers(41).total, 2024); + assert_eq!(Staking::stakers(71).total, 1936); + }) +} + +#[test] +fn phragmen_chooses_correct_validators() { + with_externalities(&mut ExtBuilder::default() + .nominate(true) + .validator_pool(true) + .fare(true) + .validator_count(1) + .build(), + || { + // 4 validator candidates + // self vote + default account 100 is nominator. + assert_eq!(Staking::validator_count(), 1); + assert_eq!(Session::validators().len(), 1); + + System::set_block_number(1); + Session::check_rotate_session(System::block_number()); + + assert_eq!(Session::validators().len(), 1); + }) +}