1#![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
43type OpaqueTimeSlot = Vec<u8>;
45
46type 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	#[pallet::config]
65	pub trait Config: frame_system::Config {
66		#[allow(deprecated)]
68		type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
69		type IdentificationTuple: Parameter;
71		type OnOffenceHandler: OnOffenceHandler<Self::AccountId, Self::IdentificationTuple, Weight>;
73	}
74
75	#[pallet::storage]
77	pub type Reports<T: Config> = StorageMap<
78		_,
79		Twox64Concat,
80		ReportIdOf<T>,
81		OffenceDetails<T::AccountId, T::IdentificationTuple>,
82	>;
83
84	#[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	#[pallet::event]
98	#[pallet::generate_deposit(pub(super) fn deposit_event)]
99	pub enum Event {
100		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		let TriageOutcome { concurrent_offenders } =
119			match Self::triage_offence_report::<O>(reporters, &time_slot, offenders) {
120				Some(triage) => triage,
121				None => return Err(OffenceError::DuplicateReport),
123			};
124
125		let offenders_count = concurrent_offenders.len() as u32;
126
127		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		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	pub fn reports(
157		report_id: ReportIdOf<T>,
158	) -> Option<OffenceDetails<T::AccountId, T::IdentificationTuple>> {
159		Reports::<T>::get(report_id)
160	}
161
162	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	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			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	concurrent_offenders: Vec<OffenceDetails<T::AccountId, T::IdentificationTuple>>,
216}
217
218#[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	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	fn insert(&mut self, report_id: ReportIdOf<T>) {
242		self.concurrent_reports.push(report_id);
244	}
245
246	fn save(self) {
248		<ConcurrentReportsIndex<T>>::insert(
249			&O::ID,
250			&self.opaque_time_slot,
251			&self.concurrent_reports,
252		);
253	}
254}