Punish offline validators, aura-style (#1216)

* make offline-reporting infrastructure more generic

* add a listener-trait for watching when the timestamp has been set

* prevent inclusion of empty offline reports

* add test for exclusion

* generate aura-offline reports

* ability to slash many times for being offline "multiple" times

* Logic for punishing validators for missing aura steps

* stub tests

* pave way for verification of timestamp vs slot

* alter aura import queue to wait for timestamp

* check timestamp matches seal

* do inherent check properly

* service compiles

* all tests compile

* test srml-aura logic

* aura tests pass

* everything builds

* some more final tweaks to block authorship for aura

* switch to manual delays before step

* restore substrate-consensus-aura to always std and address grumbles

* update some state roots in executor tests

* node-executor tests pass

* get most tests passing

* address grumbles
This commit is contained in:
Robert Habermeier
2018-12-10 18:37:08 +01:00
committed by GitHub
parent dcc38fe45a
commit 6299b42a4d
41 changed files with 1344 additions and 379 deletions
+40
View File
@@ -0,0 +1,40 @@
[package]
name = "srml-aura"
version = "0.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
hex-literal = "0.1.0"
parity-codec = { version = "2.1", default-features = false }
parity-codec-derive = { version = "2.1", default-features = false }
serde = { version = "1.0", default-features = false }
substrate-primitives = { path = "../../core/primitives", default-features = false }
sr-std = { path = "../../core/sr-std", default-features = false }
sr-io = { path = "../../core/sr-io", default-features = false }
sr-primitives = { path = "../../core/sr-primitives", default-features = false }
srml-support = { path = "../support", default-features = false }
srml-system = { path = "../system", default-features = false }
srml-consensus = { path = "../consensus", default-features = false }
srml-timestamp = { path = "../timestamp", default-features = false }
srml-staking = { path = "../staking", default-features = false }
[dev-dependencies]
lazy_static = "1.0"
parking_lot = "0.6"
[features]
default = ["std"]
std = [
"serde/std",
"parity-codec/std",
"parity-codec-derive/std",
"substrate-primitives/std",
"sr-std/std",
"sr-io/std",
"srml-support/std",
"sr-primitives/std",
"srml-system/std",
"srml-consensus/std",
"srml-timestamp/std",
"srml-staking/std",
]
+199
View File
@@ -0,0 +1,199 @@
// Copyright 2017-2018 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// 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,
// 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/>.
//! Consensus extension module for Aura consensus. This manages offline reporting.
#![cfg_attr(not(feature = "std"), no_std)]
#[allow(unused_imports)]
#[macro_use]
extern crate sr_std as rstd;
#[macro_use]
extern crate parity_codec_derive;
extern crate parity_codec;
#[macro_use]
extern crate srml_support as runtime_support;
extern crate sr_primitives as primitives;
extern crate srml_system as system;
extern crate srml_timestamp as timestamp;
extern crate srml_staking as staking;
extern crate substrate_primitives;
#[cfg(test)]
extern crate srml_consensus as consensus;
#[cfg(test)]
extern crate sr_io as runtime_io;
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
extern crate parking_lot;
use rstd::prelude::*;
use runtime_support::storage::StorageValue;
use runtime_support::dispatch::Result;
use primitives::traits::{As, Zero};
use timestamp::OnTimestampSet;
mod mock;
mod tests;
/// Something which can handle Aura consensus reports.
pub trait HandleReport {
fn handle_report(report: AuraReport);
}
impl HandleReport for () {
fn handle_report(_report: AuraReport) { }
}
pub trait Trait: timestamp::Trait {
/// The logic for handling reports.
type HandleReport: HandleReport;
}
decl_storage! {
trait Store for Module<T: Trait> as Aura {
// The last timestamp.
LastTimestamp get(last) build(|_| T::Moment::sa(0)): T::Moment;
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin { }
}
/// A report of skipped authorities in aura.
#[derive(Clone, Encode, Decode, PartialEq, Eq)]
#[cfg_attr(feature = "std", derive(Debug))]
pub struct AuraReport {
// The first skipped slot.
start_slot: usize,
// The number of times authorities were skipped.
skipped: usize,
}
impl AuraReport {
/// Call the closure with (validator_indices, punishment_count) for each
/// validator to punish.
pub fn punish<F>(&self, validator_count: usize, mut punish_with: F)
where F: FnMut(usize, usize)
{
let start_slot = self.start_slot % validator_count;
// the number of times everyone was skipped.
let skipped_all = self.skipped / validator_count;
// the number of validators who were skipped once after that.
let skipped_after = self.skipped % validator_count;
let iter = (start_slot..validator_count).into_iter()
.chain(0..start_slot)
.enumerate();
for (rel_index, actual_index) in iter {
let slash_count = skipped_all + if rel_index < skipped_after {
1
} else {
// avoid iterating over all authorities when skipping a couple.
if skipped_all == 0 { break }
0
};
if slash_count > 0 {
punish_with(actual_index, slash_count);
}
}
}
}
impl<T: Trait> Module<T> {
/// Determine the Aura slot-duration based on the timestamp module configuration.
pub fn slot_duration() -> u64 {
// we double the minimum block-period so each author can always propose within
// the majority of their slot.
<timestamp::Module<T>>::block_period().as_().saturating_mul(2)
}
/// Verify an inherent slot that is used in a block seal against a timestamp
/// extracted from the block.
// TODO: ensure `ProvideInherent` can deal with dependencies like this.
// https://github.com/paritytech/substrate/issues/1228
pub fn verify_inherent(timestamp: T::Moment, seal_slot: u64) -> Result {
let timestamp_based_slot = timestamp.as_() / Self::slot_duration();
if timestamp_based_slot == seal_slot {
Ok(())
} else {
Err("timestamp set in block doesn't match slot in seal".into())
}
}
fn on_timestamp_set<H: HandleReport>(now: T::Moment, slot_duration: T::Moment) {
let last = Self::last();
<Self as Store>::LastTimestamp::put(now.clone());
if last == T::Moment::zero() {
return;
}
assert!(slot_duration > T::Moment::zero(), "Aura slot duration cannot be zero.");
let last_slot = last / slot_duration.clone();
let first_skipped = last_slot.clone() + T::Moment::sa(1);
let cur_slot = now / slot_duration;
assert!(last_slot < cur_slot, "Only one block may be authored per slot.");
if cur_slot == first_skipped { return }
let slot_to_usize = |slot: T::Moment| { slot.as_() as usize };
let skipped_slots = cur_slot - last_slot - T::Moment::sa(1);
H::handle_report(AuraReport {
start_slot: slot_to_usize(first_skipped),
skipped: slot_to_usize(skipped_slots),
})
}
}
impl<T: Trait> OnTimestampSet<T::Moment> for Module<T> {
fn on_timestamp_set(moment: T::Moment) {
Self::on_timestamp_set::<T::HandleReport>(moment, T::Moment::sa(Self::slot_duration()))
}
}
/// A type for performing slashing based on aura reports.
pub struct StakingSlasher<T>(::rstd::marker::PhantomData<T>);
impl<T: staking::Trait + Trait> HandleReport for StakingSlasher<T> {
fn handle_report(report: AuraReport) {
let validators = staking::Module::<T>::validators();
report.punish(
validators.len(),
|idx, slash_count| {
let v = validators[idx].clone();
staking::Module::<T>::on_offline_validator(v, slash_count);
}
);
}
}
+78
View File
@@ -0,0 +1,78 @@
// Copyright 2018 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// 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,
// 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/>.
//! Test utilities
#![cfg(test)]
use primitives::{BuildStorage, testing::{Digest, DigestItem, Header}};
use runtime_io;
use substrate_primitives::{H256, Blake2Hasher};
use {Trait, Module, consensus, system, timestamp};
impl_outer_origin!{
pub enum Origin for Test {}
}
// Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Test;
impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem;
type SessionKey = u64;
type InherentOfflineReport = ();
}
impl system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = ::primitives::traits::BlakeTwo256;
type Digest = Digest;
type AccountId = u64;
type Header = Header;
type Event = ();
type Log = DigestItem;
}
impl timestamp::Trait for Test {
const TIMESTAMP_SET_POSITION: u32 = 0;
type Moment = u64;
type OnTimestampSet = Aura;
}
impl Trait for Test {
type HandleReport = ();
}
pub fn new_test_ext(authorities: Vec<u64>) -> runtime_io::TestExternalities<Blake2Hasher> {
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
t.extend(consensus::GenesisConfig::<Test>{
code: vec![],
authorities,
}.build_storage().unwrap().0);
t.extend(timestamp::GenesisConfig::<Test>{
period: 1,
}.build_storage().unwrap().0);
t.into()
}
pub type System = system::Module<Test>;
pub type Aura = Module<Test>;
+79
View File
@@ -0,0 +1,79 @@
// Copyright 2017-2018 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// 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,
// 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/>.
//! Tests for the module.
#![cfg(test)]
use mock::{System, Aura, new_test_ext};
use primitives::traits::Header;
use runtime_io::with_externalities;
use parking_lot::Mutex;
use {AuraReport, HandleReport};
#[test]
fn aura_report_gets_skipped_correctly() {
let mut report = AuraReport {
start_slot: 0,
skipped: 30,
};
let mut validators = vec![0; 10];
report.punish(10, |idx, count| validators[idx] += count);
assert_eq!(validators, vec![3; 10]);
let mut validators = vec![0; 4];
report.punish(4, |idx, count| validators[idx] += count);
assert_eq!(validators, vec![8, 8, 7, 7]);
report.start_slot = 2;
report.punish(4, |idx, count| validators[idx] += count);
assert_eq!(validators, vec![15, 15, 15, 15]);
}
#[test]
fn aura_reports_offline() {
lazy_static! {
static ref SLASH_COUNTS: Mutex<Vec<usize>> = Mutex::new(vec![0; 4]);
}
struct HandleTestReport;
impl HandleReport for HandleTestReport {
fn handle_report(report: AuraReport) {
let mut counts = SLASH_COUNTS.lock();
report.punish(counts.len(), |idx, count| counts[idx] += count);
}
}
with_externalities(&mut new_test_ext(vec![0, 1, 2, 3]), || {
System::initialise(&1, &Default::default(), &Default::default());
let slot_duration = Aura::slot_duration();
Aura::on_timestamp_set::<HandleTestReport>(5 * slot_duration, slot_duration);
let header = System::finalise();
// no slashing when last step was 0.
assert_eq!(SLASH_COUNTS.lock().as_slice(), &[0, 0, 0, 0]);
System::initialise(&2, &header.hash(), &Default::default());
Aura::on_timestamp_set::<HandleTestReport>(8 * slot_duration, slot_duration);
let _header = System::finalise();
// Steps 6 and 7 were skipped.
assert_eq!(SLASH_COUNTS.lock().as_slice(), &[0, 0, 1, 1]);
});
}
+80 -25
View File
@@ -61,12 +61,63 @@ impl<S: codec::Codec + Default> StorageVec for AuthorityStorageVec<S> {
pub type KeyValue = (Vec<u8>, Vec<u8>);
pub trait OnOfflineValidator {
fn on_offline_validator(validator_index: usize);
/// Handling offline validator reports in a generic way.
pub trait OnOfflineReport<Offline> {
fn handle_report(offline: Offline);
}
impl OnOfflineValidator for () {
fn on_offline_validator(_validator_index: usize) {}
impl<T> OnOfflineReport<T> for () {
fn handle_report(_: T) {}
}
/// Describes the offline-reporting extrinsic.
pub trait InherentOfflineReport {
/// The report data type passed to the runtime during block authorship.
type Inherent: codec::Codec + Parameter;
/// Whether an inherent is empty and doesn't need to be included.
fn is_empty(inherent: &Self::Inherent) -> bool;
/// Handle the report.
fn handle_report(report: Self::Inherent);
/// Whether two reports are compatible.
fn check_inherent(contained: &Self::Inherent, expected: &Self::Inherent) -> Result<(), &'static str>;
}
impl InherentOfflineReport for () {
type Inherent = ();
fn is_empty(_inherent: &()) -> bool { true }
fn handle_report(_: ()) { }
fn check_inherent(_: &(), _: &()) -> Result<(), &'static str> {
Err("Explicit reporting not allowed")
}
}
/// A variant of the `OfflineReport` which is useful for instant-finality blocks.
///
/// This assumes blocks are only finalized
pub struct InstantFinalityReportVec<T>(::rstd::marker::PhantomData<T>);
impl<T: OnOfflineReport<Vec<u32>>> InherentOfflineReport for InstantFinalityReportVec<T> {
type Inherent = Vec<u32>;
fn is_empty(inherent: &Self::Inherent) -> bool { inherent.is_empty() }
fn handle_report(report: Vec<u32>) {
T::handle_report(report)
}
fn check_inherent(contained: &Self::Inherent, expected: &Self::Inherent) -> Result<(), &'static str> {
contained.iter().try_for_each(|n|
if !expected.contains(n) {
Err("Node we believe online marked offline")
} else {
Ok(())
}
)
}
}
pub type Log<T> = RawLog<
@@ -111,7 +162,9 @@ pub trait Trait: system::Trait {
type Log: From<Log<Self>> + Into<system::DigestItemOf<Self>>;
type SessionKey: Parameter + Default + MaybeSerializeDebug;
type OnOfflineValidator: OnOfflineValidator;
/// Defines the offline-report type of the trait.
/// Set to `()` if offline-reports aren't needed for this runtime.
type InherentOfflineReport: InherentOfflineReport;
}
decl_storage! {
@@ -143,23 +196,20 @@ decl_module! {
/// Report some misbehaviour.
fn report_misbehavior(origin, _report: Vec<u8>) {
ensure_signed(origin)?;
// TODO.
// TODO: requires extension trait.
}
/// Note the previous block's validator missed their opportunity to propose a block.
/// This only comes in if 2/3+1 of the validators agree that no proposal was submitted.
/// It's only relevant for the previous block.
fn note_offline(origin, offline_val_indices: Vec<u32>) {
fn note_offline(origin, offline: <T::InherentOfflineReport as InherentOfflineReport>::Inherent) {
ensure_inherent(origin)?;
assert!(
<system::Module<T>>::extrinsic_index() == Some(T::NOTE_OFFLINE_POSITION),
"note_offline extrinsic must be at position {} in the block",
T::NOTE_OFFLINE_POSITION
);
for validator_index in offline_val_indices.into_iter() {
T::OnOfflineValidator::on_offline_validator(validator_index as usize);
}
T::InherentOfflineReport::handle_report(offline);
}
/// Make some on-chain remark.
@@ -239,29 +289,34 @@ impl<T: Trait> Module<T> {
}
impl<T: Trait> ProvideInherent for Module<T> {
type Inherent = Vec<u32>;
type Inherent = <T::InherentOfflineReport as InherentOfflineReport>::Inherent;
type Call = Call<T>;
fn create_inherent_extrinsics(data: Self::Inherent) -> Vec<(u32, Self::Call)> {
vec![(T::NOTE_OFFLINE_POSITION, Call::note_offline(data))]
if <T::InherentOfflineReport as InherentOfflineReport>::is_empty(&data) {
vec![]
} else {
vec![(T::NOTE_OFFLINE_POSITION, Call::note_offline(data))]
}
}
fn check_inherent<Block: BlockT, F: Fn(&Block::Extrinsic) -> Option<&Self::Call>>(
block: &Block, data: Self::Inherent, extract_function: &F
block: &Block, expected: Self::Inherent, extract_function: &F
) -> result::Result<(), CheckInherentError> {
let noted_offline = block
.extrinsics().get(T::NOTE_OFFLINE_POSITION as usize)
.extrinsics()
.get(T::NOTE_OFFLINE_POSITION as usize)
.and_then(|xt| match extract_function(&xt) {
Some(Call::note_offline(ref x)) => Some(&x[..]),
Some(Call::note_offline(ref x)) => Some(x),
_ => None,
}).unwrap_or(&[]);
});
noted_offline.iter().try_for_each(|n|
if !data.contains(n) {
Err(CheckInherentError::Other("Online node marked offline".into()))
} else {
Ok(())
}
)
// REVIEW: perhaps we should be passing a `None` to check_inherent.
if let Some(noted_offline) = noted_offline {
<T::InherentOfflineReport as InherentOfflineReport>::check_inherent(&noted_offline, &expected)
.map_err(|e| CheckInherentError::Other(e.into()))?;
}
Ok(())
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ impl Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem;
type SessionKey = u64;
type OnOfflineValidator = ();
type InherentOfflineReport = ::InstantFinalityReportVec<()>;
}
impl system::Trait for Test {
type Origin = Origin;
+10 -1
View File
@@ -18,7 +18,7 @@
#![cfg(test)]
use primitives::{generic, testing, traits::OnFinalise};
use primitives::{generic, testing, traits::{OnFinalise, ProvideInherent}};
use runtime_io::with_externalities;
use substrate_primitives::H256;
use mock::{Consensus, System, new_test_ext};
@@ -63,3 +63,12 @@ fn authorities_change_is_not_logged_when_changed_back_to_original() {
});
});
}
#[test]
fn offline_report_can_be_excluded() {
with_externalities(&mut new_test_ext(vec![1, 2, 3]), || {
System::initialise(&1, &Default::default(), &Default::default());
assert!(Consensus::create_inherent_extrinsics(Vec::new()).is_empty());
assert_eq!(Consensus::create_inherent_extrinsics(vec![0]).len(), 1);
});
}
+2 -1
View File
@@ -261,7 +261,7 @@ mod tests {
const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem;
type SessionKey = u64;
type OnOfflineValidator = ();
type InherentOfflineReport = ();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -278,6 +278,7 @@ mod tests {
impl timestamp::Trait for Test {
const TIMESTAMP_SET_POSITION: u32 = 0;
type Moment = u64;
type OnTimestampSet = ();
}
impl Trait for Test {
type ConvertAccountIdToSessionKey = Identity;
+43 -28
View File
@@ -333,6 +333,11 @@ impl<T: Trait> Module<T> {
}
}
/// Get the current validators.
pub fn validators() -> Vec<T::AccountId> {
session::Module::<T>::validators()
}
// PUBLIC MUTABLES (DANGEROUS)
/// Slash a given validator by a specific amount. Removes the slash from their balance by preference,
@@ -490,6 +495,38 @@ impl<T: Trait> Module<T> {
<CurrentOfflineSlash<T>>::put(Self::offline_slash().times(stake_range.1));
<CurrentSessionReward<T>>::put(Self::session_reward().times(stake_range.1));
}
/// Call when a validator is determined to be offline. `count` is the
/// number of offences the validator has committed.
pub fn on_offline_validator(v: T::AccountId, count: usize) {
for _ in 0..count {
let slash_count = Self::slash_count(&v);
<SlashCount<T>>::insert(v.clone(), slash_count + 1);
let grace = Self::offline_slash_grace();
let event = if slash_count >= grace {
let instances = slash_count - grace;
let slash = Self::current_offline_slash() << instances;
let next_slash = slash << 1u32;
let _ = Self::slash_validator(&v, slash);
if instances >= Self::validator_preferences(&v).unstake_threshold
|| Self::slashable_balance(&v) < next_slash
{
if let Some(pos) = Self::intentions().into_iter().position(|x| &x == &v) {
Self::apply_unstake(&v, pos)
.expect("pos derived correctly from Self::intentions(); \
apply_unstake can only fail if pos wrong; \
Self::intentions() doesn't change; qed");
}
let _ = Self::apply_force_new_era(false);
}
RawEvent::OfflineSlash(v.clone(), slash)
} else {
RawEvent::OfflineWarning(v.clone(), slash_count)
};
Self::deposit_event(event);
}
}
}
impl<T: Trait> OnSessionChange<T::Moment> for Module<T> {
@@ -514,33 +551,11 @@ impl<T: Trait> balances::OnFreeBalanceZero<T::AccountId> for Module<T> {
}
}
impl<T: Trait> consensus::OnOfflineValidator for Module<T> {
fn on_offline_validator(validator_index: usize) {
let v = <session::Module<T>>::validators()[validator_index].clone();
let slash_count = Self::slash_count(&v);
<SlashCount<T>>::insert(v.clone(), slash_count + 1);
let grace = Self::offline_slash_grace();
let event = if slash_count >= grace {
let instances = slash_count - grace;
let slash = Self::current_offline_slash() << instances;
let next_slash = slash << 1u32;
let _ = Self::slash_validator(&v, slash);
if instances >= Self::validator_preferences(&v).unstake_threshold
|| Self::slashable_balance(&v) < next_slash
{
if let Some(pos) = Self::intentions().into_iter().position(|x| &x == &v) {
Self::apply_unstake(&v, pos)
.expect("pos derived correctly from Self::intentions(); \
apply_unstake can only fail if pos wrong; \
Self::intentions() doesn't change; qed");
}
let _ = Self::apply_force_new_era(false);
}
RawEvent::OfflineSlash(v, slash)
} else {
RawEvent::OfflineWarning(v, slash_count)
};
Self::deposit_event(event);
impl<T: Trait> consensus::OnOfflineReport<Vec<u32>> for Module<T> {
fn handle_report(reported_indices: Vec<u32>) {
for validator_index in reported_indices {
let v = <session::Module<T>>::validators()[validator_index as usize].clone();
Self::on_offline_validator(v, 1);
}
}
}
+2 -1
View File
@@ -36,7 +36,7 @@ impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem;
type SessionKey = u64;
type OnOfflineValidator = ();
type InherentOfflineReport = ();
}
impl system::Trait for Test {
type Origin = Origin;
@@ -65,6 +65,7 @@ impl session::Trait for Test {
impl timestamp::Trait for Test {
const TIMESTAMP_SET_POSITION: u32 = 0;
type Moment = u64;
type OnTimestampSet = ();
}
impl Trait for Test {
type OnRewardMinted = ();
+21 -22
View File
@@ -19,7 +19,6 @@
#![cfg(test)]
use super::*;
use consensus::OnOfflineValidator;
use runtime_io::with_externalities;
use mock::{Balances, Session, Staking, System, Timestamp, Test, new_test_ext, Origin};
@@ -44,7 +43,7 @@ fn note_offline_should_work() {
assert_eq!(Staking::slash_count(&10), 0);
assert_eq!(Balances::free_balance(&10), 70);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(10, 1);
assert_eq!(Staking::slash_count(&10), 1);
assert_eq!(Balances::free_balance(&10), 50);
assert!(Staking::forcing_new_era().is_none());
@@ -59,11 +58,11 @@ fn note_offline_exponent_should_work() {
assert_eq!(Staking::slash_count(&10), 0);
assert_eq!(Balances::free_balance(&10), 150);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(10, 1);
assert_eq!(Staking::slash_count(&10), 1);
assert_eq!(Balances::free_balance(&10), 130);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(10, 1);
assert_eq!(Staking::slash_count(&10), 2);
assert_eq!(Balances::free_balance(&10), 90);
assert!(Staking::forcing_new_era().is_none());
@@ -82,15 +81,15 @@ fn note_offline_grace_should_work() {
assert_eq!(Balances::free_balance(&10), 70);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(10, 1);
assert_eq!(Staking::slash_count(&10), 1);
assert_eq!(Balances::free_balance(&10), 70);
assert_eq!(Staking::slash_count(&20), 0);
assert_eq!(Balances::free_balance(&20), 70);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(1);
Staking::on_offline_validator(10, 1);
Staking::on_offline_validator(20, 1);
assert_eq!(Staking::slash_count(&10), 2);
assert_eq!(Balances::free_balance(&10), 50);
assert_eq!(Staking::slash_count(&20), 1);
@@ -105,20 +104,20 @@ fn note_offline_force_unstake_session_change_should_work() {
Balances::set_free_balance(&10, 70);
Balances::set_free_balance(&20, 70);
assert_ok!(Staking::stake(Origin::signed(1)));
assert_eq!(Staking::slash_count(&10), 0);
assert_eq!(Balances::free_balance(&10), 70);
assert_eq!(Staking::intentions(), vec![10, 20, 1]);
assert_eq!(Session::validators(), vec![10, 20]);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(10, 1);
assert_eq!(Balances::free_balance(&10), 50);
assert_eq!(Staking::slash_count(&10), 1);
assert_eq!(Staking::intentions(), vec![10, 20, 1]);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(10, 1);
assert_eq!(Staking::intentions(), vec![1, 20]);
assert_eq!(Balances::free_balance(&10), 10);
assert!(Staking::forcing_new_era().is_some());
@@ -131,33 +130,33 @@ fn note_offline_auto_unstake_session_change_should_work() {
Balances::set_free_balance(&10, 7000);
Balances::set_free_balance(&20, 7000);
assert_ok!(Staking::register_preferences(Origin::signed(10), 0.into(), ValidatorPrefs { unstake_threshold: 1, validator_payment: 0 }));
assert_eq!(Staking::intentions(), vec![10, 20]);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(1);
Staking::on_offline_validator(10, 1);
Staking::on_offline_validator(20, 1);
assert_eq!(Balances::free_balance(&10), 6980);
assert_eq!(Balances::free_balance(&20), 6980);
assert_eq!(Staking::intentions(), vec![10, 20]);
assert!(Staking::forcing_new_era().is_none());
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(1);
Staking::on_offline_validator(10, 1);
Staking::on_offline_validator(20, 1);
assert_eq!(Balances::free_balance(&10), 6940);
assert_eq!(Balances::free_balance(&20), 6940);
assert_eq!(Staking::intentions(), vec![20]);
assert!(Staking::forcing_new_era().is_some());
System::set_extrinsic_index(1);
Staking::on_offline_validator(1);
Staking::on_offline_validator(20, 1);
assert_eq!(Balances::free_balance(&10), 6940);
assert_eq!(Balances::free_balance(&20), 6860);
assert_eq!(Staking::intentions(), vec![20]);
System::set_extrinsic_index(1);
Staking::on_offline_validator(1);
Staking::on_offline_validator(20, 1);
assert_eq!(Balances::free_balance(&10), 6940);
assert_eq!(Balances::free_balance(&20), 6700);
assert_eq!(Staking::intentions(), vec![0u64; 0]);
@@ -220,8 +219,8 @@ fn slashing_should_work() {
System::set_block_number(7);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(1);
Staking::on_offline_validator(10, 1);
Staking::on_offline_validator(20, 1);
assert_eq!(Balances::total_balance(&10), 1);
});
}
@@ -235,7 +234,7 @@ fn staking_should_work() {
assert_eq!(Staking::era_length(), 2);
assert_eq!(Staking::validator_count(), 2);
assert_eq!(Session::validators(), vec![10, 20]);
assert_ok!(Staking::set_bonding_duration(2.into()));
assert_eq!(Staking::bonding_duration(), 2);
@@ -395,8 +394,8 @@ fn nominating_slashes_should_work() {
System::set_block_number(5);
System::set_extrinsic_index(1);
Staking::on_offline_validator(0);
Staking::on_offline_validator(1);
Staking::on_offline_validator(1, 1);
Staking::on_offline_validator(3, 1);
assert_eq!(Balances::total_balance(&1), 0); //slashed
assert_eq!(Balances::total_balance(&2), 20); //not slashed
assert_eq!(Balances::total_balance(&3), 10); //slashed
+25 -2
View File
@@ -56,12 +56,32 @@ use runtime_primitives::traits::{
use system::ensure_inherent;
use rstd::{result, ops::{Mul, Div}, vec::Vec};
/// A trait which is called when the timestamp is set.
pub trait OnTimestampSet<Moment> {
fn on_timestamp_set(moment: Moment);
}
impl<Moment> OnTimestampSet<Moment> for () {
fn on_timestamp_set(_moment: Moment) { }
}
impl<A, B, Moment: Clone> OnTimestampSet<Moment> for (A, B)
where A: OnTimestampSet<Moment>, B: OnTimestampSet<Moment>
{
fn on_timestamp_set(moment: Moment) {
A::on_timestamp_set(moment.clone());
B::on_timestamp_set(moment);
}
}
pub trait Trait: consensus::Trait + system::Trait {
/// The position of the required timestamp-set extrinsic.
const TIMESTAMP_SET_POSITION: u32;
/// Type used for expressing timestamp.
type Moment: Parameter + Default + SimpleArithmetic + Mul<Self::BlockNumber, Output = Self::Moment> + Div<Self::BlockNumber, Output = Self::Moment>;
/// Something which can be notified when the timestamp is set. Set this to `()` if not needed.
type OnTimestampSet: OnTimestampSet<Self::Moment>;
}
decl_module! {
@@ -88,8 +108,10 @@ decl_module! {
Self::now().is_zero() || now >= Self::now() + Self::block_period(),
"Timestamp must increment by at least <BlockPeriod> between sequential blocks"
);
<Self as Store>::Now::put(now);
<Self as Store>::Now::put(now.clone());
<Self as Store>::DidUpdate::put(true);
<T::OnTimestampSet as OnTimestampSet<_>>::on_timestamp_set(now);
}
fn on_finalise() {
@@ -192,11 +214,12 @@ mod tests {
const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem;
type SessionKey = u64;
type OnOfflineValidator = ();
type InherentOfflineReport = ();
}
impl Trait for Test {
const TIMESTAMP_SET_POSITION: u32 = 0;
type Moment = u64;
type OnTimestampSet = ();
}
type Timestamp = Module<Test>;