diff --git a/Cargo.lock b/Cargo.lock index 3eab84d5ed16..647c78563efc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16711,6 +16711,7 @@ dependencies = [ "staging-xcm-builder 7.0.0", "staging-xcm-executor 7.0.0", "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", "xcm-runtime-apis 0.1.0", ] diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs index 8506125d4133..dbefdf624819 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 08b2f520c4b9..53b5918be966 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -16,9 +16,9 @@ use super::{ AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, BaseDeliveryFee, CollatorSelection, FeeAssetId, ForeignAssets, ForeignAssetsInstance, ParachainInfo, - ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - ToWestendXcmRouter, TransactionByteFee, TrustBackedAssetsInstance, Uniques, WeightToFee, - XcmpQueue, + ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, + RuntimeHoldReason, RuntimeOrigin, ToWestendXcmRouter, TransactionByteFee, + TrustBackedAssetsInstance, Uniques, WeightToFee, XcmpQueue, }; use assets_common::{ matching::{FromNetwork, FromSiblingParachain, IsForeignConcreteAsset, ParentLocation}, @@ -27,12 +27,13 @@ use assets_common::{ use frame_support::{ parameter_types, traits::{ + fungible::HoldConsideration, tokens::imbalance::{ResolveAssetTo, ResolveTo}, - ConstU32, Contains, Equals, Everything, PalletInfoAccess, + ConstU32, Contains, Equals, Everything, LinearStoragePrice, PalletInfoAccess, }, }; use frame_system::EnsureRoot; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{ xcm_config::{ AllSiblingSystemParachains, AssetFeeAsExistentialDepositMultiplier, @@ -330,6 +331,12 @@ pub type TrustedTeleporters = ( IsForeignConcreteAsset>>, ); +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +pub type TrustedAliasers = (AliasChildLocation, AuthorizedAliasers); + /// Asset converter for pool assets. /// Used to convert one asset to another, when there is a pool available between the two. /// This type thus allows paying fees with any asset as long as there is a pool between said @@ -444,7 +451,7 @@ impl xcm_executor::Config for XcmConfig { type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; // We allow any origin to alias into a child sub-location (equivalent to DescendOrigin). - type Aliasers = AliasChildLocation; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -452,8 +459,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = PolkadotXcm; } -/// Converts a local signed origin into an XCM location. -/// Forms the basis for local origins sending/executing XCMs. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; pub type PriceForParentDelivery = @@ -479,6 +486,12 @@ pub type XcmRouter = WithUniqueTopic<( SovereignPaidRemoteExporter, )>; +parameter_types! { + pub const DepositPerItem: Balance = crate::deposit(1, 0); + pub const DepositPerByte: Balance = crate::deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; // We want to disallow users sending (arbitrary) XCMs from this chain. @@ -509,6 +522,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs index 93409463d4e5..4208903e3087 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index b4e938f1f8b5..34aa50bcb029 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -15,10 +15,10 @@ use super::{ AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, BaseDeliveryFee, - CollatorSelection, FeeAssetId, ForeignAssets, ForeignAssetsInstance, ParachainInfo, - ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - ToRococoXcmRouter, TransactionByteFee, TrustBackedAssetsInstance, Uniques, WeightToFee, - XcmpQueue, + CollatorSelection, DepositPerByte, DepositPerItem, FeeAssetId, ForeignAssets, + ForeignAssetsInstance, ParachainInfo, ParachainSystem, PolkadotXcm, PoolAssets, Runtime, + RuntimeCall, RuntimeEvent, RuntimeHoldReason, RuntimeOrigin, ToRococoXcmRouter, + TransactionByteFee, TrustBackedAssetsInstance, Uniques, WeightToFee, XcmpQueue, }; use assets_common::{ matching::{FromSiblingParachain, IsForeignConcreteAsset, ParentLocation}, @@ -27,12 +27,13 @@ use assets_common::{ use frame_support::{ parameter_types, traits::{ + fungible::HoldConsideration, tokens::imbalance::{ResolveAssetTo, ResolveTo}, - ConstU32, Contains, Equals, Everything, PalletInfoAccess, + ConstU32, Contains, Equals, Everything, LinearStoragePrice, PalletInfoAccess, }, }; use frame_system::EnsureRoot; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{ xcm_config::{ AllSiblingSystemParachains, AssetFeeAsExistentialDepositMultiplier, @@ -353,6 +354,12 @@ pub type TrustedTeleporters = ( IsForeignConcreteAsset>>, ); +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +pub type TrustedAliasers = (AliasChildLocation, AuthorizedAliasers); + /// Asset converter for pool assets. /// Used to convert one asset to another, when there is a pool available between the two. /// This type thus allows paying fees with any asset as long as there is a pool between said @@ -465,8 +472,7 @@ impl xcm_executor::Config for XcmConfig { (bridging::to_rococo::UniversalAliases, bridging::to_ethereum::UniversalAliases); type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - // We allow any origin to alias into a child sub-location (equivalent to DescendOrigin). - type Aliasers = AliasChildLocation; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -474,7 +480,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = PolkadotXcm; } -/// Local origins on this chain are allowed to dispatch XCM sends/executions. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; pub type PriceForParentDelivery = @@ -504,6 +511,10 @@ pub type XcmRouter = WithUniqueTopic<( >, )>; +parameter_types! { + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SendXcmOrigin = EnsureXcmOrigin; @@ -532,6 +543,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs index 24b6d83ffae4..09bb5f332884 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs @@ -43,6 +43,7 @@ use frame_support::{ fungibles::{ Create, Inspect as FungiblesInspect, InspectEnumerable, Mutate as FungiblesMutate, }, + ContainsPair, }, weights::{Weight, WeightToFee as WeightToFeeT}, }; @@ -54,7 +55,7 @@ use std::{convert::Into, ops::Mul}; use testnet_parachains_constants::westend::{consensus::*, currency::UNITS, fee::WeightToFee}; use xcm::latest::{ prelude::{Assets as XcmAssets, *}, - ROCOCO_GENESIS_HASH, + ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH, }; use xcm_builder::WithLatestLocationConverter; use xcm_executor::traits::{ConvertLocation, JustTry, WeightTrader}; @@ -136,6 +137,7 @@ fn setup_pool_for_paying_fees_with_foreign_assets( #[test] fn test_buy_and_refund_weight_in_native() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -194,6 +196,7 @@ fn test_buy_and_refund_weight_in_native() { #[test] fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -303,6 +306,7 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() { #[test] fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -413,6 +417,7 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() { #[test] fn test_asset_xcm_take_first_trader() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -491,6 +496,7 @@ fn test_asset_xcm_take_first_trader() { #[test] fn test_foreign_asset_xcm_take_first_trader() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -572,6 +578,7 @@ fn test_foreign_asset_xcm_take_first_trader() { #[test] fn test_asset_xcm_take_first_trader_with_refund() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -651,6 +658,7 @@ fn test_asset_xcm_take_first_trader_with_refund() { #[test] fn test_asset_xcm_take_first_trader_refund_not_possible_since_amount_less_than_ed() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -703,6 +711,7 @@ fn test_asset_xcm_take_first_trader_refund_not_possible_since_amount_less_than_e #[test] fn test_that_buying_ed_refund_does_not_refund_for_take_first_trader() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -767,6 +776,7 @@ fn test_that_buying_ed_refund_does_not_refund_for_take_first_trader() { #[test] fn test_asset_xcm_take_first_trader_not_possible_for_non_sufficient_assets() { ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -828,6 +838,7 @@ fn test_assets_balances_api_works() { use assets_common::runtime_api::runtime_decl_for_fungibles_api::FungiblesApi; ExtBuilder::::default() + .with_tracing() .with_collators(vec![AccountId::from(ALICE)]) .with_session_keys(vec![( AccountId::from(ALICE), @@ -942,6 +953,92 @@ fn test_assets_balances_api_works() { }); } +#[test] +fn authorized_aliases_work() { + ExtBuilder::::default() + .with_tracing() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + let alice: AccountId = ALICE.into(); + let local_alice = Location::new( + 0, + AccountId32 { network: Some(ByGenesis(WESTEND_GENESIS_HASH)), id: ALICE }, + ); + let alice_on_sibling_para = + Location::new(1, [Parachain(42), AccountId32 { network: None, id: ALICE }]); + let alice_on_relay = Location::new(1, AccountId32 { network: None, id: ALICE }); + let bob_on_relay = Location::new(1, AccountId32 { network: None, id: [42_u8; 32] }); + + // neither `alice_on_sibling_para`, `alice_on_relay`, `bob_on_relay` are allowed to + // alias into `local_alice` + for aliaser in [&alice_on_sibling_para, &alice_on_relay, &bob_on_relay] { + assert!(!::Aliasers::contains( + aliaser, + &local_alice + )); + } + + // Alice explicitly authorizes `alice_on_sibling_para` to alias her local account + assert_ok!(PolkadotXcm::add_authorized_alias( + RuntimeHelper::origin_of(alice.clone()), + Box::new(alice_on_sibling_para.clone().into()), + None + )); + + // `alice_on_sibling_para` now explicitly allowed to alias into `local_alice` + assert!(::Aliasers::contains( + &alice_on_sibling_para, + &local_alice + )); + // as expected, `alice_on_relay` and `bob_on_relay` still can't alias into `local_alice` + for aliaser in [&alice_on_relay, &bob_on_relay] { + assert!(!::Aliasers::contains( + aliaser, + &local_alice + )); + } + + // Alice explicitly authorizes `alice_on_relay` to alias her local account + assert_ok!(PolkadotXcm::add_authorized_alias( + RuntimeHelper::origin_of(alice.clone()), + Box::new(alice_on_relay.clone().into()), + None + )); + // Now both `alice_on_relay` and `alice_on_sibling_para` can alias into her local + // account + for aliaser in [&alice_on_relay, &alice_on_sibling_para] { + assert!(::Aliasers::contains( + aliaser, + &local_alice + )); + } + + // Alice removes authorization for `alice_on_relay` to alias her local account + assert_ok!(PolkadotXcm::remove_authorized_alias( + RuntimeHelper::origin_of(alice.clone()), + Box::new(alice_on_relay.clone().into()) + )); + + // `alice_on_relay` no longer allowed to alias into `local_alice` + assert!(!::Aliasers::contains( + &alice_on_relay, + &local_alice + )); + + // `alice_on_sibling_para` still allowed to alias into `local_alice` + assert!(::Aliasers::contains( + &alice_on_sibling_para, + &local_alice + )); + }) +} + asset_test_utils::include_teleports_for_native_asset_works!( Runtime, AllPalletsWithoutSystem, diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs index 0a085b858251..78c370b9484f 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index b37945317f6c..df50bb4aadd7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -15,19 +15,23 @@ // along with Cumulus. If not, see . use super::{ - AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, FeeAssetId, ParachainInfo, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TransactionByteFee, WeightToFee, XcmOverBridgeHubWestend, XcmOverRococoBulletin, XcmpQueue, + AccountId, AllPalletsWithSystem, Balance, Balances, BaseDeliveryFee, FeeAssetId, ParachainInfo, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason, + RuntimeOrigin, TransactionByteFee, WeightToFee, XcmOverBridgeHubWestend, XcmOverRococoBulletin, + XcmpQueue, }; use core::marker::PhantomData; use frame_support::{ parameter_types, - traits::{tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, Everything, Nothing}, + traits::{ + fungible::HoldConsideration, tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, + Everything, LinearStoragePrice, Nothing, + }, }; use frame_system::EnsureRoot; use pallet_collator_selection::StakingPotAccountId; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{ xcm_config::{ AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, @@ -42,14 +46,14 @@ use sp_runtime::traits::AccountIdConversion; use testnet_parachains_constants::rococo::snowbridge::EthereumNetwork; use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, - EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HandleFee, HashedDescription, - IsConcrete, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, + AccountId32Aliases, AliasChildLocation, AllowExplicitUnpaidExecutionFrom, + AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, + DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FrameTransactionalProcessor, + FungibleAdapter, HandleFee, HashedDescription, IsConcrete, ParentAsSuperuser, ParentIsPreset, + RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, }; use xcm_executor::{ traits::{FeeManager, FeeReason, FeeReason::Export}, @@ -174,6 +178,12 @@ pub type WaivedLocations = ( /// - NativeToken with the parent Relay Chain and sibling parachains. pub type TrustedTeleporters = ConcreteAssetFromSystem; +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +pub type TrustedAliasers = (AliasChildLocation, AuthorizedAliasers); + pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; @@ -228,7 +238,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Nothing; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -239,8 +249,8 @@ impl xcm_executor::Config for XcmConfig { pub type PriceForParentDelivery = ExponentialPrice; -/// Converts a local signed origin into an XCM location. -/// Forms the basis for local origins sending/executing XCMs. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; /// The means for routing XCM messages which are not for local execution into the right message @@ -252,6 +262,12 @@ pub type XcmRouter = WithUniqueTopic<( XcmpQueue, )>; +parameter_types! { + pub const DepositPerItem: Balance = crate::deposit(1, 0); + pub const DepositPerByte: Balance = crate::deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmRouter = XcmRouter; @@ -282,6 +298,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs index fdae0c9a1522..cc0e18f3fde2 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index befb63ef9709..7762c8b3381f 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -15,17 +15,20 @@ // along with Cumulus. If not, see . use super::{ - AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, FeeAssetId, ParachainInfo, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TransactionByteFee, WeightToFee, XcmOverBridgeHubRococo, XcmpQueue, + AccountId, AllPalletsWithSystem, Balance, Balances, BaseDeliveryFee, FeeAssetId, ParachainInfo, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason, + RuntimeOrigin, TransactionByteFee, WeightToFee, XcmOverBridgeHubRococo, XcmpQueue, }; use frame_support::{ parameter_types, - traits::{tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, Everything, Nothing}, + traits::{ + fungible::HoldConsideration, tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, + Everything, LinearStoragePrice, Nothing, + }, }; use frame_system::EnsureRoot; use pallet_collator_selection::StakingPotAccountId; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{ xcm_config::{ AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, @@ -41,14 +44,14 @@ use sp_std::marker::PhantomData; use testnet_parachains_constants::westend::snowbridge::EthereumNetwork; use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, - EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HandleFee, HashedDescription, - IsConcrete, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, + AccountId32Aliases, AliasChildLocation, AllowExplicitUnpaidExecutionFrom, + AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, + DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FrameTransactionalProcessor, + FungibleAdapter, HandleFee, HashedDescription, IsConcrete, ParentAsSuperuser, ParentIsPreset, + RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, }; use xcm_executor::{ traits::{FeeManager, FeeReason, FeeReason::Export}, @@ -171,6 +174,12 @@ pub type WaivedLocations = ( /// - NativeToken with the parent Relay Chain and sibling parachains. pub type TrustedTeleporters = ConcreteAssetFromSystem; +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +pub type TrustedAliasers = (AliasChildLocation, AuthorizedAliasers); + pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; @@ -222,7 +231,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Nothing; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -233,8 +242,8 @@ impl xcm_executor::Config for XcmConfig { pub type PriceForParentDelivery = ExponentialPrice; -/// Converts a local signed origin into an XCM location. -/// Forms the basis for local origins sending/executing XCMs. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; /// The means for routing XCM messages which are not for local execution into the right message @@ -246,6 +255,12 @@ pub type XcmRouter = WithUniqueTopic<( XcmpQueue, )>; +parameter_types! { + pub const DepositPerItem: Balance = crate::deposit(1, 0); + pub const DepositPerByte: Balance = crate::deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmRouter = XcmRouter; @@ -276,6 +291,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs index ccf88873c2cd..eda4f186d197 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs index c5ab21fe8f90..cf9e253b7d84 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs @@ -14,17 +14,21 @@ // limitations under the License. use super::{ - AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, FeeAssetId, Fellows, ParachainInfo, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TransactionByteFee, WeightToFee, WestendTreasuryAccount, XcmpQueue, + AccountId, AllPalletsWithSystem, Balance, Balances, BaseDeliveryFee, FeeAssetId, Fellows, + ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, + RuntimeHoldReason, RuntimeOrigin, TransactionByteFee, WeightToFee, WestendTreasuryAccount, + XcmpQueue, }; use frame_support::{ parameter_types, - traits::{tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, Everything, Nothing}, + traits::{ + fungible::HoldConsideration, tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, + Everything, LinearStoragePrice, Nothing, + }, }; use frame_system::EnsureRoot; use pallet_collator_selection::StakingPotAccountId; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::xcm_config::{ AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, RelayOrOtherSystemParachains, @@ -183,12 +187,19 @@ pub type WaivedLocations = ( ); /// Cases where a remote origin is accepted as trusted Teleporter for a given asset: -/// - DOT with the parent Relay Chain and sibling parachains. +/// - WND with the parent Relay Chain and sibling parachains. pub type TrustedTeleporters = ConcreteAssetFromSystem; -/// We allow locations to alias into their own child locations, as well as -/// AssetHub to alias into anything. -pub type Aliasers = (AliasChildLocation, AliasOriginRootUsingFilter); +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +/// - Allow AssetHub root to alias into anything. +pub type TrustedAliasers = ( + AliasChildLocation, + AliasOriginRootUsingFilter, + AuthorizedAliasers, +); pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -230,7 +241,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Aliasers; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -238,8 +249,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = PolkadotXcm; } -/// Converts a local signed origin into an XCM location. -/// Forms the basis for local origins sending/executing XCMs. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; pub type PriceForParentDelivery = @@ -262,6 +273,12 @@ parameter_types! { /// Type to convert the Fellows origin to a Plurality `Location` value. pub type FellowsToPlurality = OriginToPluralityVoice; +parameter_types! { + pub const DepositPerItem: Balance = crate::deposit(1, 0); + pub const DepositPerByte: Balance = crate::deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; // We only allow the Fellows to send messages. @@ -292,6 +309,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index 532ad4ff4ce0..930e83ac84d6 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -210,8 +210,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = PolkadotXcm; } -/// Converts a local signed origin into an XCM location. -/// Forms the basis for local origins sending/executing XCMs. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; pub type PriceForParentDelivery = diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/pallet_xcm.rs index b2b8cd6e5349..a5203821636f 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs index 33ad172962a1..8f0b993963dd 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs @@ -183,6 +183,10 @@ pub type WaivedLocations = ( Equals, ); +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// - ROC with the parent Relay Chain and sibling parachains. +pub type TrustedTeleporters = ConcreteAssetFromSystem; + pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; @@ -192,8 +196,7 @@ impl xcm_executor::Config for XcmConfig { // Coretime chain does not recognize a reserve location for any asset. Users must teleport ROC // where allowed (e.g. with the Relay Chain). type IsReserve = (); - /// Only allow teleportation of ROC. - type IsTeleporter = ConcreteAssetFromSystem; + type IsTeleporter = TrustedTeleporters; type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = WeightInfoBounds< @@ -278,6 +281,7 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = (); } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/pallet_xcm.rs index 7659b8a1ac7e..eaf73c10f3b5 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs index 8a4879a1506e..e21c6bb807f8 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs @@ -15,18 +15,21 @@ // along with Cumulus. If not, see . use super::{ - AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, Broker, FeeAssetId, ParachainInfo, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TransactionByteFee, WeightToFee, XcmpQueue, + AccountId, AllPalletsWithSystem, Balance, Balances, BaseDeliveryFee, Broker, FeeAssetId, + ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, + RuntimeHoldReason, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, }; use frame_support::{ pallet_prelude::PalletInfoAccess, parameter_types, - traits::{tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, Everything, Nothing}, + traits::{ + fungible::HoldConsideration, tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, + Everything, LinearStoragePrice, Nothing, + }, }; use frame_system::EnsureRoot; use pallet_collator_selection::StakingPotAccountId; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{ xcm_config::{ AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, @@ -193,9 +196,20 @@ pub type WaivedLocations = ( Equals, ); -/// We allow locations to alias into their own child locations, as well as -/// AssetHub to alias into anything. -pub type Aliasers = (AliasChildLocation, AliasOriginRootUsingFilter); +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// - WND with the parent Relay Chain and sibling parachains. +pub type TrustedTeleporters = ConcreteAssetFromSystem; + +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +/// - Allow AssetHub root to alias into anything. +pub type TrustedAliasers = ( + AliasChildLocation, + AliasOriginRootUsingFilter, + AuthorizedAliasers, +); pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -206,8 +220,7 @@ impl xcm_executor::Config for XcmConfig { // Coretime chain does not recognize a reserve location for any asset. Users must teleport ROC // where allowed (e.g. with the Relay Chain). type IsReserve = (); - /// Only allow teleportation of WND. - type IsTeleporter = ConcreteAssetFromSystem; + type IsTeleporter = TrustedTeleporters; type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = WeightInfoBounds< @@ -238,7 +251,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Aliasers; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -262,6 +275,12 @@ pub type XcmRouter = WithUniqueTopic<( XcmpQueue, )>; +parameter_types! { + pub const DepositPerItem: Balance = crate::deposit(1, 0); + pub const DepositPerByte: Balance = crate::deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; // We want to disallow users sending (arbitrary) XCM programs from this chain. @@ -292,6 +311,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_xcm.rs index d50afdbee475..57931fcdd121 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs index 724d87587c6c..6516455f43f3 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs @@ -279,6 +279,7 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = (); } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_xcm.rs index f06669209a18..17601b19fa29 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_xcm.rs @@ -50,6 +50,28 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `498` + // Estimated: `3963` + // Minimum execution time: 19_789_000 picoseconds. + Weight::from_parts(20_317_000, 3963) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::AuthorizedAliases` (r:1 w:1) + /// Proof: `PolkadotXcm::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `537` + // Estimated: `4002` + // Minimum execution time: 20_805_000 picoseconds. + Weight::from_parts(21_481_000, 4002) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) diff --git a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs index 7eaa43c05b20..b2cb083e87a7 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs @@ -14,17 +14,21 @@ // limitations under the License. use super::{ - AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, - Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, + AccountId, AllPalletsWithSystem, Balance, Balances, ParachainInfo, ParachainSystem, + PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason, RuntimeOrigin, WeightToFee, + XcmpQueue, }; use crate::{TransactionByteFee, CENTS}; use frame_support::{ parameter_types, - traits::{tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, Everything, Nothing}, + traits::{ + fungible::HoldConsideration, tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, + Everything, LinearStoragePrice, Nothing, + }, }; use frame_system::EnsureRoot; use pallet_collator_selection::StakingPotAccountId; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{ xcm_config::{ AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, @@ -197,9 +201,20 @@ pub type WaivedLocations = ( LocalPlurality, ); -/// We allow locations to alias into their own child locations, as well as -/// AssetHub to alias into anything. -pub type Aliasers = (AliasChildLocation, AliasOriginRootUsingFilter); +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// - WND with the parent Relay Chain and sibling parachains. +pub type TrustedTeleporters = ConcreteAssetFromSystem; + +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +/// - Allow AssetHub root to alias into anything. +pub type TrustedAliasers = ( + AliasChildLocation, + AliasOriginRootUsingFilter, + AuthorizedAliasers, +); pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -210,8 +225,7 @@ impl xcm_executor::Config for XcmConfig { // People does not recognize a reserve location for any asset. Users must teleport WND // where allowed (e.g. with the Relay Chain). type IsReserve = (); - /// Only allow teleportation of WND amongst the system. - type IsTeleporter = ConcreteAssetFromSystem; + type IsTeleporter = TrustedTeleporters; type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = WeightInfoBounds< @@ -242,7 +256,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Aliasers; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -263,6 +277,12 @@ pub type XcmRouter = WithUniqueTopic<( XcmpQueue, )>; +parameter_types! { + pub const DepositPerItem: Balance = crate::deposit(1, 0); + pub const DepositPerByte: Balance = crate::deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; // We want to disallow users sending (arbitrary) XCMs from this chain. @@ -293,6 +313,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml index 5b17f4f57388..95302f486675 100644 --- a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml @@ -80,6 +80,7 @@ pallet-message-queue = { workspace = true } parachain-info = { workspace = true } parachains-common = { workspace = true } snowbridge-router-primitives = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "num-traits", "scale-info"] } diff --git a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs index 10481d5d2ebc..ac9d0e308c3a 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs @@ -25,8 +25,8 @@ use super::{ AccountId, AllPalletsWithSystem, AssetId as AssetIdPalletAssets, Assets, Authorship, Balance, Balances, CollatorSelection, ForeignAssets, ForeignAssetsInstance, NonZeroIssuance, - ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - WeightToFee, XcmpQueue, + ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, + RuntimeHoldReason, RuntimeOrigin, WeightToFee, XcmpQueue, }; use crate::{BaseDeliveryFee, FeeAssetId, TransactionByteFee}; use assets_common::TrustBackedAssetsAsLocation; @@ -34,30 +34,33 @@ use core::marker::PhantomData; use frame_support::{ parameter_types, traits::{ - tokens::imbalance::ResolveAssetTo, ConstU32, Contains, ContainsPair, Equals, Everything, - EverythingBut, Get, Nothing, PalletInfoAccess, + fungible::HoldConsideration, tokens::imbalance::ResolveAssetTo, ConstU32, Contains, + ContainsPair, Equals, Everything, EverythingBut, Get, LinearStoragePrice, Nothing, + PalletInfoAccess, }, weights::Weight, }; use frame_system::EnsureRoot; -use pallet_xcm::XcmPassthrough; +use pallet_xcm::{AuthorizedAliasers, XcmPassthrough}; use parachains_common::{xcm_config::AssetFeeAsExistentialDepositMultiplier, TREASURY_PALLET_ID}; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::{impls::ToAuthor, xcm_sender::ExponentialPrice}; use snowbridge_router_primitives::inbound::EthereumLocationsConverterFor; use sp_runtime::traits::{AccountIdConversion, ConvertInto, Identity, TryConvertInto}; +use testnet_parachains_constants::westend::currency::deposit; use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ - AccountId32Aliases, AliasOriginRootUsingFilter, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - AsPrefixedGeneralIndex, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily, - EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, - FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, - LocalMint, NativeAsset, NoChecking, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SingleAssetExchangeAdapter, - SovereignSignedViaLocation, StartsWith, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, + AccountId32Aliases, AliasChildLocation, AliasOriginRootUsingFilter, + AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, ConvertedConcreteId, + DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FixedWeightBounds, + FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, + GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, NativeAsset, + NoChecking, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SingleAssetExchangeAdapter, SovereignSignedViaLocation, StartsWith, + TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::{traits::JustTry, XcmExecutor}; @@ -337,6 +340,17 @@ pub type TrustedReserves = ( pub type TrustedTeleporters = (AssetFromChain,); +/// Defines origin aliasing rules for this chain. +/// +/// - Allow any origin to alias into a child sub-location (equivalent to DescendOrigin), +/// - Allow origins explicitly authorized by the alias target location. +/// - Allow AssetHub root to alias into anything. +pub type TrustedAliasers = ( + AliasChildLocation, + AliasOriginRootUsingFilter, + AuthorizedAliasers, +); + pub type WaivedLocations = Equals; /// `AssetId`/`Balance` converter for `TrustBackedAssets`. pub type TrustBackedAssetsConvertedConcreteId = @@ -408,8 +422,7 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - // We allow trusted Asset Hub root to alias other locations. - type Aliasers = AliasOriginRootUsingFilter; + type Aliasers = TrustedAliasers; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -426,7 +439,8 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = ForeignAssetsInstance, >; -/// No local origins on this chain are allowed to dispatch XCM sends/executions. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; pub type PriceForParentDelivery = @@ -441,6 +455,12 @@ pub type XcmRouter = WithUniqueTopic<( XcmpQueue, )>; +parameter_types! { + pub const DepositPerItem: Balance = deposit(1, 0); + pub const DepositPerByte: Balance = deposit(0, 1); + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::PolkadotXcm(pallet_xcm::HoldReason::AuthorizeAlias); +} + impl pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type SendXcmOrigin = EnsureXcmOrigin; @@ -467,6 +487,12 @@ impl pallet_xcm::Config for Runtime { type AdminOrigin = EnsureRoot; type MaxRemoteLockConsumers = ConstU32<0>; type RemoteLockConsumerIdentifier = (); + type Consideration = HoldConsideration< + AccountId, + Balances, + AuthorizeAliasHoldReason, + LinearStoragePrice, + >; } impl cumulus_pallet_xcm::Config for Runtime { diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 89cd17d5450a..a60b8893589c 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -502,7 +502,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = PolkadotXcm; } -/// Local origins on this chain are allowed to dispatch XCM sends/executions. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; /// The means for routing XCM messages which are not for local execution into the right message diff --git a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs index b60165934f92..0f2591c4bdb5 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs @@ -371,4 +371,26 @@ impl pallet_xcm::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } + /// Storage: `XcmPallet::AuthorizedAliases` (r:1 w:1) + /// Proof: `XcmPallet::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `361` + // Estimated: `3826` + // Minimum execution time: 15_975_000 picoseconds. + Weight::from_parts(16_398_000, 3826) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmPallet::AuthorizedAliases` (r:1 w:1) + /// Proof: `XcmPallet::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `400` + // Estimated: `3865` + // Minimum execution time: 17_326_000 picoseconds. + Weight::from_parts(17_622_000, 3865) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } } diff --git a/polkadot/runtime/westend/src/weights/pallet_xcm.rs b/polkadot/runtime/westend/src/weights/pallet_xcm.rs index e2c0232139fb..ad606120d529 100644 --- a/polkadot/runtime/westend/src/weights/pallet_xcm.rs +++ b/polkadot/runtime/westend/src/weights/pallet_xcm.rs @@ -371,4 +371,26 @@ impl pallet_xcm::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } + /// Storage: `XcmPallet::AuthorizedAliases` (r:1 w:1) + /// Proof: `XcmPallet::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn add_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `361` + // Estimated: `3826` + // Minimum execution time: 15_975_000 picoseconds. + Weight::from_parts(16_398_000, 3826) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmPallet::AuthorizedAliases` (r:1 w:1) + /// Proof: `XcmPallet::AuthorizedAliases` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn remove_authorized_alias() -> Weight { + // Proof Size summary in bytes: + // Measured: `400` + // Estimated: `3865` + // Minimum execution time: 17_326_000 picoseconds. + Weight::from_parts(17_622_000, 3865) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } } diff --git a/polkadot/runtime/westend/src/xcm_config.rs b/polkadot/runtime/westend/src/xcm_config.rs index 3f6a7304c8a9..d72d8965ac10 100644 --- a/polkadot/runtime/westend/src/xcm_config.rs +++ b/polkadot/runtime/westend/src/xcm_config.rs @@ -245,7 +245,8 @@ parameter_types! { pub type GeneralAdminToPlurality = OriginToPluralityVoice; -/// location of this chain. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = ( GeneralAdminToPlurality, // And a usual Signed origin to be used in XCM as a corresponding AccountId32 diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs index 0180354458ce..388849213ad2 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs @@ -146,6 +146,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = (); } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; impl pallet_xcm::Config for Runtime { diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs index 06b00c39e8a0..d6b4396f26f4 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs @@ -119,6 +119,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = (); } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; impl pallet_xcm::Config for Runtime { diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index 3ca048057ee4..e68f6587f3eb 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -28,7 +28,7 @@ type RuntimeOrigin = ::RuntimeOrigin; pub struct Pallet(crate::Pallet); /// Trait that must be implemented by runtime to be able to benchmark pallet properly. -pub trait Config: crate::Config { +pub trait Config: crate::Config + pallet_balances::Config { /// Helper that ensures successful delivery for extrinsics/benchmarks which need `SendXcm`. type DeliveryHelper: EnsureDelivery; @@ -396,7 +396,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::MigrateSupportedVersion, Weight::zero(), ); @@ -411,7 +411,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::MigrateVersionNotifiers, Weight::zero(), ); @@ -433,7 +433,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::NotifyCurrentTargets(None), Weight::zero(), ); @@ -454,7 +454,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::NotifyCurrentTargets(None), Weight::zero(), ); @@ -480,7 +480,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::MigrateAndNotifyOldTargets, Weight::zero(), ); @@ -496,7 +496,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::MigrateAndNotifyOldTargets, Weight::zero(), ); @@ -514,7 +514,7 @@ mod benchmarks { #[block] { - crate::Pallet::::check_xcm_version_change( + crate::Pallet::::lazy_migration( VersionMigrationStage::MigrateAndNotifyOldTargets, Weight::zero(), ); @@ -597,6 +597,81 @@ mod benchmarks { Ok(()) } + #[benchmark] + fn add_authorized_alias() -> Result<(), BenchmarkError> { + let who: T::AccountId = whitelisted_caller(); + let origin = RawOrigin::Signed(who.clone()); + let origin_location: VersionedLocation = + T::ExecuteXcmOrigin::try_origin(origin.clone().into()) + .map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))? + .into(); + + // Give some multiple of ED + let balance = T::ExistentialDeposit::get() * 1000u32.into(); + let _ = + as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance); + + let mut existing_aliases = BoundedVec::::new(); + // prepopulate list with `max-1` aliases to benchmark worst case + for i in 1..MaxAuthorizedAliases::get() { + let alias = + Location::new(1, [Parachain(i), AccountId32 { network: None, id: [42_u8; 32] }]) + .into(); + let aliaser = OriginAliaser { location: alias, expiry: None }; + existing_aliases.try_push(aliaser).unwrap() + } + let ticket = TicketOf::::new(&who, aliasers_footprint(existing_aliases.len())).unwrap(); + let entry = AuthorizedAliasesEntry { aliasers: existing_aliases, ticket }; + AuthorizedAliases::::insert(&origin_location, entry); + + // now benchmark adding new alias + let aliaser: VersionedLocation = + Location::new(1, [Parachain(1234), AccountId32 { network: None, id: [42_u8; 32] }]) + .into(); + + #[extrinsic_call] + _(origin, Box::new(aliaser), None); + + Ok(()) + } + + #[benchmark] + fn remove_authorized_alias() -> Result<(), BenchmarkError> { + let who: T::AccountId = whitelisted_caller(); + let origin = RawOrigin::Signed(who.clone()); + let origin_location: VersionedLocation = + T::ExecuteXcmOrigin::try_origin(origin.clone().into()) + .map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))? + .into(); + + // Give some multiple of ED + let balance = T::ExistentialDeposit::get() * 1000u32.into(); + let _ = + as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance); + + let mut existing_aliases = BoundedVec::::new(); + // prepopulate list with `max` aliases to benchmark worst case + for i in 1..MaxAuthorizedAliases::get() + 1 { + let alias = + Location::new(1, [Parachain(i), AccountId32 { network: None, id: [42_u8; 32] }]) + .into(); + let aliaser = OriginAliaser { location: alias, expiry: None }; + existing_aliases.try_push(aliaser).unwrap() + } + let ticket = TicketOf::::new(&who, aliasers_footprint(existing_aliases.len())).unwrap(); + let entry = AuthorizedAliasesEntry { aliasers: existing_aliases, ticket }; + AuthorizedAliases::::insert(&origin_location, entry); + + // now benchmark removing an alias + let aliaser_to_remove: VersionedLocation = + Location::new(1, [Parachain(1), AccountId32 { network: None, id: [42_u8; 32] }]).into(); + + #[extrinsic_call] + _(origin, Box::new(aliaser_to_remove)); + + Ok(()) + } + impl_benchmark_test_suite!( Pallet, crate::mock::new_test_ext_with_balances(Vec::new()), diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 6360298b21c3..3ce1d5f6db0f 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -38,8 +38,8 @@ use frame_support::{ }, pallet_prelude::*, traits::{ - Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Get, LockableCurrency, - OriginTrait, WithdrawReasons, + Consideration, Contains, ContainsPair, Currency, Defensive, EnsureOrigin, Footprint, Get, + LockableCurrency, OriginTrait, WithdrawReasons, }, PalletId, }; @@ -51,7 +51,7 @@ use sp_runtime::{ AccountIdConversion, BadOrigin, BlakeTwo256, BlockNumberProvider, Dispatchable, Hash, Saturating, Zero, }, - Either, RuntimeDebug, + Either, RuntimeDebug, SaturatedConversion, }; use xcm::{latest::QueryResponseInfo, prelude::*}; use xcm_builder::{ @@ -61,13 +61,14 @@ use xcm_builder::{ use xcm_executor::{ traits::{ AssetTransferError, CheckSuspension, ClaimAssets, ConvertLocation, ConvertOrigin, - DropAssets, MatchesFungible, OnResponse, Properties, QueryHandler, QueryResponseStatus, - RecordXcm, TransactAsset, TransferType, VersionChangeNotifier, WeightBounds, - XcmAssetTransfers, + DropAssets, FeeManager, FeeReason, MatchesFungible, OnResponse, Properties, QueryHandler, + QueryResponseStatus, RecordXcm, TransactAsset, TransferType, VersionChangeNotifier, + WeightBounds, XcmAssetTransfers, }, AssetsInHolding, }; use xcm_runtime_apis::{ + authorized_aliases::OriginAliaser, dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, trusted_query::Error as TrustedQueryApiError, @@ -75,7 +76,6 @@ use xcm_runtime_apis::{ #[cfg(any(feature = "try-runtime", test))] use sp_runtime::TryRuntimeError; -use xcm_executor::traits::{FeeManager, FeeReason}; pub trait WeightInfo { fn send() -> Weight; @@ -98,6 +98,8 @@ pub trait WeightInfo { fn new_query() -> Weight; fn take_response() -> Weight; fn claim_assets() -> Weight; + fn add_authorized_alias() -> Weight; + fn remove_authorized_alias() -> Weight; } /// fallback implementation @@ -182,6 +184,24 @@ impl WeightInfo for TestWeightInfo { fn claim_assets() -> Weight { Weight::from_parts(100_000_000, 0) } + + fn add_authorized_alias() -> Weight { + Weight::from_parts(100_000, 0) + } + + fn remove_authorized_alias() -> Weight { + Weight::from_parts(100_000, 0) + } +} + +#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)] +pub struct AuthorizedAliasesEntry> { + pub aliasers: BoundedVec, + pub ticket: Ticket, +} + +pub fn aliasers_footprint(aliasers_count: usize) -> Footprint { + Footprint::from_parts(aliasers_count, OriginAliaser::max_encoded_len()) } #[frame_support::pallet] @@ -200,6 +220,10 @@ pub mod pallet { /// An implementation of `Get` which just returns the latest XCM version which we can /// support. pub const CurrentXcmVersion: u32 = XCM_VERSION; + + #[derive(Debug, TypeInfo)] + /// The maximum number of distinct locations allowed as authorized aliases for a local origin. + pub const MaxAuthorizedAliases: u32 = 10; } const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); @@ -211,6 +235,7 @@ pub mod pallet { pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; + pub type TicketOf = ::Consideration; #[pallet::config] /// The module configuration trait. @@ -225,6 +250,9 @@ pub mod pallet { /// The `Asset` matcher for `Currency`. type CurrencyMatcher: MatchesFungible>; + /// A means of providing some cost while data is stored on-chain. + type Consideration: Consideration; + /// Required origin for sending XCM messages. If successful, it resolves to `Location` /// which exists as an interior location within this chain's XCM context. type SendXcmOrigin: EnsureOrigin<::RuntimeOrigin, Success = Location>; @@ -505,6 +533,15 @@ pub mod pallet { AssetsClaimed { hash: H256, origin: Location, assets: VersionedAssets }, /// A XCM version migration finished. VersionMigrationFinished { version: XcmVersion }, + /// An `aliaser` location was authorized by `target` to alias it, authorization valid until + /// `expiry` block number. + AliasAuthorized { + aliaser: VersionedLocation, + target: VersionedLocation, + expiry: Option, + }, + /// `target` removed alias authorization for `aliaser`. + AliasAuthorizationRemoved { aliaser: VersionedLocation, target: VersionedLocation }, } #[pallet::origin] @@ -521,6 +558,13 @@ pub mod pallet { } } + /// A reason for this pallet placing a hold on funds. + #[pallet::composite_enum] + pub enum HoldReason { + /// The funds are held as storage deposit for an authorized alias. + AuthorizeAlias, + } + #[pallet::error] pub enum Error { /// The desired destination was unreachable, generally because there is a no way of routing @@ -578,6 +622,12 @@ pub mod pallet { /// Local XCM execution incomplete. #[codec(index = 24)] LocalExecutionIncomplete, + /// Too many locations authorized to alias origin. + #[codec(index = 25)] + TooManyAuthorizedAliases, + /// Expiry block number is in the past. + #[codec(index = 26)] + ExpiresInPast, } impl From for Error { @@ -599,7 +649,7 @@ pub mod pallet { } /// The status of a query. - #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] + #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum QueryStatus { /// The query was sent but no response has yet been received. Pending { @@ -797,6 +847,18 @@ pub mod pallet { #[pallet::storage] pub(crate) type RecordedXcm = StorageValue<_, Xcm<()>>; + /// Map of authorized aliasers of local origins. Each local location can authorize a list of + /// other locations to alias into it. Each aliaser is only valid until its inner `expiry` + /// block number. + #[pallet::storage] + pub(super) type AuthorizedAliases = StorageMap< + _, + Blake2_128Concat, + VersionedLocation, + AuthorizedAliasesEntry, MaxAuthorizedAliases>, + OptionQuery, + >; + #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] @@ -825,7 +887,7 @@ pub mod pallet { if let Some(migration) = CurrentMigration::::get() { // Consume 10% of block at most let max_weight = T::BlockWeights::get().max_block / 10; - let (w, maybe_migration) = Self::check_xcm_version_change(migration, max_weight); + let (w, maybe_migration) = Self::lazy_migration(migration, max_weight); if maybe_migration.is_none() { Self::deposit_event(Event::VersionMigrationFinished { version: XCM_VERSION }); } @@ -1429,6 +1491,113 @@ pub mod pallet { weight_limit, ) } + + /// Authorize another `aliaser` location to alias into the local `origin` making this call. + /// The `aliaser` is only authorized until the provided `expiry` block number. + /// + /// Usually useful to allow your local account to be aliased into from a remote location + /// also under your control (like your account on another chain). + /// + /// WARNING: make sure the caller `origin` (you) trusts the `aliaser` location to act in + /// their/your name. Once authorized using this call, the `aliaser` can freely impersonate + /// `origin` in XCM programs executed on the local chain. + #[pallet::call_index(14)] + pub fn add_authorized_alias( + origin: OriginFor, + aliaser: Box, + expires: Option, + ) -> DispatchResult { + let signed_origin = ensure_signed(origin.clone())?; + let origin_location: Location = T::ExecuteXcmOrigin::ensure_origin(origin)?; + let aliaser: Location = (*aliaser).try_into().map_err(|()| Error::::BadVersion)?; + tracing::debug!(target: "xcm::pallet_xcm::add_authorized_alias", ?origin_location, ?aliaser, ?expires); + ensure!(origin_location != aliaser, Error::::BadLocation); + if let Some(expiry) = expires { + ensure!( + expiry > + frame_system::Pallet::::current_block_number().saturated_into::(), + Error::::ExpiresInPast + ); + } + let versioned_origin = VersionedLocation::from(origin_location); + let versioned_aliaser = VersionedLocation::from(aliaser); + + let entry = if let Some(entry) = AuthorizedAliases::::get(&versioned_origin) { + // entry already exists, update it + let (mut aliasers, mut ticket) = (entry.aliasers, entry.ticket); + if let Some(aliaser) = + aliasers.iter_mut().find(|aliaser| aliaser.location == versioned_aliaser) + { + // if the aliaser already exists, just update its expiry block + aliaser.expiry = expires; + } else { + // if it doesn't, we try to add it + let aliaser = + OriginAliaser { location: versioned_aliaser.clone(), expiry: expires }; + aliasers.try_push(aliaser).map_err(|_| Error::::TooManyAuthorizedAliases)?; + // we try to update the ticket (the storage deposit) + ticket = ticket.update(&signed_origin, aliasers_footprint(aliasers.len()))?; + } + AuthorizedAliasesEntry { aliasers, ticket } + } else { + // add new entry with its first alias + let ticket = TicketOf::::new(&signed_origin, aliasers_footprint(1))?; + let aliaser = + OriginAliaser { location: versioned_aliaser.clone(), expiry: expires }; + let mut aliasers = BoundedVec::::new(); + aliasers.try_push(aliaser).map_err(|_| Error::::TooManyAuthorizedAliases)?; + AuthorizedAliasesEntry { aliasers, ticket } + }; + // write to storage + AuthorizedAliases::::insert(&versioned_origin, entry); + Self::deposit_event(Event::AliasAuthorized { + aliaser: versioned_aliaser, + target: versioned_origin, + expiry: expires, + }); + Ok(()) + } + + /// Remove a previously authorized `aliaser` from the list of locations that can alias into + /// the local `origin` making this call. + #[pallet::call_index(15)] + pub fn remove_authorized_alias( + origin: OriginFor, + aliaser: Box, + ) -> DispatchResult { + let signed_origin = ensure_signed(origin.clone())?; + let origin_location: Location = T::ExecuteXcmOrigin::ensure_origin(origin)?; + let to_remove: Location = (*aliaser).try_into().map_err(|()| Error::::BadVersion)?; + tracing::debug!(target: "xcm::pallet_xcm::add_authorized_alias", ?origin_location, ?to_remove); + ensure!(origin_location != to_remove, Error::::BadLocation); + let versioned_origin = VersionedLocation::from(origin_location); + let versioned_to_remove = VersionedLocation::from(to_remove); + if let Some(entry) = AuthorizedAliases::::get(&versioned_origin) { + let (mut aliasers, mut ticket) = (entry.aliasers, entry.ticket); + let old_len = aliasers.len(); + aliasers.retain(|alias| versioned_to_remove.ne(&alias.location)); + let new_len = aliasers.len(); + if aliasers.is_empty() { + // remove entry altogether and return all storage deposit + ticket.drop(&signed_origin)?; + AuthorizedAliases::::remove(&versioned_origin); + Self::deposit_event(Event::AliasAuthorizationRemoved { + aliaser: versioned_to_remove, + target: versioned_origin, + }); + } else if old_len != new_len { + // update aliasers and storage deposit + ticket = ticket.update(&signed_origin, aliasers_footprint(new_len))?; + let entry = AuthorizedAliasesEntry { aliasers, ticket }; + AuthorizedAliases::::insert(&versioned_origin, entry); + Self::deposit_event(Event::AliasAuthorizationRemoved { + aliaser: versioned_to_remove, + target: versioned_origin, + }); + } + } + Ok(()) + } } } @@ -1511,7 +1680,7 @@ impl QueryHandler for Pallet { let response = response.into(); Queries::::insert( id, - QueryStatus::Ready { response, at: frame_system::Pallet::::block_number() }, + QueryStatus::Ready { response, at: frame_system::Pallet::::current_block_number() }, ); } } @@ -2274,7 +2443,7 @@ impl Pallet { /// Will always make progress, and will do its best not to use much more than `weight_cutoff` /// in doing so. - pub(crate) fn check_xcm_version_change( + pub(crate) fn lazy_migration( mut stage: VersionMigrationStage, weight_cutoff: Weight, ) -> (Weight, Option) { @@ -2615,6 +2784,40 @@ impl Pallet { }) } + /// Given a `destination` and XCM `message`, return assets to be charged as XCM delivery fees. + pub fn query_delivery_fees( + destination: VersionedLocation, + message: VersionedXcm<()>, + ) -> Result { + let result_version = destination.identify_version().max(message.identify_version()); + + let destination: Location = destination + .clone() + .try_into() + .map_err(|e| { + tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?destination, "Failed to convert versioned destination"); + XcmPaymentApiError::VersionedConversionFailed + })?; + + let message: Xcm<()> = + message.clone().try_into().map_err(|e| { + tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?message, "Failed to convert versioned message"); + XcmPaymentApiError::VersionedConversionFailed + })?; + + let (_, fees) = validate_send::(destination.clone(), message.clone()).map_err(|error| { + tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?error, ?destination, ?message, "Failed to validate send to destination"); + XcmPaymentApiError::Unroutable + })?; + + VersionedAssets::from(fees) + .into_version(result_version) + .map_err(|e| { + tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?result_version, "Failed to convert fees into version"); + XcmPaymentApiError::VersionedConversionFailed + }) + } + /// Given an Asset and a Location, returns if the provided location is a trusted reserve for the /// given asset. pub fn is_trusted_reserve( @@ -2666,37 +2869,32 @@ impl Pallet { Ok(::IsTeleporter::contains(&a, &location)) } - pub fn query_delivery_fees( - destination: VersionedLocation, - message: VersionedXcm<()>, - ) -> Result { - let result_version = destination.identify_version().max(message.identify_version()); - - let destination: Location = destination - .clone() - .try_into() - .map_err(|e| { - tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?destination, "Failed to convert versioned destination"); - XcmPaymentApiError::VersionedConversionFailed - })?; - - let message: Xcm<()> = - message.clone().try_into().map_err(|e| { - tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?message, "Failed to convert versioned message"); - XcmPaymentApiError::VersionedConversionFailed - })?; - - let (_, fees) = validate_send::(destination.clone(), message.clone()).map_err(|error| { - tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?error, ?destination, ?message, "Failed to validate send to destination"); - XcmPaymentApiError::Unroutable - })?; + /// Returns locations allowed to alias into and act as `target`. + fn authorized_aliasers(target: VersionedLocation) -> Vec { + AuthorizedAliases::::get(&target) + .map(|authorized| authorized.aliasers.into_iter().collect()) + .unwrap_or_default() + } - VersionedAssets::from(fees) - .into_version(result_version) - .map_err(|e| { - tracing::error!(target: "xcm::pallet_xcm::query_delivery_fees", ?e, ?result_version, "Failed to convert fees into version"); - XcmPaymentApiError::VersionedConversionFailed + /// Given an `origin` and a `target`, returns if the `origin` location was added by `target` as + /// an authorized aliaser. + /// + /// Effectively says whether `origin` is allowed to alias into and act as `target`. + pub fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> bool { + Self::authorized_aliasers(target) + .iter() + .find(|&aliaser| { + aliaser.location == origin && + aliaser + .expiry + .map(|expiry| { + expiry < + frame_system::Pallet::::current_block_number() + .saturated_into::() + }) + .unwrap_or(true) }) + .is_some() } /// Create a new expectation of a query response with the querier being here. @@ -3440,6 +3638,23 @@ where } } +/// Filter for `(origin: Location, target: Location)` to find whether `target` has explicitly +/// authorized `origin` to alias it. +/// +/// Note: users can authorize other locations to alias them by using +/// `pallet_xcm::add_authorized_alias()`. +pub struct AuthorizedAliasers(PhantomData); +impl + Clone, T: Config> ContainsPair for AuthorizedAliasers { + fn contains(origin: &L, target: &L) -> bool { + let origin: VersionedLocation = origin.clone().into(); + let target: VersionedLocation = target.clone().into(); + tracing::trace!(target: "xcm::pallet_xcm::AuthorizedAliasers::contains", ?origin, ?target); + // return true if the `origin` has been explicitly authorized by `target` as aliaser, and + // the authorization has not expired + Pallet::::is_authorized_alias(origin, target) + } +} + /// Filter for `Location` to find those which represent a strict majority approval of an /// identified plurality. /// diff --git a/polkadot/xcm/pallet-xcm/src/migration.rs b/polkadot/xcm/pallet-xcm/src/migration.rs index 80154f57ddfb..f43719ef9b99 100644 --- a/polkadot/xcm/pallet-xcm/src/migration.rs +++ b/polkadot/xcm/pallet-xcm/src/migration.rs @@ -170,6 +170,48 @@ pub mod data { } } + /// Implementation of `NeedsMigration` for `AuthorizedAliases` data. + impl, T: Config> NeedsMigration + for (&VersionedLocation, AuthorizedAliasesEntry, M>, PhantomData) + { + type MigratedData = (VersionedLocation, AuthorizedAliasesEntry, M>); + + fn needs_migration(&self, _: XcmVersion) -> bool { + self.0.identify_version() < XCM_VERSION || + self.1 + .aliasers + .iter() + .any(|alias| alias.location.identify_version() < XCM_VERSION) + } + + fn try_migrate(self, _: XcmVersion) -> Result, ()> { + if !self.needs_migration(XCM_VERSION) { + return Ok(None) + } + + let key = if self.0.identify_version() < XCM_VERSION { + let Ok(converted_key) = self.0.clone().into_version(XCM_VERSION) else { + return Err(()) + }; + converted_key + } else { + self.0.clone() + }; + + let mut new_aliases = BoundedVec::::new(); + let (aliasers, ticket) = (self.1.aliasers, self.1.ticket); + for alias in aliasers { + let OriginAliaser { mut location, expiry } = alias.clone(); + if location.identify_version() < XCM_VERSION { + location = location.into_version(XCM_VERSION)?; + } + new_aliases.try_push(OriginAliaser { location, expiry }).map_err(|_| ())?; + } + + Ok(Some((key, AuthorizedAliasesEntry { aliasers: new_aliases, ticket }))) + } + } + impl Pallet { /// Migrates relevant data to the `required_xcm_version`. pub(crate) fn migrate_data_to_xcm_version( @@ -323,6 +365,38 @@ pub mod data { >(&old_key, &new_key); weight.saturating_add(T::DbWeight::get().writes(1)); } + + // check and migrate `AuthorizedAliases` + let aliases_to_migrate = AuthorizedAliases::::iter().filter_map(|(id, data)| { + weight.saturating_add(T::DbWeight::get().reads(1)); + match (&id, data, PhantomData::).try_migrate(required_xcm_version) { + Ok(Some((new_id, new_data))) => Some((id, new_id, new_data)), + Ok(None) => None, + Err(_) => { + tracing::error!( + target: LOG_TARGET, + ?id, + ?required_xcm_version, + "`AuthorizedAliases` cannot be migrated!" + ); + None + }, + } + }); + let mut count = 0; + for (old_id, new_id, new_data) in aliases_to_migrate { + tracing::info!( + target: LOG_TARGET, + ?new_id, + ?new_data, + "Migrating `AuthorizedAliases`" + ); + AuthorizedAliases::::remove(old_id); + AuthorizedAliases::::insert(new_id, new_data); + count = count + 1; + } + // two writes per key, one to remove old entry, one to write new entry + weight.saturating_add(T::DbWeight::get().writes(count * 2)); } } } diff --git a/polkadot/xcm/pallet-xcm/src/mock.rs b/polkadot/xcm/pallet-xcm/src/mock.rs index 8d0476b0e70d..e7a756add549 100644 --- a/polkadot/xcm/pallet-xcm/src/mock.rs +++ b/polkadot/xcm/pallet-xcm/src/mock.rs @@ -19,8 +19,8 @@ pub use core::cell::RefCell; use frame_support::{ construct_runtime, derive_impl, parameter_types, traits::{ - AsEnsureOriginWithArg, ConstU128, ConstU32, Contains, Equals, Everything, EverythingBut, - Nothing, + fungible::HoldConsideration, AsEnsureOriginWithArg, ConstU128, ConstU32, Contains, Equals, + Everything, EverythingBut, Footprint, Nothing, }, weights::Weight, }; @@ -28,7 +28,10 @@ use frame_system::EnsureRoot; use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::origin; use sp_core::H256; -use sp_runtime::{traits::IdentityLookup, AccountId32, BuildStorage}; +use sp_runtime::{ + traits::{Convert, IdentityLookup}, + AccountId32, BuildStorage, +}; use xcm::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, @@ -518,10 +521,20 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = XcmPallet; } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; parameter_types! { pub static AdvertisedXcmVersion: pallet_xcm::XcmVersion = 4; + pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::XcmPallet(pallet_xcm::HoldReason::AuthorizeAlias); +} + +pub struct ConvertDeposit; +impl Convert for ConvertDeposit { + fn convert(a: Footprint) -> u128 { + (a.count * 2 + a.size) as u128 + } } pub struct XcmTeleportFiltered; @@ -556,6 +569,8 @@ impl pallet_xcm::Config for Test { type MaxRemoteLockConsumers = frame_support::traits::ConstU32<0>; type RemoteLockConsumerIdentifier = (); type WeightInfo = TestWeightInfo; + type Consideration = + HoldConsideration; } impl origin::Config for Test {} diff --git a/polkadot/xcm/pallet-xcm/src/tests/mod.rs b/polkadot/xcm/pallet-xcm/src/tests/mod.rs index 350530f7711f..42fe0ded5dc8 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/mod.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/mod.rs @@ -19,22 +19,26 @@ pub(crate) mod assets_transfer; use crate::{ + aliasers_footprint, migration::data::NeedsMigration, mock::*, pallet::{LockedFungibles, RemoteLockedFungibles, SupportedVersion}, - AssetTraps, Config, CurrentMigration, Error, ExecuteControllerWeightInfo, - LatestVersionedLocation, Pallet, Queries, QueryStatus, RecordedXcm, RemoteLockedFungibleRecord, - ShouldRecordXcm, VersionDiscoveryQueue, VersionMigrationStage, VersionNotifiers, - VersionNotifyTargets, WeightInfo, + AssetTraps, AuthorizedAliasers, Config, CurrentMigration, Error, ExecuteControllerWeightInfo, + LatestVersionedLocation, MaxAuthorizedAliases, Pallet, Queries, QueryStatus, RecordedXcm, + RemoteLockedFungibleRecord, ShouldRecordXcm, VersionDiscoveryQueue, VersionMigrationStage, + VersionNotifiers, VersionNotifyTargets, WeightInfo, }; use bounded_collections::BoundedVec; use frame_support::{ assert_err_ignore_postinfo, assert_noop, assert_ok, - traits::{Currency, Hooks}, + traits::{ContainsPair, Currency, Hooks}, weights::Weight, }; use polkadot_parachain_primitives::primitives::Id as ParaId; -use sp_runtime::traits::{AccountIdConversion, BlakeTwo256, Hash}; +use sp_runtime::{ + traits::{AccountIdConversion, BlakeTwo256, BlockNumberProvider, Hash}, + SaturatedConversion, TokenError, +}; use xcm::{latest::QueryResponseInfo, prelude::*}; use xcm_builder::AllowKnownQueryResponses; use xcm_executor::{ @@ -44,7 +48,7 @@ use xcm_executor::{ const ALICE: AccountId = AccountId::new([0u8; 32]); const BOB: AccountId = AccountId::new([1u8; 32]); -const INITIAL_BALANCE: u128 = 100; +const INITIAL_BALANCE: u128 = 1000; const SEND_AMOUNT: u128 = 10; const FEE_AMOUNT: u128 = 2; @@ -395,6 +399,172 @@ fn execute_withdraw_to_deposit_works() { }); } +/// Test XCM authorized aliases. +#[test] +fn authorized_aliases_work() { + let balances = vec![(ALICE, INITIAL_BALANCE)]; + new_test_ext_with_balances(balances).execute_with(|| { + // --- alias is same as origin + let alias: Location = AccountId32 { network: None, id: BOB.into() }.into(); + assert_eq!( + XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(BOB), + Box::new(alias.into()), + None + ), + Err(Error::::BadLocation.into()) + ); + + // --- alias already expired + let alias = Location::here(); + let expires = Some(System::current_block_number().saturated_into::()); + assert_eq!( + XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(BOB), + Box::new(alias.clone().into()), + expires + ), + Err(Error::::ExpiresInPast.into()) + ); + + // --- storage deposit not covered (BOB has no funds) + assert_eq!( + XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(BOB), + Box::new(alias.clone().into()), + None + ), + Err(sp_runtime::DispatchError::Token(TokenError::FundsUnavailable)) + ); + + // --- setting single alias works + let who = ALICE; + let total_balance_before = >::total_balance(&who); + let free_balance = >::free_balance(&who); + assert_eq!(free_balance, total_balance_before); + assert_ok!(XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.clone().into()), + None + )); + let footprint = aliasers_footprint(1); + let deposit = footprint.size + 2 * footprint.count; + let free_balance = >::free_balance(&who); + let total_balance = >::total_balance(&who); + assert_eq!(total_balance, total_balance_before); + assert_eq!(total_balance, free_balance + deposit as u128); + + // --- setting same alias again only updates its expiry + assert_ok!(XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.into()), + Some(100) + )); + // deposit is unchanged + assert_eq!(total_balance - deposit as u128, >::free_balance(&who)); + + // --- setting max number of aliases works + for i in 1..MaxAuthorizedAliases::get() { + let alias = Location::new(0, [Parachain(OTHER_PARA_ID), GeneralIndex(i as u128)]); + assert_ok!(XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.into()), + None + )); + let footprint = aliasers_footprint(i as usize + 1); + let deposit = (footprint.size + 2 * footprint.count) as u128; + assert_eq!(total_balance - deposit, >::free_balance(&who)); + } + + // deposit held for MaxAliases + let footprint = aliasers_footprint(MaxAuthorizedAliases::get() as usize); + let deposit = (footprint.size + 2 * footprint.count) as u128; + assert_eq!(total_balance - deposit, >::free_balance(&who)); + + // --- adding more than max aliases is not allowed + let alias = Location::new( + 0, + [Parachain(OTHER_PARA_ID), GeneralIndex(MaxAuthorizedAliases::get() as u128 + 100)], + ); + assert_eq!( + XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.clone().into()), + None + ), + Err(Error::::TooManyAuthorizedAliases.into()) + ); + + // --- remove one alias + let target: Location = AccountId32 { network: None, id: who.clone().into() }.into(); + assert_ok!(XcmPallet::remove_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(Location::here().into()), + )); + // deposit held for MaxAliases - 1 + let footprint = aliasers_footprint(MaxAuthorizedAliases::get() as usize - 1); + let deposit = (footprint.size + 2 * footprint.count) as u128; + assert_eq!(total_balance - deposit, >::free_balance(&who)); + // de-authorization event + assert_eq!( + last_events(1), + vec![RuntimeEvent::XcmPallet(crate::Event::AliasAuthorizationRemoved { + aliaser: Location::here().into(), + target: target.clone().into(), + }),] + ); + + // --- adding one more is now allowed + assert_ok!(XcmPallet::add_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.clone().into()), + None + )); + assert_eq!( + last_events(1), + vec![RuntimeEvent::XcmPallet(crate::Event::AliasAuthorized { + aliaser: alias.clone().into(), + target: target.clone().into(), + expiry: None, + })] + ); + + // --- un-authorized alias is correctly filtered/denied + assert!(!AuthorizedAliasers::::contains(&Location::here(), &target)); + // --- authorized alias is correctly allowed + assert!(AuthorizedAliasers::::contains(&alias, &target)); + // --- remove alias then verify no longer allowed + assert_ok!(XcmPallet::remove_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.clone().into()), + )); + assert!(!AuthorizedAliasers::::contains(&alias, &target)); + + // --- remove nonexistent alias - noop + assert_ok!(XcmPallet::remove_authorized_alias( + RuntimeOrigin::signed(ALICE), + Box::new(Location::parent().into()), + )); + + // --- remove nonexistent alias (BOB has no registered aliases) - noop + assert_ok!(XcmPallet::remove_authorized_alias( + RuntimeOrigin::signed(BOB), + Box::new(Location::parent().into()), + )); + + // --- remove all aliases then verify all deposit is returned + for i in 1..MaxAuthorizedAliases::get() { + let alias = Location::new(0, [Parachain(OTHER_PARA_ID), GeneralIndex(i as u128)]); + assert_ok!(XcmPallet::remove_authorized_alias( + RuntimeOrigin::signed(who.clone()), + Box::new(alias.into()), + )); + } + assert_eq!(total_balance, >::free_balance(&who)); + assert_eq!(total_balance, total_balance_before); + }); +} + /// Test drop/claim assets. #[test] fn trapped_assets_can_be_claimed() { @@ -1058,7 +1228,7 @@ fn subscription_side_upgrades_work_with_multistage_notify() { let mut counter = 0; while let Some(migration) = maybe_migration.take() { counter += 1; - let (_, m) = XcmPallet::check_xcm_version_change(migration, Weight::zero()); + let (_, m) = XcmPallet::lazy_migration(migration, Weight::zero()); maybe_migration = m; } assert_eq!(counter, 4); @@ -1211,7 +1381,7 @@ fn multistage_migration_works() { let mut weight_used = Weight::zero(); while let Some(migration) = maybe_migration.take() { counter += 1; - let (w, m) = XcmPallet::check_xcm_version_change(migration, Weight::zero()); + let (w, m) = XcmPallet::lazy_migration(migration, Weight::zero()); maybe_migration = m; weight_used.saturating_accrue(w); } diff --git a/polkadot/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs b/polkadot/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs index e6fe8e45c265..2f0287c3c2b7 100644 --- a/polkadot/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs +++ b/polkadot/xcm/xcm-builder/src/asset_exchange/single_asset_adapter/mock.rs @@ -290,6 +290,8 @@ parameter_types! { pub const NoNetwork: Option = None; } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountIndex64; impl pallet_xcm::Config for Runtime { diff --git a/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs b/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs index 6ebf6476f7e5..3dd41b5dbc0b 100644 --- a/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs +++ b/polkadot/xcm/xcm-builder/src/tests/pay/mock.rs @@ -161,6 +161,8 @@ impl MaybeEquivalence } } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; pub type LocalAssetsTransactor = FungiblesAdapter< Assets, diff --git a/polkadot/xcm/xcm-builder/tests/mock/mod.rs b/polkadot/xcm/xcm-builder/tests/mock/mod.rs index 0468b0a5410c..2a0148d409c5 100644 --- a/polkadot/xcm/xcm-builder/tests/mock/mod.rs +++ b/polkadot/xcm/xcm-builder/tests/mock/mod.rs @@ -197,6 +197,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = XcmPallet; } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; impl pallet_xcm::Config for Runtime { diff --git a/polkadot/xcm/xcm-runtime-apis/src/authorized_aliases.rs b/polkadot/xcm/xcm-runtime-apis/src/authorized_aliases.rs new file mode 100644 index 000000000000..b7aa82c5fa97 --- /dev/null +++ b/polkadot/xcm/xcm-runtime-apis/src/authorized_aliases.rs @@ -0,0 +1,40 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Contains runtime APIs for querying XCM authorized aliases. + +use alloc::vec::Vec; +use codec::{Decode, Encode}; +use frame_support::pallet_prelude::{MaxEncodedLen, TypeInfo}; +use xcm::VersionedLocation; + +/// Entry of an authorized aliaser for a local origin. The aliaser `location` is only authorized +/// until its inner `expiry` block number. +#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)] +pub struct OriginAliaser { + pub location: VersionedLocation, + pub expiry: Option, +} + +sp_api::decl_runtime_apis! { + /// API for querying XCM authorized aliases + pub trait AuthorizedAliasersApi { + /// Returns locations allowed to alias into and act as `target`. + fn authorized_aliasers(target: VersionedLocation) -> Vec; + /// Returns whether `origin` is allowed to alias into and act as `target`. + fn is_authorized_alias(origin: VersionedLocation, target: VersionedLocation) -> bool; + } +} diff --git a/polkadot/xcm/xcm-runtime-apis/src/lib.rs b/polkadot/xcm/xcm-runtime-apis/src/lib.rs index f9a857c7c4ce..3fe591b48b20 100644 --- a/polkadot/xcm/xcm-runtime-apis/src/lib.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/lib.rs @@ -20,17 +20,16 @@ extern crate alloc; +/// Runtime APIs for querying XCM authorized aliases. +pub mod authorized_aliases; /// Exposes runtime APIs for various XCM-related conversions. pub mod conversions; - /// Dry-run API. /// Given an extrinsic or an XCM program, it returns the outcome of its execution. pub mod dry_run; - /// Fee estimation API. /// Given an XCM program, it will return the fees needed to execute it properly or send it. pub mod fees; - -// Exposes runtime API for querying whether a Location is trusted as a reserve or teleporter for a -// given Asset. +/// Exposes runtime API for querying whether a Location is trusted as a reserve or teleporter for a +/// given Asset. pub mod trusted_query; diff --git a/polkadot/xcm/xcm-runtime-apis/src/trusted_query.rs b/polkadot/xcm/xcm-runtime-apis/src/trusted_query.rs index a2e3e1625486..9536f2bf6731 100644 --- a/polkadot/xcm/xcm-runtime-apis/src/trusted_query.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/trusted_query.rs @@ -24,7 +24,7 @@ use xcm::{VersionedAsset, VersionedLocation}; pub type XcmTrustedQueryResult = Result; sp_api::decl_runtime_apis! { - // API for querying trusted reserves and trusted teleporters. + /// API for querying trusted reserves and trusted teleporters. pub trait TrustedQueryApi { /// Returns if the location is a trusted reserve for the asset. /// diff --git a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs index 56a77094f177..ce6040c46883 100644 --- a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs @@ -333,6 +333,8 @@ where } } +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountIndex64; impl pallet_xcm::Config for TestRuntime { diff --git a/prdoc/pr_6336.prdoc b/prdoc/pr_6336.prdoc new file mode 100644 index 000000000000..f02f2aaa8f33 --- /dev/null +++ b/prdoc/pr_6336.prdoc @@ -0,0 +1,58 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "pallet-xcm: add support to authorize aliases" + +doc: + - audience: Runtime User + description: | + Added new `add_authorized_alias()` and `remove_authorized_alias()` calls to `pallet-xcm`. + These can be used by a "caller" to explicitly authorize another location to alias into the "caller" origin. + Usually useful to allow one's local account to be aliased into from a remote location also under + one's control (one's account on another chain). + WARNING: make sure that you as the caller `origin` trust the `aliaser` location to act in your name on this + chain. Once authorized using this call, the `aliaser` can freely impersonate `origin` in XCM programs + executed on the local chain. + + - audience: Runtime Dev + description: | + Added `AuthorizedAliasers` type exposed by `pallet-xcm`, that acts as a filter for explicitly authorized + aliases using `pallet-xcm::add_authorized_alias()` and `pallet-xcm::remove_authorized_alias()`. + Runtime developers can simply plug this `pallet-xcm::AuthorizedAliasers` type in their runtime's `XcmConfig`, + specifically in `::Aliasers`. + +crates: + - name: pallet-xcm + bump: major + - name: xcm-runtime-apis + bump: minor + - name: staging-xcm-builder + bump: none + - name: westend-runtime + bump: none + - name: rococo-runtime + bump: none + - name: asset-hub-rococo-runtime + bump: none + - name: asset-hub-westend-runtime + bump: none + - name: bridge-hub-rococo-runtime + bump: none + - name: bridge-hub-westend-runtime + bump: none + - name: collectives-westend-runtime + bump: none + - name: coretime-rococo-runtime + bump: none + - name: coretime-westend-runtime + bump: none + - name: people-rococo-runtime + bump: none + - name: people-westend-runtime + bump: none + - name: penpal-runtime + bump: none + - name: contracts-rococo-runtime + bump: none + - name: rococo-parachain-runtime + bump: none diff --git a/templates/parachain/runtime/src/configs/xcm_config.rs b/templates/parachain/runtime/src/configs/xcm_config.rs index 3da3b711f4ff..09e8e3bfef1b 100644 --- a/templates/parachain/runtime/src/configs/xcm_config.rs +++ b/templates/parachain/runtime/src/configs/xcm_config.rs @@ -150,7 +150,8 @@ impl xcm_executor::Config for XcmConfig { type XcmRecorder = PolkadotXcm; } -/// No local origins on this chain are allowed to dispatch XCM sends/executions. +/// Converts a local signed origin into an XCM location. Forms the basis for local origins +/// sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; /// The means for routing XCM messages which are not for local execution into the right message