Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit

Permalink
Ensure relay chain block number strictly increases (#1280)
Browse files Browse the repository at this point in the history
* Ensure relay chain block number strictly increases

This is a safeguard for when async backing is enabled on the relay chain and multiple parachain
blocks per relay chain block are legal. We will need to later change this to support then multiple
parachain blocks per relay chain block.

* Make the check configurable

* Fix compilation

* Update pallets/parachain-system/src/lib.rs

Co-authored-by: André Silva <123550+andresilva@users.noreply.github.com>

* Update pallets/parachain-system/src/lib.rs

Co-authored-by: André Silva <123550+andresilva@users.noreply.github.com>

* Fix test

Co-authored-by: André Silva <123550+andresilva@users.noreply.github.com>
  • Loading branch information
bkchr and andresilva authored Jun 5, 2022
1 parent dba5a11 commit 8befd60
Show file tree
Hide file tree
Showing 13 changed files with 99 additions and 10 deletions.
62 changes: 61 additions & 1 deletion pallets/parachain-system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,51 @@ pub use relay_state_snapshot::{MessagingStateSnapshot, RelayChainStateProof};

pub use pallet::*;

/// Something that can check the associated relay block number.
///
/// Each Parachain block is built in the context of a relay chain block, this trait allows us
/// to validate the given relay chain block number. With async backing it is legal to build
/// multiple Parachain blocks per relay chain parent. With this trait it is possible for the
/// Parachain to ensure that still only one Parachain block is build per relay chain parent.
///
/// By default [`RelayNumberStrictlyIncreases`] and [`AnyRelayNumber`] are provided.
pub trait CheckAssociatedRelayNumber {
/// Check the current relay number versus the previous relay number.
///
/// The implementation should panic when there is something wrong.
fn check_associated_relay_number(
current: RelayChainBlockNumber,
previous: RelayChainBlockNumber,
);
}

/// Provides an implementation of [`CheckAssociatedRelayNumber`].
///
/// It will ensure that the associated relay block number strictly increases between Parachain
/// blocks. This should be used by production Parachains when in doubt.
pub struct RelayNumberStrictlyIncreases;

impl CheckAssociatedRelayNumber for RelayNumberStrictlyIncreases {
fn check_associated_relay_number(
current: RelayChainBlockNumber,
previous: RelayChainBlockNumber,
) {
if current <= previous {
panic!("Relay chain block number needs to strictly increase between Parachain blocks!")
}
}
}

/// Provides an implementation of [`CheckAssociatedRelayNumber`].
///
/// This will accept any relay chain block number combination. This is mainly useful for
/// test parachains.
pub struct AnyRelayNumber;

impl CheckAssociatedRelayNumber for AnyRelayNumber {
fn check_associated_relay_number(_: RelayChainBlockNumber, _: RelayChainBlockNumber) {}
}

#[frame_support::pallet]
pub mod pallet {
use super::*;
Expand Down Expand Up @@ -128,6 +173,9 @@ pub mod pallet {

/// The weight we reserve at the beginning of the block for processing XCMP messages.
type ReservedXcmpWeight: Get<Weight>;

/// Something that can check the associated relay parent block number.
type CheckAssociatedRelayNumber: CheckAssociatedRelayNumber;
}

#[pallet::hooks]
Expand Down Expand Up @@ -232,7 +280,7 @@ pub mod pallet {
}

// Remove the validation from the old block.
<ValidationData<T>>::kill();
ValidationData::<T>::kill();
ProcessedDownwardMessages::<T>::kill();
HrmpWatermark::<T>::kill();
UpwardMessages::<T>::kill();
Expand Down Expand Up @@ -307,6 +355,13 @@ pub mod pallet {

Self::validate_validation_data(&vfp);

// Check that the associated relay chain block number is as expected.
T::CheckAssociatedRelayNumber::check_associated_relay_number(
vfp.relay_parent_number,
LastRelayChainBlockNumber::<T>::get(),
);
LastRelayChainBlockNumber::<T>::put(vfp.relay_parent_number);

let relay_state_proof = RelayChainStateProof::new(
T::SelfParaId::get(),
vfp.relay_parent_storage_root,
Expand Down Expand Up @@ -474,6 +529,11 @@ pub mod pallet {
#[pallet::storage]
pub(super) type DidSetValidationCode<T: Config> = StorageValue<_, bool, ValueQuery>;

/// The relay chain block number associated with the last parachain block.
#[pallet::storage]
pub(super) type LastRelayChainBlockNumber<T: Config> =
StorageValue<_, RelayChainBlockNumber, ValueQuery>;

/// An option which indicates if the relay-chain restricts signalling a validation code upgrade.
/// In other words, if this is `Some` and [`NewValidationCode`] is `Some` then the produced
/// candidate will be invalid.
Expand Down
20 changes: 15 additions & 5 deletions pallets/parachain-system/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ impl Config for Test {
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = SaveIntoThreadLocal;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

pub struct FromThreadLocal;
Expand Down Expand Up @@ -226,8 +227,7 @@ struct BlockTests {
ran: bool,
relay_sproof_builder_hook:
Option<Box<dyn Fn(&BlockTests, RelayChainBlockNumber, &mut RelayStateSproofBuilder)>>,
persisted_validation_data_hook:
Option<Box<dyn Fn(&BlockTests, RelayChainBlockNumber, &mut PersistedValidationData)>>,
persisted_validation_data_hook: Option<Box<dyn Fn(&BlockTests, &mut PersistedValidationData)>>,
inherent_data_hook:
Option<Box<dyn Fn(&BlockTests, RelayChainBlockNumber, &mut ParachainInherentData)>>,
}
Expand Down Expand Up @@ -274,10 +274,9 @@ impl BlockTests {
self
}

#[allow(dead_code)] // might come in handy in future. If now is future and it still hasn't - feel free.
fn with_validation_data<F>(mut self, f: F) -> Self
where
F: 'static + Fn(&BlockTests, RelayChainBlockNumber, &mut PersistedValidationData),
F: 'static + Fn(&BlockTests, &mut PersistedValidationData),
{
self.persisted_validation_data_hook = Some(Box::new(f));
self
Expand Down Expand Up @@ -319,7 +318,7 @@ impl BlockTests {
..Default::default()
};
if let Some(ref hook) = self.persisted_validation_data_hook {
hook(self, *n as RelayChainBlockNumber, &mut vfp);
hook(self, &mut vfp);
}

<ValidationData<Test>>::put(&vfp);
Expand Down Expand Up @@ -964,3 +963,14 @@ fn receive_hrmp_after_pause() {
});
});
}

#[test]
#[should_panic = "Relay chain block number needs to strictly increase between Parachain blocks!"]
fn test() {
BlockTests::new()
.with_validation_data(|_, data| {
data.relay_parent_number = 1;
})
.add(1, || {})
.add(2, || {});
}
4 changes: 2 additions & 2 deletions pallets/parachain-system/src/validate_block/implementation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ where
assert!(parent_head.hash() == *block.header().parent_hash(), "Invalid parent hash",);

// Create the db
let (db, root) = match storage_proof.to_memory_db(Some(parent_head.state_root())) {
Ok((db, root)) => (db, root),
let db = match storage_proof.to_memory_db(Some(parent_head.state_root())) {
Ok((db, _)) => db,
Err(_) => panic!("Compact proof decoding failure."),
};

Expand Down
2 changes: 2 additions & 0 deletions pallets/xcmp-queue/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use super::*;
use crate as xcmp_queue;
use core::marker::PhantomData;
use cumulus_pallet_parachain_system::AnyRelayNumber;
use cumulus_primitives_core::{IsSystem, ParaId};
use frame_support::{parameter_types, traits::OriginTrait};
use frame_system::EnsureRoot;
Expand Down Expand Up @@ -109,6 +110,7 @@ impl cumulus_pallet_parachain_system::Config for Test {
type ReservedDmpWeight = ();
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ();
type CheckAssociatedRelayNumber = AnyRelayNumber;
}

parameter_types! {
Expand Down
4 changes: 3 additions & 1 deletion parachain-template/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
mod weights;
pub mod xcm_config;

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use smallvec::smallvec;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
Expand Down Expand Up @@ -369,11 +370,12 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type Event = Event;
type OnSystemEvent = ();
type SelfParaId = parachain_info::Pallet<Runtime>;
type OutboundXcmpMessageSource = XcmpQueue;
type DmpMessageHandler = DmpQueue;
type ReservedDmpWeight = ReservedDmpWeight;
type OutboundXcmpMessageSource = XcmpQueue;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
2 changes: 2 additions & 0 deletions parachains/runtimes/assets/statemine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod constants;
mod weights;
pub mod xcm_config;

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
Expand Down Expand Up @@ -416,6 +417,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type OutboundXcmpMessageSource = XcmpQueue;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
2 changes: 2 additions & 0 deletions parachains/runtimes/assets/statemint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub mod constants;
mod weights;
pub mod xcm_config;

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
Expand Down Expand Up @@ -446,6 +447,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type OutboundXcmpMessageSource = XcmpQueue;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
4 changes: 3 additions & 1 deletion parachains/runtimes/assets/westmint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub mod constants;
mod weights;
pub mod xcm_config;

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
Expand Down Expand Up @@ -406,11 +407,12 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type Event = Event;
type OnSystemEvent = ();
type SelfParaId = parachain_info::Pallet<Runtime>;
type OutboundXcmpMessageSource = XcmpQueue;
type DmpMessageHandler = DmpQueue;
type ReservedDmpWeight = ReservedDmpWeight;
type OutboundXcmpMessageSource = XcmpQueue;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
2 changes: 2 additions & 0 deletions parachains/runtimes/contracts/contracts-rococo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ mod contracts;
mod weights;
mod xcm_config;

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
use sp_runtime::{
Expand Down Expand Up @@ -252,6 +253,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type OutboundXcmpMessageSource = XcmpQueue;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ConstU64<{ MAXIMUM_BLOCK_WEIGHT / 4 }>;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl pallet_randomness_collective_flip::Config for Runtime {}
Expand Down
2 changes: 2 additions & 0 deletions parachains/runtimes/starters/seedling/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use sp_api::impl_runtime_apis;
use sp_core::OpaqueMetadata;
use sp_runtime::{
Expand Down Expand Up @@ -166,6 +167,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type ReservedDmpWeight = ();
type XcmpMessageHandler = ();
type ReservedXcmpWeight = ();
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
2 changes: 2 additions & 0 deletions parachains/runtimes/starters/shell/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
pub mod xcm_config;

use codec::{Decode, Encode};
use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use frame_support::unsigned::TransactionValidityError;
use scale_info::TypeInfo;
use sp_api::impl_runtime_apis;
Expand Down Expand Up @@ -170,6 +171,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = ();
type ReservedXcmpWeight = ();
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
2 changes: 2 additions & 0 deletions parachains/runtimes/testing/rococo-parachain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));

use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
use sp_api::impl_runtime_apis;
use sp_core::OpaqueMetadata;
use sp_runtime::{
Expand Down Expand Up @@ -265,6 +266,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases;
}

impl parachain_info::Config for Runtime {}
Expand Down
1 change: 1 addition & 0 deletions test/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ impl cumulus_pallet_parachain_system::Config for Runtime {
type ReservedDmpWeight = ();
type XcmpMessageHandler = ();
type ReservedXcmpWeight = ();
type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::AnyRelayNumber;
}

parameter_types! {
Expand Down

0 comments on commit 8befd60

Please sign in to comment.