Skip to main content

tp_staking/
offence.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2019-2021 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 tetcore_std::vec::Vec;
22
23use codec::{Encode, Decode};
24use tp_runtime::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 an offence.
47	const ID: Kind;
48
49	/// A type that represents a point in time on an abstract timescale.
50	///
51	/// See `Offence::time_slot` for details. The only requirement is that such timescale could be
52	/// represented by a single `u128` value.
53	type TimeSlot: Clone + codec::Codec + Ord;
54
55	/// The list of all offenders involved in this incident.
56	///
57	/// The list has no duplicates, so it is rather a set.
58	fn offenders(&self) -> Vec<Offender>;
59
60	/// The session index that is used for querying the validator set for the `slash_fraction`
61	/// function.
62	///
63	/// This is used for filtering historical sessions.
64	fn session_index(&self) -> SessionIndex;
65
66	/// Return a validator set count at the time when the offence took place.
67	fn validator_set_count(&self) -> u32;
68
69	/// A point in time when this offence happened.
70	///
71	/// This is used for looking up offences that happened at the "same time".
72	///
73	/// The timescale is abstract and doesn't have to be the same across different implementations
74	/// of this trait. The value doesn't represent absolute timescale though since it is interpreted
75	/// along with the `session_index`. Two offences are considered to happen at the same time iff
76	/// both `session_index` and `time_slot` are equal.
77	///
78	/// As an example, for GRANDPA timescale could be a round number and for BABE it could be a slot
79	/// number. Note that for GRANDPA the round number is reset each epoch.
80	fn time_slot(&self) -> Self::TimeSlot;
81
82	/// A slash fraction of the total exposure that should be slashed for this
83	/// particular offence kind for the given parameters that happened at a singular `TimeSlot`.
84	///
85	/// `offenders_count` - the count of unique offending authorities. It is >0.
86	/// `validator_set_count` - the cardinality of the validator set at the time of offence.
87	fn slash_fraction(
88		offenders_count: u32,
89		validator_set_count: u32,
90	) -> Perbill;
91}
92
93/// Errors that may happen on offence reports.
94#[derive(PartialEq, tp_runtime::RuntimeDebug)]
95pub enum OffenceError {
96	/// The report has already been sumbmitted.
97	DuplicateReport,
98
99	/// Other error has happened.
100	Other(u8),
101}
102
103impl tp_runtime::traits::Printable for OffenceError {
104	fn print(&self) {
105		"OffenceError".print();
106		match self {
107			Self::DuplicateReport => "DuplicateReport".print(),
108			Self::Other(e) => {
109				"Other".print();
110				e.print();
111			}
112		}
113	}
114}
115
116/// A trait for decoupling offence reporters from the actual handling of offence reports.
117pub trait ReportOffence<Reporter, Offender, O: Offence<Offender>> {
118	/// Report an `offence` and reward given `reporters`.
119	fn report_offence(reporters: Vec<Reporter>, offence: O) -> Result<(), OffenceError>;
120
121	/// Returns true iff all of the given offenders have been previously reported
122	/// at the given time slot. This function is useful to prevent the sending of
123	/// duplicate offence reports.
124	fn is_known_offence(offenders: &[Offender], time_slot: &O::TimeSlot) -> bool;
125}
126
127impl<Reporter, Offender, O: Offence<Offender>> ReportOffence<Reporter, Offender, O> for () {
128	fn report_offence(_reporters: Vec<Reporter>, _offence: O) -> Result<(), OffenceError> {
129		Ok(())
130	}
131
132	fn is_known_offence(_offenders: &[Offender], _time_slot: &O::TimeSlot) -> bool {
133		true
134	}
135}
136
137/// A trait to take action on an offence.
138///
139/// Used to decouple the module that handles offences and
140/// the one that should punish for those offences.
141pub trait OnOffenceHandler<Reporter, Offender, Res> {
142	/// A handler for an offence of a particular kind.
143	///
144	/// Note that this contains a list of all previous offenders
145	/// as well. The implementer should cater for a case, where
146	/// the same authorities were reported for the same offence
147	/// in the past (see `OffenceCount`).
148	///
149	/// The vector of `slash_fraction` contains `Perbill`s
150	/// the authorities should be slashed and is computed
151	/// according to the `OffenceCount` already. This is of the same length as `offenders.`
152	/// Zero is a valid value for a fraction.
153	///
154	/// The `session` parameter is the session index of the offence.
155	///
156	/// The receiver might decide to not accept this offence. In this case, the call site is
157	/// responsible for queuing the report and re-submitting again.
158	fn on_offence(
159		offenders: &[OffenceDetails<Reporter, Offender>],
160		slash_fraction: &[Perbill],
161		session: SessionIndex,
162	) -> Result<Res, ()>;
163
164	/// Can an offence be reported now or not. This is an method to short-circuit a call into
165	/// `on_offence`. Ideally, a correct implementation should return `false` if `on_offence` will
166	/// return `Err`. Nonetheless, this is up to the implementation and this trait cannot guarantee
167	/// it.
168	fn can_report() -> bool;
169}
170
171impl<Reporter, Offender, Res: Default> OnOffenceHandler<Reporter, Offender, Res> for () {
172	fn on_offence(
173		_offenders: &[OffenceDetails<Reporter, Offender>],
174		_slash_fraction: &[Perbill],
175		_session: SessionIndex,
176	) -> Result<Res, ()> {
177		Ok(Default::default())
178	}
179
180	fn can_report() -> bool { true }
181}
182
183/// A details about an offending authority for a particular kind of offence.
184#[derive(Clone, PartialEq, Eq, Encode, Decode, tp_runtime::RuntimeDebug)]
185pub struct OffenceDetails<Reporter, Offender> {
186	/// The offending authority id
187	pub offender: Offender,
188	/// A list of reporters of offences of this authority ID. Possibly empty where there are no
189	/// particular reporters.
190	pub reporters: Vec<Reporter>,
191}