use crate::{
BalanceOf, Config, Error, Exposure, NegativeImbalanceOf, NominatorSlashInEra,
OffendingValidators, Pallet, Perbill, SessionInterface, SpanSlash, UnappliedSlash,
ValidatorSlashInEra,
};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
ensure,
traits::{Currency, Defensive, Get, Imbalance, OnUnbalanced},
};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{Saturating, Zero},
DispatchResult, RuntimeDebug,
};
use sp_staking::{offence::DisableStrategy, EraIndex};
use sp_std::vec::Vec;
const REWARD_F1: Perbill = Perbill::from_percent(50);
pub type SpanIndex = u32;
#[derive(Encode, Decode, TypeInfo)]
#[cfg_attr(test, derive(Debug, PartialEq))]
pub(crate) struct SlashingSpan {
pub(crate) index: SpanIndex,
pub(crate) start: EraIndex,
pub(crate) length: Option<EraIndex>, }
impl SlashingSpan {
fn contains_era(&self, era: EraIndex) -> bool {
self.start <= era && self.length.map_or(true, |l| self.start + l > era)
}
}
#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct SlashingSpans {
span_index: SpanIndex,
last_start: EraIndex,
last_nonzero_slash: EraIndex,
prior: Vec<EraIndex>,
}
impl SlashingSpans {
pub(crate) fn new(window_start: EraIndex) -> Self {
SlashingSpans {
span_index: 0,
last_start: window_start,
last_nonzero_slash: 0,
prior: Vec::new(),
}
}
pub(crate) fn end_span(&mut self, now: EraIndex) -> bool {
let next_start = now + 1;
if next_start <= self.last_start {
return false
}
let last_length = next_start - self.last_start;
self.prior.insert(0, last_length);
self.last_start = next_start;
self.span_index += 1;
true
}
pub(crate) fn iter(&'_ self) -> impl Iterator<Item = SlashingSpan> + '_ {
let mut last_start = self.last_start;
let mut index = self.span_index;
let last = SlashingSpan { index, start: last_start, length: None };
let prior = self.prior.iter().cloned().map(move |length| {
let start = last_start - length;
last_start = start;
index -= 1;
SlashingSpan { index, start, length: Some(length) }
});
sp_std::iter::once(last).chain(prior)
}
pub fn last_nonzero_slash(&self) -> EraIndex {
self.last_nonzero_slash
}
fn prune(&mut self, window_start: EraIndex) -> Option<(SpanIndex, SpanIndex)> {
let old_idx = self
.iter()
.skip(1) .position(|span| span.length.map_or(false, |len| span.start + len <= window_start));
let earliest_span_index = self.span_index - self.prior.len() as SpanIndex;
let pruned = match old_idx {
Some(o) => {
self.prior.truncate(o);
let new_earliest = self.span_index - self.prior.len() as SpanIndex;
Some((earliest_span_index, new_earliest))
},
None => None,
};
self.last_start = sp_std::cmp::max(self.last_start, window_start);
pruned
}
}
#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]
pub(crate) struct SpanRecord<Balance> {
slashed: Balance,
paid_out: Balance,
}
impl<Balance> SpanRecord<Balance> {
#[cfg(test)]
pub(crate) fn amount(&self) -> &Balance {
&self.slashed
}
}
#[derive(Clone)]
pub(crate) struct SlashParams<'a, T: 'a + Config> {
pub(crate) stash: &'a T::AccountId,
pub(crate) slash: Perbill,
pub(crate) exposure: &'a Exposure<T::AccountId, BalanceOf<T>>,
pub(crate) slash_era: EraIndex,
pub(crate) window_start: EraIndex,
pub(crate) now: EraIndex,
pub(crate) reward_proportion: Perbill,
pub(crate) disable_strategy: DisableStrategy,
}
pub(crate) fn compute_slash<T: Config>(
params: SlashParams<T>,
) -> Option<UnappliedSlash<T::AccountId, BalanceOf<T>>> {
let mut reward_payout = Zero::zero();
let mut val_slashed = Zero::zero();
let own_slash = params.slash * params.exposure.own;
if params.slash * params.exposure.total == Zero::zero() {
kick_out_if_recent::<T>(params);
return None
}
let prior_slash_p = ValidatorSlashInEra::<T>::get(¶ms.slash_era, params.stash)
.map_or(Zero::zero(), |(prior_slash_proportion, _)| prior_slash_proportion);
if params.slash.deconstruct() > prior_slash_p.deconstruct() {
ValidatorSlashInEra::<T>::insert(
¶ms.slash_era,
params.stash,
&(params.slash, own_slash),
);
} else {
return None
}
{
let mut spans = fetch_spans::<T>(
params.stash,
params.window_start,
&mut reward_payout,
&mut val_slashed,
params.reward_proportion,
);
let target_span = spans.compare_and_update_span_slash(params.slash_era, own_slash);
if target_span == Some(spans.span_index()) {
spans.end_span(params.now);
<Pallet<T>>::chill_stash(params.stash);
}
}
let disable_when_slashed = params.disable_strategy != DisableStrategy::Never;
add_offending_validator::<T>(params.stash, disable_when_slashed);
let mut nominators_slashed = Vec::new();
reward_payout += slash_nominators::<T>(params.clone(), prior_slash_p, &mut nominators_slashed);
Some(UnappliedSlash {
validator: params.stash.clone(),
own: val_slashed,
others: nominators_slashed,
reporters: Vec::new(),
payout: reward_payout,
})
}
fn kick_out_if_recent<T: Config>(params: SlashParams<T>) {
let mut reward_payout = Zero::zero();
let mut val_slashed = Zero::zero();
let mut spans = fetch_spans::<T>(
params.stash,
params.window_start,
&mut reward_payout,
&mut val_slashed,
params.reward_proportion,
);
if spans.era_span(params.slash_era).map(|s| s.index) == Some(spans.span_index()) {
spans.end_span(params.now);
<Pallet<T>>::chill_stash(params.stash);
}
let disable_without_slash = params.disable_strategy == DisableStrategy::Always;
add_offending_validator::<T>(params.stash, disable_without_slash);
}
fn add_offending_validator<T: Config>(stash: &T::AccountId, disable: bool) {
OffendingValidators::<T>::mutate(|offending| {
let validators = T::SessionInterface::validators();
let validator_index = match validators.iter().position(|i| i == stash) {
Some(index) => index,
None => return,
};
let validator_index_u32 = validator_index as u32;
match offending.binary_search_by_key(&validator_index_u32, |(index, _)| *index) {
Err(index) => {
offending.insert(index, (validator_index_u32, disable));
let offending_threshold =
T::OffendingValidatorsThreshold::get() * validators.len() as u32;
if offending.len() >= offending_threshold as usize {
<Pallet<T>>::ensure_new_era()
}
if disable {
T::SessionInterface::disable_validator(validator_index_u32);
}
},
Ok(index) => {
if disable && !offending[index].1 {
offending[index].1 = true;
T::SessionInterface::disable_validator(validator_index_u32);
}
},
}
});
}
fn slash_nominators<T: Config>(
params: SlashParams<T>,
prior_slash_p: Perbill,
nominators_slashed: &mut Vec<(T::AccountId, BalanceOf<T>)>,
) -> BalanceOf<T> {
let mut reward_payout = Zero::zero();
nominators_slashed.reserve(params.exposure.others.len());
for nominator in ¶ms.exposure.others {
let stash = &nominator.who;
let mut nom_slashed = Zero::zero();
let era_slash = {
let own_slash_prior = prior_slash_p * nominator.value;
let own_slash_by_validator = params.slash * nominator.value;
let own_slash_difference = own_slash_by_validator.saturating_sub(own_slash_prior);
let mut era_slash =
NominatorSlashInEra::<T>::get(¶ms.slash_era, stash).unwrap_or_else(Zero::zero);
era_slash += own_slash_difference;
NominatorSlashInEra::<T>::insert(¶ms.slash_era, stash, &era_slash);
era_slash
};
{
let mut spans = fetch_spans::<T>(
stash,
params.window_start,
&mut reward_payout,
&mut nom_slashed,
params.reward_proportion,
);
let target_span = spans.compare_and_update_span_slash(params.slash_era, era_slash);
if target_span == Some(spans.span_index()) {
spans.end_span(params.now);
}
}
nominators_slashed.push((stash.clone(), nom_slashed));
}
reward_payout
}
struct InspectingSpans<'a, T: Config + 'a> {
dirty: bool,
window_start: EraIndex,
stash: &'a T::AccountId,
spans: SlashingSpans,
paid_out: &'a mut BalanceOf<T>,
slash_of: &'a mut BalanceOf<T>,
reward_proportion: Perbill,
_marker: sp_std::marker::PhantomData<T>,
}
fn fetch_spans<'a, T: Config + 'a>(
stash: &'a T::AccountId,
window_start: EraIndex,
paid_out: &'a mut BalanceOf<T>,
slash_of: &'a mut BalanceOf<T>,
reward_proportion: Perbill,
) -> InspectingSpans<'a, T> {
let spans = crate::SlashingSpans::<T>::get(stash).unwrap_or_else(|| {
let spans = SlashingSpans::new(window_start);
crate::SlashingSpans::<T>::insert(stash, &spans);
spans
});
InspectingSpans {
dirty: false,
window_start,
stash,
spans,
slash_of,
paid_out,
reward_proportion,
_marker: sp_std::marker::PhantomData,
}
}
impl<'a, T: 'a + Config> InspectingSpans<'a, T> {
fn span_index(&self) -> SpanIndex {
self.spans.span_index
}
fn end_span(&mut self, now: EraIndex) {
self.dirty = self.spans.end_span(now) || self.dirty;
}
fn add_slash(&mut self, amount: BalanceOf<T>, slash_era: EraIndex) {
*self.slash_of += amount;
self.spans.last_nonzero_slash = sp_std::cmp::max(self.spans.last_nonzero_slash, slash_era);
}
fn era_span(&self, era: EraIndex) -> Option<SlashingSpan> {
self.spans.iter().find(|span| span.contains_era(era))
}
fn compare_and_update_span_slash(
&mut self,
slash_era: EraIndex,
slash: BalanceOf<T>,
) -> Option<SpanIndex> {
let target_span = self.era_span(slash_era)?;
let span_slash_key = (self.stash.clone(), target_span.index);
let mut span_record = SpanSlash::<T>::get(&span_slash_key);
let mut changed = false;
let reward = if span_record.slashed < slash {
let difference = slash - span_record.slashed;
span_record.slashed = slash;
let reward =
REWARD_F1 * (self.reward_proportion * slash).saturating_sub(span_record.paid_out);
self.add_slash(difference, slash_era);
changed = true;
reward
} else if span_record.slashed == slash {
REWARD_F1 * (self.reward_proportion * slash).saturating_sub(span_record.paid_out)
} else {
Zero::zero()
};
if !reward.is_zero() {
changed = true;
span_record.paid_out += reward;
*self.paid_out += reward;
}
if changed {
self.dirty = true;
SpanSlash::<T>::insert(&span_slash_key, &span_record);
}
Some(target_span.index)
}
}
impl<'a, T: 'a + Config> Drop for InspectingSpans<'a, T> {
fn drop(&mut self) {
if !self.dirty {
return
}
if let Some((start, end)) = self.spans.prune(self.window_start) {
for span_index in start..end {
SpanSlash::<T>::remove(&(self.stash.clone(), span_index));
}
}
crate::SlashingSpans::<T>::insert(self.stash, &self.spans);
}
}
pub(crate) fn clear_era_metadata<T: Config>(obsolete_era: EraIndex) {
#[allow(deprecated)]
ValidatorSlashInEra::<T>::remove_prefix(&obsolete_era, None);
#[allow(deprecated)]
NominatorSlashInEra::<T>::remove_prefix(&obsolete_era, None);
}
pub(crate) fn clear_stash_metadata<T: Config>(
stash: &T::AccountId,
num_slashing_spans: u32,
) -> DispatchResult {
let spans = match crate::SlashingSpans::<T>::get(stash) {
None => return Ok(()),
Some(s) => s,
};
ensure!(
num_slashing_spans as usize >= spans.iter().count(),
Error::<T>::IncorrectSlashingSpans
);
crate::SlashingSpans::<T>::remove(stash);
for span in spans.iter() {
SpanSlash::<T>::remove(&(stash.clone(), span.index));
}
Ok(())
}
pub fn do_slash<T: Config>(
stash: &T::AccountId,
value: BalanceOf<T>,
reward_payout: &mut BalanceOf<T>,
slashed_imbalance: &mut NegativeImbalanceOf<T>,
slash_era: EraIndex,
) {
let controller = match <Pallet<T>>::bonded(stash).defensive() {
None => return,
Some(c) => c,
};
let mut ledger = match <Pallet<T>>::ledger(&controller) {
Some(ledger) => ledger,
None => return, };
let value = ledger.slash(value, T::Currency::minimum_balance(), slash_era);
if !value.is_zero() {
let (imbalance, missing) = T::Currency::slash(stash, value);
slashed_imbalance.subsume(imbalance);
if !missing.is_zero() {
*reward_payout = reward_payout.saturating_sub(missing);
}
<Pallet<T>>::update_ledger(&controller, &ledger);
<Pallet<T>>::deposit_event(super::Event::<T>::Slashed {
staker: stash.clone(),
amount: value,
});
}
}
pub(crate) fn apply_slash<T: Config>(
unapplied_slash: UnappliedSlash<T::AccountId, BalanceOf<T>>,
slash_era: EraIndex,
) {
let mut slashed_imbalance = NegativeImbalanceOf::<T>::zero();
let mut reward_payout = unapplied_slash.payout;
do_slash::<T>(
&unapplied_slash.validator,
unapplied_slash.own,
&mut reward_payout,
&mut slashed_imbalance,
slash_era,
);
for &(ref nominator, nominator_slash) in &unapplied_slash.others {
do_slash::<T>(
nominator,
nominator_slash,
&mut reward_payout,
&mut slashed_imbalance,
slash_era,
);
}
pay_reporters::<T>(reward_payout, slashed_imbalance, &unapplied_slash.reporters);
}
fn pay_reporters<T: Config>(
reward_payout: BalanceOf<T>,
slashed_imbalance: NegativeImbalanceOf<T>,
reporters: &[T::AccountId],
) {
if reward_payout.is_zero() || reporters.is_empty() {
T::Slash::on_unbalanced(slashed_imbalance);
return
}
let reward_payout = reward_payout.min(slashed_imbalance.peek());
let (mut reward_payout, mut value_slashed) = slashed_imbalance.split(reward_payout);
let per_reporter = reward_payout.peek() / (reporters.len() as u32).into();
for reporter in reporters {
let (reporter_reward, rest) = reward_payout.split(per_reporter);
reward_payout = rest;
T::Currency::resolve_creating(reporter, reporter_reward);
}
value_slashed.subsume(reward_payout); T::Slash::on_unbalanced(value_slashed);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn span_contains_era() {
let span = SlashingSpan { index: 0, start: 1000, length: None };
assert!(!span.contains_era(0));
assert!(!span.contains_era(999));
assert!(span.contains_era(1000));
assert!(span.contains_era(1001));
assert!(span.contains_era(10000));
let span = SlashingSpan { index: 0, start: 1000, length: Some(10) };
assert!(!span.contains_era(0));
assert!(!span.contains_era(999));
assert!(span.contains_era(1000));
assert!(span.contains_era(1001));
assert!(span.contains_era(1009));
assert!(!span.contains_era(1010));
assert!(!span.contains_era(1011));
}
#[test]
fn single_slashing_span() {
let spans = SlashingSpans {
span_index: 0,
last_start: 1000,
last_nonzero_slash: 0,
prior: Vec::new(),
};
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![SlashingSpan { index: 0, start: 1000, length: None }],
);
}
#[test]
fn many_prior_spans() {
let spans = SlashingSpans {
span_index: 10,
last_start: 1000,
last_nonzero_slash: 0,
prior: vec![10, 9, 8, 10],
};
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 10, start: 1000, length: None },
SlashingSpan { index: 9, start: 990, length: Some(10) },
SlashingSpan { index: 8, start: 981, length: Some(9) },
SlashingSpan { index: 7, start: 973, length: Some(8) },
SlashingSpan { index: 6, start: 963, length: Some(10) },
],
)
}
#[test]
fn pruning_spans() {
let mut spans = SlashingSpans {
span_index: 10,
last_start: 1000,
last_nonzero_slash: 0,
prior: vec![10, 9, 8, 10],
};
assert_eq!(spans.prune(981), Some((6, 8)));
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 10, start: 1000, length: None },
SlashingSpan { index: 9, start: 990, length: Some(10) },
SlashingSpan { index: 8, start: 981, length: Some(9) },
],
);
assert_eq!(spans.prune(982), None);
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 10, start: 1000, length: None },
SlashingSpan { index: 9, start: 990, length: Some(10) },
SlashingSpan { index: 8, start: 981, length: Some(9) },
],
);
assert_eq!(spans.prune(989), None);
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 10, start: 1000, length: None },
SlashingSpan { index: 9, start: 990, length: Some(10) },
SlashingSpan { index: 8, start: 981, length: Some(9) },
],
);
assert_eq!(spans.prune(1000), Some((8, 10)));
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![SlashingSpan { index: 10, start: 1000, length: None },],
);
assert_eq!(spans.prune(2000), None);
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![SlashingSpan { index: 10, start: 2000, length: None },],
);
let mut spans = SlashingSpans {
span_index: 10,
last_start: 1000,
last_nonzero_slash: 0,
prior: vec![10, 9, 8, 10],
};
assert_eq!(spans.prune(2000), Some((6, 10)));
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![SlashingSpan { index: 10, start: 2000, length: None },],
);
}
#[test]
fn ending_span() {
let mut spans = SlashingSpans {
span_index: 1,
last_start: 10,
last_nonzero_slash: 0,
prior: Vec::new(),
};
assert!(spans.end_span(10));
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 2, start: 11, length: None },
SlashingSpan { index: 1, start: 10, length: Some(1) },
],
);
assert!(spans.end_span(15));
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 3, start: 16, length: None },
SlashingSpan { index: 2, start: 11, length: Some(5) },
SlashingSpan { index: 1, start: 10, length: Some(1) },
],
);
assert!(!spans.end_span(15));
assert_eq!(
spans.iter().collect::<Vec<_>>(),
vec![
SlashingSpan { index: 3, start: 16, length: None },
SlashingSpan { index: 2, start: 11, length: Some(5) },
SlashingSpan { index: 1, start: 10, length: Some(1) },
],
);
}
}