Skip to content
[package]
name = "pallet-xcm-bridge-hub-router"
description = "Bridge hub interface for sibling/parent chains with dynamic fees support."
version = "0.5.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
log = { workspace = true }
scale-info = { version = "2.10.0", default-features = false, features = ["bit-vec", "derive", "serde"] }
# Bridge dependencies
bp-xcm-bridge-hub-router = { path = "../../primitives/xcm-bridge-hub-router", default-features = false }
# Substrate Dependencies
frame-benchmarking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false, optional = true }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Polkadot Dependencies
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[dev-dependencies]
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = ["std"]
std = [
"bp-xcm-bridge-hub-router/std",
"codec/std",
"frame-benchmarking/std",
"frame-support/std",
"frame-system/std",
"log/std",
"scale-info/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
"xcm-builder/std",
"xcm/std",
]
runtime-benchmarks = [
"frame-benchmarking/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"sp-runtime/try-runtime",
]
// Copyright (C) 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/>.
//! XCM bridge hub router pallet benchmarks.
#![cfg(feature = "runtime-benchmarks")]
use crate::{Bridge, Call};
use bp_xcm_bridge_hub_router::{BridgeState, MINIMAL_DELIVERY_FEE_FACTOR};
use frame_benchmarking::{benchmarks_instance_pallet, BenchmarkError};
use frame_support::traits::{EnsureOrigin, Get, Hooks, UnfilteredDispatchable};
use sp_runtime::traits::Zero;
use xcm::prelude::*;
/// Pallet we're benchmarking here.
pub struct Pallet<T: Config<I>, I: 'static = ()>(crate::Pallet<T, I>);
/// Trait that must be implemented by runtime to be able to benchmark pallet properly.
pub trait Config<I: 'static>: crate::Config<I> {
/// Fill up queue so it becomes congested.
fn make_congested();
/// Returns destination which is valid for this router instance.
/// (Needs to pass `T::Bridges`)
/// Make sure that `SendXcm` will pass.
fn ensure_bridged_target_destination() -> Result<Location, BenchmarkError> {
Ok(Location::new(
Self::UniversalLocation::get().len() as u8,
[GlobalConsensus(Self::BridgedNetworkId::get().unwrap())],
))
}
}
benchmarks_instance_pallet! {
on_initialize_when_non_congested {
Bridge::<T, I>::put(BridgeState {
is_congested: false,
delivery_fee_factor: MINIMAL_DELIVERY_FEE_FACTOR + MINIMAL_DELIVERY_FEE_FACTOR,
});
}: {
crate::Pallet::<T, I>::on_initialize(Zero::zero())
}
on_initialize_when_congested {
Bridge::<T, I>::put(BridgeState {
is_congested: false,
delivery_fee_factor: MINIMAL_DELIVERY_FEE_FACTOR + MINIMAL_DELIVERY_FEE_FACTOR,
});
let _ = T::ensure_bridged_target_destination()?;
T::make_congested();
}: {
crate::Pallet::<T, I>::on_initialize(Zero::zero())
}
report_bridge_status {
Bridge::<T, I>::put(BridgeState::default());
let origin: T::RuntimeOrigin = T::BridgeHubOrigin::try_successful_origin().expect("expected valid BridgeHubOrigin");
let bridge_id = Default::default();
let is_congested = true;
let call = Call::<T, I>::report_bridge_status { bridge_id, is_congested };
}: { call.dispatch_bypass_filter(origin)? }
verify {
assert!(Bridge::<T, I>::get().is_congested);
}
send_message {
let dest = T::ensure_bridged_target_destination()?;
let xcm = sp_std::vec![].into();
// make local queue congested, because it means additional db write
T::make_congested();
}: {
send_xcm::<crate::Pallet<T, I>>(dest, xcm).expect("message is sent")
}
verify {
assert!(Bridge::<T, I>::get().delivery_fee_factor > MINIMAL_DELIVERY_FEE_FACTOR);
}
}
// Copyright (C) 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/>.
//! Pallet that may be used instead of `SovereignPaidRemoteExporter` in the XCM router
//! configuration. The main thing that the pallet offers is the dynamic message fee,
//! that is computed based on the bridge queues state. It starts exponentially increasing
//! if the queue between this chain and the sibling/child bridge hub is congested.
//!
//! All other bridge hub queues offer some backpressure mechanisms. So if at least one
//! of all queues is congested, it will eventually lead to the growth of the queue at
//! this chain.
//!
//! **A note on terminology**: when we mention the bridge hub here, we mean the chain that
//! has the messages pallet deployed (`pallet-bridge-grandpa`, `pallet-bridge-messages`,
//! `pallet-xcm-bridge-hub`, ...). It may be the system bridge hub parachain or any other
//! chain.
#![cfg_attr(not(feature = "std"), no_std)]
use bp_xcm_bridge_hub_router::{
BridgeState, XcmChannelStatusProvider, MINIMAL_DELIVERY_FEE_FACTOR,
};
use codec::Encode;
use frame_support::traits::Get;
use sp_core::H256;
use sp_runtime::{FixedPointNumber, FixedU128, Saturating};
use xcm::prelude::*;
use xcm_builder::{ExporterFor, SovereignPaidRemoteExporter};
pub use pallet::*;
pub use weights::WeightInfo;
pub mod benchmarking;
pub mod weights;
mod mock;
/// The factor that is used to increase current message fee factor when bridge experiencing
/// some lags.
const EXPONENTIAL_FEE_BASE: FixedU128 = FixedU128::from_rational(105, 100); // 1.05
/// The factor that is used to increase current message fee factor for every sent kilobyte.
const MESSAGE_SIZE_FEE_BASE: FixedU128 = FixedU128::from_rational(1, 1000); // 0.001
/// Maximal size of the XCM message that may be sent over bridge.
///
/// This should be less than the maximal size, allowed by the messages pallet, because
/// the message itself is wrapped in other structs and is double encoded.
pub const HARD_MESSAGE_SIZE_LIMIT: u32 = 32 * 1024;
/// The target that will be used when publishing logs related to this pallet.
///
/// This doesn't match the pattern used by other bridge pallets (`runtime::bridge-*`). But this
/// pallet has significant differences with those pallets. The main one is that is intended to
/// be deployed at sending chains. Other bridge pallets are likely to be deployed at the separate
/// bridge hub parachain.
pub const LOG_TARGET: &str = "xcm::bridge-hub-router";
#[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 {
/// Benchmarks results from runtime we're plugged into.
type WeightInfo: WeightInfo;
/// Universal location of this runtime.
type UniversalLocation: Get<InteriorLocation>;
/// The bridged network that this config is for if specified.
/// Also used for filtering `Bridges` by `BridgedNetworkId`.
/// If not specified, allows all networks pass through.
type BridgedNetworkId: Get<Option<NetworkId>>;
/// Configuration for supported **bridged networks/locations** with **bridge location** and
/// **possible fee**. Allows to externalize better control over allowed **bridged
/// networks/locations**.
type Bridges: ExporterFor;
/// Checks the XCM version for the destination.
type DestinationVersion: GetVersion;
/// Origin of the sibling bridge hub that is allowed to report bridge status.
type BridgeHubOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Actual message sender (`HRMP` or `DMP`) to the sibling bridge hub location.
type ToBridgeHubSender: SendXcm;
/// Underlying channel with the sibling bridge hub. It must match the channel, used
/// by the `Self::ToBridgeHubSender`.
type WithBridgeHubChannel: XcmChannelStatusProvider;
/// Additional fee that is paid for every byte of the outbound message.
type ByteFee: Get<u128>;
/// Asset that is used to paid bridge fee.
type FeeAsset: Get<AssetId>;
}
#[pallet::pallet]
pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
// TODO: make sure that `WithBridgeHubChannel::is_congested` returns true if either
// of XCM channels (outbound/inbound) is suspended. Because if outbound is suspended
// that is definitely congestion. If inbound is suspended, then we are not able to
// receive the "report_bridge_status" signal (that maybe sent by the bridge hub).
// if the channel with sibling/child bridge hub is suspended, we don't change
// anything
if T::WithBridgeHubChannel::is_congested() {
return T::WeightInfo::on_initialize_when_congested()
}
// if bridge has reported congestion, we don't change anything
let mut bridge = Self::bridge();
if bridge.is_congested {
return T::WeightInfo::on_initialize_when_congested()
}
// if fee factor is already minimal, we don't change anything
if bridge.delivery_fee_factor == MINIMAL_DELIVERY_FEE_FACTOR {
return T::WeightInfo::on_initialize_when_congested()
}
let previous_factor = bridge.delivery_fee_factor;
bridge.delivery_fee_factor =
MINIMAL_DELIVERY_FEE_FACTOR.max(bridge.delivery_fee_factor / EXPONENTIAL_FEE_BASE);
log::info!(
target: LOG_TARGET,
"Bridge queue is uncongested. Decreased fee factor from {} to {}",
previous_factor,
bridge.delivery_fee_factor,
);
Bridge::<T, I>::put(bridge);
T::WeightInfo::on_initialize_when_non_congested()
}
}
#[pallet::call]
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Notification about congested bridge queue.
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::report_bridge_status())]
pub fn report_bridge_status(
origin: OriginFor<T>,
// this argument is not currently used, but to ease future migration, we'll keep it
// here
bridge_id: H256,
is_congested: bool,
) -> DispatchResult {
let _ = T::BridgeHubOrigin::ensure_origin(origin)?;
log::info!(
target: LOG_TARGET,
"Received bridge status from {:?}: congested = {}",
bridge_id,
is_congested,
);
Bridge::<T, I>::mutate(|bridge| {
bridge.is_congested = is_congested;
});
Ok(())
}
}
/// Bridge that we are using.
///
/// **bridges-v1** assumptions: all outbound messages through this router are using single lane
/// and to single remote consensus. If there is some other remote consensus that uses the same
/// bridge hub, the separate pallet instance shall be used, In `v2` we'll have all required
/// primitives (lane-id aka bridge-id, derived from XCM locations) to support multiple bridges
/// by the same pallet instance.
#[pallet::storage]
#[pallet::getter(fn bridge)]
pub type Bridge<T: Config<I>, I: 'static = ()> = StorageValue<_, BridgeState, ValueQuery>;
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Called when new message is sent (queued to local outbound XCM queue) over the bridge.
pub(crate) fn on_message_sent_to_bridge(message_size: u32) {
let _ = Bridge::<T, I>::try_mutate(|bridge| {
let is_channel_with_bridge_hub_congested = T::WithBridgeHubChannel::is_congested();
let is_bridge_congested = bridge.is_congested;
// if outbound queue is not congested AND bridge has not reported congestion, do
// nothing
if !is_channel_with_bridge_hub_congested && !is_bridge_congested {
return Err(())
}
// ok - we need to increase the fee factor, let's do that
let message_size_factor = FixedU128::from_u32(message_size.saturating_div(1024))
.saturating_mul(MESSAGE_SIZE_FEE_BASE);
let total_factor = EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor);
let previous_factor = bridge.delivery_fee_factor;
bridge.delivery_fee_factor =
bridge.delivery_fee_factor.saturating_mul(total_factor);
log::info!(
target: LOG_TARGET,
"Bridge channel is congested. Increased fee factor from {} to {}",
previous_factor,
bridge.delivery_fee_factor,
);
Ok(())
});
}
}
}
/// We'll be using `SovereignPaidRemoteExporter` to send remote messages over the sibling/child
/// bridge hub.
type ViaBridgeHubExporter<T, I> = SovereignPaidRemoteExporter<
Pallet<T, I>,
<T as Config<I>>::ToBridgeHubSender,
<T as Config<I>>::UniversalLocation,
>;
// This pallet acts as the `ExporterFor` for the `SovereignPaidRemoteExporter` to compute
// message fee using fee factor.
impl<T: Config<I>, I: 'static> ExporterFor for Pallet<T, I> {
fn exporter_for(
network: &NetworkId,
remote_location: &InteriorLocation,
message: &Xcm<()>,
) -> Option<(Location, Option<Asset>)> {
// ensure that the message is sent to the expected bridged network (if specified).
if let Some(bridged_network) = T::BridgedNetworkId::get() {
if *network != bridged_network {
log::trace!(
target: LOG_TARGET,
"Router with bridged_network_id {:?} does not support bridging to network {:?}!",
bridged_network,
network,
);
return None
}
}
// ensure that the message is sent to the expected bridged network and location.
let Some((bridge_hub_location, maybe_payment)) =
T::Bridges::exporter_for(network, remote_location, message)
else {
log::trace!(
target: LOG_TARGET,
"Router with bridged_network_id {:?} does not support bridging to network {:?} and remote_location {:?}!",
T::BridgedNetworkId::get(),
network,
remote_location,
);
return None
};
// take `base_fee` from `T::Brides`, but it has to be the same `T::FeeAsset`
let base_fee = match maybe_payment {
Some(payment) => match payment {
Asset { fun: Fungible(amount), id } if id.eq(&T::FeeAsset::get()) => amount,
invalid_asset => {
log::error!(
target: LOG_TARGET,
"Router with bridged_network_id {:?} is configured for `T::FeeAsset` {:?} which is not \
compatible with {:?} for bridge_hub_location: {:?} for bridging to {:?}/{:?}!",
T::BridgedNetworkId::get(),
T::FeeAsset::get(),
invalid_asset,
bridge_hub_location,
network,
remote_location,
);
return None
},
},
None => 0,
};
// compute fee amount. Keep in mind that this is only the bridge fee. The fee for sending
// message from this chain to child/sibling bridge hub is determined by the
// `Config::ToBridgeHubSender`
let message_size = message.encoded_size();
let message_fee = (message_size as u128).saturating_mul(T::ByteFee::get());
let fee_sum = base_fee.saturating_add(message_fee);
let fee_factor = Self::bridge().delivery_fee_factor;
let fee = fee_factor.saturating_mul_int(fee_sum);
let fee = if fee > 0 { Some((T::FeeAsset::get(), fee).into()) } else { None };
log::info!(
target: LOG_TARGET,
"Going to send message to {:?} ({} bytes) over bridge. Computed bridge fee {:?} using fee factor {}",
(network, remote_location),
message_size,
fee,
fee_factor
);
Some((bridge_hub_location, fee))
}
}
// This pallet acts as the `SendXcm` to the sibling/child bridge hub instead of regular
// XCMP/DMP transport. This allows injecting dynamic message fees into XCM programs that
// are going to the bridged network.
impl<T: Config<I>, I: 'static> SendXcm for Pallet<T, I> {
type Ticket = (u32, <T::ToBridgeHubSender as SendXcm>::Ticket);
fn validate(
dest: &mut Option<Location>,
xcm: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
// `dest` and `xcm` are required here
let dest_ref = dest.as_ref().ok_or(SendError::MissingArgument)?;
let xcm_ref = xcm.as_ref().ok_or(SendError::MissingArgument)?;
// we won't have an access to `dest` and `xcm` in the `deliver` method, so precompute
// everything required here
let message_size = xcm_ref.encoded_size() as _;
// bridge doesn't support oversized/overweight messages now. So it is better to drop such
// messages here than at the bridge hub. Let's check the message size.
if message_size > HARD_MESSAGE_SIZE_LIMIT {
return Err(SendError::ExceedsMaxMessageSize)
}
// We need to ensure that the known `dest`'s XCM version can comprehend the current `xcm`
// program. This may seem like an additional, unnecessary check, but it is not. A similar
// check is probably performed by the `ViaBridgeHubExporter`, which attempts to send a
// versioned message to the sibling bridge hub. However, the local bridge hub may have a
// higher XCM version than the remote `dest`. Once again, it is better to discard such
// messages here than at the bridge hub (e.g., to avoid losing funds).
let destination_version = T::DestinationVersion::get_version_for(dest_ref)
.ok_or(SendError::DestinationUnsupported)?;
let _ = VersionedXcm::from(xcm_ref.clone())
.into_version(destination_version)
.map_err(|()| SendError::DestinationUnsupported)?;
// just use exporter to validate destination and insert instructions to pay message fee
// at the sibling/child bridge hub
//
// the cost will include both cost of: (1) to-sibling bridge hub delivery (returned by
// the `Config::ToBridgeHubSender`) and (2) to-bridged bridge hub delivery (returned by
// `Self::exporter_for`)
ViaBridgeHubExporter::<T, I>::validate(dest, xcm)
.map(|(ticket, cost)| ((message_size, ticket), cost))
}
fn deliver(ticket: Self::Ticket) -> Result<XcmHash, SendError> {
// use router to enqueue message to the sibling/child bridge hub. This also should handle
// payment for passing through this queue.
let (message_size, ticket) = ticket;
let xcm_hash = ViaBridgeHubExporter::<T, I>::deliver(ticket)?;
// increase delivery fee factor if required
Self::on_message_sent_to_bridge(message_size);
Ok(xcm_hash)
}
}
#[cfg(test)]
mod tests {
use super::*;
use frame_support::assert_ok;
use mock::*;
use frame_support::traits::Hooks;
use sp_runtime::traits::One;
fn congested_bridge(delivery_fee_factor: FixedU128) -> BridgeState {
BridgeState { is_congested: true, delivery_fee_factor }
}
fn uncongested_bridge(delivery_fee_factor: FixedU128) -> BridgeState {
BridgeState { is_congested: false, delivery_fee_factor }
}
#[test]
fn initial_fee_factor_is_one() {
run_test(|| {
assert_eq!(
Bridge::<TestRuntime, ()>::get(),
uncongested_bridge(MINIMAL_DELIVERY_FEE_FACTOR),
);
})
}
#[test]
fn fee_factor_is_not_decreased_from_on_initialize_when_xcm_channel_is_congested() {
run_test(|| {
Bridge::<TestRuntime, ()>::put(uncongested_bridge(FixedU128::from_rational(125, 100)));
TestWithBridgeHubChannel::make_congested();
// it should not decrease, because xcm channel is congested
let old_bridge = XcmBridgeHubRouter::bridge();
XcmBridgeHubRouter::on_initialize(One::one());
assert_eq!(XcmBridgeHubRouter::bridge(), old_bridge);
})
}
#[test]
fn fee_factor_is_not_decreased_from_on_initialize_when_bridge_has_reported_congestion() {
run_test(|| {
Bridge::<TestRuntime, ()>::put(congested_bridge(FixedU128::from_rational(125, 100)));
// it should not decrease, because bridge congested
let old_bridge = XcmBridgeHubRouter::bridge();
XcmBridgeHubRouter::on_initialize(One::one());
assert_eq!(XcmBridgeHubRouter::bridge(), old_bridge);
})
}
#[test]
fn fee_factor_is_decreased_from_on_initialize_when_xcm_channel_is_uncongested() {
run_test(|| {
Bridge::<TestRuntime, ()>::put(uncongested_bridge(FixedU128::from_rational(125, 100)));
// it shold eventually decreased to one
while XcmBridgeHubRouter::bridge().delivery_fee_factor > MINIMAL_DELIVERY_FEE_FACTOR {
XcmBridgeHubRouter::on_initialize(One::one());
}
// verify that it doesn't decreases anymore
XcmBridgeHubRouter::on_initialize(One::one());
assert_eq!(
XcmBridgeHubRouter::bridge(),
uncongested_bridge(MINIMAL_DELIVERY_FEE_FACTOR)
);
})
}
#[test]
fn not_applicable_if_destination_is_within_other_network() {
run_test(|| {
assert_eq!(
send_xcm::<XcmBridgeHubRouter>(
Location::new(2, [GlobalConsensus(Rococo), Parachain(1000)]),
vec![].into(),
),
Err(SendError::NotApplicable),
);
});
}
#[test]
fn exceeds_max_message_size_if_size_is_above_hard_limit() {
run_test(|| {
assert_eq!(
send_xcm::<XcmBridgeHubRouter>(
Location::new(2, [GlobalConsensus(Rococo), Parachain(1000)]),
vec![ClearOrigin; HARD_MESSAGE_SIZE_LIMIT as usize].into(),
),
Err(SendError::ExceedsMaxMessageSize),
);
});
}
#[test]
fn destination_unsupported_if_wrap_version_fails() {
run_test(|| {
assert_eq!(
send_xcm::<XcmBridgeHubRouter>(
UnknownXcmVersionLocation::get(),
vec![ClearOrigin].into(),
),
Err(SendError::DestinationUnsupported),
);
});
}
#[test]
fn returns_proper_delivery_price() {
run_test(|| {
let dest = Location::new(2, [GlobalConsensus(BridgedNetworkId::get())]);
let xcm: Xcm<()> = vec![ClearOrigin].into();
let msg_size = xcm.encoded_size();
// initially the base fee is used: `BASE_FEE + BYTE_FEE * msg_size + HRMP_FEE`
let expected_fee = BASE_FEE + BYTE_FEE * (msg_size as u128) + HRMP_FEE;
assert_eq!(
XcmBridgeHubRouter::validate(&mut Some(dest.clone()), &mut Some(xcm.clone()))
.unwrap()
.1
.get(0),
Some(&(BridgeFeeAsset::get(), expected_fee).into()),
);
// but when factor is larger than one, it increases the fee, so it becomes:
// `(BASE_FEE + BYTE_FEE * msg_size) * F + HRMP_FEE`
let factor = FixedU128::from_rational(125, 100);
Bridge::<TestRuntime, ()>::put(uncongested_bridge(factor));
let expected_fee =
(FixedU128::saturating_from_integer(BASE_FEE + BYTE_FEE * (msg_size as u128)) *
factor)
.into_inner() / FixedU128::DIV +
HRMP_FEE;
assert_eq!(
XcmBridgeHubRouter::validate(&mut Some(dest), &mut Some(xcm)).unwrap().1.get(0),
Some(&(BridgeFeeAsset::get(), expected_fee).into()),
);
});
}
#[test]
fn sent_message_doesnt_increase_factor_if_xcm_channel_is_uncongested() {
run_test(|| {
let old_bridge = XcmBridgeHubRouter::bridge();
assert_ok!(send_xcm::<XcmBridgeHubRouter>(
Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)]),
vec![ClearOrigin].into(),
)
.map(drop));
assert!(TestToBridgeHubSender::is_message_sent());
assert_eq!(old_bridge, XcmBridgeHubRouter::bridge());
});
}
#[test]
fn sent_message_increases_factor_if_xcm_channel_is_congested() {
run_test(|| {
TestWithBridgeHubChannel::make_congested();
let old_bridge = XcmBridgeHubRouter::bridge();
assert_ok!(send_xcm::<XcmBridgeHubRouter>(
Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)]),
vec![ClearOrigin].into(),
)
.map(drop));
assert!(TestToBridgeHubSender::is_message_sent());
assert!(
old_bridge.delivery_fee_factor < XcmBridgeHubRouter::bridge().delivery_fee_factor
);
});
}
#[test]
fn sent_message_increases_factor_if_bridge_has_reported_congestion() {
run_test(|| {
Bridge::<TestRuntime, ()>::put(congested_bridge(MINIMAL_DELIVERY_FEE_FACTOR));
let old_bridge = XcmBridgeHubRouter::bridge();
assert_ok!(send_xcm::<XcmBridgeHubRouter>(
Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)]),
vec![ClearOrigin].into(),
)
.map(drop));
assert!(TestToBridgeHubSender::is_message_sent());
assert!(
old_bridge.delivery_fee_factor < XcmBridgeHubRouter::bridge().delivery_fee_factor
);
});
}
}
// Copyright (C) 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/>.
#![cfg(test)]
use crate as pallet_xcm_bridge_hub_router;
use bp_xcm_bridge_hub_router::XcmChannelStatusProvider;
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{Contains, Equals},
};
use frame_system::EnsureRoot;
use sp_runtime::{traits::ConstU128, BuildStorage};
use xcm::prelude::*;
use xcm_builder::{NetworkExportTable, NetworkExportTableItem};
pub type AccountId = u64;
type Block = frame_system::mocking::MockBlock<TestRuntime>;
/// HRMP fee.
pub const HRMP_FEE: u128 = 500;
/// Base bridge fee.
pub const BASE_FEE: u128 = 1_000_000;
/// Byte bridge fee.
pub const BYTE_FEE: u128 = 1_000;
construct_runtime! {
pub enum TestRuntime
{
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
XcmBridgeHubRouter: pallet_xcm_bridge_hub_router::{Pallet, Storage},
}
}
parameter_types! {
pub ThisNetworkId: NetworkId = Polkadot;
pub BridgedNetworkId: NetworkId = Kusama;
pub UniversalLocation: InteriorLocation = [GlobalConsensus(ThisNetworkId::get()), Parachain(1000)].into();
pub SiblingBridgeHubLocation: Location = ParentThen([Parachain(1002)].into()).into();
pub BridgeFeeAsset: AssetId = Location::parent().into();
pub BridgeTable: Vec<NetworkExportTableItem>
= vec![
NetworkExportTableItem::new(
BridgedNetworkId::get(),
None,
SiblingBridgeHubLocation::get(),
Some((BridgeFeeAsset::get(), BASE_FEE).into())
)
];
pub UnknownXcmVersionLocation: Location = Location::new(2, [GlobalConsensus(BridgedNetworkId::get()), Parachain(9999)]);
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for TestRuntime {
type Block = Block;
}
impl pallet_xcm_bridge_hub_router::Config<()> for TestRuntime {
type WeightInfo = ();
type UniversalLocation = UniversalLocation;
type BridgedNetworkId = BridgedNetworkId;
type Bridges = NetworkExportTable<BridgeTable>;
type DestinationVersion =
LatestOrNoneForLocationVersionChecker<Equals<UnknownXcmVersionLocation>>;
type BridgeHubOrigin = EnsureRoot<AccountId>;
type ToBridgeHubSender = TestToBridgeHubSender;
type WithBridgeHubChannel = TestWithBridgeHubChannel;
type ByteFee = ConstU128<BYTE_FEE>;
type FeeAsset = BridgeFeeAsset;
}
pub struct LatestOrNoneForLocationVersionChecker<Location>(sp_std::marker::PhantomData<Location>);
impl<LocationValue: Contains<Location>> GetVersion
for LatestOrNoneForLocationVersionChecker<LocationValue>
{
fn get_version_for(dest: &Location) -> Option<XcmVersion> {
if LocationValue::contains(dest) {
return None
}
Some(XCM_VERSION)
}
}
pub struct TestToBridgeHubSender;
impl TestToBridgeHubSender {
pub fn is_message_sent() -> bool {
frame_support::storage::unhashed::get_or_default(b"TestToBridgeHubSender.Sent")
}
}
impl SendXcm for TestToBridgeHubSender {
type Ticket = ();
fn validate(
_destination: &mut Option<Location>,
_message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
Ok(((), (BridgeFeeAsset::get(), HRMP_FEE).into()))
}
fn deliver(_ticket: Self::Ticket) -> Result<XcmHash, SendError> {
frame_support::storage::unhashed::put(b"TestToBridgeHubSender.Sent", &true);
Ok([0u8; 32])
}
}
pub struct TestWithBridgeHubChannel;
impl TestWithBridgeHubChannel {
pub fn make_congested() {
frame_support::storage::unhashed::put(b"TestWithBridgeHubChannel.Congested", &true);
}
}
impl XcmChannelStatusProvider for TestWithBridgeHubChannel {
fn is_congested() -> bool {
frame_support::storage::unhashed::get_or_default(b"TestWithBridgeHubChannel.Congested")
}
}
/// Return test externalities to use in tests.
pub fn new_test_ext() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::<TestRuntime>::default().build_storage().unwrap();
sp_io::TestExternalities::new(t)
}
/// Run pallet test.
pub fn run_test<T>(test: impl FnOnce() -> T) -> T {
new_test_ext().execute_with(test)
}
// Copyright (C) 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/>.
//! Autogenerated weights for pallet_xcm_bridge_hub_router
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
//! DATE: 2023-08-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! WORST CASE MAP SIZE: `1000000`
//! HOSTNAME: `covid`, CPU: `11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz`
//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
// target/release/rip-bridge-node
// benchmark
// pallet
// --chain=dev
// --steps=50
// --repeat=20
// --pallet=pallet_xcm_bridge_hub_router
// --extrinsic=*
// --execution=wasm
// --wasm-execution=Compiled
// --heap-pages=4096
// --output=./modules/xcm-bridge-hub-router/src/weights.rs
// --template=./.maintain/bridge-weight-template.hbs
#![allow(clippy::all)]
#![allow(unused_parens)]
#![allow(unused_imports)]
#![allow(missing_docs)]
use frame_support::{
traits::Get,
weights::{constants::RocksDbWeight, Weight},
};
use sp_std::marker::PhantomData;
/// Weight functions needed for pallet_xcm_bridge_hub_router.
pub trait WeightInfo {
fn on_initialize_when_non_congested() -> Weight;
fn on_initialize_when_congested() -> Weight;
fn report_bridge_status() -> Weight;
fn send_message() -> Weight;
}
/// Weights for `pallet_xcm_bridge_hub_router` that are generated using one of the Bridge testnets.
///
/// Those weights are test only and must never be used in production.
pub struct BridgeWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
///
/// Storage: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765`
/// (r:1 w:0)
///
/// Proof: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765` (r:1
/// w:0)
fn on_initialize_when_non_congested() -> Weight {
// Proof Size summary in bytes:
// Measured: `53`
// Estimated: `3518`
// Minimum execution time: 11_934 nanoseconds.
Weight::from_parts(12_201_000, 3518)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
///
/// Storage: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765`
/// (r:1 w:0)
///
/// Proof: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765` (r:1
/// w:0)
fn on_initialize_when_congested() -> Weight {
// Proof Size summary in bytes:
// Measured: `94`
// Estimated: `3559`
// Minimum execution time: 9_010 nanoseconds.
Weight::from_parts(9_594_000, 3559)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
fn report_bridge_status() -> Weight {
// Proof Size summary in bytes:
// Measured: `53`
// Estimated: `1502`
// Minimum execution time: 10_427 nanoseconds.
Weight::from_parts(10_682_000, 1502)
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
///
/// Storage: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765`
/// (r:1 w:0)
///
/// Proof: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765` (r:1
/// w:0)
fn send_message() -> Weight {
// Proof Size summary in bytes:
// Measured: `52`
// Estimated: `3517`
// Minimum execution time: 19_709 nanoseconds.
Weight::from_parts(20_110_000, 3517)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
///
/// Storage: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765`
/// (r:1 w:0)
///
/// Proof: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765` (r:1
/// w:0)
fn on_initialize_when_non_congested() -> Weight {
// Proof Size summary in bytes:
// Measured: `53`
// Estimated: `3518`
// Minimum execution time: 11_934 nanoseconds.
Weight::from_parts(12_201_000, 3518)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
///
/// Storage: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765`
/// (r:1 w:0)
///
/// Proof: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765` (r:1
/// w:0)
fn on_initialize_when_congested() -> Weight {
// Proof Size summary in bytes:
// Measured: `94`
// Estimated: `3559`
// Minimum execution time: 9_010 nanoseconds.
Weight::from_parts(9_594_000, 3559)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
fn report_bridge_status() -> Weight {
// Proof Size summary in bytes:
// Measured: `53`
// Estimated: `1502`
// Minimum execution time: 10_427 nanoseconds.
Weight::from_parts(10_682_000, 1502)
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: `XcmBridgeHubRouter::Bridge` (r:1 w:1)
///
/// Proof: `XcmBridgeHubRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added:
/// 512, mode: `MaxEncodedLen`)
///
/// Storage: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765`
/// (r:1 w:0)
///
/// Proof: UNKNOWN KEY `0x456d756c617465645369626c696e6758636d704368616e6e656c2e436f6e6765` (r:1
/// w:0)
fn send_message() -> Weight {
// Proof Size summary in bytes:
// Measured: `52`
// Estimated: `3517`
// Minimum execution time: 19_709 nanoseconds.
Weight::from_parts(20_110_000, 3517)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
}
[package]
name = "pallet-xcm-bridge-hub"
description = "Module that adds dynamic bridges/lanes support to XCM infrastucture at the bridge hub."
version = "0.2.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
log = { workspace = true }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Bridge Dependencies
bp-messages = { path = "../../primitives/messages", default-features = false }
bp-runtime = { path = "../../primitives/runtime", default-features = false }
bp-xcm-bridge-hub = { path = "../../primitives/xcm-bridge-hub", default-features = false }
pallet-bridge-messages = { path = "../messages", default-features = false }
bridge-runtime-common = { path = "../../bin/runtime-common", default-features = false }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-core = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Polkadot Dependencies
xcm = { package = "staging-xcm", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-builder = { package = "staging-xcm-builder", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
xcm-executor = { package = "staging-xcm-executor", git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[dev-dependencies]
bp-header-chain = { path = "../../primitives/header-chain" }
pallet-balances = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
sp-io = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master" }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-runtime/std",
"bp-xcm-bridge-hub/std",
"bridge-runtime-common/std",
"codec/std",
"frame-support/std",
"frame-system/std",
"log/std",
"pallet-bridge-messages/std",
"scale-info/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
"xcm-builder/std",
"xcm-executor/std",
"xcm/std",
]
runtime-benchmarks = [
"bridge-runtime-common/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-bridge-messages/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
]
try-runtime = [
"frame-support/try-runtime",
"frame-system/try-runtime",
"pallet-balances/try-runtime",
"pallet-bridge-messages/try-runtime",
"sp-runtime/try-runtime",
]
// Copyright 2019-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/>.
//! The code that allows to use the pallet (`pallet-xcm-bridge-hub`) as XCM message
//! exporter at the sending bridge hub. Internally, it just enqueues outbound blob
//! in the messages pallet queue.
//!
//! This code is executed at the source bridge hub.
use crate::{Config, Pallet, LOG_TARGET};
use bp_messages::source_chain::MessagesBridge;
use bp_xcm_bridge_hub::XcmAsPlainPayload;
use bridge_runtime_common::messages_xcm_extension::{LocalXcmQueueManager, SenderAndLane};
use pallet_bridge_messages::{Config as BridgeMessagesConfig, Pallet as BridgeMessagesPallet};
use xcm::prelude::*;
use xcm_builder::{HaulBlob, HaulBlobError, HaulBlobExporter};
use xcm_executor::traits::ExportXcm;
/// An easy way to access `HaulBlobExporter`.
pub type PalletAsHaulBlobExporter<T, I> = HaulBlobExporter<
DummyHaulBlob,
<T as Config<I>>::BridgedNetwork,
<T as Config<I>>::DestinationVersion,
<T as Config<I>>::MessageExportPrice,
>;
/// An easy way to access associated messages pallet.
type MessagesPallet<T, I> = BridgeMessagesPallet<T, <T as Config<I>>::BridgeMessagesPalletInstance>;
impl<T: Config<I>, I: 'static> ExportXcm for Pallet<T, I>
where
T: BridgeMessagesConfig<T::BridgeMessagesPalletInstance, OutboundPayload = XcmAsPlainPayload>,
{
type Ticket = (
SenderAndLane,
<MessagesPallet<T, I> as MessagesBridge<T::OutboundPayload>>::SendMessageArgs,
XcmHash,
);
fn validate(
network: NetworkId,
channel: u32,
universal_source: &mut Option<InteriorLocation>,
destination: &mut Option<InteriorLocation>,
message: &mut Option<Xcm<()>>,
) -> Result<(Self::Ticket, Assets), SendError> {
// Find supported lane_id.
let sender_and_lane = Self::lane_for(
universal_source.as_ref().ok_or(SendError::MissingArgument)?,
(&network, destination.as_ref().ok_or(SendError::MissingArgument)?),
)
.ok_or(SendError::NotApplicable)?;
// check if we are able to route the message. We use existing `HaulBlobExporter` for that.
// It will make all required changes and will encode message properly, so that the
// `DispatchBlob` at the bridged bridge hub will be able to decode it
let ((blob, id), price) = PalletAsHaulBlobExporter::<T, I>::validate(
network,
channel,
universal_source,
destination,
message,
)?;
let bridge_message = MessagesPallet::<T, I>::validate_message(sender_and_lane.lane, &blob)
.map_err(|e| {
log::debug!(
target: LOG_TARGET,
"XCM message {:?} cannot be exported because of bridge error {:?} on bridge {:?}",
id,
e,
sender_and_lane.lane,
);
SendError::Transport("BridgeValidateError")
})?;
Ok(((sender_and_lane, bridge_message, id), price))
}
fn deliver((sender_and_lane, bridge_message, id): Self::Ticket) -> Result<XcmHash, SendError> {
let lane_id = sender_and_lane.lane;
let artifacts = MessagesPallet::<T, I>::send_message(bridge_message);
log::info!(
target: LOG_TARGET,
"XCM message {:?} has been enqueued at bridge {:?} with nonce {}",
id,
lane_id,
artifacts.nonce,
);
// notify XCM queue manager about updated lane state
LocalXcmQueueManager::<T::LanesSupport>::on_bridge_message_enqueued(
&sender_and_lane,
artifacts.enqueued_messages,
);
Ok(id)
}
}
/// Dummy implementation of the `HaulBlob` trait that is never called.
///
/// We are using `HaulBlobExporter`, which requires `HaulBlob` implementation. It assumes that
/// there's a single channel between two bridge hubs - `HaulBlob` only accepts the blob and nothing
/// else. But bridge messages pallet may have a dedicated channel (lane) for every pair of bridged
/// chains. So we are using our own `ExportXcm` implementation, but to utilize `HaulBlobExporter` we
/// still need this `DummyHaulBlob`.
pub struct DummyHaulBlob;
impl HaulBlob for DummyHaulBlob {
fn haul_blob(_blob: XcmAsPlainPayload) -> Result<(), HaulBlobError> {
Err(HaulBlobError::Transport("DummyHaulBlob"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mock::*;
use frame_support::assert_ok;
use xcm_executor::traits::export_xcm;
fn universal_source() -> InteriorLocation {
[GlobalConsensus(RelayNetwork::get()), Parachain(SIBLING_ASSET_HUB_ID)].into()
}
fn universal_destination() -> InteriorLocation {
BridgedDestination::get()
}
#[test]
fn export_works() {
run_test(|| {
assert_ok!(export_xcm::<XcmOverBridge>(
BridgedRelayNetwork::get(),
0,
universal_source(),
universal_destination(),
vec![Instruction::ClearOrigin].into(),
));
})
}
#[test]
fn export_fails_if_argument_is_missing() {
run_test(|| {
assert_eq!(
XcmOverBridge::validate(
BridgedRelayNetwork::get(),
0,
&mut None,
&mut Some(universal_destination()),
&mut Some(Vec::new().into()),
),
Err(SendError::MissingArgument),
);
assert_eq!(
XcmOverBridge::validate(
BridgedRelayNetwork::get(),
0,
&mut Some(universal_source()),
&mut None,
&mut Some(Vec::new().into()),
),
Err(SendError::MissingArgument),
);
})
}
#[test]
fn exporter_computes_correct_lane_id() {
run_test(|| {
let expected_lane_id = TEST_LANE_ID;
assert_eq!(
XcmOverBridge::validate(
BridgedRelayNetwork::get(),
0,
&mut Some(universal_source()),
&mut Some(universal_destination()),
&mut Some(Vec::new().into()),
)
.unwrap()
.0
.0
.lane,
expected_lane_id,
);
})
}
}
// Copyright 2019-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/>.
//! Module that adds XCM support to bridge pallets.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
use bridge_runtime_common::messages_xcm_extension::XcmBlobHauler;
use pallet_bridge_messages::Config as BridgeMessagesConfig;
use xcm::prelude::*;
pub use exporter::PalletAsHaulBlobExporter;
pub use pallet::*;
mod exporter;
mod mock;
/// The target that will be used when publishing logs related to this pallet.
pub const LOG_TARGET: &str = "runtime::bridge-xcm";
#[frame_support::pallet]
pub mod pallet {
use super::*;
use bridge_runtime_common::messages_xcm_extension::SenderAndLane;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::BlockNumberFor;
#[pallet::config]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config<I: 'static = ()>:
BridgeMessagesConfig<Self::BridgeMessagesPalletInstance>
{
/// Runtime's universal location.
type UniversalLocation: Get<InteriorLocation>;
// TODO: https://github.com/paritytech/parity-bridges-common/issues/1666 remove `ChainId` and
// replace it with the `NetworkId` - then we'll be able to use
// `T as pallet_bridge_messages::Config<T::BridgeMessagesPalletInstance>::BridgedChain::NetworkId`
/// Bridged network as relative location of bridged `GlobalConsensus`.
#[pallet::constant]
type BridgedNetwork: Get<Location>;
/// Associated messages pallet instance that bridges us with the
/// `BridgedNetworkId` consensus.
type BridgeMessagesPalletInstance: 'static;
/// Price of single message export to the bridged consensus (`Self::BridgedNetworkId`).
type MessageExportPrice: Get<Assets>;
/// Checks the XCM version for the destination.
type DestinationVersion: GetVersion;
/// Get point-to-point links with bridged consensus (`Self::BridgedNetworkId`).
/// (this will be replaced with dynamic on-chain bridges - `Bridges V2`)
type Lanes: Get<sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))>>;
/// Support for point-to-point links
/// (this will be replaced with dynamic on-chain bridges - `Bridges V2`)
type LanesSupport: XcmBlobHauler;
}
#[pallet::pallet]
pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);
#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
fn integrity_test() {
assert!(
Self::bridged_network_id().is_some(),
"Configured `T::BridgedNetwork`: {:?} does not contain `GlobalConsensus` junction with `NetworkId`",
T::BridgedNetwork::get()
)
}
}
impl<T: Config<I>, I: 'static> Pallet<T, I> {
/// Returns dedicated/configured lane identifier.
pub(crate) fn lane_for(
source: &InteriorLocation,
dest: (&NetworkId, &InteriorLocation),
) -> Option<SenderAndLane> {
let source = source.clone().relative_to(&T::UniversalLocation::get());
// Check that we have configured a point-to-point lane for 'source' and `dest`.
T::Lanes::get()
.into_iter()
.find_map(|(lane_source, (lane_dest_network, lane_dest))| {
if lane_source.location == source &&
&lane_dest_network == dest.0 &&
Self::bridged_network_id().as_ref() == Some(dest.0) &&
&lane_dest == dest.1
{
Some(lane_source)
} else {
None
}
})
}
/// Returns some `NetworkId` if contains `GlobalConsensus` junction.
fn bridged_network_id() -> Option<NetworkId> {
match T::BridgedNetwork::get().take_first_interior() {
Some(GlobalConsensus(network)) => Some(network),
_ => None,
}
}
}
}
// Copyright 2019-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/>.
#![cfg(test)]
use crate as pallet_xcm_bridge_hub;
use bp_messages::{
target_chain::{DispatchMessage, MessageDispatch},
LaneId,
};
use bp_runtime::{messages::MessageDispatchResult, Chain, ChainId, UnderlyingChainProvider};
use bridge_runtime_common::{
messages::{
source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter,
BridgedChainWithMessages, HashOf, MessageBridge, ThisChainWithMessages,
},
messages_xcm_extension::{SenderAndLane, XcmBlobHauler},
};
use codec::Encode;
use frame_support::{derive_impl, parameter_types, traits::ConstU32, weights::RuntimeDbWeight};
use sp_core::H256;
use sp_runtime::{
testing::Header as SubstrateHeader,
traits::{BlakeTwo256, IdentityLookup},
AccountId32, BuildStorage,
};
use xcm::prelude::*;
pub type AccountId = AccountId32;
pub type Balance = u64;
type Block = frame_system::mocking::MockBlock<TestRuntime>;
pub const SIBLING_ASSET_HUB_ID: u32 = 2001;
pub const THIS_BRIDGE_HUB_ID: u32 = 2002;
pub const BRIDGED_ASSET_HUB_ID: u32 = 1001;
pub const TEST_LANE_ID: LaneId = LaneId([0, 0, 0, 1]);
frame_support::construct_runtime! {
pub enum TestRuntime {
System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Event<T>},
Messages: pallet_bridge_messages::{Pallet, Call, Event<T>},
XcmOverBridge: pallet_xcm_bridge_hub::{Pallet},
}
}
parameter_types! {
pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 };
pub const ExistentialDeposit: Balance = 1;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for TestRuntime {
type AccountId = AccountId;
type AccountData = pallet_balances::AccountData<Balance>;
type Block = Block;
type Lookup = IdentityLookup<Self::AccountId>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)]
impl pallet_balances::Config for TestRuntime {
type AccountStore = System;
}
parameter_types! {
pub const ActiveOutboundLanes: &'static [LaneId] = &[TEST_LANE_ID];
}
impl pallet_bridge_messages::Config for TestRuntime {
type RuntimeEvent = RuntimeEvent;
type WeightInfo = TestMessagesWeights;
type BridgedChainId = ();
type ActiveOutboundLanes = ActiveOutboundLanes;
type MaxUnrewardedRelayerEntriesAtInboundLane = ();
type MaxUnconfirmedMessagesAtInboundLane = ();
type MaximalOutboundPayloadSize = ConstU32<2048>;
type OutboundPayload = Vec<u8>;
type InboundPayload = Vec<u8>;
type InboundRelayer = ();
type DeliveryPayments = ();
type TargetHeaderChain = TargetHeaderChainAdapter<OnThisChainBridge>;
type DeliveryConfirmationPayments = ();
type OnMessagesDelivered = ();
type SourceHeaderChain = SourceHeaderChainAdapter<OnThisChainBridge>;
type MessageDispatch = TestMessageDispatch;
}
pub struct TestMessagesWeights;
impl pallet_bridge_messages::WeightInfo for TestMessagesWeights {
fn receive_single_message_proof() -> Weight {
Weight::zero()
}
fn receive_single_message_proof_with_outbound_lane_state() -> Weight {
Weight::zero()
}
fn receive_delivery_proof_for_single_message() -> Weight {
Weight::zero()
}
fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight {
Weight::zero()
}
fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight {
Weight::zero()
}
fn receive_two_messages_proof() -> Weight {
Weight::zero()
}
fn receive_single_message_proof_1_kb() -> Weight {
Weight::zero()
}
fn receive_single_message_proof_16_kb() -> Weight {
Weight::zero()
}
fn receive_single_message_proof_with_dispatch(_: u32) -> Weight {
Weight::from_parts(1, 0)
}
}
impl pallet_bridge_messages::WeightInfoExt for TestMessagesWeights {
fn expected_extra_storage_proof_size() -> u32 {
0
}
fn receive_messages_proof_overhead_from_runtime() -> Weight {
Weight::zero()
}
fn receive_messages_delivery_proof_overhead_from_runtime() -> Weight {
Weight::zero()
}
}
parameter_types! {
pub const RelayNetwork: NetworkId = NetworkId::Kusama;
pub const BridgedRelayNetwork: NetworkId = NetworkId::Polkadot;
pub BridgedRelayNetworkLocation: Location = (Parent, GlobalConsensus(BridgedRelayNetwork::get())).into();
pub const NonBridgedRelayNetwork: NetworkId = NetworkId::Rococo;
pub const BridgeReserve: Balance = 100_000;
pub UniversalLocation: InteriorLocation = [
GlobalConsensus(RelayNetwork::get()),
Parachain(THIS_BRIDGE_HUB_ID),
].into();
pub const Penalty: Balance = 1_000;
}
impl pallet_xcm_bridge_hub::Config for TestRuntime {
type UniversalLocation = UniversalLocation;
type BridgedNetwork = BridgedRelayNetworkLocation;
type BridgeMessagesPalletInstance = ();
type MessageExportPrice = ();
type DestinationVersion = AlwaysLatest;
type Lanes = TestLanes;
type LanesSupport = TestXcmBlobHauler;
}
parameter_types! {
pub TestSenderAndLane: SenderAndLane = SenderAndLane {
location: Location::new(1, [Parachain(SIBLING_ASSET_HUB_ID)]),
lane: TEST_LANE_ID,
};
pub BridgedDestination: InteriorLocation = [
Parachain(BRIDGED_ASSET_HUB_ID)
].into();
pub TestLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![
(TestSenderAndLane::get(), (BridgedRelayNetwork::get(), BridgedDestination::get()))
];
}
pub struct TestXcmBlobHauler;
impl XcmBlobHauler for TestXcmBlobHauler {
type Runtime = TestRuntime;
type MessagesInstance = ();
type ToSourceChainSender = ();
type CongestedMessage = ();
type UncongestedMessage = ();
}
pub struct ThisChain;
impl Chain for ThisChain {
const ID: ChainId = *b"tuch";
type BlockNumber = u64;
type Hash = H256;
type Hasher = BlakeTwo256;
type Header = SubstrateHeader;
type AccountId = AccountId;
type Balance = Balance;
type Nonce = u64;
type Signature = sp_runtime::MultiSignature;
fn max_extrinsic_size() -> u32 {
u32::MAX
}
fn max_extrinsic_weight() -> Weight {
Weight::MAX
}
}
pub struct BridgedChain;
pub type BridgedHeaderHash = H256;
pub type BridgedChainHeader = SubstrateHeader;
impl Chain for BridgedChain {
const ID: ChainId = *b"tuch";
type BlockNumber = u64;
type Hash = BridgedHeaderHash;
type Hasher = BlakeTwo256;
type Header = BridgedChainHeader;
type AccountId = AccountId;
type Balance = Balance;
type Nonce = u64;
type Signature = sp_runtime::MultiSignature;
fn max_extrinsic_size() -> u32 {
4096
}
fn max_extrinsic_weight() -> Weight {
Weight::MAX
}
}
/// Test message dispatcher.
pub struct TestMessageDispatch;
impl TestMessageDispatch {
pub fn deactivate(lane: LaneId) {
frame_support::storage::unhashed::put(&(b"inactive", lane).encode()[..], &false);
}
}
impl MessageDispatch for TestMessageDispatch {
type DispatchPayload = Vec<u8>;
type DispatchLevelResult = ();
fn is_active() -> bool {
frame_support::storage::unhashed::take::<bool>(&(b"inactive").encode()[..]) != Some(false)
}
fn dispatch_weight(_message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight {
Weight::zero()
}
fn dispatch(
_: DispatchMessage<Self::DispatchPayload>,
) -> MessageDispatchResult<Self::DispatchLevelResult> {
MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: () }
}
}
pub struct WrappedThisChain;
impl UnderlyingChainProvider for WrappedThisChain {
type Chain = ThisChain;
}
impl ThisChainWithMessages for WrappedThisChain {
type RuntimeOrigin = RuntimeOrigin;
}
pub struct WrappedBridgedChain;
impl UnderlyingChainProvider for WrappedBridgedChain {
type Chain = BridgedChain;
}
impl BridgedChainWithMessages for WrappedBridgedChain {}
pub struct BridgedHeaderChain;
impl bp_header_chain::HeaderChain<BridgedChain> for BridgedHeaderChain {
fn finalized_header_state_root(
_hash: HashOf<WrappedBridgedChain>,
) -> Option<HashOf<WrappedBridgedChain>> {
unreachable!()
}
}
/// Bridge that is deployed on `ThisChain` and allows sending/receiving messages to/from
/// `BridgedChain`.
#[derive(Debug, PartialEq, Eq)]
pub struct OnThisChainBridge;
impl MessageBridge for OnThisChainBridge {
const BRIDGED_MESSAGES_PALLET_NAME: &'static str = "";
type ThisChain = WrappedThisChain;
type BridgedChain = WrappedBridgedChain;
type BridgedHeaderChain = BridgedHeaderChain;
}
/// Run pallet test.
pub fn run_test<T>(test: impl FnOnce() -> T) -> T {
sp_io::TestExternalities::new(
frame_system::GenesisConfig::<TestRuntime>::default().build_storage().unwrap(),
)
.execute_with(test)
}
[package]
name = "bp-beefy"
description = "Primitives of pallet-bridge-beefy module."
version = "0.1.0"
authors = ["Parity Technologies <[email protected]>"]
edition = "2021"
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] }
scale-info = { version = "2.10.0", default-features = false, features = ["bit-vec", "derive"] }
serde = { default-features = false, features = ["alloc", "derive"], workspace = true }
# Bridge Dependencies
bp-runtime = { path = "../runtime", default-features = false }
# Substrate Dependencies
binary-merkle-tree = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-consensus-beefy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-beefy-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
pallet-mmr = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[features]
default = [ "std" ]
std = [
"bp-runtime/std",
"codec/std",
"frame-support/std",
"pallet-beefy-mmr/std",
"pallet-mmr/std",
"scale-info/std",
"serde/std",
"sp-consensus-beefy/std",
"sp-runtime/std",
"sp-std/std",
]
// Copyright 2019-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/>.
//! Primitives that are used to interact with BEEFY bridge pallet.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs)]
pub use binary_merkle_tree::merkle_root;
pub use pallet_beefy_mmr::BeefyEcdsaToEthereum;
pub use pallet_mmr::{
primitives::{DataOrHash as MmrDataOrHash, Proof as MmrProof},
verify_leaves_proof as verify_mmr_leaves_proof,
};
pub use sp_consensus_beefy::{
ecdsa_crypto::{
AuthorityId as EcdsaValidatorId, AuthoritySignature as EcdsaValidatorSignature,
},
known_payloads::MMR_ROOT_ID as MMR_ROOT_PAYLOAD_ID,
mmr::{BeefyAuthoritySet, MmrLeafVersion},
BeefyAuthorityId, Commitment, Payload as BeefyPayload, SignedCommitment, ValidatorSet,
ValidatorSetId, BEEFY_ENGINE_ID,
};
use bp_runtime::{BasicOperatingMode, BlockNumberOf, Chain, HashOf};
use codec::{Decode, Encode};
use frame_support::Parameter;
use scale_info::TypeInfo;
use serde::{Deserialize, Serialize};
use sp_runtime::{
traits::{Convert, MaybeSerializeDeserialize},
RuntimeAppPublic, RuntimeDebug,
};
use sp_std::prelude::*;
/// Substrate-based chain with BEEFY && MMR pallets deployed.
///
/// Both BEEFY and MMR pallets and their clients may be configured to use different
/// primitives. Some of types can be configured in low-level pallets, but are constrained
/// when BEEFY+MMR bundle is used.
pub trait ChainWithBeefy: Chain {
/// The hashing algorithm used to compute the digest of the BEEFY commitment.
///
/// Corresponds to the hashing algorithm, used by `sc_consensus_beefy::BeefyKeystore`.
type CommitmentHasher: sp_runtime::traits::Hash;
/// The hashing algorithm used to build the MMR.
///
/// The same algorithm is also used to compute merkle roots in BEEFY
/// (e.g. validator addresses root in leaf data).
///
/// Corresponds to the `Hashing` field of the `pallet-mmr` configuration.
type MmrHashing: sp_runtime::traits::Hash<Output = Self::MmrHash>;
/// The output type of the hashing algorithm used to build the MMR.
///
/// This type is actually stored in the MMR.
/// Corresponds to the `Hash` field of the `pallet-mmr` configuration.
type MmrHash: sp_std::hash::Hash
+ Parameter
+ Copy
+ AsRef<[u8]>
+ Default
+ MaybeSerializeDeserialize
+ PartialOrd;
/// The type expected for the MMR leaf extra data.
type BeefyMmrLeafExtra: Parameter;
/// A way to identify a BEEFY validator.
///
/// Corresponds to the `BeefyId` field of the `pallet-beefy` configuration.
type AuthorityId: BeefyAuthorityId<Self::CommitmentHasher> + Parameter;
/// A way to convert validator id to its raw representation in the BEEFY merkle tree.
///
/// Corresponds to the `BeefyAuthorityToMerkleLeaf` field of the `pallet-beefy-mmr`
/// configuration.
type AuthorityIdToMerkleLeaf: Convert<Self::AuthorityId, Vec<u8>>;
}
/// BEEFY validator id used by given Substrate chain.
pub type BeefyAuthorityIdOf<C> = <C as ChainWithBeefy>::AuthorityId;
/// BEEFY validator set, containing both validator identifiers and the numeric set id.
pub type BeefyAuthoritySetOf<C> = ValidatorSet<BeefyAuthorityIdOf<C>>;
/// BEEFY authority set, containing both validator identifiers and the numeric set id.
pub type BeefyAuthoritySetInfoOf<C> = sp_consensus_beefy::mmr::BeefyAuthoritySet<MmrHashOf<C>>;
/// BEEFY validator signature used by given Substrate chain.
pub type BeefyValidatorSignatureOf<C> =
<<C as ChainWithBeefy>::AuthorityId as RuntimeAppPublic>::Signature;
/// Signed BEEFY commitment used by given Substrate chain.
pub type BeefySignedCommitmentOf<C> =
SignedCommitment<BlockNumberOf<C>, BeefyValidatorSignatureOf<C>>;
/// Hash algorithm, used to compute the digest of the BEEFY commitment before signing it.
pub type BeefyCommitmentHasher<C> = <C as ChainWithBeefy>::CommitmentHasher;
/// Hash algorithm used in Beefy MMR construction by given Substrate chain.
pub type MmrHashingOf<C> = <C as ChainWithBeefy>::MmrHashing;
/// Hash type, used in MMR construction by given Substrate chain.
pub type MmrHashOf<C> = <C as ChainWithBeefy>::MmrHash;
/// BEEFY MMR proof type used by the given Substrate chain.
pub type MmrProofOf<C> = MmrProof<MmrHashOf<C>>;
/// The type of the MMR leaf extra data used by the given Substrate chain.
pub type BeefyMmrLeafExtraOf<C> = <C as ChainWithBeefy>::BeefyMmrLeafExtra;
/// A way to convert a validator id to its raw representation in the BEEFY merkle tree, used by
/// the given Substrate chain.
pub type BeefyAuthorityIdToMerkleLeafOf<C> = <C as ChainWithBeefy>::AuthorityIdToMerkleLeaf;
/// Actual type of leafs in the BEEFY MMR.
pub type BeefyMmrLeafOf<C> = sp_consensus_beefy::mmr::MmrLeaf<
BlockNumberOf<C>,
HashOf<C>,
MmrHashOf<C>,
BeefyMmrLeafExtraOf<C>,
>;
/// Data required for initializing the BEEFY pallet.
///
/// Provides the initial context that the bridge needs in order to know
/// where to start the sync process from.
#[derive(Encode, Decode, RuntimeDebug, PartialEq, Clone, TypeInfo, Serialize, Deserialize)]
pub struct InitializationData<BlockNumber, Hash> {
/// Pallet operating mode.
pub operating_mode: BasicOperatingMode,
/// Number of the best block, finalized by BEEFY.
pub best_block_number: BlockNumber,
/// BEEFY authority set that will be finalizing descendants of the `best_beefy_block_number`
/// block.
pub authority_set: BeefyAuthoritySet<Hash>,
}
/// Basic data, stored by the pallet for every imported commitment.
#[derive(Encode, Decode, RuntimeDebug, PartialEq, TypeInfo)]
pub struct ImportedCommitment<BlockNumber, BlockHash, MmrHash> {
/// Block number and hash of the finalized block parent.
pub parent_number_and_hash: (BlockNumber, BlockHash),
/// MMR root at the imported block.
pub mmr_root: MmrHash,
}
[package]
name = "bp-asset-hub-rococo"
description = "Primitives of AssetHubRococo parachain runtime."
version = "0.4.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Bridge Dependencies
bp-xcm-bridge-hub-router = { path = "../xcm-bridge-hub-router", default-features = false }
[features]
default = ["std"]
std = [
"bp-xcm-bridge-hub-router/std",
"codec/std",
"frame-support/std",
"scale-info/std",
]
// Copyright (C) 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/>.
//! Module with configuration which reflects AssetHubRococo runtime setup.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use scale_info::TypeInfo;
pub use bp_xcm_bridge_hub_router::XcmBridgeHubRouterCall;
/// `AssetHubRococo` Runtime `Call` enum.
///
/// The enum represents a subset of possible `Call`s we can send to `AssetHubRococo` chain.
/// Ideally this code would be auto-generated from metadata, because we want to
/// avoid depending directly on the ENTIRE runtime just to get the encoding of `Dispatchable`s.
///
/// All entries here (like pretty much in the entire file) must be kept in sync with
/// `AssetHubRococo` `construct_runtime`, so that we maintain SCALE-compatibility.
#[allow(clippy::large_enum_variant)]
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
pub enum Call {
/// `ToWestendXcmRouter` bridge pallet.
#[codec(index = 45)]
ToWestendXcmRouter(XcmBridgeHubRouterCall),
}
frame_support::parameter_types! {
/// Some sane weight to execute `xcm::Transact(pallet-xcm-bridge-hub-router::Call::report_bridge_status)`.
pub const XcmBridgeHubRouterTransactCallMaxWeight: frame_support::weights::Weight = frame_support::weights::Weight::from_parts(200_000_000, 6144);
}
/// Identifier of AssetHubRococo in the Rococo relay chain.
pub const ASSET_HUB_ROCOCO_PARACHAIN_ID: u32 = 1000;
[package]
name = "bp-asset-hub-westend"
description = "Primitives of AssetHubWestend parachain runtime."
version = "0.3.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
scale-info = { version = "2.10.0", default-features = false, features = ["derive"] }
# Substrate Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Bridge Dependencies
bp-xcm-bridge-hub-router = { path = "../xcm-bridge-hub-router", default-features = false }
[features]
default = ["std"]
std = [
"bp-xcm-bridge-hub-router/std",
"codec/std",
"frame-support/std",
"scale-info/std",
]
// Copyright (C) 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/>.
//! Module with configuration which reflects AssetHubWestend runtime setup.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode};
use scale_info::TypeInfo;
pub use bp_xcm_bridge_hub_router::XcmBridgeHubRouterCall;
/// `AssetHubWestend` Runtime `Call` enum.
///
/// The enum represents a subset of possible `Call`s we can send to `AssetHubWestend` chain.
/// Ideally this code would be auto-generated from metadata, because we want to
/// avoid depending directly on the ENTIRE runtime just to get the encoding of `Dispatchable`s.
///
/// All entries here (like pretty much in the entire file) must be kept in sync with
/// `AssetHubWestend` `construct_runtime`, so that we maintain SCALE-compatibility.
#[allow(clippy::large_enum_variant)]
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
pub enum Call {
/// `ToRococoXcmRouter` bridge pallet.
#[codec(index = 34)]
ToRococoXcmRouter(XcmBridgeHubRouterCall),
}
frame_support::parameter_types! {
/// Some sane weight to execute `xcm::Transact(pallet-xcm-bridge-hub-router::Call::report_bridge_status)`.
pub const XcmBridgeHubRouterTransactCallMaxWeight: frame_support::weights::Weight = frame_support::weights::Weight::from_parts(200_000_000, 6144);
}
/// Identifier of AssetHubWestend in the Westend relay chain.
pub const ASSET_HUB_WESTEND_PARACHAIN_ID: u32 = 1000;
[package]
name = "bp-bridge-hub-cumulus"
description = "Primitives for BridgeHub parachain runtimes."
version = "0.7.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
# Bridge Dependencies
bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false }
bp-messages = { path = "../../primitives/messages", default-features = false }
bp-runtime = { path = "../../primitives/runtime", default-features = false }
# Substrate Based Dependencies
frame-system = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
# Polkadot Dependencies
polkadot-primitives = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false , branch = "master" }
[features]
default = ["std"]
std = [
"bp-messages/std",
"bp-polkadot-core/std",
"bp-runtime/std",
"frame-support/std",
"frame-system/std",
"polkadot-primitives/std",
"sp-api/std",
"sp-std/std",
]
// Copyright (C) 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/>.
//! Primitives of all Cumulus-based bridge hubs.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
pub use bp_polkadot_core::{
AccountId, AccountInfoStorageMapKeyProvider, AccountPublic, Balance, BlockNumber, Hash, Hasher,
Hashing, Header, Nonce, Perbill, Signature, SignedBlock, UncheckedExtrinsic,
EXTRA_STORAGE_PROOF_SIZE, TX_EXTRA_BYTES,
};
use bp_messages::*;
use bp_polkadot_core::SuffixedCommonTransactionExtension;
use bp_runtime::extensions::{
BridgeRejectObsoleteHeadersAndMessages, RefundBridgedParachainMessagesSchema,
};
use frame_support::{
dispatch::DispatchClass,
parameter_types,
sp_runtime::{MultiAddress, MultiSigner},
weights::constants,
};
use frame_system::limits;
use sp_std::time::Duration;
/// Maximal bridge hub header size.
pub const MAX_BRIDGE_HUB_HEADER_SIZE: u32 = 4_096;
/// Average block interval in Cumulus-based parachains.
///
/// Corresponds to the `MILLISECS_PER_BLOCK` from `parachains_common` crate.
pub const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_secs(12);
/// All cumulus bridge hubs allow normal extrinsics to fill block up to 75 percent.
///
/// This is a copy-paste from the cumulus repo's `parachains-common` crate.
pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// All cumulus bridge hubs chains allow for 0.5 seconds of compute with a 6-second average block
/// time.
///
/// This is a copy-paste from the cumulus repo's `parachains-common` crate.
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_SECOND, 0)
.saturating_div(2)
.set_proof_size(polkadot_primitives::MAX_POV_SIZE as u64);
/// We allow for 2 seconds of compute with a 6 second average block.
const MAXIMUM_BLOCK_WEIGHT_FOR_ASYNC_BACKING: Weight = Weight::from_parts(
constants::WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
polkadot_primitives::MAX_POV_SIZE as u64,
);
/// All cumulus bridge hubs assume that about 5 percent of the block weight is consumed by
/// `on_initialize` handlers. This is used to limit the maximal weight of a single extrinsic.
///
/// This is a copy-paste from the cumulus repo's `parachains-common` crate.
pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
parameter_types! {
/// Size limit of the Cumulus-based bridge hub blocks.
pub BlockLength: limits::BlockLength = limits::BlockLength::max_with_normal_ratio(
5 * 1024 * 1024,
NORMAL_DISPATCH_RATIO,
);
/// Importing a block with 0 Extrinsics.
pub const BlockExecutionWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS, 0)
.saturating_mul(5_000_000);
/// Executing a NO-OP `System::remarks` Extrinsic.
pub const ExtrinsicBaseWeight: Weight = Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS, 0)
.saturating_mul(125_000);
/// Weight limit of the Cumulus-based bridge hub blocks.
pub BlockWeights: limits::BlockWeights = limits::BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Operational transactions have an extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT,
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
/// Weight limit of the Cumulus-based bridge hub blocks when async backing is enabled.
pub BlockWeightsForAsyncBacking: limits::BlockWeights = limits::BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT_FOR_ASYNC_BACKING);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT_FOR_ASYNC_BACKING);
// Operational transactions have an extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT_FOR_ASYNC_BACKING`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT_FOR_ASYNC_BACKING - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT_FOR_ASYNC_BACKING,
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
}
/// Public key of the chain account that may be used to verify signatures.
pub type AccountSigner = MultiSigner;
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
// Note about selecting values of two following constants:
//
// Normal transactions have limit of 75% of 1/2 second weight for Cumulus parachains. Let's keep
// some reserve for the rest of stuff there => let's select values that fit in 50% of maximal limit.
//
// Using current constants, the limit would be:
//
// `75% * WEIGHT_REF_TIME_PER_SECOND * 1 / 2 * 50% = 0.75 * 1_000_000_000_000 / 2 * 0.5 =
// 187_500_000_000`
//
// According to (preliminary) weights of messages pallet, cost of additional message is zero and the
// cost of additional relayer is `8_000_000 + db read + db write`. Let's say we want no more than
// 4096 unconfirmed messages (no any scientific justification for that - it just looks large
// enough). And then we can't have more than 4096 relayers. E.g. for 1024 relayers is (using
// `RocksDbWeight`):
//
// `1024 * (8_000_000 + db read + db write) = 1024 * (8_000_000 + 25_000_000 + 100_000_000) =
// 136_192_000_000`
//
// So 1024 looks like good approximation for the number of relayers. If something is wrong in those
// assumptions, or something will change, it shall be caught by the
// `ensure_able_to_receive_confirmation` test.
/// Maximal number of unrewarded relayer entries at inbound lane for Cumulus-based parachains.
/// Note: this value is security-relevant, decreasing it should not be done without careful
/// analysis (like the one above).
pub const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 1024;
/// Maximal number of unconfirmed messages at inbound lane for Cumulus-based parachains.
/// Note: this value is security-relevant, decreasing it should not be done without careful
/// analysis (like the one above).
pub const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 4096;
/// Signed extension that is used by all bridge hubs.
pub type TransactionExtension = SuffixedCommonTransactionExtension<(
BridgeRejectObsoleteHeadersAndMessages,
RefundBridgedParachainMessagesSchema,
)>;
[package]
name = "bp-bridge-hub-kusama"
description = "Primitives of BridgeHubKusama parachain runtime."
version = "0.6.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
# Bridge Dependencies
bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false }
bp-runtime = { path = "../../primitives/runtime", default-features = false }
bp-messages = { path = "../../primitives/messages", default-features = false }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-bridge-hub-cumulus/std",
"bp-messages/std",
"bp-runtime/std",
"frame-support/std",
"sp-api/std",
"sp-runtime/std",
"sp-std/std",
]
// Copyright (C) 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/>.
//! Module with configuration which reflects BridgeHubKusama runtime setup (AccountId, Headers,
//! Hashes...)
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
pub use bp_bridge_hub_cumulus::*;
use bp_messages::*;
use bp_runtime::{
decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, ChainId, Parachain,
};
use frame_support::{
dispatch::DispatchClass,
sp_runtime::{MultiAddress, MultiSigner},
};
use sp_runtime::RuntimeDebug;
/// BridgeHubKusama parachain.
#[derive(RuntimeDebug)]
pub struct BridgeHubKusama;
impl Chain for BridgeHubKusama {
const ID: ChainId = *b"bhks";
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hasher = Hasher;
type Header = Header;
type AccountId = AccountId;
type Balance = Balance;
type Nonce = Nonce;
type Signature = Signature;
fn max_extrinsic_size() -> u32 {
*BlockLength::get().max.get(DispatchClass::Normal)
}
fn max_extrinsic_weight() -> Weight {
BlockWeights::get()
.get(DispatchClass::Normal)
.max_extrinsic
.unwrap_or(Weight::MAX)
}
}
impl Parachain for BridgeHubKusama {
const PARACHAIN_ID: u32 = BRIDGE_HUB_KUSAMA_PARACHAIN_ID;
const MAX_HEADER_SIZE: u32 = MAX_BRIDGE_HUB_HEADER_SIZE;
}
impl ChainWithMessages for BridgeHubKusama {
const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str =
WITH_BRIDGE_HUB_KUSAMA_MESSAGES_PALLET_NAME;
const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce =
MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX;
const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce =
MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX;
}
/// Public key of the chain account that may be used to verify signatures.
pub type AccountSigner = MultiSigner;
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
/// Identifier of BridgeHubKusama in the Kusama relay chain.
pub const BRIDGE_HUB_KUSAMA_PARACHAIN_ID: u32 = 1002;
/// Name of the With-BridgeHubKusama messages pallet instance that is deployed at bridged chains.
pub const WITH_BRIDGE_HUB_KUSAMA_MESSAGES_PALLET_NAME: &str = "BridgeKusamaMessages";
/// Name of the With-BridgeHubKusama bridge-relayers pallet instance that is deployed at bridged
/// chains.
pub const WITH_BRIDGE_HUB_KUSAMA_RELAYERS_PALLET_NAME: &str = "BridgeRelayers";
decl_bridge_finality_runtime_apis!(bridge_hub_kusama);
decl_bridge_messages_runtime_apis!(bridge_hub_kusama);
[package]
name = "bp-bridge-hub-polkadot"
description = "Primitives of BridgeHubPolkadot parachain runtime."
version = "0.6.0"
authors.workspace = true
edition.workspace = true
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
[lints]
workspace = true
[dependencies]
# Bridge Dependencies
bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false }
bp-runtime = { path = "../../primitives/runtime", default-features = false }
bp-messages = { path = "../../primitives/messages", default-features = false }
# Substrate Based Dependencies
frame-support = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-api = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-runtime = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
sp-std = { git = "https://github.com/paritytech/polkadot-sdk", branch = "master", default-features = false }
[features]
default = ["std"]
std = [
"bp-bridge-hub-cumulus/std",
"bp-messages/std",
"bp-runtime/std",
"frame-support/std",
"sp-api/std",
"sp-runtime/std",
"sp-std/std",
]