Session keys buffered for a session. (#2946)

* Session keys buffered for the duration of a session.

* Add queued_keys getter.

* Make sure genesis state is consistent.

* Add validator_count validators.

* Compensate for session delay.

* Remove unused code.

* Add num_validators option.

* Fix session numbers.

* Fix merge.

* Reintroduce changed.

* Update runtime.

* Make NextKeyFor private.

* Move block initialization to function.

* Update lib.rs

* Add test for change propagation.

* Fix docstring.

* Use get instead of take.

* Initialize validators from keys.

* Next try.

* Fix build.

* Fix warning.

* Make initial validator selection more transparent.

* Make storage items private.

* Reorder genesis initialization.

* Update Cargo.lock

* Update runtime version.

* Update runtime version.

* Update Cargo.lock

* Update runtime version.

* Add docs.
This commit is contained in:
David Craven
2019-07-04 12:40:10 +02:00
committed by GitHub
parent fe08221479
commit 336053f7ae
8 changed files with 264 additions and 141 deletions
+7 -5
View File
@@ -281,7 +281,7 @@ use srml_support::{
WithdrawReasons, OnUnbalanced, Imbalance, Get
}
};
use session::{OnSessionEnding, SessionIndex};
use session::{OnSessionEnding, SelectInitialValidators, SessionIndex};
use primitives::Perbill;
use primitives::traits::{
Convert, Zero, One, StaticLookup, CheckedSub, CheckedShl, Saturating, Bounded
@@ -587,10 +587,6 @@ decl_storage! {
}, _ => Ok(())
};
}
if let (_, Some(validators)) = <Module<T>>::select_validators() {
<session::Validators<T>>::put(&validators);
}
});
});
}
@@ -1255,3 +1251,9 @@ impl<T: Trait> OnFreeBalanceZero<T::AccountId> for Module<T> {
<Nominators<T>>::remove(stash);
}
}
impl<T: Trait> SelectInitialValidators<T> for Module<T> {
fn select_initial_validators() -> Option<Vec<T::AccountId>> {
<Module<T>>::select_validators().1
}
}
+24 -14
View File
@@ -126,6 +126,7 @@ impl session::Trait for Test {
type ShouldEndSession = session::PeriodicSessions<Period, Offset>;
type SessionHandler = TestSessionHandler;
type Event = ();
type SelectInitialValidators = Staking;
}
impl timestamp::Trait for Test {
type Moment = u64;
@@ -148,26 +149,26 @@ impl Trait for Test {
pub struct ExtBuilder {
existential_deposit: u64,
current_era: EraIndex,
reward: u64,
validator_pool: bool,
nominate: bool,
validator_count: u32,
minimum_validator_count: u32,
fair: bool,
num_validators: Option<u32>,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self {
existential_deposit: 0,
current_era: 0,
reward: 10,
validator_pool: false,
nominate: true,
validator_count: 2,
minimum_validator_count: 0,
fair: true
fair: true,
num_validators: None,
}
}
}
@@ -177,10 +178,6 @@ impl ExtBuilder {
self.existential_deposit = existential_deposit;
self
}
pub fn _current_era(mut self, current_era: EraIndex) -> Self {
self.current_era = current_era;
self
}
pub fn validator_pool(mut self, validator_pool: bool) -> Self {
self.validator_pool = validator_pool;
self
@@ -201,6 +198,10 @@ impl ExtBuilder {
self.fair = is_fair;
self
}
pub fn num_validators(mut self, num_validators: u32) -> Self {
self.num_validators = Some(num_validators);
self
}
pub fn set_associated_consts(&self) {
EXISTENTIAL_DEPOSIT.with(|v| *v.borrow_mut() = self.existential_deposit);
}
@@ -212,12 +213,12 @@ impl ExtBuilder {
} else {
1
};
let validators = if self.validator_pool { vec![10, 20, 30, 40] } else { vec![10, 20] };
let _ = session::GenesisConfig::<Test>{
// NOTE: if config.nominate == false then 100 is also selected in the initial round.
validators,
keys: vec![],
}.assimilate_storage(&mut t, &mut c);
let num_validators = self.num_validators.unwrap_or(self.validator_count);
let validators = (0..num_validators)
.map(|x| ((x + 1) * 10) as u64)
.collect::<Vec<_>>();
let _ = balances::GenesisConfig::<Test>{
balances: vec![
(1, 10 * balance_factor),
@@ -237,6 +238,7 @@ impl ExtBuilder {
],
vesting: vec![],
}.assimilate_storage(&mut t, &mut c);
let stake_21 = if self.fair { 1000 } else { 2000 };
let stake_31 = if self.validator_pool { balance_factor * 1000 } else { 1 };
let status_41 = if self.validator_pool {
@@ -246,7 +248,7 @@ impl ExtBuilder {
};
let nominated = if self.nominate { vec![11, 21] } else { vec![] };
let _ = GenesisConfig::<Test>{
current_era: self.current_era,
current_era: 0,
stakers: vec![
(11, 10, balance_factor * 1000, StakerStatus::<AccountId>::Validator),
(21, 20, stake_21, StakerStatus::<AccountId>::Validator),
@@ -263,9 +265,15 @@ impl ExtBuilder {
offline_slash_grace: 0,
invulnerables: vec![],
}.assimilate_storage(&mut t, &mut c);
let _ = timestamp::GenesisConfig::<Test>{
minimum_period: 5,
}.assimilate_storage(&mut t, &mut c);
let _ = session::GenesisConfig::<Test> {
keys: validators.iter().map(|x| (*x, UintAuthorityId(*x))).collect(),
}.assimilate_storage(&mut t, &mut c);
let mut ext = t.into();
runtime_io::with_externalities(&mut ext, || {
let validators = Session::validators();
@@ -346,6 +354,8 @@ pub fn bond_nominator(acc: u64, val: u64, target: Vec<u64>) {
}
pub fn start_session(session_index: session::SessionIndex) {
// Compensate for session delay
let session_index = session_index + 1;
for i in 0..(session_index - Session::current_index()) {
System::set_block_number((i + 1).into());
Session::on_initialize(System::block_number());
+29 -54
View File
@@ -411,18 +411,18 @@ fn multi_era_reward_should_work() {
// Set payee to controller
assert_ok!(Staking::set_payee(Origin::signed(10), RewardDestination::Controller));
start_session(1);
start_session(0);
// session triggered: the reward value stashed should be 10
assert_eq!(Staking::current_session_reward(), session_reward);
assert_eq!(Staking::current_era_reward(), session_reward);
start_session(2);
start_session(1);
assert_eq!(Staking::current_session_reward(), session_reward);
assert_eq!(Staking::current_era_reward(), 2*session_reward);
start_session(3);
start_session(2);
// 1 + sum of of the session rewards accumulated
let recorded_balance = 1 + 3*session_reward;
@@ -433,13 +433,13 @@ fn multi_era_reward_should_work() {
assert_eq!(Staking::current_session_reward(), new_session_reward);
// fast forward to next era:
start_session(5);
start_session(4);
// intermediate test.
assert_eq!(Staking::current_era_reward(), 2*new_session_reward);
// new era is triggered here.
start_session(6);
start_session(5);
// pay time
assert_eq!(Balances::total_balance(&10), 3*new_session_reward + recorded_balance);
@@ -464,10 +464,7 @@ fn staking_should_work() {
for i in 1..5 { let _ = Balances::make_free_balance_be(&i, 2000); }
// --- Block 1:
System::set_block_number(1);
Session::on_initialize(System::block_number());
assert_eq!(Staking::current_era(), 0);
start_session(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));
assert_ok!(Staking::validate(Origin::signed(4), ValidatorPrefs::default()));
@@ -476,48 +473,30 @@ fn staking_should_work() {
assert_eq_uvec!(Session::validators(), vec![20, 10]);
// --- Block 2:
System::set_block_number(2);
Session::on_initialize(System::block_number());
assert_eq!(Staking::current_era(), 0);
start_session(2);
// No effects will be seen so far. Era has not been yet triggered.
assert_eq_uvec!(Session::validators(), vec![20, 10]);
// --- Block 3: the validators will now change.
System::set_block_number(3);
Session::on_initialize(System::block_number());
// 2 only voted for 4 and 20
assert_eq!(Session::validators().len(), 2);
assert_eq_uvec!(Session::validators(), vec![20, 4]);
// --- Block 3: the validators will now be queued.
start_session(3);
assert_eq!(Staking::current_era(), 1);
// --- Block 4: the validators will now be changed.
start_session(4);
assert_eq_uvec!(Session::validators(), vec![20, 4]);
// --- Block 4: Unstake 4 as a validator, freeing up the balance stashed in 3
System::set_block_number(4);
Session::on_initialize(System::block_number());
// 4 will chill
Staking::chill(Origin::signed(4)).unwrap();
// nothing should be changed so far.
assert_eq_uvec!(Session::validators(), vec![20, 4]);
assert_eq!(Staking::current_era(), 1);
// --- Block 5: nothing. 4 is still there.
System::set_block_number(5);
Session::on_initialize(System::block_number());
start_session(5);
assert_eq_uvec!(Session::validators(), vec![20, 4]);
assert_eq!(Staking::current_era(), 1);
// --- Block 6: 4 will not be a validator.
System::set_block_number(6);
Session::on_initialize(System::block_number());
assert_eq!(Staking::current_era(), 2);
assert_eq!(Session::validators().contains(&4), false);
start_session(7);
assert_eq_uvec!(Session::validators(), vec![20, 10]);
// Note: the stashed value of 4 is still lock
@@ -537,6 +516,7 @@ fn less_than_needed_candidates_works() {
.minimum_validator_count(1)
.validator_count(4)
.nominate(false)
.num_validators(3)
.build(),
|| {
assert_eq!(Staking::validator_count(), 4);
@@ -564,6 +544,7 @@ fn no_candidate_emergency_condition() {
with_externalities(&mut ExtBuilder::default()
.minimum_validator_count(10)
.validator_count(15)
.num_validators(4)
.validator_pool(true)
.nominate(false)
.build(),
@@ -857,37 +838,37 @@ fn session_and_eras_work() {
assert_eq!(Staking::current_era(), 0);
// Block 1: No change.
start_session(1);
start_session(0);
assert_eq!(Session::current_index(), 1);
assert_eq!(Staking::current_era(), 0);
// Block 2: Simple era change.
start_session(3);
start_session(2);
assert_eq!(Session::current_index(), 3);
assert_eq!(Staking::current_era(), 1);
// Block 3: Schedule an era length change; no visible changes.
start_session(4);
start_session(3);
assert_eq!(Session::current_index(), 4);
assert_eq!(Staking::current_era(), 1);
// Block 4: Era change kicks in.
start_session(6);
start_session(5);
assert_eq!(Session::current_index(), 6);
assert_eq!(Staking::current_era(), 2);
// Block 5: No change.
start_session(7);
start_session(6);
assert_eq!(Session::current_index(), 7);
assert_eq!(Staking::current_era(), 2);
// Block 6: No change.
start_session(8);
start_session(7);
assert_eq!(Session::current_index(), 8);
assert_eq!(Staking::current_era(), 2);
// Block 7: Era increment.
start_session(9);
start_session(8);
assert_eq!(Session::current_index(), 9);
assert_eq!(Staking::current_era(), 3);
});
@@ -1656,22 +1637,19 @@ fn switching_roles() {
assert_ok!(Staking::validate(Origin::signed(6), ValidatorPrefs::default()));
// new block
System::set_block_number(1);
Session::on_initialize(System::block_number());
start_session(1);
// no change
assert_eq_uvec!(Session::validators(), vec![20, 10]);
// new block
System::set_block_number(2);
Session::on_initialize(System::block_number());
start_session(2);
// no change
assert_eq_uvec!(Session::validators(), vec![20, 10]);
// new block --> ne era --> new validators
System::set_block_number(3);
Session::on_initialize(System::block_number());
start_session(3);
// with current nominators 10 and 5 have the most stake
assert_eq_uvec!(Session::validators(), vec![6, 10]);
@@ -1685,17 +1663,14 @@ fn switching_roles() {
// 2 : 2000 self vote + 250 vote.
// Winners: 20 and 2
System::set_block_number(4);
Session::on_initialize(System::block_number());
start_session(4);
assert_eq_uvec!(Session::validators(), vec![6, 10]);
System::set_block_number(5);
Session::on_initialize(System::block_number());
start_session(5);
assert_eq_uvec!(Session::validators(), vec![6, 10]);
// ne era
System::set_block_number(6);
Session::on_initialize(System::block_number());
start_session(6);
assert_eq_uvec!(Session::validators(), vec![2, 20]);
check_exposure_all();