// Copyright 2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.
// Parity Bridges Common is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Bridges Common is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Bridges Common. If not, see .
//! Substrate GRANDPA Pallet
//!
//! This pallet is an on-chain GRANDPA light client for Substrate based chains.
//!
//! This pallet achieves this by trustlessly verifying GRANDPA finality proofs on-chain. Once
//! verified, finalized headers are stored in the pallet, thereby creating a sparse header chain.
//! This sparse header chain can be used as a source of truth for other higher-level applications.
//!
//! The pallet is responsible for tracking GRANDPA validator set hand-offs. We only import headers
//! with justifications signed by the current validator set we know of. The header is inspected for
//! a `ScheduledChanges` digest item, which is then used to update to next validator set.
//!
//! Since this pallet only tracks finalized headers it does not deal with forks. Forks can only
//! occur if the GRANDPA validator set on the bridged chain is either colluding or there is a severe
//! bug causing resulting in an equivocation. Such events are outside the scope of this pallet.
//! Shall the fork occur on the bridged chain governance intervention will be required to
//! re-initialize the bridge and track the right fork.
#![cfg_attr(not(feature = "std"), no_std)]
// Runtime-generated enums
#![allow(clippy::large_enum_variant)]
pub use storage_types::StoredAuthoritySet;
use bp_header_chain::{
justification::GrandpaJustification, ChainWithGrandpa, HeaderChain, InitializationData,
StoredHeaderData, StoredHeaderDataBuilder,
};
use bp_runtime::{BlockNumberOf, HashOf, HasherOf, HeaderId, HeaderOf, OwnedBridgeModule};
use finality_grandpa::voter_set::VoterSet;
use frame_support::{dispatch::PostDispatchInfo, ensure};
use sp_finality_grandpa::{ConsensusLog, GRANDPA_ENGINE_ID};
use sp_runtime::{
traits::{Header as HeaderT, Zero},
SaturatedConversion,
};
use sp_std::{boxed::Box, convert::TryInto};
mod call_ext;
#[cfg(test)]
mod mock;
mod storage_types;
/// Module, containing weights for this pallet.
pub mod weights;
#[cfg(feature = "runtime-benchmarks")]
pub mod benchmarking;
// Re-export in crate namespace for `construct_runtime!`
pub use call_ext::*;
pub use pallet::*;
pub use weights::WeightInfo;
/// The target that will be used when publishing logs related to this pallet.
pub const LOG_TARGET: &str = "runtime::bridge-grandpa";
/// Bridged chain from the pallet configuration.
pub type BridgedChain = >::BridgedChain;
/// Block number of the bridged chain.
pub type BridgedBlockNumber = BlockNumberOf<>::BridgedChain>;
/// Block hash of the bridged chain.
pub type BridgedBlockHash = HashOf<>::BridgedChain>;
/// Block id of the bridged chain.
pub type BridgedBlockId = HeaderId, BridgedBlockNumber>;
/// Hasher of the bridged chain.
pub type BridgedBlockHasher = HasherOf<>::BridgedChain>;
/// Header of the bridged chain.
pub type BridgedHeader = HeaderOf<>::BridgedChain>;
/// Header data of the bridged chain that is stored at this chain by this pallet.
pub type BridgedStoredHeaderData =
StoredHeaderData, BridgedBlockHash>;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use bp_runtime::BasicOperatingMode;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config {
/// The chain we are bridging to here.
type BridgedChain: ChainWithGrandpa;
/// The upper bound on the number of requests allowed by the pallet.
///
/// A request refers to an action which writes a header to storage.
///
/// Once this bound is reached the pallet will not allow any dispatchables to be called
/// until the request count has decreased.
#[pallet::constant]
type MaxRequests: Get;
/// Maximal number of finalized headers to keep in the storage.
///
/// The setting is there to prevent growing the on-chain state indefinitely. Note
/// the setting does not relate to block numbers - we will simply keep as much items
/// in the storage, so it doesn't guarantee any fixed timeframe for finality headers.
///
/// Incautious change of this constant may lead to orphan entries in the runtime storage.
#[pallet::constant]
type HeadersToKeep: Get;
/// Weights gathered through benchmarking.
type WeightInfo: WeightInfo;
}
#[pallet::pallet]
pub struct Pallet(PhantomData<(T, I)>);
#[pallet::hooks]
impl, I: 'static> Hooks> for Pallet {
fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight {
>::mutate(|count| *count = count.saturating_sub(1));
T::DbWeight::get().reads_writes(1, 1)
}
}
impl, I: 'static> OwnedBridgeModule for Pallet {
const LOG_TARGET: &'static str = LOG_TARGET;
type OwnerStorage = PalletOwner;
type OperatingMode = BasicOperatingMode;
type OperatingModeStorage = PalletOperatingMode;
}
#[pallet::call]
impl, I: 'static> Pallet {
/// Verify a target header is finalized according to the given finality proof.
///
/// It will use the underlying storage pallet to fetch information about the current
/// authorities and best finalized header in order to verify that the header is finalized.
///
/// If successful in verification, it will write the target header to the underlying storage
/// pallet.
#[pallet::call_index(0)]
#[pallet::weight(::submit_finality_proof(
justification.commit.precommits.len().saturated_into(),
justification.votes_ancestries.len().saturated_into(),
))]
pub fn submit_finality_proof(
_origin: OriginFor,
finality_target: Box>,
justification: GrandpaJustification>,
) -> DispatchResultWithPostInfo {
Self::ensure_not_halted().map_err(Error::::BridgeModule)?;
ensure!(Self::request_count() < T::MaxRequests::get(), >::TooManyRequests);
let (hash, number) = (finality_target.hash(), finality_target.number());
log::trace!(
target: LOG_TARGET,
"Going to try and finalize header {:?}",
finality_target
);
SubmitFinalityProofHelper::::check_obsolete(*number)?;
let authority_set = >::get();
let unused_proof_size = authority_set.unused_proof_size();
let set_id = authority_set.set_id;
verify_justification::(&justification, hash, *number, authority_set.into())?;
let is_authorities_change_enacted =
try_enact_authority_change::(&finality_target, set_id)?;
let may_refund_call_fee = is_authorities_change_enacted &&
submit_finality_proof_info_from_args::(&*finality_target, &justification)
.fits_limits();
>::mutate(|count| *count += 1);
insert_header::(*finality_target, hash);
log::info!(
target: LOG_TARGET,
"Successfully imported finalized header with hash {:?}!",
hash
);
// mandatory header is a header that changes authorities set. The pallet can't go
// further without importing this header. So every bridge MUST import mandatory headers.
//
// We don't want to charge extra costs for mandatory operations. So relayer is not
// paying fee for mandatory headers import transactions.
//
// If size/weight of the call is exceeds our estimated limits, the relayer still needs
// to pay for the transaction.
let pays_fee = if may_refund_call_fee { Pays::No } else { Pays::Yes };
// the proof size component of the call weight assumes that there are
// `MaxBridgedAuthorities` in the `CurrentAuthoritySet` (we use `MaxEncodedLen`
// estimation). But if their number is lower, then we may "refund" some `proof_size`,
// making proof smaller and leaving block space to other useful transactions
let pre_dispatch_weight = T::WeightInfo::submit_finality_proof(
justification.commit.precommits.len().saturated_into(),
justification.votes_ancestries.len().saturated_into(),
);
let actual_weight = pre_dispatch_weight
.set_proof_size(pre_dispatch_weight.proof_size().saturating_sub(unused_proof_size));
Ok(PostDispatchInfo { actual_weight: Some(actual_weight), pays_fee })
}
/// Bootstrap the bridge pallet with an initial header and authority set from which to sync.
///
/// The initial configuration provided does not need to be the genesis header of the bridged
/// chain, it can be any arbitrary header. You can also provide the next scheduled set
/// change if it is already know.
///
/// This function is only allowed to be called from a trusted origin and writes to storage
/// with practically no checks in terms of the validity of the data. It is important that
/// you ensure that valid data is being passed in.
#[pallet::call_index(1)]
#[pallet::weight((T::DbWeight::get().reads_writes(2, 5), DispatchClass::Operational))]
pub fn initialize(
origin: OriginFor,
init_data: super::InitializationData>,
) -> DispatchResultWithPostInfo {
Self::ensure_owner_or_root(origin)?;
let init_allowed = !>::exists();
ensure!(init_allowed, >::AlreadyInitialized);
initialize_bridge::(init_data.clone())?;
log::info!(
target: LOG_TARGET,
"Pallet has been initialized with the following parameters: {:?}",
init_data
);
Ok(().into())
}
/// Change `PalletOwner`.
///
/// May only be called either by root, or by `PalletOwner`.
#[pallet::call_index(2)]
#[pallet::weight((T::DbWeight::get().reads_writes(1, 1), DispatchClass::Operational))]
pub fn set_owner(origin: OriginFor, new_owner: Option) -> DispatchResult {
>::set_owner(origin, new_owner)
}
/// Halt or resume all pallet operations.
///
/// May only be called either by root, or by `PalletOwner`.
#[pallet::call_index(3)]
#[pallet::weight((T::DbWeight::get().reads_writes(1, 1), DispatchClass::Operational))]
pub fn set_operating_mode(
origin: OriginFor,
operating_mode: BasicOperatingMode,
) -> DispatchResult {
>::set_operating_mode(origin, operating_mode)
}
}
/// The current number of requests which have written to storage.
///
/// If the `RequestCount` hits `MaxRequests`, no more calls will be allowed to the pallet until
/// the request capacity is increased.
///
/// The `RequestCount` is decreased by one at the beginning of every block. This is to ensure
/// that the pallet can always make progress.
#[pallet::storage]
#[pallet::getter(fn request_count)]
pub(super) type RequestCount, I: 'static = ()> = StorageValue<_, u32, ValueQuery>;
/// Hash of the header used to bootstrap the pallet.
#[pallet::storage]
pub(super) type InitialHash, I: 'static = ()> =
StorageValue<_, BridgedBlockHash, ValueQuery>;
/// Hash of the best finalized header.
#[pallet::storage]
#[pallet::getter(fn best_finalized)]
pub type BestFinalized, I: 'static = ()> =
StorageValue<_, BridgedBlockId, OptionQuery>;
/// A ring buffer of imported hashes. Ordered by the insertion time.
#[pallet::storage]
pub(super) type ImportedHashes, I: 'static = ()> = StorageMap<
Hasher = Identity,
Key = u32,
Value = BridgedBlockHash,
QueryKind = OptionQuery,
OnEmpty = GetDefault,
MaxValues = MaybeHeadersToKeep,
>;
/// Current ring buffer position.
#[pallet::storage]
pub(super) type ImportedHashesPointer, I: 'static = ()> =
StorageValue<_, u32, ValueQuery>;
/// Relevant fields of imported headers.
#[pallet::storage]
pub type ImportedHeaders, I: 'static = ()> = StorageMap<
Hasher = Identity,
Key = BridgedBlockHash,
Value = BridgedStoredHeaderData,
QueryKind = OptionQuery,
OnEmpty = GetDefault,
MaxValues = MaybeHeadersToKeep,
>;
/// The current GRANDPA Authority set.
#[pallet::storage]
pub type CurrentAuthoritySet, I: 'static = ()> =
StorageValue<_, StoredAuthoritySet, ValueQuery>;
/// Optional pallet owner.
///
/// Pallet owner has a right to halt all pallet operations and then resume it. If it is
/// `None`, then there are no direct ways to halt/resume pallet operations, but other
/// runtime methods may still be used to do that (i.e. democracy::referendum to update halt
/// flag directly or call the `halt_operations`).
#[pallet::storage]
pub type PalletOwner, I: 'static = ()> =
StorageValue<_, T::AccountId, OptionQuery>;
/// The current operating mode of the pallet.
///
/// Depending on the mode either all, or no transactions will be allowed.
#[pallet::storage]
pub type PalletOperatingMode, I: 'static = ()> =
StorageValue<_, BasicOperatingMode, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig, I: 'static = ()> {
/// Optional module owner account.
pub owner: Option,
/// Optional module initialization data.
pub init_data: Option>>,
}
#[cfg(feature = "std")]
impl, I: 'static> Default for GenesisConfig {
fn default() -> Self {
Self { owner: None, init_data: None }
}
}
#[pallet::genesis_build]
impl, I: 'static> GenesisBuild for GenesisConfig {
fn build(&self) {
if let Some(ref owner) = self.owner {
>::put(owner);
}
if let Some(init_data) = self.init_data.clone() {
initialize_bridge::(init_data).expect("genesis config is correct; qed");
} else {
// Since the bridge hasn't been initialized we shouldn't allow anyone to perform
// transactions.
>::put(BasicOperatingMode::Halted);
}
}
}
#[pallet::error]
pub enum Error {
/// The given justification is invalid for the given header.
InvalidJustification,
/// The authority set from the underlying header chain is invalid.
InvalidAuthoritySet,
/// There are too many requests for the current window to handle.
TooManyRequests,
/// The header being imported is older than the best finalized header known to the pallet.
OldHeader,
/// The scheduled authority set change found in the header is unsupported by the pallet.
///
/// This is the case for non-standard (e.g forced) authority set changes.
UnsupportedScheduledChange,
/// The pallet is not yet initialized.
NotInitialized,
/// The pallet has already been initialized.
AlreadyInitialized,
/// Too many authorities in the set.
TooManyAuthoritiesInSet,
/// Error generated by the `OwnedBridgeModule` trait.
BridgeModule(bp_runtime::OwnedBridgeModuleError),
}
/// Check the given header for a GRANDPA scheduled authority set change. If a change
/// is found it will be enacted immediately.
///
/// This function does not support forced changes, or scheduled changes with delays
/// since these types of changes are indicative of abnormal behavior from GRANDPA.
///
/// Returned value will indicate if a change was enacted or not.
pub(crate) fn try_enact_authority_change, I: 'static>(
header: &BridgedHeader,
current_set_id: sp_finality_grandpa::SetId,
) -> Result {
let mut change_enacted = false;
// We don't support forced changes - at that point governance intervention is required.
ensure!(
super::find_forced_change(header).is_none(),
>::UnsupportedScheduledChange
);
if let Some(change) = super::find_scheduled_change(header) {
// GRANDPA only includes a `delay` for forced changes, so this isn't valid.
ensure!(change.delay == Zero::zero(), >::UnsupportedScheduledChange);
// TODO [#788]: Stop manually increasing the `set_id` here.
let next_authorities = StoredAuthoritySet:: {
authorities: change
.next_authorities
.try_into()
.map_err(|_| Error::::TooManyAuthoritiesInSet)?,
set_id: current_set_id + 1,
};
// Since our header schedules a change and we know the delay is 0, it must also enact
// the change.
>::put(&next_authorities);
change_enacted = true;
log::info!(
target: LOG_TARGET,
"Transitioned from authority set {} to {}! New authorities are: {:?}",
current_set_id,
current_set_id + 1,
next_authorities,
);
};
Ok(change_enacted)
}
/// Verify a GRANDPA justification (finality proof) for a given header.
///
/// Will use the GRANDPA current authorities known to the pallet.
///
/// If successful it returns the decoded GRANDPA justification so we can refund any weight which
/// was overcharged in the initial call.
pub(crate) fn verify_justification, I: 'static>(
justification: &GrandpaJustification>,
hash: BridgedBlockHash,
number: BridgedBlockNumber,
authority_set: bp_header_chain::AuthoritySet,
) -> Result<(), sp_runtime::DispatchError> {
use bp_header_chain::justification::verify_justification;
let voter_set =
VoterSet::new(authority_set.authorities).ok_or(>::InvalidAuthoritySet)?;
let set_id = authority_set.set_id;
Ok(verify_justification::>(
(hash, number),
set_id,
&voter_set,
justification,
)
.map_err(|e| {
log::error!(
target: LOG_TARGET,
"Received invalid justification for {:?}: {:?}",
hash,
e,
);
>::InvalidJustification
})?)
}
/// Import a previously verified header to the storage.
///
/// Note this function solely takes care of updating the storage and pruning old entries,
/// but does not verify the validity of such import.
pub(crate) fn insert_header, I: 'static>(
header: BridgedHeader,
hash: BridgedBlockHash,
) {
let index = >::get();
let pruning = >::try_get(index);
>::put(HeaderId(*header.number(), hash));
>::insert(hash, header.build());
>::insert(index, hash);
// Update ring buffer pointer and remove old header.
>::put((index + 1) % T::HeadersToKeep::get());
if let Ok(hash) = pruning {
log::debug!(target: LOG_TARGET, "Pruning old header: {:?}.", hash);
>::remove(hash);
}
}
/// Since this writes to storage with no real checks this should only be used in functions that
/// were called by a trusted origin.
pub(crate) fn initialize_bridge, I: 'static>(
init_params: super::InitializationData>,
) -> Result<(), Error> {
let super::InitializationData { header, authority_list, set_id, operating_mode } =
init_params;
let authority_set_length = authority_list.len();
let authority_set = StoredAuthoritySet::::try_new(authority_list, set_id)
.map_err(|e| {
log::error!(
target: LOG_TARGET,
"Failed to initialize bridge. Number of authorities in the set {} is larger than the configured value {}",
authority_set_length,
T::BridgedChain::MAX_AUTHORITIES_COUNT,
);
e
})?;
let initial_hash = header.hash();
>::put(initial_hash);
>::put(0);
insert_header::(*header, initial_hash);
>::put(authority_set);
>::put(operating_mode);
Ok(())
}
/// Adapter for using `Config::HeadersToKeep` as `MaxValues` bound in our storage maps.
pub struct MaybeHeadersToKeep(PhantomData<(T, I)>);
// this implementation is required to use the struct as `MaxValues`
impl, I: 'static> Get