referrerpolicy=no-referrer-when-downgrade

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
100impl sp_runtime::traits::Printable for OffenceError {
101	fn print(&self) {
102		"OffenceError".print();
103		match self {
104			Self::DuplicateReport => "DuplicateReport".print(),
105			Self::Other(e) => {
106				"Other".print();
107				e.print();
108			},
109		}
110	}
111}
112
113/// A trait for decoupling offence reporters from the actual handling of offence reports.
114pub trait ReportOffence<Reporter, Offender, O: Offence<Offender>> {
115	/// Report an `offence` and reward given `reporters`.
116	fn report_offence(reporters: Vec<Reporter>, offence: O) -> Result<(), OffenceError>;
117
118	/// Returns true iff all of the given offenders have been previously reported
119	/// at the given slot. This function is useful to prevent the sending of
120	/// duplicate offence reports.
121	fn is_known_offence(offenders: &[Offender], time_slot: &O::Slot) -> bool;
122}
123
124impl<Reporter, Offender, O: Offence<Offender>> ReportOffence<Reporter, Offender, O> for () {
125	fn report_offence(_reporters: Vec<Reporter>, _offence: O) -> Result<(), OffenceError> {
126		Ok(())
127	}
128
129	fn is_known_offence(_offenders: &[Offender], _time_slot: &O::Slot) -> bool {
130		true
131	}
132}
133
134/// A trait to take action on an offence.
135///
136/// Used to decouple the module that handles offences and
137/// the one that should punish for those offences.
138pub trait OnOffenceHandler<Reporter, Offender, Res> {
139	/// A handler for an offence of a particular kind.
140	///
141	/// Note that this contains a list of all previous offenders
142	/// as well. The implementer should cater for a case, where
143	/// the same authorities were reported for the same offence
144	/// in the past (see `OffenceCount`).
145	///
146	/// The vector of `slash_fraction` contains `Perbill`s
147	/// the authorities should be slashed and is computed
148	/// according to the `OffenceCount` already. This is of the same length as `offenders.`
149	/// Zero is a valid value for a fraction.
150	///
151	/// The `session` parameter is the session index of the offence.
152	///
153	/// The receiver might decide to not accept this offence. In this case, the call site is
154	/// responsible for queuing the report and re-submitting again.
155	fn on_offence(
156		offenders: &[OffenceDetails<Reporter, Offender>],
157		slash_fraction: &[Perbill],
158		session: SessionIndex,
159	) -> Res;
160}
161
162impl<Reporter, Offender, Res: Default> OnOffenceHandler<Reporter, Offender, Res> for () {
163	fn on_offence(
164		_offenders: &[OffenceDetails<Reporter, Offender>],
165		_slash_fraction: &[Perbill],
166		_session: SessionIndex,
167	) -> Res {
168		Default::default()
169	}
170}
171
172/// A details about an offending authority for a particular kind of offence.
173#[derive(Clone, PartialEq, Eq, Encode, Decode, Debug, scale_info::TypeInfo)]
174pub struct OffenceDetails<Reporter, Offender> {
175	/// The offending authority id
176	pub offender: Offender,
177	/// A list of reporters of offences of this authority ID. Possibly empty where there are no
178	/// particular reporters.
179	pub reporters: Vec<Reporter>,
180}
181
182/// An abstract system to publish, check and process offence evidences.
183///
184/// Implementation details are left opaque and we don't assume any specific usage
185/// scenario for this trait at this level. The main goal is to group together some
186/// common actions required during a typical offence report flow.
187///
188/// Even though this trait doesn't assume too much, this is a general guideline
189/// for a typical usage scenario:
190///
191/// 1. An offence is detected and an evidence is submitted on-chain via the
192///    [`OffenceReportSystem::publish_evidence`] method. This will construct and submit an extrinsic
193///    transaction containing the offence evidence.
194///
195/// 2. If the extrinsic is unsigned then the transaction receiver may want to perform some
196///    preliminary checks before further processing. This is a good place to call the
197///    [`OffenceReportSystem::check_evidence`] method.
198///
199/// 3. Finally the report extrinsic is executed on-chain. This is where the user calls the
200///    [`OffenceReportSystem::process_evidence`] to consume the offence report and enact any
201///    required action.
202pub trait OffenceReportSystem<Reporter, Evidence> {
203	/// Longevity, in blocks, for the evidence report validity.
204	///
205	/// For example, when using the staking pallet this should be set equal
206	/// to the bonding duration in blocks, not eras.
207	type Longevity: Get<u64>;
208
209	/// Publish an offence evidence.
210	///
211	/// Common usage: submit the evidence on-chain via some kind of extrinsic.
212	fn publish_evidence(evidence: Evidence) -> Result<(), ()>;
213
214	/// Check an offence evidence.
215	///
216	/// Common usage: preliminary validity check before execution
217	/// (e.g. for unsigned extrinsic quick checks).
218	fn check_evidence(evidence: Evidence) -> Result<(), TransactionValidityError>;
219
220	/// Process an offence evidence.
221	///
222	/// Common usage: enact some form of slashing directly or by forwarding
223	/// the evidence to a lower level specialized subsystem (e.g. a handler
224	/// implementing `ReportOffence` trait).
225	fn process_evidence(reporter: Reporter, evidence: Evidence) -> Result<(), DispatchError>;
226}
227
228/// Dummy offence report system.
229///
230/// Doesn't do anything special and returns `Ok(())` for all the actions.
231impl<Reporter, Evidence> OffenceReportSystem<Reporter, Evidence> for () {
232	type Longevity = ();
233
234	fn publish_evidence(_evidence: Evidence) -> Result<(), ()> {
235		Ok(())
236	}
237
238	fn check_evidence(_evidence: Evidence) -> Result<(), TransactionValidityError> {
239		Ok(())
240	}
241
242	fn process_evidence(_reporter: Reporter, _evidence: Evidence) -> Result<(), DispatchError> {
243		Ok(())
244	}
245}
246
247/// Wrapper type representing the severity of an offence.
248///
249/// As of now the only meaningful value taken into account
250/// when deciding the severity of an offence is the associated
251/// slash amount `Perbill`.
252///
253/// For instance used for the purposes of distinguishing who should be
254/// prioritized for disablement.
255#[derive(
256	Clone,
257	Copy,
258	PartialEq,
259	Eq,
260	Encode,
261	Decode,
262	MaxEncodedLen,
263	core::fmt::Debug,
264	scale_info::TypeInfo,
265)]
266pub struct OffenceSeverity(pub Perbill);
267
268impl OffenceSeverity {
269	/// Returns the maximum severity.
270	pub fn max_severity() -> Self {
271		Self(Perbill::from_percent(100))
272	}
273
274	/// Returns the minimum severity.
275	pub fn min_severity() -> Self {
276		Self(Perbill::from_percent(0))
277	}
278}
279
280impl Default for OffenceSeverity {
281	/// Default is the maximum severity.
282	/// When severity is unclear it is best to assume the worst.
283	fn default() -> Self {
284		Self::max_severity()
285	}
286}
287
288impl PartialOrd for OffenceSeverity {
289	fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
290		self.0.partial_cmp(&other.0)
291	}
292}
293
294impl Ord for OffenceSeverity {
295	fn cmp(&self, other: &Self) -> core::cmp::Ordering {
296		self.0.cmp(&other.0)
297	}
298}