use sp_std::prelude::*;
use codec::{self as codec, Decode, Encode};
use frame_support::traits::{Get, KeyOwnerProofSystem};
use sp_finality_grandpa::{EquivocationProof, RoundNumber, SetId};
use sp_runtime::{
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
DispatchResult, Perbill,
};
use sp_staking::{
offence::{Kind, Offence, OffenceError, ReportOffence},
SessionIndex,
};
use super::{Call, Config, Pallet, LOG_TARGET};
pub trait HandleEquivocation<T: Config> {
type Offence: GrandpaOffence<T::KeyOwnerIdentification>;
type ReportLongevity: Get<u64>;
fn report_offence(
reporters: Vec<T::AccountId>,
offence: Self::Offence,
) -> Result<(), OffenceError>;
fn is_known_offence(
offenders: &[T::KeyOwnerIdentification],
time_slot: &<Self::Offence as Offence<T::KeyOwnerIdentification>>::TimeSlot,
) -> bool;
fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Hash, T::BlockNumber>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult;
fn block_author() -> Option<T::AccountId>;
}
impl<T: Config> HandleEquivocation<T> for () {
type Offence = GrandpaEquivocationOffence<T::KeyOwnerIdentification>;
type ReportLongevity = ();
fn report_offence(
_reporters: Vec<T::AccountId>,
_offence: GrandpaEquivocationOffence<T::KeyOwnerIdentification>,
) -> Result<(), OffenceError> {
Ok(())
}
fn is_known_offence(
_offenders: &[T::KeyOwnerIdentification],
_time_slot: &GrandpaTimeSlot,
) -> bool {
true
}
fn submit_unsigned_equivocation_report(
_equivocation_proof: EquivocationProof<T::Hash, T::BlockNumber>,
_key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
Ok(())
}
fn block_author() -> Option<T::AccountId> {
None
}
}
pub struct EquivocationHandler<I, R, L, O = GrandpaEquivocationOffence<I>> {
_phantom: sp_std::marker::PhantomData<(I, R, L, O)>,
}
impl<I, R, L, O> Default for EquivocationHandler<I, R, L, O> {
fn default() -> Self {
Self { _phantom: Default::default() }
}
}
impl<T, R, L, O> HandleEquivocation<T> for EquivocationHandler<T::KeyOwnerIdentification, R, L, O>
where
T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes<Call<T>>,
R: ReportOffence<T::AccountId, T::KeyOwnerIdentification, O>,
L: Get<u64>,
O: GrandpaOffence<T::KeyOwnerIdentification>,
{
type Offence = O;
type ReportLongevity = L;
fn report_offence(reporters: Vec<T::AccountId>, offence: O) -> Result<(), OffenceError> {
R::report_offence(reporters, offence)
}
fn is_known_offence(offenders: &[T::KeyOwnerIdentification], time_slot: &O::TimeSlot) -> bool {
R::is_known_offence(offenders, time_slot)
}
fn submit_unsigned_equivocation_report(
equivocation_proof: EquivocationProof<T::Hash, T::BlockNumber>,
key_owner_proof: T::KeyOwnerProof,
) -> DispatchResult {
use frame_system::offchain::SubmitTransaction;
let call = Call::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof),
key_owner_proof,
};
match SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into()) {
Ok(()) => log::info!(target: LOG_TARGET, "Submitted GRANDPA equivocation report.",),
Err(e) =>
log::error!(target: LOG_TARGET, "Error submitting equivocation report: {:?}", e,),
}
Ok(())
}
fn block_author() -> Option<T::AccountId> {
<pallet_authorship::Pallet<T>>::author()
}
}
#[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Encode, Decode)]
pub struct GrandpaTimeSlot {
pub set_id: SetId,
pub round: RoundNumber,
}
impl<T: Config> Pallet<T> {
pub fn validate_unsigned(source: TransactionSource, call: &Call<T>) -> TransactionValidity {
if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
match source {
TransactionSource::Local | TransactionSource::InBlock => { },
_ => {
log::warn!(
target: LOG_TARGET,
"rejecting unsigned report equivocation transaction because it is not local/in-block."
);
return InvalidTransaction::Call.into()
},
}
is_known_offence::<T>(equivocation_proof, key_owner_proof)?;
let longevity =
<T::HandleEquivocation as HandleEquivocation<T>>::ReportLongevity::get();
ValidTransaction::with_tag_prefix("GrandpaEquivocation")
.priority(TransactionPriority::max_value())
.and_provides((
equivocation_proof.offender().clone(),
equivocation_proof.set_id(),
equivocation_proof.round(),
))
.longevity(longevity)
.propagate(false)
.build()
} else {
InvalidTransaction::Call.into()
}
}
pub fn pre_dispatch(call: &Call<T>) -> Result<(), TransactionValidityError> {
if let Call::report_equivocation_unsigned { equivocation_proof, key_owner_proof } = call {
is_known_offence::<T>(equivocation_proof, key_owner_proof)
} else {
Err(InvalidTransaction::Call.into())
}
}
}
fn is_known_offence<T: Config>(
equivocation_proof: &EquivocationProof<T::Hash, T::BlockNumber>,
key_owner_proof: &T::KeyOwnerProof,
) -> Result<(), TransactionValidityError> {
let key = (sp_finality_grandpa::KEY_TYPE, equivocation_proof.offender().clone());
let offender = T::KeyOwnerProofSystem::check_proof(key, key_owner_proof.clone())
.ok_or(InvalidTransaction::BadProof)?;
let time_slot = <T::HandleEquivocation as HandleEquivocation<T>>::Offence::new_time_slot(
equivocation_proof.set_id(),
equivocation_proof.round(),
);
let is_known_offence = T::HandleEquivocation::is_known_offence(&[offender], &time_slot);
if is_known_offence {
Err(InvalidTransaction::Stale.into())
} else {
Ok(())
}
}
#[allow(dead_code)]
pub struct GrandpaEquivocationOffence<FullIdentification> {
pub time_slot: GrandpaTimeSlot,
pub session_index: SessionIndex,
pub validator_set_count: u32,
pub offender: FullIdentification,
}
pub trait GrandpaOffence<FullIdentification>: Offence<FullIdentification> {
fn new(
session_index: SessionIndex,
validator_set_count: u32,
offender: FullIdentification,
set_id: SetId,
round: RoundNumber,
) -> Self;
fn new_time_slot(set_id: SetId, round: RoundNumber) -> Self::TimeSlot;
}
impl<FullIdentification: Clone> GrandpaOffence<FullIdentification>
for GrandpaEquivocationOffence<FullIdentification>
{
fn new(
session_index: SessionIndex,
validator_set_count: u32,
offender: FullIdentification,
set_id: SetId,
round: RoundNumber,
) -> Self {
GrandpaEquivocationOffence {
session_index,
validator_set_count,
offender,
time_slot: GrandpaTimeSlot { set_id, round },
}
}
fn new_time_slot(set_id: SetId, round: RoundNumber) -> Self::TimeSlot {
GrandpaTimeSlot { set_id, round }
}
}
impl<FullIdentification: Clone> Offence<FullIdentification>
for GrandpaEquivocationOffence<FullIdentification>
{
const ID: Kind = *b"grandpa:equivoca";
type TimeSlot = GrandpaTimeSlot;
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.time_slot
}
fn slash_fraction(&self, offenders_count: u32) -> Perbill {
let x = Perbill::from_rational(3 * offenders_count, self.validator_set_count);
x.square()
}
}