Skip to content

Commit

Permalink
Generic LaneId for pallet_xcm_bridge_hub
Browse files Browse the repository at this point in the history
  • Loading branch information
bkontur committed Sep 9, 2024
1 parent 14b8469 commit c0c2d54
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 48 deletions.
1 change: 1 addition & 0 deletions bridges/modules/messages/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ pub struct TestPayload {
pub type TestMessageFee = u64;
pub type TestRelayer = u64;
pub type TestDispatchLevelResult = ();
/// Lane identifier type used for tests.
pub type TestLaneIdType = HashedLaneId;

pub struct ThisChain;
Expand Down
32 changes: 16 additions & 16 deletions bridges/modules/xcm-bridge-hub/src/dispatcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@
use crate::{Config, Pallet, LOG_TARGET};

use bp_messages::{
target_chain::{DispatchMessage, MessageDispatch},
LaneId,
};
use bp_messages::target_chain::{DispatchMessage, MessageDispatch};
use bp_runtime::messages::MessageDispatchResult;
use bp_xcm_bridge_hub::{LocalXcmChannelManager, XcmAsPlainPayload};
use codec::{Decode, Encode};
Expand Down Expand Up @@ -58,15 +55,18 @@ where
{
type DispatchPayload = XcmAsPlainPayload;
type DispatchLevelResult = XcmBlobMessageDispatchResult;
type LaneId = T::LaneId;

fn is_active(lane: LaneId) -> bool {
fn is_active(lane: Self::LaneId) -> bool {
Pallet::<T, I>::bridge_by_lane_id(&lane)
.and_then(|(_, bridge)| bridge.bridge_origin_relative_location.try_as().cloned().ok())
.map(|recipient: Location| !T::LocalXcmChannelManager::is_congested(&recipient))
.unwrap_or(false)
}

fn dispatch_weight(message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight {
fn dispatch_weight(
message: &mut DispatchMessage<Self::DispatchPayload, Self::LaneId>,
) -> Weight {
match message.data.payload {
Ok(ref payload) => {
let payload_size = payload.encoded_size().saturated_into();
Expand All @@ -77,14 +77,14 @@ where
}

fn dispatch(
message: DispatchMessage<Self::DispatchPayload>,
message: DispatchMessage<Self::DispatchPayload, Self::LaneId>,
) -> MessageDispatchResult<Self::DispatchLevelResult> {
let payload = match message.data.payload {
Ok(payload) => payload,
Err(e) => {
log::error!(
target: LOG_TARGET,
"dispatch - payload error: {e:?} for lane_id: {} and message_nonce: {:?}",
"dispatch - payload error: {e:?} for lane_id: {:?} and message_nonce: {:?}",
message.key.lane_id,
message.key.nonce
);
Expand All @@ -98,7 +98,7 @@ where
Ok(_) => {
log::debug!(
target: LOG_TARGET,
"dispatch - `DispatchBlob::dispatch_blob` was ok for lane_id: {} and message_nonce: {:?}",
"dispatch - `DispatchBlob::dispatch_blob` was ok for lane_id: {:?} and message_nonce: {:?}",
message.key.lane_id,
message.key.nonce
);
Expand All @@ -107,7 +107,7 @@ where
Err(e) => {
log::error!(
target: LOG_TARGET,
"dispatch - `DispatchBlob::dispatch_blob` failed with error: {e:?} for lane_id: {} and message_nonce: {:?}",
"dispatch - `DispatchBlob::dispatch_blob` failed with error: {e:?} for lane_id: {:?} and message_nonce: {:?}",
message.key.lane_id,
message.key.nonce
);
Expand All @@ -123,13 +123,13 @@ mod tests {
use super::*;
use crate::{mock::*, Bridges, LaneToBridge, LanesManagerOf};

use bp_messages::{target_chain::DispatchMessageData, MessageKey};
use bp_messages::{target_chain::DispatchMessageData, LaneIdType, MessageKey};
use bp_xcm_bridge_hub::{Bridge, BridgeLocations, BridgeState};
use frame_support::assert_ok;
use pallet_bridge_messages::InboundLaneStorage;
use xcm_executor::traits::ConvertLocation;

fn bridge() -> (Box<BridgeLocations>, LaneId) {
fn bridge() -> (Box<BridgeLocations>, TestLaneIdType) {
let origin = OpenBridgeOrigin::sibling_parachain_origin();
let with = bridged_asset_hub_universal_location();
let locations =
Expand Down Expand Up @@ -194,16 +194,16 @@ mod tests {
});
}

fn invalid_message() -> DispatchMessage<Vec<u8>> {
fn invalid_message() -> DispatchMessage<Vec<u8>, TestLaneIdType> {
DispatchMessage {
key: MessageKey { lane_id: LaneId::new(1, 2), nonce: 1 },
key: MessageKey { lane_id: TestLaneIdType::new(1, 2), nonce: 1 },
data: DispatchMessageData { payload: Err(codec::Error::from("test")) },
}
}

fn valid_message() -> DispatchMessage<Vec<u8>> {
fn valid_message() -> DispatchMessage<Vec<u8>, TestLaneIdType> {
DispatchMessage {
key: MessageKey { lane_id: LaneId::new(1, 2), nonce: 1 },
key: MessageKey { lane_id: TestLaneIdType::new(1, 2), nonce: 1 },
data: DispatchMessageData { payload: Ok(vec![42]) },
}
}
Expand Down
14 changes: 7 additions & 7 deletions bridges/modules/xcm-bridge-hub/src/exporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::{BridgeOf, Bridges};

use bp_messages::{
source_chain::{MessagesBridge, OnMessagesDelivered},
LaneId, MessageNonce,
MessageNonce,
};
use bp_xcm_bridge_hub::{BridgeId, BridgeState, LocalXcmChannelManager, XcmAsPlainPayload};
use frame_support::{ensure, traits::Get};
Expand Down Expand Up @@ -62,7 +62,7 @@ where
type Ticket = (
BridgeId,
BridgeOf<T, I>,
<MessagesPallet<T, I> as MessagesBridge<T::OutboundPayload>>::SendMessageArgs,
<MessagesPallet<T, I> as MessagesBridge<T::OutboundPayload, T::LaneId>>::SendMessageArgs,
XcmHash,
);

Expand Down Expand Up @@ -198,8 +198,8 @@ where
}
}

impl<T: Config<I>, I: 'static> OnMessagesDelivered for Pallet<T, I> {
fn on_messages_delivered(lane_id: LaneId, enqueued_messages: MessageNonce) {
impl<T: Config<I>, I: 'static> OnMessagesDelivered<T::LaneId> for Pallet<T, I> {
fn on_messages_delivered(lane_id: T::LaneId, enqueued_messages: MessageNonce) {
Self::on_bridge_messages_delivered(lane_id, enqueued_messages);
}
}
Expand Down Expand Up @@ -273,7 +273,7 @@ impl<T: Config<I>, I: 'static> Pallet<T, I> {
}

/// Must be called whenever we receive a message delivery confirmation.
fn on_bridge_messages_delivered(lane_id: LaneId, enqueued_messages: MessageNonce) {
fn on_bridge_messages_delivered(lane_id: T::LaneId, enqueued_messages: MessageNonce) {
// if the bridge queue is still congested, we don't want to do anything
let is_congested = enqueued_messages > OUTBOUND_LANE_UNCONGESTED_THRESHOLD;
if is_congested {
Expand Down Expand Up @@ -381,7 +381,7 @@ mod tests {
BridgedUniversalDestination::get()
}

fn open_lane() -> (BridgeLocations, LaneId) {
fn open_lane() -> (BridgeLocations, TestLaneIdType) {
// open expected outbound lane
let origin = OpenBridgeOrigin::sibling_parachain_origin();
let with = bridged_asset_hub_universal_location();
Expand Down Expand Up @@ -438,7 +438,7 @@ mod tests {
(*locations, lane_id)
}

fn open_lane_and_send_regular_message() -> (BridgeId, LaneId) {
fn open_lane_and_send_regular_message() -> (BridgeId, TestLaneIdType) {
let (locations, lane_id) = open_lane();

// now let's try to enqueue message using our `ExportXcm` implementation
Expand Down
34 changes: 17 additions & 17 deletions bridges/modules/xcm-bridge-hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]

use bp_messages::{LaneId, LaneIdBytes, LaneState, MessageNonce};
use bp_messages::{LaneState, MessageNonce};
use bp_runtime::{AccountIdOf, BalanceOf, RangeInclusiveExt};
pub use bp_xcm_bridge_hub::{Bridge, BridgeId, BridgeState};
use bp_xcm_bridge_hub::{BridgeLocations, BridgeLocationsError, LocalXcmChannelManager};
Expand Down Expand Up @@ -247,10 +247,13 @@ pub mod pallet {
}

/// An alias for the bridge metadata.
pub type BridgeOf<T, I> = Bridge<ThisChainOf<T, I>>;
pub type BridgeOf<T, I> = Bridge<ThisChainOf<T, I>, LaneIdOf<T, I>>;
/// An alias for this chain.
pub type ThisChainOf<T, I> =
pallet_bridge_messages::ThisChainOf<T, <T as Config<I>>::BridgeMessagesPalletInstance>;
/// An alias for lane identifier type.
type LaneIdOf<T, I> =
<T as BridgeMessagesConfig<<T as Config<I>>::BridgeMessagesPalletInstance>>::LaneId;
/// An alias for the associated lanes manager.
pub type LanesManagerOf<T, I> =
pallet_bridge_messages::LanesManager<T, <T as Config<I>>::BridgeMessagesPalletInstance>;
Expand Down Expand Up @@ -450,7 +453,7 @@ pub mod pallet {
impl<T: Config<I>, I: 'static> Pallet<T, I> {
pub(crate) fn do_open_bridge(
locations: Box<BridgeLocations>,
lane_id: LaneId,
lane_id: T::LaneId,
create_lanes: bool,
) -> Result<(), DispatchError> {
// reserve balance on the origin's sovereign account (if needed)
Expand Down Expand Up @@ -590,7 +593,7 @@ pub mod pallet {
}

/// Return bridge metadata by lane_id
pub fn bridge_by_lane_id(lane_id: &LaneId) -> Option<(BridgeId, BridgeOf<T, I>)> {
pub fn bridge_by_lane_id(lane_id: &T::LaneId) -> Option<(BridgeId, BridgeOf<T, I>)> {
LaneToBridge::<T, I>::get(lane_id)
.and_then(|bridge_id| Self::bridge(&bridge_id).map(|bridge| (bridge_id, bridge)))
}
Expand Down Expand Up @@ -638,7 +641,7 @@ pub mod pallet {
pub fn do_try_state_for_bridge(
bridge_id: BridgeId,
bridge: BridgeOf<T, I>,
) -> Result<LaneId, sp_runtime::TryRuntimeError> {
) -> Result<T::LaneId, sp_runtime::TryRuntimeError> {
log::info!(target: LOG_TARGET, "Checking `do_try_state_for_bridge` for bridge_id: {bridge_id:?} and bridge: {bridge:?}");

// check `BridgeId` points to the same `LaneId` and vice versa.
Expand Down Expand Up @@ -716,7 +719,7 @@ pub mod pallet {
/// All registered `lane_id` and `bridge_id` mappings.
#[pallet::storage]
pub type LaneToBridge<T: Config<I>, I: 'static = ()> =
StorageMap<_, Identity, LaneId, BridgeId>;
StorageMap<_, Identity, T::LaneId, BridgeId>;

#[pallet::genesis_config]
#[derive(DefaultNoBound)]
Expand All @@ -726,7 +729,7 @@ pub mod pallet {
/// Keep in mind that we are **NOT** reserving any amount for the bridges opened at
/// genesis. We are **NOT** opening lanes, used by this bridge. It all must be done using
/// other pallets genesis configuration or some other means.
pub opened_bridges: Vec<(Location, InteriorLocation, Option<LaneId>)>,
pub opened_bridges: Vec<(Location, InteriorLocation, Option<T::LaneId>)>,
/// Dummy marker.
#[serde(skip)]
pub _phantom: sp_std::marker::PhantomData<(T, I)>,
Expand Down Expand Up @@ -805,14 +808,14 @@ pub mod pallet {
/// Universal location of remote bridge endpoint.
remote_endpoint: Box<InteriorLocation>,
/// Lane identifier.
lane_id: LaneIdBytes,
lane_id: T::LaneId,
},
/// Bridge is going to be closed, but not yet fully pruned from the runtime storage.
ClosingBridge {
/// Bridge identifier.
bridge_id: BridgeId,
/// Lane identifier.
lane_id: LaneIdBytes,
lane_id: T::LaneId,
/// Number of pruned messages during the close call.
pruned_messages: MessageNonce,
/// Number of enqueued messages that need to be pruned in follow up calls.
Expand All @@ -824,7 +827,7 @@ pub mod pallet {
/// Bridge identifier.
bridge_id: BridgeId,
/// Lane identifier.
lane_id: LaneIdBytes,
lane_id: T::LaneId,
/// Amount of deposit released.
bridge_deposit: BalanceOf<ThisChainOf<T, I>>,
/// Number of pruned messages during the close call.
Expand Down Expand Up @@ -858,12 +861,11 @@ pub mod pallet {
#[cfg(test)]
mod tests {
use super::*;
use bp_messages::LaneIdType;
use mock::*;

use bp_messages::LaneId;
use frame_support::{assert_err, assert_noop, assert_ok, traits::fungible::Mutate, BoundedVec};
use frame_system::{EventRecord, Phase};
use sp_core::H256;
use sp_runtime::TryRuntimeError;

fn fund_origin_sovereign_account(locations: &BridgeLocations, balance: Balance) -> AccountId {
Expand Down Expand Up @@ -920,7 +922,7 @@ mod tests {
mock_open_bridge_from_with(origin, deposit, bridged_asset_hub_universal_location())
}

fn enqueue_message(lane: LaneId) {
fn enqueue_message(lane: TestLaneIdType) {
let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
lanes_manager
.active_outbound_lane(lane)
Expand Down Expand Up @@ -1465,8 +1467,6 @@ mod tests {

#[test]
fn do_try_state_works() {
use sp_runtime::Either;

let bridge_origin_relative_location = SiblingLocation::get();
let bridge_origin_universal_location = SiblingUniversalLocation::get();
let bridge_destination_universal_location = BridgedUniversalDestination::get();
Expand All @@ -1480,8 +1480,8 @@ mod tests {
&bridge_destination_universal_location,
);
let bridge_id_mismatch = BridgeId::new(&InteriorLocation::Here, &InteriorLocation::Here);
let lane_id = LaneId::from_inner(Either::Left(H256::default()));
let lane_id_mismatch = LaneId::from_inner(Either::Left(H256::from([1u8; 32])));
let lane_id = TestLaneIdType::new(1, 2);
let lane_id_mismatch = TestLaneIdType::new(3, 4);

let test_bridge_state = |id,
bridge,
Expand Down
3 changes: 1 addition & 2 deletions bridges/modules/xcm-bridge-hub/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
//! A module that is responsible for migration of storage.
use crate::{Config, Pallet, LOG_TARGET};
use bp_messages::LaneId;
use frame_support::{
traits::{Get, OnRuntimeUpgrade, StorageVersion},
weights::Weight,
Expand Down Expand Up @@ -52,7 +51,7 @@ pub struct OpenBridgeForLane<
impl<
T: Config<I>,
I: 'static,
Lane: Get<LaneId>,
Lane: Get<T::LaneId>,
CreateLane: Get<bool>,
SourceRelativeLocation: Get<Location>,
BridgedUniversalLocation: Get<InteriorLocation>,
Expand Down
16 changes: 11 additions & 5 deletions bridges/modules/xcm-bridge-hub/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate as pallet_xcm_bridge_hub;

use bp_messages::{
target_chain::{DispatchMessage, MessageDispatch},
ChainWithMessages, LaneId, MessageNonce,
ChainWithMessages, HashedLaneId, MessageNonce,
};
use bp_runtime::{messages::MessageDispatchResult, Chain, ChainId, HashOf};
use bp_xcm_bridge_hub::{BridgeId, LocalXcmChannelManager};
Expand Down Expand Up @@ -49,6 +49,8 @@ use xcm_executor::XcmExecutor;
pub type AccountId = AccountId32;
pub type Balance = u64;
type Block = frame_system::mocking::MockBlock<TestRuntime>;
/// Lane identifier type used for tests.
pub type TestLaneIdType = HashedLaneId;

pub const SIBLING_ASSET_HUB_ID: u32 = 2001;
pub const THIS_BRIDGE_HUB_ID: u32 = 2002;
Expand Down Expand Up @@ -92,6 +94,7 @@ impl pallet_bridge_messages::Config for TestRuntime {

type OutboundPayload = Vec<u8>;
type InboundPayload = Vec<u8>;
type LaneId = HashedLaneId;

type DeliveryPayments = ();
type DeliveryConfirmationPayments = ();
Expand Down Expand Up @@ -523,26 +526,29 @@ impl bp_header_chain::HeaderChain<BridgedUnderlyingChain> for BridgedHeaderChain
pub struct TestMessageDispatch;

impl TestMessageDispatch {
pub fn deactivate(lane: LaneId) {
pub fn deactivate(lane: TestLaneIdType) {
frame_support::storage::unhashed::put(&(b"inactive", lane).encode()[..], &false);
}
}

impl MessageDispatch for TestMessageDispatch {
type DispatchPayload = Vec<u8>;
type DispatchLevelResult = ();
type LaneId = TestLaneIdType;

fn is_active(lane: LaneId) -> bool {
fn is_active(lane: TestLaneIdType) -> bool {
frame_support::storage::unhashed::take::<bool>(&(b"inactive", lane).encode()[..]) !=
Some(false)
}

fn dispatch_weight(_message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight {
fn dispatch_weight(
_message: &mut DispatchMessage<Self::DispatchPayload, Self::LaneId>,
) -> Weight {
Weight::zero()
}

fn dispatch(
_: DispatchMessage<Self::DispatchPayload>,
_: DispatchMessage<Self::DispatchPayload, Self::LaneId>,
) -> MessageDispatchResult<Self::DispatchLevelResult> {
MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: () }
}
Expand Down
1 change: 1 addition & 0 deletions bridges/primitives/messages/src/lane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pub trait LaneIdType:
+ Debug
+ PartialEq
+ Eq
+ Ord
+ TypeInfo
+ MaxEncodedLen
+ Serialize
Expand Down
Loading

0 comments on commit c0c2d54

Please sign in to comment.