referrerpolicy=no-referrer-when-downgrade

pallet_offences/
lib.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//! # Offences Pallet
19//!
20//! Tracks reported offences
21
22// Ensure we're `no_std` when compiling for Wasm.
23#![cfg_attr(not(feature = "std"), no_std)]
24
25pub mod migration;
26mod mock;
27mod tests;
28
29extern crate alloc;
30
31use alloc::vec::Vec;
32use codec::Encode;
33use core::marker::PhantomData;
34use frame_support::weights::Weight;
35use sp_runtime::{traits::Hash, Perbill};
36use sp_staking::{
37	offence::{Kind, Offence, OffenceDetails, OffenceError, OnOffenceHandler, ReportOffence},
38	SessionIndex,
39};
40
41pub use pallet::*;
42
43/// A binary blob which represents a SCALE codec-encoded `O::TimeSlot`.
44type OpaqueTimeSlot = Vec<u8>;
45
46/// A type alias for a report identifier.
47type ReportIdOf<T> = <T as frame_system::Config>::Hash;
48
49const LOG_TARGET: &str = "runtime::offences";
50
51#[frame_support::pallet]
52pub mod pallet {
53	use super::*;
54	use frame_support::pallet_prelude::*;
55
56	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
57
58	#[pallet::pallet]
59	#[pallet::storage_version(STORAGE_VERSION)]
60	#[pallet::without_storage_info]
61	pub struct Pallet<T>(_);
62
63	/// The pallet's config trait.
64	#[pallet::config]
65	pub trait Config: frame_system::Config {
66		/// The overarching event type.
67		#[allow(deprecated)]
68		type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
69		/// Full identification of the validator.
70		type IdentificationTuple: Parameter;
71		/// A handler called for every offence report.
72		type OnOffenceHandler: OnOffenceHandler<Self::AccountId, Self::IdentificationTuple, Weight>;
73	}
74
75	/// The primary structure that holds all offence records keyed by report identifiers.
76	#[pallet::storage]
77	pub type Reports<T: Config> = StorageMap<
78		_,
79		Twox64Concat,
80		ReportIdOf<T>,
81		OffenceDetails<T::AccountId, T::IdentificationTuple>,
82	>;
83
84	/// A vector of reports of the same kind that happened at the same time slot.
85	#[pallet::storage]
86	pub type ConcurrentReportsIndex<T: Config> = StorageDoubleMap<
87		_,
88		Twox64Concat,
89		Kind,
90		Twox64Concat,
91		OpaqueTimeSlot,
92		Vec<ReportIdOf<T>>,
93		ValueQuery,
94	>;
95
96	/// Events type.
97	#[pallet::event]
98	#[pallet::generate_deposit(pub(super) fn deposit_event)]
99	pub enum Event {
100		/// There is an offence reported of the given `kind` happened at the `session_index` and
101		/// (kind-specific) time slot. This event is not deposited for duplicate slashes.
102		/// \[kind, timeslot\].
103		Offence { kind: Kind, timeslot: OpaqueTimeSlot },
104	}
105}
106
107impl<T, O> ReportOffence<T::AccountId, T::IdentificationTuple, O> for Pallet<T>
108where
109	T: Config,
110	O: Offence<T::IdentificationTuple>,
111{
112	fn report_offence(reporters: Vec<T::AccountId>, offence: O) -> Result<(), OffenceError> {
113		let offenders = offence.offenders();
114		let time_slot = offence.time_slot();
115
116		// Go through all offenders in the offence report and find all offenders that were spotted
117		// in unique reports.
118		let TriageOutcome { concurrent_offenders } =
119			match Self::triage_offence_report::<O>(reporters, &time_slot, offenders) {
120				Some(triage) => triage,
121				// The report contained only duplicates, so there is no need to slash again.
122				None => return Err(OffenceError::DuplicateReport),
123			};
124
125		let offenders_count = concurrent_offenders.len() as u32;
126
127		// The amount new offenders are slashed
128		let new_fraction = offence.slash_fraction(offenders_count);
129
130		let slash_perbill: Vec<_> = (0..concurrent_offenders.len()).map(|_| new_fraction).collect();
131
132		T::OnOffenceHandler::on_offence(
133			&concurrent_offenders,
134			&slash_perbill,
135			offence.session_index(),
136		);
137
138		// Deposit the event.
139		Self::deposit_event(Event::Offence { kind: O::ID, timeslot: time_slot.encode() });
140
141		Ok(())
142	}
143
144	fn is_known_offence(offenders: &[T::IdentificationTuple], time_slot: &O::TimeSlot) -> bool {
145		let any_unknown = offenders.iter().any(|offender| {
146			let report_id = Self::report_id::<O>(time_slot, offender);
147			!<Reports<T>>::contains_key(&report_id)
148		});
149
150		!any_unknown
151	}
152}
153
154impl<T: Config> Pallet<T> {
155	/// Get the offence details from reports of given ID.
156	pub fn reports(
157		report_id: ReportIdOf<T>,
158	) -> Option<OffenceDetails<T::AccountId, T::IdentificationTuple>> {
159		Reports::<T>::get(report_id)
160	}
161
162	/// Compute the ID for the given report properties.
163	///
164	/// The report id depends on the offence kind, time slot and the id of offender.
165	fn report_id<O: Offence<T::IdentificationTuple>>(
166		time_slot: &O::TimeSlot,
167		offender: &T::IdentificationTuple,
168	) -> ReportIdOf<T> {
169		(O::ID, time_slot.encode(), offender).using_encoded(T::Hashing::hash)
170	}
171
172	/// Triages the offence report and returns the set of offenders that was involved in unique
173	/// reports along with the list of the concurrent offences.
174	fn triage_offence_report<O: Offence<T::IdentificationTuple>>(
175		reporters: Vec<T::AccountId>,
176		time_slot: &O::TimeSlot,
177		offenders: Vec<T::IdentificationTuple>,
178	) -> Option<TriageOutcome<T>> {
179		let mut storage = ReportIndexStorage::<T, O>::load(time_slot);
180
181		let mut any_new = false;
182		for offender in offenders {
183			let report_id = Self::report_id::<O>(time_slot, &offender);
184
185			if !<Reports<T>>::contains_key(&report_id) {
186				any_new = true;
187				<Reports<T>>::insert(
188					&report_id,
189					OffenceDetails { offender, reporters: reporters.clone() },
190				);
191
192				storage.insert(report_id);
193			}
194		}
195
196		if any_new {
197			// Load report details for the all reports happened at the same time.
198			let concurrent_offenders = storage
199				.concurrent_reports
200				.iter()
201				.filter_map(<Reports<T>>::get)
202				.collect::<Vec<_>>();
203
204			storage.save();
205
206			Some(TriageOutcome { concurrent_offenders })
207		} else {
208			None
209		}
210	}
211}
212
213struct TriageOutcome<T: Config> {
214	/// Other reports for the same report kinds.
215	concurrent_offenders: Vec<OffenceDetails<T::AccountId, T::IdentificationTuple>>,
216}
217
218/// An auxiliary struct for working with storage of indexes localized for a specific offence
219/// kind (specified by the `O` type parameter).
220///
221/// This struct is responsible for aggregating storage writes and the underlying storage should not
222/// accessed directly meanwhile.
223#[must_use = "The changes are not saved without called `save`"]
224struct ReportIndexStorage<T: Config, O: Offence<T::IdentificationTuple>> {
225	opaque_time_slot: OpaqueTimeSlot,
226	concurrent_reports: Vec<ReportIdOf<T>>,
227	_phantom: PhantomData<O>,
228}
229
230impl<T: Config, O: Offence<T::IdentificationTuple>> ReportIndexStorage<T, O> {
231	/// Preload indexes from the storage for the specific `time_slot` and the kind of the offence.
232	fn load(time_slot: &O::TimeSlot) -> Self {
233		let opaque_time_slot = time_slot.encode();
234
235		let concurrent_reports = <ConcurrentReportsIndex<T>>::get(&O::ID, &opaque_time_slot);
236
237		Self { opaque_time_slot, concurrent_reports, _phantom: Default::default() }
238	}
239
240	/// Insert a new report to the index.
241	fn insert(&mut self, report_id: ReportIdOf<T>) {
242		// Update the list of concurrent reports.
243		self.concurrent_reports.push(report_id);
244	}
245
246	/// Dump the indexes to the storage.
247	fn save(self) {
248		<ConcurrentReportsIndex<T>>::insert(
249			&O::ID,
250			&self.opaque_time_slot,
251			&self.concurrent_reports,
252		);
253	}
254}