#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
extern crate alloc;
use sp_runtime::{
generic::OpaqueDigestItemId,
traits::{Convert, Header, Member},
SaturatedConversion,
};
use alloc::vec::Vec;
use codec::Decode;
use pallet_mmr::{primitives::AncestryProof, LeafDataProvider, NodesUtils, ParentNumberAndHash};
use sp_consensus_beefy::{
known_payloads,
mmr::{BeefyAuthoritySet, BeefyDataProvider, BeefyNextAuthoritySet, MmrLeaf, MmrLeafVersion},
AncestryHelper, AncestryHelperWeightInfo, Commitment, ConsensusLog,
ValidatorSet as BeefyValidatorSet,
};
use frame_support::{crypto::ecdsa::ECDSAExt, pallet_prelude::Weight, traits::Get};
use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor};
pub use pallet::*;
pub use weights::WeightInfo;
mod benchmarking;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod weights;
pub struct DepositBeefyDigest<T>(core::marker::PhantomData<T>);
impl<T> pallet_mmr::primitives::OnNewRoot<sp_consensus_beefy::MmrRootHash> for DepositBeefyDigest<T>
where
T: pallet_mmr::Config<Hashing = sp_consensus_beefy::MmrHashing>,
T: pallet_beefy::Config,
{
fn on_new_root(root: &sp_consensus_beefy::MmrRootHash) {
let digest = sp_runtime::generic::DigestItem::Consensus(
sp_consensus_beefy::BEEFY_ENGINE_ID,
codec::Encode::encode(&sp_consensus_beefy::ConsensusLog::<
<T as pallet_beefy::Config>::BeefyId,
>::MmrRoot(*root)),
);
frame_system::Pallet::<T>::deposit_log(digest);
}
}
pub struct BeefyEcdsaToEthereum;
impl Convert<sp_consensus_beefy::ecdsa_crypto::AuthorityId, Vec<u8>> for BeefyEcdsaToEthereum {
fn convert(beefy_id: sp_consensus_beefy::ecdsa_crypto::AuthorityId) -> Vec<u8> {
sp_core::ecdsa::Public::from(beefy_id)
.to_eth_address()
.map(|v| v.to_vec())
.map_err(|_| {
log::debug!(target: "runtime::beefy", "Failed to convert BEEFY PublicKey to ETH address!");
})
.unwrap_or_default()
}
}
type MerkleRootOf<T> = <<T as pallet_mmr::Config>::Hashing as sp_runtime::traits::Hash>::Output;
#[frame_support::pallet]
pub mod pallet {
#![allow(missing_docs)]
use super::*;
use frame_support::pallet_prelude::*;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config: pallet_mmr::Config + pallet_beefy::Config {
type LeafVersion: Get<MmrLeafVersion>;
type BeefyAuthorityToMerkleLeaf: Convert<<Self as pallet_beefy::Config>::BeefyId, Vec<u8>>;
type LeafExtra: Member + codec::FullCodec;
type BeefyDataProvider: BeefyDataProvider<Self::LeafExtra>;
type WeightInfo: WeightInfo;
}
#[pallet::storage]
pub type BeefyAuthorities<T: Config> =
StorageValue<_, BeefyAuthoritySet<MerkleRootOf<T>>, ValueQuery>;
#[pallet::storage]
pub type BeefyNextAuthorities<T: Config> =
StorageValue<_, BeefyNextAuthoritySet<MerkleRootOf<T>>, ValueQuery>;
}
impl<T: Config> LeafDataProvider for Pallet<T> {
type LeafData = MmrLeaf<
BlockNumberFor<T>,
<T as frame_system::Config>::Hash,
MerkleRootOf<T>,
T::LeafExtra,
>;
fn leaf_data() -> Self::LeafData {
MmrLeaf {
version: T::LeafVersion::get(),
parent_number_and_hash: ParentNumberAndHash::<T>::leaf_data(),
leaf_extra: T::BeefyDataProvider::extra_data(),
beefy_next_authority_set: BeefyNextAuthorities::<T>::get(),
}
}
}
impl<T> sp_consensus_beefy::OnNewValidatorSet<<T as pallet_beefy::Config>::BeefyId> for Pallet<T>
where
T: pallet::Config,
{
fn on_new_validator_set(
current_set: &BeefyValidatorSet<<T as pallet_beefy::Config>::BeefyId>,
next_set: &BeefyValidatorSet<<T as pallet_beefy::Config>::BeefyId>,
) {
let current = Pallet::<T>::compute_authority_set(current_set);
let next = Pallet::<T>::compute_authority_set(next_set);
BeefyAuthorities::<T>::put(¤t);
BeefyNextAuthorities::<T>::put(&next);
}
}
impl<T: Config> AncestryHelper<HeaderFor<T>> for Pallet<T>
where
T: pallet_mmr::Config<Hashing = sp_consensus_beefy::MmrHashing>,
{
type Proof = AncestryProof<MerkleRootOf<T>>;
type ValidationContext = MerkleRootOf<T>;
fn generate_proof(
prev_block_number: BlockNumberFor<T>,
best_known_block_number: Option<BlockNumberFor<T>>,
) -> Option<Self::Proof> {
pallet_mmr::Pallet::<T>::generate_ancestry_proof(prev_block_number, best_known_block_number)
.map_err(|e| {
log::error!(
target: "runtime::beefy",
"Failed to generate ancestry proof for block {:?} at {:?}: {:?}",
prev_block_number,
best_known_block_number,
e
);
e
})
.ok()
}
fn extract_validation_context(header: HeaderFor<T>) -> Option<Self::ValidationContext> {
let expected_hash = frame_system::Pallet::<T>::block_hash(header.number());
if expected_hash != header.hash() {
return None;
}
header.digest().convert_first(|l| {
l.try_to(OpaqueDigestItemId::Consensus(&sp_consensus_beefy::BEEFY_ENGINE_ID))
.and_then(|log: ConsensusLog<<T as pallet_beefy::Config>::BeefyId>| match log {
ConsensusLog::MmrRoot(mmr_root) => Some(mmr_root),
_ => None,
})
})
}
fn is_non_canonical(
commitment: &Commitment<BlockNumberFor<T>>,
proof: Self::Proof,
context: Self::ValidationContext,
) -> bool {
let commitment_leaf_count =
match pallet_mmr::Pallet::<T>::block_num_to_leaf_count(commitment.block_number) {
Ok(commitment_leaf_count) => commitment_leaf_count,
Err(_) => {
return false
},
};
if commitment_leaf_count != proof.prev_leaf_count {
return false;
}
let canonical_mmr_root = context;
let canonical_prev_root =
match pallet_mmr::Pallet::<T>::verify_ancestry_proof(canonical_mmr_root, proof) {
Ok(canonical_prev_root) => canonical_prev_root,
Err(_) => {
return false
},
};
let mut found_commitment_root = false;
let commitment_roots = commitment
.payload
.get_all_decoded::<MerkleRootOf<T>>(&known_payloads::MMR_ROOT_ID);
for maybe_commitment_root in commitment_roots {
match maybe_commitment_root {
Some(commitment_root) => {
found_commitment_root = true;
if canonical_prev_root != commitment_root {
return true;
}
},
None => {
return true;
},
}
}
if !found_commitment_root {
return true;
}
false
}
}
impl<T: Config> AncestryHelperWeightInfo<HeaderFor<T>> for Pallet<T>
where
T: pallet_mmr::Config<Hashing = sp_consensus_beefy::MmrHashing>,
{
fn extract_validation_context() -> Weight {
<T as Config>::WeightInfo::extract_validation_context()
}
fn is_non_canonical(proof: &<Self as AncestryHelper<HeaderFor<T>>>::Proof) -> Weight {
let mmr_utils = NodesUtils::new(proof.leaf_count);
let num_peaks = mmr_utils.number_of_peaks();
<T as Config>::WeightInfo::n_items_proof_is_non_canonical(
proof.items.len().saturating_add(proof.prev_peaks.len()).saturated_into(),
)
.saturating_add(<T as Config>::WeightInfo::read_peak().saturating_mul(num_peaks))
}
}
impl<T: Config> Pallet<T> {
pub fn authority_set_proof() -> BeefyAuthoritySet<MerkleRootOf<T>> {
BeefyAuthorities::<T>::get()
}
pub fn next_authority_set_proof() -> BeefyNextAuthoritySet<MerkleRootOf<T>> {
BeefyNextAuthorities::<T>::get()
}
fn compute_authority_set(
validator_set: &BeefyValidatorSet<<T as pallet_beefy::Config>::BeefyId>,
) -> BeefyAuthoritySet<MerkleRootOf<T>> {
let id = validator_set.id();
let beefy_addresses = validator_set
.validators()
.into_iter()
.cloned()
.map(T::BeefyAuthorityToMerkleLeaf::convert)
.collect::<Vec<_>>();
let default_eth_addr = [0u8; 20];
let len = beefy_addresses.len() as u32;
let uninitialized_addresses = beefy_addresses
.iter()
.filter(|&addr| addr.as_slice().eq(&default_eth_addr))
.count();
if uninitialized_addresses > 0 {
log::error!(
target: "runtime::beefy",
"Failed to convert {} out of {} BEEFY PublicKeys to ETH addresses!",
uninitialized_addresses,
len,
);
}
let keyset_commitment = binary_merkle_tree::merkle_root::<
<T as pallet_mmr::Config>::Hashing,
_,
>(beefy_addresses)
.into();
BeefyAuthoritySet { id, len, keyset_commitment }
}
}
sp_api::decl_runtime_apis! {
pub trait BeefyMmrApi<H>
where
BeefyAuthoritySet<H>: Decode,
{
fn authority_set_proof() -> BeefyAuthoritySet<H>;
fn next_authority_set_proof() -> BeefyNextAuthoritySet<H>;
}
}