git.delta.rocks / unique-network / refs/commits / 5a619a936664

difftreelog

fix(xcm) improve denythentry, deny transact xcm

Daniel Shiposha2022-08-30parent: #247c0b0.patch.diff
in: master

8 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4572,6 +4572,16 @@
 ]
 
 [[package]]
+name = "logtest"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb3e43a8657c1d64516dcc9db8ca03826a4aceaf89d5ce1b37b59f6ff0e43026"
+dependencies = [
+ "lazy_static",
+ "log",
+]
+
+[[package]]
 name = "lru"
 version = "0.6.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -5148,7 +5158,9 @@
  "frame-system-rpc-runtime-api",
  "frame-try-runtime",
  "hex-literal",
+ "impl-trait-for-tuples",
  "log",
+ "logtest",
  "orml-tokens",
  "orml-traits",
  "orml-vesting",
@@ -8466,7 +8478,9 @@
  "frame-system-rpc-runtime-api",
  "frame-try-runtime",
  "hex-literal",
+ "impl-trait-for-tuples",
  "log",
+ "logtest",
  "orml-tokens",
  "orml-traits",
  "orml-vesting",
@@ -12206,7 +12220,7 @@
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675"
 dependencies = [
- "cfg-if 0.1.10",
+ "cfg-if 1.0.0",
  "digest 0.10.3",
  "rand 0.8.5",
  "static_assertions",
@@ -12459,7 +12473,9 @@
  "frame-system-rpc-runtime-api",
  "frame-try-runtime",
  "hex-literal",
+ "impl-trait-for-tuples",
  "log",
+ "logtest",
  "orml-tokens",
  "orml-traits",
  "orml-vesting",
modifiedruntime/common/config/xcm.rsdiffbeforeafterboth
before · runtime/common/config/xcm.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use frame_support::{18	traits::{19		Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get,20		Everything, fungibles,21	},22	weights::{Weight, WeightToFeePolynomial, WeightToFee},23	parameter_types, match_types,24};25use frame_system::EnsureRoot;26use sp_runtime::{27	traits::{Saturating, CheckedConversion, Zero},28	SaturatedConversion,29};30use pallet_xcm::XcmPassthrough;31use polkadot_parachain::primitives::Sibling;32use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};33use xcm::latest::{34	AssetId::{Concrete},35	Fungibility::Fungible as XcmFungible,36	MultiAsset, Error as XcmError, Instruction, Xcm,37};38use xcm_builder::{39	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40	FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser,41	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,42	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,43	ParentIsPreset, ConvertedConcreteAssetId,44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{47	Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,48	ShouldExecute,49};50use pallet_foreing_assets::{51	AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,52	TryAsForeing, ForeignAssetId,53};54use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};55use crate::{56	Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,57	xcm_config::Barrier,58};59#[cfg(feature = "foreign-assets")]60use crate::ForeingAssets;6162use up_common::{63	types::{AccountId, Balance},64	constants::*,65};6667parameter_types! {68	pub const RelayLocation: MultiLocation = MultiLocation::parent();69	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;70	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();71	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();72}7374/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used75/// when determining ownership of accounts for asset transacting and when attempting to use XCM76/// `Transact` in order to determine the dispatch Origin.77pub type LocationToAccountId = (78	// The parent (Relay-chain) origin converts to the default `AccountId`.79	ParentIsPreset<AccountId>,80	// Sibling parachain origins convert to AccountId via the `ParaId::into`.81	SiblingParachainConvertsVia<Sibling, AccountId>,82	// Straight up local `AccountId32` origins just alias directly to `AccountId`.83	AccountId32Aliases<RelayNetwork, AccountId>,84);8586pub struct OnlySelfCurrency;87impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {88	fn matches_fungible(a: &MultiAsset) -> Option<B> {89		let paraid = Parachain(ParachainInfo::parachain_id().into());90		match (&a.id, &a.fun) {91			(92				Concrete(MultiLocation {93					parents: 1,94					interior: X1(loc),95				}),96				XcmFungible(ref amount),97			) if paraid == *loc => CheckedConversion::checked_from(*amount),98			(99				Concrete(MultiLocation {100					parents: 0,101					interior: Here,102				}),103				XcmFungible(ref amount),104			) => CheckedConversion::checked_from(*amount),105			_ => None,106		}107	}108}109110/// Means for transacting assets on this chain.111pub type LocalAssetTransactor = CurrencyAdapter<112	// Use this currency:113	Balances,114	// Use this currency when it is a fungible asset matching the given location or name:115	OnlySelfCurrency,116	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:117	LocationToAccountId,118	// Our chain's account ID type (we can't get away without mentioning it explicitly):119	AccountId,120	// We don't track any teleports.121	(),122>;123124/// No local origins on this chain are allowed to dispatch XCM sends/executions.125pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);126127/// The means for routing XCM messages which are not for local execution into the right message128/// queues.129pub type XcmRouter = (130	// Two routers - use UMP to communicate with the relay chain:131	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,132	// ..and XCMP to communicate with the sibling chains.133	XcmpQueue,134);135136/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,137/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can138/// biases the kind of local `Origin` it will become.139pub type XcmOriginToTransactDispatchOrigin = (140	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location141	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for142	// foreign chains who want to have a local sovereign account on this chain which they control.143	SovereignSignedViaLocation<LocationToAccountId, Origin>,144	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when145	// recognised.146	RelayChainAsNative<RelayOrigin, Origin>,147	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when148	// recognised.149	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,150	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a151	// transaction from the Root origin.152	ParentAsSuperuser<Origin>,153	// Native signed account converter; this just converts an `AccountId32` origin into a normal154	// `Origin::Signed` origin of the same 32-byte value.155	SignedAccountId32AsNative<RelayNetwork, Origin>,156	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.157	XcmPassthrough<Origin>,158);159160parameter_types! {161	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.162	pub UnitWeightCost: Weight = 1_000_000;163	// 1200 UNIQUEs buy 1 second of weight.164	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);165	pub const MaxInstructions: u32 = 100;166}167168match_types! {169	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {170		MultiLocation { parents: 1, interior: Here } |171		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }172	};173}174175pub struct DenyTransact;176impl ShouldExecute for DenyTransact {177	fn should_execute<Call>(178		_origin: &MultiLocation,179		message: &mut Xcm<Call>,180		_max_weight: Weight,181		_weight_credit: &mut Weight,182	) -> Result<(), ()> {183		let transact_inst = message184			.0185			.iter()186			.find(|inst| matches![inst, Instruction::Transact { .. }]);187188		match transact_inst {189			Some(_) => {190				log::warn!(191					target: "xcm::barrier",192					"transact XCM rejected"193				);194195				Err(())196			}197			None => Ok(()),198		}199	}200}201202/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.203/// If it passes the Deny, and matches one of the Allow cases then it is let through.204pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)205where206	Deny: ShouldExecute,207	Allow: ShouldExecute;208209impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>210where211	Deny: ShouldExecute,212	Allow: ShouldExecute,213{214	fn should_execute<Call>(215		origin: &MultiLocation,216		message: &mut Xcm<Call>,217		max_weight: Weight,218		weight_credit: &mut Weight,219	) -> Result<(), ()> {220		Deny::should_execute(origin, message, max_weight, weight_credit)?;221		Allow::should_execute(origin, message, max_weight, weight_credit)222	}223}224225pub struct UsingOnlySelfCurrencyComponents<226	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,227	AssetId: Get<MultiLocation>,228	AccountId,229	Currency: CurrencyT<AccountId>,230	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,231>(232	Weight,233	Currency::Balance,234	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,235);236impl<237		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,238		AssetId: Get<MultiLocation>,239		AccountId,240		Currency: CurrencyT<AccountId>,241		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,242	> WeightTrader243	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>244{245	fn new() -> Self {246		Self(0, Zero::zero(), PhantomData)247	}248249	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {250		Ok(payment)251	}252}253impl<254		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,255		AssetId: Get<MultiLocation>,256		AccountId,257		Currency: CurrencyT<AccountId>,258		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,259	> Drop260	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>261{262	fn drop(&mut self) {263		OnUnbalanced::on_unbalanced(Currency::issue(self.1));264	}265}266267parameter_types! {268	pub CheckingAccount: AccountId = PolkadotXcm::check_account();269}270/// Allow checking in assets that have issuance > 0.271#[cfg(feature = "foreign-assets")]272pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);273274#[cfg(feature = "foreign-assets")]275impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>276	for NonZeroIssuance<AccountId, ForeingAssets>277where278	ForeingAssets: fungibles::Inspect<AccountId>,279{280	fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {281		!ForeingAssets::total_issuance(*id).is_zero()282	}283}284285#[cfg(feature = "foreign-assets")]286pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);287#[cfg(feature = "foreign-assets")]288impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>289	ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>290where291	AssetId: Borrow<AssetId>,292	AssetId: TryAsForeing<AssetId, ForeignAssetId>,293	AssetIds: Borrow<AssetId>,294{295	fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {296		let id = id.borrow();297298		log::trace!(299			target: "xcm::AsInnerId::Convert",300			"AsInnerId {:?}",301			id302		);303304		let parent = MultiLocation::parent();305		let here = MultiLocation::here();306		let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));307308		if *id == parent {309			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));310		}311312		if *id == here || *id == self_location {313			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));314		}315316		match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {317			Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {318				ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))319			}320			_ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),321		}322	}323324	fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {325		log::trace!(326			target: "xcm::AsInnerId::Reverse",327			"AsInnerId",328		);329330		let asset_id = what.borrow();331332		let parent_id =333			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();334		let here_id =335			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();336337		if asset_id.clone() == parent_id {338			return Ok(MultiLocation::parent());339		}340341		if asset_id.clone() == here_id {342			return Ok(MultiLocation::new(343				1,344				X1(Parachain(ParachainInfo::get().into())),345			));346		}347348		match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {349			Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {350				Some(location) => Ok(location),351				None => Err(()),352			},353			None => Err(()),354		}355	}356}357358/// Means for transacting assets besides the native currency on this chain.359#[cfg(feature = "foreign-assets")]360pub type FungiblesTransactor = FungiblesAdapter<361	// Use this fungibles implementation:362	ForeingAssets,363	// Use this currency when it is a fungible asset matching the given location or name:364	ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,365	// Convert an XCM MultiLocation into a local account id:366	LocationToAccountId,367	// Our chain's account ID type (we can't get away without mentioning it explicitly):368	AccountId,369	// We only want to allow teleports of known assets. We use non-zero issuance as an indication370	// that this asset is known.371	NonZeroIssuance<AccountId, ForeingAssets>,372	// The account to use for tracking teleports.373	CheckingAccount,374>;375376/// Means for transacting assets on this chain.377#[cfg(feature = "foreign-assets")]378pub type AssetTransactors = FungiblesTransactor;379380#[cfg(not(feature = "foreign-assets"))]381pub type AssetTransactors = LocalAssetTransactor;382383#[cfg(feature = "foreign-assets")]384pub struct AllAsset;385#[cfg(feature = "foreign-assets")]386impl FilterAssetLocation for AllAsset {387	fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {388		true389	}390}391392#[cfg(feature = "foreign-assets")]393pub type IsReserve = AllAsset;394#[cfg(not(feature = "foreign-assets"))]395pub type IsReserve = NativeAsset;396397#[cfg(feature = "foreign-assets")]398type Trader<T> = FreeForAll<399	pallet_configuration::WeightToFee<T, Balance>,400	RelayLocation,401	AccountId,402	Balances,403	(),404>;405#[cfg(not(feature = "foreign-assets"))]406type Trader<T> = UsingOnlySelfCurrencyComponents<407	pallet_configuration::WeightToFee<T, Balance>,408	RelayLocation,409	AccountId,410	Balances,411	(),412>;413414pub struct XcmConfig<T>(PhantomData<T>);415impl<T> Config for XcmConfig<T>416where417	T: pallet_configuration::Config,418{419	type Call = Call;420	type XcmSender = XcmRouter;421	// How to withdraw and deposit an asset.422	type AssetTransactor = AssetTransactors;423	type OriginConverter = XcmOriginToTransactDispatchOrigin;424	type IsReserve = IsReserve;425	type IsTeleporter = (); // Teleportation is disabled426	type LocationInverter = LocationInverter<Ancestry>;427	type Barrier = Barrier;428	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;429	type Trader = Trader<T>;430	type ResponseHandler = (); // Don't handle responses for now.431	type SubscriptionService = PolkadotXcm;432433	type AssetTrap = PolkadotXcm;434	type AssetClaims = PolkadotXcm;435}436437impl pallet_xcm::Config for Runtime {438	type Event = Event;439	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;440	type XcmRouter = XcmRouter;441	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;442	type XcmExecuteFilter = Everything;443	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;444	type XcmTeleportFilter = Everything;445	type XcmReserveTransferFilter = Everything;446	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;447	type LocationInverter = LocationInverter<Ancestry>;448	type Origin = Origin;449	type Call = Call;450	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;451	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;452}453454impl cumulus_pallet_xcm::Config for Runtime {455	type Event = Event;456	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;457}458459impl cumulus_pallet_xcmp_queue::Config for Runtime {460	type WeightInfo = ();461	type Event = Event;462	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;463	type ChannelInfo = ParachainSystem;464	type VersionWrapper = ();465	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;466	type ControllerOrigin = EnsureRoot<AccountId>;467	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;468}469470impl cumulus_pallet_dmp_queue::Config for Runtime {471	type Event = Event;472	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;473	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;474}
after · runtime/common/config/xcm.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use frame_support::{18	traits::{19		Contains, tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get,20		Everything, fungibles,21	},22	weights::{Weight, WeightToFeePolynomial, WeightToFee},23	parameter_types, match_types,24};25use frame_system::EnsureRoot;26use sp_runtime::{27	traits::{Saturating, CheckedConversion, Zero},28	SaturatedConversion,29};30use pallet_xcm::XcmPassthrough;31use polkadot_parachain::primitives::Sibling;32use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};33use xcm::latest::{34	AssetId::{Concrete},35	Fungibility::Fungible as XcmFungible,36	MultiAsset, Error as XcmError, Instruction, Xcm,37};38use xcm_builder::{39	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40	FixedWeightBounds, FungiblesAdapter, LocationInverter, NativeAsset, ParentAsSuperuser,41	RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,42	SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,43	ParentIsPreset, ConvertedConcreteAssetId,44};45use xcm_executor::{Config, XcmExecutor, Assets};46use xcm_executor::traits::{47	Convert as ConvertXcm, JustTry, MatchesFungible, WeightTrader, FilterAssetLocation,48	ShouldExecute,49};50use pallet_foreing_assets::{51	AssetIds, AssetIdMapping, XcmForeignAssetIdMapping, CurrencyId, NativeCurrency, FreeForAll,52	TryAsForeing, ForeignAssetId,53};54use sp_std::{borrow::Borrow, marker::PhantomData, vec, vec::Vec};55use crate::{56	Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,57	xcm_config::Barrier,58};59#[cfg(feature = "foreign-assets")]60use crate::ForeingAssets;6162use up_common::{63	types::{AccountId, Balance},64	constants::*,65};6667parameter_types! {68	pub const RelayLocation: MultiLocation = MultiLocation::parent();69	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;70	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();71	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();72}7374/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used75/// when determining ownership of accounts for asset transacting and when attempting to use XCM76/// `Transact` in order to determine the dispatch Origin.77pub type LocationToAccountId = (78	// The parent (Relay-chain) origin converts to the default `AccountId`.79	ParentIsPreset<AccountId>,80	// Sibling parachain origins convert to AccountId via the `ParaId::into`.81	SiblingParachainConvertsVia<Sibling, AccountId>,82	// Straight up local `AccountId32` origins just alias directly to `AccountId`.83	AccountId32Aliases<RelayNetwork, AccountId>,84);8586pub struct OnlySelfCurrency;87impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {88	fn matches_fungible(a: &MultiAsset) -> Option<B> {89		let paraid = Parachain(ParachainInfo::parachain_id().into());90		match (&a.id, &a.fun) {91			(92				Concrete(MultiLocation {93					parents: 1,94					interior: X1(loc),95				}),96				XcmFungible(ref amount),97			) if paraid == *loc => CheckedConversion::checked_from(*amount),98			(99				Concrete(MultiLocation {100					parents: 0,101					interior: Here,102				}),103				XcmFungible(ref amount),104			) => CheckedConversion::checked_from(*amount),105			_ => None,106		}107	}108}109110/// Means for transacting assets on this chain.111pub type LocalAssetTransactor = CurrencyAdapter<112	// Use this currency:113	Balances,114	// Use this currency when it is a fungible asset matching the given location or name:115	OnlySelfCurrency,116	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:117	LocationToAccountId,118	// Our chain's account ID type (we can't get away without mentioning it explicitly):119	AccountId,120	// We don't track any teleports.121	(),122>;123124/// No local origins on this chain are allowed to dispatch XCM sends/executions.125pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);126127/// The means for routing XCM messages which are not for local execution into the right message128/// queues.129pub type XcmRouter = (130	// Two routers - use UMP to communicate with the relay chain:131	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,132	// ..and XCMP to communicate with the sibling chains.133	XcmpQueue,134);135136/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,137/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can138/// biases the kind of local `Origin` it will become.139pub type XcmOriginToTransactDispatchOrigin = (140	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location141	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for142	// foreign chains who want to have a local sovereign account on this chain which they control.143	SovereignSignedViaLocation<LocationToAccountId, Origin>,144	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when145	// recognised.146	RelayChainAsNative<RelayOrigin, Origin>,147	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when148	// recognised.149	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,150	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a151	// transaction from the Root origin.152	ParentAsSuperuser<Origin>,153	// Native signed account converter; this just converts an `AccountId32` origin into a normal154	// `Origin::Signed` origin of the same 32-byte value.155	SignedAccountId32AsNative<RelayNetwork, Origin>,156	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.157	XcmPassthrough<Origin>,158);159160parameter_types! {161	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.162	pub UnitWeightCost: Weight = 1_000_000;163	// 1200 UNIQUEs buy 1 second of weight.164	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);165	pub const MaxInstructions: u32 = 100;166}167168match_types! {169	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {170		MultiLocation { parents: 1, interior: Here } |171		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }172	};173}174175pub trait TryPass {176	fn try_pass<Call>(177		origin: &MultiLocation,178		message: &mut Xcm<Call>,179	) -> Result<(), ()>;180}181182#[impl_trait_for_tuples::impl_for_tuples(30)]183impl TryPass for Tuple {184	fn try_pass<Call>(185		origin: &MultiLocation,186		message: &mut Xcm<Call>,187	)  -> Result<(), ()> {188		for_tuples!( #(189			Tuple::try_pass(origin, message)?;190		)* );191192		Ok(())193	}194}195196pub struct DenyTransact;197impl TryPass for DenyTransact {198	fn try_pass<Call>(199		_origin: &MultiLocation,200		message: &mut Xcm<Call>,201	) -> Result<(), ()> {202		let transact_inst = message203			.0204			.iter()205			.find(|inst| matches![inst, Instruction::Transact { .. }]);206207		match transact_inst {208			Some(_) => {209				log::warn!(210					target: "xcm::barrier",211					"transact XCM rejected"212				);213214				Err(())215			}216			None => Ok(()),217		}218	}219}220221/// Deny executing the XCM if it matches any of the Deny filter regardless of anything else.222/// If it passes the Deny, and matches one of the Allow cases then it is let through.223pub struct DenyThenTry<Deny, Allow>(PhantomData<Deny>, PhantomData<Allow>)224where225	Deny: TryPass,226	Allow: ShouldExecute;227228impl<Deny, Allow> ShouldExecute for DenyThenTry<Deny, Allow>229where230	Deny: TryPass,231	Allow: ShouldExecute,232{233	fn should_execute<Call>(234		origin: &MultiLocation,235		message: &mut Xcm<Call>,236		max_weight: Weight,237		weight_credit: &mut Weight,238	) -> Result<(), ()> {239		Deny::try_pass(origin, message)?;240		Allow::should_execute(origin, message, max_weight, weight_credit)241	}242}243244pub struct UsingOnlySelfCurrencyComponents<245	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,246	AssetId: Get<MultiLocation>,247	AccountId,248	Currency: CurrencyT<AccountId>,249	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,250>(251	Weight,252	Currency::Balance,253	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,254);255impl<256		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,257		AssetId: Get<MultiLocation>,258		AccountId,259		Currency: CurrencyT<AccountId>,260		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,261	> WeightTrader262	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>263{264	fn new() -> Self {265		Self(0, Zero::zero(), PhantomData)266	}267268	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {269		Ok(payment)270	}271}272impl<273		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,274		AssetId: Get<MultiLocation>,275		AccountId,276		Currency: CurrencyT<AccountId>,277		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,278	> Drop279	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>280{281	fn drop(&mut self) {282		OnUnbalanced::on_unbalanced(Currency::issue(self.1));283	}284}285286parameter_types! {287	pub CheckingAccount: AccountId = PolkadotXcm::check_account();288}289/// Allow checking in assets that have issuance > 0.290#[cfg(feature = "foreign-assets")]291pub struct NonZeroIssuance<AccountId, ForeingAssets>(PhantomData<(AccountId, ForeingAssets)>);292293#[cfg(feature = "foreign-assets")]294impl<AccountId, ForeingAssets> Contains<<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId>295	for NonZeroIssuance<AccountId, ForeingAssets>296where297	ForeingAssets: fungibles::Inspect<AccountId>,298{299	fn contains(id: &<ForeingAssets as fungibles::Inspect<AccountId>>::AssetId) -> bool {300		!ForeingAssets::total_issuance(*id).is_zero()301	}302}303304#[cfg(feature = "foreign-assets")]305pub struct AsInnerId<AssetId, ConvertAssetId>(PhantomData<(AssetId, ConvertAssetId)>);306#[cfg(feature = "foreign-assets")]307impl<AssetId: Clone + PartialEq, ConvertAssetId: ConvertXcm<AssetId, AssetId>>308	ConvertXcm<MultiLocation, AssetId> for AsInnerId<AssetId, ConvertAssetId>309where310	AssetId: Borrow<AssetId>,311	AssetId: TryAsForeing<AssetId, ForeignAssetId>,312	AssetIds: Borrow<AssetId>,313{314	fn convert_ref(id: impl Borrow<MultiLocation>) -> Result<AssetId, ()> {315		let id = id.borrow();316317		log::trace!(318			target: "xcm::AsInnerId::Convert",319			"AsInnerId {:?}",320			id321		);322323		let parent = MultiLocation::parent();324		let here = MultiLocation::here();325		let self_location = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));326327		if *id == parent {328			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent));329		}330331		if *id == here || *id == self_location {332			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));333		}334335		match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {336			Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {337				ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))338			}339			_ => ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(0)),340		}341	}342343	fn reverse_ref(what: impl Borrow<AssetId>) -> Result<MultiLocation, ()> {344		log::trace!(345			target: "xcm::AsInnerId::Reverse",346			"AsInnerId",347		);348349		let asset_id = what.borrow();350351		let parent_id =352			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Parent)).unwrap();353		let here_id =354			ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here)).unwrap();355356		if asset_id.clone() == parent_id {357			return Ok(MultiLocation::parent());358		}359360		if asset_id.clone() == here_id {361			return Ok(MultiLocation::new(362				1,363				X1(Parachain(ParachainInfo::get().into())),364			));365		}366367		match <AssetId as TryAsForeing<AssetId, ForeignAssetId>>::try_as_foreing(asset_id.clone()) {368			Some(fid) => match XcmForeignAssetIdMapping::<Runtime>::get_multi_location(fid) {369				Some(location) => Ok(location),370				None => Err(()),371			},372			None => Err(()),373		}374	}375}376377/// Means for transacting assets besides the native currency on this chain.378#[cfg(feature = "foreign-assets")]379pub type FungiblesTransactor = FungiblesAdapter<380	// Use this fungibles implementation:381	ForeingAssets,382	// Use this currency when it is a fungible asset matching the given location or name:383	ConvertedConcreteAssetId<AssetIds, Balance, AsInnerId<AssetIds, JustTry>, JustTry>,384	// Convert an XCM MultiLocation into a local account id:385	LocationToAccountId,386	// Our chain's account ID type (we can't get away without mentioning it explicitly):387	AccountId,388	// We only want to allow teleports of known assets. We use non-zero issuance as an indication389	// that this asset is known.390	NonZeroIssuance<AccountId, ForeingAssets>,391	// The account to use for tracking teleports.392	CheckingAccount,393>;394395/// Means for transacting assets on this chain.396#[cfg(feature = "foreign-assets")]397pub type AssetTransactors = FungiblesTransactor;398399#[cfg(not(feature = "foreign-assets"))]400pub type AssetTransactors = LocalAssetTransactor;401402#[cfg(feature = "foreign-assets")]403pub struct AllAsset;404#[cfg(feature = "foreign-assets")]405impl FilterAssetLocation for AllAsset {406	fn filter_asset_location(asset: &MultiAsset, origin: &MultiLocation) -> bool {407		true408	}409}410411#[cfg(feature = "foreign-assets")]412pub type IsReserve = AllAsset;413#[cfg(not(feature = "foreign-assets"))]414pub type IsReserve = NativeAsset;415416#[cfg(feature = "foreign-assets")]417type Trader<T> = FreeForAll<418	pallet_configuration::WeightToFee<T, Balance>,419	RelayLocation,420	AccountId,421	Balances,422	(),423>;424#[cfg(not(feature = "foreign-assets"))]425type Trader<T> = UsingOnlySelfCurrencyComponents<426	pallet_configuration::WeightToFee<T, Balance>,427	RelayLocation,428	AccountId,429	Balances,430	(),431>;432433pub struct XcmConfig<T>(PhantomData<T>);434impl<T> Config for XcmConfig<T>435where436	T: pallet_configuration::Config,437{438	type Call = Call;439	type XcmSender = XcmRouter;440	// How to withdraw and deposit an asset.441	type AssetTransactor = AssetTransactors;442	type OriginConverter = XcmOriginToTransactDispatchOrigin;443	type IsReserve = IsReserve;444	type IsTeleporter = (); // Teleportation is disabled445	type LocationInverter = LocationInverter<Ancestry>;446	type Barrier = Barrier;447	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;448	type Trader = Trader<T>;449	type ResponseHandler = (); // Don't handle responses for now.450	type SubscriptionService = PolkadotXcm;451452	type AssetTrap = PolkadotXcm;453	type AssetClaims = PolkadotXcm;454}455456impl pallet_xcm::Config for Runtime {457	type Event = Event;458	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;459	type XcmRouter = XcmRouter;460	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;461	type XcmExecuteFilter = Everything;462	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;463	type XcmTeleportFilter = Everything;464	type XcmReserveTransferFilter = Everything;465	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;466	type LocationInverter = LocationInverter<Ancestry>;467	type Origin = Origin;468	type Call = Call;469	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;470	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;471}472473impl cumulus_pallet_xcm::Config for Runtime {474	type Event = Event;475	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;476}477478impl cumulus_pallet_xcmp_queue::Config for Runtime {479	type WeightInfo = ();480	type Event = Event;481	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;482	type ChannelInfo = ParachainSystem;483	type VersionWrapper = ();484	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;485	type ControllerOrigin = EnsureRoot<AccountId>;486	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;487}488489impl cumulus_pallet_dmp_queue::Config for Runtime {490	type Event = Event;491	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;492	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;493}
modifiedruntime/common/tests/xcm.rsdiffbeforeafterboth
--- a/runtime/common/tests/xcm.rs
+++ b/runtime/common/tests/xcm.rs
@@ -34,7 +34,7 @@
 }
 
 #[test]
-fn xcm_barrier_does_not_allow_transact() {
+fn xcm_barrier_denies_transact() {
     // We have a `AllowTopLevelPaidExecutionFrom` barrier,
     // so an XCM program should start from one of the following commands: 
     // * `WithdrawAsset`
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -463,6 +463,11 @@
 pallet-foreing-assets = { default-features = false, path = "../../pallets/foreing-assets" }
 
 ################################################################################
+# Other Dependencies
+
+impl-trait-for-tuples = "0.2.2"
+
+################################################################################
 # Dev Dependencies
 
 [dev-dependencies.logtest]
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -471,6 +471,11 @@
 pallet-foreing-assets = { default-features = false, path = "../../pallets/foreing-assets" }
 
 ################################################################################
+# Other Dependencies
+
+impl-trait-for-tuples = "0.2.2"
+
+################################################################################
 # Dev Dependencies
 
 [dev-dependencies.logtest]
modifiedruntime/quartz/src/xcm_config.rsdiffbeforeafterboth
--- a/runtime/quartz/src/xcm_config.rs
+++ b/runtime/quartz/src/xcm_config.rs
@@ -41,7 +41,7 @@
 };
 use xcm_executor::{
     {Config, XcmExecutor},
-    traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible, ShouldExecute},
+    traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible},
 };
 
 use up_common::{
@@ -93,12 +93,10 @@
 
 // Allow xcm exchange only with locations in list
 pub struct DenyExchangeWithUnknownLocation;
-impl ShouldExecute for DenyExchangeWithUnknownLocation {
-    fn should_execute<Call>(
+impl TryPass for DenyExchangeWithUnknownLocation {
+    fn try_pass<Call>(
         origin: &MultiLocation,
         message: &mut Xcm<Call>,
-        _max_weight: Weight,
-        _weight_credit: &mut Weight,
     ) -> Result<(), ()> {
 
         // Check if deposit or transfer belongs to allowed parachains
@@ -126,9 +124,11 @@
 }
 
 pub type Barrier = DenyThenTry<
-    DenyExchangeWithUnknownLocation,
     (
         DenyTransact,
+        DenyExchangeWithUnknownLocation,
+    ),
+    (
         TakeWeightCredit,
         AllowTopLevelPaidExecutionFrom<Everything>,
         // Parent and its exec plurality get free execution
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -463,6 +463,11 @@
 pallet-foreing-assets = { default-features = false, path = "../../pallets/foreing-assets" }
 
 ################################################################################
+# Other Dependencies
+
+impl-trait-for-tuples = "0.2.2"
+
+################################################################################
 # Dev Dependencies
 
 [dev-dependencies.logtest]
modifiedruntime/unique/src/xcm_config.rsdiffbeforeafterboth
--- a/runtime/unique/src/xcm_config.rs
+++ b/runtime/unique/src/xcm_config.rs
@@ -41,7 +41,7 @@
 };
 use xcm_executor::{
     {Config, XcmExecutor},
-    traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible, ShouldExecute},
+    traits::{Convert as ConvertXcm, FilterAssetLocation, JustTry, MatchesFungible},
 };
 
 use up_common::{
@@ -67,9 +67,11 @@
 
 
 pub type Barrier = DenyThenTry<
-    DenyExchangeWithUnknownLocation,
     (
         DenyTransact,
+        DenyExchangeWithUnknownLocation,
+    ),
+    (
         TakeWeightCredit,
         AllowTopLevelPaidExecutionFrom<Everything>,
         // Parent and its exec plurality get free execution
@@ -98,12 +100,10 @@
 
 // Allow xcm exchange only with locations in list
 pub struct DenyExchangeWithUnknownLocation;
-impl ShouldExecute for DenyExchangeWithUnknownLocation {
-    fn should_execute<Call>(
+impl TryPass for DenyExchangeWithUnknownLocation {
+    fn try_pass<Call>(
         origin: &MultiLocation,
         message: &mut Xcm<Call>,
-        _max_weight: Weight,
-        _weight_credit: &mut Weight,
     ) -> Result<(), ()> {
 
         // Check if deposit or transfer belongs to allowed parachains