Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add a filter for filtering unsupported MultiLocation #714

Merged
merged 8 commits into from
Mar 20, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 29 additions & 1 deletion xtokens/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@
#![allow(clippy::unused_unit)]
#![allow(clippy::large_enum_variant)]

use frame_support::{log, pallet_prelude::*, require_transactional, traits::Get, transactional, Parameter};
use frame_support::{
log,
pallet_prelude::*,
require_transactional,
traits::{Contains, Get},
transactional, Parameter,
};
use frame_system::{ensure_signed, pallet_prelude::*};
use sp_runtime::{
traits::{AtLeast32BitUnsigned, Convert, MaybeSerializeDeserialize, Member, Zero},
Expand Down Expand Up @@ -88,6 +94,9 @@ pub mod module {
/// XCM executor.
type XcmExecutor: ExecuteXcm<Self::Call>;

/// MultiLocation filter
type MultiLocationsFilter: Contains<MultiLocation>;

/// Means of measuring the weight consumed by an XCM message locally.
type Weigher: WeightBounds<Self::Call>;

Expand Down Expand Up @@ -158,6 +167,8 @@ pub mod module {
AssetIndexNonExistent,
/// Fee is not enough.
FeeNotEnough,
/// Not supported MultiLocation
NotSupportedMultiLocation,
}

#[pallet::hooks]
Expand Down Expand Up @@ -372,6 +383,10 @@ pub mod module {
T::CurrencyIdConvert::convert(currency_id).ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;

ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);
ensure!(
T::MultiLocationsFilter::contains(&dest),
Error::<T>::NotSupportedMultiLocation
);

let asset: MultiAsset = (location, amount.into()).into();
Self::do_transfer_multiassets(who, vec![asset.clone()].into(), asset, dest, dest_weight)
Expand All @@ -390,6 +405,10 @@ pub mod module {

ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);
ensure!(!fee.is_zero(), Error::<T>::ZeroFee);
ensure!(
T::MultiLocationsFilter::contains(&dest),
Error::<T>::NotSupportedMultiLocation
);

let asset = (location.clone(), amount.into()).into();
let fee_asset: MultiAsset = (location, fee.into()).into();
Expand Down Expand Up @@ -439,6 +458,10 @@ pub mod module {
currencies.len() <= T::MaxAssetsForTransfer::get(),
Error::<T>::TooManyAssetsBeingSent
);
ensure!(
T::MultiLocationsFilter::contains(&dest),
Error::<T>::NotSupportedMultiLocation
);

let mut assets = MultiAssets::new();

Expand All @@ -451,6 +474,7 @@ pub mod module {
let location: MultiLocation = T::CurrencyIdConvert::convert(currency_id.clone())
.ok_or(Error::<T>::NotCrossChainTransferableCurrency)?;
ensure!(!amount.is_zero(), Error::<T>::ZeroAmount);

// Push contains saturated addition, so we should be able to use it safely
assets.push((location, (*amount).into()).into())
}
Expand All @@ -476,6 +500,10 @@ pub mod module {
assets.len() <= T::MaxAssetsForTransfer::get(),
Error::<T>::TooManyAssetsBeingSent
);
ensure!(
T::MultiLocationsFilter::contains(&dest),
Error::<T>::NotSupportedMultiLocation
);
let origin_location = T::AccountIdToMultiLocation::convert(who.clone());

let mut non_fee_reserve: Option<MultiLocation> = None;
Expand Down
50 changes: 49 additions & 1 deletion xtokens/src/mock/para.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate as orml_xtokens;

use frame_support::{
construct_runtime, parameter_types,
traits::{Everything, Get, Nothing},
traits::{Contains, Everything, Get, Nothing},
weights::{constants::WEIGHT_PER_SECOND, Weight},
};
use frame_system::EnsureRoot;
Expand Down Expand Up @@ -270,6 +270,53 @@ parameter_types! {
pub SelfLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(ParachainInfo::get().into())));
pub const BaseXcmWeight: Weight = 100_000_000;
pub const MaxAssetsForTransfer: usize = 3;
pub SupportedMultiLocations: Vec<MultiLocation> = vec![
MultiLocation::new(
1,
X1(Parachain(1))
),
MultiLocation::new(
1,
X1(Parachain(2))
),
MultiLocation::new(
1,
X1(Parachain(3))
),
// There's a test that uses para id = 100
MultiLocation::new(
1,
X1(Parachain(100))
)
];
}

pub struct WhiteListingMultiLocations;
impl Contains<MultiLocation> for WhiteListingMultiLocations {
Copy link
Contributor

@zqhxuyuan zqhxuyuan Mar 15, 2022

Choose a reason for hiding this comment

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

we could offer some default implementation(in trait/location.rs), and use Tuple combine with fall-through way. i.e. AllowParentAccount, AllowParachainAccount, AllowLocalAccount. so parachain can use like type MultiLocationsFilter = (AllowParentAccount, AllowParachainAccount) or type MultiLocationsFilter = (AllowParentAccount, AllowParachainAccount, AllowLocalAccount) if they allow local asset.

Copy link
Contributor

@zqhxuyuan zqhxuyuan Mar 15, 2022

Choose a reason for hiding this comment

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

or a simple way like:

match_type! {
	pub type ParentOrParachain: impl Contains<MultiLocation> = {
		MultiLocation { parents: 1, interior: X1(AccountId32(_)) } |
		MultiLocation { parents: 1, interior: X2(Parachain(_), AccountId32(_)) }
	};
}

if allow local asset:

match_type! {
	pub type ParentOrParachainOrLocal: impl Contains<MultiLocation> = {
                 MultiLocation { parents: 0, interior: X1(AccountId32(_)) } |
		MultiLocation { parents: 1, interior: X1(AccountId32(_)) } |
		MultiLocation { parents: 1, interior: X2(Parachain(_), AccountId32(_)) }
	};
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I cannot use Parachain(_), becasue it will match all para id.

fn contains(dest: &MultiLocation) -> bool {
// Consider children parachain, means parent = 0
if dest.parent_count() != 0 && dest.parent_count() != 1 {
return false;
}

if let Junctions::X1(Junction::AccountId32 { .. }) = dest.interior() {
// parent = 1 or 0, and the junctions is the variant X1
// means the asset will be sent to relaychain.
true
} else {
// if the asset is sent to parachain,
// the junctions must have the variant Parachain
dest.interior().iter().any(|i| match i {
Junction::Parachain(parachain_id) => SupportedMultiLocations::get().iter().any(|location| {
location
.interior
.iter()
.any(|junc| *junc == Junction::Parachain(*parachain_id))
}),
_ => false, // No parachain id found.
})
}
}
}

parameter_type_with_key! {
Expand All @@ -289,6 +336,7 @@ impl orml_xtokens::Config for Runtime {
type CurrencyIdConvert = CurrencyIdConvert;
type AccountIdToMultiLocation = AccountIdToMultiLocation;
type SelfLocation = SelfLocation;
type MultiLocationsFilter = WhiteListingMultiLocations;
type MinXcmFee = ParachainMinFee;
type XcmExecutor = XcmExecutor<XcmConfig>;
type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;
Expand Down
51 changes: 51 additions & 0 deletions xtokens/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1335,3 +1335,54 @@ fn send_with_zero_amount() {

// TODO: should have more tests after https://github.com/paritytech/polkadot/issues/4996
}

#[test]
fn unsupported_multilocation_should_be_filtered() {
TestNet::reset();

ParaB::execute_with(|| {
assert_ok!(ParaTokens::deposit(CurrencyId::B, &ALICE, 1_000));
assert_ok!(ParaTokens::deposit(CurrencyId::B1, &ALICE, 1_000));
assert_noop!(
Copy link
Member

Choose a reason for hiding this comment

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

more test with transfer_multiassets and transfer_multicurrencies etc

ParaXTokens::transfer(
Some(ALICE).into(),
CurrencyId::B,
500,
Box::new(
(
Parent,
Parachain(4), // parachain 4 is not supported list.
Junction::AccountId32 {
network: NetworkId::Any,
id: BOB.into(),
},
)
.into()
),
40,
),
Error::<para::Runtime>::NotSupportedMultiLocation
);

assert_noop!(
ParaXTokens::transfer_multicurrencies(
Some(ALICE).into(),
vec![(CurrencyId::B1, 50), (CurrencyId::B, 450)],
0,
Box::new(
(
Parent,
Parachain(4),
Junction::AccountId32 {
network: NetworkId::Any,
id: BOB.into(),
},
)
.into()
),
40,
),
Error::<para::Runtime>::NotSupportedMultiLocation
);
});
}