Skip to content
lib.rs 34.7 KiB
Newer Older
// 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 <http://www.gnu.org/licenses/>.

//! 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 of 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)]

use crate::weights::WeightInfo;

use bp_header_chain::justification::GrandpaJustification;
use bp_runtime::{BlockNumberOf, Chain, HashOf, HasherOf, HeaderOf};
use codec::{Decode, Encode};
use finality_grandpa::voter_set::VoterSet;
use frame_support::ensure;
use frame_system::{ensure_signed, RawOrigin};
use num_traits::cast::AsPrimitive;
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_finality_grandpa::{ConsensusLog, GRANDPA_ENGINE_ID};
use sp_runtime::traits::{BadOrigin, Header as HeaderT, Zero};
use sp_runtime::RuntimeDebug;

#[cfg(test)]
mod mock;

/// 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 pallet::*;

/// Block number of the bridged chain.
pub type BridgedBlockNumber<T, I> = BlockNumberOf<<T as Config<I>>::BridgedChain>;
/// Block hash of the bridged chain.
pub type BridgedBlockHash<T, I> = HashOf<<T as Config<I>>::BridgedChain>;
/// Hasher of the bridged chain.
pub type BridgedBlockHasher<T, I> = HasherOf<<T as Config<I>>::BridgedChain>;
/// Header of the bridged chain.
pub type BridgedHeader<T, I> = HeaderOf<<T as Config<I>>::BridgedChain>;
#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::pallet_prelude::*;
	use frame_system::pallet_prelude::*;

	#[pallet::config]
	pub trait Config<I: 'static = ()>: frame_system::Config {
		/// The chain we are bridging to here.
		type BridgedChain: Chain;

		/// 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<u32>;

		/// The maximum length of a session on the bridged chain.
		///
		/// The pallet uses this to bound justification verification since justifications contain
		/// ancestry proofs whose size is capped at `MaxBridgedSessionLength`.
		#[pallet::constant]
		type MaxBridgedSessionLength: Get<BridgedBlockNumber<Self, I>>;

		/// The number of validators on the bridged chain.
		///
		/// The pallet uses this to bound justification verification since justifications may
		/// contain up to `MaxBridgedValidatorCount` number of signed `pre-commit` messages which
		/// need to be verified.
		///
		/// Note that `MaxBridgedValidatorCount` should *not* match the exact number of validators
		/// on the bridged chain. Instead it should be a number which is greater than the actual
		/// number of validators in order to provide some buffer room should the validator set
		/// increase in size. If this number ends up being lower than the actual number of
		/// validators on the bridged chain you risk stalling the bridge.
		#[pallet::constant]
		type MaxBridgedValidatorCount: Get<u32>;

		/// Weights gathered through benchmarking.
		type WeightInfo: WeightInfo;
	pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
	impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
		fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight {
			<RequestCount<T, I>>::mutate(|count| *count = count.saturating_sub(1));

			(0_u64)
				.saturating_add(T::DbWeight::get().reads(1))
				.saturating_add(T::DbWeight::get().writes(1))
		}
	}
	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// 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::weight(T::WeightInfo::submit_finality_proof(
			T::MaxBridgedSessionLength::get().as_() as u32,
			T::MaxBridgedValidatorCount::get(),
		))]
		pub fn submit_finality_proof(
			finality_target: BridgedHeader<T, I>,
			justification: GrandpaJustification<BridgedHeader<T, I>>,
		) -> DispatchResultWithPostInfo {
			ensure_operational::<T, I>()?;
			let _ = ensure_signed(origin)?;

			ensure!(
				Self::request_count() < T::MaxRequests::get(),
				<Error<T, I>>::TooManyRequests
			let (hash, number) = (finality_target.hash(), finality_target.number());
			log::trace!(target: "runtime::bridge-grandpa", "Going to try and finalize header {:?}", finality_target);
			let best_finalized = <ImportedHeaders<T, I>>::get(<BestFinalized<T, I>>::get()).expect(
				"In order to reach this point the bridge must have been initialized. Afterwards,
				every time `BestFinalized` is updated `ImportedHeaders` is also updated. Therefore
				`ImportedHeaders` must contain an entry for `BestFinalized`.",
			);

			// We do a quick check here to ensure that our header chain is making progress and isn't
			// "travelling back in time" (which could be indicative of something bad, e.g a hard-fork).
			ensure!(best_finalized.number() < number, <Error<T, I>>::OldHeader);
			let authority_set = <CurrentAuthoritySet<T, I>>::get();
			let set_id = authority_set.set_id;
			verify_justification::<T, I>(&justification, hash, *number, authority_set)?;
			let _enacted = try_enact_authority_change::<T, I>(&finality_target, set_id)?;
			<BestFinalized<T, I>>::put(hash);
			<ImportedHeaders<T, I>>::insert(hash, finality_target);
			<RequestCount<T, I>>::mutate(|count| *count += 1);
			log::info!(target: "runtime::bridge-grandpa", "Succesfully imported finalized header with hash {:?}!", hash);
			// Note that the number of precommits is indicitive of the number of GRANDPA forks being
			// voted on.
			let precommits = justification.commit.precommits.len();

			// This represents the average number of votes in a single fork since the weight formula
			// uses that metric instead of the aggregated number of vote ancestries.
			let votes = (justification.votes_ancestries.len() + precommits - 1) / precommits;

			Ok(Some(T::WeightInfo::submit_finality_proof(votes as u32, precommits as u32)).into())
		}

		/// 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 arbirary header. You can also provide the next scheduled set change
		/// if it is already know.
		///
Loading full blame...