use codec::{self as codec, Decode, Encode};
use frame_support::traits::{Get, KeyOwnerProofSystem};
use frame_system::pallet_prelude::BlockNumberFor;
use log::{error, info};
use sp_consensus_beefy::{EquivocationProof, ValidatorSetId, KEY_TYPE as BEEFY_KEY_TYPE};
use sp_runtime::{
transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
},
DispatchError, KeyTypeId, Perbill, RuntimeAppPublic,
};
use sp_session::{GetSessionNumber, GetValidatorCount};
use sp_staking::{
offence::{Kind, Offence, OffenceReportSystem, ReportOffence},
SessionIndex,
};
use sp_std::prelude::*;
use super::{Call, Config, Error, Pallet, LOG_TARGET};
#[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Encode, Decode)]
pub struct TimeSlot<N: Copy + Clone + PartialOrd + Ord + Eq + PartialEq + Encode + Decode> {
pub set_id: ValidatorSetId,
pub round: N,
}
pub struct EquivocationOffence<Offender, N>
where
N: Copy + Clone + PartialOrd + Ord + Eq + PartialEq + Encode + Decode,
{
pub time_slot: TimeSlot<N>,
pub session_index: SessionIndex,
pub validator_set_count: u32,
pub offender: Offender,
}
impl<Offender: Clone, N> Offence<Offender> for EquivocationOffence<Offender, N>
where
N: Copy + Clone + PartialOrd + Ord + Eq + PartialEq + Encode + Decode,
{
const ID: Kind = *b"beefy:equivocati";
type TimeSlot = TimeSlot<N>;
fn offenders(&self) -> Vec<Offender> {
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 {
Perbill::from_rational(3 * offenders_count, self.validator_set_count).square()
}
}
pub struct EquivocationReportSystem<T, R, P, L>(sp_std::marker::PhantomData<(T, R, P, L)>);
pub type EquivocationEvidenceFor<T> = (
EquivocationProof<
BlockNumberFor<T>,
<T as Config>::BeefyId,
<<T as Config>::BeefyId as RuntimeAppPublic>::Signature,
>,
<T as Config>::KeyOwnerProof,
);
impl<T, R, P, L> OffenceReportSystem<Option<T::AccountId>, EquivocationEvidenceFor<T>>
for EquivocationReportSystem<T, R, P, L>
where
T: Config + pallet_authorship::Config + frame_system::offchain::SendTransactionTypes<Call<T>>,
R: ReportOffence<
T::AccountId,
P::IdentificationTuple,
EquivocationOffence<P::IdentificationTuple, BlockNumberFor<T>>,
>,
P: KeyOwnerProofSystem<(KeyTypeId, T::BeefyId), Proof = T::KeyOwnerProof>,
P::IdentificationTuple: Clone,
L: Get<u64>,
{
type Longevity = L;
fn publish_evidence(evidence: EquivocationEvidenceFor<T>) -> Result<(), ()> {
use frame_system::offchain::SubmitTransaction;
let (equivocation_proof, key_owner_proof) = evidence;
let call = Call::report_equivocation_unsigned {
equivocation_proof: Box::new(equivocation_proof),
key_owner_proof,
};
let res = SubmitTransaction::<T, Call<T>>::submit_unsigned_transaction(call.into());
match res {
Ok(_) => info!(target: LOG_TARGET, "Submitted equivocation report."),
Err(e) => error!(target: LOG_TARGET, "Error submitting equivocation report: {:?}", e),
}
res
}
fn check_evidence(
evidence: EquivocationEvidenceFor<T>,
) -> Result<(), TransactionValidityError> {
let (equivocation_proof, key_owner_proof) = evidence;
let key = (BEEFY_KEY_TYPE, equivocation_proof.offender_id().clone());
let offender = P::check_proof(key, key_owner_proof).ok_or(InvalidTransaction::BadProof)?;
let time_slot = TimeSlot {
set_id: equivocation_proof.set_id(),
round: *equivocation_proof.round_number(),
};
if R::is_known_offence(&[offender], &time_slot) {
Err(InvalidTransaction::Stale.into())
} else {
Ok(())
}
}
fn process_evidence(
reporter: Option<T::AccountId>,
evidence: EquivocationEvidenceFor<T>,
) -> Result<(), DispatchError> {
let (equivocation_proof, key_owner_proof) = evidence;
let reporter = reporter.or_else(|| <pallet_authorship::Pallet<T>>::author());
let offender = equivocation_proof.offender_id().clone();
let set_id = equivocation_proof.set_id();
let round = *equivocation_proof.round_number();
let session_index = key_owner_proof.session();
let validator_set_count = key_owner_proof.validator_count();
let offender = P::check_proof((BEEFY_KEY_TYPE, offender), key_owner_proof)
.ok_or(Error::<T>::InvalidKeyOwnershipProof)?;
if !sp_consensus_beefy::check_equivocation_proof(&equivocation_proof) {
return Err(Error::<T>::InvalidEquivocationProof.into())
}
let set_id_session_index =
crate::SetIdSession::<T>::get(set_id).ok_or(Error::<T>::InvalidEquivocationProof)?;
if session_index != set_id_session_index {
return Err(Error::<T>::InvalidEquivocationProof.into())
}
let offence = EquivocationOffence {
time_slot: TimeSlot { set_id, round },
session_index,
validator_set_count,
offender,
};
R::report_offence(reporter.into_iter().collect(), offence)
.map_err(|_| Error::<T>::DuplicateOffenceReport)?;
Ok(())
}
}
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()
},
}
let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
T::EquivocationReportSystem::check_evidence(evidence)?;
let longevity =
<T::EquivocationReportSystem as OffenceReportSystem<_, _>>::Longevity::get();
ValidTransaction::with_tag_prefix("BeefyEquivocation")
.priority(TransactionPriority::MAX)
.and_provides((
equivocation_proof.offender_id().clone(),
equivocation_proof.set_id(),
*equivocation_proof.round_number(),
))
.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 {
let evidence = (*equivocation_proof.clone(), key_owner_proof.clone());
T::EquivocationReportSystem::check_evidence(evidence)
} else {
Err(InvalidTransaction::Call.into())
}
}
}