Skip to content
tests.rs 75.6 KiB
Newer Older
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
Gav Wood's avatar
Gav Wood committed
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Substrate is distributed in the hope that it will be useful,
Gav Wood's avatar
Gav Wood committed
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Substrate.  If not, see <http://www.gnu.org/licenses/>.
Gav Wood's avatar
Gav Wood committed

//! Tests for the module.

Gav Wood's avatar
Gav Wood committed
use super::*;
use runtime_io::with_externalities;
use phragmen;
use srml_support::{assert_ok, assert_noop, assert_eq_uvec, EnumerableStorageMap};
use mock::{Balances, Session, Staking, System, Timestamp, Test, ExtBuilder, Origin};
use srml_support::traits::{Currency, ReservableCurrency};
#[inline]
fn check_exposure(acc: u64) {
	let expo = Staking::stakers(&acc);
	assert_eq!(expo.total as u128, expo.own as u128 + expo.others.iter().map(|e| e.value as u128).sum::<u128>());
}

#[inline]
fn check_exposure_all() {
	Staking::current_elected().into_iter().for_each(|acc| check_exposure(acc));
}

#[inline]
fn assert_total_expo(acc: u64, val: u64) {
	let expo = Staking::stakers(&acc);
	assert_eq!(expo.total, val);
}

#[inline]
fn bond_validator(acc: u64, val: u64) {
	// a = controller
	// a + 1 = stash
	let _ = Balances::make_free_balance_be(&(acc+1), val);
	assert_ok!(Staking::bond(Origin::signed(acc+1), acc, val, RewardDestination::Controller));
	assert_ok!(Staking::validate(Origin::signed(acc), ValidatorPrefs::default()));
}

#[inline]
fn bond_nominator(acc: u64, val: u64, target: Vec<u64>) {
	// a = controller
	// a + 1 = stash
	let _ = Balances::make_free_balance_be(&(acc+1), val);
	assert_ok!(Staking::bond(Origin::signed(acc+1), acc, val, RewardDestination::Controller));
	assert_ok!(Staking::nominate(Origin::signed(acc), target));
}

Gav Wood's avatar
Gav Wood committed
#[test]
fn basic_setup_works() {
	// Verifies initial conditions of mock
	with_externalities(&mut ExtBuilder::default()
		.build(),
	|| {
		assert_eq!(Staking::bonded(&11), Some(10)); // Account 11 is stashed and locked, and account 10 is the controller
		assert_eq!(Staking::bonded(&21), Some(20)); // Account 21 is stashed and locked, and account 20 is the controller
		assert_eq!(Staking::bonded(&1), None);		// Account 1 is not a stashed

		// 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: 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!(<Validators<Test>>::enumerate().collect::<Vec<_>>(), vec![
			(31, 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(101), vec![11, 21]);
		// 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);

		// Initial Era and session
		assert_eq!(Staking::current_era(), 0);
		assert_eq!(Session::current_index(), 0);

		// initial rewards
		assert_eq!(Staking::current_session_reward(), 10);

		// initial slot_stake
		assert_eq!(Staking::slot_stake(),  1125); // Naive
		// initial slash_count of validators
		assert_eq!(Staking::slash_count(&11), 0);
		assert_eq!(Staking::slash_count(&21), 0);

		// All exposures must be correct.
		check_exposure_all();
	});
}

#[test]
fn no_offline_should_work() {
	// Test the staking module works when no validators are offline
	with_externalities(&mut ExtBuilder::default().build(),
	|| {
		// Slashing begins for validators immediately if found offline
Gav Wood's avatar
Gav Wood committed
		assert_eq!(Staking::offline_slash_grace(), 0);
		// Account 10 has not been reported offline
Gav Wood's avatar
Gav Wood committed
		assert_eq!(Staking::slash_count(&10), 0);
		// Account 10 has `balance_factor` free balance
		assert_eq!(Balances::free_balance(&10), 1);
		// Nothing happens to Account 10, as expected
Gav Wood's avatar
Gav Wood committed
		assert_eq!(Staking::slash_count(&10), 0);
		assert_eq!(Balances::free_balance(&10), 1);
		// New era is not being forced
Gav Wood's avatar
Gav Wood committed
		assert!(Staking::forcing_new_era().is_none());
	});
}

#[test]
fn change_controller_works() {
	with_externalities(&mut ExtBuilder::default().build(),
	|| {
		assert_eq!(Staking::bonded(&11), Some(10));

		assert!(<Validators<Test>>::enumerate().map(|(c, _)| c).collect::<Vec<u64>>().contains(&11));
		// 10 can control 11 who is initially a validator.
		assert_ok!(Staking::chill(Origin::signed(10)));
		assert!(!<Validators<Test>>::enumerate().map(|(c, _)| c).collect::<Vec<u64>>().contains(&11));

		assert_ok!(Staking::set_controller(Origin::signed(11), 5));

		System::set_block_number(1);
		Session::check_rotate_session(System::block_number());
		assert_eq!(Staking::current_era(), 1);

		assert_noop!(
			Staking::validate(Origin::signed(10), ValidatorPrefs::default()),
			"not a controller"
		);
		assert_ok!(Staking::validate(Origin::signed(5), ValidatorPrefs::default()));
	})
}

#[test]
fn invulnerability_should_work() {
	// Test that users can be invulnerable from slashing and being kicked
	with_externalities(&mut ExtBuilder::default().build(),
	|| {
		// Make account 11 invulnerable
		assert_ok!(Staking::set_invulnerables(vec![11]));
		// Give account 11 some funds
		let _ = Balances::make_free_balance_be(&11, 70);
		// There is no slash grace -- slash immediately.
		assert_eq!(Staking::offline_slash_grace(), 0);
		// 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!(<Validators<Test>>::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);
		// Show that account 11 has not been touched
		assert_eq!(Staking::slash_count(&11), 0);
		assert_eq!(Balances::free_balance(&11), 70);
		assert!(<Validators<Test>>::exists(&11));
		// New era not being forced
		// NOTE: new era is always forced once slashing happens -> new validators need to be chosen.
Gav Wood's avatar
Gav Wood committed
		assert!(Staking::forcing_new_era().is_none());
	});
}

#[test]
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::make_free_balance_be(&11, 1000);
		// Confirm account 10 is a validator
Loading full blame...