use fabric_support::{debug, traits::KeyOwnerProofSystem};
use tp_consensus_babe::{EquivocationProof, Slot};
use tp_runtime::transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
};
use tp_runtime::{DispatchResult, Perbill};
use tp_staking::{
offence::{Kind, Offence, OffenceError, ReportOffence},
SessionIndex,
};
use tetcore_std::prelude::*;
use crate::{Call, Module, Config};
pub trait HandleEquivocation<T: Config> {
fn report_offence(
reporters: Vec<T::AccountId>,
offence: BabeEquivocationOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError>;
fn is_known_offence(offenders: &[T::KeyOwnerIdentification], time_slot: &Slot) -> bool;
fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Header>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult;
fn block_author() -> Option<T::AccountId>;
}
impl<T: Config> HandleEquivocation<T> for () {
fn report_offence(
_reporters: Vec<T::AccountId>,
_offence: BabeEquivocationOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
Ok(())
}
fn is_known_offence(_offenders: &[T::KeyOwnerIdentification], _time_slot: &Slot) -> bool {
true
}
fn submit_unsigned_equivocation_report(
_equivocation_proof: EquivocationProof<T::Header>,
_key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
Ok(())
}
fn block_author() -> Option<T::AccountId> {
None
}
}
pub struct EquivocationHandler<I, R> {
_phantom: tetcore_std::marker::PhantomData<(I, R)>,
}
impl<I, R> Default for EquivocationHandler<I, R> {
fn default() -> Self {
Self {
_phantom: Default::default(),
}
}
}
impl<T, R> HandleEquivocation<T> for EquivocationHandler<T::KeyOwnerIdentification, R>
where
T: Config + noble_authorship::Config + fabric_system::offchain::SendTransactionTypes<Call<T>>,
R: ReportOffence<
T::AccountId,
T::KeyOwnerIdentification,
BabeEquivocationOffence<T::KeyOwnerIdentification>,
>,
{
fn report_offence(
reporters: Vec<T::AccountId>,
offence: BabeEquivocationOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
R::report_offence(reporters, offence)
}
fn is_known_offence(offenders: &[T::KeyOwnerIdentification], time_slot: &Slot) -> bool {
R::is_known_offence(offenders, time_slot)
}
fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Header>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
use fabric_system::offchain::SubmitTransaction;
let call = Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof);
match SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
Ok(()) => debug::info!("Submitted BABE equivocation report."),
Err(e) => debug::error!("Error submitting equivocation report: {:?}", e),
}
Ok(())
}
fn block_author() -> Option<T::AccountId> {
Some(<noble_authorship::Module<T>>::author())
}
}
impl<T: Config> fabric_support::unsigned::ValidateUnsigned for Module<T> {
type Call = Call<T>;
fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
if let Call::report_equivocation_unsigned(equivocation_proof, _) = call {
match source {
TransactionSource::Local | TransactionSource::InBlock => { }
_ => {
debug::warn!(
target: "babe",
"rejecting unsigned report equivocation transaction because it is not local/in-block."
);
return InvalidTransaction::Call.into();
}
}
ValidTransaction::with_tag_prefix("BabeEquivocation")
.priority(TransactionPriority::max_value())
.and_provides((
equivocation_proof.offender.clone(),
*equivocation_proof.slot,
))
.propagate(false)
.build()
} else {
InvalidTransaction::Call.into()
}
}
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
if let Call::report_equivocation_unsigned(equivocation_proof, key_owner_proof) = call {
let key = (
tp_consensus_babe::KEY_TYPE,
equivocation_proof.offender.clone(),
);
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof.clone())
.ok_or(InvalidTransaction::BadProof)?;
let is_known_offence = T::HandleEquivocation::is_known_offence(
&[offender],
&equivocation_proof.slot,
);
if is_known_offence {
Err(InvalidTransaction::Stale.into())
} else {
Ok(())
}
} else {
Err(InvalidTransaction::Call.into())
}
}
}
pub struct BabeEquivocationOffence<FullIdentification> {
pub slot: Slot,
pub session_index: SessionIndex,
pub validator_set_count: u32,
pub offender: FullIdentification,
}
impl<FullIdentification: Clone> Offence<FullIdentification>
for BabeEquivocationOffence<FullIdentification>
{
const ID: Kind = *b"babe:equivocatio";
type TimeSlot = Slot;
fn offenders(&self) -> Vec<FullIdentification> {
vec![self.offender.clone()]
}
fn session_index(&self) -> SessionIndex {
self.session_index
}
fn validator_set_count(&self) -> u32 {
self.validator_set_count
}
fn time_slot(&self) -> Self::TimeSlot {
self.slot
}
fn slash_fraction(offenders_count: u32, validator_set_count: u32) -> Perbill {
let x = Perbill::from_rational_approximation(3 * offenders_count, validator_set_count);
x.square()
}
}