1use alloc::{boxed::Box, vec, vec::Vec};
37use frame_support::traits::{Get, KeyOwnerProofSystem};
38use frame_system::pallet_prelude::HeaderFor;
39use log::{error, info};
40
41use sp_consensus_babe::{AuthorityId, EquivocationProof, Slot, KEY_TYPE};
42use sp_runtime::{
43	transaction_validity::{
44		InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
45		TransactionValidityError, ValidTransaction,
46	},
47	DispatchError, KeyTypeId, Perbill,
48};
49use sp_session::{GetSessionNumber, GetValidatorCount};
50use sp_staking::{
51	offence::{Kind, Offence, OffenceReportSystem, ReportOffence},
52	SessionIndex,
53};
54
55use crate::{Call, Config, Error, Pallet, LOG_TARGET};
56
57pub struct EquivocationOffence<Offender> {
61	pub slot: Slot,
63	pub session_index: SessionIndex,
65	pub validator_set_count: u32,
67	pub offender: Offender,
69}
70
71impl<Offender: Clone> Offence<Offender> for EquivocationOffence<Offender> {
72	const ID: Kind = *b"babe:equivocatio";
73	type TimeSlot = Slot;
74
75	fn offenders(&self) -> Vec<Offender> {
76		vec![self.offender.clone()]
77	}
78
79	fn session_index(&self) -> SessionIndex {
80		self.session_index
81	}
82
83	fn validator_set_count(&self) -> u32 {
84		self.validator_set_count
85	}
86
87	fn time_slot(&self) -> Self::TimeSlot {
88		self.slot
89	}
90
91	fn slash_fraction(&self, offenders_count: u32) -> Perbill {
94		Perbill::from_rational(3 * offenders_count, self.validator_set_count).square()
96	}
97}
98
99pub struct EquivocationReportSystem<T, R, P, L>(core::marker::PhantomData<(T, R, P, L)>);
108
109impl<T, R, P, L>
110	OffenceReportSystem<Option<T::AccountId>, (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof)>
111	for EquivocationReportSystem<T, R, P, L>
112where
113	T: Config + pallet_authorship::Config + frame_system::offchain::CreateBare<Call<T>>,
114	R: ReportOffence<
115		T::AccountId,
116		P::IdentificationTuple,
117		EquivocationOffence<P::IdentificationTuple>,
118	>,
119	P: KeyOwnerProofSystem<(KeyTypeId, AuthorityId), Proof = T::KeyOwnerProof>,
120	P::IdentificationTuple: Clone,
121	L: Get<u64>,
122{
123	type Longevity = L;
124
125	fn publish_evidence(
126		evidence: (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof),
127	) -> Result<(), ()> {
128		use frame_system::offchain::SubmitTransaction;
129		let (equivocation_proof, key_owner_proof) = evidence;
130
131		let call = Call::report_equivocation_unsigned {
132			equivocation_proof: Box::new(equivocation_proof),
133			key_owner_proof,
134		};
135		let xt = T::create_bare(call.into());
136		let res = SubmitTransaction::<T, Call<T>>::submit_transaction(xt);
137		match res {
138			Ok(_) => info!(target: LOG_TARGET, "Submitted equivocation report"),
139			Err(e) => error!(target: LOG_TARGET, "Error submitting equivocation report: {:?}", e),
140		}
141		res
142	}
143
144	fn check_evidence(
145		evidence: (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof),
146	) -> Result<(), TransactionValidityError> {
147		let (equivocation_proof, key_owner_proof) = evidence;
148
149		let key = (sp_consensus_babe::KEY_TYPE, equivocation_proof.offender.clone());
151		let offender =
152			P::check_proof(key, key_owner_proof.clone()).ok_or(InvalidTransaction::BadProof)?;
153
154		if R::is_known_offence(&[offender], &equivocation_proof.slot) {
156			Err(InvalidTransaction::Stale.into())
157		} else {
158			Ok(())
159		}
160	}
161
162	fn process_evidence(
163		reporter: Option<T::AccountId>,
164		evidence: (EquivocationProof<HeaderFor<T>>, T::KeyOwnerProof),
165	) -> Result<(), DispatchError> {
166		let (equivocation_proof, key_owner_proof) = evidence;
167		let reporter = reporter.or_else(|| <pallet_authorship::Pallet<T>>::author());
168		let offender = equivocation_proof.offender.clone();
169		let slot = equivocation_proof.slot;
170
171		if !sp_consensus_babe::check_equivocation_proof(equivocation_proof) {
173			return Err(Error::<T>::InvalidEquivocationProof.into())
174		}
175
176		let validator_set_count = key_owner_proof.validator_count();
177		let session_index = key_owner_proof.session();
178
179		let epoch_index =
180			*slot.saturating_sub(crate::GenesisSlot::<T>::get()) / T::EpochDuration::get();
181
182		if Pallet::<T>::session_index_for_epoch(epoch_index) != session_index {
185			return Err(Error::<T>::InvalidKeyOwnershipProof.into())
186		}
187
188		let offender = P::check_proof((KEY_TYPE, offender), key_owner_proof)
190			.ok_or(Error::<T>::InvalidKeyOwnershipProof)?;
191
192		let offence = EquivocationOffence { slot, validator_set_count, offender, session_index };
193
194		R::report_offence(reporter.into_iter().collect(), offence)
195			.map_err(|_| Error::<T>::DuplicateOffenceReport)?;
196
197		Ok(())
198	}
199}
200
201impl<T: Config> Pallet<T> {
206	pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
207		if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
208			match source {
210				TransactionSource::Local | TransactionSource::InBlock => { },
211				_ => {
212					log::warn!(
213						target: LOG_TARGET,
214						"rejecting unsigned report equivocation transaction because it is not local/in-block.",
215					);
216
217					return InvalidTransaction::Call.into()
218				},
219			}
220
221			let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
223			T::EquivocationReportSystem::check_evidence(evidence)?;
224
225			let longevity =
226				<T::EquivocationReportSystem as OffenceReportSystem<_, _>>::Longevity::get();
227
228			ValidTransaction::with_tag_prefix("BabeEquivocation")
229				.priority(TransactionPriority::max_value())
231				.and_provides((equivocation_proof.offender.clone(), *equivocation_proof.slot))
233				.longevity(longevity)
234				.propagate(false)
236				.build()
237		} else {
238			InvalidTransaction::Call.into()
239		}
240	}
241
242	pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
243		if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
244			let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
245			T::EquivocationReportSystem::check_evidence(evidence)
246		} else {
247			Err(InvalidTransaction::Call.into())
248		}
249	}
250}