From fd5f8c2d0b3616163fb6f3a57a1fe6afca117d8a Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Thu, 20 Jan 2022 16:24:19 +0100 Subject: [PATCH 01/73] send_xcm returns message hash --- runtime/common/src/xcm_sender.rs | 4 ++- runtime/test-runtime/src/xcm_config.rs | 7 ++--- xcm/pallet-xcm-benchmarks/src/mock.rs | 5 ++-- xcm/pallet-xcm/src/lib.rs | 6 ++--- xcm/pallet-xcm/src/mock.rs | 11 ++++---- xcm/src/v3/mod.rs | 4 +-- xcm/src/v3/traits.rs | 11 +++++--- xcm/xcm-builder/src/mock.rs | 6 ++--- xcm/xcm-builder/tests/mock/mod.rs | 6 +++-- xcm/xcm-executor/src/lib.rs | 37 +++++++++++++++----------- xcm/xcm-simulator/src/lib.rs | 16 +++++------ 11 files changed, 65 insertions(+), 48 deletions(-) diff --git a/runtime/common/src/xcm_sender.rs b/runtime/common/src/xcm_sender.rs index 2d75edfd4571..b9e5d3e42c7f 100644 --- a/runtime/common/src/xcm_sender.rs +++ b/runtime/common/src/xcm_sender.rs @@ -35,13 +35,15 @@ impl SendXcm let versioned_xcm = W::wrap_version(&dest, msg).map_err(|()| SendError::DestinationUnsupported)?; let config = >::config(); + let encoded = versioned_xcm.encode(); + let hash = sp_io::hashing::blake2_256(&encoded[..]); >::queue_downward_message( &config, id.into(), versioned_xcm.encode(), ) .map_err(Into::::into)?; - Ok(()) + Ok(hash) }, dest => Err(SendError::CannotReachDestination(dest, msg)), } diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 77dded583479..2ab53dd7cc8a 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -15,7 +15,8 @@ // along with Polkadot. If not, see . use frame_support::{parameter_types, traits::Everything, weights::Weight}; -use xcm::latest::prelude::*; +use xcm::prelude::*; +use parity_scale_codec::Encode; use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds, SignedToAccountId32}; use xcm_executor::{ traits::{InvertLocation, TransactAsset, WeightTrader}, @@ -37,8 +38,8 @@ pub type LocalOriginToLocation = ( pub struct DoNothingRouter; impl SendXcm for DoNothingRouter { - fn send_xcm(_dest: impl Into, _msg: Xcm<()>) -> SendResult { - Ok(()) + fn send_xcm(_dest: impl Into, msg: Xcm<()>) -> SendResult { + Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index d59cf3387268..f15d89252d01 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -17,12 +17,13 @@ use crate::*; use frame_support::{parameter_types, weights::Weight}; use xcm_executor::traits::FilterAssetLocation; +use xcm::VersionedXcm; // An xcm sender/receiver akin to > /dev/null pub struct DevNull; impl xcm::opaque::latest::SendXcm for DevNull { - fn send_xcm(_: impl Into, _: Xcm<()>) -> SendResult { - Ok(()) + fn send_xcm(_: impl Into, msg: Xcm<()>) -> SendResult { + Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index 5df4aade835a..4d4b5e994beb 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -954,7 +954,7 @@ pub mod pallet { let response = Response::Version(xcm_version); let message = Xcm(vec![QueryResponse { query_id, response, max_weight }]); let event = match T::XcmRouter::send_xcm(new_key.clone(), message) { - Ok(()) => { + Ok(_) => { let value = (query_id, max_weight, xcm_version); VersionNotifyTargets::::insert(XCM_VERSION, key, value); Event::VersionChangeNotified(new_key, xcm_version) @@ -1001,7 +1001,7 @@ pub mod pallet { let message = Xcm(vec![QueryResponse { query_id, response, max_weight }]); let event = match T::XcmRouter::send_xcm(new_key.clone(), message) { - Ok(()) => { + Ok(_) => { VersionNotifyTargets::::insert( XCM_VERSION, versioned_key, @@ -1061,7 +1061,7 @@ pub mod pallet { interior: impl Into, dest: impl Into, mut message: Xcm<()>, - ) -> Result<(), SendError> { + ) -> SendResult { let interior = interior.into(); let dest = dest.into(); if interior != Junctions::Here { diff --git a/xcm/pallet-xcm/src/mock.rs b/xcm/pallet-xcm/src/mock.rs index af9ef8f98548..6cf471ee3cb2 100644 --- a/xcm/pallet-xcm/src/mock.rs +++ b/xcm/pallet-xcm/src/mock.rs @@ -20,7 +20,7 @@ use polkadot_runtime_parachains::origin; use sp_core::H256; use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; pub use sp_std::{cell::RefCell, fmt::Debug, marker::PhantomData}; -use xcm::latest::prelude::*; +use xcm::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, Case, ChildParachainAsNative, ChildParachainConvertsVia, @@ -29,6 +29,7 @@ use xcm_builder::{ SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, }; use xcm_executor::XcmExecutor; +use codec::Encode; use crate as pallet_xcm; @@ -148,8 +149,8 @@ pub(crate) fn take_sent_xcm() -> Vec<(MultiLocation, Xcm<()>)> { pub struct TestSendXcm; impl SendXcm for TestSendXcm { fn send_xcm(dest: impl Into, msg: Xcm<()>) -> SendResult { - SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg))); - Ok(()) + SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg.clone()))); + Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } /// Sender that returns error if `X8` junction and stops routing @@ -160,8 +161,8 @@ impl SendXcm for TestSendXcmErrX8 { if dest.len() == 8 { Err(SendError::Transport("Destination location full")) } else { - SENT_XCM.with(|q| q.borrow_mut().push((dest, msg))); - Ok(()) + SENT_XCM.with(|q| q.borrow_mut().push((dest, msg.clone()))); + Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } } diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 959847aebee5..03bc20b36518 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -35,7 +35,7 @@ pub use multiasset::{ AssetId, AssetInstance, Fungibility, MultiAsset, MultiAssetFilter, MultiAssets, WildFungibility, WildMultiAsset, }; -pub use traits::{Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm}; +pub use traits::{Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm, XcmHash}; // These parts of XCM v2 are unchanged in XCM v3, and are re-imported here. pub use super::v2::{ Ancestor, AncestorThen, BodyId, BodyPart, InteriorMultiLocation, Junction, Junctions, @@ -133,7 +133,7 @@ pub mod prelude { WeightLimit::{self, *}, WildFungibility::{self, Fungible as WildFungible, NonFungible as WildNonFungible}, WildMultiAsset::{self, *}, - XcmWeightInfo, VERSION as XCM_VERSION, + XcmHash, XcmWeightInfo, VERSION as XCM_VERSION, }; } pub use super::{Instruction, Xcm}; diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 2d4e8ff2325f..6fce201bc348 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -276,8 +276,11 @@ pub enum SendError { ExceedsMaxMessageSize, } +/// A hash type for identifying messages. +pub type XcmHash = [u8; 32]; + /// Result value when attempting to send an XCM message. -pub type SendResult = result::Result<(), SendError>; +pub type SendResult = result::Result; /// Utility for sending an XCM message. /// @@ -289,6 +292,7 @@ pub type SendResult = result::Result<(), SendError>; /// # Example /// ```rust /// # use xcm::v3::prelude::*; +/// # use xcm::VersionedXcm; /// # use parity_scale_codec::Encode; /// /// /// A sender that only passes the message through and does nothing. @@ -304,7 +308,7 @@ pub type SendResult = result::Result<(), SendError>; /// impl SendXcm for Sender2 { /// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { /// if let MultiLocation { parents: 0, interior: X2(j1, j2) } = destination.into() { -/// Ok(()) +/// Ok(VersionedXcm::from(message).using_encoded(sp_io::hashing::blake2_256)) /// } else { /// Err(SendError::Unroutable) /// } @@ -317,7 +321,8 @@ pub type SendResult = result::Result<(), SendError>; /// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { /// let destination = destination.into(); /// match destination { -/// MultiLocation { parents: 1, interior: Here } => Ok(()), +/// MultiLocation { parents: 1, interior: Here } +/// => Ok(VersionedXcm::from(message).using_encoded(sp_io::hashing::blake2_256)) /// _ => Err(SendError::CannotReachDestination(destination, message)), /// } /// } diff --git a/xcm/xcm-builder/src/mock.rs b/xcm/xcm-builder/src/mock.rs index d88df21050b6..ff217c705989 100644 --- a/xcm/xcm-builder/src/mock.rs +++ b/xcm/xcm-builder/src/mock.rs @@ -35,7 +35,7 @@ pub use sp_std::{ fmt::Debug, marker::PhantomData, }; -pub use xcm::latest::prelude::*; +pub use xcm::prelude::*; pub use xcm_executor::{ traits::{ConvertOrigin, FilterAssetLocation, InvertLocation, OnResponse, TransactAsset}, Assets, Config, @@ -109,8 +109,8 @@ pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> { pub struct TestSendXcm; impl SendXcm for TestSendXcm { fn send_xcm(dest: impl Into, msg: opaque::Xcm) -> SendResult { - SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg))); - Ok(()) + SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg.clone()))); + Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index d2b2152aedb7..1cfd3c16525d 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -22,10 +22,12 @@ use frame_support::{ use sp_core::H256; use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; use sp_std::cell::RefCell; +use parity_scale_codec::Encode; use polkadot_parachain::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; use xcm::latest::{opaque, prelude::*}; +use xcm::VersionedXcm; use xcm_executor::XcmExecutor; use xcm_builder::{ @@ -48,8 +50,8 @@ pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> { pub struct TestSendXcm; impl SendXcm for TestSendXcm { fn send_xcm(dest: impl Into, msg: opaque::Xcm) -> SendResult { - SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg))); - Ok(()) + SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg.clone()))); + Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 33fc376e39c2..2bb474b033c5 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -25,12 +25,8 @@ use frame_support::{ use parity_scale_codec::Encode; use sp_runtime::traits::Saturating; use sp_std::{marker::PhantomData, prelude::*}; -use xcm::latest::{ - Error as XcmError, ExecuteXcm, - Instruction::{self, *}, - MaybeErrorCode, MultiAsset, MultiAssets, MultiLocation, Outcome, PalletInfo, QueryResponseInfo, - Response, SendXcm, Xcm, -}; +use xcm::latest::prelude::*; +use xcm::latest::{MaybeErrorCode, PalletInfo}; pub mod traits; use traits::{ @@ -336,7 +332,8 @@ impl XcmExecutor { assets.reanchor(&dest, &ancestry).map_err(|()| XcmError::MultiLocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message)).map_err(Into::into) + Config::XcmSender::send_xcm(dest, Xcm(message))?; + Ok(()) }, ReceiveTeleportedAsset(assets) => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); @@ -410,7 +407,8 @@ impl XcmExecutor { ReportError(response_info) => { // Report the given result by sending a QueryResponse XCM to a previously given outcome // destination if one was registered. - Self::respond(Response::ExecutionResult(self.error), response_info) + Self::respond(Response::ExecutionResult(self.error), response_info)?; + Ok(()) }, DepositAsset { assets, beneficiary } => { let deposited = self.holding.saturating_take(assets); @@ -429,7 +427,8 @@ impl XcmExecutor { let assets = Self::reanchored(deposited, &dest, None); let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message)).map_err(Into::into) + Config::XcmSender::send_xcm(dest, Xcm(message))?; + Ok(()) }, InitiateReserveWithdraw { assets, reserve, xcm } => { // Note that here we are able to place any assets which could not be reanchored @@ -441,7 +440,8 @@ impl XcmExecutor { ); let mut message = vec![WithdrawAsset(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(reserve, Xcm(message)).map_err(Into::into) + Config::XcmSender::send_xcm(reserve, Xcm(message))?; + Ok(()) }, InitiateTeleport { assets, dest, xcm } => { // We must do this first in order to resolve wildcards. @@ -454,14 +454,16 @@ impl XcmExecutor { let assets = Self::reanchored(assets, &dest, None); let mut message = vec![ReceiveTeleportedAsset(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message)).map_err(Into::into) + Config::XcmSender::send_xcm(dest, Xcm(message))?; + Ok(()) }, ReportHolding { response_info, assets } => { // Note that we pass `None` as `maybe_failed_bin` since no assets were ever removed // from Holding. let assets = Self::reanchored(self.holding.min(&assets), &response_info.destination, None); - Self::respond(Response::Assets(assets), response_info) + Self::respond(Response::Assets(assets), response_info)?; + Ok(()) }, BuyExecution { fees, weight_limit } => { // There is no need to buy any weight is `weight_limit` is `Unlimited` since it @@ -551,7 +553,8 @@ impl XcmExecutor { let response = Response::PalletsInfo(pallets); let instruction = QueryResponse { query_id, response, max_weight }; let message = Xcm(vec![instruction]); - Config::XcmSender::send_xcm(destination, message).map_err(Into::into) + Config::XcmSender::send_xcm(destination, message)?; + Ok(()) }, ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { let pallet = Config::PalletInstancesInfo::infos() @@ -566,8 +569,10 @@ impl XcmExecutor { ensure!(minor >= min_crate_minor, XcmError::VersionIncompatible); Ok(()) }, - ReportTransactStatus(response_info) => - Self::respond(Response::DispatchResult(self.transact_status.clone()), response_info), + ReportTransactStatus(response_info) => { + Self::respond(Response::DispatchResult(self.transact_status.clone()), response_info)?; + Ok(()) + }, ClearTransactStatus => { self.transact_status = Default::default(); Ok(()) @@ -580,7 +585,7 @@ impl XcmExecutor { } /// Send a bare `QueryResponse` message containing `response` informed by the given `info`. - fn respond(response: Response, info: QueryResponseInfo) -> Result<(), XcmError> { + fn respond(response: Response, info: QueryResponseInfo) -> Result { let QueryResponseInfo { destination, query_id, max_weight } = info; let instruction = QueryResponse { query_id, response, max_weight }; let message = Xcm(vec![instruction]); diff --git a/xcm/xcm-simulator/src/lib.rs b/xcm/xcm-simulator/src/lib.rs index 5e563e153dba..d856041b47bc 100644 --- a/xcm/xcm-simulator/src/lib.rs +++ b/xcm/xcm-simulator/src/lib.rs @@ -297,20 +297,20 @@ macro_rules! decl_test_network { impl> $crate::SendXcm for ParachainXcmRouter { fn send_xcm(destination: impl Into<$crate::MultiLocation>, message: $crate::Xcm<()>) -> $crate::SendResult { - use $crate::{UmpSink, XcmpMessageHandlerT}; + use $crate::{UmpSink, XcmpMessageHandlerT, Encode}; let destination = destination.into(); match destination.interior() { $crate::Junctions::Here if destination.parent_count() == 1 => { $crate::PARA_MESSAGE_BUS.with( - |b| b.borrow_mut().push_back((T::get(), destination, message))); - Ok(()) + |b| b.borrow_mut().push_back((T::get(), destination, message.clone()))); + Ok(message.using_encoded(sp_io::hashing::blake2_256)) }, $( $crate::X1($crate::Parachain(id)) if *id == $para_id && destination.parent_count() == 1 => { $crate::PARA_MESSAGE_BUS.with( - |b| b.borrow_mut().push_back((T::get(), destination, message))); - Ok(()) + |b| b.borrow_mut().push_back((T::get(), destination, message.clone()))); + Ok(message.using_encoded(sp_io::hashing::blake2_256)) }, )* _ => Err($crate::SendError::CannotReachDestination(destination, message)), @@ -322,15 +322,15 @@ macro_rules! decl_test_network { pub struct RelayChainXcmRouter; impl $crate::SendXcm for RelayChainXcmRouter { fn send_xcm(destination: impl Into<$crate::MultiLocation>, message: $crate::Xcm<()>) -> $crate::SendResult { - use $crate::DmpMessageHandlerT; + use $crate::{DmpMessageHandlerT, Encode}; let destination = destination.into(); match destination.interior() { $( $crate::X1($crate::Parachain(id)) if *id == $para_id && destination.parent_count() == 0 => { $crate::RELAY_MESSAGE_BUS.with( - |b| b.borrow_mut().push_back((destination, message))); - Ok(()) + |b| b.borrow_mut().push_back((destination, message.clone()))); + Ok(message.using_encoded(sp_io::hashing::blake2_256)) }, )* _ => Err($crate::SendError::Unroutable), From 1f5fdf4ec8eeb1614f49c9fb47c0e5b2fcc43dc8 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 20 Jan 2022 16:48:25 -0800 Subject: [PATCH 02/73] cargo fmt --- runtime/test-runtime/src/xcm_config.rs | 2 +- xcm/pallet-xcm-benchmarks/src/mock.rs | 2 +- xcm/pallet-xcm/src/mock.rs | 2 +- xcm/xcm-builder/tests/mock/mod.rs | 8 +++++--- xcm/xcm-executor/src/lib.rs | 8 +++++--- 5 files changed, 13 insertions(+), 9 deletions(-) diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 2ab53dd7cc8a..0fc52c687cc6 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -15,8 +15,8 @@ // along with Polkadot. If not, see . use frame_support::{parameter_types, traits::Everything, weights::Weight}; -use xcm::prelude::*; use parity_scale_codec::Encode; +use xcm::prelude::*; use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds, SignedToAccountId32}; use xcm_executor::{ traits::{InvertLocation, TransactAsset, WeightTrader}, diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index f15d89252d01..2451cdeef253 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -16,8 +16,8 @@ use crate::*; use frame_support::{parameter_types, weights::Weight}; -use xcm_executor::traits::FilterAssetLocation; use xcm::VersionedXcm; +use xcm_executor::traits::FilterAssetLocation; // An xcm sender/receiver akin to > /dev/null pub struct DevNull; diff --git a/xcm/pallet-xcm/src/mock.rs b/xcm/pallet-xcm/src/mock.rs index 6cf471ee3cb2..9a0325588ce6 100644 --- a/xcm/pallet-xcm/src/mock.rs +++ b/xcm/pallet-xcm/src/mock.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use codec::Encode; use frame_support::{construct_runtime, parameter_types, traits::Everything, weights::Weight}; use polkadot_parachain::primitives::Id as ParaId; use polkadot_runtime_parachains::origin; @@ -29,7 +30,6 @@ use xcm_builder::{ SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, }; use xcm_executor::XcmExecutor; -use codec::Encode; use crate as pallet_xcm; diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index 1cfd3c16525d..b2e96340c1a5 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -19,15 +19,17 @@ use frame_support::{ traits::{Everything, Nothing}, weights::Weight, }; +use parity_scale_codec::Encode; use sp_core::H256; use sp_runtime::{testing::Header, traits::IdentityLookup, AccountId32}; use sp_std::cell::RefCell; -use parity_scale_codec::Encode; use polkadot_parachain::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; -use xcm::latest::{opaque, prelude::*}; -use xcm::VersionedXcm; +use xcm::{ + latest::{opaque, prelude::*}, + VersionedXcm, +}; use xcm_executor::XcmExecutor; use xcm_builder::{ diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 2bb474b033c5..80f9a387d55c 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -25,8 +25,7 @@ use frame_support::{ use parity_scale_codec::Encode; use sp_runtime::traits::Saturating; use sp_std::{marker::PhantomData, prelude::*}; -use xcm::latest::prelude::*; -use xcm::latest::{MaybeErrorCode, PalletInfo}; +use xcm::latest::{prelude::*, MaybeErrorCode, PalletInfo}; pub mod traits; use traits::{ @@ -570,7 +569,10 @@ impl XcmExecutor { Ok(()) }, ReportTransactStatus(response_info) => { - Self::respond(Response::DispatchResult(self.transact_status.clone()), response_info)?; + Self::respond( + Response::DispatchResult(self.transact_status.clone()), + response_info, + )?; Ok(()) }, ClearTransactStatus => { From 1f2d3dc530897225dd3dab7d70bb31644eafd878 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 20 Jan 2022 18:10:04 -0800 Subject: [PATCH 03/73] Create topic register and instructions --- xcm/src/v3/mod.rs | 20 ++++++++++++++++++++ xcm/xcm-executor/src/lib.rs | 10 ++++++++++ 2 files changed, 30 insertions(+) diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 03bc20b36518..db9a67444512 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -708,6 +708,22 @@ pub enum Instruction { /// /// Errors: *Infallible*. ClearTransactStatus, + + /// Set the Topic Register. + /// + /// Safety: No concerns. + /// + /// Kind: *Instruction* + /// + /// Errors: + SetTopic([u8; 32]), + + /// Clear the Topic Register. + /// + /// Kind: *Instruction* + /// + /// Errors: None. + ClearTopic, } impl Xcm { @@ -771,6 +787,8 @@ impl Instruction { ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, ReportTransactStatus(response_info) => ReportTransactStatus(response_info), ClearTransactStatus => ClearTransactStatus, + SetTopic(topic) => SetTopic(topic), + ClearTopic => ClearTopic, } } } @@ -826,6 +844,8 @@ impl> GetWeight for Instruction { W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), ReportTransactStatus(response_info) => W::report_transact_status(response_info), ClearTransactStatus => W::clear_transact_status(), + SetTopic(topic) => W::set_topic(topic), + ClearTopic => W::clear_topic(), } } } diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 80f9a387d55c..7acfc3a2b3ab 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -59,6 +59,7 @@ pub struct XcmExecutor { pub appendix: Xcm, pub appendix_weight: u64, pub transact_status: MaybeErrorCode, + pub topic: Option<[u8; 32]>, _config: PhantomData, } @@ -177,6 +178,7 @@ impl XcmExecutor { appendix: Xcm(vec![]), appendix_weight: 0, transact_status: Default::default(), + topic: None, _config: PhantomData, } } @@ -579,6 +581,14 @@ impl XcmExecutor { self.transact_status = Default::default(); Ok(()) }, + SetTopic(topic) => { + self.topic = Some(topic); + Ok(()) + }, + ClearTopic => { + self.topic = None; + Ok(()) + }, ExchangeAsset { .. } => Err(XcmError::Unimplemented), HrmpNewChannelOpenRequest { .. } => Err(XcmError::Unimplemented), HrmpChannelAccepted { .. } => Err(XcmError::Unimplemented), From 0194c919737cf11ce2a88b853901cb358cf93f90 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 20 Jan 2022 22:48:11 -0800 Subject: [PATCH 04/73] Fix weights --- runtime/westend/src/weights/xcm/mod.rs | 6 ++++++ .../src/weights/xcm/pallet_xcm_benchmarks_generic.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index 0116b0a04d54..2f0c75649983 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -212,4 +212,10 @@ impl XcmWeightInfo for WestendXcmWeight { fn clear_transact_status() -> Weight { XcmGeneric::::clear_transact_status() } + fn set_topic(_topic: &[u8; 32]) -> Weight { + XcmGeneric::::set_topic() + } + fn clear_topic() -> Weight { + XcmGeneric::::clear_topic() + } } diff --git a/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index bd881fd41a81..ac76a7b94b38 100644 --- a/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -167,4 +167,10 @@ impl WeightInfo { pub(crate) fn clear_transact_status() -> Weight { (5_100_000 as Weight) } + pub(crate) fn set_topic() -> Weight { + (1_000 as Weight) + } + pub(crate) fn clear_topic() -> Weight { + (1_000 as Weight) + } } From 260025c600a2abcd64ec2b8fd749bf0c1c0e3e86 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 20 Jan 2022 22:57:36 -0800 Subject: [PATCH 05/73] Use tabs --- runtime/westend/src/weights/xcm/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index 2f0c75649983..fc4bae7b8f9c 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -216,6 +216,6 @@ impl XcmWeightInfo for WestendXcmWeight { XcmGeneric::::set_topic() } fn clear_topic() -> Weight { - XcmGeneric::::clear_topic() + XcmGeneric::::clear_topic() } } From e5ceb4c053c6957f0472f1eff374ad75f16fc70f Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 21 Jan 2022 00:22:39 -0800 Subject: [PATCH 06/73] Sketch out XcmContext --- xcm/src/v3/mod.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index db9a67444512..c0b78033cfba 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -208,6 +208,17 @@ pub struct QueryResponseInfo { pub max_weight: Weight, } +/// Contextual data pertaining to a specific list of XCM instructions. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug)] +pub struct XcmContext { + /// The `MultiLocation` origin of the corresponding XCM. + pub origin: Option, + /// The hash of the XCM. + pub message_hash: XcmHash, + /// The topic of the XCM. + pub topic: Option<[u8; 32]>, +} + /// Cross-Consensus Message: A message from one consensus system to another. /// /// Consensus systems that may send and receive messages include blockchains and smart contracts. From 0a19ace7b7c7e1fdf32724800aaf95992b84f07a Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 25 Jan 2022 00:09:37 -0800 Subject: [PATCH 07/73] Fix doc test --- xcm/src/v3/traits.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index eabb0b2b4bc8..07e58f869437 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -297,6 +297,7 @@ pub type SendResult = result::Result; /// # use xcm::v3::prelude::*; /// # use xcm::VersionedXcm; /// # use parity_scale_codec::Encode; +/// # use sp_io::hashing::blake2_256; /// /// /// A sender that only passes the message through and does nothing. /// struct Sender1; @@ -311,7 +312,7 @@ pub type SendResult = result::Result; /// impl SendXcm for Sender2 { /// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { /// if let MultiLocation { parents: 0, interior: X2(j1, j2) } = destination.into() { -/// Ok(VersionedXcm::from(message).using_encoded(sp_io::hashing::blake2_256)) +/// Ok(VersionedXcm::from(message).using_encoded(blake2_256)) /// } else { /// Err(SendError::Unroutable) /// } @@ -325,7 +326,7 @@ pub type SendResult = result::Result; /// let destination = destination.into(); /// match destination { /// MultiLocation { parents: 1, interior: Here } -/// => Ok(VersionedXcm::from(message).using_encoded(sp_io::hashing::blake2_256)) +/// => Ok(VersionedXcm::from(message).using_encoded(blake2_256)), /// _ => Err(SendError::CannotReachDestination(destination, message)), /// } /// } From 25c55ebb6d33738217754b7d33157b4e04ccca16 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 25 Jan 2022 02:36:16 -0800 Subject: [PATCH 08/73] Add the XCM context as a parameter to executor trait fns --- xcm/src/v3/mod.rs | 12 +- xcm/src/v3/traits.rs | 14 +- xcm/xcm-executor/src/lib.rs | 147 +++++++++++++----- xcm/xcm-executor/src/traits/conversion.rs | 9 +- xcm/xcm-executor/src/traits/drop_assets.rs | 30 ++-- .../src/traits/filter_asset_location.rs | 19 ++- xcm/xcm-executor/src/traits/on_response.rs | 21 ++- xcm/xcm-executor/src/traits/transact_asset.rs | 138 +++++++++++----- 8 files changed, 286 insertions(+), 104 deletions(-) diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 9a6869f05751..f9d895c883fd 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -133,7 +133,7 @@ pub mod prelude { WeightLimit::{self, *}, WildFungibility::{self, Fungible as WildFungible, NonFungible as WildNonFungible}, WildMultiAsset::{self, *}, - XcmHash, XcmWeightInfo, VERSION as XCM_VERSION, + XcmContext, XcmHash, XcmWeightInfo, VERSION as XCM_VERSION, }; } pub use super::{Instruction, Xcm}; @@ -219,6 +219,16 @@ pub struct XcmContext { pub topic: Option<[u8; 32]>, } +#[cfg(test)] +impl XcmContext { + /// Helper function to create a bogus empty context for testing purposes. + /// + /// This function should only be used in cases where the context is sure to be unused. + pub fn empty() -> Self { + XcmContext { origin: None, message_hash: [0; 32], topic: None } + } +} + /// Cross-Consensus Message: A message from one consensus system to another. /// /// Consensus systems that may send and receive messages include blockchains and smart contracts. diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 07e58f869437..6674f2d73ba3 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -360,15 +360,23 @@ pub trait SendXcm { /// If it is not a destination which can be reached with this type but possibly could by others, then it *MUST* /// return `CannotReachDestination`. Any other error will cause the tuple implementation to exit early without /// trying other type fields. - fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult; + fn send_xcm( + destination: impl Into, + message: Xcm<()>, + context: XcmContext, + ) -> SendResult; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl SendXcm for Tuple { - fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { + fn send_xcm( + destination: impl Into, + message: Xcm<()>, + context: XcmContext, + ) -> SendResult { for_tuples!( #( // we shadow `destination` and `message` in each expansion for the next one. - let (destination, message) = match Tuple::send_xcm(destination, message) { + let (destination, message) = match Tuple::send_xcm(destination, message, context.clone()) { Err(SendError::CannotReachDestination(d, m)) => (d, m), o @ _ => return o, }; diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 2714597f903b..ead827b3986c 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -124,8 +124,12 @@ impl ExecuteXcm for XcmExecutor { let mut vm = Self::new(origin); + // We hash the message here instead of inside the loop, because `message` may have been + // reassigned due to the existence of the error handler or the appendix. + let message_hash = message.using_encoded(sp_io::hashing::blake2_256); + while !message.0.is_empty() { - let result = vm.execute(message); + let result = vm.execute(message, message_hash); log::trace!(target: "xcm::execute_xcm_in_credit", "result: {:?}", result); message = if let Err(error) = result { vm.total_surplus.saturating_accrue(error.weight); @@ -137,7 +141,7 @@ impl ExecuteXcm for XcmExecutor { } } - vm.post_execute(xcm_weight) + vm.post_execute(xcm_weight, message_hash) } } @@ -185,7 +189,11 @@ impl XcmExecutor { /// Execute the XCM program fragment and report back the error and which instruction caused it, /// or `Ok` if there was no error. - pub fn execute(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { + pub fn execute( + &mut self, + xcm: Xcm, + message_hash: [u8; 32], + ) -> Result<(), ExecutorError> { log::trace!( target: "xcm::execute", "origin: {:?}, total_surplus/refunded: {:?}/{:?}, error_handler_weight: {:?}", @@ -198,7 +206,7 @@ impl XcmExecutor { for (i, instr) in xcm.0.into_iter().enumerate() { match &mut result { r @ Ok(()) => - if let Err(e) = self.process_instruction(instr) { + if let Err(e) = self.process_instruction(instr, message_hash) { *r = Err(ExecutorError { index: i as u32, xcm_error: e, weight: 0 }); }, Err(ref mut error) => @@ -212,7 +220,7 @@ impl XcmExecutor { /// Execute any final operations after having executed the XCM message. /// This includes refunding surplus weight, trapping extra holding funds, and returning any errors during execution. - pub fn post_execute(mut self, xcm_weight: Weight) -> Outcome { + pub fn post_execute(mut self, xcm_weight: Weight, message_hash: [u8; 32]) -> Outcome { // We silently drop any error from our attempt to refund the surplus as it's a charitable // thing so best-effort is all we will do. let _ = self.refund_surplus(); @@ -221,8 +229,15 @@ impl XcmExecutor { let mut weight_used = xcm_weight.saturating_sub(self.total_surplus); if !self.holding.is_empty() { - log::trace!(target: "xcm::execute_xcm_in_credit", "Trapping assets in holding register: {:?} (original_origin: {:?})", self.holding, self.original_origin); - let trap_weight = Config::AssetTrap::drop_assets(&self.original_origin, self.holding); + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + log::trace!( + target: "xcm::execute_xcm_in_credit", + "Trapping assets in holding register: {:?}, context: {:?} (original_origin: {:?})", + self.holding, context, self.original_origin, + ); + let trap_weight = + Config::AssetTrap::drop_assets(&self.original_origin, self.holding, context); weight_used.saturating_accrue(trap_weight); }; @@ -291,13 +306,22 @@ impl XcmExecutor { } /// Process a single XCM instruction, mutating the state of the XCM virtual machine. - fn process_instruction(&mut self, instr: Instruction) -> Result<(), XcmError> { + fn process_instruction( + &mut self, + instr: Instruction, + message_hash: [u8; 32], + ) -> Result<(), XcmError> { match instr { WithdrawAsset(assets) => { // Take `assets` from the origin account (on-chain) and place in holding. let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.drain().into_iter() { - Config::AssetTransactor::withdraw_asset(&asset, &origin)?; + let context = XcmContext { + origin: Some(origin.clone()), + message_hash, + topic: self.topic, + }; + Config::AssetTransactor::withdraw_asset(&asset, &origin, context)?; self.subsume_asset(asset)?; } Ok(()) @@ -306,9 +330,14 @@ impl XcmExecutor { // check whether we trust origin to be our reserve location for this asset. let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.drain().into_iter() { + let context = XcmContext { + origin: Some(origin.clone()), + message_hash, + topic: self.topic, + }; // Must ensure that we recognise the asset as being managed by the origin. ensure!( - Config::IsReserve::filter_asset_location(&asset, &origin), + Config::IsReserve::filter_asset_location(&asset, &origin, context), XcmError::UntrustedReserveLocation ); self.subsume_asset(asset)?; @@ -319,52 +348,68 @@ impl XcmExecutor { // Take `assets` from the origin account (on-chain) and place into dest account. let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; for asset in assets.inner() { - Config::AssetTransactor::beam_asset(&asset, origin, &beneficiary)?; + let context = XcmContext { + origin: Some(origin.clone()), + message_hash, + topic: self.topic, + }; + Config::AssetTransactor::beam_asset(&asset, origin, &beneficiary, context)?; } Ok(()) }, TransferReserveAsset { mut assets, dest, xcm } => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; // Take `assets` from the origin account (on-chain) and place into dest account. for asset in assets.inner() { - Config::AssetTransactor::beam_asset(asset, origin, &dest)?; + Config::AssetTransactor::beam_asset(asset, origin, &dest, context.clone())?; } let ancestry = Config::LocationInverter::ancestry(); assets.reanchor(&dest, &ancestry).map_err(|()| XcmError::MultiLocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message))?; + Config::XcmSender::send_xcm(dest, Xcm(message), context)?; Ok(()) }, ReceiveTeleportedAsset(assets) => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; // check whether we trust origin to teleport this asset to us via config trait. for asset in assets.inner() { // We only trust the origin to send us assets that they identify as their // sovereign assets. ensure!( - Config::IsTeleporter::filter_asset_location(asset, &origin), + Config::IsTeleporter::filter_asset_location( + asset, + &origin, + context.clone() + ), XcmError::UntrustedTeleportLocation ); // We should check that the asset can actually be teleported in (for this to be in error, there // would need to be an accounting violation by one of the trusted chains, so it's unlikely, but we // don't want to punish a possibly innocent chain/user). - Config::AssetTransactor::can_check_in(&origin, asset)?; + Config::AssetTransactor::can_check_in(&origin, asset, context.clone())?; } for asset in assets.drain().into_iter() { - Config::AssetTransactor::check_in(&origin, &asset); + Config::AssetTransactor::check_in(&origin, &asset, context.clone()); self.subsume_asset(asset)?; } Ok(()) }, Transact { origin_kind, require_weight_at_most, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. - let origin = self.origin.clone().ok_or(XcmError::BadOrigin)?; + let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| XcmError::FailedToDecode)?; - let dispatch_origin = Config::OriginConverter::convert_origin(origin, origin_kind) - .map_err(|_| XcmError::BadOrigin)?; + let dispatch_origin = + Config::OriginConverter::convert_origin(origin, origin_kind, context) + .map_err(|_| XcmError::BadOrigin)?; let weight = message_call.get_dispatch_info().weight; ensure!(weight <= require_weight_at_most, XcmError::MaxWeightInvalid); let maybe_actual_weight = match message_call.dispatch(dispatch_origin) { @@ -392,12 +437,15 @@ impl XcmExecutor { }, QueryResponse { query_id, response, max_weight, querier } => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; Config::ResponseHandler::on_response( origin, query_id, querier.as_ref(), response, max_weight, + context, ); Ok(()) }, @@ -412,36 +460,40 @@ impl XcmExecutor { Ok(()) }, ReportError(response_info) => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Report the given result by sending a QueryResponse XCM to a previously given outcome // destination if one was registered. - Self::respond( - self.origin.clone(), - Response::ExecutionResult(self.error), - response_info, - )?; + Self::respond(context, Response::ExecutionResult(self.error), response_info)?; Ok(()) }, DepositAsset { assets, beneficiary } => { let deposited = self.holding.saturating_take(assets); for asset in deposited.into_assets_iter() { - Config::AssetTransactor::deposit_asset(&asset, &beneficiary)?; + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + Config::AssetTransactor::deposit_asset(&asset, &beneficiary, context)?; } Ok(()) }, DepositReserveAsset { assets, dest, xcm } => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; let deposited = self.holding.saturating_take(assets); for asset in deposited.assets_iter() { - Config::AssetTransactor::deposit_asset(&asset, &dest)?; + Config::AssetTransactor::deposit_asset(&asset, &dest, context.clone())?; } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot // be reanchored because we have already called `deposit_asset` on all assets. let assets = Self::reanchored(deposited, &dest, None); let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message))?; + Config::XcmSender::send_xcm(dest, Xcm(message), context)?; Ok(()) }, InitiateReserveWithdraw { assets, reserve, xcm } => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Note that here we are able to place any assets which could not be reanchored // back into Holding. let assets = Self::reanchored( @@ -451,29 +503,33 @@ impl XcmExecutor { ); let mut message = vec![WithdrawAsset(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(reserve, Xcm(message))?; + Config::XcmSender::send_xcm(reserve, Xcm(message), context)?; Ok(()) }, InitiateTeleport { assets, dest, xcm } => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // We must do this first in order to resolve wildcards. let assets = self.holding.saturating_take(assets); for asset in assets.assets_iter() { - Config::AssetTransactor::check_out(&dest, &asset); + Config::AssetTransactor::check_out(&dest, &asset, context.clone()); } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot // be reanchored because we have already checked all assets out. let assets = Self::reanchored(assets, &dest, None); let mut message = vec![ReceiveTeleportedAsset(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message))?; + Config::XcmSender::send_xcm(dest, Xcm(message), context)?; Ok(()) }, ReportHolding { response_info, assets } => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Note that we pass `None` as `maybe_failed_bin` since no assets were ever removed // from Holding. let assets = Self::reanchored(self.holding.min(&assets), &response_info.destination, None); - Self::respond(self.origin.clone(), Response::Assets(assets), response_info)?; + Self::respond(context, Response::Assets(assets), response_info)?; Ok(()) }, BuyExecution { fees, weight_limit } => { @@ -513,7 +569,9 @@ impl XcmExecutor { }, ClaimAsset { assets, ticket } => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; - let ok = Config::AssetClaims::claim_assets(origin, &ticket, &assets); + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let ok = Config::AssetClaims::claim_assets(origin, &ticket, &assets, context); ensure!(ok, XcmError::UnknownClaim); for asset in assets.drain().into_iter() { self.subsume_asset(asset)?; @@ -522,16 +580,20 @@ impl XcmExecutor { }, Trap(code) => Err(XcmError::Trap(code)), SubscribeVersion { query_id, max_response_weight } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; // We don't allow derivative origins to subscribe since it would otherwise pose a // DoS risk. - ensure!(self.original_origin == origin, XcmError::BadOrigin); - Config::SubscriptionService::start(&origin, query_id, max_response_weight) + ensure!(&self.original_origin == origin, XcmError::BadOrigin); + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + Config::SubscriptionService::start(origin, query_id, max_response_weight, context) }, UnsubscribeVersion => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; ensure!(&self.original_origin == origin, XcmError::BadOrigin); - Config::SubscriptionService::stop(origin) + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + Config::SubscriptionService::stop(origin, context) }, BurnAsset(assets) => { self.holding.saturating_take(assets.into()); @@ -548,6 +610,8 @@ impl XcmExecutor { Ok(()) }, QueryPallet { module_name, response_info } => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; let pallets = Config::PalletInstancesInfo::infos() .into_iter() .filter(|x| x.module_name.as_bytes() == &module_name[..]) @@ -565,7 +629,7 @@ impl XcmExecutor { let querier = Self::to_querier(self.origin.clone(), &destination)?; let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); - Config::XcmSender::send_xcm(destination, message)?; + Config::XcmSender::send_xcm(destination, message, context)?; Ok(()) }, ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { @@ -582,8 +646,10 @@ impl XcmExecutor { Ok(()) }, ReportTransactStatus(response_info) => { + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; Self::respond( - self.origin.clone(), + context, Response::DispatchResult(self.transact_status.clone()), response_info, )?; @@ -626,15 +692,16 @@ impl XcmExecutor { /// /// The `local_querier` argument is the querier (if any) specified from the *local* perspective. fn respond( - local_querier: Option, + context: XcmContext, response: Response, info: QueryResponseInfo, ) -> Result { + let local_querier = context.origin.clone(); let querier = Self::to_querier(local_querier, &info.destination)?; let QueryResponseInfo { destination, query_id, max_weight } = info; let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); - Config::XcmSender::send_xcm(destination, message).map_err(Into::into) + Config::XcmSender::send_xcm(destination, message, context).map_err(Into::into) } /// NOTE: Any assets which were unable to be reanchored are introduced into `failed_bin`. diff --git a/xcm/xcm-executor/src/traits/conversion.rs b/xcm/xcm-executor/src/traits/conversion.rs index d8c50037662d..51e82ee5c7dd 100644 --- a/xcm/xcm-executor/src/traits/conversion.rs +++ b/xcm/xcm-executor/src/traits/conversion.rs @@ -16,7 +16,7 @@ use parity_scale_codec::{Decode, Encode}; use sp_std::{borrow::Borrow, convert::TryFrom, prelude::*, result::Result}; -use xcm::latest::{MultiLocation, OriginKind}; +use xcm::latest::{MultiLocation, OriginKind, XcmContext}; /// Generic third-party conversion trait. Use this when you don't want to force the user to use default /// implementations of `From` and `Into` for the types you wish to convert between. @@ -178,6 +178,7 @@ pub trait ConvertOrigin { fn convert_origin( origin: impl Into, kind: OriginKind, + context: XcmContext, ) -> Result; } @@ -186,9 +187,10 @@ impl ConvertOrigin for Tuple { fn convert_origin( origin: impl Into, kind: OriginKind, + context: XcmContext, ) -> Result { for_tuples!( #( - let origin = match Tuple::convert_origin(origin, kind) { + let origin = match Tuple::convert_origin(origin, kind, context.clone()) { Err(o) => o, r => return r }; @@ -196,9 +198,10 @@ impl ConvertOrigin for Tuple { let origin = origin.into(); log::trace!( target: "xcm::convert_origin", - "could not convert: origin: {:?}, kind: {:?}", + "could not convert: origin: {:?}, kind: {:?}, context: {:?}", origin, kind, + context, ); Err(origin) } diff --git a/xcm/xcm-executor/src/traits/drop_assets.rs b/xcm/xcm-executor/src/traits/drop_assets.rs index 5f82c5feb74b..ca4fd5d8fe3e 100644 --- a/xcm/xcm-executor/src/traits/drop_assets.rs +++ b/xcm/xcm-executor/src/traits/drop_assets.rs @@ -17,15 +17,15 @@ use crate::Assets; use core::marker::PhantomData; use frame_support::{traits::Contains, weights::Weight}; -use xcm::latest::{MultiAssets, MultiLocation}; +use xcm::latest::{MultiAssets, MultiLocation, XcmContext}; /// Define a handler for when some non-empty `Assets` value should be dropped. pub trait DropAssets { /// Handler for receiving dropped assets. Returns the weight consumed by this operation. - fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight; + fn drop_assets(origin: &MultiLocation, assets: Assets, context: XcmContext) -> Weight; } impl DropAssets for () { - fn drop_assets(_origin: &MultiLocation, _assets: Assets) -> Weight { + fn drop_assets(_origin: &MultiLocation, _assets: Assets, _context: XcmContext) -> Weight { 0 } } @@ -35,9 +35,9 @@ impl DropAssets for () { pub struct FilterAssets(PhantomData<(D, A)>); impl> DropAssets for FilterAssets { - fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, context: XcmContext) -> Weight { if A::contains(&assets) { - D::drop_assets(origin, assets) + D::drop_assets(origin, assets, context) } else { 0 } @@ -50,9 +50,9 @@ impl> DropAssets for FilterAssets { pub struct FilterOrigin(PhantomData<(D, O)>); impl> DropAssets for FilterOrigin { - fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, context: XcmContext) -> Weight { if O::contains(origin) { - D::drop_assets(origin, assets) + D::drop_assets(origin, assets, context) } else { 0 } @@ -63,14 +63,24 @@ impl> DropAssets for FilterOrigin bool; + fn claim_assets( + origin: &MultiLocation, + ticket: &MultiLocation, + what: &MultiAssets, + context: XcmContext, + ) -> bool; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl ClaimAssets for Tuple { - fn claim_assets(origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets) -> bool { + fn claim_assets( + origin: &MultiLocation, + ticket: &MultiLocation, + what: &MultiAssets, + context: XcmContext, + ) -> bool { for_tuples!( #( - if Tuple::claim_assets(origin, ticket, what) { + if Tuple::claim_assets(origin, ticket, what, context.clone()) { return true; } )* ); diff --git a/xcm/xcm-executor/src/traits/filter_asset_location.rs b/xcm/xcm-executor/src/traits/filter_asset_location.rs index 31b9c47a828c..8e0ede91d07e 100644 --- a/xcm/xcm-executor/src/traits/filter_asset_location.rs +++ b/xcm/xcm-executor/src/traits/filter_asset_location.rs @@ -14,27 +14,36 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use xcm::latest::{MultiAsset, MultiLocation}; +use xcm::latest::{MultiAsset, MultiLocation, XcmContext}; /// Filters assets/location pairs. /// /// Can be amalgamated into tuples. If any item returns `true`, it short-circuits, else `false` is returned. pub trait FilterAssetLocation { /// A filter to distinguish between asset/location pairs. - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool; + fn filter_asset_location( + asset: &MultiAsset, + origin: &MultiLocation, + context: XcmContext, + ) -> bool; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl FilterAssetLocation for Tuple { - fn filter_asset_location(what: &MultiAsset, origin: &MultiLocation) -> bool { + fn filter_asset_location( + what: &MultiAsset, + origin: &MultiLocation, + context: XcmContext, + ) -> bool { for_tuples!( #( - if Tuple::filter_asset_location(what, origin) { return true } + if Tuple::filter_asset_location(what, origin, context.clone()) { return true } )* ); log::trace!( target: "xcm::filter_asset_location", - "got filtered: what: {:?}, origin: {:?}", + "got filtered: what: {:?}, origin: {:?}, context: {:?}", what, origin, + context, ); false } diff --git a/xcm/xcm-executor/src/traits/on_response.rs b/xcm/xcm-executor/src/traits/on_response.rs index 016976453511..334535ed3682 100644 --- a/xcm/xcm-executor/src/traits/on_response.rs +++ b/xcm/xcm-executor/src/traits/on_response.rs @@ -15,7 +15,9 @@ // along with Polkadot. If not, see . use frame_support::weights::Weight; -use xcm::latest::{Error as XcmError, MultiLocation, QueryId, Response, Result as XcmResult}; +use xcm::latest::{ + Error as XcmError, MultiLocation, QueryId, Response, Result as XcmResult, XcmContext, +}; /// Define what needs to be done upon receiving a query response. pub trait OnResponse { @@ -25,6 +27,7 @@ pub trait OnResponse { origin: &MultiLocation, query_id: u64, querier: Option<&MultiLocation>, + context: XcmContext, ) -> bool; /// Handler for receiving a `response` from `origin` relating to `query_id` initiated by /// `querier`. @@ -34,6 +37,7 @@ pub trait OnResponse { querier: Option<&MultiLocation>, response: Response, max_weight: Weight, + context: XcmContext, ) -> Weight; } impl OnResponse for () { @@ -41,6 +45,7 @@ impl OnResponse for () { _origin: &MultiLocation, _query_id: u64, _querier: Option<&MultiLocation>, + _context: XcmContext, ) -> bool { false } @@ -50,6 +55,7 @@ impl OnResponse for () { _querier: Option<&MultiLocation>, _response: Response, _max_weight: Weight, + _context: XcmContext, ) -> Weight { 0 } @@ -65,21 +71,26 @@ pub trait VersionChangeNotifier { /// /// If the `location` has an ongoing notification and when this function is called, then an /// error should be returned. - fn start(location: &MultiLocation, query_id: QueryId, max_weight: u64) -> XcmResult; + fn start( + location: &MultiLocation, + query_id: QueryId, + max_weight: u64, + context: XcmContext, + ) -> XcmResult; /// Stop notifying `location` should the XCM change. Returns an error if there is no existing /// notification set up. - fn stop(location: &MultiLocation) -> XcmResult; + fn stop(location: &MultiLocation, context: XcmContext) -> XcmResult; /// Return true if a location is subscribed to XCM version changes. fn is_subscribed(location: &MultiLocation) -> bool; } impl VersionChangeNotifier for () { - fn start(_: &MultiLocation, _: QueryId, _: u64) -> XcmResult { + fn start(_: &MultiLocation, _: QueryId, _: u64, _: XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } - fn stop(_: &MultiLocation) -> XcmResult { + fn stop(_: &MultiLocation, _: XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } fn is_subscribed(_: &MultiLocation) -> bool { diff --git a/xcm/xcm-executor/src/traits/transact_asset.rs b/xcm/xcm-executor/src/traits/transact_asset.rs index 78e2180ed7a4..de704fb6f9f8 100644 --- a/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/xcm/xcm-executor/src/traits/transact_asset.rs @@ -16,7 +16,7 @@ use crate::Assets; use sp_std::result::Result; -use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmResult}; +use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result as XcmResult, XcmContext}; /// Facility for asset transacting. /// @@ -29,7 +29,11 @@ pub trait TransactAsset { /// Ensure that `check_in` will result in `Ok`. /// /// When composed as a tuple, all type-items are called and at least one must result in `Ok`. - fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult { + fn can_check_in( + _origin: &MultiLocation, + _what: &MultiAsset, + _context: XcmContext, + ) -> XcmResult { Err(XcmError::Unimplemented) } @@ -46,7 +50,7 @@ pub trait TransactAsset { /// /// When composed as a tuple, all type-items are called. It is up to the implementer that there exists no /// value for `_what` which can cause side-effects for more than one of the type-items. - fn check_in(_origin: &MultiLocation, _what: &MultiAsset) {} + fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: XcmContext) {} /// An asset has been teleported out to the given destination. This should do whatever housekeeping is needed. /// @@ -58,12 +62,12 @@ pub trait TransactAsset { /// /// When composed as a tuple, all type-items are called. It is up to the implementer that there exists no /// value for `_what` which can cause side-effects for more than one of the type-items. - fn check_out(_dest: &MultiLocation, _what: &MultiAsset) {} + fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: XcmContext) {} /// Deposit the `what` asset into the account of `who`. /// /// Implementations should return `XcmError::FailedToTransactAsset` if deposit failed. - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult { + fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } @@ -71,7 +75,11 @@ pub trait TransactAsset { /// which should always be equal to `_what`. /// /// Implementations should return `XcmError::FailedToTransactAsset` if withdraw failed. - fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result { + fn withdraw_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> Result { Err(XcmError::Unimplemented) } @@ -82,6 +90,7 @@ pub trait TransactAsset { _asset: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, + _context: XcmContext, ) -> Result { Err(XcmError::Unimplemented) } @@ -93,12 +102,13 @@ pub trait TransactAsset { asset: &MultiAsset, from: &MultiLocation, to: &MultiLocation, + context: XcmContext, ) -> Result { - match Self::transfer_asset(asset, from, to) { + match Self::transfer_asset(asset, from, to, context.clone()) { Err(XcmError::Unimplemented) => { - let assets = Self::withdraw_asset(asset, from)?; + let assets = Self::withdraw_asset(asset, from, context.clone())?; // Not a very forgiving attitude; once we implement roll-backs then it'll be nicer. - Self::deposit_asset(asset, to)?; + Self::deposit_asset(asset, to, context)?; Ok(assets) }, result => result, @@ -108,62 +118,69 @@ pub trait TransactAsset { #[impl_trait_for_tuples::impl_for_tuples(30)] impl TransactAsset for Tuple { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset) -> XcmResult { + fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) -> XcmResult { for_tuples!( #( - match Tuple::can_check_in(origin, what) { + match Tuple::can_check_in(origin, what, context.clone()) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } )* ); log::trace!( target: "xcm::TransactAsset::can_check_in", - "asset not found: what: {:?}, origin: {:?}", + "asset not found: what: {:?}, origin: {:?}, context: {:?}", what, origin, + context, ); Err(XcmError::AssetNotFound) } - fn check_in(origin: &MultiLocation, what: &MultiAsset) { + fn check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) { for_tuples!( #( - Tuple::check_in(origin, what); + Tuple::check_in(origin, what, context.clone()); )* ); } - fn check_out(dest: &MultiLocation, what: &MultiAsset) { + fn check_out(dest: &MultiLocation, what: &MultiAsset, context: XcmContext) { for_tuples!( #( - Tuple::check_out(dest, what); + Tuple::check_out(dest, what, context.clone()); )* ); } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> XcmResult { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: XcmContext) -> XcmResult { for_tuples!( #( - match Tuple::deposit_asset(what, who) { + match Tuple::deposit_asset(what, who, context.clone()) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } )* ); log::trace!( target: "xcm::TransactAsset::deposit_asset", - "did not deposit asset: what: {:?}, who: {:?}", + "did not deposit asset: what: {:?}, who: {:?}, context: {:?}", what, who, + context, ); Err(XcmError::AssetNotFound) } - fn withdraw_asset(what: &MultiAsset, who: &MultiLocation) -> Result { + fn withdraw_asset( + what: &MultiAsset, + who: &MultiLocation, + context: XcmContext, + ) -> Result { for_tuples!( #( - match Tuple::withdraw_asset(what, who) { + match Tuple::withdraw_asset(what, who, context.clone()) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } )* ); log::trace!( target: "xcm::TransactAsset::withdraw_asset", - "did not withdraw asset: what: {:?}, who: {:?}", + "did not withdraw asset: what: {:?}, who: {:?}, context: {:?}", what, who, + context, ); Err(XcmError::AssetNotFound) } @@ -172,19 +189,21 @@ impl TransactAsset for Tuple { what: &MultiAsset, from: &MultiLocation, to: &MultiLocation, + context: XcmContext, ) -> Result { for_tuples!( #( - match Tuple::transfer_asset(what, from, to) { + match Tuple::transfer_asset(what, from, to, context.clone()) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } )* ); log::trace!( target: "xcm::TransactAsset::transfer_asset", - "did not transfer asset: what: {:?}, from: {:?}, to: {:?}", + "did not transfer asset: what: {:?}, from: {:?}, to: {:?}, context: {:?}", what, from, to, + context, ); Err(XcmError::AssetNotFound) } @@ -200,15 +219,27 @@ mod tests { pub struct NotFoundTransactor; impl TransactAsset for NotFoundTransactor { - fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult { + fn can_check_in( + _origin: &MultiLocation, + _what: &MultiAsset, + _context: XcmContext, + ) -> XcmResult { Err(XcmError::AssetNotFound) } - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult { + fn deposit_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> XcmResult { Err(XcmError::AssetNotFound) } - fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result { + fn withdraw_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> Result { Err(XcmError::AssetNotFound) } @@ -216,6 +247,7 @@ mod tests { _what: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, + _context: XcmContext, ) -> Result { Err(XcmError::AssetNotFound) } @@ -223,15 +255,27 @@ mod tests { pub struct OverflowTransactor; impl TransactAsset for OverflowTransactor { - fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult { + fn can_check_in( + _origin: &MultiLocation, + _what: &MultiAsset, + _context: XcmContext, + ) -> XcmResult { Err(XcmError::Overflow) } - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult { + fn deposit_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> XcmResult { Err(XcmError::Overflow) } - fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result { + fn withdraw_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> Result { Err(XcmError::Overflow) } @@ -239,6 +283,7 @@ mod tests { _what: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, + _context: XcmContext, ) -> Result { Err(XcmError::Overflow) } @@ -246,15 +291,27 @@ mod tests { pub struct SuccessfulTransactor; impl TransactAsset for SuccessfulTransactor { - fn can_check_in(_origin: &MultiLocation, _what: &MultiAsset) -> XcmResult { + fn can_check_in( + _origin: &MultiLocation, + _what: &MultiAsset, + _context: XcmContext, + ) -> XcmResult { Ok(()) } - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult { + fn deposit_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> XcmResult { Ok(()) } - fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result { + fn withdraw_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> Result { Ok(Assets::default()) } @@ -262,6 +319,7 @@ mod tests { _what: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, + _context: XcmContext, ) -> Result { Ok(Assets::default()) } @@ -273,7 +331,7 @@ mod tests { (UnimplementedTransactor, NotFoundTransactor, UnimplementedTransactor); assert_eq!( - MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), + MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), Err(XcmError::AssetNotFound) ); } @@ -282,7 +340,10 @@ mod tests { fn unimplemented_and_not_found_continue_iteration() { type MultiTransactor = (UnimplementedTransactor, NotFoundTransactor, SuccessfulTransactor); - assert_eq!(MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), Ok(()),); + assert_eq!( + MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), + Ok(()) + ); } #[test] @@ -290,7 +351,7 @@ mod tests { type MultiTransactor = (OverflowTransactor, SuccessfulTransactor); assert_eq!( - MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), + MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), Err(XcmError::Overflow) ); } @@ -299,6 +360,9 @@ mod tests { fn success_stops_iteration() { type MultiTransactor = (SuccessfulTransactor, OverflowTransactor); - assert_eq!(MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into()), Ok(()),); + assert_eq!( + MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), + Ok(()), + ); } } From 73af5b2d7eafcf7fe6dc9cb148b34e2f9d916497 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 26 Jan 2022 09:55:25 -0800 Subject: [PATCH 09/73] Fixes --- xcm/src/v3/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index f9d895c883fd..9a4099834f1c 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -219,11 +219,11 @@ pub struct XcmContext { pub topic: Option<[u8; 32]>, } -#[cfg(test)] impl XcmContext { /// Helper function to create a bogus empty context for testing purposes. /// /// This function should only be used in cases where the context is sure to be unused. + #[cfg(test)] pub fn empty() -> Self { XcmContext { origin: None, message_hash: [0; 32], topic: None } } From 797323398a7211d40e2b496d70c6eb644452b979 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 27 Jan 2022 04:23:35 -0800 Subject: [PATCH 10/73] Add XcmContext parameter --- Cargo.lock | 1 + runtime/common/src/xcm_sender.rs | 2 +- runtime/test-runtime/src/xcm_config.rs | 2 +- xcm/Cargo.toml | 3 + xcm/pallet-xcm/Cargo.toml | 8 +-- xcm/pallet-xcm/src/lib.rs | 64 ++++++++++++++------ xcm/src/v3/mod.rs | 6 ++ xcm/src/v3/traits.rs | 19 +++--- xcm/xcm-builder/src/currency_adapter.rs | 16 +++-- xcm/xcm-builder/src/filter_asset_location.rs | 14 ++++- xcm/xcm-builder/src/fungibles_adapter.rs | 34 ++++++----- xcm/xcm-builder/src/origin_conversion.rs | 13 +++- xcm/xcm-builder/src/test_utils.rs | 18 ++++-- xcm/xcm-builder/tests/mock/mod.rs | 6 +- xcm/xcm-executor/src/traits/on_response.rs | 2 - 15 files changed, 144 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5274ac533030..2099f6df31f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11933,6 +11933,7 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", + "sp-io", "xcm-procedural", ] diff --git a/runtime/common/src/xcm_sender.rs b/runtime/common/src/xcm_sender.rs index b9e5d3e42c7f..27f4124cc0d2 100644 --- a/runtime/common/src/xcm_sender.rs +++ b/runtime/common/src/xcm_sender.rs @@ -27,7 +27,7 @@ pub struct ChildParachainRouter(PhantomData<(T, W)>); impl SendXcm for ChildParachainRouter { - fn send_xcm(dest: impl Into, msg: Xcm<()>) -> SendResult { + fn send_xcm(dest: impl Into, msg: Xcm<()>, _context: XcmContext) -> SendResult { let dest = dest.into(); match dest { MultiLocation { parents: 0, interior: X1(Parachain(id)) } => { diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 0fc52c687cc6..470f171b4374 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -38,7 +38,7 @@ pub type LocalOriginToLocation = ( pub struct DoNothingRouter; impl SendXcm for DoNothingRouter { - fn send_xcm(_dest: impl Into, msg: Xcm<()>) -> SendResult { + fn send_xcm(_dest: impl Into, msg: Xcm<()>, _context: XcmContext) -> SendResult { Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } diff --git a/xcm/Cargo.toml b/xcm/Cargo.toml index 74fba460bdd9..8ec468f1fa87 100644 --- a/xcm/Cargo.toml +++ b/xcm/Cargo.toml @@ -13,6 +13,9 @@ derivative = {version = "2.2.0", default-features = false, features = [ "use_cor log = { version = "0.4.14", default-features = false } xcm-procedural = { path = "procedural" } +[dev-dependencies] +sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } + [features] default = ["std"] wasm-api = [] diff --git a/xcm/pallet-xcm/Cargo.toml b/xcm/pallet-xcm/Cargo.toml index b72fba007be9..f18860687767 100644 --- a/xcm/pallet-xcm/Cargo.toml +++ b/xcm/pallet-xcm/Cargo.toml @@ -10,11 +10,12 @@ scale-info = { version = "1.0", default-features = false, features = ["derive"] serde = { version = "1.0.132", optional = true, features = ["derive"] } log = { version = "0.4.14", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } -sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } -sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } +sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } +sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } xcm = { path = "..", default-features = false } xcm-executor = { path = "../xcm-executor", default-features = false } @@ -22,7 +23,6 @@ xcm-executor = { path = "../xcm-executor", default-features = false } [dev-dependencies] pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" } polkadot-runtime-parachains = { path = "../../runtime/parachains" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } xcm-builder = { path = "../xcm-builder" } polkadot-parachain = { path = "../../parachain" } diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index c4efc6883aa2..aeb384e0768f 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -26,6 +26,7 @@ mod tests; use codec::{Decode, Encode, EncodeLike}; use frame_support::traits::{Contains, EnsureOrigin, Get, OriginTrait}; use scale_info::TypeInfo; +use sp_io::hashing::blake2_256; use sp_runtime::{ traits::{BadOrigin, Saturating}, RuntimeDebug, @@ -1046,7 +1047,9 @@ pub mod pallet { let response = Response::Version(xcm_version); let message = Xcm(vec![QueryResponse { query_id, response, max_weight, querier: None }]); - let event = match T::XcmRouter::send_xcm(new_key.clone(), message) { + let message_hash = message.using_encoded(blake2_256); + let context = XcmContext::with_message_hash(message_hash); + let event = match T::XcmRouter::send_xcm(new_key.clone(), message, context) { Ok(_) => { let value = (query_id, max_weight, xcm_version); VersionNotifyTargets::::insert(XCM_VERSION, key, value); @@ -1097,17 +1100,21 @@ pub mod pallet { max_weight, querier: None, }]); - let event = match T::XcmRouter::send_xcm(new_key.clone(), message) { - Ok(_) => { - VersionNotifyTargets::::insert( - XCM_VERSION, - versioned_key, - (query_id, max_weight, xcm_version), - ); - Event::VersionChangeNotified(new_key, xcm_version) - }, - Err(e) => Event::NotifyTargetSendFail(new_key, query_id, e.into()), - }; + let message_hash = message.using_encoded(blake2_256); + let context = XcmContext::with_message_hash(message_hash); + let event = + match T::XcmRouter::send_xcm(new_key.clone(), message, context) { + Ok(_) => { + VersionNotifyTargets::::insert( + XCM_VERSION, + versioned_key, + (query_id, max_weight, xcm_version), + ); + Event::VersionChangeNotified(new_key, xcm_version) + }, + Err(e) => + Event::NotifyTargetSendFail(new_key, query_id, e.into()), + }; Self::deposit_event(event); weight_used.saturating_accrue(todo_vnt_notify_migrate_weight); } @@ -1133,7 +1140,10 @@ pub mod pallet { }); // TODO #3735: Correct weight. let instruction = SubscribeVersion { query_id, max_response_weight: 0 }; - T::XcmRouter::send_xcm(dest, Xcm(vec![instruction]))?; + let message = Xcm(vec![instruction]); + let message_hash = message.using_encoded(blake2_256); + let context = XcmContext::with_message_hash(message_hash); + T::XcmRouter::send_xcm(dest, message, context)?; VersionNotifiers::::insert(XCM_VERSION, &versioned_dest, query_id); let query_status = QueryStatus::VersionNotifier { origin: versioned_dest, is_active: false }; @@ -1147,7 +1157,10 @@ pub mod pallet { let versioned_dest = LatestVersionedMultiLocation(&dest); let query_id = VersionNotifiers::::take(XCM_VERSION, versioned_dest) .ok_or(XcmError::InvalidLocation)?; - T::XcmRouter::send_xcm(dest.clone(), Xcm(vec![UnsubscribeVersion]))?; + let message = Xcm(vec![UnsubscribeVersion]); + let message_hash = message.using_encoded(blake2_256); + let context = XcmContext::with_message_hash(message_hash); + T::XcmRouter::send_xcm(dest.clone(), message, context)?; Queries::::remove(query_id); Ok(()) } @@ -1165,7 +1178,9 @@ pub mod pallet { message.0.insert(0, DescendOrigin(interior)) }; log::trace!(target: "xcm::send_xcm", "dest: {:?}, message: {:?}", &dest, &message); - T::XcmRouter::send_xcm(dest, message) + let message_hash = message.using_encoded(blake2_256); + let context = XcmContext::with_message_hash(message_hash); + T::XcmRouter::send_xcm(dest, message, context) } pub fn check_account() -> T::AccountId { @@ -1354,7 +1369,12 @@ pub mod pallet { /// /// If the `location` has an ongoing notification and when this function is called, then an /// error should be returned. - fn start(dest: &MultiLocation, query_id: QueryId, max_weight: u64) -> XcmResult { + fn start( + dest: &MultiLocation, + query_id: QueryId, + max_weight: u64, + _context: XcmContext, + ) -> XcmResult { let versioned_dest = LatestVersionedMultiLocation(dest); let already = VersionNotifyTargets::::contains_key(XCM_VERSION, versioned_dest); ensure!(!already, XcmError::InvalidLocation); @@ -1362,7 +1382,10 @@ pub mod pallet { let xcm_version = T::AdvertisedXcmVersion::get(); let response = Response::Version(xcm_version); let instruction = QueryResponse { query_id, response, max_weight, querier: None }; - T::XcmRouter::send_xcm(dest.clone(), Xcm(vec![instruction]))?; + let message = Xcm(vec![instruction]); + let message_hash = message.using_encoded(blake2_256); + let context = XcmContext::with_message_hash(message_hash); + T::XcmRouter::send_xcm(dest.clone(), message, context)?; let value = (query_id, max_weight, xcm_version); VersionNotifyTargets::::insert(XCM_VERSION, versioned_dest, value); @@ -1371,7 +1394,7 @@ pub mod pallet { /// Stop notifying `location` should the XCM change. This is a no-op if there was never a /// subscription. - fn stop(dest: &MultiLocation) -> XcmResult { + fn stop(dest: &MultiLocation, _context: XcmContext) -> XcmResult { VersionNotifyTargets::::remove(XCM_VERSION, LatestVersionedMultiLocation(dest)); Ok(()) } @@ -1384,7 +1407,7 @@ pub mod pallet { } impl DropAssets for Pallet { - fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, _context: XcmContext) -> Weight { if assets.is_empty() { return 0 } @@ -1402,6 +1425,7 @@ pub mod pallet { origin: &MultiLocation, ticket: &MultiLocation, assets: &MultiAssets, + _context: XcmContext, ) -> bool { let mut versioned = VersionedMultiAssets::from(assets.clone()); match (ticket.parents, &ticket.interior) { @@ -1449,6 +1473,7 @@ pub mod pallet { querier: Option<&MultiLocation>, response: Response, max_weight: Weight, + _context: XcmContext, ) -> Weight { match (response, Queries::::get(query_id)) { ( @@ -1704,6 +1729,7 @@ impl> ConvertOrigin for XcmPassthrough, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); match kind { diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 9a4099834f1c..e94bac5a76d0 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -220,6 +220,12 @@ pub struct XcmContext { } impl XcmContext { + /// Constructor which sets the message hash to the supplied parameter and leaves the origin and + /// topic unset. + pub fn with_message_hash(message_hash: XcmHash) -> XcmContext { + XcmContext { origin: None, message_hash, topic: None } + } + /// Helper function to create a bogus empty context for testing purposes. /// /// This function should only be used in cases where the context is sure to be unused. diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 6674f2d73ba3..0205820697bc 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -302,7 +302,7 @@ pub type SendResult = result::Result; /// /// A sender that only passes the message through and does nothing. /// struct Sender1; /// impl SendXcm for Sender1 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { +/// fn send_xcm(destination: impl Into, message: Xcm<()>, _: XcmContext) -> SendResult { /// return Err(SendError::CannotReachDestination(destination.into(), message)) /// } /// } @@ -310,7 +310,7 @@ pub type SendResult = result::Result; /// /// A sender that accepts a message that has an X2 junction, otherwise stops the routing. /// struct Sender2; /// impl SendXcm for Sender2 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { +/// fn send_xcm(destination: impl Into, message: Xcm<()>, _: XcmContext) -> SendResult { /// if let MultiLocation { parents: 0, interior: X2(j1, j2) } = destination.into() { /// Ok(VersionedXcm::from(message).using_encoded(blake2_256)) /// } else { @@ -322,7 +322,7 @@ pub type SendResult = result::Result; /// /// A sender that accepts a message from a parent, passing through otherwise. /// struct Sender3; /// impl SendXcm for Sender3 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { +/// fn send_xcm(destination: impl Into, message: Xcm<()>, _: XcmContext) -> SendResult { /// let destination = destination.into(); /// match destination { /// MultiLocation { parents: 1, interior: Here } @@ -340,17 +340,22 @@ pub type SendResult = result::Result; /// require_weight_at_most: 0, /// call: call.into(), /// }]); +/// let message_hash = message.using_encoded(blake2_256); /// /// assert!( /// // Sender2 will block this. -/// <(Sender1, Sender2, Sender3) as SendXcm>::send_xcm(Parent, message.clone()) -/// .is_err() +/// <(Sender1, Sender2, Sender3) as SendXcm>::send_xcm( +/// Parent, message.clone(), XcmContext::with_message_hash(message_hash), +/// ) +/// .is_err() /// ); /// /// assert!( /// // Sender3 will catch this. -/// <(Sender1, Sender3) as SendXcm>::send_xcm(Parent, message.clone()) -/// .is_ok() +/// <(Sender1, Sender3) as SendXcm>::send_xcm( +/// Parent, message.clone(), XcmContext::with_message_hash(message_hash), +/// ) +/// .is_ok() /// ); /// # } /// ``` diff --git a/xcm/xcm-builder/src/currency_adapter.rs b/xcm/xcm-builder/src/currency_adapter.rs index 23da4fcfc8a4..5628c5fb184a 100644 --- a/xcm/xcm-builder/src/currency_adapter.rs +++ b/xcm/xcm-builder/src/currency_adapter.rs @@ -19,7 +19,7 @@ use frame_support::traits::{ExistenceRequirement::AllowDeath, Get, WithdrawReasons}; use sp_runtime::traits::{CheckedSub, SaturatedConversion}; use sp_std::{convert::TryInto, marker::PhantomData, result}; -use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result}; +use xcm::latest::{Error as XcmError, MultiAsset, MultiLocation, Result, XcmContext}; use xcm_executor::{ traits::{Convert, MatchesFungible, TransactAsset}, Assets, @@ -96,7 +96,7 @@ impl< > TransactAsset for CurrencyAdapter { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset) -> Result { + fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) -> Result { log::trace!(target: "xcm::currency_adapter", "can_check_in origin: {:?}, what: {:?}", _origin, what); // Check we handle this asset. let amount: Currency::Balance = @@ -116,7 +116,7 @@ impl< Ok(()) } - fn check_in(_origin: &MultiLocation, what: &MultiAsset) { + fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) { log::trace!(target: "xcm::currency_adapter", "check_in origin: {:?}, what: {:?}", _origin, what); if let Some(amount) = Matcher::matches_fungible(what) { if let Some(checked_account) = CheckedAccount::get() { @@ -135,7 +135,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset) { + fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: XcmContext) { log::trace!(target: "xcm::currency_adapter", "check_out dest: {:?}, what: {:?}", _dest, what); if let Some(amount) = Matcher::matches_fungible(what) { if let Some(checked_account) = CheckedAccount::get() { @@ -144,7 +144,7 @@ impl< } } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, _context: XcmContext) -> Result { log::trace!(target: "xcm::currency_adapter", "deposit_asset what: {:?}, who: {:?}", what, who); // Check we handle this asset. let amount: u128 = @@ -157,7 +157,11 @@ impl< Ok(()) } - fn withdraw_asset(what: &MultiAsset, who: &MultiLocation) -> result::Result { + fn withdraw_asset( + what: &MultiAsset, + who: &MultiLocation, + _context: XcmContext, + ) -> result::Result { log::trace!(target: "xcm::currency_adapter", "withdraw_asset what: {:?}, who: {:?}", what, who); // Check we handle this asset. let amount: u128 = diff --git a/xcm/xcm-builder/src/filter_asset_location.rs b/xcm/xcm-builder/src/filter_asset_location.rs index cb404a4dbce9..108da0e47be1 100644 --- a/xcm/xcm-builder/src/filter_asset_location.rs +++ b/xcm/xcm-builder/src/filter_asset_location.rs @@ -18,13 +18,17 @@ use frame_support::traits::Get; use sp_std::marker::PhantomData; -use xcm::latest::{AssetId::Concrete, MultiAsset, MultiAssetFilter, MultiLocation}; +use xcm::latest::{AssetId::Concrete, MultiAsset, MultiAssetFilter, MultiLocation, XcmContext}; use xcm_executor::traits::FilterAssetLocation; /// Accepts an asset iff it is a native asset. pub struct NativeAsset; impl FilterAssetLocation for NativeAsset { - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn filter_asset_location( + asset: &MultiAsset, + origin: &MultiLocation, + _context: XcmContext, + ) -> bool { log::trace!(target: "xcm::filter_asset_location", "NativeAsset asset: {:?}, origin: {:?}", asset, origin); matches!(asset.id, Concrete(ref id) if id == origin) } @@ -33,7 +37,11 @@ impl FilterAssetLocation for NativeAsset { /// Accepts an asset if it is contained in the given `T`'s `Get` implementation. pub struct Case(PhantomData); impl> FilterAssetLocation for Case { - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn filter_asset_location( + asset: &MultiAsset, + origin: &MultiLocation, + _context: XcmContext, + ) -> bool { log::trace!(target: "xcm::filter_asset_location", "Case asset: {:?}, origin: {:?}", asset, origin); let (a, o) = T::get(); a.matches(asset) && &o == origin diff --git a/xcm/xcm-builder/src/fungibles_adapter.rs b/xcm/xcm-builder/src/fungibles_adapter.rs index 082e3b6955df..62ada8c6c51a 100644 --- a/xcm/xcm-builder/src/fungibles_adapter.rs +++ b/xcm/xcm-builder/src/fungibles_adapter.rs @@ -22,7 +22,7 @@ use xcm::latest::{ AssetId::{Abstract, Concrete}, Error as XcmError, Fungibility::Fungible, - Junction, MultiAsset, MultiLocation, Result, + Junction, MultiAsset, MultiLocation, Result, XcmContext, }; use xcm_executor::traits::{Convert, Error as MatchError, MatchesFungibles, TransactAsset}; @@ -122,6 +122,7 @@ impl< what: &MultiAsset, from: &MultiLocation, to: &MultiLocation, + _context: XcmContext, ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", @@ -165,7 +166,7 @@ impl< CheckingAccount, > { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset) -> Result { + fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) -> Result { log::trace!( target: "xcm::fungibles_adapter", "can_check_in origin: {:?}, what: {:?}", @@ -183,7 +184,7 @@ impl< Ok(()) } - fn check_in(_origin: &MultiLocation, what: &MultiAsset) { + fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) { log::trace!( target: "xcm::fungibles_adapter", "check_in origin: {:?}, what: {:?}", @@ -201,7 +202,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset) { + fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: XcmContext) { log::trace!( target: "xcm::fungibles_adapter", "check_out dest: {:?}, what: {:?}", @@ -216,7 +217,7 @@ impl< } } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, _context: XcmContext) -> Result { log::trace!( target: "xcm::fungibles_adapter", "deposit_asset what: {:?}, who: {:?}", @@ -233,6 +234,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, + _context: XcmContext, ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", @@ -267,7 +269,7 @@ impl< > TransactAsset for FungiblesAdapter { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset) -> Result { + fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) -> Result { FungiblesMutateAdapter::< Assets, Matcher, @@ -275,10 +277,10 @@ impl< AccountId, CheckAsset, CheckingAccount, - >::can_check_in(origin, what) + >::can_check_in(origin, what, context) } - fn check_in(origin: &MultiLocation, what: &MultiAsset) { + fn check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) { FungiblesMutateAdapter::< Assets, Matcher, @@ -286,10 +288,10 @@ impl< AccountId, CheckAsset, CheckingAccount, - >::check_in(origin, what) + >::check_in(origin, what, context) } - fn check_out(dest: &MultiLocation, what: &MultiAsset) { + fn check_out(dest: &MultiLocation, what: &MultiAsset, context: XcmContext) { FungiblesMutateAdapter::< Assets, Matcher, @@ -297,10 +299,10 @@ impl< AccountId, CheckAsset, CheckingAccount, - >::check_out(dest, what) + >::check_out(dest, what, context) } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: XcmContext) -> Result { FungiblesMutateAdapter::< Assets, Matcher, @@ -308,12 +310,13 @@ impl< AccountId, CheckAsset, CheckingAccount, - >::deposit_asset(what, who) + >::deposit_asset(what, who, context) } fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, + context: XcmContext, ) -> result::Result { FungiblesMutateAdapter::< Assets, @@ -322,16 +325,17 @@ impl< AccountId, CheckAsset, CheckingAccount, - >::withdraw_asset(what, who) + >::withdraw_asset(what, who, context) } fn transfer_asset( what: &MultiAsset, from: &MultiLocation, to: &MultiLocation, + context: XcmContext, ) -> result::Result { FungiblesTransferAdapter::::transfer_asset( - what, from, to, + what, from, to, context, ) } } diff --git a/xcm/xcm-builder/src/origin_conversion.rs b/xcm/xcm-builder/src/origin_conversion.rs index b42c8fcff9ef..912109093102 100644 --- a/xcm/xcm-builder/src/origin_conversion.rs +++ b/xcm/xcm-builder/src/origin_conversion.rs @@ -20,7 +20,9 @@ use frame_support::traits::{EnsureOrigin, Get, GetBacking, OriginTrait}; use frame_system::RawOrigin as SystemRawOrigin; use polkadot_parachain::primitives::IsSystem; use sp_std::{convert::TryInto, marker::PhantomData}; -use xcm::latest::{BodyId, BodyPart, Junction, Junctions::*, MultiLocation, NetworkId, OriginKind}; +use xcm::latest::{ + BodyId, BodyPart, Junction, Junctions::*, MultiLocation, NetworkId, OriginKind, XcmContext, +}; use xcm_executor::traits::{Convert, ConvertOrigin}; /// Sovereign accounts use the system's `Signed` origin with an account ID derived from the `LocationConverter`. @@ -35,6 +37,7 @@ where fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -56,6 +59,7 @@ impl ConvertOrigin for ParentAsSuperuser { fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ParentAsSuperuser origin: {:?}, kind: {:?}", origin, kind); @@ -74,6 +78,7 @@ impl, Origin: OriginTrait> ConvertOrigin fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ChildSystemParachainAsSuperuser origin: {:?}, kind: {:?}", origin, kind); @@ -94,6 +99,7 @@ impl, Origin: OriginTrait> ConvertOrigin fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -118,6 +124,7 @@ impl, Origin: From> ConvertOrigin, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ChildParachainAsNative origin: {:?}, kind: {:?}", origin, kind); @@ -140,6 +147,7 @@ impl, Origin: From> ConvertOrigin, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -165,6 +173,7 @@ impl, Origin> ConvertOrigin fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "RelayChainAsNative origin: {:?}, kind: {:?}", origin, kind); @@ -185,6 +194,7 @@ where fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -212,6 +222,7 @@ where fn convert_origin( origin: impl Into, kind: OriginKind, + _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( diff --git a/xcm/xcm-builder/src/test_utils.rs b/xcm/xcm-builder/src/test_utils.rs index a3742f656da3..eecb5ef2d551 100644 --- a/xcm/xcm-builder/src/test_utils.rs +++ b/xcm/xcm-builder/src/test_utils.rs @@ -37,13 +37,18 @@ parameter_types! { pub struct TestSubscriptionService; impl VersionChangeNotifier for TestSubscriptionService { - fn start(location: &MultiLocation, query_id: QueryId, max_weight: u64) -> XcmResult { + fn start( + location: &MultiLocation, + query_id: QueryId, + max_weight: u64, + _context: XcmContext, + ) -> XcmResult { let mut r = SubscriptionRequests::get(); r.push((location.clone(), Some((query_id, max_weight)))); SubscriptionRequests::set(r); Ok(()) } - fn stop(location: &MultiLocation) -> XcmResult { + fn stop(location: &MultiLocation, _context: XcmContext) -> XcmResult { let mut r = SubscriptionRequests::get(); r.retain(|(l, _q)| l != location); r.push((location.clone(), None)); @@ -63,7 +68,7 @@ parameter_types! { pub struct TestAssetTrap; impl DropAssets for TestAssetTrap { - fn drop_assets(origin: &MultiLocation, assets: Assets) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, _context: XcmContext) -> Weight { let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get(); t.push((origin.clone(), assets.into())); TrappedAssets::set(t); @@ -72,7 +77,12 @@ impl DropAssets for TestAssetTrap { } impl ClaimAssets for TestAssetTrap { - fn claim_assets(origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets) -> bool { + fn claim_assets( + origin: &MultiLocation, + ticket: &MultiLocation, + what: &MultiAssets, + _context: XcmContext, + ) -> bool { let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get(); if let (0, X1(GeneralIndex(i))) = (ticket.parents, &ticket.interior) { if let Some((l, a)) = t.get(*i as usize) { diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index b2e96340c1a5..e8073f0007a2 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -51,7 +51,11 @@ pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> { } pub struct TestSendXcm; impl SendXcm for TestSendXcm { - fn send_xcm(dest: impl Into, msg: opaque::Xcm) -> SendResult { + fn send_xcm( + dest: impl Into, + msg: opaque::Xcm, + _context: XcmContext, + ) -> SendResult { SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg.clone()))); Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } diff --git a/xcm/xcm-executor/src/traits/on_response.rs b/xcm/xcm-executor/src/traits/on_response.rs index 334535ed3682..e2d3771233a2 100644 --- a/xcm/xcm-executor/src/traits/on_response.rs +++ b/xcm/xcm-executor/src/traits/on_response.rs @@ -27,7 +27,6 @@ pub trait OnResponse { origin: &MultiLocation, query_id: u64, querier: Option<&MultiLocation>, - context: XcmContext, ) -> bool; /// Handler for receiving a `response` from `origin` relating to `query_id` initiated by /// `querier`. @@ -45,7 +44,6 @@ impl OnResponse for () { _origin: &MultiLocation, _query_id: u64, _querier: Option<&MultiLocation>, - _context: XcmContext, ) -> bool { false } From bc9cdca24d5388519c11457618e7fc6d253f4876 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 29 Jan 2022 10:18:01 -0800 Subject: [PATCH 11/73] Revert adding context as an arg to SendXcm trait methods --- runtime/common/src/xcm_sender.rs | 2 +- runtime/test-runtime/src/xcm_config.rs | 2 +- xcm/pallet-xcm/Cargo.toml | 4 +-- xcm/pallet-xcm/src/lib.rs | 28 ++++----------- xcm/src/v3/traits.rs | 14 ++------ xcm/xcm-executor/src/lib.rs | 49 ++++++++++---------------- 6 files changed, 32 insertions(+), 67 deletions(-) diff --git a/runtime/common/src/xcm_sender.rs b/runtime/common/src/xcm_sender.rs index 27f4124cc0d2..b9e5d3e42c7f 100644 --- a/runtime/common/src/xcm_sender.rs +++ b/runtime/common/src/xcm_sender.rs @@ -27,7 +27,7 @@ pub struct ChildParachainRouter(PhantomData<(T, W)>); impl SendXcm for ChildParachainRouter { - fn send_xcm(dest: impl Into, msg: Xcm<()>, _context: XcmContext) -> SendResult { + fn send_xcm(dest: impl Into, msg: Xcm<()>) -> SendResult { let dest = dest.into(); match dest { MultiLocation { parents: 0, interior: X1(Parachain(id)) } => { diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 470f171b4374..0fc52c687cc6 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -38,7 +38,7 @@ pub type LocalOriginToLocation = ( pub struct DoNothingRouter; impl SendXcm for DoNothingRouter { - fn send_xcm(_dest: impl Into, msg: Xcm<()>, _context: XcmContext) -> SendResult { + fn send_xcm(_dest: impl Into, msg: Xcm<()>) -> SendResult { Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } } diff --git a/xcm/pallet-xcm/Cargo.toml b/xcm/pallet-xcm/Cargo.toml index f18860687767..32e464ac5d17 100644 --- a/xcm/pallet-xcm/Cargo.toml +++ b/xcm/pallet-xcm/Cargo.toml @@ -13,7 +13,6 @@ log = { version = "0.4.14", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } frame-system = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } sp-core = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } sp-std = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "master" } @@ -23,8 +22,9 @@ xcm-executor = { path = "../xcm-executor", default-features = false } [dev-dependencies] pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" } polkadot-runtime-parachains = { path = "../../runtime/parachains" } -xcm-builder = { path = "../xcm-builder" } polkadot-parachain = { path = "../../parachain" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +xcm-builder = { path = "../xcm-builder" } [features] default = ["std"] diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index aeb384e0768f..f9cbc11e8de4 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -26,7 +26,6 @@ mod tests; use codec::{Decode, Encode, EncodeLike}; use frame_support::traits::{Contains, EnsureOrigin, Get, OriginTrait}; use scale_info::TypeInfo; -use sp_io::hashing::blake2_256; use sp_runtime::{ traits::{BadOrigin, Saturating}, RuntimeDebug, @@ -1047,9 +1046,7 @@ pub mod pallet { let response = Response::Version(xcm_version); let message = Xcm(vec![QueryResponse { query_id, response, max_weight, querier: None }]); - let message_hash = message.using_encoded(blake2_256); - let context = XcmContext::with_message_hash(message_hash); - let event = match T::XcmRouter::send_xcm(new_key.clone(), message, context) { + let event = match T::XcmRouter::send_xcm(new_key.clone(), message) { Ok(_) => { let value = (query_id, max_weight, xcm_version); VersionNotifyTargets::::insert(XCM_VERSION, key, value); @@ -1100,10 +1097,8 @@ pub mod pallet { max_weight, querier: None, }]); - let message_hash = message.using_encoded(blake2_256); - let context = XcmContext::with_message_hash(message_hash); let event = - match T::XcmRouter::send_xcm(new_key.clone(), message, context) { + match T::XcmRouter::send_xcm(new_key.clone(), message) { Ok(_) => { VersionNotifyTargets::::insert( XCM_VERSION, @@ -1140,10 +1135,7 @@ pub mod pallet { }); // TODO #3735: Correct weight. let instruction = SubscribeVersion { query_id, max_response_weight: 0 }; - let message = Xcm(vec![instruction]); - let message_hash = message.using_encoded(blake2_256); - let context = XcmContext::with_message_hash(message_hash); - T::XcmRouter::send_xcm(dest, message, context)?; + T::XcmRouter::send_xcm(dest, Xcm(vec![instruction]))?; VersionNotifiers::::insert(XCM_VERSION, &versioned_dest, query_id); let query_status = QueryStatus::VersionNotifier { origin: versioned_dest, is_active: false }; @@ -1157,10 +1149,7 @@ pub mod pallet { let versioned_dest = LatestVersionedMultiLocation(&dest); let query_id = VersionNotifiers::::take(XCM_VERSION, versioned_dest) .ok_or(XcmError::InvalidLocation)?; - let message = Xcm(vec![UnsubscribeVersion]); - let message_hash = message.using_encoded(blake2_256); - let context = XcmContext::with_message_hash(message_hash); - T::XcmRouter::send_xcm(dest.clone(), message, context)?; + T::XcmRouter::send_xcm(dest.clone(), Xcm(vec![UnsubscribeVersion]))?; Queries::::remove(query_id); Ok(()) } @@ -1178,9 +1167,7 @@ pub mod pallet { message.0.insert(0, DescendOrigin(interior)) }; log::trace!(target: "xcm::send_xcm", "dest: {:?}, message: {:?}", &dest, &message); - let message_hash = message.using_encoded(blake2_256); - let context = XcmContext::with_message_hash(message_hash); - T::XcmRouter::send_xcm(dest, message, context) + T::XcmRouter::send_xcm(dest, message) } pub fn check_account() -> T::AccountId { @@ -1382,10 +1369,7 @@ pub mod pallet { let xcm_version = T::AdvertisedXcmVersion::get(); let response = Response::Version(xcm_version); let instruction = QueryResponse { query_id, response, max_weight, querier: None }; - let message = Xcm(vec![instruction]); - let message_hash = message.using_encoded(blake2_256); - let context = XcmContext::with_message_hash(message_hash); - T::XcmRouter::send_xcm(dest.clone(), message, context)?; + T::XcmRouter::send_xcm(dest.clone(), Xcm(vec![instruction]))?; let value = (query_id, max_weight, xcm_version); VersionNotifyTargets::::insert(XCM_VERSION, versioned_dest, value); diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 0205820697bc..1f4c102df006 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -365,23 +365,15 @@ pub trait SendXcm { /// If it is not a destination which can be reached with this type but possibly could by others, then it *MUST* /// return `CannotReachDestination`. Any other error will cause the tuple implementation to exit early without /// trying other type fields. - fn send_xcm( - destination: impl Into, - message: Xcm<()>, - context: XcmContext, - ) -> SendResult; + fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl SendXcm for Tuple { - fn send_xcm( - destination: impl Into, - message: Xcm<()>, - context: XcmContext, - ) -> SendResult { + fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { for_tuples!( #( // we shadow `destination` and `message` in each expansion for the next one. - let (destination, message) = match Tuple::send_xcm(destination, message, context.clone()) { + let (destination, message) = match Tuple::send_xcm(destination, message) { Err(SendError::CannotReachDestination(d, m)) => (d, m), o @ _ => return o, }; diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index ead827b3986c..0cd9a0ea07eb 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -359,17 +359,17 @@ impl XcmExecutor { }, TransferReserveAsset { mut assets, dest, xcm } => { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; // Take `assets` from the origin account (on-chain) and place into dest account. for asset in assets.inner() { - Config::AssetTransactor::beam_asset(asset, origin, &dest, context.clone())?; + let context = + XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + Config::AssetTransactor::beam_asset(asset, origin, &dest, context)?; } let ancestry = Config::LocationInverter::ancestry(); assets.reanchor(&dest, &ancestry).map_err(|()| XcmError::MultiLocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message), context)?; + Config::XcmSender::send_xcm(dest, Xcm(message))?; Ok(()) }, ReceiveTeleportedAsset(assets) => { @@ -460,11 +460,9 @@ impl XcmExecutor { Ok(()) }, ReportError(response_info) => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Report the given result by sending a QueryResponse XCM to a previously given outcome // destination if one was registered. - Self::respond(context, Response::ExecutionResult(self.error), response_info)?; + Self::respond(self.origin.clone(), Response::ExecutionResult(self.error), response_info)?; Ok(()) }, DepositAsset { assets, beneficiary } => { @@ -477,23 +475,21 @@ impl XcmExecutor { Ok(()) }, DepositReserveAsset { assets, dest, xcm } => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; let deposited = self.holding.saturating_take(assets); for asset in deposited.assets_iter() { - Config::AssetTransactor::deposit_asset(&asset, &dest, context.clone())?; + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + Config::AssetTransactor::deposit_asset(&asset, &dest, context)?; } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot // be reanchored because we have already called `deposit_asset` on all assets. let assets = Self::reanchored(deposited, &dest, None); let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message), context)?; + Config::XcmSender::send_xcm(dest, Xcm(message))?; Ok(()) }, InitiateReserveWithdraw { assets, reserve, xcm } => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Note that here we are able to place any assets which could not be reanchored // back into Holding. let assets = Self::reanchored( @@ -503,33 +499,31 @@ impl XcmExecutor { ); let mut message = vec![WithdrawAsset(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(reserve, Xcm(message), context)?; + Config::XcmSender::send_xcm(reserve, Xcm(message))?; Ok(()) }, InitiateTeleport { assets, dest, xcm } => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // We must do this first in order to resolve wildcards. let assets = self.holding.saturating_take(assets); for asset in assets.assets_iter() { - Config::AssetTransactor::check_out(&dest, &asset, context.clone()); + let context = + XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + Config::AssetTransactor::check_out(&dest, &asset, context); } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot // be reanchored because we have already checked all assets out. let assets = Self::reanchored(assets, &dest, None); let mut message = vec![ReceiveTeleportedAsset(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); - Config::XcmSender::send_xcm(dest, Xcm(message), context)?; + Config::XcmSender::send_xcm(dest, Xcm(message))?; Ok(()) }, ReportHolding { response_info, assets } => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Note that we pass `None` as `maybe_failed_bin` since no assets were ever removed // from Holding. let assets = Self::reanchored(self.holding.min(&assets), &response_info.destination, None); - Self::respond(context, Response::Assets(assets), response_info)?; + Self::respond(self.origin.clone(), Response::Assets(assets), response_info)?; Ok(()) }, BuyExecution { fees, weight_limit } => { @@ -610,8 +604,6 @@ impl XcmExecutor { Ok(()) }, QueryPallet { module_name, response_info } => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; let pallets = Config::PalletInstancesInfo::infos() .into_iter() .filter(|x| x.module_name.as_bytes() == &module_name[..]) @@ -629,7 +621,7 @@ impl XcmExecutor { let querier = Self::to_querier(self.origin.clone(), &destination)?; let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); - Config::XcmSender::send_xcm(destination, message, context)?; + Config::XcmSender::send_xcm(destination, message)?; Ok(()) }, ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => { @@ -646,10 +638,8 @@ impl XcmExecutor { Ok(()) }, ReportTransactStatus(response_info) => { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; Self::respond( - context, + self.origin.clone(), Response::DispatchResult(self.transact_status.clone()), response_info, )?; @@ -692,16 +682,15 @@ impl XcmExecutor { /// /// The `local_querier` argument is the querier (if any) specified from the *local* perspective. fn respond( - context: XcmContext, + local_querier: Option, response: Response, info: QueryResponseInfo, ) -> Result { - let local_querier = context.origin.clone(); let querier = Self::to_querier(local_querier, &info.destination)?; let QueryResponseInfo { destination, query_id, max_weight } = info; let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); - Config::XcmSender::send_xcm(destination, message, context).map_err(Into::into) + Config::XcmSender::send_xcm(destination, message).map_err(Into::into) } /// NOTE: Any assets which were unable to be reanchored are introduced into `failed_bin`. From ce34e1a934b8fa28866906420505e3bdcc3764df Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 29 Jan 2022 13:33:27 -0800 Subject: [PATCH 12/73] Revert adding context argument to ConvertOrigin trait methods --- xcm/pallet-xcm/src/lib.rs | 1 - xcm/xcm-builder/src/origin_conversion.rs | 13 +------------ xcm/xcm-executor/src/lib.rs | 4 +--- xcm/xcm-executor/src/traits/conversion.rs | 9 +++------ 4 files changed, 5 insertions(+), 22 deletions(-) diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index f9cbc11e8de4..42509da2ff87 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -1713,7 +1713,6 @@ impl> ConvertOrigin for XcmPassthrough, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); match kind { diff --git a/xcm/xcm-builder/src/origin_conversion.rs b/xcm/xcm-builder/src/origin_conversion.rs index 912109093102..b42c8fcff9ef 100644 --- a/xcm/xcm-builder/src/origin_conversion.rs +++ b/xcm/xcm-builder/src/origin_conversion.rs @@ -20,9 +20,7 @@ use frame_support::traits::{EnsureOrigin, Get, GetBacking, OriginTrait}; use frame_system::RawOrigin as SystemRawOrigin; use polkadot_parachain::primitives::IsSystem; use sp_std::{convert::TryInto, marker::PhantomData}; -use xcm::latest::{ - BodyId, BodyPart, Junction, Junctions::*, MultiLocation, NetworkId, OriginKind, XcmContext, -}; +use xcm::latest::{BodyId, BodyPart, Junction, Junctions::*, MultiLocation, NetworkId, OriginKind}; use xcm_executor::traits::{Convert, ConvertOrigin}; /// Sovereign accounts use the system's `Signed` origin with an account ID derived from the `LocationConverter`. @@ -37,7 +35,6 @@ where fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -59,7 +56,6 @@ impl ConvertOrigin for ParentAsSuperuser { fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ParentAsSuperuser origin: {:?}, kind: {:?}", origin, kind); @@ -78,7 +74,6 @@ impl, Origin: OriginTrait> ConvertOrigin fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ChildSystemParachainAsSuperuser origin: {:?}, kind: {:?}", origin, kind); @@ -99,7 +94,6 @@ impl, Origin: OriginTrait> ConvertOrigin fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -124,7 +118,6 @@ impl, Origin: From> ConvertOrigin, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "ChildParachainAsNative origin: {:?}, kind: {:?}", origin, kind); @@ -147,7 +140,6 @@ impl, Origin: From> ConvertOrigin, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -173,7 +165,6 @@ impl, Origin> ConvertOrigin fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!(target: "xcm::origin_conversion", "RelayChainAsNative origin: {:?}, kind: {:?}", origin, kind); @@ -194,7 +185,6 @@ where fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( @@ -222,7 +212,6 @@ where fn convert_origin( origin: impl Into, kind: OriginKind, - _context: XcmContext, ) -> Result { let origin = origin.into(); log::trace!( diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 0cd9a0ea07eb..011d6f4c5b2e 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -402,13 +402,11 @@ impl XcmExecutor { Transact { origin_kind, require_weight_at_most, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| XcmError::FailedToDecode)?; let dispatch_origin = - Config::OriginConverter::convert_origin(origin, origin_kind, context) + Config::OriginConverter::convert_origin(origin, origin_kind) .map_err(|_| XcmError::BadOrigin)?; let weight = message_call.get_dispatch_info().weight; ensure!(weight <= require_weight_at_most, XcmError::MaxWeightInvalid); diff --git a/xcm/xcm-executor/src/traits/conversion.rs b/xcm/xcm-executor/src/traits/conversion.rs index 51e82ee5c7dd..d8c50037662d 100644 --- a/xcm/xcm-executor/src/traits/conversion.rs +++ b/xcm/xcm-executor/src/traits/conversion.rs @@ -16,7 +16,7 @@ use parity_scale_codec::{Decode, Encode}; use sp_std::{borrow::Borrow, convert::TryFrom, prelude::*, result::Result}; -use xcm::latest::{MultiLocation, OriginKind, XcmContext}; +use xcm::latest::{MultiLocation, OriginKind}; /// Generic third-party conversion trait. Use this when you don't want to force the user to use default /// implementations of `From` and `Into` for the types you wish to convert between. @@ -178,7 +178,6 @@ pub trait ConvertOrigin { fn convert_origin( origin: impl Into, kind: OriginKind, - context: XcmContext, ) -> Result; } @@ -187,10 +186,9 @@ impl ConvertOrigin for Tuple { fn convert_origin( origin: impl Into, kind: OriginKind, - context: XcmContext, ) -> Result { for_tuples!( #( - let origin = match Tuple::convert_origin(origin, kind, context.clone()) { + let origin = match Tuple::convert_origin(origin, kind) { Err(o) => o, r => return r }; @@ -198,10 +196,9 @@ impl ConvertOrigin for Tuple { let origin = origin.into(); log::trace!( target: "xcm::convert_origin", - "could not convert: origin: {:?}, kind: {:?}, context: {:?}", + "could not convert: origin: {:?}, kind: {:?}", origin, kind, - context, ); Err(origin) } From 96241253c574e2e5cada6c5fef691bd26f0f8e61 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 29 Jan 2022 15:08:57 -0800 Subject: [PATCH 13/73] cargo fmt --- xcm/pallet-xcm/src/lib.rs | 24 +++++++++++------------- xcm/xcm-executor/src/lib.rs | 18 ++++++++++++------ 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index 42509da2ff87..29c20cd52cf1 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -1097,19 +1097,17 @@ pub mod pallet { max_weight, querier: None, }]); - let event = - match T::XcmRouter::send_xcm(new_key.clone(), message) { - Ok(_) => { - VersionNotifyTargets::::insert( - XCM_VERSION, - versioned_key, - (query_id, max_weight, xcm_version), - ); - Event::VersionChangeNotified(new_key, xcm_version) - }, - Err(e) => - Event::NotifyTargetSendFail(new_key, query_id, e.into()), - }; + let event = match T::XcmRouter::send_xcm(new_key.clone(), message) { + Ok(_) => { + VersionNotifyTargets::::insert( + XCM_VERSION, + versioned_key, + (query_id, max_weight, xcm_version), + ); + Event::VersionChangeNotified(new_key, xcm_version) + }, + Err(e) => Event::NotifyTargetSendFail(new_key, query_id, e.into()), + }; Self::deposit_event(event); weight_used.saturating_accrue(todo_vnt_notify_migrate_weight); } diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 011d6f4c5b2e..9fdbad66477f 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -361,8 +361,11 @@ impl XcmExecutor { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; // Take `assets` from the origin account (on-chain) and place into dest account. for asset in assets.inner() { - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let context = XcmContext { + origin: Some(origin.clone()), + message_hash, + topic: self.topic, + }; Config::AssetTransactor::beam_asset(asset, origin, &dest, context)?; } let ancestry = Config::LocationInverter::ancestry(); @@ -405,9 +408,8 @@ impl XcmExecutor { // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| XcmError::FailedToDecode)?; - let dispatch_origin = - Config::OriginConverter::convert_origin(origin, origin_kind) - .map_err(|_| XcmError::BadOrigin)?; + let dispatch_origin = Config::OriginConverter::convert_origin(origin, origin_kind) + .map_err(|_| XcmError::BadOrigin)?; let weight = message_call.get_dispatch_info().weight; ensure!(weight <= require_weight_at_most, XcmError::MaxWeightInvalid); let maybe_actual_weight = match message_call.dispatch(dispatch_origin) { @@ -460,7 +462,11 @@ impl XcmExecutor { ReportError(response_info) => { // Report the given result by sending a QueryResponse XCM to a previously given outcome // destination if one was registered. - Self::respond(self.origin.clone(), Response::ExecutionResult(self.error), response_info)?; + Self::respond( + self.origin.clone(), + Response::ExecutionResult(self.error), + response_info, + )?; Ok(()) }, DepositAsset { assets, beneficiary } => { From 10f19785d8410779c90fcec0de2ad81a42268a72 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 29 Jan 2022 15:20:00 -0800 Subject: [PATCH 14/73] Do not change the API of XcmExecutor::execute --- xcm/xcm-executor/src/lib.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 9fdbad66477f..d53f30ec010b 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -129,7 +129,7 @@ impl ExecuteXcm for XcmExecutor { let message_hash = message.using_encoded(sp_io::hashing::blake2_256); while !message.0.is_empty() { - let result = vm.execute(message, message_hash); + let result = vm.execute_with_hash(message, message_hash); log::trace!(target: "xcm::execute_xcm_in_credit", "result: {:?}", result); message = if let Err(error) = result { vm.total_surplus.saturating_accrue(error.weight); @@ -189,7 +189,11 @@ impl XcmExecutor { /// Execute the XCM program fragment and report back the error and which instruction caused it, /// or `Ok` if there was no error. - pub fn execute( + pub fn execute(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { + self.execute_with_hash(xcm, xcm.using_encoded(sp_io::hashing::blake2_256)) + } + + fn execute_with_hash( &mut self, xcm: Xcm, message_hash: [u8; 32], From fa0d0d0b7dc1c83c0bb606b0873b15d2d85e410d Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 29 Jan 2022 15:33:39 -0800 Subject: [PATCH 15/73] Fixes --- .../src/fungible/benchmarking.rs | 30 +++++++++++++++++-- .../src/generic/benchmarking.rs | 12 +++++++- xcm/pallet-xcm-benchmarks/src/mock.rs | 1 + 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs index 14bbe676fa66..b4a7eebf972a 100644 --- a/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs @@ -44,7 +44,15 @@ benchmarks_instance_pallet! { let worst_case_holding = T::worst_case_holding(0); let asset = T::get_multi_asset(); - >::deposit_asset(&asset, &sender_location).unwrap(); + >::deposit_asset( + &asset, + &sender_location, + XcmContext { + origin: Some(sender_location.clone()), + message_hash: [0; 32], + topic: None, + }, + ).unwrap(); // check the assets of origin. assert!(!T::TransactAsset::balance(&sender_account).is_zero()); @@ -69,7 +77,15 @@ benchmarks_instance_pallet! { let dest_location = T::valid_destination()?; let dest_account = T::AccountIdConverter::convert(dest_location.clone()).unwrap(); - >::deposit_asset(&asset, &sender_location).unwrap(); + >::deposit_asset( + &asset, + &sender_location, + XcmContext { + origin: Some(sender_location.clone()), + message_hash: [0; 32], + topic: None, + }, + ).unwrap(); assert!(T::TransactAsset::balance(&dest_account).is_zero()); let mut executor = new_executor::(sender_location); @@ -88,7 +104,15 @@ benchmarks_instance_pallet! { let dest_account = T::AccountIdConverter::convert(dest_location.clone()).unwrap(); let asset = T::get_multi_asset(); - >::deposit_asset(&asset, &sender_location).unwrap(); + >::deposit_asset( + &asset, + &sender_location, + XcmContext { + origin: Some(sender_location.clone()), + message_hash: [0; 32], + topic: None, + }, + ).unwrap(); let assets: MultiAssets = vec![ asset ].into(); assert!(T::TransactAsset::balance(&dest_account).is_zero()); diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index a55cd27b9113..a1560897b008 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -234,6 +234,11 @@ benchmarks! { ::AssetTrap::drop_assets( &origin, assets.clone().into(), + XcmContext { + origin: Some(origin.clone()), + message_hash: [0; 32], + topic: None, + }, ); // Assets should be in the trap now. @@ -285,7 +290,12 @@ benchmarks! { ::SubscriptionService::start( &origin, query_id, - max_response_weight + max_response_weight, + XcmContext { + origin: Some(origin.clone()), + message_hash: [0; 32], + topic: None, + }, ).map_err(|_| "Could not start subscription")?; assert!(::SubscriptionService::is_subscribed(&origin)); diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index d5e3b3151ee7..3f7c007026d3 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -37,6 +37,7 @@ impl xcm_executor::traits::OnResponse for DevNull { _: Option<&MultiLocation>, _: Response, _: Weight, + _: XcmContext, ) -> Weight { 0 } From b4661eaa90a43dad76c5b768e8c351152944db5f Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sat, 29 Jan 2022 15:35:58 -0800 Subject: [PATCH 16/73] Fixes --- xcm/xcm-builder/tests/mock/mod.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index e8073f0007a2..b2e96340c1a5 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -51,11 +51,7 @@ pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> { } pub struct TestSendXcm; impl SendXcm for TestSendXcm { - fn send_xcm( - dest: impl Into, - msg: opaque::Xcm, - _context: XcmContext, - ) -> SendResult { + fn send_xcm(dest: impl Into, msg: opaque::Xcm) -> SendResult { SENT_XCM.with(|q| q.borrow_mut().push((dest.into(), msg.clone()))); Ok(VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256)) } From eee33acbba4ed02096aea900bd80eb7a8e73f335 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 1 Feb 2022 18:56:31 -0800 Subject: [PATCH 17/73] Fixes --- xcm/src/v3/mod.rs | 4 +++- xcm/xcm-executor/src/lib.rs | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index e94bac5a76d0..00d2c6a97f33 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -225,11 +225,13 @@ impl XcmContext { pub fn with_message_hash(message_hash: XcmHash) -> XcmContext { XcmContext { origin: None, message_hash, topic: None } } +} +#[cfg(test)] +impl XcmContext { /// Helper function to create a bogus empty context for testing purposes. /// /// This function should only be used in cases where the context is sure to be unused. - #[cfg(test)] pub fn empty() -> Self { XcmContext { origin: None, message_hash: [0; 32], topic: None } } diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index d53f30ec010b..18e396a00174 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -190,7 +190,8 @@ impl XcmExecutor { /// Execute the XCM program fragment and report back the error and which instruction caused it, /// or `Ok` if there was no error. pub fn execute(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { - self.execute_with_hash(xcm, xcm.using_encoded(sp_io::hashing::blake2_256)) + let message_hash = xcm.using_encoded(sp_io::hashing::blake2_256); + self.execute_with_hash(xcm, message_hash) } fn execute_with_hash( From 149735b7e5bac571fa83e490089155ee478f1142 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 2 Feb 2022 05:07:50 -0800 Subject: [PATCH 18/73] Fixes --- runtime/test-runtime/src/xcm_config.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 0fc52c687cc6..86cf12598e13 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -47,11 +47,15 @@ pub type Barrier = AllowUnpaidExecutionFrom; pub struct DummyAssetTransactor; impl TransactAsset for DummyAssetTransactor { - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation) -> XcmResult { + fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: XcmContext) -> XcmResult { Ok(()) } - fn withdraw_asset(_what: &MultiAsset, _who: &MultiLocation) -> Result { + fn withdraw_asset( + _what: &MultiAsset, + _who: &MultiLocation, + _context: XcmContext, + ) -> Result { let asset: MultiAsset = (Parent, 100_000).into(); Ok(asset.into()) } From e4be71e0c359218c3b1155161b23ba3274778fa4 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 2 Feb 2022 20:47:12 -0800 Subject: [PATCH 19/73] Remove convenience method --- xcm/src/v3/mod.rs | 10 -------- xcm/xcm-executor/src/traits/transact_asset.rs | 24 +++++++++++++++---- 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 00d2c6a97f33..b4fac46a6833 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -227,16 +227,6 @@ impl XcmContext { } } -#[cfg(test)] -impl XcmContext { - /// Helper function to create a bogus empty context for testing purposes. - /// - /// This function should only be used in cases where the context is sure to be unused. - pub fn empty() -> Self { - XcmContext { origin: None, message_hash: [0; 32], topic: None } - } -} - /// Cross-Consensus Message: A message from one consensus system to another. /// /// Consensus systems that may send and receive messages include blockchains and smart contracts. diff --git a/xcm/xcm-executor/src/traits/transact_asset.rs b/xcm/xcm-executor/src/traits/transact_asset.rs index de704fb6f9f8..9a9c1be9c218 100644 --- a/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/xcm/xcm-executor/src/traits/transact_asset.rs @@ -331,7 +331,11 @@ mod tests { (UnimplementedTransactor, NotFoundTransactor, UnimplementedTransactor); assert_eq!( - MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), + MultiTransactor::deposit_asset( + &(Here, 1).into(), + &Here.into(), + XcmContext::with_message_hash([0; 32]), + ), Err(XcmError::AssetNotFound) ); } @@ -341,7 +345,11 @@ mod tests { type MultiTransactor = (UnimplementedTransactor, NotFoundTransactor, SuccessfulTransactor); assert_eq!( - MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), + MultiTransactor::deposit_asset( + &(Here, 1).into(), + &Here.into(), + XcmContext::with_message_hash([0; 32]), + ), Ok(()) ); } @@ -351,7 +359,11 @@ mod tests { type MultiTransactor = (OverflowTransactor, SuccessfulTransactor); assert_eq!( - MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), + MultiTransactor::deposit_asset( + &(Here, 1).into(), + &Here.into(), + XcmContext::with_message_hash([0; 32]), + ), Err(XcmError::Overflow) ); } @@ -361,7 +373,11 @@ mod tests { type MultiTransactor = (SuccessfulTransactor, OverflowTransactor); assert_eq!( - MultiTransactor::deposit_asset(&(Here, 1).into(), &Here.into(), XcmContext::empty()), + MultiTransactor::deposit_asset( + &(Here, 1).into(), + &Here.into(), + XcmContext::with_message_hash([0; 32]), + ), Ok(()), ); } From 5b523b082851d8d4dd4c3b9166fda26a2595d072 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 4 Feb 2022 06:41:40 -0800 Subject: [PATCH 20/73] Fixes --- xcm/xcm-builder/src/mock.rs | 25 +++++++++++++++++++++---- xcm/xcm-builder/src/tests.rs | 1 + 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/xcm/xcm-builder/src/mock.rs b/xcm/xcm-builder/src/mock.rs index 54a090b7a3b7..d1b26c75468c 100644 --- a/xcm/xcm-builder/src/mock.rs +++ b/xcm/xcm-builder/src/mock.rs @@ -126,13 +126,21 @@ pub fn add_asset>(who: u64, what: AssetArg) { pub struct TestAssetTransactor; impl TransactAsset for TestAssetTransactor { - fn deposit_asset(what: &MultiAsset, who: &MultiLocation) -> Result<(), XcmError> { + fn deposit_asset( + what: &MultiAsset, + who: &MultiLocation, + _context: XcmContext, + ) -> Result<(), XcmError> { let who = to_account(who.clone()).map_err(|_| XcmError::LocationCannotHold)?; add_asset(who, what.clone()); Ok(()) } - fn withdraw_asset(what: &MultiAsset, who: &MultiLocation) -> Result { + fn withdraw_asset( + what: &MultiAsset, + who: &MultiLocation, + _context: XcmContext, + ) -> Result { let who = to_account(who.clone()).map_err(|_| XcmError::LocationCannotHold)?; ASSETS.with(|a| { a.borrow_mut() @@ -193,14 +201,22 @@ pub fn add_teleporter(from: MultiLocation, asset: MultiAssetFilter) { } pub struct TestIsReserve; impl FilterAssetLocation for TestIsReserve { - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn filter_asset_location( + asset: &MultiAsset, + origin: &MultiLocation, + _context: XcmContext, + ) -> bool { IS_RESERVE .with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.matches(asset)))) } } pub struct TestIsTeleporter; impl FilterAssetLocation for TestIsTeleporter { - fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { + fn filter_asset_location( + asset: &MultiAsset, + origin: &MultiLocation, + _context: XcmContext, + ) -> bool { IS_TELEPORTER .with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.matches(asset)))) } @@ -232,6 +248,7 @@ impl OnResponse for TestResponseHandler { _querier: Option<&MultiLocation>, response: xcm::latest::Response, _max_weight: Weight, + _context: XcmContext, ) -> Weight { QUERIES.with(|q| { q.borrow_mut().entry(query_id).and_modify(|v| { diff --git a/xcm/xcm-builder/src/tests.rs b/xcm/xcm-builder/src/tests.rs index 81513e267511..61a5507defa3 100644 --- a/xcm/xcm-builder/src/tests.rs +++ b/xcm/xcm-builder/src/tests.rs @@ -25,6 +25,7 @@ fn basic_setup_works() { assert!(::IsReserve::filter_asset_location( &(Parent, 100).into(), &Parent.into(), + XcmContext::with_message_hash([0; 32]), )); assert_eq!(to_account(X1(Parachain(1)).into()), Ok(1001)); From 2a1f0e2d9ff7792eca3fd406aac733eb07bf5664 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 4 Feb 2022 07:25:01 -0800 Subject: [PATCH 21/73] Fixes --- xcm/pallet-xcm-benchmarks/src/generic/mock.rs | 4 ++-- xcm/pallet-xcm-benchmarks/src/mock.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 07283deee74c..8bc0e1086278 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -84,11 +84,11 @@ impl frame_system::Config for Test { /// The benchmarks in this pallet should never need an asset transactor to begin with. pub struct NoAssetTransactor; impl xcm_executor::traits::TransactAsset for NoAssetTransactor { - fn deposit_asset(_: &MultiAsset, _: &MultiLocation) -> Result<(), XcmError> { + fn deposit_asset(_: &MultiAsset, _: &MultiLocation, _: XcmContext) -> Result<(), XcmError> { unreachable!(); } - fn withdraw_asset(_: &MultiAsset, _: &MultiLocation) -> Result { + fn withdraw_asset(_: &MultiAsset, _: &MultiLocation, _: XcmContext) -> Result { unreachable!(); } } diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index 3f7c007026d3..065917a62b79 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -66,7 +66,7 @@ parameter_types! { pub struct AllAssetLocationsPass; impl FilterAssetLocation for AllAssetLocationsPass { - fn filter_asset_location(_: &MultiAsset, _: &MultiLocation) -> bool { + fn filter_asset_location(_: &MultiAsset, _: &MultiLocation, _: XcmContext) -> bool { true } } From f431c558b1dc92334f61680927bd7cb269f71872 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 4 Feb 2022 07:31:45 -0800 Subject: [PATCH 22/73] cargo fmt --- xcm/pallet-xcm-benchmarks/src/generic/mock.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 8bc0e1086278..faae236731f9 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -88,7 +88,11 @@ impl xcm_executor::traits::TransactAsset for NoAssetTransactor { unreachable!(); } - fn withdraw_asset(_: &MultiAsset, _: &MultiLocation, _: XcmContext) -> Result { + fn withdraw_asset( + _: &MultiAsset, + _: &MultiLocation, + _: XcmContext, + ) -> Result { unreachable!(); } } From d6fedf9a9e9eff82cc57a4861640433cf95919bd Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 4 Feb 2022 08:10:31 -0800 Subject: [PATCH 23/73] Fixes --- xcm/src/v3/traits.rs | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 1f4c102df006..0d0ca998e334 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -302,7 +302,7 @@ pub type SendResult = result::Result; /// /// A sender that only passes the message through and does nothing. /// struct Sender1; /// impl SendXcm for Sender1 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>, _: XcmContext) -> SendResult { +/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { /// return Err(SendError::CannotReachDestination(destination.into(), message)) /// } /// } @@ -310,7 +310,7 @@ pub type SendResult = result::Result; /// /// A sender that accepts a message that has an X2 junction, otherwise stops the routing. /// struct Sender2; /// impl SendXcm for Sender2 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>, _: XcmContext) -> SendResult { +/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { /// if let MultiLocation { parents: 0, interior: X2(j1, j2) } = destination.into() { /// Ok(VersionedXcm::from(message).using_encoded(blake2_256)) /// } else { @@ -322,7 +322,7 @@ pub type SendResult = result::Result; /// /// A sender that accepts a message from a parent, passing through otherwise. /// struct Sender3; /// impl SendXcm for Sender3 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>, _: XcmContext) -> SendResult { +/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { /// let destination = destination.into(); /// match destination { /// MultiLocation { parents: 1, interior: Here } @@ -344,18 +344,12 @@ pub type SendResult = result::Result; /// /// assert!( /// // Sender2 will block this. -/// <(Sender1, Sender2, Sender3) as SendXcm>::send_xcm( -/// Parent, message.clone(), XcmContext::with_message_hash(message_hash), -/// ) -/// .is_err() +/// <(Sender1, Sender2, Sender3) as SendXcm>::send_xcm(Parent, message.clone()).is_err() /// ); /// /// assert!( /// // Sender3 will catch this. -/// <(Sender1, Sender3) as SendXcm>::send_xcm( -/// Parent, message.clone(), XcmContext::with_message_hash(message_hash), -/// ) -/// .is_ok() +/// <(Sender1, Sender3) as SendXcm>::send_xcm(Parent, message.clone()).is_ok() /// ); /// # } /// ``` From b044e794fd06bce6b89a19fe5a4430ad1de07b27 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 4 Feb 2022 18:19:23 -0800 Subject: [PATCH 24/73] Add benchmarks for XCM topic instructions --- .../src/generic/benchmarking.rs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index a1560897b008..b18662cb24a5 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -451,6 +451,29 @@ benchmarks! { assert_eq!(executor.transact_status, MaybeErrorCode::Success); } + set_topic { + let mut executor = new_executor::(Default::default()); + + let instruction = Instruction::SetTopic([1; 32]); + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + assert_eq!(executor.topic, Some([1; 32])); + } + + clear_topic { + let mut executor = new_executor::(Default::default()); + executor.topic = Some([2; 32]); + + let instruction = Instruction::ClearTopic; + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + assert_eq!(executor.topic, None); + } + impl_benchmark_test_suite!( Pallet, crate::generic::mock::new_test_ext(), From 163a456e038b8dcfc0966b6c85672556963b6e8e Mon Sep 17 00:00:00 2001 From: Parity Bot Date: Sat, 5 Feb 2022 03:03:07 +0000 Subject: [PATCH 25/73] cargo run --quiet --profile=production --features=runtime-benchmarks -- benchmark --chain=westend-dev --steps=50 --repeat=20 --pallet=pallet_xcm_benchmarks::generic --extrinsic=* --execution=wasm --wasm-execution=compiled --heap-pages=4096 --header=./file_header.txt --template=./xcm/pallet-xcm-benchmarks/template.hbs --output=./runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs --- .../xcm/pallet_xcm_benchmarks_generic.rs | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index ac76a7b94b38..0c5ab409be77 100644 --- a/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,11 +17,11 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 128 +//! DATE: 2022-02-05, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 1024 // Executed Command: -// target/release/polkadot +// target/production/polkadot // benchmark // --chain=westend-dev // --steps=50 @@ -51,38 +51,38 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn report_holding() -> Weight { - (35_446_000 as Weight) + (24_000_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } pub(crate) fn buy_execution() -> Weight { - (5_228_000 as Weight) + (3_377_000 as Weight) } // Storage: XcmPallet Queries (r:1 w:0) pub(crate) fn query_response() -> Weight { - (18_708_000 as Weight) + (12_418_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } pub(crate) fn transact() -> Weight { - (20_401_000 as Weight) + (12_795_000 as Weight) } pub(crate) fn refund_surplus() -> Weight { - (5_238_000 as Weight) + (3_485_000 as Weight) } pub(crate) fn set_error_handler() -> Weight { - (5_104_000 as Weight) + (3_314_000 as Weight) } pub(crate) fn set_appendix() -> Weight { - (5_095_000 as Weight) + (3_334_000 as Weight) } pub(crate) fn clear_error() -> Weight { - (5_010_000 as Weight) + (3_240_000 as Weight) } pub(crate) fn descend_origin() -> Weight { - (6_368_000 as Weight) + (4_339_000 as Weight) } pub(crate) fn clear_origin() -> Weight { - (5_011_000 as Weight) + (3_338_000 as Weight) } // Storage: XcmPallet SupportedVersion (r:1 w:0) // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) @@ -90,18 +90,18 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn report_error() -> Weight { - (27_823_000 as Weight) + (20_469_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: XcmPallet AssetTraps (r:1 w:1) pub(crate) fn claim_asset() -> Weight { - (12_402_000 as Weight) + (7_749_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } pub(crate) fn trap() -> Weight { - (5_022_000 as Weight) + (3_271_000 as Weight) } // Storage: XcmPallet VersionNotifyTargets (r:1 w:1) // Storage: XcmPallet SupportedVersion (r:1 w:0) @@ -110,13 +110,13 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn subscribe_version() -> Weight { - (32_492_000 as Weight) + (22_263_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: XcmPallet VersionNotifyTargets (r:0 w:1) pub(crate) fn unsubscribe_version() -> Weight { - (7_777_000 as Weight) + (5_366_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: XcmPallet SupportedVersion (r:1 w:0) @@ -125,21 +125,21 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn initiate_reserve_withdraw() -> Weight { - (37_066_000 as Weight) + (23_659_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } pub(crate) fn burn_asset() -> Weight { - (7_935_000 as Weight) + (4_910_000 as Weight) } pub(crate) fn expect_asset() -> Weight { - (5_237_000 as Weight) + (3_488_000 as Weight) } pub(crate) fn expect_origin() -> Weight { - (5_245_000 as Weight) + (3_400_000 as Weight) } pub(crate) fn expect_error() -> Weight { - (5_062_000 as Weight) + (3_358_000 as Weight) } // Storage: XcmPallet SupportedVersion (r:1 w:0) // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) @@ -147,12 +147,12 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn query_pallet() -> Weight { - (28_876_000 as Weight) + (21_841_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } pub(crate) fn expect_pallet() -> Weight { - (5_526_000 as Weight) + (3_716_000 as Weight) } // Storage: XcmPallet SupportedVersion (r:1 w:0) // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) @@ -160,17 +160,17 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn report_transact_status() -> Weight { - (27_889_000 as Weight) + (20_503_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } pub(crate) fn clear_transact_status() -> Weight { - (5_100_000 as Weight) + (3_270_000 as Weight) } pub(crate) fn set_topic() -> Weight { - (1_000 as Weight) + (3_269_000 as Weight) } pub(crate) fn clear_topic() -> Weight { - (1_000 as Weight) + (3_268_000 as Weight) } } From 62f4193b76c90c843249e8139086e33fdf329986 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Fri, 18 Feb 2022 17:06:47 -0800 Subject: [PATCH 26/73] Remove context argument on FilterAssetLocation --- xcm/xcm-executor/src/lib.rs | 13 ++----------- .../src/traits/filter_asset_location.rs | 19 +++++-------------- 2 files changed, 7 insertions(+), 25 deletions(-) diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index fb8ef984b1ab..2e335c893620 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -338,14 +338,9 @@ impl XcmExecutor { // check whether we trust origin to be our reserve location for this asset. let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.drain().into_iter() { - let context = XcmContext { - origin: Some(origin.clone()), - message_hash, - topic: self.topic, - }; // Must ensure that we recognise the asset as being managed by the origin. ensure!( - Config::IsReserve::filter_asset_location(&asset, &origin, context), + Config::IsReserve::filter_asset_location(&asset, &origin), XcmError::UntrustedReserveLocation ); self.subsume_asset(asset)?; @@ -392,11 +387,7 @@ impl XcmExecutor { // We only trust the origin to send us assets that they identify as their // sovereign assets. ensure!( - Config::IsTeleporter::filter_asset_location( - asset, - &origin, - context.clone() - ), + Config::IsTeleporter::filter_asset_location(asset, &origin), XcmError::UntrustedTeleportLocation ); // We should check that the asset can actually be teleported in (for this to be in error, there diff --git a/xcm/xcm-executor/src/traits/filter_asset_location.rs b/xcm/xcm-executor/src/traits/filter_asset_location.rs index 8e0ede91d07e..31b9c47a828c 100644 --- a/xcm/xcm-executor/src/traits/filter_asset_location.rs +++ b/xcm/xcm-executor/src/traits/filter_asset_location.rs @@ -14,36 +14,27 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use xcm::latest::{MultiAsset, MultiLocation, XcmContext}; +use xcm::latest::{MultiAsset, MultiLocation}; /// Filters assets/location pairs. /// /// Can be amalgamated into tuples. If any item returns `true`, it short-circuits, else `false` is returned. pub trait FilterAssetLocation { /// A filter to distinguish between asset/location pairs. - fn filter_asset_location( - asset: &MultiAsset, - origin: &MultiLocation, - context: XcmContext, - ) -> bool; + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool; } #[impl_trait_for_tuples::impl_for_tuples(30)] impl FilterAssetLocation for Tuple { - fn filter_asset_location( - what: &MultiAsset, - origin: &MultiLocation, - context: XcmContext, - ) -> bool { + fn filter_asset_location(what: &MultiAsset, origin: &MultiLocation) -> bool { for_tuples!( #( - if Tuple::filter_asset_location(what, origin, context.clone()) { return true } + if Tuple::filter_asset_location(what, origin) { return true } )* ); log::trace!( target: "xcm::filter_asset_location", - "got filtered: what: {:?}, origin: {:?}, context: {:?}", + "got filtered: what: {:?}, origin: {:?}", what, origin, - context, ); false } From 166cac1319761d6b73d1075a8b01020aeac650ac Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 16:50:25 -0800 Subject: [PATCH 27/73] Fixes --- xcm/xcm-builder/src/filter_asset_location.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/xcm/xcm-builder/src/filter_asset_location.rs b/xcm/xcm-builder/src/filter_asset_location.rs index 108da0e47be1..7bd76aec4580 100644 --- a/xcm/xcm-builder/src/filter_asset_location.rs +++ b/xcm/xcm-builder/src/filter_asset_location.rs @@ -24,11 +24,7 @@ use xcm_executor::traits::FilterAssetLocation; /// Accepts an asset iff it is a native asset. pub struct NativeAsset; impl FilterAssetLocation for NativeAsset { - fn filter_asset_location( - asset: &MultiAsset, - origin: &MultiLocation, - _context: XcmContext, - ) -> bool { + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { log::trace!(target: "xcm::filter_asset_location", "NativeAsset asset: {:?}, origin: {:?}", asset, origin); matches!(asset.id, Concrete(ref id) if id == origin) } @@ -37,11 +33,7 @@ impl FilterAssetLocation for NativeAsset { /// Accepts an asset if it is contained in the given `T`'s `Get` implementation. pub struct Case(PhantomData); impl> FilterAssetLocation for Case { - fn filter_asset_location( - asset: &MultiAsset, - origin: &MultiLocation, - _context: XcmContext, - ) -> bool { + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { log::trace!(target: "xcm::filter_asset_location", "Case asset: {:?}, origin: {:?}", asset, origin); let (a, o) = T::get(); a.matches(asset) && &o == origin From 95a5855bf5146be8cc588244bb1547db5266cfa4 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 16:50:57 -0800 Subject: [PATCH 28/73] Remove unused import --- xcm/xcm-builder/src/filter_asset_location.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/xcm-builder/src/filter_asset_location.rs b/xcm/xcm-builder/src/filter_asset_location.rs index 7bd76aec4580..cb404a4dbce9 100644 --- a/xcm/xcm-builder/src/filter_asset_location.rs +++ b/xcm/xcm-builder/src/filter_asset_location.rs @@ -18,7 +18,7 @@ use frame_support::traits::Get; use sp_std::marker::PhantomData; -use xcm::latest::{AssetId::Concrete, MultiAsset, MultiAssetFilter, MultiLocation, XcmContext}; +use xcm::latest::{AssetId::Concrete, MultiAsset, MultiAssetFilter, MultiLocation}; use xcm_executor::traits::FilterAssetLocation; /// Accepts an asset iff it is a native asset. From c9b1ca70fb67e00a8d1dc90c7623c00a04d22f43 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 16:55:54 -0800 Subject: [PATCH 29/73] Fixes --- xcm/pallet-xcm-benchmarks/src/mock.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index 16b3c0ce8848..ac4199618f3b 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -70,7 +70,7 @@ parameter_types! { pub struct AllAssetLocationsPass; impl FilterAssetLocation for AllAssetLocationsPass { - fn filter_asset_location(_: &MultiAsset, _: &MultiLocation, _: XcmContext) -> bool { + fn filter_asset_location(_: &MultiAsset, _: &MultiLocation) -> bool { true } } From 8f41fbe7e2947ea6e971a8802db1e3f7517f7387 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 17:00:34 -0800 Subject: [PATCH 30/73] Fixes --- xcm/xcm-builder/src/tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/xcm/xcm-builder/src/tests.rs b/xcm/xcm-builder/src/tests.rs index 55d6ac468ae9..b9611fad829d 100644 --- a/xcm/xcm-builder/src/tests.rs +++ b/xcm/xcm-builder/src/tests.rs @@ -24,7 +24,6 @@ fn basic_setup_works() { assert!(::IsReserve::filter_asset_location( &(Parent, 100).into(), &Parent.into(), - XcmContext::with_message_hash([0; 32]), )); assert_eq!(to_account(Parachain(1)), Ok(1001)); From fd28e0e7e6782ff7eba4430e000063c5d78c13bd Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 17:55:53 -0800 Subject: [PATCH 31/73] Fixes --- xcm/xcm-builder/src/mock.rs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/xcm/xcm-builder/src/mock.rs b/xcm/xcm-builder/src/mock.rs index efba182fa94e..8e854efa957a 100644 --- a/xcm/xcm-builder/src/mock.rs +++ b/xcm/xcm-builder/src/mock.rs @@ -292,22 +292,14 @@ pub fn clear_universal_aliases() { pub struct TestIsReserve; impl FilterAssetLocation for TestIsReserve { - fn filter_asset_location( - asset: &MultiAsset, - origin: &MultiLocation, - _context: XcmContext, - ) -> bool { + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { IS_RESERVE .with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.matches(asset)))) } } pub struct TestIsTeleporter; impl FilterAssetLocation for TestIsTeleporter { - fn filter_asset_location( - asset: &MultiAsset, - origin: &MultiLocation, - _context: XcmContext, - ) -> bool { + fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool { IS_TELEPORTER .with(|r| r.borrow().get(origin).map_or(false, |v| v.iter().any(|a| a.matches(asset)))) } From d5819b37d0a4a69bc2d3aa7719c8549e96967b3e Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 21:25:47 -0800 Subject: [PATCH 32/73] Accept XCM hash parameter in ExecuteXcm trait methods --- runtime/parachains/src/ump.rs | 2 +- xcm/pallet-xcm-benchmarks/src/mock.rs | 1 - xcm/pallet-xcm/Cargo.toml | 1 + xcm/pallet-xcm/src/lib.rs | 8 +- xcm/pallet-xcm/src/tests.rs | 86 +++-- xcm/src/v3/traits.rs | 17 +- xcm/xcm-builder/src/tests/assets.rs | 363 ++++++++++-------- xcm/xcm-builder/src/tests/basic.rs | 6 +- xcm/xcm-builder/src/tests/bridging/mod.rs | 14 +- xcm/xcm-builder/src/tests/expecting.rs | 160 ++++---- xcm/xcm-builder/src/tests/locking.rs | 98 +++-- xcm/xcm-builder/src/tests/origins.rs | 35 +- xcm/xcm-builder/src/tests/querying.rs | 41 +- xcm/xcm-builder/src/tests/transacting.rs | 21 +- .../src/tests/version_subscriptions.rs | 32 +- xcm/xcm-builder/src/tests/weight.rs | 10 +- xcm/xcm-builder/tests/scenarios.rs | 152 ++++---- xcm/xcm-executor/src/lib.rs | 14 +- 18 files changed, 592 insertions(+), 469 deletions(-) diff --git a/runtime/parachains/src/ump.rs b/runtime/parachains/src/ump.rs index 344b0f7d439f..caa14325c656 100644 --- a/runtime/parachains/src/ump.rs +++ b/runtime/parachains/src/ump.rs @@ -115,7 +115,7 @@ impl, C: Config> UmpSink for XcmSi }, Ok(Ok(xcm_message)) => { let xcm_junction = Junction::Parachain(origin.into()); - let outcome = XcmExecutor::execute_xcm(xcm_junction, xcm_message, max_weight); + let outcome = XcmExecutor::execute_xcm(xcm_junction, xcm_message, id, max_weight); match outcome { Outcome::Error(XcmError::WeightLimitReached(required)) => Err((id, required)), outcome => { diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index ac4199618f3b..219effd2532e 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -16,7 +16,6 @@ use crate::*; use frame_support::{parameter_types, weights::Weight}; -use xcm::VersionedXcm; use xcm_executor::traits::FilterAssetLocation; // An xcm sender/receiver akin to > /dev/null diff --git a/xcm/pallet-xcm/Cargo.toml b/xcm/pallet-xcm/Cargo.toml index 5d8db03df5c4..bd986828e079 100644 --- a/xcm/pallet-xcm/Cargo.toml +++ b/xcm/pallet-xcm/Cargo.toml @@ -36,6 +36,7 @@ std = [ "sp-std/std", "sp-io/std", "sp-core/std", + "sp-io/std", "sp-runtime/std", "frame-support/std", "frame-system/std", diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index dfc3bff1311b..aaf6d12fd6c0 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -810,6 +810,7 @@ pub mod pallet { max_weight: Weight, ) -> DispatchResultWithPostInfo { let origin_location = T::ExecuteXcmOrigin::ensure_origin(origin)?; + let hash = message.using_encoded(sp_io::hashing::blake2_256); let message = (*message).try_into().map_err(|()| Error::::BadVersion)?; let value = (origin_location, message); ensure!(T::XcmExecuteFilter::contains(&value), Error::::Filtered); @@ -817,6 +818,7 @@ pub mod pallet { let outcome = T::XcmExecutor::execute_xcm_in_credit( origin_location, message, + hash, max_weight, max_weight, ); @@ -1056,8 +1058,9 @@ impl Pallet { let mut message = Xcm(vec![TransferReserveAsset { assets, dest, xcm }]); let weight = T::Weigher::weight(&mut message).map_err(|()| Error::::UnweighableMessage)?; + let hash = message.using_encoded(sp_io::hashing::blake2_256); let outcome = - T::XcmExecutor::execute_xcm_in_credit(origin_location, message, weight, weight); + T::XcmExecutor::execute_xcm_in_credit(origin_location, message, hash, weight, weight); Self::deposit_event(Event::Attempted(outcome)); Ok(()) } @@ -1114,8 +1117,9 @@ impl Pallet { Xcm(vec![WithdrawAsset(assets), InitiateTeleport { assets: Wild(All), dest, xcm }]); let weight = T::Weigher::weight(&mut message).map_err(|()| Error::::UnweighableMessage)?; + let hash = message.using_encoded(sp_io::hashing::blake2_256); let outcome = - T::XcmExecutor::execute_xcm_in_credit(origin_location, message, weight, weight); + T::XcmExecutor::execute_xcm_in_credit(origin_location, message, hash, weight, weight); Self::deposit_event(Event::Attempted(outcome)); Ok(()) } diff --git a/xcm/pallet-xcm/src/tests.rs b/xcm/pallet-xcm/src/tests.rs index 5739f57f0a97..ad1b1ee35a54 100644 --- a/xcm/pallet-xcm/src/tests.rs +++ b/xcm/pallet-xcm/src/tests.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use codec::Encode; use crate::{ mock::*, AssetTraps, CurrentMigration, Error, LatestVersionedMultiLocation, Queries, QueryStatus, VersionDiscoveryQueue, VersionNotifiers, VersionNotifyTargets, @@ -77,14 +78,16 @@ fn report_outcome_notify_works() { }; assert_eq!(crate::Queries::::iter().collect::>(), vec![(0, status)]); + let message = Xcm(vec![QueryResponse { + query_id: 0, + response: Response::ExecutionResult(None), + max_weight: 1_000_000, + querier: Some(querier), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(PARA_ID), - Xcm(vec![QueryResponse { - query_id: 0, - response: Response::ExecutionResult(None), - max_weight: 1_000_000, - querier: Some(querier), - }]), + message, hash, 1_000_000_000, ); assert_eq!(r, Outcome::Complete(1_000)); @@ -134,14 +137,16 @@ fn report_outcome_works() { }; assert_eq!(crate::Queries::::iter().collect::>(), vec![(0, status)]); + let message = Xcm(vec![QueryResponse { + query_id: 0, + response: Response::ExecutionResult(None), + max_weight: 0, + querier: Some(querier), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(PARA_ID), - Xcm(vec![QueryResponse { - query_id: 0, - response: Response::ExecutionResult(None), - max_weight: 0, - querier: Some(querier), - }]), + message, hash, 1_000_000_000, ); assert_eq!(r, Outcome::Complete(1_000)); @@ -174,14 +179,16 @@ fn custom_querier_works() { assert_eq!(crate::Queries::::iter().collect::>(), vec![(0, status)]); // Supplying no querier when one is expected will fail + let message = Xcm(vec![QueryResponse { + query_id: 0, + response: Response::ExecutionResult(None), + max_weight: 0, + querier: None, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm_in_credit( AccountId32 { network: None, id: ALICE.into() }, - Xcm(vec![QueryResponse { - query_id: 0, - response: Response::ExecutionResult(None), - max_weight: 0, - querier: None, - }]), + message, hash, 1_000_000_000, 1_000, ); @@ -197,14 +204,16 @@ fn custom_querier_works() { ); // Supplying the wrong querier will also fail + let message = Xcm(vec![QueryResponse { + query_id: 0, + response: Response::ExecutionResult(None), + max_weight: 0, + querier: Some(MultiLocation::here()), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm_in_credit( AccountId32 { network: None, id: ALICE.into() }, - Xcm(vec![QueryResponse { - query_id: 0, - response: Response::ExecutionResult(None), - max_weight: 0, - querier: Some(MultiLocation::here()), - }]), + message, hash, 1_000_000_000, 1_000, ); @@ -220,14 +229,16 @@ fn custom_querier_works() { ); // Multiple failures should not have changed the query state + let message = Xcm(vec![QueryResponse { + query_id: 0, + response: Response::ExecutionResult(None), + max_weight: 0, + querier: Some(querier), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( AccountId32 { network: None, id: ALICE.into() }, - Xcm(vec![QueryResponse { - query_id: 0, - response: Response::ExecutionResult(None), - max_weight: 0, - querier: Some(querier), - }]), + message, hash, 1_000_000_000, ); assert_eq!(r, Outcome::Complete(1_000)); @@ -815,7 +826,8 @@ fn subscription_side_works() { let remote: MultiLocation = Parachain(1000).into(); let weight = BaseXcmWeight::get(); let message = Xcm(vec![SubscribeVersion { query_id: 0, max_response_weight: 0 }]); - let r = XcmExecutor::::execute_xcm(remote.clone(), message, weight); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(remote.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let instr = QueryResponse { @@ -949,7 +961,8 @@ fn subscriber_side_subscription_works() { querier: None, }, ]); - let r = XcmExecutor::::execute_xcm(remote.clone(), message, weight); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(remote.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!(take_sent_xcm(), vec![]); @@ -966,7 +979,8 @@ fn subscriber_side_subscription_works() { querier: None, }, ]); - let r = XcmExecutor::::execute_xcm(remote.clone(), message, weight); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(remote.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); // This message can now be sent to remote as it's v2. @@ -1026,7 +1040,8 @@ fn auto_subscription_works() { querier: None, }, ]); - let r = XcmExecutor::::execute_xcm(remote0.clone(), message, weight); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(remote0.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); // This message can now be sent to remote0 as it's v2. @@ -1056,7 +1071,8 @@ fn auto_subscription_works() { querier: None, }, ]); - let r = XcmExecutor::::execute_xcm(remote1.clone(), message, weight); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(remote1.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); // v2 messages cannot be sent to remote1... diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index bfab64ebe0a2..82c4fe10797e 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -246,15 +246,17 @@ pub trait ExecuteXcm { fn execute( origin: impl Into, pre: Self::Prepared, + hash: XcmHash, weight_credit: Weight, ) -> Outcome; - /// Execute some XCM `message` from `origin` using no more than `weight_limit` weight. The weight limit is - /// a basic hard-limit and the implementation may place further restrictions or requirements on weight and - /// other aspects. + /// Execute some XCM `message` with the versioned `hash` from `origin` using no more than `weight_limit` weight. + /// The weight limit is a basic hard-limit and the implementation may place further restrictions or requirements + /// on weight and other aspects. fn execute_xcm( origin: impl Into, message: Xcm, + hash: XcmHash, weight_limit: Weight, ) -> Outcome { let origin = origin.into(); @@ -265,16 +267,17 @@ pub trait ExecuteXcm { message, weight_limit, ); - Self::execute_xcm_in_credit(origin, message, weight_limit, 0) + Self::execute_xcm_in_credit(origin, message, hash, weight_limit, 0) } - /// Execute some XCM `message` from `origin` using no more than `weight_limit` weight. + /// Execute some XCM `message` with the versioned `hash` from `origin` using no more than `weight_limit` weight. /// /// Some amount of `weight_credit` may be provided which, depending on the implementation, may allow /// execution without associated payment. fn execute_xcm_in_credit( origin: impl Into, message: Xcm, + hash: XcmHash, weight_limit: Weight, weight_credit: Weight, ) -> Outcome { @@ -286,7 +289,7 @@ pub trait ExecuteXcm { if xcm_weight > weight_limit { return Outcome::Error(Error::WeightLimitReached(xcm_weight)) } - Self::execute(origin, pre, weight_credit) + Self::execute(origin, pre, hash, weight_credit) } /// Deduct some `fees` to the sovereign account of the given `location` and place them as per @@ -310,7 +313,7 @@ impl ExecuteXcm for () { fn prepare(message: Xcm) -> result::Result> { Err(message) } - fn execute(_: impl Into, _: Self::Prepared, _: Weight) -> Outcome { + fn execute(_: impl Into, _: Self::Prepared, _: XcmHash, _: Weight) -> Outcome { unreachable!() } fn charge_fees( diff --git a/xcm/xcm-builder/src/tests/assets.rs b/xcm/xcm-builder/src/tests/assets.rs index e3d4c9ab75fe..5944707e11f5 100644 --- a/xcm/xcm-builder/src/tests/assets.rs +++ b/xcm/xcm-builder/src/tests/assets.rs @@ -21,20 +21,22 @@ fn exchange_asset_should_work() { AllowUnpaidFrom::set(vec![Parent.into()]); add_asset(Parent, (Parent, 1000)); set_exchange_assets(vec![(Here, 100).into()]); + let message = Xcm(vec![ + WithdrawAsset((Parent, 100).into()), + SetAppendix( + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] + .into(), + ), + ExchangeAsset { + give: Definite((Parent, 50).into()), + want: (Here, 50).into(), + maximal: true, + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parent, - Xcm(vec![ - WithdrawAsset((Parent, 100).into()), - SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] - .into(), - ), - ExchangeAsset { - give: Definite((Parent, 50).into()), - want: (Here, 50).into(), - maximal: true, - }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(40)); @@ -47,20 +49,22 @@ fn exchange_asset_without_maximal_should_work() { AllowUnpaidFrom::set(vec![Parent.into()]); add_asset(Parent, (Parent, 1000)); set_exchange_assets(vec![(Here, 100).into()]); + let message = Xcm(vec![ + WithdrawAsset((Parent, 100).into()), + SetAppendix( + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] + .into(), + ), + ExchangeAsset { + give: Definite((Parent, 50).into()), + want: (Here, 50).into(), + maximal: false, + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parent, - Xcm(vec![ - WithdrawAsset((Parent, 100).into()), - SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] - .into(), - ), - ExchangeAsset { - give: Definite((Parent, 50).into()), - want: (Here, 50).into(), - maximal: false, - }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(40)); @@ -73,20 +77,22 @@ fn exchange_asset_should_fail_when_no_deal_possible() { AllowUnpaidFrom::set(vec![Parent.into()]); add_asset(Parent, (Parent, 1000)); set_exchange_assets(vec![(Here, 100).into()]); + let message = Xcm(vec![ + WithdrawAsset((Parent, 150).into()), + SetAppendix( + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] + .into(), + ), + ExchangeAsset { + give: Definite((Parent, 150).into()), + want: (Here, 150).into(), + maximal: false, + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parent, - Xcm(vec![ - WithdrawAsset((Parent, 150).into()), - SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] - .into(), - ), - ExchangeAsset { - give: Definite((Parent, 150).into()), - want: (Here, 150).into(), - maximal: false, - }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(40, XcmError::NoDeal)); @@ -106,8 +112,9 @@ fn paying_reserve_deposit_should_work() { BuyExecution { fees, weight_limit: Limited(30) }, DepositAsset { assets: AllCounted(1).into(), beneficiary: Here.into() }, ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 50; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Here), vec![(Parent, 70).into()]); } @@ -119,12 +126,14 @@ fn transfer_should_work() { // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); // They want to transfer 100 of them to their sibling parachain #2 + let message = Xcm(vec![TransferAsset { + assets: (Here, 100).into(), + beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![TransferAsset { - assets: (Here, 100).into(), - beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -143,16 +152,18 @@ fn reserve_transfer_should_work() { // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. + let message = Xcm(vec![TransferReserveAsset { + assets: (Here, 100).into(), + dest: Parachain(2).into(), + xcm: Xcm::<()>(vec![DepositAsset { + assets: AllCounted(1).into(), + beneficiary: three.clone(), + }]), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![TransferReserveAsset { - assets: (Here, 100).into(), - dest: Parachain(2).into(), - xcm: Xcm::<()>(vec![DepositAsset { - assets: AllCounted(1).into(), - beneficiary: three.clone(), - }]), - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -178,13 +189,15 @@ fn burn_should_work() { // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); // They want to burn 100 of them + let message = Xcm(vec![ + WithdrawAsset((Here, 1000).into()), + BurnAsset((Here, 100).into()), + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset((Here, 1000).into()), - BurnAsset((Here, 100).into()), - DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(30)); @@ -192,13 +205,15 @@ fn burn_should_work() { assert_eq!(sent_xcm(), vec![]); // Now they want to burn 1000 of them, which will actually only burn 900. + let message = Xcm(vec![ + WithdrawAsset((Here, 900).into()), + BurnAsset((Here, 1000).into()), + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset((Here, 900).into()), - BurnAsset((Here, 1000).into()), - DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(30)); @@ -214,15 +229,17 @@ fn basic_asset_trap_should_work() { // Child parachain #1 owns 1000 tokens held by us in reserve. add_asset(Parachain(1), (Here, 1000)); // They want to transfer 100 of them to their sibling parachain #2 but have a problem + let message = Xcm(vec![ + WithdrawAsset((Here, 100).into()), + DepositAsset { + assets: Wild(AllCounted(0)), // <<< 0 is an error. + beneficiary: AccountIndex64 { index: 3, network: None }.into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset((Here, 100).into()), - DepositAsset { - assets: Wild(AllCounted(0)), // <<< 0 is an error. - beneficiary: AccountIndex64 { index: 3, network: None }.into(), - }, - ]), + message, hash, 20, ); assert_eq!(r, Outcome::Complete(25)); @@ -230,16 +247,18 @@ fn basic_asset_trap_should_work() { assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); // Incorrect ticket doesn't work. + let message = Xcm(vec![ + ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(1).into() }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: AccountIndex64 { index: 3, network: None }.into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(1).into() }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: AccountIndex64 { index: 3, network: None }.into(), - }, - ]), + message, hash, 20, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -248,16 +267,18 @@ fn basic_asset_trap_should_work() { assert_eq!(old_trapped_assets, TrappedAssets::get()); // Incorrect origin doesn't work. + let message = Xcm(vec![ + ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(0).into() }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: AccountIndex64 { index: 3, network: None }.into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm( Parachain(2), - Xcm(vec![ - ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(0).into() }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: AccountIndex64 { index: 3, network: None }.into(), - }, - ]), + message, hash, 20, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -266,16 +287,18 @@ fn basic_asset_trap_should_work() { assert_eq!(old_trapped_assets, TrappedAssets::get()); // Incorrect assets doesn't work. + let message = Xcm(vec![ + ClaimAsset { assets: (Here, 101).into(), ticket: GeneralIndex(0).into() }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: AccountIndex64 { index: 3, network: None }.into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - ClaimAsset { assets: (Here, 101).into(), ticket: GeneralIndex(0).into() }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: AccountIndex64 { index: 3, network: None }.into(), - }, - ]), + message, hash, 20, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -283,15 +306,17 @@ fn basic_asset_trap_should_work() { assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); assert_eq!(old_trapped_assets, TrappedAssets::get()); + let message = Xcm(vec![ + ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(0).into() }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: AccountIndex64 { index: 3, network: None }.into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(0).into() }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: AccountIndex64 { index: 3, network: None }.into(), - }, - ]), + message, hash, 20, ); assert_eq!(r, Outcome::Complete(20)); @@ -299,15 +324,17 @@ fn basic_asset_trap_should_work() { assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 100).into()]); // Same again doesn't work :-) + let message = Xcm(vec![ + ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(0).into() }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: AccountIndex64 { index: 3, network: None }.into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - ClaimAsset { assets: (Here, 100).into(), ticket: GeneralIndex(0).into() }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: AccountIndex64 { index: 3, network: None }.into(), - }, - ]), + message, hash, 20, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -329,98 +356,108 @@ fn max_assets_limit_should_work() { add_asset(Parachain(1), ([9u8; 32], 1000)); // Attempt to withdraw 8 (=2x4)different assets. This will succeed. + let message = Xcm(vec![ + WithdrawAsset(([1u8; 32], 100).into()), + WithdrawAsset(([2u8; 32], 100).into()), + WithdrawAsset(([3u8; 32], 100).into()), + WithdrawAsset(([4u8; 32], 100).into()), + WithdrawAsset(([5u8; 32], 100).into()), + WithdrawAsset(([6u8; 32], 100).into()), + WithdrawAsset(([7u8; 32], 100).into()), + WithdrawAsset(([8u8; 32], 100).into()), + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset(([1u8; 32], 100).into()), - WithdrawAsset(([2u8; 32], 100).into()), - WithdrawAsset(([3u8; 32], 100).into()), - WithdrawAsset(([4u8; 32], 100).into()), - WithdrawAsset(([5u8; 32], 100).into()), - WithdrawAsset(([6u8; 32], 100).into()), - WithdrawAsset(([7u8; 32], 100).into()), - WithdrawAsset(([8u8; 32], 100).into()), - ]), + message, hash, 100, ); assert_eq!(r, Outcome::Complete(85)); // Attempt to withdraw 9 different assets will fail. + let message = Xcm(vec![ + WithdrawAsset(([1u8; 32], 100).into()), + WithdrawAsset(([2u8; 32], 100).into()), + WithdrawAsset(([3u8; 32], 100).into()), + WithdrawAsset(([4u8; 32], 100).into()), + WithdrawAsset(([5u8; 32], 100).into()), + WithdrawAsset(([6u8; 32], 100).into()), + WithdrawAsset(([7u8; 32], 100).into()), + WithdrawAsset(([8u8; 32], 100).into()), + WithdrawAsset(([9u8; 32], 100).into()), + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset(([1u8; 32], 100).into()), - WithdrawAsset(([2u8; 32], 100).into()), - WithdrawAsset(([3u8; 32], 100).into()), - WithdrawAsset(([4u8; 32], 100).into()), - WithdrawAsset(([5u8; 32], 100).into()), - WithdrawAsset(([6u8; 32], 100).into()), - WithdrawAsset(([7u8; 32], 100).into()), - WithdrawAsset(([8u8; 32], 100).into()), - WithdrawAsset(([9u8; 32], 100).into()), - ]), + message, hash, 100, ); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); // Attempt to withdraw 4 different assets and then the same 4 and then a different 4 will succeed. + let message = Xcm(vec![ + WithdrawAsset(([1u8; 32], 100).into()), + WithdrawAsset(([2u8; 32], 100).into()), + WithdrawAsset(([3u8; 32], 100).into()), + WithdrawAsset(([4u8; 32], 100).into()), + WithdrawAsset(([1u8; 32], 100).into()), + WithdrawAsset(([2u8; 32], 100).into()), + WithdrawAsset(([3u8; 32], 100).into()), + WithdrawAsset(([4u8; 32], 100).into()), + WithdrawAsset(([5u8; 32], 100).into()), + WithdrawAsset(([6u8; 32], 100).into()), + WithdrawAsset(([7u8; 32], 100).into()), + WithdrawAsset(([8u8; 32], 100).into()), + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset(([1u8; 32], 100).into()), - WithdrawAsset(([2u8; 32], 100).into()), - WithdrawAsset(([3u8; 32], 100).into()), - WithdrawAsset(([4u8; 32], 100).into()), - WithdrawAsset(([1u8; 32], 100).into()), - WithdrawAsset(([2u8; 32], 100).into()), - WithdrawAsset(([3u8; 32], 100).into()), - WithdrawAsset(([4u8; 32], 100).into()), - WithdrawAsset(([5u8; 32], 100).into()), - WithdrawAsset(([6u8; 32], 100).into()), - WithdrawAsset(([7u8; 32], 100).into()), - WithdrawAsset(([8u8; 32], 100).into()), - ]), + message, hash, 200, ); assert_eq!(r, Outcome::Complete(125)); // Attempt to withdraw 4 different assets and then a different 4 and then the same 4 will fail. + let message = Xcm(vec![ + WithdrawAsset(([1u8; 32], 100).into()), + WithdrawAsset(([2u8; 32], 100).into()), + WithdrawAsset(([3u8; 32], 100).into()), + WithdrawAsset(([4u8; 32], 100).into()), + WithdrawAsset(([5u8; 32], 100).into()), + WithdrawAsset(([6u8; 32], 100).into()), + WithdrawAsset(([7u8; 32], 100).into()), + WithdrawAsset(([8u8; 32], 100).into()), + WithdrawAsset(([1u8; 32], 100).into()), + WithdrawAsset(([2u8; 32], 100).into()), + WithdrawAsset(([3u8; 32], 100).into()), + WithdrawAsset(([4u8; 32], 100).into()), + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset(([1u8; 32], 100).into()), - WithdrawAsset(([2u8; 32], 100).into()), - WithdrawAsset(([3u8; 32], 100).into()), - WithdrawAsset(([4u8; 32], 100).into()), - WithdrawAsset(([5u8; 32], 100).into()), - WithdrawAsset(([6u8; 32], 100).into()), - WithdrawAsset(([7u8; 32], 100).into()), - WithdrawAsset(([8u8; 32], 100).into()), - WithdrawAsset(([1u8; 32], 100).into()), - WithdrawAsset(([2u8; 32], 100).into()), - WithdrawAsset(([3u8; 32], 100).into()), - WithdrawAsset(([4u8; 32], 100).into()), - ]), + message, hash, 200, ); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); // Attempt to withdraw 4 different assets and then a different 4 and then the same 4 will fail. + let message = Xcm(vec![ + WithdrawAsset(MultiAssets::from(vec![ + ([1u8; 32], 100).into(), + ([2u8; 32], 100).into(), + ([3u8; 32], 100).into(), + ([4u8; 32], 100).into(), + ([5u8; 32], 100).into(), + ([6u8; 32], 100).into(), + ([7u8; 32], 100).into(), + ([8u8; 32], 100).into(), + ])), + WithdrawAsset(([1u8; 32], 100).into()), + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - WithdrawAsset(MultiAssets::from(vec![ - ([1u8; 32], 100).into(), - ([2u8; 32], 100).into(), - ([3u8; 32], 100).into(), - ([4u8; 32], 100).into(), - ([5u8; 32], 100).into(), - ([6u8; 32], 100).into(), - ([7u8; 32], 100).into(), - ([8u8; 32], 100).into(), - ])), - WithdrawAsset(([1u8; 32], 100).into()), - ]), + message, hash, 200, ); assert_eq!(r, Outcome::Incomplete(25, XcmError::HoldingWouldOverflow)); diff --git a/xcm/xcm-builder/src/tests/basic.rs b/xcm/xcm-builder/src/tests/basic.rs index 1b611d5b6168..08fe2a3f7441 100644 --- a/xcm/xcm-builder/src/tests/basic.rs +++ b/xcm/xcm-builder/src/tests/basic.rs @@ -85,13 +85,15 @@ fn code_registers_should_work() { let limit = ::Weigher::weight(&mut message).unwrap(); assert_eq!(limit, 70); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), limit); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + + let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); assert_eq!(r, Outcome::Complete(50)); // We don't pay the 20 weight for the error handler. assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 13).into()]); assert_eq!(asset_list(Here), vec![(Here, 8).into()]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message, limit); + let r = XcmExecutor::::execute_xcm(Here, message, hash, limit); assert_eq!(r, Outcome::Complete(70)); // We pay the full weight here. assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 20).into()]); assert_eq!(asset_list(Here), vec![(Here, 1).into()]); diff --git a/xcm/xcm-builder/src/tests/bridging/mod.rs b/xcm/xcm-builder/src/tests/bridging/mod.rs index 1be2a68148c2..74c202afa0e3 100644 --- a/xcm/xcm-builder/src/tests/bridging/mod.rs +++ b/xcm/xcm-builder/src/tests/bridging/mod.rs @@ -130,14 +130,15 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S AllowUnpaidFrom::set(vec![origin.clone()]); set_exporter_override(price::, deliver::); // The we execute it: + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let outcome = XcmExecutor::::execute_xcm( origin, - message.clone().into(), + message.into(), + hash, 2_000_000_000_000, ); match outcome { - Outcome::Complete(..) => - Ok(VersionedXcm::from(message).using_encoded(sp_io::hashing::blake2_256)), + Outcome::Complete(..) => Ok(hash), Outcome::Incomplete(..) => Err(Transport("Error executing")), Outcome::Error(..) => Err(Transport("Unable to execute")), } @@ -174,14 +175,15 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S AllowPaidFrom::set(vec![origin.clone()]); set_exporter_override(price::, deliver::); // The we execute it: + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let outcome = XcmExecutor::::execute_xcm( origin, - message.clone().into(), + message.into(), + hash, 2_000_000_000_000, ); match outcome { - Outcome::Complete(..) => - Ok(VersionedXcm::from(message).using_encoded(sp_io::hashing::blake2_256)), + Outcome::Complete(..) => Ok(hash), Outcome::Incomplete(..) => Err(Transport("Error executing")), Outcome::Error(..) => Err(Transport("Unable to execute")), } diff --git a/xcm/xcm-builder/src/tests/expecting.rs b/xcm/xcm-builder/src/tests/expecting.rs index d54eef86c358..e505150c4c6a 100644 --- a/xcm/xcm-builder/src/tests/expecting.rs +++ b/xcm/xcm-builder/src/tests/expecting.rs @@ -21,28 +21,32 @@ fn expect_pallet_should_work() { AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 41, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 41, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -51,106 +55,122 @@ fn expect_pallet_should_work() { #[test] fn expect_pallet_should_fail_correctly() { AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 60, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 60, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"System".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"System".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_system".as_ref().into(), + crate_major: 1, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_system".as_ref().into(), - crate_major: 1, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); + let message = Xcm(vec![ExpectPallet { + index: 0, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 0, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); + let message = Xcm(vec![ExpectPallet { + index: 2, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 2, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::PalletNotFound)); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 2, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 2, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 0, + min_crate_minor: 42, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 0, - min_crate_minor: 42, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); + let message = Xcm(vec![ExpectPallet { + index: 1, + name: b"Balances".as_ref().into(), + module_name: b"pallet_balances".as_ref().into(), + crate_major: 1, + min_crate_minor: 43, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExpectPallet { - index: 1, - name: b"Balances".as_ref().into(), - module_name: b"pallet_balances".as_ref().into(), - crate_major: 1, - min_crate_minor: 43, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index 01cdb80f8ad5..125f51e9d69f 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -27,16 +27,18 @@ fn lock_roundtrip_should_work() { set_send_price((Parent, 10)); // They want to lock 100 of the native parent tokens to be unlocked only by Parachain #1. + let message = Xcm(vec![ + WithdrawAsset((Parent, 100).into()), + SetAppendix( + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }] + .into(), + ), + LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![ - WithdrawAsset((Parent, 100).into()), - SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }] - .into(), - ), - LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(40)); @@ -59,9 +61,11 @@ fn lock_roundtrip_should_work() { ); // Now we'll unlock it. + let message = Xcm(vec![UnlockAsset { asset: (Parent, 100).into(), target: (3u64,).into() }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (Parent, Parachain(1)), - Xcm(vec![UnlockAsset { asset: (Parent, 100).into(), target: (3u64,).into() }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -77,12 +81,14 @@ fn auto_fee_paying_should_work() { set_send_price((Parent, 10)); // They want to lock 100 of the native parent tokens to be unlocked only by Parachain #1. + let message = Xcm(vec![ + SetFeesMode { jit_withdraw: true }, + LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![ - SetFeesMode { jit_withdraw: true }, - LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(20)); @@ -96,12 +102,14 @@ fn lock_should_fail_correctly() { // #3 wants to lock 100 of the native parent tokens to be unlocked only by parachain ../#1, // but they don't have any. + let message = Xcm(vec![LockAsset { + asset: (Parent, 100).into(), + unlocker: (Parent, Parachain(1)).into(), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![LockAsset { - asset: (Parent, 100).into(), - unlocker: (Parent, Parachain(1)).into(), - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::LockError)); @@ -115,12 +123,14 @@ fn lock_should_fail_correctly() { // #3 wants to lock 100 of the native parent tokens to be unlocked only by parachain ../#1, // but there's nothing to pay the fees for sending the notification message. + let message = Xcm(vec![LockAsset { + asset: (Parent, 100).into(), + unlocker: (Parent, Parachain(1)).into(), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![LockAsset { - asset: (Parent, 100).into(), - unlocker: (Parent, Parachain(1)).into(), - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotHoldingFees)); @@ -138,9 +148,11 @@ fn remote_unlock_roundtrip_should_work() { set_send_price((Parent, 10)); // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. + let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (Parent, Parachain(1)), - Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -154,16 +166,18 @@ fn remote_unlock_roundtrip_should_work() { ); // Let's request those funds be unlocked. + let message = Xcm(vec![ + WithdrawAsset((Parent, 100).into()), + SetAppendix( + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }] + .into(), + ), + RequestUnlock { asset: (Parent, 100).into(), locker: (Parent, Parachain(1)).into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![ - WithdrawAsset((Parent, 100).into()), - SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }] - .into(), - ), - RequestUnlock { asset: (Parent, 100).into(), locker: (Parent, Parachain(1)).into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(40)); @@ -196,12 +210,14 @@ fn remote_unlock_should_fail_correctly() { // We want to unlock 100 of the native parent tokens which were locked for us on parachain. // This won't work as we don't have any record of them being locked for us. // No message will be sent and no lock records changed. + let message = Xcm(vec![RequestUnlock { + asset: (Parent, 100).into(), + locker: (Parent, Parachain(1)).into(), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![RequestUnlock { - asset: (Parent, 100).into(), - locker: (Parent, Parachain(1)).into(), - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::LockError)); @@ -209,9 +225,11 @@ fn remote_unlock_should_fail_correctly() { assert_eq!(take_lock_trace(), vec![]); // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. + let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (Parent, Parachain(1)), - Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -220,12 +238,14 @@ fn remote_unlock_should_fail_correctly() { // We want to unlock 100 of the native parent tokens which were locked for us on parachain. // This won't work now as we don't have the funds to send the onward message. // No message will be sent and no lock records changed. + let message = Xcm(vec![RequestUnlock { + asset: (Parent, 100).into(), + locker: (Parent, Parachain(1)).into(), + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( (3u64,), - Xcm(vec![RequestUnlock { - asset: (Parent, 100).into(), - locker: (Parent, Parachain(1)).into(), - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotHoldingFees)); diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index 5dee287a559b..7d506d1f137d 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -25,33 +25,39 @@ fn universal_origin_should_work() { // Parachain 2 may represent Polkadot to us add_universal_alias(Parachain(2), Polkadot); + let message = Xcm(vec![ + UniversalOrigin(GlobalConsensus(Kusama)), + TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(2), - Xcm(vec![ - UniversalOrigin(GlobalConsensus(Kusama)), - TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(10, XcmError::InvalidLocation)); + let message = Xcm(vec![ + UniversalOrigin(GlobalConsensus(Kusama)), + TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - UniversalOrigin(GlobalConsensus(Kusama)), - TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Incomplete(20, XcmError::NotWithdrawable)); add_asset((Ancestor(2), GlobalConsensus(Kusama)), (Parent, 100)); + let message = Xcm(vec![ + UniversalOrigin(GlobalConsensus(Kusama)), + TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ - UniversalOrigin(GlobalConsensus(Kusama)), - TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, - ]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(20)); @@ -66,9 +72,12 @@ fn export_message_should_work() { // Polkadot parachain #2. let message = Xcm(vec![TransferAsset { assets: (Here, 100).into(), beneficiary: Parachain(2).into() }]); + let exported_msg = + Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: message.clone() }]); + let hash = VersionedXcm::from(exported_msg.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: message.clone() }]), + exported_msg, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); diff --git a/xcm/xcm-builder/src/tests/querying.rs b/xcm/xcm-builder/src/tests/querying.rs index 1b6e90e230d4..da3d39173e96 100644 --- a/xcm/xcm-builder/src/tests/querying.rs +++ b/xcm/xcm-builder/src/tests/querying.rs @@ -21,16 +21,18 @@ fn pallet_query_should_work() { AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. + let message = Xcm(vec![QueryPallet { + module_name: "Error".into(), + response_info: QueryResponseInfo { + destination: Parachain(1).into(), + query_id: 1, + max_weight: 50, + }, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![QueryPallet { - module_name: "Error".into(), - response_info: QueryResponseInfo { - destination: Parachain(1).into(), - query_id: 1, - max_weight: 50, - }, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -54,16 +56,18 @@ fn pallet_query_with_results_should_work() { AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); // They want to transfer 100 of our native asset from sovereign account of parachain #1 into #2 // and let them know to hand it to account #3. + let message = Xcm(vec![QueryPallet { + module_name: "pallet_balances".into(), + response_info: QueryResponseInfo { + destination: Parachain(1).into(), + query_id: 1, + max_weight: 50, + }, + }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( Parachain(1), - Xcm(vec![QueryPallet { - module_name: "pallet_balances".into(), - response_info: QueryResponseInfo { - destination: Parachain(1).into(), - query_id: 1, - max_weight: 50, - }, - }]), + message, hash, 50, ); assert_eq!(r, Outcome::Complete(10)); @@ -107,14 +111,15 @@ fn prepaid_result_of_query_should_get_free_execution() { max_weight: 10, querier: Some(Here.into()), }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 10; // First time the response gets through since we're expecting it... - let r = XcmExecutor::::execute_xcm(Parent, message.clone(), weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message.clone(), hash, weight_limit); assert_eq!(r, Outcome::Complete(10)); assert_eq!(response(query_id).unwrap(), the_response); // Second time it doesn't, since we're not. - let r = XcmExecutor::::execute_xcm(Parent, message.clone(), weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message.clone(), hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); } diff --git a/xcm/xcm-builder/src/tests/transacting.rs b/xcm/xcm-builder/src/tests/transacting.rs index 643a1054d8cb..68108ce268b3 100644 --- a/xcm/xcm-builder/src/tests/transacting.rs +++ b/xcm/xcm-builder/src/tests/transacting.rs @@ -25,8 +25,9 @@ fn transacting_should_work() { require_weight_at_most: 50, call: TestCall::Any(50, None).encode().into(), }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 60; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(60)); } @@ -39,8 +40,9 @@ fn transacting_should_respect_max_weight_requirement() { require_weight_at_most: 40, call: TestCall::Any(50, None).encode().into(), }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 60; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Incomplete(50, XcmError::MaxWeightInvalid)); } @@ -53,8 +55,9 @@ fn transacting_should_refund_weight() { require_weight_at_most: 50, call: TestCall::Any(50, Some(30)).encode().into(), }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 60; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(40)); } @@ -79,8 +82,9 @@ fn paid_transacting_should_refund_payment_for_unused_weight() { RefundSurplus, DepositAsset { assets: AllCounted(1).into(), beneficiary: one.clone() }, ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 100; - let r = XcmExecutor::::execute_xcm(origin, message, weight_limit); + let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(60)); assert_eq!(asset_list(AccountIndex64 { index: 1, network: None }), vec![(Parent, 40).into()]); } @@ -101,8 +105,9 @@ fn report_successful_transact_status_should_work() { max_weight: 5000, }), ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 70; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(70)); assert_eq!( sent_xcm(), @@ -134,8 +139,9 @@ fn report_failed_transact_status_should_work() { max_weight: 5000, }), ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 70; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(70)); assert_eq!( sent_xcm(), @@ -168,8 +174,9 @@ fn clear_transact_status_should_work() { max_weight: 5000, }), ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 80; - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(80)); assert_eq!( sent_xcm(), diff --git a/xcm/xcm-builder/src/tests/version_subscriptions.rs b/xcm/xcm-builder/src/tests/version_subscriptions.rs index 2ecd12a05b4f..cab4f42be3b0 100644 --- a/xcm/xcm-builder/src/tests/version_subscriptions.rs +++ b/xcm/xcm-builder/src/tests/version_subscriptions.rs @@ -25,18 +25,20 @@ fn simple_version_subscriptions_should_work() { SetAppendix(Xcm(vec![])), SubscribeVersion { query_id: 42, max_response_weight: 5000 }, ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 20; - let r = XcmExecutor::::execute_xcm(origin, message, weight_limit); + let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); let origin = Parachain(1000); let message = Xcm::(vec![SubscribeVersion { query_id: 42, max_response_weight: 5000 }]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 10; - let r = XcmExecutor::::execute_xcm(origin, message.clone(), weight_limit); + let r = XcmExecutor::::execute_xcm(origin, message.clone(), hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(10)); assert_eq!(SubscriptionRequests::get(), vec![(Parent.into(), Some((42, 5000)))]); @@ -49,10 +51,12 @@ fn version_subscription_instruction_should_work() { DescendOrigin(X1(AccountIndex64 { index: 1, network: None })), SubscribeVersion { query_id: 42, max_response_weight: 5000 }, ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 20; let r = XcmExecutor::::execute_xcm_in_credit( origin.clone(), - message.clone(), + message, + hash, weight_limit, weight_limit, ); @@ -62,9 +66,11 @@ fn version_subscription_instruction_should_work() { SetAppendix(Xcm(vec![])), SubscribeVersion { query_id: 42, max_response_weight: 5000 }, ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm_in_credit( origin, - message.clone(), + message, + hash, weight_limit, weight_limit, ); @@ -79,17 +85,19 @@ fn simple_version_unsubscriptions_should_work() { let origin = Parachain(1000); let message = Xcm::(vec![SetAppendix(Xcm(vec![])), UnsubscribeVersion]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 20; - let r = XcmExecutor::::execute_xcm(origin, message, weight_limit); + let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); let origin = Parachain(1000); let message = Xcm::(vec![UnsubscribeVersion]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 10; - let r = XcmExecutor::::execute_xcm(origin, message.clone(), weight_limit); + let r = XcmExecutor::::execute_xcm(origin, message.clone(), hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); - let r = XcmExecutor::::execute_xcm(Parent, message, weight_limit); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(10)); assert_eq!(SubscriptionRequests::get(), vec![(Parent.into(), None)]); @@ -105,10 +113,12 @@ fn version_unsubscription_instruction_should_work() { DescendOrigin(X1(AccountIndex64 { index: 1, network: None })), UnsubscribeVersion, ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight_limit = 20; let r = XcmExecutor::::execute_xcm_in_credit( origin.clone(), - message.clone(), + message, + hash, weight_limit, weight_limit, ); @@ -116,9 +126,11 @@ fn version_unsubscription_instruction_should_work() { // Fine to do it when origin is untouched. let message = Xcm::(vec![SetAppendix(Xcm(vec![])), UnsubscribeVersion]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm_in_credit( origin, - message.clone(), + message, + hash, weight_limit, weight_limit, ); diff --git a/xcm/xcm-builder/src/tests/weight.rs b/xcm/xcm-builder/src/tests/weight.rs index 6c2a5cf112f8..c1344594317b 100644 --- a/xcm/xcm-builder/src/tests/weight.rs +++ b/xcm/xcm-builder/src/tests/weight.rs @@ -43,25 +43,27 @@ fn errors_should_return_unused_weight() { let limit = ::Weigher::weight(&mut message).unwrap(); assert_eq!(limit, 30); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), limit); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + + let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 7).into()]); assert_eq!(asset_list(Here), vec![(Here, 4).into()]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), limit); + let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); assert_eq!(r, Outcome::Incomplete(30, XcmError::NotWithdrawable)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 10).into()]); assert_eq!(asset_list(Here), vec![(Here, 1).into()]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message.clone(), limit); + let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); assert_eq!(r, Outcome::Incomplete(20, XcmError::NotWithdrawable)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 11).into()]); assert_eq!(asset_list(Here), vec![]); assert_eq!(sent_xcm(), vec![]); - let r = XcmExecutor::::execute_xcm(Here, message, limit); + let r = XcmExecutor::::execute_xcm(Here, message, hash, limit); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotWithdrawable)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 11).into()]); assert_eq!(asset_list(Here), vec![]); diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index 6932c006546a..18f8ba245d44 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -19,9 +19,10 @@ mod mock; use mock::{ kusama_like_with_balances, AccountId, Balance, Balances, BaseXcmWeight, XcmConfig, CENTS, }; +use parity_scale_codec::Encode; use polkadot_parachain::primitives::Id as ParaId; use sp_runtime::traits::AccountIdConversion; -use xcm::latest::prelude::*; +use xcm::{latest::prelude::*, VersionedXcm}; use xcm_executor::XcmExecutor; pub const ALICE: AccountId = AccountId::new([0u8; 32]); @@ -46,18 +47,16 @@ fn withdraw_and_deposit_works() { let other_para_id = 3000; let amount = REGISTER_AMOUNT; let weight = 3 * BaseXcmWeight::get(); - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - Xcm(vec![ - WithdrawAsset((Here, amount).into()), - buy_execution(), - DepositAsset { - assets: AllCounted(1).into(), - beneficiary: Parachain(other_para_id).into(), - }, - ]), - weight, - ); + let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + buy_execution(), + DepositAsset { + assets: AllCounted(1).into(), + beneficiary: Parachain(other_para_id).into(), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account(); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - amount); @@ -87,20 +86,18 @@ fn report_holding_works() { query_id: 1234, max_weight: 1_000_000_000, }; - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - Xcm(vec![ - WithdrawAsset((Here, amount).into()), - buy_execution(), - DepositAsset { - assets: AllCounted(1).into(), - beneficiary: OnlyChild.into(), // invalid destination - }, - // is not triggered becasue the deposit fails - ReportHolding { response_info: response_info.clone(), assets: All.into() }, - ]), - weight, - ); + let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + buy_execution(), + DepositAsset { + assets: AllCounted(1).into(), + beneficiary: OnlyChild.into(), // invalid destination + }, + // is not triggered becasue the deposit fails + ReportHolding { response_info: response_info.clone(), assets: All.into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!( r, Outcome::Incomplete( @@ -113,23 +110,18 @@ fn report_holding_works() { assert_eq!(Balances::free_balance(para_acc.clone()), INITIAL_BALANCE - amount); // now do a successful transfer - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - Xcm(vec![ - WithdrawAsset((Here, amount).into()), - buy_execution(), - DepositAsset { - assets: AllCounted(1).into(), - beneficiary: Parachain(other_para_id).into(), - }, - // used to get a notification in case of success - ReportHolding { - response_info: response_info.clone(), - assets: AllCounted(1).into(), - }, - ]), - weight, - ); + let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + buy_execution(), + DepositAsset { + assets: AllCounted(1).into(), + beneficiary: Parachain(other_para_id).into(), + }, + // used to get a notification in case of success + ReportHolding { response_info: response_info.clone(), assets: AllCounted(1).into() }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account(); assert_eq!(Balances::free_balance(other_para_acc), amount); @@ -176,19 +168,17 @@ fn teleport_to_statemine_works() { let weight = 3 * BaseXcmWeight::get(); // teleports are allowed to community chains, even in the absence of trust from their side. - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - Xcm(vec![ - WithdrawAsset((Here, amount).into()), - buy_execution(), - InitiateTeleport { - assets: All.into(), - dest: Parachain(other_para_id).into(), - xcm: Xcm(teleport_effects.clone()), - }, - ]), - weight, - ); + let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + buy_execution(), + InitiateTeleport { + assets: All.into(), + dest: Parachain(other_para_id).into(), + xcm: Xcm(teleport_effects.clone()), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!( mock::sent_xcm(), @@ -202,19 +192,17 @@ fn teleport_to_statemine_works() { ); // teleports are allowed from statemine to kusama. - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - Xcm(vec![ - WithdrawAsset((Here, amount).into()), - buy_execution(), - InitiateTeleport { - assets: All.into(), - dest: Parachain(statemine_id).into(), - xcm: Xcm(teleport_effects.clone()), - }, - ]), - weight, - ); + let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + buy_execution(), + InitiateTeleport { + assets: All.into(), + dest: Parachain(statemine_id).into(), + xcm: Xcm(teleport_effects.clone()), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); // 2 * amount because of the other teleport above assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - 2 * amount); @@ -261,20 +249,18 @@ fn reserve_based_transfer_works() { beneficiary: (Parent, Parachain(PARA_ID)).into(), }, ]; + let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + buy_execution(), + DepositReserveAsset { + assets: AllCounted(1).into(), + dest: Parachain(other_para_id).into(), + xcm: Xcm(transfer_effects.clone()), + }, + ]); + let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let weight = 3 * BaseXcmWeight::get(); - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - Xcm(vec![ - WithdrawAsset((Here, amount).into()), - buy_execution(), - DepositReserveAsset { - assets: AllCounted(1).into(), - dest: Parachain(other_para_id).into(), - xcm: Xcm(transfer_effects.clone()), - }, - ]), - weight, - ); + let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - amount); assert_eq!( diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 15d55cf25f73..14254a382120 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -26,7 +26,7 @@ use parity_scale_codec::{Decode, Encode}; use sp_io::hashing::blake2_128; use sp_runtime::traits::Saturating; use sp_std::{marker::PhantomData, prelude::*}; -use xcm::latest::prelude::*; +use xcm::{latest::prelude::*, VersionedXcm}; pub mod traits; use traits::{ @@ -183,6 +183,7 @@ impl ExecuteXcm for XcmExecutor { fn execute( origin: impl Into, WeighedMessage(xcm_weight, mut message): WeighedMessage, + message_hash: XcmHash, mut weight_credit: Weight, ) -> Outcome { let origin = origin.into(); @@ -212,10 +213,6 @@ impl ExecuteXcm for XcmExecutor { let mut vm = Self::new(origin); - // We hash the message here instead of inside the loop, because `message` may have been - // reassigned due to the existence of the error handler or the appendix. - let message_hash = message.using_encoded(sp_io::hashing::blake2_256); - while !message.0.is_empty() { let result = vm.execute_with_hash(message, message_hash); log::trace!(target: "xcm::execute_xcm_in_credit", "result: {:?}", result); @@ -290,14 +287,15 @@ impl XcmExecutor { /// Execute the XCM program fragment and report back the error and which instruction caused it, /// or `Ok` if there was no error. pub fn execute(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { - let message_hash = xcm.using_encoded(sp_io::hashing::blake2_256); + let message_hash = + VersionedXcm::from(xcm.clone()).using_encoded(sp_io::hashing::blake2_256); self.execute_with_hash(xcm, message_hash) } fn execute_with_hash( &mut self, xcm: Xcm, - message_hash: [u8; 32], + message_hash: XcmHash, ) -> Result<(), ExecutorError> { log::trace!( target: "xcm::execute", @@ -429,7 +427,7 @@ impl XcmExecutor { fn process_instruction( &mut self, instr: Instruction, - message_hash: [u8; 32], + message_hash: XcmHash, ) -> Result<(), XcmError> { match instr { WithdrawAsset(assets) => { From 03720b58ed50b2cdca4982e2c61e29a67b89f2aa Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 21:26:50 -0800 Subject: [PATCH 33/73] cargo fmt --- xcm/pallet-xcm/src/lib.rs | 10 +- xcm/pallet-xcm/src/tests.rs | 25 ++--- xcm/xcm-builder/src/tests/assets.rs | 117 ++++------------------ xcm/xcm-builder/src/tests/bridging/mod.rs | 16 +-- xcm/xcm-builder/src/tests/expecting.rs | 60 ++--------- xcm/xcm-builder/src/tests/locking.rs | 66 +++--------- xcm/xcm-builder/src/tests/origins.rs | 24 +---- xcm/xcm-builder/src/tests/querying.rs | 12 +-- xcm/xcm-executor/src/lib.rs | 6 +- 9 files changed, 72 insertions(+), 264 deletions(-) diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index aaf6d12fd6c0..1c7fb0b80a95 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -1324,11 +1324,7 @@ impl Pallet { VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let (ticket, price) = validate_send::(dest, message)?; if let Some(fee_payer) = maybe_fee_payer { - let context = XcmContext { - origin: Some(fee_payer.clone()), - message_hash, - topic: None, - }; + let context = XcmContext { origin: Some(fee_payer.clone()), message_hash, topic: None }; Self::charge_fees(fee_payer, price, context).map_err(|_| SendError::Fees)?; } T::XcmRouter::deliver(ticket) @@ -1590,8 +1586,8 @@ impl xcm_executor::traits::Enact for ReduceTicket { ensure!(self.locker == record.locker && self.owner == record.owner, UnexpectedState); ensure!(record.users == 0, UnexpectedState); record.amount = record.amount.checked_sub(self.amount).ok_or(UnexpectedState)?; - if record.amount == 0 -{ RemoteLockedFungibles::::remove(&self.key); + if record.amount == 0 { + RemoteLockedFungibles::::remove(&self.key); } else { RemoteLockedFungibles::::insert(&self.key, &record); } diff --git a/xcm/pallet-xcm/src/tests.rs b/xcm/pallet-xcm/src/tests.rs index ad1b1ee35a54..c129a00a0dc1 100644 --- a/xcm/pallet-xcm/src/tests.rs +++ b/xcm/pallet-xcm/src/tests.rs @@ -14,11 +14,11 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use codec::Encode; use crate::{ mock::*, AssetTraps, CurrentMigration, Error, LatestVersionedMultiLocation, Queries, QueryStatus, VersionDiscoveryQueue, VersionNotifiers, VersionNotifyTargets, }; +use codec::Encode; use frame_support::{ assert_noop, assert_ok, traits::{Currency, Hooks}, @@ -85,11 +85,8 @@ fn report_outcome_notify_works() { querier: Some(querier), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - message, hash, - 1_000_000_000, - ); + let r = + XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, 1_000_000_000); assert_eq!(r, Outcome::Complete(1_000)); assert_eq!( last_events(2), @@ -144,11 +141,8 @@ fn report_outcome_works() { querier: Some(querier), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(PARA_ID), - message, hash, - 1_000_000_000, - ); + let r = + XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, 1_000_000_000); assert_eq!(r, Outcome::Complete(1_000)); assert_eq!( last_event(), @@ -188,7 +182,8 @@ fn custom_querier_works() { let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm_in_credit( AccountId32 { network: None, id: ALICE.into() }, - message, hash, + message, + hash, 1_000_000_000, 1_000, ); @@ -213,7 +208,8 @@ fn custom_querier_works() { let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm_in_credit( AccountId32 { network: None, id: ALICE.into() }, - message, hash, + message, + hash, 1_000_000_000, 1_000, ); @@ -238,7 +234,8 @@ fn custom_querier_works() { let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let r = XcmExecutor::::execute_xcm( AccountId32 { network: None, id: ALICE.into() }, - message, hash, + message, + hash, 1_000_000_000, ); assert_eq!(r, Outcome::Complete(1_000)); diff --git a/xcm/xcm-builder/src/tests/assets.rs b/xcm/xcm-builder/src/tests/assets.rs index 5944707e11f5..114d42c3e6ef 100644 --- a/xcm/xcm-builder/src/tests/assets.rs +++ b/xcm/xcm-builder/src/tests/assets.rs @@ -24,8 +24,7 @@ fn exchange_asset_should_work() { let message = Xcm(vec![ WithdrawAsset((Parent, 100).into()), SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] - .into(), + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }].into(), ), ExchangeAsset { give: Definite((Parent, 50).into()), @@ -34,11 +33,7 @@ fn exchange_asset_should_work() { }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parent, - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list(Parent), vec![(Here, 100).into(), (Parent, 950).into()]); assert_eq!(exchange_assets(), vec![(Parent, 50).into()].into()); @@ -52,8 +47,7 @@ fn exchange_asset_without_maximal_should_work() { let message = Xcm(vec![ WithdrawAsset((Parent, 100).into()), SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] - .into(), + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }].into(), ), ExchangeAsset { give: Definite((Parent, 50).into()), @@ -62,11 +56,7 @@ fn exchange_asset_without_maximal_should_work() { }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parent, - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list(Parent), vec![(Here, 50).into(), (Parent, 950).into()]); assert_eq!(exchange_assets(), vec![(Here, 50).into(), (Parent, 50).into()].into()); @@ -80,8 +70,7 @@ fn exchange_asset_should_fail_when_no_deal_possible() { let message = Xcm(vec![ WithdrawAsset((Parent, 150).into()), SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }] - .into(), + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: Parent.into() }].into(), ), ExchangeAsset { give: Definite((Parent, 150).into()), @@ -90,11 +79,7 @@ fn exchange_asset_should_fail_when_no_deal_possible() { }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parent, - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Incomplete(40, XcmError::NoDeal)); assert_eq!(asset_list(Parent), vec![(Parent, 1000).into()]); assert_eq!(exchange_assets(), vec![(Here, 100).into()].into()); @@ -131,11 +116,7 @@ fn transfer_should_work() { beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 100).into()]); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -161,11 +142,7 @@ fn reserve_transfer_should_work() { }]), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!(asset_list(Parachain(2)), vec![(Here, 100).into()]); @@ -195,11 +172,7 @@ fn burn_should_work() { DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); assert_eq!(sent_xcm(), vec![]); @@ -211,11 +184,7 @@ fn burn_should_work() { DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Parachain(1)), vec![]); assert_eq!(sent_xcm(), vec![]); @@ -237,11 +206,7 @@ fn basic_asset_trap_should_work() { }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 20, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Complete(25)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); @@ -256,11 +221,7 @@ fn basic_asset_trap_should_work() { ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let old_trapped_assets = TrappedAssets::get(); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 20, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); @@ -276,11 +237,7 @@ fn basic_asset_trap_should_work() { ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let old_trapped_assets = TrappedAssets::get(); - let r = XcmExecutor::::execute_xcm( - Parachain(2), - message, hash, - 20, - ); + let r = XcmExecutor::::execute_xcm(Parachain(2), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); @@ -296,11 +253,7 @@ fn basic_asset_trap_should_work() { ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let old_trapped_assets = TrappedAssets::get(); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 20, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![]); @@ -314,11 +267,7 @@ fn basic_asset_trap_should_work() { }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 20, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 100).into()]); @@ -332,11 +281,7 @@ fn basic_asset_trap_should_work() { }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 20, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); } @@ -367,11 +312,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([8u8; 32], 100).into()), ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 100, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 100); assert_eq!(r, Outcome::Complete(85)); // Attempt to withdraw 9 different assets will fail. @@ -387,11 +328,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([9u8; 32], 100).into()), ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 100, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 100); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); // Attempt to withdraw 4 different assets and then the same 4 and then a different 4 will succeed. @@ -410,11 +347,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([8u8; 32], 100).into()), ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 200, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Complete(125)); // Attempt to withdraw 4 different assets and then a different 4 and then the same 4 will fail. @@ -433,11 +366,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([4u8; 32], 100).into()), ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 200, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); // Attempt to withdraw 4 different assets and then a different 4 and then the same 4 will fail. @@ -455,10 +384,6 @@ fn max_assets_limit_should_work() { WithdrawAsset(([1u8; 32], 100).into()), ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 200, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Incomplete(25, XcmError::HoldingWouldOverflow)); } diff --git a/xcm/xcm-builder/src/tests/bridging/mod.rs b/xcm/xcm-builder/src/tests/bridging/mod.rs index 74c202afa0e3..594993f30ce1 100644 --- a/xcm/xcm-builder/src/tests/bridging/mod.rs +++ b/xcm/xcm-builder/src/tests/bridging/mod.rs @@ -131,12 +131,8 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S set_exporter_override(price::, deliver::); // The we execute it: let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let outcome = XcmExecutor::::execute_xcm( - origin, - message.into(), - hash, - 2_000_000_000_000, - ); + let outcome = + XcmExecutor::::execute_xcm(origin, message.into(), hash, 2_000_000_000_000); match outcome { Outcome::Complete(..) => Ok(hash), Outcome::Incomplete(..) => Err(Transport("Error executing")), @@ -176,12 +172,8 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S set_exporter_override(price::, deliver::); // The we execute it: let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let outcome = XcmExecutor::::execute_xcm( - origin, - message.into(), - hash, - 2_000_000_000_000, - ); + let outcome = + XcmExecutor::::execute_xcm(origin, message.into(), hash, 2_000_000_000_000); match outcome { Outcome::Complete(..) => Ok(hash), Outcome::Incomplete(..) => Err(Transport("Error executing")), diff --git a/xcm/xcm-builder/src/tests/expecting.rs b/xcm/xcm-builder/src/tests/expecting.rs index e505150c4c6a..d1d76946b2a0 100644 --- a/xcm/xcm-builder/src/tests/expecting.rs +++ b/xcm/xcm-builder/src/tests/expecting.rs @@ -29,11 +29,7 @@ fn expect_pallet_should_work() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); let message = Xcm(vec![ExpectPallet { @@ -44,11 +40,7 @@ fn expect_pallet_should_work() { min_crate_minor: 41, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); } @@ -63,11 +55,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 60, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); let message = Xcm(vec![ExpectPallet { @@ -78,11 +66,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); let message = Xcm(vec![ExpectPallet { @@ -93,11 +77,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); let message = Xcm(vec![ExpectPallet { @@ -108,11 +88,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); let message = Xcm(vec![ExpectPallet { @@ -123,11 +99,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::PalletNotFound)); let message = Xcm(vec![ExpectPallet { @@ -138,11 +110,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); let message = Xcm(vec![ExpectPallet { @@ -153,11 +121,7 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 42, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); let message = Xcm(vec![ExpectPallet { @@ -168,10 +132,6 @@ fn expect_pallet_should_fail_correctly() { min_crate_minor: 43, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); } diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index 125f51e9d69f..5e8ca80c0d1a 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -30,17 +30,12 @@ fn lock_roundtrip_should_work() { let message = Xcm(vec![ WithdrawAsset((Parent, 100).into()), SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }] - .into(), + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }].into(), ), LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); @@ -63,11 +58,7 @@ fn lock_roundtrip_should_work() { // Now we'll unlock it. let message = Xcm(vec![UnlockAsset { asset: (Parent, 100).into(), target: (3u64,).into() }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (Parent, Parachain(1)), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); } @@ -86,11 +77,7 @@ fn auto_fee_paying_should_work() { LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); } @@ -107,11 +94,7 @@ fn lock_should_fail_correctly() { unlocker: (Parent, Parachain(1)).into(), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::LockError)); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); @@ -128,11 +111,7 @@ fn lock_should_fail_correctly() { unlocker: (Parent, Parachain(1)).into(), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotHoldingFees)); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); @@ -150,11 +129,7 @@ fn remote_unlock_roundtrip_should_work() { // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (Parent, Parachain(1)), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!( take_lock_trace(), @@ -169,17 +144,12 @@ fn remote_unlock_roundtrip_should_work() { let message = Xcm(vec![ WithdrawAsset((Parent, 100).into()), SetAppendix( - vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }] - .into(), + vec![DepositAsset { assets: AllCounted(2).into(), beneficiary: (3u64,).into() }].into(), ), RequestUnlock { asset: (Parent, 100).into(), locker: (Parent, Parachain(1)).into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); @@ -215,11 +185,7 @@ fn remote_unlock_should_fail_correctly() { locker: (Parent, Parachain(1)).into(), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::LockError)); assert_eq!(sent_xcm(), vec![]); assert_eq!(take_lock_trace(), vec![]); @@ -227,11 +193,7 @@ fn remote_unlock_should_fail_correctly() { // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (Parent, Parachain(1)), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); let _discard = take_lock_trace(); @@ -243,11 +205,7 @@ fn remote_unlock_should_fail_correctly() { locker: (Parent, Parachain(1)).into(), }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - (3u64,), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotHoldingFees)); assert_eq!(sent_xcm(), vec![]); diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index 7d506d1f137d..05a5f7f86bb3 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -30,11 +30,7 @@ fn universal_origin_should_work() { TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(2), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(2), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::InvalidLocation)); let message = Xcm(vec![ @@ -42,11 +38,7 @@ fn universal_origin_should_work() { TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(20, XcmError::NotWithdrawable)); add_asset((Ancestor(2), GlobalConsensus(Kusama)), (Parent, 100)); @@ -55,11 +47,7 @@ fn universal_origin_should_work() { TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, ]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list((Ancestor(2), GlobalConsensus(Kusama))), vec![]); } @@ -75,11 +63,7 @@ fn export_message_should_work() { let exported_msg = Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: message.clone() }]); let hash = VersionedXcm::from(exported_msg.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - exported_msg, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), exported_msg, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!(exported_xcm(), vec![(Polkadot, 403611790, Here, message)]); } diff --git a/xcm/xcm-builder/src/tests/querying.rs b/xcm/xcm-builder/src/tests/querying.rs index da3d39173e96..7aec423e73df 100644 --- a/xcm/xcm-builder/src/tests/querying.rs +++ b/xcm/xcm-builder/src/tests/querying.rs @@ -30,11 +30,7 @@ fn pallet_query_should_work() { }, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!( @@ -65,11 +61,7 @@ fn pallet_query_with_results_should_work() { }, }]); let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); - let r = XcmExecutor::::execute_xcm( - Parachain(1), - message, hash, - 50, - ); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!( diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 14254a382120..d69134da70b2 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -229,7 +229,11 @@ impl ExecuteXcm for XcmExecutor { vm.post_execute(xcm_weight, message_hash) } - fn charge_fees(origin: impl Into, fees: MultiAssets, context: XcmContext) -> XcmResult { + fn charge_fees( + origin: impl Into, + fees: MultiAssets, + context: XcmContext, + ) -> XcmResult { let origin = origin.into(); if !Config::FeeManager::is_waived(Some(&origin), FeeReason::ChargeFees) { for asset in fees.inner() { From 487e4e29180b1e81d363302e122c890fb9a17701 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 21:36:51 -0800 Subject: [PATCH 34/73] Properly enable sp-io/std --- xcm/Cargo.toml | 1 + xcm/pallet-xcm-benchmarks/Cargo.toml | 1 + xcm/pallet-xcm/Cargo.toml | 1 - 3 files changed, 2 insertions(+), 1 deletion(-) diff --git a/xcm/Cargo.toml b/xcm/Cargo.toml index f225a3e50ebf..deaafcf3e678 100644 --- a/xcm/Cargo.toml +++ b/xcm/Cargo.toml @@ -21,4 +21,5 @@ runtime-benchmarks = [] std = [ "parity-scale-codec/std", "scale-info/std", + "sp-io/std" ] diff --git a/xcm/pallet-xcm-benchmarks/Cargo.toml b/xcm/pallet-xcm-benchmarks/Cargo.toml index 9d0ee0c3d5e2..fa6202f25247 100644 --- a/xcm/pallet-xcm-benchmarks/Cargo.toml +++ b/xcm/pallet-xcm-benchmarks/Cargo.toml @@ -41,6 +41,7 @@ std = [ "frame-benchmarking/std", "frame-support/std", "frame-system/std", + "sp-io/std", "sp-runtime/std", "sp-std/std" ] diff --git a/xcm/pallet-xcm/Cargo.toml b/xcm/pallet-xcm/Cargo.toml index bd986828e079..7a548d16109b 100644 --- a/xcm/pallet-xcm/Cargo.toml +++ b/xcm/pallet-xcm/Cargo.toml @@ -34,7 +34,6 @@ std = [ "scale-info/std", "serde", "sp-std/std", - "sp-io/std", "sp-core/std", "sp-io/std", "sp-runtime/std", From 85a151b412a55788ebd5dd3719c677b92f79ed21 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 23:24:42 -0800 Subject: [PATCH 35/73] Fixes --- xcm/pallet-xcm-benchmarks/Cargo.toml | 4 ++-- xcm/xcm-builder/Cargo.toml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/xcm/pallet-xcm-benchmarks/Cargo.toml b/xcm/pallet-xcm-benchmarks/Cargo.toml index fa6202f25247..f68e1110de8e 100644 --- a/xcm/pallet-xcm-benchmarks/Cargo.toml +++ b/xcm/pallet-xcm-benchmarks/Cargo.toml @@ -24,7 +24,6 @@ log = "0.4.0" pallet-balances = { branch = "master", git = "https://github.com/paritytech/substrate" } pallet-assets = { branch = "master", git = "https://github.com/paritytech/substrate" } sp-core = { branch = "master", git = "https://github.com/paritytech/substrate" } -sp-io = { branch = "master", git = "https://github.com/paritytech/substrate" } sp-tracing = { branch = "master", git = "https://github.com/paritytech/substrate" } xcm-builder = { path = "../xcm-builder" } xcm = { path = ".." } @@ -43,5 +42,6 @@ std = [ "frame-system/std", "sp-io/std", "sp-runtime/std", - "sp-std/std" + "sp-std/std", + "xcm-executor/std" ] diff --git a/xcm/xcm-builder/Cargo.toml b/xcm/xcm-builder/Cargo.toml index 08d13b23cb6b..6997fb8fc5da 100644 --- a/xcm/xcm-builder/Cargo.toml +++ b/xcm/xcm-builder/Cargo.toml @@ -44,6 +44,7 @@ std = [ "sp-io/std", "sp-runtime/std", "frame-support/std", + "frame-system/std", "polkadot-parachain/std", "pallet-transaction-payment/std", ] From e83175a7048d78cd573024d22811cdd6032712c0 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 21 Feb 2022 23:31:06 -0800 Subject: [PATCH 36/73] default-features = false --- xcm/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/Cargo.toml b/xcm/Cargo.toml index deaafcf3e678..e80daf2f2a8b 100644 --- a/xcm/Cargo.toml +++ b/xcm/Cargo.toml @@ -9,7 +9,7 @@ edition = "2018" impl-trait-for-tuples = "0.2.2" parity-scale-codec = { version = "2.3.1", default-features = false, features = [ "derive", "max-encoded-len" ] } scale-info = { version = "1.0", default-features = false, features = ["derive"] } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } derivative = {version = "2.2.0", default-features = false, features = [ "use_core" ] } log = { version = "0.4.14", default-features = false } xcm-procedural = { path = "procedural" } From be3b4ffb607bf002ad43f0e96c29d7cb5a709015 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 22 Feb 2022 00:33:36 -0800 Subject: [PATCH 37/73] Fixes --- xcm/xcm-simulator/example/src/parachain.rs | 26 +++++++++++++--------- xcm/xcm-simulator/fuzzer/src/parachain.rs | 2 +- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/xcm/xcm-simulator/example/src/parachain.rs b/xcm/xcm-simulator/example/src/parachain.rs index f7f8588fe382..bb8f1968e35f 100644 --- a/xcm/xcm-simulator/example/src/parachain.rs +++ b/xcm/xcm-simulator/example/src/parachain.rs @@ -227,10 +227,11 @@ pub mod mock_msg_queue { max_weight: Weight, ) -> Result { let hash = Encode::using_encoded(&xcm, T::Hashing::hash); + let message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); let (result, event) = match Xcm::::try_from(xcm) { Ok(xcm) => { let location = (Parent, Parachain(sender.into())); - match T::XcmExecutor::execute_xcm(location, xcm, max_weight) { + match T::XcmExecutor::execute_xcm(location, xcm, message_hash, max_weight) { Outcome::Error(e) => (Err(e.clone()), Event::Fail(Some(hash), e)), Outcome::Complete(w) => (Ok(w), Event::Success(Some(hash))), // As far as the caller is concerned, this was dispatched without error, so @@ -275,19 +276,22 @@ pub mod mock_msg_queue { ) -> Weight { for (_i, (_sent_at, data)) in iter.enumerate() { let id = sp_io::hashing::blake2_256(&data[..]); - let maybe_msg = - VersionedXcm::::decode(&mut &data[..]).map(Xcm::::try_from); - match maybe_msg { + let maybe_versioned = VersionedXcm::::decode(&mut &data[..]); + match maybe_versioned { Err(_) => { Self::deposit_event(Event::InvalidFormat(id)); }, - Ok(Err(())) => { - Self::deposit_event(Event::UnsupportedVersion(id)); - }, - Ok(Ok(x)) => { - let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), limit); - >::append(x); - Self::deposit_event(Event::ExecutedDownward(id, outcome)); + Ok(versioned) => { + let hash = versioned.using_encoded(sp_io::hashing::blake2_256); + match Xcm::try_from(versioned) { + Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), + Ok(x) => { + let outcome = + T::XcmExecutor::execute_xcm(Parent, x.clone(), hash, limit); + >::append(x); + Self::deposit_event(Event::ExecutedDownward(id, outcome)); + }, + } }, } } diff --git a/xcm/xcm-simulator/fuzzer/src/parachain.rs b/xcm/xcm-simulator/fuzzer/src/parachain.rs index ef9958ecd522..2e10f652f73a 100644 --- a/xcm/xcm-simulator/fuzzer/src/parachain.rs +++ b/xcm/xcm-simulator/fuzzer/src/parachain.rs @@ -285,7 +285,7 @@ pub mod mock_msg_queue { Self::deposit_event(Event::UnsupportedVersion(id)); }, Ok(Ok(x)) => { - let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), limit); + let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); >::append(x); Self::deposit_event(Event::ExecutedDownward(id, outcome)); }, From 3ba62dbfd71d95e1df57bc0dd5180370a9a16ce7 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 22 Feb 2022 00:57:38 -0800 Subject: [PATCH 38/73] Fixes --- xcm/xcm-simulator/fuzzer/src/parachain.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/xcm/xcm-simulator/fuzzer/src/parachain.rs b/xcm/xcm-simulator/fuzzer/src/parachain.rs index 2e10f652f73a..ebecc61d40c7 100644 --- a/xcm/xcm-simulator/fuzzer/src/parachain.rs +++ b/xcm/xcm-simulator/fuzzer/src/parachain.rs @@ -227,10 +227,11 @@ pub mod mock_msg_queue { max_weight: Weight, ) -> Result { let hash = Encode::using_encoded(&xcm, T::Hashing::hash); + let message_hash = xcm.using_encoded(sp_io::hashing::blake2_256); let (result, event) = match Xcm::::try_from(xcm) { Ok(xcm) => { let location = MultiLocation::new(1, X1(Parachain(sender.into()))); - match T::XcmExecutor::execute_xcm(location, xcm, max_weight) { + match T::XcmExecutor::execute_xcm(location, xcm, message_hash, max_weight) { Outcome::Error(e) => (Err(e.clone()), Event::Fail(Some(hash), e)), Outcome::Complete(w) => (Ok(w), Event::Success(Some(hash))), // As far as the caller is concerned, this was dispatched without error, so From 33a4308f56dd1e57ea3a0219f56a79cc6809719e Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 22 Feb 2022 01:47:36 -0800 Subject: [PATCH 39/73] Fixes --- xcm/src/v3/traits.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 82c4fe10797e..7e4e686a0fe6 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -386,6 +386,7 @@ impl Unwrappable for Option { /// /// # Example /// ```rust +/// # use parity_scale_codec::Encode; /// # use xcm::v3::prelude::*; /// # use xcm::VersionedXcm; /// # use std::convert::Infallible; @@ -427,7 +428,7 @@ impl Unwrappable for Option { /// _ => Err(SendError::NotApplicable), /// } /// } -/// fn deliver(_: ()) -> Result<(), SendError> { +/// fn deliver(_: ()) -> Result { /// Ok([0; 32]) /// } /// } @@ -440,7 +441,7 @@ impl Unwrappable for Option { /// require_weight_at_most: 0, /// call: call.into(), /// }]); -/// let message_hash = message.using_encoded(blake2_256); +/// let message_hash = message.using_encoded(sp_io::hashing::blake2_256); /// /// // Sender2 will block this. /// assert!(send_xcm::<(Sender1, Sender2, Sender3)>(Parent.into(), message.clone()).is_err()); From 0de1a0032c032bdd1b7b2dec338a0924d17109f3 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 12:02:13 -0800 Subject: [PATCH 40/73] Make XcmContext optional in withdraw_asset --- runtime/test-runtime/src/xcm_config.rs | 2 +- xcm/pallet-xcm-benchmarks/src/generic/mock.rs | 2 +- xcm/pallet-xcm/src/lib.rs | 18 +++++------------- xcm/xcm-builder/src/currency_adapter.rs | 2 +- xcm/xcm-builder/src/fungibles_adapter.rs | 4 ++-- xcm/xcm-builder/src/tests/mock.rs | 2 +- xcm/xcm-executor/src/traits/transact_asset.rs | 12 ++++++------ 7 files changed, 17 insertions(+), 25 deletions(-) diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 886c6c153b5c..99e60a9e0e76 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -61,7 +61,7 @@ impl TransactAsset for DummyAssetTransactor { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> Result { let asset: MultiAsset = (Parent, 100_000).into(); Ok(asset.into()) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index f3d56fc8174e..779c487896bd 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -91,7 +91,7 @@ impl xcm_executor::traits::TransactAsset for NoAssetTransactor { fn withdraw_asset( _: &MultiAsset, _: &MultiLocation, - _: XcmContext, + _: Option, ) -> Result { unreachable!(); } diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index 1c7fb0b80a95..8cd5decdef5e 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -1313,19 +1313,16 @@ impl Pallet { ) -> Result { let interior = interior.into(); let dest = dest.into(); - let maybe_fee_payer: Option = if interior != Junctions::Here { + let maybe_fee_payer = if interior != Junctions::Here { message.0.insert(0, DescendOrigin(interior.clone())); Some(interior.into()) } else { None }; log::trace!(target: "xcm::send_xcm", "dest: {:?}, message: {:?}", &dest, &message); - let message_hash = - VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); let (ticket, price) = validate_send::(dest, message)?; if let Some(fee_payer) = maybe_fee_payer { - let context = XcmContext { origin: Some(fee_payer.clone()), message_hash, topic: None }; - Self::charge_fees(fee_payer, price, context).map_err(|_| SendError::Fees)?; + Self::charge_fees(fee_payer, price).map_err(|_| SendError::Fees)?; } T::XcmRouter::deliver(ticket) } @@ -1483,18 +1480,13 @@ impl Pallet { }); } - /// Withdraw given `assets` from the given `location` with the given `context` and pay as XCM - /// fees. + /// Withdraw given `assets` from the given `location` and pay as XCM fees. /// /// Fails if: /// - the `assets` are not known on this chain; /// - the `assets` cannot be withdrawn with that location as the Origin. - fn charge_fees( - location: MultiLocation, - assets: MultiAssets, - context: XcmContext, - ) -> DispatchResult { - T::XcmExecutor::charge_fees(location.clone(), assets.clone(), context) + fn charge_fees(location: MultiLocation, assets: MultiAssets) -> DispatchResult { + T::XcmExecutor::charge_fees(location.clone(), assets.clone()) .map_err(|_| Error::::FeesNotMet)?; Self::deposit_event(Event::FeesPaid(location, assets)); Ok(()) diff --git a/xcm/xcm-builder/src/currency_adapter.rs b/xcm/xcm-builder/src/currency_adapter.rs index 7193479339be..b2e9e56f7668 100644 --- a/xcm/xcm-builder/src/currency_adapter.rs +++ b/xcm/xcm-builder/src/currency_adapter.rs @@ -165,7 +165,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> result::Result { log::trace!(target: "xcm::currency_adapter", "withdraw_asset what: {:?}, who: {:?}", what, who); // Check we handle this asset. diff --git a/xcm/xcm-builder/src/fungibles_adapter.rs b/xcm/xcm-builder/src/fungibles_adapter.rs index 73b462517431..689c66de1b8d 100644 --- a/xcm/xcm-builder/src/fungibles_adapter.rs +++ b/xcm/xcm-builder/src/fungibles_adapter.rs @@ -234,7 +234,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", @@ -316,7 +316,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - context: XcmContext, + context: Option, ) -> result::Result { FungiblesMutateAdapter::< Assets, diff --git a/xcm/xcm-builder/src/tests/mock.rs b/xcm/xcm-builder/src/tests/mock.rs index 93bc5a34c11d..e673d7d3f73c 100644 --- a/xcm/xcm-builder/src/tests/mock.rs +++ b/xcm/xcm-builder/src/tests/mock.rs @@ -217,7 +217,7 @@ impl TransactAsset for TestAssetTransactor { fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> Result { ASSETS.with(|a| { a.borrow_mut() diff --git a/xcm/xcm-executor/src/traits/transact_asset.rs b/xcm/xcm-executor/src/traits/transact_asset.rs index 9a9c1be9c218..e9078e97ba59 100644 --- a/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/xcm/xcm-executor/src/traits/transact_asset.rs @@ -78,7 +78,7 @@ pub trait TransactAsset { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> Result { Err(XcmError::Unimplemented) } @@ -106,7 +106,7 @@ pub trait TransactAsset { ) -> Result { match Self::transfer_asset(asset, from, to, context.clone()) { Err(XcmError::Unimplemented) => { - let assets = Self::withdraw_asset(asset, from, context.clone())?; + let assets = Self::withdraw_asset(asset, from, Some(context.clone()))?; // Not a very forgiving attitude; once we implement roll-backs then it'll be nicer. Self::deposit_asset(asset, to, context)?; Ok(assets) @@ -167,7 +167,7 @@ impl TransactAsset for Tuple { fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - context: XcmContext, + context: Option, ) -> Result { for_tuples!( #( match Tuple::withdraw_asset(what, who, context.clone()) { @@ -238,7 +238,7 @@ mod tests { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> Result { Err(XcmError::AssetNotFound) } @@ -274,7 +274,7 @@ mod tests { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> Result { Err(XcmError::Overflow) } @@ -310,7 +310,7 @@ mod tests { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: Option, ) -> Result { Ok(Assets::default()) } From f4751e25addb9b67bd52f1ec98c6c9c62b8f8a21 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 12:03:09 -0800 Subject: [PATCH 41/73] Fixes --- xcm/xcm-executor/src/lib.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index d69134da70b2..e62b83a42737 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -229,15 +229,11 @@ impl ExecuteXcm for XcmExecutor { vm.post_execute(xcm_weight, message_hash) } - fn charge_fees( - origin: impl Into, - fees: MultiAssets, - context: XcmContext, - ) -> XcmResult { + fn charge_fees(origin: impl Into, fees: MultiAssets) -> XcmResult { let origin = origin.into(); if !Config::FeeManager::is_waived(Some(&origin), FeeReason::ChargeFees) { for asset in fees.inner() { - Config::AssetTransactor::withdraw_asset(&asset, &origin, context.clone())?; + Config::AssetTransactor::withdraw_asset(&asset, &origin, None)?; } Config::FeeManager::handle_fee(fees); } From f4cd03805df2efb638efbf87835b91e8dbfec47d Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 12:15:45 -0800 Subject: [PATCH 42/73] Fixes --- xcm/src/v3/traits.rs | 6 +----- xcm/xcm-executor/src/lib.rs | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 7e4e686a0fe6..14a75c324db3 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -294,11 +294,7 @@ pub trait ExecuteXcm { /// Deduct some `fees` to the sovereign account of the given `location` and place them as per /// the convention for fees. - fn charge_fees( - location: impl Into, - fees: MultiAssets, - context: XcmContext, - ) -> Result; + fn charge_fees(location: impl Into, fees: MultiAssets) -> Result; } pub enum Weightless {} diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index e62b83a42737..702396bc60bc 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -439,7 +439,7 @@ impl XcmExecutor { message_hash, topic: self.topic, }; - Config::AssetTransactor::withdraw_asset(&asset, &origin, context)?; + Config::AssetTransactor::withdraw_asset(&asset, &origin, Some(context))?; self.subsume_asset(asset)?; } Ok(()) @@ -880,7 +880,7 @@ impl XcmExecutor { let paid = if self.fees_mode.jit_withdraw { let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; for asset in fee.inner() { - Config::AssetTransactor::withdraw_asset(&asset, origin, context.clone())?; + Config::AssetTransactor::withdraw_asset(&asset, origin, Some(context.clone()))?; } fee } else { From 8bf4f6a24ffb36a385a9f55d2c6476979356e749 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 13:23:08 -0800 Subject: [PATCH 43/73] Fixes --- xcm/src/v3/traits.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 14a75c324db3..d4b72a236785 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -312,11 +312,7 @@ impl ExecuteXcm for () { fn execute(_: impl Into, _: Self::Prepared, _: XcmHash, _: Weight) -> Outcome { unreachable!() } - fn charge_fees( - _location: impl Into, - _fees: MultiAssets, - _context: XcmContext, - ) -> Result { + fn charge_fees(_location: impl Into, _fees: MultiAssets) -> Result { Err(Error::Unimplemented) } } From 4b62f979a3e42cb4606e0667059b98339738e222 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 19:54:33 -0800 Subject: [PATCH 44/73] Modify tests to check for the correct XCM hash --- xcm/xcm-builder/tests/mock/mod.rs | 7 ++-- xcm/xcm-builder/tests/scenarios.rs | 67 +++++++++++++++++------------- 2 files changed, 43 insertions(+), 31 deletions(-) diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index 73d817ddad9d..fc5e1414c5fd 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -44,9 +44,9 @@ pub type AccountId = AccountId32; pub type Balance = u128; thread_local! { - pub static SENT_XCM: RefCell> = RefCell::new(Vec::new()); + pub static SENT_XCM: RefCell> = RefCell::new(Vec::new()); } -pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> { +pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm, XcmHash)> { SENT_XCM.with(|q| (*q.borrow()).clone()) } pub struct TestSendXcm; @@ -61,7 +61,8 @@ impl SendXcm for TestSendXcm { } fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { let hash = VersionedXcm::from(pair.1.clone()).using_encoded(sp_io::hashing::blake2_256); - SENT_XCM.with(|q| q.borrow_mut().push(pair)); + let triplet = (pair.0, pair.1, hash); + SENT_XCM.with(|q| q.borrow_mut().push(triplet)); Ok(hash) } } diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index 18f8ba245d44..edf76ec1293b 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -21,6 +21,7 @@ use mock::{ }; use parity_scale_codec::Encode; use polkadot_parachain::primitives::Id as ParaId; +use sp_io::hashing::blake2_256; use sp_runtime::traits::AccountIdConversion; use xcm::{latest::prelude::*, VersionedXcm}; use xcm_executor::XcmExecutor; @@ -55,7 +56,7 @@ fn withdraw_and_deposit_works() { beneficiary: Parachain(other_para_id).into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account(); @@ -96,7 +97,7 @@ fn report_holding_works() { // is not triggered becasue the deposit fails ReportHolding { response_info: response_info.clone(), assets: All.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!( r, @@ -120,22 +121,25 @@ fn report_holding_works() { // used to get a notification in case of success ReportHolding { response_info: response_info.clone(), assets: AllCounted(1).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account(); assert_eq!(Balances::free_balance(other_para_acc), amount); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - 2 * amount); + let expected_msg = Xcm(vec![QueryResponse { + query_id: response_info.query_id, + response: Response::Assets(vec![].into()), + max_weight: response_info.max_weight, + querier: Some(Here.into()), + }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), vec![( Parachain(PARA_ID).into(), - Xcm(vec![QueryResponse { - query_id: response_info.query_id, - response: Response::Assets(vec![].into()), - max_weight: response_info.max_weight, - querier: Some(Here.into()), - }]), + expected_msg, + expected_hash, )] ); }); @@ -177,17 +181,20 @@ fn teleport_to_statemine_works() { xcm: Xcm(teleport_effects.clone()), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); + let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] + .into_iter() + .chain(teleport_effects.clone().into_iter()) + .collect()); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), vec![( Parachain(other_para_id).into(), - Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] - .into_iter() - .chain(teleport_effects.clone().into_iter()) - .collect()) + expected_msg, + expected_hash, )] ); @@ -201,27 +208,28 @@ fn teleport_to_statemine_works() { xcm: Xcm(teleport_effects.clone()), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); // 2 * amount because of the other teleport above assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - 2 * amount); + let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] + .into_iter() + .chain(teleport_effects.clone().into_iter()) + .collect()); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), vec![ ( Parachain(other_para_id).into(), - Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] - .into_iter() - .chain(teleport_effects.clone().into_iter()) - .collect()), + expected_msg.clone(), + expected_hash, ), ( Parachain(statemine_id).into(), - Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] - .into_iter() - .chain(teleport_effects.clone().into_iter()) - .collect()), + expected_msg, + expected_hash, ) ] ); @@ -258,19 +266,22 @@ fn reserve_based_transfer_works() { xcm: Xcm(transfer_effects.clone()), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let weight = 3 * BaseXcmWeight::get(); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - amount); + let expected_msg = Xcm(vec![ReserveAssetDeposited((Parent, amount).into()), ClearOrigin,] + .into_iter() + .chain(transfer_effects.into_iter()) + .collect()); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), vec![( Parachain(other_para_id).into(), - Xcm(vec![ReserveAssetDeposited((Parent, amount).into()), ClearOrigin,] - .into_iter() - .chain(transfer_effects.into_iter()) - .collect()) + expected_msg, + expected_hash, )] ); }); From 8702ebcf94b77a7173dfd6ec1dcef89bed54219a Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 20:00:20 -0800 Subject: [PATCH 45/73] Small refactor --- xcm/xcm-builder/tests/mock/mod.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index fc5e1414c5fd..541251991d29 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -51,17 +51,18 @@ pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm, XcmHash)> { } pub struct TestSendXcm; impl SendXcm for TestSendXcm { - type Ticket = (MultiLocation, Xcm<()>); + type Ticket = (MultiLocation, Xcm<()>, XcmHash); fn validate( dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>)> { - let pair = (dest.take().unwrap(), msg.take().unwrap()); - Ok((pair, MultiAssets::new())) + ) -> SendResult<(MultiLocation, Xcm<()>, XcmHash)> { + let msg = msg.take().unwrap(); + let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let triplet = (dest.take().unwrap(), msg, hash); + Ok((triplet, MultiAssets::new())) } - fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { - let hash = VersionedXcm::from(pair.1.clone()).using_encoded(sp_io::hashing::blake2_256); - let triplet = (pair.0, pair.1, hash); + fn deliver(triplet: (MultiLocation, Xcm<()>, XcmHash)) -> Result { + let hash = triplet.2; SENT_XCM.with(|q| q.borrow_mut().push(triplet)); Ok(hash) } From 0cde431e4bf0f2c17c81bc81bf36d5cd796cc286 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 20:40:04 -0800 Subject: [PATCH 46/73] cargo fmt --- xcm/xcm-builder/tests/scenarios.rs | 36 +++++++----------------------- 1 file changed, 8 insertions(+), 28 deletions(-) diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index edf76ec1293b..0d6eca893d97 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -136,11 +136,7 @@ fn report_holding_works() { let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), - vec![( - Parachain(PARA_ID).into(), - expected_msg, - expected_hash, - )] + vec![(Parachain(PARA_ID).into(), expected_msg, expected_hash,)] ); }); } @@ -184,18 +180,14 @@ fn teleport_to_statemine_works() { let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); - let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] + let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin] .into_iter() .chain(teleport_effects.clone().into_iter()) .collect()); let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), - vec![( - Parachain(other_para_id).into(), - expected_msg, - expected_hash, - )] + vec![(Parachain(other_para_id).into(), expected_msg, expected_hash,)] ); // teleports are allowed from statemine to kusama. @@ -213,7 +205,7 @@ fn teleport_to_statemine_works() { assert_eq!(r, Outcome::Complete(weight)); // 2 * amount because of the other teleport above assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - 2 * amount); - let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin,] + let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin] .into_iter() .chain(teleport_effects.clone().into_iter()) .collect()); @@ -221,16 +213,8 @@ fn teleport_to_statemine_works() { assert_eq!( mock::sent_xcm(), vec![ - ( - Parachain(other_para_id).into(), - expected_msg.clone(), - expected_hash, - ), - ( - Parachain(statemine_id).into(), - expected_msg, - expected_hash, - ) + (Parachain(other_para_id).into(), expected_msg.clone(), expected_hash,), + (Parachain(statemine_id).into(), expected_msg, expected_hash,) ] ); }); @@ -271,18 +255,14 @@ fn reserve_based_transfer_works() { let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!(Balances::free_balance(para_acc), INITIAL_BALANCE - amount); - let expected_msg = Xcm(vec![ReserveAssetDeposited((Parent, amount).into()), ClearOrigin,] + let expected_msg = Xcm(vec![ReserveAssetDeposited((Parent, amount).into()), ClearOrigin] .into_iter() .chain(transfer_effects.into_iter()) .collect()); let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!( mock::sent_xcm(), - vec![( - Parachain(other_para_id).into(), - expected_msg, - expected_hash, - )] + vec![(Parachain(other_para_id).into(), expected_msg, expected_hash,)] ); }); } From 2ca011781a2b44de2172f7ad9ae5396ea164bd33 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 23 Feb 2022 23:40:05 -0800 Subject: [PATCH 47/73] Check for expected hash in xcm-builder unit tests --- xcm/xcm-builder/src/tests/assets.rs | 56 ++++++++++----------- xcm/xcm-builder/src/tests/locking.rs | 22 +++----- xcm/xcm-builder/src/tests/mock.rs | 39 ++++++++------- xcm/xcm-builder/src/tests/origins.rs | 3 +- xcm/xcm-builder/src/tests/querying.rs | 64 +++++++++++------------- xcm/xcm-builder/src/tests/transacting.rs | 60 +++++++++------------- 6 files changed, 109 insertions(+), 135 deletions(-) diff --git a/xcm/xcm-builder/src/tests/assets.rs b/xcm/xcm-builder/src/tests/assets.rs index 114d42c3e6ef..ed1efed9b79e 100644 --- a/xcm/xcm-builder/src/tests/assets.rs +++ b/xcm/xcm-builder/src/tests/assets.rs @@ -32,7 +32,7 @@ fn exchange_asset_should_work() { maximal: true, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list(Parent), vec![(Here, 100).into(), (Parent, 950).into()]); @@ -55,7 +55,7 @@ fn exchange_asset_without_maximal_should_work() { maximal: false, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list(Parent), vec![(Here, 50).into(), (Parent, 950).into()]); @@ -78,7 +78,7 @@ fn exchange_asset_should_fail_when_no_deal_possible() { maximal: false, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Incomplete(40, XcmError::NoDeal)); assert_eq!(asset_list(Parent), vec![(Parent, 1000).into()]); @@ -97,7 +97,7 @@ fn paying_reserve_deposit_should_work() { BuyExecution { fees, weight_limit: Limited(30) }, DepositAsset { assets: AllCounted(1).into(), beneficiary: Here.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let weight_limit = 50; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(30)); @@ -115,7 +115,7 @@ fn transfer_should_work() { assets: (Here, 100).into(), beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 100).into()]); @@ -141,22 +141,18 @@ fn reserve_transfer_should_work() { beneficiary: three.clone(), }]), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); + let expected_msg = Xcm::<()>(vec![ + ReserveAssetDeposited((Parent, 100).into()), + ClearOrigin, + DepositAsset { assets: AllCounted(1).into(), beneficiary: three }, + ]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); assert_eq!(asset_list(Parachain(2)), vec![(Here, 100).into()]); - assert_eq!( - sent_xcm(), - vec![( - Parachain(2).into(), - Xcm::<()>(vec![ - ReserveAssetDeposited((Parent, 100).into()), - ClearOrigin, - DepositAsset { assets: AllCounted(1).into(), beneficiary: three }, - ]), - )] - ); + assert_eq!(sent_xcm(), vec![(Parachain(2).into(), expected_msg, expected_hash)]); } #[test] @@ -171,7 +167,7 @@ fn burn_should_work() { BurnAsset((Here, 100).into()), DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -183,7 +179,7 @@ fn burn_should_work() { BurnAsset((Here, 1000).into()), DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Parachain(1)), vec![]); @@ -205,7 +201,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Complete(25)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -219,7 +215,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -235,7 +231,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm(Parachain(2), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -251,7 +247,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -266,7 +262,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -280,7 +276,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); } @@ -311,7 +307,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([7u8; 32], 100).into()), WithdrawAsset(([8u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 100); assert_eq!(r, Outcome::Complete(85)); @@ -327,7 +323,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([8u8; 32], 100).into()), WithdrawAsset(([9u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 100); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); @@ -346,7 +342,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([7u8; 32], 100).into()), WithdrawAsset(([8u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Complete(125)); @@ -365,7 +361,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([3u8; 32], 100).into()), WithdrawAsset(([4u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); @@ -383,7 +379,7 @@ fn max_assets_limit_should_work() { ])), WithdrawAsset(([1u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Incomplete(25, XcmError::HoldingWouldOverflow)); } diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index 5e8ca80c0d1a..c1393f32441c 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -39,13 +39,10 @@ fn lock_roundtrip_should_work() { assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); - assert_eq!( - sent_xcm(), - vec![( - (Parent, Parachain(1)).into(), - Xcm::<()>(vec![NoteUnlockable { owner: (3u64,).into(), asset: (Parent, 100).into() },]), - )] - ); + let expected_msg = + Xcm::<()>(vec![NoteUnlockable { owner: (3u64,).into(), asset: (Parent, 100).into() }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![((Parent, Parachain(1)).into(), expected_msg, expected_hash)]); assert_eq!( take_lock_trace(), vec![Lock { @@ -153,13 +150,10 @@ fn remote_unlock_roundtrip_should_work() { assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); - assert_eq!( - sent_xcm(), - vec![( - (Parent, Parachain(1)).into(), - Xcm::<()>(vec![UnlockAsset { target: (3u64,).into(), asset: (Parent, 100).into() },]), - )] - ); + let expected_msg = + Xcm::<()>(vec![UnlockAsset { target: (3u64,).into(), asset: (Parent, 100).into() }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![((Parent, Parachain(1)).into(), expected_msg, expected_hash)]); assert_eq!( take_lock_trace(), vec![Reduce { diff --git a/xcm/xcm-builder/src/tests/mock.rs b/xcm/xcm-builder/src/tests/mock.rs index e673d7d3f73c..b720639c54a4 100644 --- a/xcm/xcm-builder/src/tests/mock.rs +++ b/xcm/xcm-builder/src/tests/mock.rs @@ -29,6 +29,7 @@ pub use frame_support::{ weights::{GetDispatchInfo, PostDispatchInfo}, }; pub use parity_scale_codec::{Decode, Encode}; +pub use sp_io::hashing::blake2_256; pub use sp_std::{ cell::RefCell, collections::{btree_map::BTreeMap, btree_set::BTreeSet}, @@ -104,21 +105,21 @@ impl GetDispatchInfo for TestCall { } thread_local! { - pub static SENT_XCM: RefCell)>> = RefCell::new(Vec::new()); - pub static EXPORTED_XCM: RefCell)>> = RefCell::new(Vec::new()); + pub static SENT_XCM: RefCell, XcmHash)>> = RefCell::new(Vec::new()); + pub static EXPORTED_XCM: RefCell, XcmHash)>> = RefCell::new(Vec::new()); pub static EXPORTER_OVERRIDE: RefCell) -> Result, fn(NetworkId, u32, InteriorMultiLocation, Xcm<()>) -> Result, )>> = RefCell::new(None); pub static SEND_PRICE: RefCell = RefCell::new(MultiAssets::new()); } -pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm)> { +pub fn sent_xcm() -> Vec<(MultiLocation, opaque::Xcm, XcmHash)> { SENT_XCM.with(|q| (*q.borrow()).clone()) } pub fn set_send_price(p: impl Into) { SEND_PRICE.with(|l| l.replace(p.into().into())); } -pub fn exported_xcm() -> Vec<(NetworkId, u32, InteriorMultiLocation, opaque::Xcm)> { +pub fn exported_xcm() -> Vec<(NetworkId, u32, InteriorMultiLocation, opaque::Xcm, XcmHash)> { EXPORTED_XCM.with(|q| (*q.borrow()).clone()) } pub fn set_exporter_override( @@ -133,29 +134,31 @@ pub fn clear_exporter_override() { } pub struct TestMessageSender; impl SendXcm for TestMessageSender { - type Ticket = (MultiLocation, Xcm<()>); + type Ticket = (MultiLocation, Xcm<()>, XcmHash); fn validate( dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(MultiLocation, Xcm<()>)> { - let pair = (dest.take().unwrap(), msg.take().unwrap()); - Ok((pair, SEND_PRICE.with(|l| l.borrow().clone()))) + ) -> SendResult<(MultiLocation, Xcm<()>, XcmHash)> { + let msg = msg.take().unwrap(); + let hash = VersionedXcm::from(msg.clone()).using_encoded(blake2_256); + let triplet = (dest.take().unwrap(), msg, hash); + Ok((triplet, SEND_PRICE.with(|l| l.borrow().clone()))) } - fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { - let hash = VersionedXcm::from(pair.1.clone()).using_encoded(sp_io::hashing::blake2_256); - SENT_XCM.with(|q| q.borrow_mut().push(pair)); + fn deliver(triplet: (MultiLocation, Xcm<()>, XcmHash)) -> Result { + let hash = triplet.2; + SENT_XCM.with(|q| q.borrow_mut().push(triplet)); Ok(hash) } } pub struct TestMessageExporter; impl ExportXcm for TestMessageExporter { - type Ticket = (NetworkId, u32, InteriorMultiLocation, Xcm<()>); + type Ticket = (NetworkId, u32, InteriorMultiLocation, Xcm<()>, XcmHash); fn validate( network: NetworkId, channel: u32, dest: &mut Option, msg: &mut Option>, - ) -> SendResult<(NetworkId, u32, InteriorMultiLocation, Xcm<()>)> { + ) -> SendResult<(NetworkId, u32, InteriorMultiLocation, Xcm<()>, XcmHash)> { let (d, m) = (dest.take().unwrap(), msg.take().unwrap()); let r: Result = EXPORTER_OVERRIDE.with(|e| { if let Some((ref f, _)) = &*e.borrow() { @@ -164,8 +167,9 @@ impl ExportXcm for TestMessageExporter { Ok(MultiAssets::new()) } }); + let h = VersionedXcm::from(m.clone()).using_encoded(blake2_256); match r { - Ok(price) => Ok(((network, channel, d, m), price)), + Ok(price) => Ok(((network, channel, d, m, h), price)), Err(e) => { *dest = Some(d); *msg = Some(m); @@ -174,15 +178,14 @@ impl ExportXcm for TestMessageExporter { } } fn deliver( - tuple: (NetworkId, u32, InteriorMultiLocation, Xcm<()>), + tuple: (NetworkId, u32, InteriorMultiLocation, Xcm<()>, XcmHash), ) -> Result { EXPORTER_OVERRIDE.with(|e| { if let Some((_, ref f)) = &*e.borrow() { - let (network, channel, dest, msg) = tuple; + let (network, channel, dest, msg, _hash) = tuple; f(network, channel, dest, msg) } else { - let hash = - VersionedXcm::from(tuple.3.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = tuple.4; EXPORTED_XCM.with(|q| q.borrow_mut().push(tuple)); Ok(hash) } diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index 05a5f7f86bb3..a3ca40ca51d5 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -63,7 +63,8 @@ fn export_message_should_work() { let exported_msg = Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: message.clone() }]); let hash = VersionedXcm::from(exported_msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let expected_hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); let r = XcmExecutor::::execute_xcm(Parachain(1), exported_msg, hash, 50); assert_eq!(r, Outcome::Complete(10)); - assert_eq!(exported_xcm(), vec![(Polkadot, 403611790, Here, message)]); + assert_eq!(exported_xcm(), vec![(Polkadot, 403611790, Here, message, expected_hash)]); } diff --git a/xcm/xcm-builder/src/tests/querying.rs b/xcm/xcm-builder/src/tests/querying.rs index 7aec423e73df..860a7fe3a557 100644 --- a/xcm/xcm-builder/src/tests/querying.rs +++ b/xcm/xcm-builder/src/tests/querying.rs @@ -33,18 +33,14 @@ fn pallet_query_should_work() { let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); - assert_eq!( - sent_xcm(), - vec![( - Parachain(1).into(), - Xcm::<()>(vec![QueryResponse { - query_id: 1, - max_weight: 50, - response: Response::PalletsInfo(vec![].try_into().unwrap()), - querier: Some(Here.into()), - }]), - )] - ); + let expected_msg = Xcm::<()>(vec![QueryResponse { + query_id: 1, + max_weight: 50, + response: Response::PalletsInfo(vec![].try_into().unwrap()), + querier: Some(Here.into()), + }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![(Parachain(1).into(), expected_msg, expected_hash)]); } #[test] @@ -64,30 +60,26 @@ fn pallet_query_with_results_should_work() { let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); - assert_eq!( - sent_xcm(), - vec![( - Parachain(1).into(), - Xcm::<()>(vec![QueryResponse { - query_id: 1, - max_weight: 50, - response: Response::PalletsInfo( - vec![PalletInfo::new( - 1, - b"Balances".as_ref().into(), - b"pallet_balances".as_ref().into(), - 1, - 42, - 69, - ) - .unwrap(),] - .try_into() - .unwrap() - ), - querier: Some(Here.into()), - }]), - )] - ); + let expected_msg = Xcm::<()>(vec![QueryResponse { + query_id: 1, + max_weight: 50, + response: Response::PalletsInfo( + vec![PalletInfo::new( + 1, + b"Balances".as_ref().into(), + b"pallet_balances".as_ref().into(), + 1, + 42, + 69, + ) + .unwrap()] + .try_into() + .unwrap(), + ), + querier: Some(Here.into()), + }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![(Parachain(1).into(), expected_msg, expected_hash)]); } #[test] diff --git a/xcm/xcm-builder/src/tests/transacting.rs b/xcm/xcm-builder/src/tests/transacting.rs index 68108ce268b3..cd7445f8ad6b 100644 --- a/xcm/xcm-builder/src/tests/transacting.rs +++ b/xcm/xcm-builder/src/tests/transacting.rs @@ -109,18 +109,14 @@ fn report_successful_transact_status_should_work() { let weight_limit = 70; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(70)); - assert_eq!( - sent_xcm(), - vec![( - Parent.into(), - Xcm(vec![QueryResponse { - response: Response::DispatchResult(MaybeErrorCode::Success), - query_id: 42, - max_weight: 5000, - querier: Some(Here.into()), - }]) - )] - ); + let expected_msg = Xcm(vec![QueryResponse { + response: Response::DispatchResult(MaybeErrorCode::Success), + query_id: 42, + max_weight: 5000, + querier: Some(Here.into()), + }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![(Parent.into(), expected_msg, expected_hash)]); } #[test] @@ -143,18 +139,14 @@ fn report_failed_transact_status_should_work() { let weight_limit = 70; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(70)); - assert_eq!( - sent_xcm(), - vec![( - Parent.into(), - Xcm(vec![QueryResponse { - response: Response::DispatchResult(MaybeErrorCode::Error(vec![2])), - query_id: 42, - max_weight: 5000, - querier: Some(Here.into()), - }]) - )] - ); + let expected_msg = Xcm(vec![QueryResponse { + response: Response::DispatchResult(MaybeErrorCode::Error(vec![2])), + query_id: 42, + max_weight: 5000, + querier: Some(Here.into()), + }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![(Parent.into(), expected_msg, expected_hash)]); } #[test] @@ -178,16 +170,12 @@ fn clear_transact_status_should_work() { let weight_limit = 80; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(80)); - assert_eq!( - sent_xcm(), - vec![( - Parent.into(), - Xcm(vec![QueryResponse { - response: Response::DispatchResult(MaybeErrorCode::Success), - query_id: 42, - max_weight: 5000, - querier: Some(Here.into()), - }]) - )] - ); + let expected_msg = Xcm(vec![QueryResponse { + response: Response::DispatchResult(MaybeErrorCode::Success), + query_id: 42, + max_weight: 5000, + querier: Some(Here.into()), + }]); + let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + assert_eq!(sent_xcm(), vec![(Parent.into(), expected_msg, expected_hash)]); } From 3df1279ed446b647083e8f8f2f84bc662d42c218 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 1 Mar 2022 03:21:53 -0800 Subject: [PATCH 48/73] Add doc comment for the optionality of the XCM context in withdraw_asset --- xcm/xcm-executor/src/traits/transact_asset.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/xcm/xcm-executor/src/traits/transact_asset.rs b/xcm/xcm-executor/src/traits/transact_asset.rs index e9078e97ba59..f18ef0d296ff 100644 --- a/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/xcm/xcm-executor/src/traits/transact_asset.rs @@ -74,6 +74,10 @@ pub trait TransactAsset { /// Withdraw the given asset from the consensus system. Return the actual asset(s) withdrawn, /// which should always be equal to `_what`. /// + /// The XCM `_context` parameter may be `None` when the caller of `withdraw_asset` is outside of + /// the context of a currently-executing XCM. An example will be the `charge_fees` method in the + /// XCM executor. + /// /// Implementations should return `XcmError::FailedToTransactAsset` if withdraw failed. fn withdraw_asset( _what: &MultiAsset, From a5492869df629ad2d10fae3d4ec67597b4b14ad9 Mon Sep 17 00:00:00 2001 From: Gavin Wood Date: Sat, 5 Mar 2022 14:12:02 +0100 Subject: [PATCH 49/73] Update xcm/src/v3/traits.rs --- xcm/src/v3/traits.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index d4b72a236785..49cce4c2cf40 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -250,7 +250,7 @@ pub trait ExecuteXcm { weight_credit: Weight, ) -> Outcome; - /// Execute some XCM `message` with the versioned `hash` from `origin` using no more than `weight_limit` weight. + /// Execute some XCM `message` with the message `hash` from `origin` using no more than `weight_limit` weight. /// The weight limit is a basic hard-limit and the implementation may place further restrictions or requirements /// on weight and other aspects. fn execute_xcm( From 18bb864c08e4b91ff130ca51ac222f4ae5ddb8b9 Mon Sep 17 00:00:00 2001 From: Gavin Wood Date: Sat, 5 Mar 2022 14:12:07 +0100 Subject: [PATCH 50/73] Update xcm/src/v3/traits.rs --- xcm/src/v3/traits.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 49cce4c2cf40..1e3baae37d7a 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -270,7 +270,7 @@ pub trait ExecuteXcm { Self::execute_xcm_in_credit(origin, message, hash, weight_limit, 0) } - /// Execute some XCM `message` with the versioned `hash` from `origin` using no more than `weight_limit` weight. + /// Execute some XCM `message` with the message `hash` from `origin` using no more than `weight_limit` weight. /// /// Some amount of `weight_credit` may be provided which, depending on the implementation, may allow /// execution without associated payment. From 3c1117f20aa335a2b315e93bc3fde283b6d09e6e Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Sat, 5 Mar 2022 14:42:02 +0100 Subject: [PATCH 51/73] Store XcmContext and avoid rebuilding --- xcm/xcm-executor/src/lib.rs | 167 +++++++++++++++--------------------- 1 file changed, 69 insertions(+), 98 deletions(-) diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 702396bc60bc..6be88ba0d927 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -26,7 +26,7 @@ use parity_scale_codec::{Decode, Encode}; use sp_io::hashing::blake2_128; use sp_runtime::traits::Saturating; use sp_std::{marker::PhantomData, prelude::*}; -use xcm::{latest::prelude::*, VersionedXcm}; +use xcm::latest::prelude::*; pub mod traits; use traits::{ @@ -49,7 +49,7 @@ pub struct FeesMode { pub struct XcmExecutor { holding: Assets, holding_limit: usize, - origin: Option, + context: XcmContext, original_origin: MultiLocation, trader: Config::Trader, /// The most recent error result and instruction index into the fragment in which it occurred, @@ -86,10 +86,10 @@ impl XcmExecutor { self.holding_limit = v } pub fn origin(&self) -> &Option { - &self.origin + &self.context.origin } pub fn set_origin(&mut self, v: Option) { - self.origin = v + self.context.origin = v } pub fn original_origin(&self) -> &MultiLocation { &self.original_origin @@ -211,10 +211,10 @@ impl ExecuteXcm for XcmExecutor { return Outcome::Error(XcmError::Barrier) } - let mut vm = Self::new(origin); + let mut vm = Self::new(origin, message_hash); while !message.0.is_empty() { - let result = vm.execute_with_hash(message, message_hash); + let result = vm.process(message); log::trace!(target: "xcm::execute_xcm_in_credit", "result: {:?}", result); message = if let Err(error) = result { vm.total_surplus.saturating_accrue(error.weight); @@ -226,7 +226,7 @@ impl ExecuteXcm for XcmExecutor { } } - vm.post_execute(xcm_weight, message_hash) + vm.post_process(xcm_weight) } fn charge_fees(origin: impl Into, fees: MultiAssets) -> XcmResult { @@ -262,12 +262,12 @@ impl From for frame_benchmarking::BenchmarkError { } impl XcmExecutor { - pub fn new(origin: impl Into) -> Self { + pub fn new(origin: impl Into, message_hash: XcmHash, ) -> Self { let origin = origin.into(); Self { holding: Assets::new(), holding_limit: Config::MaxAssetsIntoHolding::get() as usize, - origin: Some(origin.clone()), + context: XcmContext { origin: Some(origin.clone()), message_hash, topic: None }, original_origin: origin, trader: Config::Trader::new(), error: None, @@ -284,23 +284,14 @@ impl XcmExecutor { } } - /// Execute the XCM program fragment and report back the error and which instruction caused it, - /// or `Ok` if there was no error. - pub fn execute(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { - let message_hash = - VersionedXcm::from(xcm.clone()).using_encoded(sp_io::hashing::blake2_256); - self.execute_with_hash(xcm, message_hash) - } - - fn execute_with_hash( + fn process( &mut self, xcm: Xcm, - message_hash: XcmHash, ) -> Result<(), ExecutorError> { log::trace!( - target: "xcm::execute", + target: "xcm::process", "origin: {:?}, total_surplus/refunded: {:?}/{:?}, error_handler_weight: {:?}", - self.origin, + self.origin(), self.total_surplus, self.total_refunded, self.error_handler_weight, @@ -309,7 +300,7 @@ impl XcmExecutor { for (i, instr) in xcm.0.into_iter().enumerate() { match &mut result { r @ Ok(()) => - if let Err(e) = self.process_instruction(instr, message_hash) { + if let Err(e) = self.process_instruction(instr) { *r = Err(ExecutorError { index: i as u32, xcm_error: e, weight: 0 }); }, Err(ref mut error) => @@ -323,7 +314,7 @@ impl XcmExecutor { /// Execute any final operations after having executed the XCM message. /// This includes refunding surplus weight, trapping extra holding funds, and returning any errors during execution. - pub fn post_execute(mut self, xcm_weight: Weight, message_hash: [u8; 32]) -> Outcome { + pub fn post_process(mut self, xcm_weight: Weight) -> Outcome { // We silently drop any error from our attempt to refund the surplus as it's a charitable // thing so best-effort is all we will do. let _ = self.refund_surplus(); @@ -332,8 +323,7 @@ impl XcmExecutor { let mut weight_used = xcm_weight.saturating_sub(self.total_surplus); if !self.holding.is_empty() { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + let context = self.context.clone(); log::trace!( target: "xcm::execute_xcm_in_credit", "Trapping assets in holding register: {:?}, context: {:?} (original_origin: {:?})", @@ -355,6 +345,14 @@ impl XcmExecutor { } } + fn origin(&self) -> Option<&MultiLocation> { + self.context.origin.as_ref() + } + + fn cloned_origin(&self) -> Option { + self.context.origin.clone() + } + /// Send an XCM, charging fees from Holding as needed. fn send( &mut self, @@ -363,7 +361,7 @@ impl XcmExecutor { reason: FeeReason, ) -> Result { let (ticket, fee) = validate_send::(dest, msg)?; - if !Config::FeeManager::is_waived(self.origin.as_ref(), reason) { + if !Config::FeeManager::is_waived(self.origin(), reason) { let paid = self.holding.try_take(fee.into()).map_err(|_| XcmError::NotHoldingFees)?; Config::FeeManager::handle_fee(paid.into()); } @@ -427,26 +425,21 @@ impl XcmExecutor { fn process_instruction( &mut self, instr: Instruction, - message_hash: XcmHash, ) -> Result<(), XcmError> { match instr { WithdrawAsset(assets) => { // Take `assets` from the origin account (on-chain) and place in holding. - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.into_inner().into_iter() { - let context = XcmContext { - origin: Some(origin.clone()), - message_hash, - topic: self.topic, - }; - Config::AssetTransactor::withdraw_asset(&asset, &origin, Some(context))?; + let context = Some(self.context.clone()); + Config::AssetTransactor::withdraw_asset(&asset, &origin, context)?; self.subsume_asset(asset)?; } Ok(()) }, ReserveAssetDeposited(assets) => { // check whether we trust origin to be our reserve location for this asset. - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.into_inner().into_iter() { // Must ensure that we recognise the asset as being managed by the origin. ensure!( @@ -459,26 +452,18 @@ impl XcmExecutor { }, TransferAsset { assets, beneficiary } => { // Take `assets` from the origin account (on-chain) and place into dest account. - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; for asset in assets.inner() { - let context = XcmContext { - origin: Some(origin.clone()), - message_hash, - topic: self.topic, - }; + let context = self.context.clone(); Config::AssetTransactor::beam_asset(&asset, origin, &beneficiary, context)?; } Ok(()) }, TransferReserveAsset { mut assets, dest, xcm } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; // Take `assets` from the origin account (on-chain) and place into dest account. for asset in assets.inner() { - let context = XcmContext { - origin: Some(origin.clone()), - message_hash, - topic: self.topic, - }; + let context = self.context.clone(); Config::AssetTransactor::beam_asset(asset, origin, &dest, context)?; } let context = Config::LocationInverter::universal_location().into(); @@ -489,9 +474,8 @@ impl XcmExecutor { Ok(()) }, ReceiveTeleportedAsset(assets) => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let context = self.context.clone(); // check whether we trust origin to teleport this asset to us via config trait. for asset in assets.inner() { // We only trust the origin to send us assets that they identify as their @@ -513,7 +497,7 @@ impl XcmExecutor { }, Transact { origin_kind, require_weight_at_most, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| XcmError::FailedToDecode)?; @@ -545,9 +529,8 @@ impl XcmExecutor { Ok(()) }, QueryResponse { query_id, response, max_weight, querier } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let context = self.context.clone(); Config::ResponseHandler::on_response( origin, query_id, @@ -559,20 +542,21 @@ impl XcmExecutor { Ok(()) }, DescendOrigin(who) => self + .context .origin .as_mut() .ok_or(XcmError::BadOrigin)? .append_with(who) .map_err(|_| XcmError::MultiLocationFull), ClearOrigin => { - self.origin = None; + self.context.origin = None; Ok(()) }, ReportError(response_info) => { // Report the given result by sending a QueryResponse XCM to a previously given outcome // destination if one was registered. self.respond( - self.origin.clone(), + self.cloned_origin(), Response::ExecutionResult(self.error), response_info, FeeReason::Report, @@ -582,17 +566,14 @@ impl XcmExecutor { DepositAsset { assets, beneficiary } => { let deposited = self.holding.saturating_take(assets); for asset in deposited.into_assets_iter() { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; - Config::AssetTransactor::deposit_asset(&asset, &beneficiary, context)?; + Config::AssetTransactor::deposit_asset(&asset, &beneficiary, self.context.clone())?; } Ok(()) }, DepositReserveAsset { assets, dest, xcm } => { let deposited = self.holding.saturating_take(assets); for asset in deposited.assets_iter() { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + let context = self.context.clone(); Config::AssetTransactor::deposit_asset(&asset, &dest, context)?; } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot @@ -620,8 +601,7 @@ impl XcmExecutor { // We must do this first in order to resolve wildcards. let assets = self.holding.saturating_take(assets); for asset in assets.assets_iter() { - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; + let context = self.context.clone(); Config::AssetTransactor::check_out(&dest, &asset, context); } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot @@ -638,7 +618,7 @@ impl XcmExecutor { let assets = Self::reanchored(self.holding.min(&assets), &response_info.destination, None); self.respond( - self.origin.clone(), + self.cloned_origin(), Response::Assets(assets), response_info, FeeReason::Report, @@ -681,9 +661,8 @@ impl XcmExecutor { Ok(()) }, ClaimAsset { assets, ticket } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let context = self.context.clone(); let ok = Config::AssetClaims::claim_assets(origin, &ticket, &assets, context); ensure!(ok, XcmError::UnknownClaim); for asset in assets.into_inner().into_iter() { @@ -693,19 +672,17 @@ impl XcmExecutor { }, Trap(code) => Err(XcmError::Trap(code)), SubscribeVersion { query_id, max_response_weight } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; // We don't allow derivative origins to subscribe since it would otherwise pose a // DoS risk. ensure!(&self.original_origin == origin, XcmError::BadOrigin); - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let context = self.context.clone(); Config::SubscriptionService::start(origin, query_id, max_response_weight, context) }, UnsubscribeVersion => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; ensure!(&self.original_origin == origin, XcmError::BadOrigin); - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; + let context = self.context.clone(); Config::SubscriptionService::stop(origin, context) }, BurnAsset(assets) => { @@ -715,7 +692,7 @@ impl XcmExecutor { ExpectAsset(assets) => self.holding.ensure_contains(&assets).map_err(|_| XcmError::ExpectationFalse), ExpectOrigin(origin) => { - ensure!(self.origin == origin, XcmError::ExpectationFalse); + ensure!(self.context.origin == origin, XcmError::ExpectationFalse); Ok(()) }, ExpectError(error) => { @@ -739,7 +716,7 @@ impl XcmExecutor { .collect::, XcmError>>()?; let QueryResponseInfo { destination, query_id, max_weight } = response_info; let response = Response::PalletsInfo(pallets.try_into()?); - let querier = Self::to_querier(self.origin.clone(), &destination)?; + let querier = Self::to_querier(self.cloned_origin(), &destination)?; let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); self.send(destination, message, FeeReason::QueryPallet)?; @@ -760,7 +737,7 @@ impl XcmExecutor { }, ReportTransactStatus(response_info) => { self.respond( - self.origin.clone(), + self.cloned_origin(), Response::DispatchResult(self.transact_status.clone()), response_info, FeeReason::Report, @@ -774,56 +751,52 @@ impl XcmExecutor { UniversalOrigin(new_global) => { let universal_location = Config::LocationInverter::universal_location(); ensure!(universal_location.first() != Some(&new_global), XcmError::InvalidLocation); - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); let origin_xform = (origin, new_global); let ok = Config::UniversalAliases::contains(&origin_xform); ensure!(ok, XcmError::InvalidLocation); let (_, new_global) = origin_xform; let new_origin = X1(new_global).relative_to(&universal_location); - self.origin = Some(new_origin); + self.context.origin = Some(new_origin); Ok(()) }, ExportMessage { network, destination, xcm } => { - let hash = (&self.origin, &destination).using_encoded(blake2_128); + let hash = (self.origin(), &destination).using_encoded(blake2_128); let channel = u32::decode(&mut hash.as_ref()).unwrap_or(0); - let context = - XcmContext { origin: self.origin.clone(), message_hash, topic: self.topic }; // Hash identifies the lane on the exporter which we use. We use the pairwise // combination of the origin and destination to ensure origin/destination pairs will // generally have their own lanes. let (ticket, fee) = validate_export::(network, channel, destination, xcm)?; - self.take_fee(fee, FeeReason::Export(network), context)?; + self.take_fee(fee, FeeReason::Export(network))?; Config::MessageExporter::deliver(ticket)?; Ok(()) }, LockAsset { asset, unlocker } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); let remote_asset = Self::try_reanchor(asset.clone(), &unlocker)?; let lock_ticket = Config::AssetLocker::prepare_lock(unlocker.clone(), asset, origin.clone())?; let msg = Xcm::<()>(vec![NoteUnlockable { asset: remote_asset, owner: origin.clone() }]); - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; let (ticket, price) = validate_send::(unlocker, msg)?; - self.take_fee(price, FeeReason::LockAsset, context)?; + self.take_fee(price, FeeReason::LockAsset)?; lock_ticket.enact()?; Config::XcmSender::deliver(ticket)?; Ok(()) }, UnlockAsset { asset, target } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); Config::AssetLocker::prepare_unlock(origin.clone(), asset, target)?.enact()?; Ok(()) }, NoteUnlockable { asset, owner } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); Config::AssetLocker::note_unlockable(origin, asset, owner)?; Ok(()) }, RequestUnlock { asset, locker } => { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); let remote_asset = Self::try_reanchor(asset.clone(), &locker)?; let reduce_ticket = Config::AssetLocker::prepare_reduce_unlockable( locker.clone(), @@ -832,16 +805,14 @@ impl XcmExecutor { )?; let msg = Xcm::<()>(vec![UnlockAsset { asset: remote_asset, target: origin.clone() }]); - let context = - XcmContext { origin: Some(origin.clone()), message_hash, topic: self.topic }; let (ticket, price) = validate_send::(locker, msg)?; - self.take_fee(price, FeeReason::RequestUnlock, context)?; + self.take_fee(price, FeeReason::RequestUnlock)?; reduce_ticket.enact()?; Config::XcmSender::deliver(ticket)?; Ok(()) }, ExchangeAsset { give, want, maximal } => { - let origin = self.origin.as_ref(); + let origin = self.origin(); let give = self.holding.saturating_take(give); let r = Config::AssetExchanger::exchange_asset(origin, give, &want, maximal); let completed = r.is_ok(); @@ -873,14 +844,14 @@ impl XcmExecutor { } } - fn take_fee(&mut self, fee: MultiAssets, reason: FeeReason, context: XcmContext) -> XcmResult { - if Config::FeeManager::is_waived(self.origin.as_ref(), reason) { + fn take_fee(&mut self, fee: MultiAssets, reason: FeeReason) -> XcmResult { + if Config::FeeManager::is_waived(self.origin(), reason) { return Ok(()) } let paid = if self.fees_mode.jit_withdraw { - let origin = self.origin.as_ref().ok_or(XcmError::BadOrigin)?; + let origin = self.origin().ok_or(XcmError::BadOrigin)?; for asset in fee.inner() { - Config::AssetTransactor::withdraw_asset(&asset, origin, Some(context.clone()))?; + Config::AssetTransactor::withdraw_asset(&asset, origin, Some(self.context.clone()))?; } fee } else { @@ -919,7 +890,7 @@ impl XcmExecutor { let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); let (ticket, fee) = validate_send::(destination, message)?; - if !Config::FeeManager::is_waived(self.origin.as_ref(), fee_reason) { + if !Config::FeeManager::is_waived(self.origin(), fee_reason) { let paid = self.holding.try_take(fee.into()).map_err(|_| XcmError::NotHoldingFees)?; Config::FeeManager::handle_fee(paid.into()); } From c554b976d02af39a0bafb2f77a98ebaaf8cd6a0e Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Sat, 5 Mar 2022 15:34:51 +0100 Subject: [PATCH 52/73] Use ref for XcmContext --- runtime/test-runtime/src/xcm_config.rs | 4 +- .../src/fungible/benchmarking.rs | 20 ++-- .../src/generic/benchmarking.rs | 58 +++++----- xcm/pallet-xcm-benchmarks/src/generic/mock.rs | 4 +- xcm/pallet-xcm-benchmarks/src/lib.rs | 2 +- xcm/pallet-xcm-benchmarks/src/mock.rs | 2 +- xcm/pallet-xcm/src/lib.rs | 10 +- xcm/xcm-builder/src/currency_adapter.rs | 10 +- xcm/xcm-builder/src/fungibles_adapter.rs | 26 ++--- xcm/xcm-builder/src/test_utils.rs | 8 +- xcm/xcm-builder/src/tests/mock.rs | 6 +- xcm/xcm-executor/src/lib.rs | 108 +++++++++--------- xcm/xcm-executor/src/traits/drop_assets.rs | 14 +-- xcm/xcm-executor/src/traits/on_response.rs | 12 +- xcm/xcm-executor/src/traits/transact_asset.rs | 78 ++++++------- xcm/xcm-simulator/example/src/parachain.rs | 3 +- 16 files changed, 180 insertions(+), 185 deletions(-) diff --git a/runtime/test-runtime/src/xcm_config.rs b/runtime/test-runtime/src/xcm_config.rs index 99e60a9e0e76..cd0ac5137bd0 100644 --- a/runtime/test-runtime/src/xcm_config.rs +++ b/runtime/test-runtime/src/xcm_config.rs @@ -54,14 +54,14 @@ pub type Barrier = AllowUnpaidExecutionFrom; pub struct DummyAssetTransactor; impl TransactAsset for DummyAssetTransactor { - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: XcmContext) -> XcmResult { + fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: &XcmContext) -> XcmResult { Ok(()) } fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: Option, + _maybe_context: Option<&XcmContext>, ) -> Result { let asset: MultiAsset = (Parent, 100_000).into(); Ok(asset.into()) diff --git a/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs index f983049c2209..110f4993c369 100644 --- a/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs @@ -47,7 +47,7 @@ benchmarks_instance_pallet! { >::deposit_asset( &asset, &sender_location, - XcmContext { + &XcmContext { origin: Some(sender_location.clone()), message_hash: [0; 32], topic: None, @@ -61,7 +61,7 @@ benchmarks_instance_pallet! { let instruction = Instruction::>::WithdrawAsset(vec![asset.clone()].into()); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // check one of the assets of origin. assert!(T::TransactAsset::balance(&sender_account).is_zero()); @@ -80,7 +80,7 @@ benchmarks_instance_pallet! { >::deposit_asset( &asset, &sender_location, - XcmContext { + &XcmContext { origin: Some(sender_location.clone()), message_hash: [0; 32], topic: None, @@ -92,7 +92,7 @@ benchmarks_instance_pallet! { let instruction = Instruction::TransferAsset { assets, beneficiary: dest_location }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(T::TransactAsset::balance(&sender_account).is_zero()); assert!(!T::TransactAsset::balance(&dest_account).is_zero()); @@ -107,7 +107,7 @@ benchmarks_instance_pallet! { >::deposit_asset( &asset, &sender_location, - XcmContext { + &XcmContext { origin: Some(sender_location.clone()), message_hash: [0; 32], topic: None, @@ -124,7 +124,7 @@ benchmarks_instance_pallet! { }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(T::TransactAsset::balance(&sender_account).is_zero()); assert!(!T::TransactAsset::balance(&dest_account).is_zero()); @@ -153,7 +153,7 @@ benchmarks_instance_pallet! { let instruction = Instruction::ReceiveTeleportedAsset(assets.clone()); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm).map_err(|_| { + executor.bench_process(xcm).map_err(|_| { BenchmarkError::Override( BenchmarkResult::from_weight(T::BlockWeights::get().max_block) ) @@ -182,7 +182,7 @@ benchmarks_instance_pallet! { }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // dest should have received some asset. assert!(!T::TransactAsset::balance(&dest_account).is_zero()) @@ -209,7 +209,7 @@ benchmarks_instance_pallet! { }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // dest should have received some asset. assert!(!T::TransactAsset::balance(&dest_account).is_zero()) @@ -234,7 +234,7 @@ benchmarks_instance_pallet! { }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { if let Some(checked_account) = T::CheckedAccount::get() { // teleport checked account should have received some asset. diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 056924f86fc4..ada7e85b3bb2 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -47,7 +47,7 @@ benchmarks! { let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // The completion of execution above is enough to validate this is completed. } @@ -69,7 +69,7 @@ benchmarks! { let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { } @@ -89,7 +89,7 @@ benchmarks! { let instruction = Instruction::ReserveAssetDeposited(multiassets.clone()); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm).map_err(|_| BenchmarkError::Skip)?; + executor.bench_process(xcm).map_err(|_| BenchmarkError::Skip)?; } verify { assert_eq!(executor.holding(), &multiassets.into()); } @@ -102,7 +102,7 @@ benchmarks! { let instruction = Instruction::QueryResponse { query_id, response, max_weight, querier }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // The assert above is enough to show this XCM succeeded } @@ -127,7 +127,7 @@ benchmarks! { let num_events = frame_system::Pallet::::events().len(); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // TODO make better assertion? #4426 let num_events2 = frame_system::Pallet::::events().len(); @@ -144,7 +144,7 @@ benchmarks! { let instruction = Instruction::>::RefundSurplus; let xcm = Xcm(vec![instruction]); } : { - let result = executor.execute(xcm)?; + let result = executor.bench_process(xcm)?; } verify { assert_eq!(executor.total_surplus(), &1337); assert_eq!(executor.total_refunded(), &1337); @@ -155,7 +155,7 @@ benchmarks! { let instruction = Instruction::>::SetErrorHandler(Xcm(vec![])); let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!(executor.error_handler(), &Xcm(vec![])); } @@ -166,7 +166,7 @@ benchmarks! { let instruction = Instruction::>::SetAppendix(appendix); let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!(executor.appendix(), &Xcm(vec![])); } @@ -177,7 +177,7 @@ benchmarks! { let instruction = Instruction::>::ClearError; let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(executor.error().is_none()) } @@ -188,7 +188,7 @@ benchmarks! { let instruction = Instruction::DescendOrigin(who.clone()); let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!( executor.origin(), @@ -204,7 +204,7 @@ benchmarks! { let instruction = Instruction::ClearOrigin; let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!(executor.origin(), &None); } @@ -221,7 +221,7 @@ benchmarks! { }); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // the execution succeeding is all we need to verify this xcm was successful } @@ -235,7 +235,7 @@ benchmarks! { ::AssetTrap::drop_assets( &origin, assets.clone().into(), - XcmContext { + &XcmContext { origin: Some(origin.clone()), message_hash: [0; 32], topic: None, @@ -248,7 +248,7 @@ benchmarks! { let instruction = Instruction::ClaimAsset { assets: assets.clone(), ticket }; let xcm = Xcm(vec![instruction]); } :{ - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(executor.holding().ensure_contains(&assets).is_ok()); } @@ -260,7 +260,7 @@ benchmarks! { // In order to access result in the verification below, it needs to be defined here. let mut _result = Ok(()); } : { - _result = executor.execute(xcm); + _result = executor.bench_process(xcm); } verify { assert!(matches!(_result, Err(ExecutorError { xcm_error: XcmError::Trap(10), @@ -277,7 +277,7 @@ benchmarks! { let instruction = Instruction::SubscribeVersion { query_id, max_response_weight }; let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(::SubscriptionService::is_subscribed(&origin)); } @@ -292,7 +292,7 @@ benchmarks! { &origin, query_id, max_response_weight, - XcmContext { + &XcmContext { origin: Some(origin.clone()), message_hash: [0; 32], topic: None, @@ -304,7 +304,7 @@ benchmarks! { let instruction = Instruction::UnsubscribeVersion; let xcm = Xcm(vec![instruction]); } : { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(!::SubscriptionService::is_subscribed(&origin)); } @@ -318,7 +318,7 @@ benchmarks! { let instruction = Instruction::InitiateReserveWithdraw { assets: assets_filter, reserve, xcm: Xcm(vec![]) }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // The execute completing successfully is as good as we can check. // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 @@ -334,7 +334,7 @@ benchmarks! { let instruction = Instruction::BurnAsset(assets.into()); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert!(executor.holding().is_empty()); } @@ -349,7 +349,7 @@ benchmarks! { let instruction = Instruction::ExpectAsset(assets.into()); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // `execute` completing successfully is as good as we can check. } @@ -362,7 +362,7 @@ benchmarks! { let xcm = Xcm(vec![instruction]); let mut _result = Ok(()); }: { - _result = executor.execute(xcm); + _result = executor.bench_process(xcm); } verify { assert!(matches!(_result, Err(ExecutorError { xcm_error: XcmError::ExpectationFalse, @@ -378,7 +378,7 @@ benchmarks! { let xcm = Xcm(vec![instruction]); let mut _result = Ok(()); }: { - _result = executor.execute(xcm); + _result = executor.bench_process(xcm); } verify { assert!(matches!(_result, Err(ExecutorError { xcm_error: XcmError::ExpectationFalse, @@ -398,7 +398,7 @@ benchmarks! { }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } @@ -415,7 +415,7 @@ benchmarks! { }; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // the execution succeeding is all we need to verify this xcm was successful } @@ -435,7 +435,7 @@ benchmarks! { }); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } @@ -447,7 +447,7 @@ benchmarks! { let instruction = Instruction::ClearTransactStatus; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!(executor.transact_status(), &MaybeErrorCode::Success); } @@ -458,7 +458,7 @@ benchmarks! { let instruction = Instruction::SetTopic([1; 32]); let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!(executor.topic(), &Some([1; 32])); } @@ -470,7 +470,7 @@ benchmarks! { let instruction = Instruction::ClearTopic; let xcm = Xcm(vec![instruction]); }: { - executor.execute(xcm)?; + executor.bench_process(xcm)?; } verify { assert_eq!(executor.topic(), &None); } diff --git a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 779c487896bd..52f6e4528c58 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -84,14 +84,14 @@ impl frame_system::Config for Test { /// The benchmarks in this pallet should never need an asset transactor to begin with. pub struct NoAssetTransactor; impl xcm_executor::traits::TransactAsset for NoAssetTransactor { - fn deposit_asset(_: &MultiAsset, _: &MultiLocation, _: XcmContext) -> Result<(), XcmError> { + fn deposit_asset(_: &MultiAsset, _: &MultiLocation, _: &XcmContext) -> Result<(), XcmError> { unreachable!(); } fn withdraw_asset( _: &MultiAsset, _: &MultiLocation, - _: Option, + _: Option<&XcmContext>, ) -> Result { unreachable!(); } diff --git a/xcm/pallet-xcm-benchmarks/src/lib.rs b/xcm/pallet-xcm-benchmarks/src/lib.rs index 8db2496e0b7d..4759199c7d63 100644 --- a/xcm/pallet-xcm-benchmarks/src/lib.rs +++ b/xcm/pallet-xcm-benchmarks/src/lib.rs @@ -89,7 +89,7 @@ pub fn asset_instance_from(x: u32) -> AssetInstance { } pub fn new_executor(origin: MultiLocation) -> ExecutorOf { - ExecutorOf::::new(origin) + ExecutorOf::::new(origin, [0; 32]) } /// Build a multi-location from an account id. diff --git a/xcm/pallet-xcm-benchmarks/src/mock.rs b/xcm/pallet-xcm-benchmarks/src/mock.rs index 219effd2532e..f05235c893f6 100644 --- a/xcm/pallet-xcm-benchmarks/src/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/mock.rs @@ -40,7 +40,7 @@ impl xcm_executor::traits::OnResponse for DevNull { _: Option<&MultiLocation>, _: Response, _: Weight, - _: XcmContext, + _: &XcmContext, ) -> Weight { 0 } diff --git a/xcm/pallet-xcm/src/lib.rs b/xcm/pallet-xcm/src/lib.rs index 8cd5decdef5e..4b997ea1b904 100644 --- a/xcm/pallet-xcm/src/lib.rs +++ b/xcm/pallet-xcm/src/lib.rs @@ -1712,7 +1712,7 @@ impl VersionChangeNotifier for Pallet { dest: &MultiLocation, query_id: QueryId, max_weight: u64, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { let versioned_dest = LatestVersionedMultiLocation(dest); let already = VersionNotifyTargets::::contains_key(XCM_VERSION, versioned_dest); @@ -1731,7 +1731,7 @@ impl VersionChangeNotifier for Pallet { /// Stop notifying `location` should the XCM change. This is a no-op if there was never a /// subscription. - fn stop(dest: &MultiLocation, _context: XcmContext) -> XcmResult { + fn stop(dest: &MultiLocation, _context: &XcmContext) -> XcmResult { VersionNotifyTargets::::remove(XCM_VERSION, LatestVersionedMultiLocation(dest)); Ok(()) } @@ -1744,7 +1744,7 @@ impl VersionChangeNotifier for Pallet { } impl DropAssets for Pallet { - fn drop_assets(origin: &MultiLocation, assets: Assets, _context: XcmContext) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, _context: &XcmContext) -> Weight { if assets.is_empty() { return 0 } @@ -1762,7 +1762,7 @@ impl ClaimAssets for Pallet { origin: &MultiLocation, ticket: &MultiLocation, assets: &MultiAssets, - _context: XcmContext, + _context: &XcmContext, ) -> bool { let mut versioned = VersionedMultiAssets::from(assets.clone()); match (ticket.parents, &ticket.interior) { @@ -1810,7 +1810,7 @@ impl OnResponse for Pallet { querier: Option<&MultiLocation>, response: Response, max_weight: Weight, - _context: XcmContext, + _context: &XcmContext, ) -> Weight { match (response, Queries::::get(query_id)) { ( diff --git a/xcm/xcm-builder/src/currency_adapter.rs b/xcm/xcm-builder/src/currency_adapter.rs index b2e9e56f7668..d85f371bd346 100644 --- a/xcm/xcm-builder/src/currency_adapter.rs +++ b/xcm/xcm-builder/src/currency_adapter.rs @@ -101,7 +101,7 @@ impl< > TransactAsset for CurrencyAdapter { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) -> Result { + fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) -> Result { log::trace!(target: "xcm::currency_adapter", "can_check_in origin: {:?}, what: {:?}", _origin, what); // Check we handle this asset. let amount: Currency::Balance = @@ -121,7 +121,7 @@ impl< Ok(()) } - fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) { + fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { log::trace!(target: "xcm::currency_adapter", "check_in origin: {:?}, what: {:?}", _origin, what); if let Some(amount) = Matcher::matches_fungible(what) { if let Some(checked_account) = CheckedAccount::get() { @@ -140,7 +140,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: XcmContext) { + fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { log::trace!(target: "xcm::currency_adapter", "check_out dest: {:?}, what: {:?}", _dest, what); if let Some(amount) = Matcher::matches_fungible(what) { if let Some(checked_account) = CheckedAccount::get() { @@ -149,7 +149,7 @@ impl< } } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation, _context: XcmContext) -> Result { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, _context: &XcmContext) -> Result { log::trace!(target: "xcm::currency_adapter", "deposit_asset what: {:?}, who: {:?}", what, who); // Check we handle this asset. let amount: u128 = @@ -165,7 +165,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - _context: Option, + _maybe_context: Option<&XcmContext>, ) -> result::Result { log::trace!(target: "xcm::currency_adapter", "withdraw_asset what: {:?}, who: {:?}", what, who); // Check we handle this asset. diff --git a/xcm/xcm-builder/src/fungibles_adapter.rs b/xcm/xcm-builder/src/fungibles_adapter.rs index 689c66de1b8d..b0b8e5b8162c 100644 --- a/xcm/xcm-builder/src/fungibles_adapter.rs +++ b/xcm/xcm-builder/src/fungibles_adapter.rs @@ -122,7 +122,7 @@ impl< what: &MultiAsset, from: &MultiLocation, to: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", @@ -166,7 +166,7 @@ impl< CheckingAccount, > { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) -> Result { + fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) -> Result { log::trace!( target: "xcm::fungibles_adapter", "can_check_in origin: {:?}, what: {:?}", @@ -184,7 +184,7 @@ impl< Ok(()) } - fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: XcmContext) { + fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { log::trace!( target: "xcm::fungibles_adapter", "check_in origin: {:?}, what: {:?}", @@ -202,7 +202,7 @@ impl< } } - fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: XcmContext) { + fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { log::trace!( target: "xcm::fungibles_adapter", "check_out dest: {:?}, what: {:?}", @@ -217,7 +217,7 @@ impl< } } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation, _context: XcmContext) -> Result { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, _context: &XcmContext) -> Result { log::trace!( target: "xcm::fungibles_adapter", "deposit_asset what: {:?}, who: {:?}", @@ -234,7 +234,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - _context: Option, + _maybe_context: Option<&XcmContext>, ) -> result::Result { log::trace!( target: "xcm::fungibles_adapter", @@ -269,7 +269,7 @@ impl< > TransactAsset for FungiblesAdapter { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) -> Result { + fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> Result { FungiblesMutateAdapter::< Assets, Matcher, @@ -280,7 +280,7 @@ impl< >::can_check_in(origin, what, context) } - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) { + fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { FungiblesMutateAdapter::< Assets, Matcher, @@ -291,7 +291,7 @@ impl< >::check_in(origin, what, context) } - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: XcmContext) { + fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { FungiblesMutateAdapter::< Assets, Matcher, @@ -302,7 +302,7 @@ impl< >::check_out(dest, what, context) } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: XcmContext) -> Result { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: &XcmContext) -> Result { FungiblesMutateAdapter::< Assets, Matcher, @@ -316,7 +316,7 @@ impl< fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - context: Option, + maybe_context: Option<&XcmContext>, ) -> result::Result { FungiblesMutateAdapter::< Assets, @@ -325,14 +325,14 @@ impl< AccountId, CheckAsset, CheckingAccount, - >::withdraw_asset(what, who, context) + >::withdraw_asset(what, who, maybe_context) } fn transfer_asset( what: &MultiAsset, from: &MultiLocation, to: &MultiLocation, - context: XcmContext, + context: &XcmContext, ) -> result::Result { FungiblesTransferAdapter::::transfer_asset( what, from, to, context, diff --git a/xcm/xcm-builder/src/test_utils.rs b/xcm/xcm-builder/src/test_utils.rs index ef593b38413f..658adddc3c5e 100644 --- a/xcm/xcm-builder/src/test_utils.rs +++ b/xcm/xcm-builder/src/test_utils.rs @@ -41,14 +41,14 @@ impl VersionChangeNotifier for TestSubscriptionService { location: &MultiLocation, query_id: QueryId, max_weight: u64, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { let mut r = SubscriptionRequests::get(); r.push((location.clone(), Some((query_id, max_weight)))); SubscriptionRequests::set(r); Ok(()) } - fn stop(location: &MultiLocation, _context: XcmContext) -> XcmResult { + fn stop(location: &MultiLocation, _context: &XcmContext) -> XcmResult { let mut r = SubscriptionRequests::get(); r.retain(|(l, _q)| l != location); r.push((location.clone(), None)); @@ -68,7 +68,7 @@ parameter_types! { pub struct TestAssetTrap; impl DropAssets for TestAssetTrap { - fn drop_assets(origin: &MultiLocation, assets: Assets, _context: XcmContext) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, _context: &XcmContext) -> Weight { let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get(); t.push((origin.clone(), assets.into())); TrappedAssets::set(t); @@ -81,7 +81,7 @@ impl ClaimAssets for TestAssetTrap { origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets, - _context: XcmContext, + _context: &XcmContext, ) -> bool { let mut t: Vec<(MultiLocation, MultiAssets)> = TrappedAssets::get(); if let (0, X1(GeneralIndex(i))) = (ticket.parents, &ticket.interior) { diff --git a/xcm/xcm-builder/src/tests/mock.rs b/xcm/xcm-builder/src/tests/mock.rs index b720639c54a4..652eb7b9f9c6 100644 --- a/xcm/xcm-builder/src/tests/mock.rs +++ b/xcm/xcm-builder/src/tests/mock.rs @@ -211,7 +211,7 @@ impl TransactAsset for TestAssetTransactor { fn deposit_asset( what: &MultiAsset, who: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> Result<(), XcmError> { add_asset(who.clone(), what.clone()); Ok(()) @@ -220,7 +220,7 @@ impl TransactAsset for TestAssetTransactor { fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - _context: Option, + _maybe_context: Option<&XcmContext>, ) -> Result { ASSETS.with(|a| { a.borrow_mut() @@ -345,7 +345,7 @@ impl OnResponse for TestResponseHandler { _querier: Option<&MultiLocation>, response: xcm::latest::Response, _max_weight: Weight, - _context: XcmContext, + _context: &XcmContext, ) -> Weight { QUERIES.with(|q| { q.borrow_mut().entry(query_id).and_modify(|v| { diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 6be88ba0d927..67b210612f23 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -284,6 +284,14 @@ impl XcmExecutor { } } + #[cfg(feature = "runtime-benchmarks")] + pub fn bench_process( + &mut self, + xcm: Xcm, + ) -> Result<(), ExecutorError> { + self.process(xcm) + } + fn process( &mut self, xcm: Xcm, @@ -291,7 +299,7 @@ impl XcmExecutor { log::trace!( target: "xcm::process", "origin: {:?}, total_surplus/refunded: {:?}/{:?}, error_handler_weight: {:?}", - self.origin(), + self.origin_ref(), self.total_surplus, self.total_refunded, self.error_handler_weight, @@ -323,14 +331,13 @@ impl XcmExecutor { let mut weight_used = xcm_weight.saturating_sub(self.total_surplus); if !self.holding.is_empty() { - let context = self.context.clone(); log::trace!( target: "xcm::execute_xcm_in_credit", "Trapping assets in holding register: {:?}, context: {:?} (original_origin: {:?})", - self.holding, context, self.original_origin, + self.holding, self.context, self.original_origin, ); let trap_weight = - Config::AssetTrap::drop_assets(&self.original_origin, self.holding, context); + Config::AssetTrap::drop_assets(&self.original_origin, self.holding, &self.context); weight_used.saturating_accrue(trap_weight); }; @@ -345,7 +352,7 @@ impl XcmExecutor { } } - fn origin(&self) -> Option<&MultiLocation> { + fn origin_ref(&self) -> Option<&MultiLocation> { self.context.origin.as_ref() } @@ -361,7 +368,7 @@ impl XcmExecutor { reason: FeeReason, ) -> Result { let (ticket, fee) = validate_send::(dest, msg)?; - if !Config::FeeManager::is_waived(self.origin(), reason) { + if !Config::FeeManager::is_waived(self.origin_ref(), reason) { let paid = self.holding.try_take(fee.into()).map_err(|_| XcmError::NotHoldingFees)?; Config::FeeManager::handle_fee(paid.into()); } @@ -429,17 +436,16 @@ impl XcmExecutor { match instr { WithdrawAsset(assets) => { // Take `assets` from the origin account (on-chain) and place in holding. - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.into_inner().into_iter() { - let context = Some(self.context.clone()); - Config::AssetTransactor::withdraw_asset(&asset, &origin, context)?; + Config::AssetTransactor::withdraw_asset(&asset, &origin, Some(&self.context))?; self.subsume_asset(asset)?; } Ok(()) }, ReserveAssetDeposited(assets) => { // check whether we trust origin to be our reserve location for this asset. - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); for asset in assets.into_inner().into_iter() { // Must ensure that we recognise the asset as being managed by the origin. ensure!( @@ -452,30 +458,27 @@ impl XcmExecutor { }, TransferAsset { assets, beneficiary } => { // Take `assets` from the origin account (on-chain) and place into dest account. - let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in assets.inner() { - let context = self.context.clone(); - Config::AssetTransactor::beam_asset(&asset, origin, &beneficiary, context)?; + Config::AssetTransactor::beam_asset(&asset, origin, &beneficiary, &self.context)?; } Ok(()) }, TransferReserveAsset { mut assets, dest, xcm } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; // Take `assets` from the origin account (on-chain) and place into dest account. for asset in assets.inner() { - let context = self.context.clone(); - Config::AssetTransactor::beam_asset(asset, origin, &dest, context)?; + Config::AssetTransactor::beam_asset(asset, origin, &dest, &self.context)?; } - let context = Config::LocationInverter::universal_location().into(); - assets.reanchor(&dest, &context).map_err(|()| XcmError::MultiLocationFull)?; + let reanchor_context = Config::LocationInverter::universal_location().into(); + assets.reanchor(&dest, &reanchor_context).map_err(|()| XcmError::MultiLocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); self.send(dest, Xcm(message), FeeReason::TransferReserveAsset)?; Ok(()) }, ReceiveTeleportedAsset(assets) => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); - let context = self.context.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); // check whether we trust origin to teleport this asset to us via config trait. for asset in assets.inner() { // We only trust the origin to send us assets that they identify as their @@ -487,17 +490,17 @@ impl XcmExecutor { // We should check that the asset can actually be teleported in (for this to be in error, there // would need to be an accounting violation by one of the trusted chains, so it's unlikely, but we // don't want to punish a possibly innocent chain/user). - Config::AssetTransactor::can_check_in(&origin, asset, context.clone())?; + Config::AssetTransactor::can_check_in(&origin, asset, &self.context)?; } for asset in assets.into_inner().into_iter() { - Config::AssetTransactor::check_in(&origin, &asset, context.clone()); + Config::AssetTransactor::check_in(&origin, &asset, &self.context); self.subsume_asset(asset)?; } Ok(()) }, Transact { origin_kind, require_weight_at_most, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| XcmError::FailedToDecode)?; @@ -529,15 +532,14 @@ impl XcmExecutor { Ok(()) }, QueryResponse { query_id, response, max_weight, querier } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?; - let context = self.context.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; Config::ResponseHandler::on_response( origin, query_id, querier.as_ref(), response, max_weight, - context, + &self.context, ); Ok(()) }, @@ -566,15 +568,14 @@ impl XcmExecutor { DepositAsset { assets, beneficiary } => { let deposited = self.holding.saturating_take(assets); for asset in deposited.into_assets_iter() { - Config::AssetTransactor::deposit_asset(&asset, &beneficiary, self.context.clone())?; + Config::AssetTransactor::deposit_asset(&asset, &beneficiary, &self.context)?; } Ok(()) }, DepositReserveAsset { assets, dest, xcm } => { let deposited = self.holding.saturating_take(assets); for asset in deposited.assets_iter() { - let context = self.context.clone(); - Config::AssetTransactor::deposit_asset(&asset, &dest, context)?; + Config::AssetTransactor::deposit_asset(&asset, &dest, &self.context)?; } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot // be reanchored because we have already called `deposit_asset` on all assets. @@ -601,8 +602,7 @@ impl XcmExecutor { // We must do this first in order to resolve wildcards. let assets = self.holding.saturating_take(assets); for asset in assets.assets_iter() { - let context = self.context.clone(); - Config::AssetTransactor::check_out(&dest, &asset, context); + Config::AssetTransactor::check_out(&dest, &asset, &self.context); } // Note that we pass `None` as `maybe_failed_bin` and drop any assets which cannot // be reanchored because we have already checked all assets out. @@ -661,9 +661,8 @@ impl XcmExecutor { Ok(()) }, ClaimAsset { assets, ticket } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?; - let context = self.context.clone(); - let ok = Config::AssetClaims::claim_assets(origin, &ticket, &assets, context); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; + let ok = Config::AssetClaims::claim_assets(origin, &ticket, &assets, &self.context); ensure!(ok, XcmError::UnknownClaim); for asset in assets.into_inner().into_iter() { self.subsume_asset(asset)?; @@ -672,18 +671,16 @@ impl XcmExecutor { }, Trap(code) => Err(XcmError::Trap(code)), SubscribeVersion { query_id, max_response_weight } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; // We don't allow derivative origins to subscribe since it would otherwise pose a // DoS risk. ensure!(&self.original_origin == origin, XcmError::BadOrigin); - let context = self.context.clone(); - Config::SubscriptionService::start(origin, query_id, max_response_weight, context) + Config::SubscriptionService::start(origin, query_id, max_response_weight, &self.context) }, UnsubscribeVersion => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; ensure!(&self.original_origin == origin, XcmError::BadOrigin); - let context = self.context.clone(); - Config::SubscriptionService::stop(origin, context) + Config::SubscriptionService::stop(origin, &self.context) }, BurnAsset(assets) => { self.holding.saturating_take(assets.into()); @@ -751,7 +748,7 @@ impl XcmExecutor { UniversalOrigin(new_global) => { let universal_location = Config::LocationInverter::universal_location(); ensure!(universal_location.first() != Some(&new_global), XcmError::InvalidLocation); - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); let origin_xform = (origin, new_global); let ok = Config::UniversalAliases::contains(&origin_xform); ensure!(ok, XcmError::InvalidLocation); @@ -761,7 +758,7 @@ impl XcmExecutor { Ok(()) }, ExportMessage { network, destination, xcm } => { - let hash = (self.origin(), &destination).using_encoded(blake2_128); + let hash = (self.origin_ref(), &destination).using_encoded(blake2_128); let channel = u32::decode(&mut hash.as_ref()).unwrap_or(0); // Hash identifies the lane on the exporter which we use. We use the pairwise // combination of the origin and destination to ensure origin/destination pairs will @@ -773,7 +770,7 @@ impl XcmExecutor { Ok(()) }, LockAsset { asset, unlocker } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); let remote_asset = Self::try_reanchor(asset.clone(), &unlocker)?; let lock_ticket = Config::AssetLocker::prepare_lock(unlocker.clone(), asset, origin.clone())?; @@ -786,17 +783,17 @@ impl XcmExecutor { Ok(()) }, UnlockAsset { asset, target } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); Config::AssetLocker::prepare_unlock(origin.clone(), asset, target)?.enact()?; Ok(()) }, NoteUnlockable { asset, owner } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); Config::AssetLocker::note_unlockable(origin, asset, owner)?; Ok(()) }, RequestUnlock { asset, locker } => { - let origin = self.origin().ok_or(XcmError::BadOrigin)?.clone(); + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?.clone(); let remote_asset = Self::try_reanchor(asset.clone(), &locker)?; let reduce_ticket = Config::AssetLocker::prepare_reduce_unlockable( locker.clone(), @@ -812,9 +809,8 @@ impl XcmExecutor { Ok(()) }, ExchangeAsset { give, want, maximal } => { - let origin = self.origin(); let give = self.holding.saturating_take(give); - let r = Config::AssetExchanger::exchange_asset(origin, give, &want, maximal); + let r = Config::AssetExchanger::exchange_asset(self.origin_ref(), give, &want, maximal); let completed = r.is_ok(); let received = r.unwrap_or_else(|a| a); for asset in received.into_assets_iter() { @@ -845,13 +841,13 @@ impl XcmExecutor { } fn take_fee(&mut self, fee: MultiAssets, reason: FeeReason) -> XcmResult { - if Config::FeeManager::is_waived(self.origin(), reason) { + if Config::FeeManager::is_waived(self.origin_ref(), reason) { return Ok(()) } let paid = if self.fees_mode.jit_withdraw { - let origin = self.origin().ok_or(XcmError::BadOrigin)?; + let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in fee.inner() { - Config::AssetTransactor::withdraw_asset(&asset, origin, Some(self.context.clone()))?; + Config::AssetTransactor::withdraw_asset(&asset, origin, Some(&self.context))?; } fee } else { @@ -890,7 +886,7 @@ impl XcmExecutor { let instruction = QueryResponse { query_id, response, max_weight, querier }; let message = Xcm(vec![instruction]); let (ticket, fee) = validate_send::(destination, message)?; - if !Config::FeeManager::is_waived(self.origin(), fee_reason) { + if !Config::FeeManager::is_waived(self.origin_ref(), fee_reason) { let paid = self.holding.try_take(fee.into()).map_err(|_| XcmError::NotHoldingFees)?; Config::FeeManager::handle_fee(paid.into()); } @@ -901,8 +897,8 @@ impl XcmExecutor { asset: MultiAsset, destination: &MultiLocation, ) -> Result { - let context = Config::LocationInverter::universal_location().into(); - asset.reanchored(&destination, &context).map_err(|()| XcmError::ReanchorFailed) + let reanchor_context = Config::LocationInverter::universal_location().into(); + asset.reanchored(&destination, &reanchor_context).map_err(|()| XcmError::ReanchorFailed) } /// NOTE: Any assets which were unable to be reanchored are introduced into `failed_bin`. @@ -911,8 +907,8 @@ impl XcmExecutor { dest: &MultiLocation, maybe_failed_bin: Option<&mut Assets>, ) -> MultiAssets { - let context = Config::LocationInverter::universal_location().into(); - assets.reanchor(dest, &context, maybe_failed_bin); + let reanchor_context = Config::LocationInverter::universal_location().into(); + assets.reanchor(dest, &reanchor_context, maybe_failed_bin); assets.into_assets_iter().collect::>().into() } } diff --git a/xcm/xcm-executor/src/traits/drop_assets.rs b/xcm/xcm-executor/src/traits/drop_assets.rs index ca4fd5d8fe3e..45eefc9fba4e 100644 --- a/xcm/xcm-executor/src/traits/drop_assets.rs +++ b/xcm/xcm-executor/src/traits/drop_assets.rs @@ -22,10 +22,10 @@ use xcm::latest::{MultiAssets, MultiLocation, XcmContext}; /// Define a handler for when some non-empty `Assets` value should be dropped. pub trait DropAssets { /// Handler for receiving dropped assets. Returns the weight consumed by this operation. - fn drop_assets(origin: &MultiLocation, assets: Assets, context: XcmContext) -> Weight; + fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight; } impl DropAssets for () { - fn drop_assets(_origin: &MultiLocation, _assets: Assets, _context: XcmContext) -> Weight { + fn drop_assets(_origin: &MultiLocation, _assets: Assets, _context: &XcmContext) -> Weight { 0 } } @@ -35,7 +35,7 @@ impl DropAssets for () { pub struct FilterAssets(PhantomData<(D, A)>); impl> DropAssets for FilterAssets { - fn drop_assets(origin: &MultiLocation, assets: Assets, context: XcmContext) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight { if A::contains(&assets) { D::drop_assets(origin, assets, context) } else { @@ -50,7 +50,7 @@ impl> DropAssets for FilterAssets { pub struct FilterOrigin(PhantomData<(D, O)>); impl> DropAssets for FilterOrigin { - fn drop_assets(origin: &MultiLocation, assets: Assets, context: XcmContext) -> Weight { + fn drop_assets(origin: &MultiLocation, assets: Assets, context: &XcmContext) -> Weight { if O::contains(origin) { D::drop_assets(origin, assets, context) } else { @@ -67,7 +67,7 @@ pub trait ClaimAssets { origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets, - context: XcmContext, + context: &XcmContext, ) -> bool; } @@ -77,10 +77,10 @@ impl ClaimAssets for Tuple { origin: &MultiLocation, ticket: &MultiLocation, what: &MultiAssets, - context: XcmContext, + context: &XcmContext, ) -> bool { for_tuples!( #( - if Tuple::claim_assets(origin, ticket, what, context.clone()) { + if Tuple::claim_assets(origin, ticket, what, context) { return true; } )* ); diff --git a/xcm/xcm-executor/src/traits/on_response.rs b/xcm/xcm-executor/src/traits/on_response.rs index e2d3771233a2..2720dfd6ce5a 100644 --- a/xcm/xcm-executor/src/traits/on_response.rs +++ b/xcm/xcm-executor/src/traits/on_response.rs @@ -36,7 +36,7 @@ pub trait OnResponse { querier: Option<&MultiLocation>, response: Response, max_weight: Weight, - context: XcmContext, + context: &XcmContext, ) -> Weight; } impl OnResponse for () { @@ -53,7 +53,7 @@ impl OnResponse for () { _querier: Option<&MultiLocation>, _response: Response, _max_weight: Weight, - _context: XcmContext, + _context: &XcmContext, ) -> Weight { 0 } @@ -73,22 +73,22 @@ pub trait VersionChangeNotifier { location: &MultiLocation, query_id: QueryId, max_weight: u64, - context: XcmContext, + context: &XcmContext, ) -> XcmResult; /// Stop notifying `location` should the XCM change. Returns an error if there is no existing /// notification set up. - fn stop(location: &MultiLocation, context: XcmContext) -> XcmResult; + fn stop(location: &MultiLocation, context: &XcmContext) -> XcmResult; /// Return true if a location is subscribed to XCM version changes. fn is_subscribed(location: &MultiLocation) -> bool; } impl VersionChangeNotifier for () { - fn start(_: &MultiLocation, _: QueryId, _: u64, _: XcmContext) -> XcmResult { + fn start(_: &MultiLocation, _: QueryId, _: u64, _: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } - fn stop(_: &MultiLocation, _: XcmContext) -> XcmResult { + fn stop(_: &MultiLocation, _: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } fn is_subscribed(_: &MultiLocation) -> bool { diff --git a/xcm/xcm-executor/src/traits/transact_asset.rs b/xcm/xcm-executor/src/traits/transact_asset.rs index f18ef0d296ff..94aff222d162 100644 --- a/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/xcm/xcm-executor/src/traits/transact_asset.rs @@ -32,7 +32,7 @@ pub trait TransactAsset { fn can_check_in( _origin: &MultiLocation, _what: &MultiAsset, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Err(XcmError::Unimplemented) } @@ -50,7 +50,7 @@ pub trait TransactAsset { /// /// When composed as a tuple, all type-items are called. It is up to the implementer that there exists no /// value for `_what` which can cause side-effects for more than one of the type-items. - fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: XcmContext) {} + fn check_in(_origin: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {} /// An asset has been teleported out to the given destination. This should do whatever housekeeping is needed. /// @@ -62,12 +62,12 @@ pub trait TransactAsset { /// /// When composed as a tuple, all type-items are called. It is up to the implementer that there exists no /// value for `_what` which can cause side-effects for more than one of the type-items. - fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: XcmContext) {} + fn check_out(_dest: &MultiLocation, _what: &MultiAsset, _context: &XcmContext) {} /// Deposit the `what` asset into the account of `who`. /// /// Implementations should return `XcmError::FailedToTransactAsset` if deposit failed. - fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: XcmContext) -> XcmResult { + fn deposit_asset(_what: &MultiAsset, _who: &MultiLocation, _context: &XcmContext) -> XcmResult { Err(XcmError::Unimplemented) } @@ -82,7 +82,7 @@ pub trait TransactAsset { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: Option, + _maybe_context: Option<&XcmContext>, ) -> Result { Err(XcmError::Unimplemented) } @@ -94,7 +94,7 @@ pub trait TransactAsset { _asset: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> Result { Err(XcmError::Unimplemented) } @@ -106,11 +106,11 @@ pub trait TransactAsset { asset: &MultiAsset, from: &MultiLocation, to: &MultiLocation, - context: XcmContext, + context: &XcmContext, ) -> Result { - match Self::transfer_asset(asset, from, to, context.clone()) { + match Self::transfer_asset(asset, from, to, context) { Err(XcmError::Unimplemented) => { - let assets = Self::withdraw_asset(asset, from, Some(context.clone()))?; + let assets = Self::withdraw_asset(asset, from, Some(context))?; // Not a very forgiving attitude; once we implement roll-backs then it'll be nicer. Self::deposit_asset(asset, to, context)?; Ok(assets) @@ -122,9 +122,9 @@ pub trait TransactAsset { #[impl_trait_for_tuples::impl_for_tuples(30)] impl TransactAsset for Tuple { - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) -> XcmResult { + fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { for_tuples!( #( - match Tuple::can_check_in(origin, what, context.clone()) { + match Tuple::can_check_in(origin, what, context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } @@ -139,21 +139,21 @@ impl TransactAsset for Tuple { Err(XcmError::AssetNotFound) } - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: XcmContext) { + fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { for_tuples!( #( - Tuple::check_in(origin, what, context.clone()); + Tuple::check_in(origin, what, context); )* ); } - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: XcmContext) { + fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { for_tuples!( #( - Tuple::check_out(dest, what, context.clone()); + Tuple::check_out(dest, what, context); )* ); } - fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: XcmContext) -> XcmResult { + fn deposit_asset(what: &MultiAsset, who: &MultiLocation, context: &XcmContext) -> XcmResult { for_tuples!( #( - match Tuple::deposit_asset(what, who, context.clone()) { + match Tuple::deposit_asset(what, who, context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } @@ -171,20 +171,20 @@ impl TransactAsset for Tuple { fn withdraw_asset( what: &MultiAsset, who: &MultiLocation, - context: Option, + maybe_context: Option<&XcmContext>, ) -> Result { for_tuples!( #( - match Tuple::withdraw_asset(what, who, context.clone()) { + match Tuple::withdraw_asset(what, who, maybe_context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } )* ); log::trace!( target: "xcm::TransactAsset::withdraw_asset", - "did not withdraw asset: what: {:?}, who: {:?}, context: {:?}", + "did not withdraw asset: what: {:?}, who: {:?}, maybe_context: {:?}", what, who, - context, + maybe_context, ); Err(XcmError::AssetNotFound) } @@ -193,10 +193,10 @@ impl TransactAsset for Tuple { what: &MultiAsset, from: &MultiLocation, to: &MultiLocation, - context: XcmContext, + context: &XcmContext, ) -> Result { for_tuples!( #( - match Tuple::transfer_asset(what, from, to, context.clone()) { + match Tuple::transfer_asset(what, from, to, context) { Err(XcmError::AssetNotFound) | Err(XcmError::Unimplemented) => (), r => return r, } @@ -226,7 +226,7 @@ mod tests { fn can_check_in( _origin: &MultiLocation, _what: &MultiAsset, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Err(XcmError::AssetNotFound) } @@ -234,7 +234,7 @@ mod tests { fn deposit_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Err(XcmError::AssetNotFound) } @@ -242,7 +242,7 @@ mod tests { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: Option, + _context: Option<&XcmContext>, ) -> Result { Err(XcmError::AssetNotFound) } @@ -251,7 +251,7 @@ mod tests { _what: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> Result { Err(XcmError::AssetNotFound) } @@ -262,7 +262,7 @@ mod tests { fn can_check_in( _origin: &MultiLocation, _what: &MultiAsset, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Err(XcmError::Overflow) } @@ -270,7 +270,7 @@ mod tests { fn deposit_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Err(XcmError::Overflow) } @@ -278,7 +278,7 @@ mod tests { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: Option, + _context: Option<&XcmContext>, ) -> Result { Err(XcmError::Overflow) } @@ -287,7 +287,7 @@ mod tests { _what: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> Result { Err(XcmError::Overflow) } @@ -298,7 +298,7 @@ mod tests { fn can_check_in( _origin: &MultiLocation, _what: &MultiAsset, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Ok(()) } @@ -306,7 +306,7 @@ mod tests { fn deposit_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> XcmResult { Ok(()) } @@ -314,7 +314,7 @@ mod tests { fn withdraw_asset( _what: &MultiAsset, _who: &MultiLocation, - _context: Option, + _context: Option<&XcmContext>, ) -> Result { Ok(Assets::default()) } @@ -323,7 +323,7 @@ mod tests { _what: &MultiAsset, _from: &MultiLocation, _to: &MultiLocation, - _context: XcmContext, + _context: &XcmContext, ) -> Result { Ok(Assets::default()) } @@ -338,7 +338,7 @@ mod tests { MultiTransactor::deposit_asset( &(Here, 1).into(), &Here.into(), - XcmContext::with_message_hash([0; 32]), + &XcmContext::with_message_hash([0; 32]), ), Err(XcmError::AssetNotFound) ); @@ -352,7 +352,7 @@ mod tests { MultiTransactor::deposit_asset( &(Here, 1).into(), &Here.into(), - XcmContext::with_message_hash([0; 32]), + &XcmContext::with_message_hash([0; 32]), ), Ok(()) ); @@ -366,7 +366,7 @@ mod tests { MultiTransactor::deposit_asset( &(Here, 1).into(), &Here.into(), - XcmContext::with_message_hash([0; 32]), + &XcmContext::with_message_hash([0; 32]), ), Err(XcmError::Overflow) ); @@ -380,7 +380,7 @@ mod tests { MultiTransactor::deposit_asset( &(Here, 1).into(), &Here.into(), - XcmContext::with_message_hash([0; 32]), + &XcmContext::with_message_hash([0; 32]), ), Ok(()), ); diff --git a/xcm/xcm-simulator/example/src/parachain.rs b/xcm/xcm-simulator/example/src/parachain.rs index bb8f1968e35f..573075845119 100644 --- a/xcm/xcm-simulator/example/src/parachain.rs +++ b/xcm/xcm-simulator/example/src/parachain.rs @@ -282,12 +282,11 @@ pub mod mock_msg_queue { Self::deposit_event(Event::InvalidFormat(id)); }, Ok(versioned) => { - let hash = versioned.using_encoded(sp_io::hashing::blake2_256); match Xcm::try_from(versioned) { Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), Ok(x) => { let outcome = - T::XcmExecutor::execute_xcm(Parent, x.clone(), hash, limit); + T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); >::append(x); Self::deposit_event(Event::ExecutedDownward(id, outcome)); }, From 292f8d49d36a38b4e12dc4eed22da60e9d83a760 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Sat, 5 Mar 2022 15:35:37 +0100 Subject: [PATCH 53/73] Formatting --- xcm/xcm-executor/src/lib.rs | 42 ++++++++++++---------- xcm/xcm-simulator/example/src/parachain.rs | 17 ++++----- 2 files changed, 31 insertions(+), 28 deletions(-) diff --git a/xcm/xcm-executor/src/lib.rs b/xcm/xcm-executor/src/lib.rs index 67b210612f23..fc2a4299fd8d 100644 --- a/xcm/xcm-executor/src/lib.rs +++ b/xcm/xcm-executor/src/lib.rs @@ -262,7 +262,7 @@ impl From for frame_benchmarking::BenchmarkError { } impl XcmExecutor { - pub fn new(origin: impl Into, message_hash: XcmHash, ) -> Self { + pub fn new(origin: impl Into, message_hash: XcmHash) -> Self { let origin = origin.into(); Self { holding: Assets::new(), @@ -285,17 +285,11 @@ impl XcmExecutor { } #[cfg(feature = "runtime-benchmarks")] - pub fn bench_process( - &mut self, - xcm: Xcm, - ) -> Result<(), ExecutorError> { + pub fn bench_process(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { self.process(xcm) } - fn process( - &mut self, - xcm: Xcm, - ) -> Result<(), ExecutorError> { + fn process(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { log::trace!( target: "xcm::process", "origin: {:?}, total_surplus/refunded: {:?}/{:?}, error_handler_weight: {:?}", @@ -429,10 +423,7 @@ impl XcmExecutor { } /// Process a single XCM instruction, mutating the state of the XCM virtual machine. - fn process_instruction( - &mut self, - instr: Instruction, - ) -> Result<(), XcmError> { + fn process_instruction(&mut self, instr: Instruction) -> Result<(), XcmError> { match instr { WithdrawAsset(assets) => { // Take `assets` from the origin account (on-chain) and place in holding. @@ -460,7 +451,12 @@ impl XcmExecutor { // Take `assets` from the origin account (on-chain) and place into dest account. let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; for asset in assets.inner() { - Config::AssetTransactor::beam_asset(&asset, origin, &beneficiary, &self.context)?; + Config::AssetTransactor::beam_asset( + &asset, + origin, + &beneficiary, + &self.context, + )?; } Ok(()) }, @@ -471,7 +467,9 @@ impl XcmExecutor { Config::AssetTransactor::beam_asset(asset, origin, &dest, &self.context)?; } let reanchor_context = Config::LocationInverter::universal_location().into(); - assets.reanchor(&dest, &reanchor_context).map_err(|()| XcmError::MultiLocationFull)?; + assets + .reanchor(&dest, &reanchor_context) + .map_err(|()| XcmError::MultiLocationFull)?; let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; message.extend(xcm.0.into_iter()); self.send(dest, Xcm(message), FeeReason::TransferReserveAsset)?; @@ -675,7 +673,12 @@ impl XcmExecutor { // We don't allow derivative origins to subscribe since it would otherwise pose a // DoS risk. ensure!(&self.original_origin == origin, XcmError::BadOrigin); - Config::SubscriptionService::start(origin, query_id, max_response_weight, &self.context) + Config::SubscriptionService::start( + origin, + query_id, + max_response_weight, + &self.context, + ) }, UnsubscribeVersion => { let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; @@ -810,7 +813,8 @@ impl XcmExecutor { }, ExchangeAsset { give, want, maximal } => { let give = self.holding.saturating_take(give); - let r = Config::AssetExchanger::exchange_asset(self.origin_ref(), give, &want, maximal); + let r = + Config::AssetExchanger::exchange_asset(self.origin_ref(), give, &want, maximal); let completed = r.is_ok(); let received = r.unwrap_or_else(|a| a); for asset in received.into_assets_iter() { @@ -898,7 +902,9 @@ impl XcmExecutor { destination: &MultiLocation, ) -> Result { let reanchor_context = Config::LocationInverter::universal_location().into(); - asset.reanchored(&destination, &reanchor_context).map_err(|()| XcmError::ReanchorFailed) + asset + .reanchored(&destination, &reanchor_context) + .map_err(|()| XcmError::ReanchorFailed) } /// NOTE: Any assets which were unable to be reanchored are introduced into `failed_bin`. diff --git a/xcm/xcm-simulator/example/src/parachain.rs b/xcm/xcm-simulator/example/src/parachain.rs index 573075845119..3b7529a9bf29 100644 --- a/xcm/xcm-simulator/example/src/parachain.rs +++ b/xcm/xcm-simulator/example/src/parachain.rs @@ -281,16 +281,13 @@ pub mod mock_msg_queue { Err(_) => { Self::deposit_event(Event::InvalidFormat(id)); }, - Ok(versioned) => { - match Xcm::try_from(versioned) { - Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), - Ok(x) => { - let outcome = - T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); - >::append(x); - Self::deposit_event(Event::ExecutedDownward(id, outcome)); - }, - } + Ok(versioned) => match Xcm::try_from(versioned) { + Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), + Ok(x) => { + let outcome = T::XcmExecutor::execute_xcm(Parent, x.clone(), id, limit); + >::append(x); + Self::deposit_event(Event::ExecutedDownward(id, outcome)); + }, }, } } From 4612154e940ee7ba4670fb9b808c14a282bef029 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 09:54:01 +0100 Subject: [PATCH 54/73] Fix incorrect hash CC @KiChjang --- xcm/src/v3/traits.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 1e3baae37d7a..261cde15697f 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -523,7 +523,5 @@ pub fn send_xcm( msg: Xcm<()>, ) -> result::Result<(XcmHash, MultiAssets), SendError> { let (ticket, price) = T::validate(&mut Some(dest), &mut Some(msg.clone()))?; - T::deliver(ticket)?; - let hash = crate::VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256); - Ok((hash, price)) + Ok((T::deliver(ticket)?, price)) } From 053c51095ddd78cb7f42d5e458a44e44ba44721b Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:05:50 +0100 Subject: [PATCH 55/73] Refactor and make clear fake hashes --- xcm/pallet-xcm/src/mock.rs | 4 ++ xcm/pallet-xcm/src/tests.rs | 24 +++++++----- xcm/xcm-builder/src/tests/assets.rs | 38 +++++++++---------- xcm/xcm-builder/src/tests/basic.rs | 2 +- xcm/xcm-builder/src/tests/bridging/mod.rs | 4 +- xcm/xcm-builder/src/tests/expecting.rs | 20 +++++----- xcm/xcm-builder/src/tests/locking.rs | 20 +++++----- xcm/xcm-builder/src/tests/mock.rs | 4 ++ xcm/xcm-builder/src/tests/origins.rs | 6 +-- xcm/xcm-builder/src/tests/querying.rs | 6 +-- xcm/xcm-builder/src/tests/transacting.rs | 14 +++---- .../src/tests/version_subscriptions.rs | 16 ++++---- xcm/xcm-builder/src/tests/weight.rs | 2 +- xcm/xcm-builder/tests/scenarios.rs | 12 +++--- 14 files changed, 92 insertions(+), 80 deletions(-) diff --git a/xcm/pallet-xcm/src/mock.rs b/xcm/pallet-xcm/src/mock.rs index 2a5d17e9e589..91fecf529c7d 100644 --- a/xcm/pallet-xcm/src/mock.rs +++ b/xcm/pallet-xcm/src/mock.rs @@ -375,3 +375,7 @@ pub(crate) fn new_test_ext_with_balances( ext.execute_with(|| System::set_block_number(1)); ext } + +pub(crate) fn fake_message_hash(message: &Xcm) -> XcmHash { + message.using_encoded(sp_io::hashing::blake2_256) +} diff --git a/xcm/pallet-xcm/src/tests.rs b/xcm/pallet-xcm/src/tests.rs index c129a00a0dc1..4115a3b413a7 100644 --- a/xcm/pallet-xcm/src/tests.rs +++ b/xcm/pallet-xcm/src/tests.rs @@ -36,6 +36,10 @@ const PARA_ID: u32 = 2000; const INITIAL_BALANCE: u128 = 100; const SEND_AMOUNT: u128 = 10; +fn fake_message_hash(message: &Xcm) -> XcmHash { + message.using_encoded(sp_io::hashing::blake2_256) +} + #[test] fn report_outcome_notify_works() { let balances = @@ -84,7 +88,7 @@ fn report_outcome_notify_works() { max_weight: 1_000_000, querier: Some(querier), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, 1_000_000_000); assert_eq!(r, Outcome::Complete(1_000)); @@ -140,7 +144,7 @@ fn report_outcome_works() { max_weight: 0, querier: Some(querier), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, 1_000_000_000); assert_eq!(r, Outcome::Complete(1_000)); @@ -179,7 +183,7 @@ fn custom_querier_works() { max_weight: 0, querier: None, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm_in_credit( AccountId32 { network: None, id: ALICE.into() }, message, @@ -205,7 +209,7 @@ fn custom_querier_works() { max_weight: 0, querier: Some(MultiLocation::here()), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm_in_credit( AccountId32 { network: None, id: ALICE.into() }, message, @@ -231,7 +235,7 @@ fn custom_querier_works() { max_weight: 0, querier: Some(querier), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm( AccountId32 { network: None, id: ALICE.into() }, message, @@ -823,7 +827,7 @@ fn subscription_side_works() { let remote: MultiLocation = Parachain(1000).into(); let weight = BaseXcmWeight::get(); let message = Xcm(vec![SubscribeVersion { query_id: 0, max_response_weight: 0 }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(remote.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); @@ -958,7 +962,7 @@ fn subscriber_side_subscription_works() { querier: None, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(remote.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!(take_sent_xcm(), vec![]); @@ -976,7 +980,7 @@ fn subscriber_side_subscription_works() { querier: None, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(remote.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); @@ -1037,7 +1041,7 @@ fn auto_subscription_works() { querier: None, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(remote0.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); @@ -1068,7 +1072,7 @@ fn auto_subscription_works() { querier: None, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(remote1.clone(), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); diff --git a/xcm/xcm-builder/src/tests/assets.rs b/xcm/xcm-builder/src/tests/assets.rs index ed1efed9b79e..44a7c45a7eea 100644 --- a/xcm/xcm-builder/src/tests/assets.rs +++ b/xcm/xcm-builder/src/tests/assets.rs @@ -32,7 +32,7 @@ fn exchange_asset_should_work() { maximal: true, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list(Parent), vec![(Here, 100).into(), (Parent, 950).into()]); @@ -55,7 +55,7 @@ fn exchange_asset_without_maximal_should_work() { maximal: false, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list(Parent), vec![(Here, 50).into(), (Parent, 950).into()]); @@ -78,7 +78,7 @@ fn exchange_asset_should_fail_when_no_deal_possible() { maximal: false, }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parent, message, hash, 50); assert_eq!(r, Outcome::Incomplete(40, XcmError::NoDeal)); assert_eq!(asset_list(Parent), vec![(Parent, 1000).into()]); @@ -97,7 +97,7 @@ fn paying_reserve_deposit_should_work() { BuyExecution { fees, weight_limit: Limited(30) }, DepositAsset { assets: AllCounted(1).into(), beneficiary: Here.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 50; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(30)); @@ -115,7 +115,7 @@ fn transfer_should_work() { assets: (Here, 100).into(), beneficiary: X1(AccountIndex64 { index: 3, network: None }).into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!(asset_list(AccountIndex64 { index: 3, network: None }), vec![(Here, 100).into()]); @@ -141,7 +141,7 @@ fn reserve_transfer_should_work() { beneficiary: three.clone(), }]), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); @@ -167,7 +167,7 @@ fn burn_should_work() { BurnAsset((Here, 100).into()), DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -179,7 +179,7 @@ fn burn_should_work() { BurnAsset((Here, 1000).into()), DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Parachain(1).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(30)); assert_eq!(asset_list(Parachain(1)), vec![]); @@ -201,7 +201,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Complete(25)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -215,7 +215,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -231,7 +231,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm(Parachain(2), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -247,7 +247,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let old_trapped_assets = TrappedAssets::get(); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); @@ -262,7 +262,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list(Parachain(1)), vec![(Here, 900).into()]); @@ -276,7 +276,7 @@ fn basic_asset_trap_should_work() { beneficiary: AccountIndex64 { index: 3, network: None }.into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 20); assert_eq!(r, Outcome::Incomplete(10, XcmError::UnknownClaim)); } @@ -307,7 +307,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([7u8; 32], 100).into()), WithdrawAsset(([8u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 100); assert_eq!(r, Outcome::Complete(85)); @@ -323,7 +323,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([8u8; 32], 100).into()), WithdrawAsset(([9u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 100); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); @@ -342,7 +342,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([7u8; 32], 100).into()), WithdrawAsset(([8u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Complete(125)); @@ -361,7 +361,7 @@ fn max_assets_limit_should_work() { WithdrawAsset(([3u8; 32], 100).into()), WithdrawAsset(([4u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Incomplete(95, XcmError::HoldingWouldOverflow)); @@ -379,7 +379,7 @@ fn max_assets_limit_should_work() { ])), WithdrawAsset(([1u8; 32], 100).into()), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 200); assert_eq!(r, Outcome::Incomplete(25, XcmError::HoldingWouldOverflow)); } diff --git a/xcm/xcm-builder/src/tests/basic.rs b/xcm/xcm-builder/src/tests/basic.rs index 08fe2a3f7441..e3a55b2106e9 100644 --- a/xcm/xcm-builder/src/tests/basic.rs +++ b/xcm/xcm-builder/src/tests/basic.rs @@ -85,7 +85,7 @@ fn code_registers_should_work() { let limit = ::Weigher::weight(&mut message).unwrap(); assert_eq!(limit, 70); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); assert_eq!(r, Outcome::Complete(50)); // We don't pay the 20 weight for the error handler. diff --git a/xcm/xcm-builder/src/tests/bridging/mod.rs b/xcm/xcm-builder/src/tests/bridging/mod.rs index 594993f30ce1..24182d2e0133 100644 --- a/xcm/xcm-builder/src/tests/bridging/mod.rs +++ b/xcm/xcm-builder/src/tests/bridging/mod.rs @@ -130,7 +130,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S AllowUnpaidFrom::set(vec![origin.clone()]); set_exporter_override(price::, deliver::); // The we execute it: - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let outcome = XcmExecutor::::execute_xcm(origin, message.into(), hash, 2_000_000_000_000); match outcome { @@ -171,7 +171,7 @@ impl, Remote: Get, RemoteExporter: ExportXcm> S AllowPaidFrom::set(vec![origin.clone()]); set_exporter_override(price::, deliver::); // The we execute it: - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let outcome = XcmExecutor::::execute_xcm(origin, message.into(), hash, 2_000_000_000_000); match outcome { diff --git a/xcm/xcm-builder/src/tests/expecting.rs b/xcm/xcm-builder/src/tests/expecting.rs index d1d76946b2a0..33830a721e05 100644 --- a/xcm/xcm-builder/src/tests/expecting.rs +++ b/xcm/xcm-builder/src/tests/expecting.rs @@ -28,7 +28,7 @@ fn expect_pallet_should_work() { crate_major: 1, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); @@ -39,7 +39,7 @@ fn expect_pallet_should_work() { crate_major: 1, min_crate_minor: 41, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); } @@ -54,7 +54,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 60, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); @@ -65,7 +65,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); @@ -76,7 +76,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); @@ -87,7 +87,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NameMismatch)); @@ -98,7 +98,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::PalletNotFound)); @@ -109,7 +109,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 2, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); @@ -120,7 +120,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 0, min_crate_minor: 42, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); @@ -131,7 +131,7 @@ fn expect_pallet_should_fail_correctly() { crate_major: 1, min_crate_minor: 43, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::VersionIncompatible)); } diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index c1393f32441c..24d34621cc7c 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -34,7 +34,7 @@ fn lock_roundtrip_should_work() { ), LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); @@ -54,7 +54,7 @@ fn lock_roundtrip_should_work() { // Now we'll unlock it. let message = Xcm(vec![UnlockAsset { asset: (Parent, 100).into(), target: (3u64,).into() }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); } @@ -73,7 +73,7 @@ fn auto_fee_paying_should_work() { SetFeesMode { jit_withdraw: true }, LockAsset { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); @@ -90,7 +90,7 @@ fn lock_should_fail_correctly() { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::LockError)); assert_eq!(sent_xcm(), vec![]); @@ -107,7 +107,7 @@ fn lock_should_fail_correctly() { asset: (Parent, 100).into(), unlocker: (Parent, Parachain(1)).into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotHoldingFees)); assert_eq!(sent_xcm(), vec![]); @@ -125,7 +125,7 @@ fn remote_unlock_roundtrip_should_work() { // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); assert_eq!( @@ -145,7 +145,7 @@ fn remote_unlock_roundtrip_should_work() { ), RequestUnlock { asset: (Parent, 100).into(), locker: (Parent, Parachain(1)).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990).into()]); @@ -178,7 +178,7 @@ fn remote_unlock_should_fail_correctly() { asset: (Parent, 100).into(), locker: (Parent, Parachain(1)).into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::LockError)); assert_eq!(sent_xcm(), vec![]); @@ -186,7 +186,7 @@ fn remote_unlock_should_fail_correctly() { // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100).into(), owner: (3u64,).into() }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); let _discard = take_lock_trace(); @@ -198,7 +198,7 @@ fn remote_unlock_should_fail_correctly() { asset: (Parent, 100).into(), locker: (Parent, Parachain(1)).into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((3u64,), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::NotHoldingFees)); diff --git a/xcm/xcm-builder/src/tests/mock.rs b/xcm/xcm-builder/src/tests/mock.rs index 652eb7b9f9c6..c6a69319821e 100644 --- a/xcm/xcm-builder/src/tests/mock.rs +++ b/xcm/xcm-builder/src/tests/mock.rs @@ -612,3 +612,7 @@ impl Config for TestConfig { pub fn fungible_multi_asset(location: MultiLocation, amount: u128) -> MultiAsset { (AssetId::from(location), Fungibility::Fungible(amount)).into() } + +pub fn fake_message_hash(message: &Xcm) -> XcmHash { + message.using_encoded(sp_io::hashing::blake2_256) +} diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index a3ca40ca51d5..c3acb30e961d 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -29,7 +29,7 @@ fn universal_origin_should_work() { UniversalOrigin(GlobalConsensus(Kusama)), TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(2), message, hash, 50); assert_eq!(r, Outcome::Incomplete(10, XcmError::InvalidLocation)); @@ -37,7 +37,7 @@ fn universal_origin_should_work() { UniversalOrigin(GlobalConsensus(Kusama)), TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Incomplete(20, XcmError::NotWithdrawable)); @@ -46,7 +46,7 @@ fn universal_origin_should_work() { UniversalOrigin(GlobalConsensus(Kusama)), TransferAsset { assets: (Parent, 100).into(), beneficiary: Here.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(20)); assert_eq!(asset_list((Ancestor(2), GlobalConsensus(Kusama))), vec![]); diff --git a/xcm/xcm-builder/src/tests/querying.rs b/xcm/xcm-builder/src/tests/querying.rs index 860a7fe3a557..15685a5569aa 100644 --- a/xcm/xcm-builder/src/tests/querying.rs +++ b/xcm/xcm-builder/src/tests/querying.rs @@ -29,7 +29,7 @@ fn pallet_query_should_work() { max_weight: 50, }, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); @@ -56,7 +56,7 @@ fn pallet_query_with_results_should_work() { max_weight: 50, }, }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); @@ -95,7 +95,7 @@ fn prepaid_result_of_query_should_get_free_execution() { max_weight: 10, querier: Some(Here.into()), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 10; // First time the response gets through since we're expecting it... diff --git a/xcm/xcm-builder/src/tests/transacting.rs b/xcm/xcm-builder/src/tests/transacting.rs index cd7445f8ad6b..91f4685a210f 100644 --- a/xcm/xcm-builder/src/tests/transacting.rs +++ b/xcm/xcm-builder/src/tests/transacting.rs @@ -25,7 +25,7 @@ fn transacting_should_work() { require_weight_at_most: 50, call: TestCall::Any(50, None).encode().into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 60; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(60)); @@ -40,7 +40,7 @@ fn transacting_should_respect_max_weight_requirement() { require_weight_at_most: 40, call: TestCall::Any(50, None).encode().into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 60; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Incomplete(50, XcmError::MaxWeightInvalid)); @@ -55,7 +55,7 @@ fn transacting_should_refund_weight() { require_weight_at_most: 50, call: TestCall::Any(50, Some(30)).encode().into(), }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 60; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(40)); @@ -82,7 +82,7 @@ fn paid_transacting_should_refund_payment_for_unused_weight() { RefundSurplus, DepositAsset { assets: AllCounted(1).into(), beneficiary: one.clone() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 100; let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(60)); @@ -105,7 +105,7 @@ fn report_successful_transact_status_should_work() { max_weight: 5000, }), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 70; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(70)); @@ -135,7 +135,7 @@ fn report_failed_transact_status_should_work() { max_weight: 5000, }), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 70; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(70)); @@ -166,7 +166,7 @@ fn clear_transact_status_should_work() { max_weight: 5000, }), ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 80; let r = XcmExecutor::::execute_xcm(Parent, message, hash, weight_limit); assert_eq!(r, Outcome::Complete(80)); diff --git a/xcm/xcm-builder/src/tests/version_subscriptions.rs b/xcm/xcm-builder/src/tests/version_subscriptions.rs index cab4f42be3b0..e7125e6e75a5 100644 --- a/xcm/xcm-builder/src/tests/version_subscriptions.rs +++ b/xcm/xcm-builder/src/tests/version_subscriptions.rs @@ -25,7 +25,7 @@ fn simple_version_subscriptions_should_work() { SetAppendix(Xcm(vec![])), SubscribeVersion { query_id: 42, max_response_weight: 5000 }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 20; let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); @@ -33,7 +33,7 @@ fn simple_version_subscriptions_should_work() { let origin = Parachain(1000); let message = Xcm::(vec![SubscribeVersion { query_id: 42, max_response_weight: 5000 }]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 10; let r = XcmExecutor::::execute_xcm(origin, message.clone(), hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); @@ -51,7 +51,7 @@ fn version_subscription_instruction_should_work() { DescendOrigin(X1(AccountIndex64 { index: 1, network: None })), SubscribeVersion { query_id: 42, max_response_weight: 5000 }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 20; let r = XcmExecutor::::execute_xcm_in_credit( origin.clone(), @@ -66,7 +66,7 @@ fn version_subscription_instruction_should_work() { SetAppendix(Xcm(vec![])), SubscribeVersion { query_id: 42, max_response_weight: 5000 }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm_in_credit( origin, message, @@ -85,14 +85,14 @@ fn simple_version_unsubscriptions_should_work() { let origin = Parachain(1000); let message = Xcm::(vec![SetAppendix(Xcm(vec![])), UnsubscribeVersion]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 20; let r = XcmExecutor::::execute_xcm(origin, message, hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); let origin = Parachain(1000); let message = Xcm::(vec![UnsubscribeVersion]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 10; let r = XcmExecutor::::execute_xcm(origin, message.clone(), hash, weight_limit); assert_eq!(r, Outcome::Error(XcmError::Barrier)); @@ -113,7 +113,7 @@ fn version_unsubscription_instruction_should_work() { DescendOrigin(X1(AccountIndex64 { index: 1, network: None })), UnsubscribeVersion, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let weight_limit = 20; let r = XcmExecutor::::execute_xcm_in_credit( origin.clone(), @@ -126,7 +126,7 @@ fn version_unsubscription_instruction_should_work() { // Fine to do it when origin is untouched. let message = Xcm::(vec![SetAppendix(Xcm(vec![])), UnsubscribeVersion]); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm_in_credit( origin, message, diff --git a/xcm/xcm-builder/src/tests/weight.rs b/xcm/xcm-builder/src/tests/weight.rs index c1344594317b..3f6c3f3aa9f5 100644 --- a/xcm/xcm-builder/src/tests/weight.rs +++ b/xcm/xcm-builder/src/tests/weight.rs @@ -43,7 +43,7 @@ fn errors_should_return_unused_weight() { let limit = ::Weigher::weight(&mut message).unwrap(); assert_eq!(limit, 30); - let hash = VersionedXcm::from(message.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Here, message.clone(), hash, limit); assert_eq!(r, Outcome::Complete(30)); diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index 0d6eca893d97..84c40b4c9ef5 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -56,7 +56,7 @@ fn withdraw_and_deposit_works() { beneficiary: Parachain(other_para_id).into(), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account(); @@ -97,7 +97,7 @@ fn report_holding_works() { // is not triggered becasue the deposit fails ReportHolding { response_info: response_info.clone(), assets: All.into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!( r, @@ -121,7 +121,7 @@ fn report_holding_works() { // used to get a notification in case of success ReportHolding { response_info: response_info.clone(), assets: AllCounted(1).into() }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let other_para_acc: AccountId = ParaId::from(other_para_id).into_account(); @@ -177,7 +177,7 @@ fn teleport_to_statemine_works() { xcm: Xcm(teleport_effects.clone()), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); let expected_msg = Xcm(vec![ReceiveTeleportedAsset((Parent, amount).into()), ClearOrigin] @@ -200,7 +200,7 @@ fn teleport_to_statemine_works() { xcm: Xcm(teleport_effects.clone()), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); // 2 * amount because of the other teleport above @@ -250,7 +250,7 @@ fn reserve_based_transfer_works() { xcm: Xcm(transfer_effects.clone()), }, ]); - let hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&message); let weight = 3 * BaseXcmWeight::get(); let r = XcmExecutor::::execute_xcm(Parachain(PARA_ID), message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); From 9e463e16afe1dd72a116c5b89b0e6131f14f23ef Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:13:15 +0100 Subject: [PATCH 56/73] Fixes --- xcm/pallet-xcm/src/mock.rs | 2 +- xcm/pallet-xcm/src/tests.rs | 5 ----- xcm/xcm-builder/src/tests/bridging/local_para_para.rs | 6 +++--- .../src/tests/bridging/local_relay_relay.rs | 4 ++-- .../src/tests/bridging/paid_remote_relay_relay.rs | 4 ++-- .../src/tests/bridging/remote_para_para.rs | 6 +++--- .../src/tests/bridging/remote_para_para_via_relay.rs | 6 +++--- .../src/tests/bridging/remote_relay_relay.rs | 4 ++-- xcm/xcm-builder/tests/mock/mod.rs | 11 ++++++----- xcm/xcm-builder/tests/scenarios.rs | 3 ++- 10 files changed, 24 insertions(+), 27 deletions(-) diff --git a/xcm/pallet-xcm/src/mock.rs b/xcm/pallet-xcm/src/mock.rs index 91fecf529c7d..c10347e075ff 100644 --- a/xcm/pallet-xcm/src/mock.rs +++ b/xcm/pallet-xcm/src/mock.rs @@ -376,6 +376,6 @@ pub(crate) fn new_test_ext_with_balances( ext } -pub(crate) fn fake_message_hash(message: &Xcm) -> XcmHash { +pub(crate) fn fake_message_hash(message: &Xcm) -> XcmHash { message.using_encoded(sp_io::hashing::blake2_256) } diff --git a/xcm/pallet-xcm/src/tests.rs b/xcm/pallet-xcm/src/tests.rs index 4115a3b413a7..69b804fb9804 100644 --- a/xcm/pallet-xcm/src/tests.rs +++ b/xcm/pallet-xcm/src/tests.rs @@ -18,7 +18,6 @@ use crate::{ mock::*, AssetTraps, CurrentMigration, Error, LatestVersionedMultiLocation, Queries, QueryStatus, VersionDiscoveryQueue, VersionNotifiers, VersionNotifyTargets, }; -use codec::Encode; use frame_support::{ assert_noop, assert_ok, traits::{Currency, Hooks}, @@ -36,10 +35,6 @@ const PARA_ID: u32 = 2000; const INITIAL_BALANCE: u128 = 100; const SEND_AMOUNT: u128 = 10; -fn fake_message_hash(message: &Xcm) -> XcmHash { - message.using_encoded(sp_io::hashing::blake2_256) -} - #[test] fn report_outcome_notify_works() { let balances = diff --git a/xcm/xcm-builder/src/tests/bridging/local_para_para.rs b/xcm/xcm-builder/src/tests/bridging/local_para_para.rs index 6624ac6fb877..7087d2178869 100644 --- a/xcm/xcm-builder/src/tests/bridging/local_para_para.rs +++ b/xcm/xcm-builder/src/tests/bridging/local_para_para.rs @@ -41,7 +41,7 @@ type Router = LocalUnpaidExporter, Un #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1)).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); assert_eq!(TheBridge::service(), 1); @@ -71,7 +71,7 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_parachain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); assert_eq!(TheBridge::service(), 1); @@ -99,7 +99,7 @@ fn sending_to_parachain_of_bridged_chain_works() { #[test] fn sending_to_relay_chain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get()).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); assert_eq!(TheBridge::service(), 1); diff --git a/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs b/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs index b94e07afccb3..4c76b4589e30 100644 --- a/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs @@ -37,7 +37,7 @@ type Router = LocalUnpaidExporter, Un #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); assert_eq!( send_xcm::((Parent, Remote::get()).into(), msg), Ok((hash, (Here, 100).into())) @@ -62,7 +62,7 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_parachain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Remote::get(), Parachain(1000)).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); assert_eq!(TheBridge::service(), 1); diff --git a/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs b/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs index 9105b334e57e..6afe447c2877 100644 --- a/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs @@ -66,7 +66,7 @@ fn sending_to_bridged_chain_works() { add_asset(Parachain(100), (Here, 1000)); let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); assert_eq!(send_xcm::(dest, msg), Ok((hash, (Parent, 150).into()))); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -108,7 +108,7 @@ fn sending_to_parachain_of_bridged_chain_works() { add_asset(Parachain(100), (Here, 1000)); let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); assert_eq!(send_xcm::(dest, msg), Ok((hash, (Parent, 150).into()))); assert_eq!(TheBridge::service(), 1); let expected = vec![( diff --git a/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs b/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs index b3c0f61e0abf..485b207e9b4c 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs @@ -49,7 +49,7 @@ type LocalRouter = (LocalInnerRouter, LocalBridgingRouter); #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); assert_eq!( send_xcm::((Parent, Parent, Remote::get(), Parachain(1)).into(), msg), Ok((hash, MultiAssets::new())) @@ -81,7 +81,7 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_sibling_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); assert_eq!(TheBridge::service(), 1); @@ -109,7 +109,7 @@ fn sending_to_sibling_of_bridged_chain_works() { #[test] fn sending_to_relay_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get()).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); assert_eq!(TheBridge::service(), 1); diff --git a/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs b/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs index 6eeadda02840..e50f2d9c1cf3 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs @@ -49,7 +49,7 @@ type LocalRouter = (LocalInnerRouter, LocalBridgingRouter); #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); assert_eq!( send_xcm::((Parent, Remote::get(), Parachain(1)).into(), msg), Ok((hash, MultiAssets::new())) @@ -74,7 +74,7 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_sibling_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Remote::get(), Parachain(1000)).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); assert_eq!(TheBridge::service(), 1); @@ -98,7 +98,7 @@ fn sending_to_sibling_of_bridged_chain_works() { #[test] fn sending_to_relay_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Remote::get()).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); assert_eq!(TheBridge::service(), 1); diff --git a/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs b/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs index 297b6ad6fc1c..4b791eb5737e 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs @@ -49,7 +49,7 @@ type LocalRouter = (LocalInnerRouter, LocalBridgeRouter); #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); assert_eq!( send_xcm::((Parent, Parent, Remote::get()).into(), msg), Ok((hash, MultiAssets::new())) @@ -81,7 +81,7 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_parachain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); assert_eq!(TheBridge::service(), 1); diff --git a/xcm/xcm-builder/tests/mock/mod.rs b/xcm/xcm-builder/tests/mock/mod.rs index 541251991d29..3b782d99de66 100644 --- a/xcm/xcm-builder/tests/mock/mod.rs +++ b/xcm/xcm-builder/tests/mock/mod.rs @@ -26,10 +26,7 @@ use sp_std::cell::RefCell; use polkadot_parachain::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; -use xcm::{ - latest::{opaque, prelude::*}, - VersionedXcm, -}; +use xcm::latest::{opaque, prelude::*}; use xcm_executor::XcmExecutor; use xcm_builder::{ @@ -57,7 +54,7 @@ impl SendXcm for TestSendXcm { msg: &mut Option>, ) -> SendResult<(MultiLocation, Xcm<()>, XcmHash)> { let msg = msg.take().unwrap(); - let hash = VersionedXcm::from(msg.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&msg); let triplet = (dest.take().unwrap(), msg, hash); Ok((triplet, MultiAssets::new())) } @@ -252,3 +249,7 @@ pub fn kusama_like_with_balances(balances: Vec<(AccountId, Balance)>) -> sp_io:: ext.execute_with(|| System::set_block_number(1)); ext } + +pub fn fake_message_hash(message: &Xcm) -> XcmHash { + message.using_encoded(sp_io::hashing::blake2_256) +} diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index 84c40b4c9ef5..b37679488e3b 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -17,7 +17,8 @@ mod mock; use mock::{ - kusama_like_with_balances, AccountId, Balance, Balances, BaseXcmWeight, XcmConfig, CENTS, + kusama_like_with_balances, fake_message_hash, AccountId, Balance, Balances, BaseXcmWeight, + XcmConfig, CENTS, }; use parity_scale_codec::Encode; use polkadot_parachain::primitives::Id as ParaId; From 63f7b608ae1f4be9dd0e8f4c8e8d4e36975c6d5d Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:20:54 +0100 Subject: [PATCH 57/73] Fixes --- xcm/xcm-builder/src/tests/mock.rs | 4 ++-- xcm/xcm-builder/src/tests/origins.rs | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/xcm/xcm-builder/src/tests/mock.rs b/xcm/xcm-builder/src/tests/mock.rs index c6a69319821e..b9acec97924e 100644 --- a/xcm/xcm-builder/src/tests/mock.rs +++ b/xcm/xcm-builder/src/tests/mock.rs @@ -140,7 +140,7 @@ impl SendXcm for TestMessageSender { msg: &mut Option>, ) -> SendResult<(MultiLocation, Xcm<()>, XcmHash)> { let msg = msg.take().unwrap(); - let hash = VersionedXcm::from(msg.clone()).using_encoded(blake2_256); + let hash = fake_message_hash(&msg); let triplet = (dest.take().unwrap(), msg, hash); Ok((triplet, SEND_PRICE.with(|l| l.borrow().clone()))) } @@ -167,7 +167,7 @@ impl ExportXcm for TestMessageExporter { Ok(MultiAssets::new()) } }); - let h = VersionedXcm::from(m.clone()).using_encoded(blake2_256); + let h = fake_message_hash(&m); match r { Ok(price) => Ok(((network, channel, d, m, h), price)), Err(e) => { diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index c3acb30e961d..3476214b9146 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -58,13 +58,13 @@ fn export_message_should_work() { AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); // Local parachain #1 issues a transfer asset on Polkadot Relay-chain, transfering 100 Planck to // Polkadot parachain #2. - let message = + let expected_message = Xcm(vec![TransferAsset { assets: (Here, 100).into(), beneficiary: Parachain(2).into() }]); - let exported_msg = - Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: message.clone() }]); - let hash = VersionedXcm::from(exported_msg.clone()).using_encoded(sp_io::hashing::blake2_256); - let expected_hash = VersionedXcm::from(message.clone()).using_encoded(blake2_256); - let r = XcmExecutor::::execute_xcm(Parachain(1), exported_msg, hash, 50); + let expected_hash = fake_message_hash(&expected_message); + let message = + Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: expected_message.clone() }]); + let hash = fake_message_hash(&message); + let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); - assert_eq!(exported_xcm(), vec![(Polkadot, 403611790, Here, message, expected_hash)]); + assert_eq!(exported_xcm(), vec![(Polkadot, 403611790, Here, expected_message, expected_hash)]); } From e1933fa4c3839c5381bb061db5e504a3e2ac568d Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:23:11 +0100 Subject: [PATCH 58/73] Fixes --- xcm/xcm-builder/src/tests/assets.rs | 2 +- xcm/xcm-builder/src/tests/locking.rs | 4 ++-- xcm/xcm-builder/src/tests/querying.rs | 4 ++-- xcm/xcm-builder/src/tests/transacting.rs | 6 +++--- xcm/xcm-builder/tests/scenarios.rs | 12 +++++------- 5 files changed, 13 insertions(+), 15 deletions(-) diff --git a/xcm/xcm-builder/src/tests/assets.rs b/xcm/xcm-builder/src/tests/assets.rs index 44a7c45a7eea..628f992034ed 100644 --- a/xcm/xcm-builder/src/tests/assets.rs +++ b/xcm/xcm-builder/src/tests/assets.rs @@ -150,7 +150,7 @@ fn reserve_transfer_should_work() { ClearOrigin, DepositAsset { assets: AllCounted(1).into(), beneficiary: three }, ]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(asset_list(Parachain(2)), vec![(Here, 100).into()]); assert_eq!(sent_xcm(), vec![(Parachain(2).into(), expected_msg, expected_hash)]); } diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index 24d34621cc7c..929b449e80c7 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -41,7 +41,7 @@ fn lock_roundtrip_should_work() { let expected_msg = Xcm::<()>(vec![NoteUnlockable { owner: (3u64,).into(), asset: (Parent, 100).into() }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![((Parent, Parachain(1)).into(), expected_msg, expected_hash)]); assert_eq!( take_lock_trace(), @@ -152,7 +152,7 @@ fn remote_unlock_roundtrip_should_work() { let expected_msg = Xcm::<()>(vec![UnlockAsset { target: (3u64,).into(), asset: (Parent, 100).into() }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![((Parent, Parachain(1)).into(), expected_msg, expected_hash)]); assert_eq!( take_lock_trace(), diff --git a/xcm/xcm-builder/src/tests/querying.rs b/xcm/xcm-builder/src/tests/querying.rs index 15685a5569aa..e3a8a68f3ec6 100644 --- a/xcm/xcm-builder/src/tests/querying.rs +++ b/xcm/xcm-builder/src/tests/querying.rs @@ -39,7 +39,7 @@ fn pallet_query_should_work() { response: Response::PalletsInfo(vec![].try_into().unwrap()), querier: Some(Here.into()), }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![(Parachain(1).into(), expected_msg, expected_hash)]); } @@ -78,7 +78,7 @@ fn pallet_query_with_results_should_work() { ), querier: Some(Here.into()), }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![(Parachain(1).into(), expected_msg, expected_hash)]); } diff --git a/xcm/xcm-builder/src/tests/transacting.rs b/xcm/xcm-builder/src/tests/transacting.rs index 91f4685a210f..d7cfdc8e99bb 100644 --- a/xcm/xcm-builder/src/tests/transacting.rs +++ b/xcm/xcm-builder/src/tests/transacting.rs @@ -115,7 +115,7 @@ fn report_successful_transact_status_should_work() { max_weight: 5000, querier: Some(Here.into()), }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![(Parent.into(), expected_msg, expected_hash)]); } @@ -145,7 +145,7 @@ fn report_failed_transact_status_should_work() { max_weight: 5000, querier: Some(Here.into()), }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![(Parent.into(), expected_msg, expected_hash)]); } @@ -176,6 +176,6 @@ fn clear_transact_status_should_work() { max_weight: 5000, querier: Some(Here.into()), }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![(Parent.into(), expected_msg, expected_hash)]); } diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index b37679488e3b..3b912b97453f 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -20,11 +20,9 @@ use mock::{ kusama_like_with_balances, fake_message_hash, AccountId, Balance, Balances, BaseXcmWeight, XcmConfig, CENTS, }; -use parity_scale_codec::Encode; use polkadot_parachain::primitives::Id as ParaId; -use sp_io::hashing::blake2_256; use sp_runtime::traits::AccountIdConversion; -use xcm::{latest::prelude::*, VersionedXcm}; +use xcm::latest::prelude::*; use xcm_executor::XcmExecutor; pub const ALICE: AccountId = AccountId::new([0u8; 32]); @@ -134,7 +132,7 @@ fn report_holding_works() { max_weight: response_info.max_weight, querier: Some(Here.into()), }]); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!( mock::sent_xcm(), vec![(Parachain(PARA_ID).into(), expected_msg, expected_hash,)] @@ -185,7 +183,7 @@ fn teleport_to_statemine_works() { .into_iter() .chain(teleport_effects.clone().into_iter()) .collect()); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!( mock::sent_xcm(), vec![(Parachain(other_para_id).into(), expected_msg, expected_hash,)] @@ -210,7 +208,7 @@ fn teleport_to_statemine_works() { .into_iter() .chain(teleport_effects.clone().into_iter()) .collect()); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!( mock::sent_xcm(), vec![ @@ -260,7 +258,7 @@ fn reserve_based_transfer_works() { .into_iter() .chain(transfer_effects.into_iter()) .collect()); - let expected_hash = VersionedXcm::from(expected_msg.clone()).using_encoded(blake2_256); + let expected_hash = fake_message_hash(&expected_msg); assert_eq!( mock::sent_xcm(), vec![(Parachain(other_para_id).into(), expected_msg, expected_hash,)] From c9d0e32f958eb8b82a19c992fd5cfa6205adf59f Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:27:42 +0100 Subject: [PATCH 59/73] Fix broken hashing --- xcm/src/v3/traits.rs | 3 ++- xcm/xcm-executor/src/traits/export.rs | 3 +-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 261cde15697f..b5b3f6adaff2 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -523,5 +523,6 @@ pub fn send_xcm( msg: Xcm<()>, ) -> result::Result<(XcmHash, MultiAssets), SendError> { let (ticket, price) = T::validate(&mut Some(dest), &mut Some(msg.clone()))?; - Ok((T::deliver(ticket)?, price)) + let hash = T::deliver(ticket)?; + Ok((hash, price)) } diff --git a/xcm/xcm-executor/src/traits/export.rs b/xcm/xcm-executor/src/traits/export.rs index 8544e1c4f81b..c259fe3c1f9e 100644 --- a/xcm/xcm-executor/src/traits/export.rs +++ b/xcm/xcm-executor/src/traits/export.rs @@ -113,7 +113,6 @@ pub fn export_xcm( msg: Xcm<()>, ) -> Result<(XcmHash, MultiAssets), SendError> { let (ticket, price) = T::validate(network, channel, &mut Some(dest), &mut Some(msg.clone()))?; - T::deliver(ticket)?; - let hash = VersionedXcm::from(msg).using_encoded(sp_io::hashing::blake2_256); + let hash = T::deliver(ticket)?; Ok((hash, price)) } From c3d1ddfc7a6d2376f8998f352e153728ce09452c Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:29:42 +0100 Subject: [PATCH 60/73] Docs --- xcm/xcm-executor/src/traits/transact_asset.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/xcm/xcm-executor/src/traits/transact_asset.rs b/xcm/xcm-executor/src/traits/transact_asset.rs index 94aff222d162..ebd05905bfc4 100644 --- a/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/xcm/xcm-executor/src/traits/transact_asset.rs @@ -74,9 +74,9 @@ pub trait TransactAsset { /// Withdraw the given asset from the consensus system. Return the actual asset(s) withdrawn, /// which should always be equal to `_what`. /// - /// The XCM `_context` parameter may be `None` when the caller of `withdraw_asset` is outside of - /// the context of a currently-executing XCM. An example will be the `charge_fees` method in the - /// XCM executor. + /// The XCM `_maybe_context` parameter may be `None` when the caller of `withdraw_asset` is + /// outside of the context of a currently-executing XCM. An example will be the `charge_fees` + /// method in the XCM executor. /// /// Implementations should return `XcmError::FailedToTransactAsset` if withdraw failed. fn withdraw_asset( From a4e3656568fa1adf1a70ec9c64909e737d1cfa0e Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:32:54 +0100 Subject: [PATCH 61/73] Fixes --- xcm/xcm-simulator/src/lib.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/xcm/xcm-simulator/src/lib.rs b/xcm/xcm-simulator/src/lib.rs index cee9f58dc3f0..1cba71107e69 100644 --- a/xcm/xcm-simulator/src/lib.rs +++ b/xcm/xcm-simulator/src/lib.rs @@ -20,7 +20,7 @@ pub use codec::Encode; pub use paste; pub use frame_support::{traits::Get, weights::Weight}; -pub use sp_io::{self, TestExternalities}; +pub use sp_io::{hashing::blake2_256, TestExternalities}; pub use sp_std::{cell::RefCell, collections::vec_deque::VecDeque, marker::PhantomData}; pub use polkadot_core_primitives::BlockNumber as RelayBlockNumber; @@ -76,6 +76,10 @@ pub fn encode_xcm(message: Xcm<()>, message_kind: MessageKind) -> Vec { } } +pub fn fake_message_hash(message: Xcm) -> XcmHash { + message.using_encoded(blake2_256) +} + #[macro_export] #[rustfmt::skip] macro_rules! decl_test_relay_chain { @@ -321,7 +325,7 @@ macro_rules! decl_test_network { fn deliver( triple: ($crate::ParaId, $crate::MultiLocation, $crate::Xcm<()>), ) -> Result<$crate::XcmHash, $crate::SendError> { - let hash = $crate::VersionedXcm::from(triple.2.clone()).using_encoded($crate::sp_io::hashing::blake2_256); + let hash = $crate::fake_message_hash(&triple.2); $crate::PARA_MESSAGE_BUS.with(|b| b.borrow_mut().push_back(triple)); Ok(hash) } @@ -353,7 +357,7 @@ macro_rules! decl_test_network { fn deliver( pair: ($crate::MultiLocation, $crate::Xcm<()>), ) -> Result<$crate::XcmHash, $crate::SendError> { - let hash = $crate::VersionedXcm::from(pair.1.clone()).using_encoded($crate::sp_io::hashing::blake2_256); + let hash = $crate::fake_message_hash(&pair.1); $crate::RELAY_MESSAGE_BUS.with(|b| b.borrow_mut().push_back(pair)); Ok(hash) } From 788004df4198f71fed5f8aad475525c30656fb56 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:33:50 +0100 Subject: [PATCH 62/73] Fixes --- xcm/xcm-executor/src/traits/export.rs | 3 +-- xcm/xcm-simulator/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/xcm/xcm-executor/src/traits/export.rs b/xcm/xcm-executor/src/traits/export.rs index c259fe3c1f9e..4b4169ddc16d 100644 --- a/xcm/xcm-executor/src/traits/export.rs +++ b/xcm/xcm-executor/src/traits/export.rs @@ -14,8 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use parity_scale_codec::Encode; -use xcm::{latest::prelude::*, VersionedXcm}; +use xcm::latest::prelude::*; pub trait ExportXcm { type Ticket; diff --git a/xcm/xcm-simulator/src/lib.rs b/xcm/xcm-simulator/src/lib.rs index 1cba71107e69..6a60eecb71d4 100644 --- a/xcm/xcm-simulator/src/lib.rs +++ b/xcm/xcm-simulator/src/lib.rs @@ -76,7 +76,7 @@ pub fn encode_xcm(message: Xcm<()>, message_kind: MessageKind) -> Vec { } } -pub fn fake_message_hash(message: Xcm) -> XcmHash { +pub fn fake_message_hash(message: &Xcm) -> XcmHash { message.using_encoded(blake2_256) } From c247f63501fe785b9880ea71801c9c5b5e2a7c2d Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:35:44 +0100 Subject: [PATCH 63/73] Fixes --- xcm/pallet-xcm/src/mock.rs | 4 ++-- xcm/xcm-builder/src/tests/bridging/mod.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/xcm/pallet-xcm/src/mock.rs b/xcm/pallet-xcm/src/mock.rs index c10347e075ff..0e86483d6792 100644 --- a/xcm/pallet-xcm/src/mock.rs +++ b/xcm/pallet-xcm/src/mock.rs @@ -166,7 +166,7 @@ impl SendXcm for TestSendXcm { Ok((pair, MultiAssets::new())) } fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { - let hash = VersionedXcm::from(pair.1.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&pair.1); SENT_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) } @@ -187,7 +187,7 @@ impl SendXcm for TestSendXcmErrX8 { } } fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { - let hash = VersionedXcm::from(pair.1.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&pair.1); SENT_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) } diff --git a/xcm/xcm-builder/src/tests/bridging/mod.rs b/xcm/xcm-builder/src/tests/bridging/mod.rs index 24182d2e0133..044aa00986cf 100644 --- a/xcm/xcm-builder/src/tests/bridging/mod.rs +++ b/xcm/xcm-builder/src/tests/bridging/mod.rs @@ -70,7 +70,7 @@ impl SendXcm for TestRemoteIncomingRouter { Ok((pair, MultiAssets::new())) } fn deliver(pair: (MultiLocation, Xcm<()>)) -> Result { - let hash = VersionedXcm::from(pair.1.clone()).using_encoded(sp_io::hashing::blake2_256); + let hash = fake_message_hash(&pair.1); REMOTE_INCOMING_XCM.with(|q| q.borrow_mut().push(pair)); Ok(hash) } From 28899e425f4db67d03895047c46d55ff959de80d Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 10:37:58 +0100 Subject: [PATCH 64/73] Formatting --- xcm/xcm-builder/src/tests/origins.rs | 7 +++++-- xcm/xcm-builder/tests/scenarios.rs | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index 3476214b9146..474561002987 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -61,8 +61,11 @@ fn export_message_should_work() { let expected_message = Xcm(vec![TransferAsset { assets: (Here, 100).into(), beneficiary: Parachain(2).into() }]); let expected_hash = fake_message_hash(&expected_message); - let message = - Xcm(vec![ExportMessage { network: Polkadot, destination: Here, xcm: expected_message.clone() }]); + let message = Xcm(vec![ExportMessage { + network: Polkadot, + destination: Here, + xcm: expected_message.clone(), + }]); let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(Parachain(1), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); diff --git a/xcm/xcm-builder/tests/scenarios.rs b/xcm/xcm-builder/tests/scenarios.rs index 3b912b97453f..f2c708ab849b 100644 --- a/xcm/xcm-builder/tests/scenarios.rs +++ b/xcm/xcm-builder/tests/scenarios.rs @@ -17,7 +17,7 @@ mod mock; use mock::{ - kusama_like_with_balances, fake_message_hash, AccountId, Balance, Balances, BaseXcmWeight, + fake_message_hash, kusama_like_with_balances, AccountId, Balance, Balances, BaseXcmWeight, XcmConfig, CENTS, }; use polkadot_parachain::primitives::Id as ParaId; From f50e5d64c8e01df87f1f92c6f7b27a987c381e42 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 12:51:46 +0100 Subject: [PATCH 65/73] Fixes --- bridges/bin/rialto-parachain/runtime/src/lib.rs | 2 +- runtime/kusama/src/xcm_config.rs | 4 ++-- runtime/polkadot/src/xcm_config.rs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/bridges/bin/rialto-parachain/runtime/src/lib.rs b/bridges/bin/rialto-parachain/runtime/src/lib.rs index 7660597892b0..50caa47ccf21 100644 --- a/bridges/bin/rialto-parachain/runtime/src/lib.rs +++ b/bridges/bin/rialto-parachain/runtime/src/lib.rs @@ -349,7 +349,7 @@ parameter_types! { pub const MaxAuthorities: u32 = 100_000; } -match_type! { +match_types! { pub type ParentOrParentsUnitPlurality: impl Contains = { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) } diff --git a/runtime/kusama/src/xcm_config.rs b/runtime/kusama/src/xcm_config.rs index aab416f7f33d..8adb87b804a6 100644 --- a/runtime/kusama/src/xcm_config.rs +++ b/runtime/kusama/src/xcm_config.rs @@ -21,7 +21,7 @@ use super::{ Origin, ParaId, Runtime, WeightToFee, XcmPallet, }; use frame_support::{ - match_type, parameter_types, + match_types, parameter_types, traits::{Everything, Nothing}, weights::Weight, }; @@ -114,7 +114,7 @@ parameter_types! { pub type TrustedTeleporters = (xcm_builder::Case, xcm_builder::Case); -match_type! { +match_types! { pub type OnlyParachains: impl Contains = { MultiLocation { parents: 0, interior: X1(Parachain(_)) } }; diff --git a/runtime/polkadot/src/xcm_config.rs b/runtime/polkadot/src/xcm_config.rs index 7f67563bf319..d88596847983 100644 --- a/runtime/polkadot/src/xcm_config.rs +++ b/runtime/polkadot/src/xcm_config.rs @@ -21,7 +21,7 @@ use super::{ Origin, ParaId, Runtime, WeightToFee, XcmPallet, }; use frame_support::{ - match_type, parameter_types, + match_types, parameter_types, traits::{Everything, Nothing}, weights::Weight, }; @@ -108,7 +108,7 @@ parameter_types! { pub type TrustedTeleporters = (xcm_builder::Case,); -match_type! { +match_types! { pub type OnlyParachains: impl Contains = { MultiLocation { parents: 0, interior: X1(Parachain(_)) } }; From cd8b8dd5d373b84cea4771083c54c7e36391503f Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 13:24:34 +0100 Subject: [PATCH 66/73] Fixes --- runtime/parachains/src/ump/benchmarking.rs | 6 +++--- runtime/westend/src/weights/xcm/mod.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/runtime/parachains/src/ump/benchmarking.rs b/runtime/parachains/src/ump/benchmarking.rs index 2c132324d44a..0d38e77b7b71 100644 --- a/runtime/parachains/src/ump/benchmarking.rs +++ b/runtime/parachains/src/ump/benchmarking.rs @@ -42,7 +42,7 @@ fn queue_upward_msg( fn create_message_min_size(size: u32) -> Vec { // Create a message with an empty remark call to determine the encoding overhead let msg_size_empty_transact = VersionedXcm::::from(Xcm::(vec![Transact { - origin_type: OriginKind::SovereignAccount, + origin_kind: OriginKind::SovereignAccount, require_weight_at_most: Weight::MAX, call: frame_system::Call::::remark_with_event { remark: vec![] }.encode().into(), }])) @@ -54,7 +54,7 @@ fn create_message_min_size(size: u32) -> Vec { let mut remark = Vec::new(); remark.resize(size, 0u8); let msg = VersionedXcm::::from(Xcm::(vec![Transact { - origin_type: OriginKind::SovereignAccount, + origin_kind: OriginKind::SovereignAccount, require_weight_at_most: Weight::MAX, call: frame_system::Call::::remark_with_event { remark }.encode().into(), }])) @@ -69,7 +69,7 @@ fn create_message_overweight() -> Vec { // We use a `set_code` Call because it let call = frame_system::Call::::set_code { code: vec![] }; VersionedXcm::::from(Xcm::(vec![Transact { - origin_type: OriginKind::Superuser, + origin_kind: OriginKind::Superuser, require_weight_at_most: max_block_weight, call: call.encode().into(), }])) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index 702121fb5855..c5530f2f1592 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -98,7 +98,7 @@ impl XcmWeightInfo for WestendXcmWeight { assets.weigh_multi_assets(XcmBalancesWeight::::transfer_reserve_asset()) } fn transact( - _origin_type: &OriginKind, + _origin_kind &OriginKind, _require_weight_at_most: &u64, _call: &DoubleEncoded, ) -> Weight { From 43f9ced981b56f992d11f44ac6be90f17e2cdba4 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 13:24:44 +0100 Subject: [PATCH 67/73] Fixes --- runtime/westend/src/weights/xcm/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index c5530f2f1592..85bcd7f60472 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -98,7 +98,7 @@ impl XcmWeightInfo for WestendXcmWeight { assets.weigh_multi_assets(XcmBalancesWeight::::transfer_reserve_asset()) } fn transact( - _origin_kind &OriginKind, + _origin_kind: &OriginKind, _require_weight_at_most: &u64, _call: &DoubleEncoded, ) -> Weight { From 426370cd92428bce974811b5e83b0abd407ffe18 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 17:14:51 +0100 Subject: [PATCH 68/73] Remove unknowable hash --- runtime/westend/src/weights/xcm/mod.rs | 2 +- xcm/xcm-builder/src/tests/bridging/local_para_para.rs | 9 +++------ .../src/tests/bridging/local_relay_relay.rs | 8 +++----- .../src/tests/bridging/paid_remote_relay_relay.rs | 6 ++---- .../src/tests/bridging/remote_para_para.rs | 11 ++++------- .../src/tests/bridging/remote_para_para_via_relay.rs | 11 ++++------- .../src/tests/bridging/remote_relay_relay.rs | 8 +++----- 7 files changed, 20 insertions(+), 35 deletions(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index 85bcd7f60472..702121fb5855 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -98,7 +98,7 @@ impl XcmWeightInfo for WestendXcmWeight { assets.weigh_multi_assets(XcmBalancesWeight::::transfer_reserve_asset()) } fn transact( - _origin_kind: &OriginKind, + _origin_type: &OriginKind, _require_weight_at_most: &u64, _call: &DoubleEncoded, ) -> Weight { diff --git a/xcm/xcm-builder/src/tests/bridging/local_para_para.rs b/xcm/xcm-builder/src/tests/bridging/local_para_para.rs index 7087d2178869..396aa81d792f 100644 --- a/xcm/xcm-builder/src/tests/bridging/local_para_para.rs +++ b/xcm/xcm-builder/src/tests/bridging/local_para_para.rs @@ -41,9 +41,8 @@ type Router = LocalUnpaidExporter, Un #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1)).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, (Here, 100).into()); assert_eq!(TheBridge::service(), 1); assert_eq!( take_received_remote_messages(), @@ -71,9 +70,8 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_parachain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, (Here, 100).into()); assert_eq!(TheBridge::service(), 1); let expected = vec![( (Parent, Parachain(1000)).into(), @@ -99,9 +97,8 @@ fn sending_to_parachain_of_bridged_chain_works() { #[test] fn sending_to_relay_chain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get()).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, (Here, 100).into()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parent.into(), diff --git a/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs b/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs index 4c76b4589e30..7fd5de2b2719 100644 --- a/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs @@ -37,10 +37,9 @@ type Router = LocalUnpaidExporter, Un #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); assert_eq!( - send_xcm::((Parent, Remote::get()).into(), msg), - Ok((hash, (Here, 100).into())) + send_xcm::((Parent, Remote::get()).into(), msg).unwrap().1, + (Here, 100).into() ); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -62,9 +61,8 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_parachain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, (Here, 100).into()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, (Here, 100).into()); assert_eq!(TheBridge::service(), 1); let expected = vec![(Parachain(1000).into(), Xcm(vec![UniversalOrigin(Local::get().into()), Trap(1)]))]; diff --git a/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs b/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs index 6afe447c2877..2b0ad6c4f431 100644 --- a/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs @@ -66,8 +66,7 @@ fn sending_to_bridged_chain_works() { add_asset(Parachain(100), (Here, 1000)); let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); - assert_eq!(send_xcm::(dest, msg), Ok((hash, (Parent, 150).into()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, (Parent, 150).into()); assert_eq!(TheBridge::service(), 1); assert_eq!( take_received_remote_messages(), @@ -108,8 +107,7 @@ fn sending_to_parachain_of_bridged_chain_works() { add_asset(Parachain(100), (Here, 1000)); let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); - assert_eq!(send_xcm::(dest, msg), Ok((hash, (Parent, 150).into()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, (Parent, 150).into()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parachain(100).into(), diff --git a/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs b/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs index 485b207e9b4c..50a4ea8f3f70 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs @@ -49,10 +49,9 @@ type LocalRouter = (LocalInnerRouter, LocalBridgingRouter); #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); assert_eq!( - send_xcm::((Parent, Parent, Remote::get(), Parachain(1)).into(), msg), - Ok((hash, MultiAssets::new())) + send_xcm::((Parent, Parent, Remote::get(), Parachain(1)).into(), msg).unwrap().1, + MultiAssets::new() ); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -81,9 +80,8 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_sibling_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( (Parent, Parachain(1000)).into(), @@ -109,9 +107,8 @@ fn sending_to_sibling_of_bridged_chain_works() { #[test] fn sending_to_relay_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get()).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parent.into(), diff --git a/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs b/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs index e50f2d9c1cf3..cb7e85ef2480 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs @@ -49,10 +49,9 @@ type LocalRouter = (LocalInnerRouter, LocalBridgingRouter); #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); assert_eq!( - send_xcm::((Parent, Remote::get(), Parachain(1)).into(), msg), - Ok((hash, MultiAssets::new())) + send_xcm::((Parent, Remote::get(), Parachain(1)).into(), msg).unwrap().1, + MultiAssets::new() ); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -74,9 +73,8 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_sibling_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( (Parent, Parachain(1000)).into(), @@ -98,9 +96,8 @@ fn sending_to_sibling_of_bridged_chain_works() { #[test] fn sending_to_relay_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Remote::get()).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![(Parent.into(), Xcm(vec![UniversalOrigin(Local::get().into()), Trap(1)]))]; assert_eq!(take_received_remote_messages(), expected); diff --git a/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs b/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs index 4b791eb5737e..83cc0ac78096 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs @@ -49,10 +49,9 @@ type LocalRouter = (LocalInnerRouter, LocalBridgeRouter); #[test] fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); assert_eq!( - send_xcm::((Parent, Parent, Remote::get()).into(), msg), - Ok((hash, MultiAssets::new())) + send_xcm::((Parent, Parent, Remote::get()).into(), msg).unwrap().1, + MultiAssets::new() ); assert_eq!(TheBridge::service(), 1); assert_eq!( @@ -81,9 +80,8 @@ fn sending_to_bridged_chain_works() { #[test] fn sending_to_parachain_of_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); - let hash = fake_message_hash(&msg); let dest = (Parent, Parent, Remote::get(), Parachain(1000)).into(); - assert_eq!(send_xcm::(dest, msg), Ok((hash, MultiAssets::new()))); + assert_eq!(send_xcm::(dest, msg).unwrap().1, MultiAssets::new()); assert_eq!(TheBridge::service(), 1); let expected = vec![( Parachain(1000).into(), From 84b3f98597b6c1276d75f45dc035c58b2009593f Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Mon, 7 Mar 2022 17:37:33 +0100 Subject: [PATCH 69/73] Formatting --- xcm/xcm-builder/src/tests/bridging/remote_para_para.rs | 4 +++- .../src/tests/bridging/remote_para_para_via_relay.rs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs b/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs index 50a4ea8f3f70..648807763b2a 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs @@ -50,7 +50,9 @@ type LocalRouter = (LocalInnerRouter, LocalBridgingRouter); fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); assert_eq!( - send_xcm::((Parent, Parent, Remote::get(), Parachain(1)).into(), msg).unwrap().1, + send_xcm::((Parent, Parent, Remote::get(), Parachain(1)).into(), msg) + .unwrap() + .1, MultiAssets::new() ); assert_eq!(TheBridge::service(), 1); diff --git a/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs b/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs index cb7e85ef2480..0a6e0bfb73dd 100644 --- a/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs +++ b/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs @@ -50,7 +50,9 @@ type LocalRouter = (LocalInnerRouter, LocalBridgingRouter); fn sending_to_bridged_chain_works() { let msg = Xcm(vec![Trap(1)]); assert_eq!( - send_xcm::((Parent, Remote::get(), Parachain(1)).into(), msg).unwrap().1, + send_xcm::((Parent, Remote::get(), Parachain(1)).into(), msg) + .unwrap() + .1, MultiAssets::new() ); assert_eq!(TheBridge::service(), 1); From 46bda6320ac8fb9c381fd04f68a916a277b2eefe Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 8 Mar 2022 11:44:19 +0100 Subject: [PATCH 70/73] Use message hash for greater identifiability --- xcm/xcm-builder/src/universal_exports.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/xcm/xcm-builder/src/universal_exports.rs b/xcm/xcm-builder/src/universal_exports.rs index 3eb11148e955..1e0869801812 100644 --- a/xcm/xcm-builder/src/universal_exports.rs +++ b/xcm/xcm-builder/src/universal_exports.rs @@ -331,14 +331,14 @@ pub struct HaulBlobExporter( impl, Price: Get> ExportXcm for HaulBlobExporter { - type Ticket = Vec; + type Ticket = (Vec, XcmHash); fn validate( network: NetworkId, _channel: u32, destination: &mut Option, message: &mut Option>, - ) -> Result<(Vec, MultiAssets), SendError> { + ) -> Result<((Vec, XcmHash), MultiAssets), SendError> { let bridged_network = BridgedNetwork::get(); ensure!(&network == &bridged_network, SendError::NotApplicable); // We don't/can't use the `channel` for this adapter. @@ -351,12 +351,12 @@ impl, Price: Get> }, }; let message = VersionedXcm::from(message.take().ok_or(SendError::MissingArgument)?); + let hash = message.using_encoded(sp_io::hashing::blake2_256); let blob = BridgeMessage { universal_dest, message }.encode(); - Ok((blob, Price::get())) + Ok(((blob, hash), Price::get())) } - fn deliver(blob: Vec) -> Result { - let hash = sp_io::hashing::blake2_256(&blob[..]); + fn deliver((blob, hash): (Vec, XcmHash)) -> Result { Bridge::haul_blob(blob); Ok(hash) } From d1876fb7f07811f2d4f751d1c393053cfa9d6f0d Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 8 Mar 2022 11:59:27 +0100 Subject: [PATCH 71/73] Formatting --- xcm/xcm-builder/src/fungibles_adapter.rs | 8 ++++++-- xcm/xcm-builder/src/tests/locking.rs | 9 ++++++--- xcm/xcm-builder/src/tests/origins.rs | 6 ++++-- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/xcm/xcm-builder/src/fungibles_adapter.rs b/xcm/xcm-builder/src/fungibles_adapter.rs index 3a8a551e761b..be8e9d27cfaa 100644 --- a/xcm/xcm-builder/src/fungibles_adapter.rs +++ b/xcm/xcm-builder/src/fungibles_adapter.rs @@ -17,7 +17,7 @@ //! Adapters to work with `frame_support::traits::tokens::fungibles` through XCM. use frame_support::traits::{tokens::fungibles, Contains, Get}; -use sp_std::{prelude::*, result, marker::PhantomData}; +use sp_std::{marker::PhantomData, prelude::*, result}; use xcm::latest::prelude::*; use xcm_executor::traits::{Convert, Error as MatchError, MatchesFungibles, TransactAsset}; @@ -79,7 +79,11 @@ impl< CheckingAccount, > { - fn can_check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) -> XcmResult { + fn can_check_in( + _origin: &MultiLocation, + what: &MultiAsset, + _context: &XcmContext, + ) -> XcmResult { log::trace!( target: "xcm::fungibles_adapter", "can_check_in origin: {:?}, what: {:?}", diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index 40d5433c22db..f5f80409ef78 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -53,7 +53,8 @@ fn lock_roundtrip_should_work() { ); // Now we'll unlock it. - let message = Xcm(vec![UnlockAsset { asset: (Parent, 100u128).into(), target: (3u64,).into() }]); + let message = + Xcm(vec![UnlockAsset { asset: (Parent, 100u128).into(), target: (3u64,).into() }]); let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); @@ -124,7 +125,8 @@ fn remote_unlock_roundtrip_should_work() { set_send_price((Parent, 10u128)); // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. - let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100u128).into(), owner: (3u64,).into() }]); + let message = + Xcm(vec![NoteUnlockable { asset: (Parent, 100u128).into(), owner: (3u64,).into() }]); let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); @@ -185,7 +187,8 @@ fn remote_unlock_should_fail_correctly() { assert_eq!(take_lock_trace(), vec![]); // We have been told by Parachain #1 that Account #3 has locked funds which we can unlock. - let message = Xcm(vec![NoteUnlockable { asset: (Parent, 100u128).into(), owner: (3u64,).into() }]); + let message = + Xcm(vec![NoteUnlockable { asset: (Parent, 100u128).into(), owner: (3u64,).into() }]); let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm((Parent, Parachain(1)), message, hash, 50); assert_eq!(r, Outcome::Complete(10)); diff --git a/xcm/xcm-builder/src/tests/origins.rs b/xcm/xcm-builder/src/tests/origins.rs index b88093cc21e9..9b75c4f98650 100644 --- a/xcm/xcm-builder/src/tests/origins.rs +++ b/xcm/xcm-builder/src/tests/origins.rs @@ -58,8 +58,10 @@ fn export_message_should_work() { AllowUnpaidFrom::set(vec![X1(Parachain(1)).into()]); // Local parachain #1 issues a transfer asset on Polkadot Relay-chain, transfering 100 Planck to // Polkadot parachain #2. - let expected_message = - Xcm(vec![TransferAsset { assets: (Here, 100u128).into(), beneficiary: Parachain(2).into() }]); + let expected_message = Xcm(vec![TransferAsset { + assets: (Here, 100u128).into(), + beneficiary: Parachain(2).into(), + }]); let expected_hash = fake_message_hash(&expected_message); let message = Xcm(vec![ExportMessage { network: Polkadot, From c7143c9af01b43a0798b3062859a6303d09852bb Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 8 Mar 2022 12:20:49 +0100 Subject: [PATCH 72/73] Fixes --- xcm/xcm-builder/src/tests/locking.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index f5f80409ef78..4102913d8dcb 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -40,7 +40,7 @@ fn lock_roundtrip_should_work() { assert_eq!(asset_list((3u64,)), vec![(Parent, 990u128).into()]); let expected_msg = - Xcm::<()>(vec![NoteUnlockable { owner: (3u64,).into(), asset: (Parent, 100u128).into() }]); + Xcm::<()>(vec![NoteUnlockable { owner: (Parent, Parachain(42), 3u64).into(), asset: (Parent, 100u128).into() }]); let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![((Parent, Parachain(1)).into(), expected_msg, expected_hash)]); assert_eq!( From a2b16867f3cbed456e83929e4e08d9225db6f946 Mon Sep 17 00:00:00 2001 From: Gav Wood Date: Tue, 8 Mar 2022 12:21:01 +0100 Subject: [PATCH 73/73] Formatting --- xcm/xcm-builder/src/tests/locking.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/xcm/xcm-builder/src/tests/locking.rs b/xcm/xcm-builder/src/tests/locking.rs index 4102913d8dcb..9f58936faa39 100644 --- a/xcm/xcm-builder/src/tests/locking.rs +++ b/xcm/xcm-builder/src/tests/locking.rs @@ -39,8 +39,10 @@ fn lock_roundtrip_should_work() { assert_eq!(r, Outcome::Complete(40)); assert_eq!(asset_list((3u64,)), vec![(Parent, 990u128).into()]); - let expected_msg = - Xcm::<()>(vec![NoteUnlockable { owner: (Parent, Parachain(42), 3u64).into(), asset: (Parent, 100u128).into() }]); + let expected_msg = Xcm::<()>(vec![NoteUnlockable { + owner: (Parent, Parachain(42), 3u64).into(), + asset: (Parent, 100u128).into(), + }]); let expected_hash = fake_message_hash(&expected_msg); assert_eq!(sent_xcm(), vec![((Parent, Parachain(1)).into(), expected_msg, expected_hash)]); assert_eq!(