-
Notifications
You must be signed in to change notification settings - Fork 129
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
// 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 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 } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,184 @@ | ||
// Copyright 2019-2021 Parity Technologies (UK) Ltd. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here, I had to change the original |
||
// 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()); | ||
}); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 thePallet
, instead of a dedicated struct