sp_staking/offence.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Common traits and types that are useful for describing offences for usage in environments
19//! that use staking.
20
21use alloc::vec::Vec;
22use codec::{Decode, Encode, MaxEncodedLen};
23use sp_core::Get;
24use sp_runtime::{transaction_validity::TransactionValidityError, DispatchError, Perbill};
25
26use crate::SessionIndex;
27
28/// The kind of an offence, is a byte string representing some kind identifier
29/// e.g. `b"im-online:offlin"`, `b"babe:equivocatio"`
30pub type Kind = [u8; 16];
31
32/// Number of times the offence of this authority was already reported in the past.
33///
34/// Note that we don't buffer offence reporting, so every time we see a new offence
35/// of the same kind, we will report past authorities again.
36/// This counter keeps track of how many times the authority was already reported in the past,
37/// so that we can slash it accordingly.
38pub type OffenceCount = u32;
39
40/// A trait implemented by an offence report.
41///
42/// This trait assumes that the offence is legitimate and was validated already.
43///
44/// Examples of offences include: a BABE equivocation or a GRANDPA unjustified vote.
45pub trait Offence<Offender> {
46 /// Identifier which is unique for this kind of offence.
47 const ID: Kind;
48
49 /// A type used for grouping offences that happened at the "same time".
50 ///
51 /// Usually this will be a time slot, representing a point in time on an abstract timescale.
52 /// But it can also be a more complex grouping strategy.
53 ///
54 /// See `Offence::slot` for details.
55 type Slot: Clone + codec::Codec + Ord;
56
57 /// The list of all offenders involved in this incident.
58 ///
59 /// The list has no duplicates, so it is rather a set.
60 fn offenders(&self) -> Vec<Offender>;
61
62 /// The session index that is used for querying the validator set for the `slash_fraction`
63 /// function.
64 ///
65 /// This is used for filtering historical sessions.
66 fn session_index(&self) -> SessionIndex;
67
68 /// Return a validator set count at the time when the offence took place.
69 fn validator_set_count(&self) -> u32;
70
71 /// A slot within which this offence happened.
72 ///
73 /// This is used for looking up offences that happened at the "same time".
74 ///
75 /// The slot is abstract and doesn't have to be the same across different implementations
76 /// of this trait. Two offences are considered to happen at the same time iff both
77 /// `session_index` and `slot` are equal.
78 ///
79 /// As an example, for GRANDPA the slot could be a round number and for BABE it could be
80 /// a slot number. Note that for GRANDPA the round number is reset each epoch.
81 fn slot(&self) -> Self::Slot;
82
83 /// A slash fraction of the total exposure that should be slashed for this
84 /// particular offence for the `offenders_count` that happened at a singular `TimeSlot`.
85 ///
86 /// `offenders_count` - the count of unique offending authorities for this `TimeSlot`. It is >0.
87 fn slash_fraction(&self, offenders_count: u32) -> Perbill;
88}
89
90/// Errors that may happen on offence reports.
91#[derive(PartialEq, Debug)]
92pub enum OffenceError {
93 /// The report has already been submitted.
94 DuplicateReport,
95
96 /// Other error has happened.
97 Other(u8),
98}
99
100/// A trait for decoupling offence reporters from the actual handling of offence reports.
101pub trait ReportOffence<Reporter, Offender, O: Offence<Offender>> {
102 /// Report an `offence` and reward given `reporters`.
103 fn report_offence(reporters: Vec<Reporter>, offence: O) -> Result<(), OffenceError>;
104
105 /// Returns true iff all of the given offenders have been previously reported
106 /// at the given slot. This function is useful to prevent the sending of
107 /// duplicate offence reports.
108 fn is_known_offence(offenders: &[Offender], time_slot: &O::Slot) -> bool;
109}
110
111impl<Reporter, Offender, O: Offence<Offender>> ReportOffence<Reporter, Offender, O> for () {
112 fn report_offence(_reporters: Vec<Reporter>, _offence: O) -> Result<(), OffenceError> {
113 Ok(())
114 }
115
116 fn is_known_offence(_offenders: &[Offender], _time_slot: &O::Slot) -> bool {
117 true
118 }
119}
120
121/// A trait to take action on an offence.
122///
123/// Used to decouple the module that handles offences and
124/// the one that should punish for those offences.
125pub trait OnOffenceHandler<Reporter, Offender, Res> {
126 /// A handler for an offence of a particular kind.
127 ///
128 /// Note that this contains a list of all previous offenders
129 /// as well. The implementer should cater for a case, where
130 /// the same authorities were reported for the same offence
131 /// in the past (see `OffenceCount`).
132 ///
133 /// The vector of `slash_fraction` contains `Perbill`s
134 /// the authorities should be slashed and is computed
135 /// according to the `OffenceCount` already. This is of the same length as `offenders.`
136 /// Zero is a valid value for a fraction.
137 ///
138 /// The `session` parameter is the session index of the offence.
139 ///
140 /// The receiver might decide to not accept this offence. In this case, the call site is
141 /// responsible for queuing the report and re-submitting again.
142 fn on_offence(
143 offenders: &[OffenceDetails<Reporter, Offender>],
144 slash_fraction: &[Perbill],
145 session: SessionIndex,
146 ) -> Res;
147}
148
149impl<Reporter, Offender, Res: Default> OnOffenceHandler<Reporter, Offender, Res> for () {
150 fn on_offence(
151 _offenders: &[OffenceDetails<Reporter, Offender>],
152 _slash_fraction: &[Perbill],
153 _session: SessionIndex,
154 ) -> Res {
155 Default::default()
156 }
157}
158
159/// A details about an offending authority for a particular kind of offence.
160#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug, scale_info::TypeInfo)]
161pub struct OffenceDetails<Reporter, Offender> {
162 /// The offending authority id
163 pub offender: Offender,
164 /// A list of reporters of offences of this authority ID. Possibly empty where there are no
165 /// particular reporters.
166 pub reporters: Vec<Reporter>,
167}
168
169/// An abstract system to publish, check and process offence evidences.
170///
171/// Implementation details are left opaque and we don't assume any specific usage
172/// scenario for this trait at this level. The main goal is to group together some
173/// common actions required during a typical offence report flow.
174///
175/// Even though this trait doesn't assume too much, this is a general guideline
176/// for a typical usage scenario:
177///
178/// 1. An offence is detected and an evidence is submitted on-chain via the
179/// [`OffenceReportSystem::publish_evidence`] method. This will construct and submit an extrinsic
180/// transaction containing the offence evidence.
181///
182/// 2. If the extrinsic is unsigned then the transaction receiver may want to perform some
183/// preliminary checks before further processing. This is a good place to call the
184/// [`OffenceReportSystem::check_evidence`] method.
185///
186/// 3. Finally the report extrinsic is executed on-chain. This is where the user calls the
187/// [`OffenceReportSystem::process_evidence`] to consume the offence report and enact any
188/// required action.
189pub trait OffenceReportSystem<Reporter, Evidence> {
190 /// Longevity, in blocks, for the evidence report validity.
191 ///
192 /// For example, when using the staking pallet this should be set equal
193 /// to the bonding duration in blocks, not eras.
194 type Longevity: Get<u64>;
195
196 /// Publish an offence evidence.
197 ///
198 /// Common usage: submit the evidence on-chain via some kind of extrinsic.
199 fn publish_evidence(evidence: Evidence) -> Result<(), ()>;
200
201 /// Check an offence evidence.
202 ///
203 /// Common usage: preliminary validity check before execution
204 /// (e.g. for unsigned extrinsic quick checks).
205 fn check_evidence(evidence: Evidence) -> Result<(), TransactionValidityError>;
206
207 /// Process an offence evidence.
208 ///
209 /// Common usage: enact some form of slashing directly or by forwarding
210 /// the evidence to a lower level specialized subsystem (e.g. a handler
211 /// implementing `ReportOffence` trait).
212 fn process_evidence(reporter: Reporter, evidence: Evidence) -> Result<(), DispatchError>;
213}
214
215/// Dummy offence report system.
216///
217/// Doesn't do anything special and returns `Ok(())` for all the actions.
218impl<Reporter, Evidence> OffenceReportSystem<Reporter, Evidence> for () {
219 type Longevity = ();
220
221 fn publish_evidence(_evidence: Evidence) -> Result<(), ()> {
222 Ok(())
223 }
224
225 fn check_evidence(_evidence: Evidence) -> Result<(), TransactionValidityError> {
226 Ok(())
227 }
228
229 fn process_evidence(_reporter: Reporter, _evidence: Evidence) -> Result<(), DispatchError> {
230 Ok(())
231 }
232}
233
234/// Wrapper type representing the severity of an offence.
235///
236/// As of now the only meaningful value taken into account
237/// when deciding the severity of an offence is the associated
238/// slash amount `Perbill`.
239///
240/// For instance used for the purposes of distinguishing who should be
241/// prioritized for disablement.
242#[derive(
243 Clone,
244 Copy,
245 PartialEq,
246 Eq,
247 Encode,
248 Decode,
249 MaxEncodedLen,
250 core::fmt::Debug,
251 scale_info::TypeInfo,
252)]
253pub struct OffenceSeverity(pub Perbill);
254
255impl OffenceSeverity {
256 /// Returns the maximum severity.
257 pub fn max_severity() -> Self {
258 Self(Perbill::from_percent(100))
259 }
260
261 /// Returns the minimum severity.
262 pub fn min_severity() -> Self {
263 Self(Perbill::from_percent(0))
264 }
265}
266
267impl Default for OffenceSeverity {
268 /// Default is the maximum severity.
269 /// When severity is unclear it is best to assume the worst.
270 fn default() -> Self {
271 Self::max_severity()
272 }
273}
274
275impl PartialOrd for OffenceSeverity {
276 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
277 self.0.partial_cmp(&other.0)
278 }
279}
280
281impl Ord for OffenceSeverity {
282 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
283 self.0.cmp(&other.0)
284 }
285}