Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement ExportXcm and MessageDispatch for pallet-xcm-bridge-hub #2285

Merged
merged 2 commits into from
Jul 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion modules/xcm-bridge-hub/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", d
# Polkadot Dependencies

xcm = { git = "https://github.com/paritytech/polkadot", branch = "master", default-features = false }
xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "master" }
xcm-executor = { git = "https://github.com/paritytech/polkadot", branch = "master", default-features = false }

[dev-dependencies]
pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" }
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "master" }
sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" }
xcm-builder = { git = "https://github.com/paritytech/polkadot", branch = "master" }

[features]
default = ["std"]
Expand All @@ -52,6 +52,7 @@ std = [
"sp-runtime/std",
"sp-std/std",
"xcm/std",
"xcm-builder/std",
"xcm-executor/std",
]
runtime-benchmarks = []
103 changes: 103 additions & 0 deletions modules/xcm-bridge-hub/src/dispatcher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file is almost 1:1 copy of the XcmBlobMessageDispatch. The only difference is that it is now implemented for the Pallet, instead of a dedicated struct

// 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 inbound
//! bridge messages dispatcher. Internally, it just forwards inbound blob to the
//! XCM-level blob dispatcher, which pushes message to some other queue (e.g.
//! to HRMP queue with the sibling target chain).

use crate::{Config, Pallet, XcmAsPlainPayload, LOG_TARGET};

use bp_messages::target_chain::{DispatchMessage, MessageDispatch};
use bp_runtime::messages::MessageDispatchResult;
use codec::{Decode, Encode};
use frame_support::{dispatch::Weight, CloneNoBound, EqNoBound, PartialEqNoBound};
use pallet_bridge_messages::{Config as BridgeMessagesConfig, WeightInfoExt};
use scale_info::TypeInfo;
use sp_runtime::SaturatedConversion;
use xcm_builder::{DispatchBlob, DispatchBlobError};

/// Message dispatch result type for single message.
#[derive(CloneNoBound, EqNoBound, PartialEqNoBound, Encode, Decode, Debug, TypeInfo)]
pub enum XcmBlobMessageDispatchResult {
/// We've been unable to decode message payload.
InvalidPayload,
/// Message has been dispatched.
Dispatched,
/// Message has **NOT** been dispatched because of given error.
NotDispatched(#[codec(skip)] Option<DispatchBlobError>),
}

/// An easy way to access associated messages pallet weights.
type MessagesPalletWeights<T, I> =
<T as BridgeMessagesConfig<<T as Config<I>>::BridgeMessagesPalletInstance>>::WeightInfo;

impl<T: Config<I>, I: 'static> MessageDispatch for Pallet<T, I>
where
T: BridgeMessagesConfig<InboundPayload = XcmAsPlainPayload>,
{
type DispatchPayload = XcmAsPlainPayload;
type DispatchLevelResult = XcmBlobMessageDispatchResult;

fn dispatch_weight(message: &mut DispatchMessage<Self::DispatchPayload>) -> Weight {
match message.data.payload {
Ok(ref payload) => {
let payload_size = payload.encoded_size().saturated_into();
MessagesPalletWeights::<T, I>::message_dispatch_weight(payload_size)
},
Err(_) => Weight::zero(),
}
}

fn dispatch(
message: DispatchMessage<Self::DispatchPayload>,
) -> MessageDispatchResult<Self::DispatchLevelResult> {
let payload = match message.data.payload {
Ok(payload) => payload,
Err(e) => {
log::error!(
target: LOG_TARGET,
"[XcmBlobMessageDispatch] payload error: {:?} - message_nonce: {:?}",
e,
message.key.nonce
);
return MessageDispatchResult {
unspent_weight: Weight::zero(),
dispatch_level_result: XcmBlobMessageDispatchResult::InvalidPayload,
}
},
};
let dispatch_level_result = match T::BlobDispatcher::dispatch_blob(payload) {
Ok(_) => {
log::debug!(
target: LOG_TARGET,
"[XcmBlobMessageDispatch] DispatchBlob::dispatch_blob was ok - message_nonce: {:?}",
message.key.nonce
);
XcmBlobMessageDispatchResult::Dispatched
},
Err(e) => {
log::error!(
target: LOG_TARGET,
"[XcmBlobMessageDispatch] DispatchBlob::dispatch_blob failed, error: {:?} - message_nonce: {:?}",
e, message.key.nonce
);
XcmBlobMessageDispatchResult::NotDispatched(Some(e))
},
};
MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result }
}
}
184 changes: 184 additions & 0 deletions modules/xcm-bridge-hub/src/exporter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here, I had to change the original XcmBlobHaulerAdapter a bit, because it doesn't work well with dynamic lanes. So it needs more careful review

// 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.

use crate::{Config, Pallet, XcmAsPlainPayload, LOG_TARGET};

use bp_messages::{source_chain::MessagesBridge, LaneId};
use frame_support::traits::Get;
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`.
type PalletAsHaulBlobExporter<T, I> = HaulBlobExporter<
DummyHaulBlob,
<T as Config<I>>::BridgedNetworkId,
<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 as Config<I>>::BridgeMessagesPalletInstance,
OutboundPayload = XcmAsPlainPayload,
>,
{
type Ticket = (LaneId, XcmAsPlainPayload, XcmHash);

fn validate(
network: NetworkId,
channel: u32,
universal_source: &mut Option<InteriorMultiLocation>,
destination: &mut Option<InteriorMultiLocation>,
message: &mut Option<Xcm<()>>,
) -> Result<(Self::Ticket, MultiAssets), SendError> {
// `HaulBlobExporter` may consume the `universal_source` and `destination` arguments, so
// let's save them before
let bridge_origin_universal_location =
universal_source.clone().take().ok_or(SendError::MissingArgument)?;
let bridge_destination_interior_location =
destination.clone().take().ok_or(SendError::MissingArgument)?;

// 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,
)?;

// ok - now we know that the message may be routed by the pallet, let's prepare the
// destination universal location
let mut bridge_destination_universal_location =
X1(GlobalConsensus(T::BridgedNetworkId::get()));
bridge_destination_universal_location
.append_with(bridge_destination_interior_location)
.map_err(|_| SendError::Unroutable)?;

// .. and the origin relative location
let bridge_origin_relative_location =
bridge_origin_universal_location.relative_to(&T::UniversalLocation::get());

// then we are able to compute the lane id used to send messages
let bridge_locations = Self::bridge_locations(
Box::new(bridge_origin_relative_location),
Box::new(bridge_destination_universal_location.into()),
)
.map_err(|_| SendError::Unroutable)?;

Ok(((bridge_locations.lane_id, blob, id), price))
}

fn deliver(
(lane_id, blob, id): (LaneId, XcmAsPlainPayload, XcmHash),
) -> Result<XcmHash, SendError> {
let send_result = MessagesPallet::<T, I>::send_message(lane_id, blob);

match send_result {
Ok(artifacts) => {
log::info!(
target: LOG_TARGET,
"XCM message {:?} has been enqueued at lane {:?} with nonce {}",
id,
lane_id,
artifacts.nonce,
);
},
Err(error) => {
log::debug!(
target: LOG_TARGET,
"XCM message {:?} has been dropped because of bridge error {:?} on lane {:?}",
id,
error,
lane_id,
);
return Err(SendError::Transport("BridgeSendError"))
},
}

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`.
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::*, LanesManagerOf};

use xcm_executor::traits::export_xcm;

#[test]
fn proper_lane_is_used_by_export_xcm() {
run_test(|| {
// open expected outbound lane
let origin = OpenBridgeOrigin::sibling_parachain_origin();
let with = bridged_asset_hub_location();
let locations =
XcmOverBridge::bridge_locations_from_origin(origin, Box::new(with.into())).unwrap();

let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
lanes_manager.create_outbound_lane(locations.lane_id).unwrap();
assert!(lanes_manager
.active_outbound_lane(locations.lane_id)
.unwrap()
.queued_messages()
.is_empty());

// now let's try to enqueue message using our `ExportXcm` implementation
export_xcm::<XcmOverBridge>(
BridgedRelayNetwork::get(),
0,
locations.bridge_origin_universal_location,
locations.bridge_destination_universal_location.split_first().0,
vec![Instruction::ClearOrigin].into(),
)
.unwrap();

// double check that the message has been pushed to the expected lane
// (it should already been checked during `send_message` call)
assert!(!lanes_manager
.active_outbound_lane(locations.lane_id)
.unwrap()
.queued_messages()
.is_empty());
});
}
}
Loading