feat: initialize Kurdistan SDK - independent fork of Polkadot SDK

This commit is contained in:
2025-12-13 15:44:15 +03:00
commit 286de54384
6841 changed files with 1848356 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
[package]
name = "xcm-simulator"
description = "Test kit to simulate cross-chain message passing and XCM execution"
version = "7.0.0"
authors.workspace = true
edition.workspace = true
license.workspace = true
homepage.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
codec = { workspace = true, default-features = true }
paste = { workspace = true, default-features = true }
scale-info = { workspace = true }
frame-support = { workspace = true, default-features = true }
frame-system = { workspace = true, default-features = true }
sp-io = { workspace = true, default-features = true }
sp-runtime = { workspace = true, default-features = true }
pezkuwi-core-primitives = { workspace = true, default-features = true }
pezkuwi-primitives = { workspace = true, default-features = true }
pezkuwi-runtime-teyrchains = { workspace = true, default-features = true }
pezkuwi-teyrchain-primitives = { workspace = true, default-features = true }
xcm = { workspace = true, default-features = true }
xcm-builder = { workspace = true, default-features = true }
xcm-executor = { workspace = true, default-features = true }
[features]
runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pezkuwi-core-primitives/runtime-benchmarks",
"pezkuwi-primitives/runtime-benchmarks",
"pezkuwi-runtime-teyrchains/runtime-benchmarks",
"pezkuwi-teyrchain-primitives/runtime-benchmarks",
"sp-io/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
"xcm/runtime-benchmarks",
]
@@ -0,0 +1,59 @@
[package]
name = "xcm-simulator-example"
description = "Examples of xcm-simulator usage."
authors.workspace = true
edition.workspace = true
license.workspace = true
version = "7.0.0"
homepage.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
codec = { workspace = true, default-features = true }
scale-info = { features = [
"derive",
], workspace = true, default-features = true }
tracing = { workspace = true }
frame-support = { workspace = true, default-features = true }
frame-system = { workspace = true, default-features = true }
pallet-balances = { workspace = true, default-features = true }
pallet-message-queue = { workspace = true, default-features = true }
pallet-uniques = { workspace = true, default-features = true }
sp-core = { workspace = true, default-features = true }
sp-io = { workspace = true, default-features = true }
sp-runtime = { workspace = true, default-features = true }
sp-tracing = { workspace = true, default-features = true }
pallet-xcm = { workspace = true, default-features = true }
pezkuwi-runtime-teyrchains = { workspace = true, default-features = true }
pezkuwi-teyrchain-primitives = { workspace = true, default-features = true }
xcm = { workspace = true, default-features = true }
xcm-builder = { workspace = true, default-features = true }
xcm-executor = { workspace = true, default-features = true }
xcm-simulator = { workspace = true, default-features = true }
[dev-dependencies]
sp-tracing = { workspace = true }
[features]
default = []
runtime-benchmarks = [
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-message-queue/runtime-benchmarks",
"pallet-uniques/runtime-benchmarks",
"pallet-xcm/runtime-benchmarks",
"pezkuwi-runtime-teyrchains/runtime-benchmarks",
"pezkuwi-teyrchain-primitives/runtime-benchmarks",
"sp-io/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
"xcm-simulator/runtime-benchmarks",
"xcm/runtime-benchmarks",
]
@@ -0,0 +1,149 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
// We do not declare all features used by `construct_runtime`
#[allow(unexpected_cfgs)]
mod teyrchain;
// We do not declare all features used by `construct_runtime`
#[allow(unexpected_cfgs)]
mod relay_chain;
#[cfg(test)]
mod tests;
use sp_runtime::BuildStorage;
use sp_tracing;
use xcm::prelude::*;
use xcm_executor::traits::ConvertLocation;
use xcm_simulator::{decl_test_network, decl_test_relay_chain, decl_test_teyrchain, TestExt};
pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([1u8; 32]);
pub const INITIAL_BALANCE: u128 = 1_000_000_000;
decl_test_teyrchain! {
pub struct ParaA {
Runtime = teyrchain::Runtime,
XcmpMessageHandler = teyrchain::MsgQueue,
DmpMessageHandler = teyrchain::MsgQueue,
new_ext = para_ext(1),
}
}
decl_test_teyrchain! {
pub struct ParaB {
Runtime = teyrchain::Runtime,
XcmpMessageHandler = teyrchain::MsgQueue,
DmpMessageHandler = teyrchain::MsgQueue,
new_ext = para_ext(2),
}
}
decl_test_relay_chain! {
pub struct Relay {
Runtime = relay_chain::Runtime,
RuntimeCall = relay_chain::RuntimeCall,
RuntimeEvent = relay_chain::RuntimeEvent,
XcmConfig = relay_chain::XcmConfig,
MessageQueue = relay_chain::MessageQueue,
System = relay_chain::System,
new_ext = relay_ext(),
}
}
decl_test_network! {
pub struct MockNet {
relay_chain = Relay,
teyrchains = vec![
(1, ParaA),
(2, ParaB),
],
}
}
pub fn parent_account_id() -> teyrchain::AccountId {
let location = (Parent,);
teyrchain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn child_account_id(para: u32) -> relay_chain::AccountId {
let location = (Teyrchain(para),);
relay_chain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn child_account_account_id(para: u32, who: sp_runtime::AccountId32) -> relay_chain::AccountId {
let location = (Teyrchain(para), AccountId32 { network: None, id: who.into() });
relay_chain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn sibling_account_account_id(para: u32, who: sp_runtime::AccountId32) -> teyrchain::AccountId {
let location = (Parent, Teyrchain(para), AccountId32 { network: None, id: who.into() });
teyrchain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn parent_account_account_id(who: sp_runtime::AccountId32) -> teyrchain::AccountId {
let location = (Parent, AccountId32 { network: None, id: who.into() });
teyrchain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn para_ext(para_id: u32) -> sp_io::TestExternalities {
use teyrchain::{MsgQueue, Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(ALICE, INITIAL_BALANCE), (parent_account_id(), INITIAL_BALANCE)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
sp_tracing::try_init_simple();
System::set_block_number(1);
MsgQueue::set_para_id(para_id.into());
});
ext
}
pub fn relay_ext() -> sp_io::TestExternalities {
use relay_chain::{Runtime, RuntimeOrigin, System, Uniques};
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![
(ALICE, INITIAL_BALANCE),
(child_account_id(1), INITIAL_BALANCE),
(child_account_id(2), INITIAL_BALANCE),
],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
System::set_block_number(1);
assert_eq!(Uniques::force_create(RuntimeOrigin::root(), 1, ALICE, true), Ok(()));
assert_eq!(Uniques::mint(RuntimeOrigin::signed(ALICE), 1, 42, child_account_id(1)), Ok(()));
});
ext
}
pub type RelayChainPalletXcm = pallet_xcm::Pallet<relay_chain::Runtime>;
pub type TeyrchainPalletXcm = pallet_xcm::Pallet<teyrchain::Runtime>;
@@ -0,0 +1,182 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Relay chain runtime mock.
mod xcm_config;
pub use xcm_config::*;
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{
AsEnsureOriginWithArg, ConstU128, Disabled, Everything, Nothing, ProcessMessage,
ProcessMessageError,
},
weights::{Weight, WeightMeter},
};
use frame_system::EnsureRoot;
use sp_core::ConstU32;
use sp_runtime::{traits::IdentityLookup, AccountId32};
use pezkuwi_runtime_teyrchains::{
configuration,
inclusion::{AggregateMessageOrigin, UmpQueueId},
origin, shared,
};
use xcm::latest::prelude::*;
use xcm_builder::{IsConcrete, SignedToAccountId32};
use xcm_executor::XcmExecutor;
pub type AccountId = AccountId32;
pub type Balance = u128;
parameter_types! {
pub const BlockHashCount: u64 = 250;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Block = Block;
type AccountData = pallet_balances::AccountData<Balance>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type ExistentialDeposit = ConstU128<1>;
type AccountStore = System;
}
impl pallet_uniques::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type CollectionId = u32;
type ItemId = u32;
type Currency = Balances;
type CreateOrigin = AsEnsureOriginWithArg<frame_system::EnsureSigned<AccountId>>;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type CollectionDeposit = frame_support::traits::ConstU128<1_000>;
type ItemDeposit = frame_support::traits::ConstU128<1_000>;
type MetadataDepositBase = frame_support::traits::ConstU128<1_000>;
type AttributeDepositBase = frame_support::traits::ConstU128<1_000>;
type DepositPerByte = frame_support::traits::ConstU128<1>;
type StringLimit = ConstU32<64>;
type KeyLimit = ConstU32<64>;
type ValueLimit = ConstU32<128>;
type Locker = ();
type WeightInfo = ();
#[cfg(feature = "runtime-benchmarks")]
type Helper = ();
}
impl shared::Config for Runtime {
type DisabledValidators = ();
}
impl configuration::Config for Runtime {
type WeightInfo = configuration::TestWeightInfo;
}
pub type LocalOriginToLocation =
SignedToAccountId32<RuntimeOrigin, AccountId, constants::RelayNetwork>;
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
// Anyone can execute XCM messages locally...
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Nothing;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Everything;
type XcmReserveTransferFilter = Everything;
type Weigher = weigher::Weigher;
type UniversalLocation = constants::UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = IsConcrete<constants::TokenLocation>;
type TrustedLockers = ();
type SovereignAccountOf = location_converter::LocationConverter;
type MaxLockers = ConstU32<8>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type WeightInfo = pallet_xcm::TestWeightInfo;
type AdminOrigin = EnsureRoot<AccountId>;
type AuthorizedAliasConsideration = Disabled;
}
impl origin::Config for Runtime {}
type Block = frame_system::mocking::MockBlock<Runtime>;
parameter_types! {
/// Amount of weight that can be spent per block to service messages.
pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000);
pub const MessageQueueHeapSize: u32 = 65_536;
pub const MessageQueueMaxStale: u32 = 16;
}
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
pub struct MessageProcessor;
impl ProcessMessage for MessageProcessor {
type Origin = AggregateMessageOrigin;
fn process_message(
message: &[u8],
origin: Self::Origin,
meter: &mut WeightMeter,
id: &mut [u8; 32],
) -> Result<bool, ProcessMessageError> {
let para = match origin {
AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
};
xcm_builder::ProcessXcmMessage::<
Junction,
xcm_executor::XcmExecutor<XcmConfig>,
RuntimeCall,
>::process_message(message, Junction::Teyrchain(para.into()), meter, id)
}
}
impl pallet_message_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Size = u32;
type HeapSize = MessageQueueHeapSize;
type MaxStale = MessageQueueMaxStale;
type ServiceWeight = MessageQueueServiceWeight;
type IdleMaxServiceWeight = ();
type MessageProcessor = MessageProcessor;
type QueueChangeHandler = ();
type QueuePausedQuery = ();
type WeightInfo = ();
}
construct_runtime!(
pub enum Runtime
{
System: frame_system,
Balances: pallet_balances,
ParasOrigin: origin,
XcmPallet: pallet_xcm,
Uniques: pallet_uniques,
MessageQueue: pallet_message_queue,
}
);
@@ -0,0 +1,38 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::relay_chain::{
constants::TokenLocation, location_converter::LocationConverter, AccountId, Balances, Uniques,
};
use xcm_builder::{
AsPrefixedGeneralIndex, ConvertedConcreteId, FungibleAdapter, IsConcrete, NoChecking,
NonFungiblesAdapter,
};
use xcm_executor::traits::JustTry;
type LocalAssetTransactor = (
FungibleAdapter<Balances, IsConcrete<TokenLocation>, LocationConverter, AccountId, ()>,
NonFungiblesAdapter<
Uniques,
ConvertedConcreteId<u32, u32, AsPrefixedGeneralIndex<(), u32, JustTry>, JustTry>,
LocationConverter,
AccountId,
NoChecking,
(),
>,
);
pub type AssetTransactor = LocalAssetTransactor;
@@ -0,0 +1,20 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use frame_support::traits::Everything;
use xcm_builder::AllowUnpaidExecutionFrom;
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
@@ -0,0 +1,31 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use frame_support::parameter_types;
use xcm::latest::prelude::*;
parameter_types! {
pub TokensPerSecondPerByte: (AssetId, u128, u128) =
(AssetId(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024);
pub const MaxAssetsIntoHolding: u32 = 64;
}
parameter_types! {
pub const TokenLocation: Location = Here.into_location();
pub RelayNetwork: NetworkId = ByGenesis([0; 32]);
pub UniversalLocation: InteriorLocation = RelayNetwork::get().into();
pub UnitWeightCost: u64 = 1_000;
}
@@ -0,0 +1,25 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::relay_chain::{constants::RelayNetwork, AccountId};
use xcm_builder::{AccountId32Aliases, DescribeAllTerminal, DescribeFamily, HashedDescription};
type LocationToAccountId = (
HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
AccountId32Aliases<RelayNetwork, AccountId>,
);
pub type LocationConverter = LocationToAccountId;
@@ -0,0 +1,65 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
pub mod asset_transactor;
pub mod barrier;
pub mod constants;
pub mod location_converter;
pub mod origin_converter;
pub mod teleporter;
pub mod weigher;
use crate::relay_chain::{RuntimeCall, XcmPallet};
use frame_support::traits::{Everything, Nothing};
use xcm_builder::{EnsureDecodableXcm, FixedRateOfFungible, FrameTransactionalProcessor};
use xcm_executor::Config;
// Generated from `decl_test_network!`
pub type XcmRouter = EnsureDecodableXcm<crate::RelayChainXcmRouter>;
pub struct XcmConfig;
impl Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter;
type XcmEventEmitter = ();
type AssetTransactor = asset_transactor::AssetTransactor;
type OriginConverter = origin_converter::OriginConverter;
type IsReserve = ();
type IsTeleporter = teleporter::TrustedTeleporters;
type UniversalLocation = constants::UniversalLocation;
type Barrier = barrier::Barrier;
type Weigher = weigher::Weigher;
type Trader = FixedRateOfFungible<constants::TokensPerSecondPerByte, ()>;
type ResponseHandler = ();
type AssetTrap = ();
type AssetLocker = XcmPallet;
type AssetExchanger = ();
type AssetClaims = ();
type SubscriptionService = ();
type PalletInstancesInfo = ();
type FeeManager = ();
type MaxAssetsIntoHolding = constants::MaxAssetsIntoHolding;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = XcmPallet;
}
@@ -0,0 +1,34 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::relay_chain::{
constants::RelayNetwork, location_converter::LocationConverter, RuntimeOrigin,
};
use pezkuwi_runtime_teyrchains::origin;
use pezkuwi_teyrchain_primitives::primitives::Id as ParaId;
use xcm_builder::{
ChildSystemTeyrchainAsSuperuser, ChildTeyrchainAsNative, SignedAccountId32AsNative,
SovereignSignedViaLocation,
};
type LocalOriginConverter = (
SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
ChildTeyrchainAsNative<origin::Origin, RuntimeOrigin>,
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
ChildSystemTeyrchainAsSuperuser<ParaId, RuntimeOrigin>,
);
pub type OriginConverter = LocalOriginConverter;
@@ -0,0 +1,26 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use frame_support::parameter_types;
use xcm::latest::prelude::*;
parameter_types! {
pub NftCollectionOnRelay: AssetFilter
= Wild(AllOf { fun: WildNonFungible, id: AssetId(GeneralIndex(1).into()) });
pub NftCollectionForChild: (AssetFilter, Location)
= (NftCollectionOnRelay::get(), Teyrchain(1).into());
}
pub type TrustedTeleporters = xcm_builder::Case<NftCollectionForChild>;
@@ -0,0 +1,27 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::relay_chain::RuntimeCall;
use frame_support::parameter_types;
use xcm::latest::prelude::*;
use xcm_builder::FixedWeightBounds;
parameter_types! {
pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000);
pub const MaxInstructions: u32 = 100;
}
pub type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
@@ -0,0 +1,579 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::*;
use codec::Encode;
use frame_support::{assert_ok, weights::Weight};
use xcm::latest::QueryResponseInfo;
use xcm_simulator::{mock_message_queue::ReceivedDmp, TestExt};
// Helper function for forming buy execution message
fn buy_execution<C>(fees: impl Into<Asset>) -> Instruction<C> {
BuyExecution { fees: fees.into(), weight_limit: Unlimited }
}
/// Helper macro to check if a system event exists in the event list.
///
/// Example usage:
/// ```ignore
/// assert!(system_contains_event!(teyrchain, System(frame_system::Event::Remarked { .. })));
/// assert!(system_contains_event!(relay_chain, XcmPallet(pallet_xcm::Event::Attempted { .. })));
/// ```
macro_rules! system_contains_event {
($runtime:ident, $variant:ident($($pattern:tt)*)) => {
$runtime::System::events().iter().any(|e| {
matches!(e.event, $runtime::RuntimeEvent::$variant($($pattern)*))
})
};
}
#[test]
fn remote_account_ids_work() {
child_account_account_id(1, ALICE);
sibling_account_account_id(1, ALICE);
parent_account_account_id(ALICE);
}
#[test]
fn dmp() {
MockNet::reset();
let remark = teyrchain::RuntimeCall::System(
frame_system::Call::<teyrchain::Runtime>::remark_with_event { remark: vec![1, 2, 3] },
);
Relay::execute_with(|| {
assert_ok!(RelayChainPalletXcm::send_xcm(
Here,
Teyrchain(1),
Xcm(vec![Transact {
origin_kind: OriginKind::SovereignAccount,
call: remark.encode().into(),
fallback_max_weight: None,
}]),
));
});
ParaA::execute_with(|| {
assert!(system_contains_event!(teyrchain, System(frame_system::Event::Remarked { .. })));
});
}
#[test]
fn ump() {
MockNet::reset();
let remark = relay_chain::RuntimeCall::System(
frame_system::Call::<relay_chain::Runtime>::remark_with_event { remark: vec![1, 2, 3] },
);
ParaA::execute_with(|| {
assert_ok!(TeyrchainPalletXcm::send_xcm(
Here,
Parent,
Xcm(vec![Transact {
origin_kind: OriginKind::SovereignAccount,
call: remark.encode().into(),
fallback_max_weight: None,
}]),
));
});
Relay::execute_with(|| {
assert!(system_contains_event!(relay_chain, System(frame_system::Event::Remarked { .. })));
});
}
#[test]
fn xcmp() {
MockNet::reset();
let remark = teyrchain::RuntimeCall::System(
frame_system::Call::<teyrchain::Runtime>::remark_with_event { remark: vec![1, 2, 3] },
);
ParaA::execute_with(|| {
assert_ok!(TeyrchainPalletXcm::send_xcm(
Here,
(Parent, Teyrchain(2)),
Xcm(vec![Transact {
origin_kind: OriginKind::SovereignAccount,
call: remark.encode().into(),
fallback_max_weight: None,
}]),
));
});
ParaB::execute_with(|| {
assert!(system_contains_event!(teyrchain, System(frame_system::Event::Remarked { .. })));
});
}
#[test]
fn reserve_transfer() {
MockNet::reset();
let withdraw_amount = 123;
Relay::execute_with(|| {
assert_ok!(RelayChainPalletXcm::limited_reserve_transfer_assets(
relay_chain::RuntimeOrigin::signed(ALICE),
Box::new(Teyrchain(1).into()),
Box::new(AccountId32 { network: None, id: ALICE.into() }.into()),
Box::new((Here, withdraw_amount).into()),
Box::new(Here.into()),
Unlimited,
));
assert_eq!(
relay_chain::Balances::free_balance(&child_account_id(1)),
INITIAL_BALANCE + withdraw_amount
);
// Ensure expected events were emitted
let attempted_emitted =
system_contains_event!(relay_chain, XcmPallet(pallet_xcm::Event::Attempted { .. }));
let sent_emitted =
system_contains_event!(relay_chain, XcmPallet(pallet_xcm::Event::Sent { .. }));
assert!(attempted_emitted, "Expected XcmPallet::Attempted event emitted");
assert!(sent_emitted, "Expected XcmPallet::Sent event emitted");
});
ParaA::execute_with(|| {
// free execution, full amount received
assert_eq!(
pallet_balances::Pallet::<teyrchain::Runtime>::free_balance(&ALICE),
INITIAL_BALANCE + withdraw_amount
);
});
}
#[test]
fn reserve_transfer_with_error() {
use sp_tracing::{
test_log_capture::init_log_capture,
tracing::{subscriber, Level},
};
// Reset the test network
MockNet::reset();
// Execute XCM Transfer and Capture Logs
let (log_capture, subscriber) = init_log_capture(Level::ERROR, false);
subscriber::with_default(subscriber, || {
let invalid_dest = Box::new(Teyrchain(9999).into());
let withdraw_amount = 123;
Relay::execute_with(|| {
let result = RelayChainPalletXcm::limited_reserve_transfer_assets(
relay_chain::RuntimeOrigin::signed(ALICE),
invalid_dest,
Box::new(AccountId32 { network: None, id: ALICE.into() }.into()),
Box::new((Here, withdraw_amount).into()),
Box::new(Here.into()),
Unlimited,
);
// Ensure an error occurred
assert!(result.is_err(), "Expected an error due to invalid destination");
// Assert captured logs
assert!(log_capture.contains("XCM validate_send failed"));
// Verify that XcmPallet::Attempted was NOT emitted (rollback happened)
let xcm_attempted_emitted =
system_contains_event!(relay_chain, XcmPallet(pallet_xcm::Event::Attempted { .. }));
assert!(
!xcm_attempted_emitted,
"Expected no XcmPallet::Attempted event due to rollback, but it was emitted"
);
});
// Ensure no balance change due to the error
ParaA::execute_with(|| {
assert_eq!(
pallet_balances::Pallet::<teyrchain::Runtime>::free_balance(&ALICE),
INITIAL_BALANCE
);
});
});
}
#[test]
fn remote_locking_and_unlocking() {
MockNet::reset();
let locked_amount = 100;
ParaB::execute_with(|| {
let message = Xcm(vec![LockAsset {
asset: (Here, locked_amount).into(),
unlocker: Teyrchain(1).into(),
}]);
assert_ok!(TeyrchainPalletXcm::send_xcm(Here, Parent, message.clone()));
});
Relay::execute_with(|| {
use pallet_balances::{BalanceLock, Reasons};
assert_eq!(
relay_chain::Balances::locks(&child_account_id(2)),
vec![BalanceLock { id: *b"py/xcmlk", amount: locked_amount, reasons: Reasons::All }]
);
});
ParaA::execute_with(|| {
assert_eq!(
ReceivedDmp::<teyrchain::Runtime>::get(),
vec![Xcm(vec![NoteUnlockable {
owner: (Parent, Teyrchain(2)).into(),
asset: (Parent, locked_amount).into()
}])]
);
});
ParaB::execute_with(|| {
// Request unlocking part of the funds on the relay chain
let message = Xcm(vec![RequestUnlock {
asset: (Parent, locked_amount - 50).into(),
locker: Parent.into(),
}]);
assert_ok!(TeyrchainPalletXcm::send_xcm(Here, (Parent, Teyrchain(1)), message));
});
Relay::execute_with(|| {
use pallet_balances::{BalanceLock, Reasons};
// Lock is reduced
assert_eq!(
relay_chain::Balances::locks(&child_account_id(2)),
vec![BalanceLock {
id: *b"py/xcmlk",
amount: locked_amount - 50,
reasons: Reasons::All
}]
);
});
}
/// Scenario:
/// A teyrchain transfers an NFT resident on the relay chain to another teyrchain account.
///
/// Asserts that the teyrchain accounts are updated as expected.
#[test]
fn withdraw_and_deposit_nft() {
MockNet::reset();
Relay::execute_with(|| {
assert_eq!(relay_chain::Uniques::owner(1, 42), Some(child_account_id(1)));
});
ParaA::execute_with(|| {
let message = Xcm(vec![TransferAsset {
assets: (GeneralIndex(1), 42u32).into(),
beneficiary: Teyrchain(2).into(),
}]);
// Send withdraw and deposit
assert_ok!(TeyrchainPalletXcm::send_xcm(Here, Parent, message));
});
Relay::execute_with(|| {
assert_eq!(relay_chain::Uniques::owner(1, 42), Some(child_account_id(2)));
});
}
/// Scenario:
/// The relay-chain teleports an NFT to a teyrchain.
///
/// Asserts that the teyrchain accounts are updated as expected.
#[test]
fn teleport_nft() {
MockNet::reset();
Relay::execute_with(|| {
// Mint the NFT (1, 69) and give it to our "teyrchain#1 alias".
assert_ok!(relay_chain::Uniques::mint(
relay_chain::RuntimeOrigin::signed(ALICE),
1,
69,
child_account_account_id(1, ALICE),
));
// The teyrchain#1 alias of Alice is what must hold it on the Relay-chain for it to be
// withdrawable by Alice on the teyrchain.
assert_eq!(relay_chain::Uniques::owner(1, 69), Some(child_account_account_id(1, ALICE)));
});
ParaA::execute_with(|| {
assert_ok!(teyrchain::ForeignUniques::force_create(
teyrchain::RuntimeOrigin::root(),
(Parent, GeneralIndex(1)).into(),
ALICE,
false,
));
assert_eq!(
teyrchain::ForeignUniques::owner((Parent, GeneralIndex(1)).into(), 69u32.into()),
None,
);
assert_eq!(teyrchain::Balances::reserved_balance(&ALICE), 0);
// IRL Alice would probably just execute this locally on the Relay-chain, but we can't
// easily do that here since we only send between chains.
let message = Xcm(vec![
WithdrawAsset((GeneralIndex(1), 69u32).into()),
InitiateTeleport {
assets: AllCounted(1).into(),
dest: Teyrchain(1).into(),
xcm: Xcm(vec![DepositAsset {
assets: AllCounted(1).into(),
beneficiary: (AccountId32 { id: ALICE.into(), network: None },).into(),
}]),
},
]);
// Send teleport
let alice = AccountId32 { id: ALICE.into(), network: None };
assert_ok!(TeyrchainPalletXcm::send_xcm(alice, Parent, message));
});
ParaA::execute_with(|| {
assert_eq!(
teyrchain::ForeignUniques::owner((Parent, GeneralIndex(1)).into(), 69u32.into()),
Some(ALICE),
);
assert_eq!(teyrchain::Balances::reserved_balance(&ALICE), 1000);
});
Relay::execute_with(|| {
assert_eq!(relay_chain::Uniques::owner(1, 69), None);
});
}
/// Scenario:
/// The relay-chain transfers an NFT into a teyrchain's sovereign account, who then mints a
/// trustless-backed-derived locally.
///
/// Asserts that the teyrchain accounts are updated as expected.
#[test]
fn reserve_asset_transfer_nft() {
sp_tracing::init_for_tests();
MockNet::reset();
Relay::execute_with(|| {
assert_ok!(relay_chain::Uniques::force_create(
relay_chain::RuntimeOrigin::root(),
2,
ALICE,
false
));
assert_ok!(relay_chain::Uniques::mint(
relay_chain::RuntimeOrigin::signed(ALICE),
2,
69,
child_account_account_id(1, ALICE)
));
assert_eq!(relay_chain::Uniques::owner(2, 69), Some(child_account_account_id(1, ALICE)));
});
ParaA::execute_with(|| {
assert_ok!(teyrchain::ForeignUniques::force_create(
teyrchain::RuntimeOrigin::root(),
(Parent, GeneralIndex(2)).into(),
ALICE,
false,
));
assert_eq!(
teyrchain::ForeignUniques::owner((Parent, GeneralIndex(2)).into(), 69u32.into()),
None,
);
assert_eq!(teyrchain::Balances::reserved_balance(&ALICE), 0);
let message = Xcm(vec![
WithdrawAsset((GeneralIndex(2), 69u32).into()),
DepositReserveAsset {
assets: AllCounted(1).into(),
dest: Teyrchain(1).into(),
xcm: Xcm(vec![DepositAsset {
assets: AllCounted(1).into(),
beneficiary: (AccountId32 { id: ALICE.into(), network: None },).into(),
}]),
},
]);
// Send transfer
let alice = AccountId32 { id: ALICE.into(), network: None };
assert_ok!(TeyrchainPalletXcm::send_xcm(alice, Parent, message));
});
ParaA::execute_with(|| {
tracing::debug!(target: "xcm-executor", "Hello");
assert_eq!(
teyrchain::ForeignUniques::owner((Parent, GeneralIndex(2)).into(), 69u32.into()),
Some(ALICE),
);
assert_eq!(teyrchain::Balances::reserved_balance(&ALICE), 1000);
});
Relay::execute_with(|| {
assert_eq!(relay_chain::Uniques::owner(2, 69), Some(child_account_id(1)));
});
}
/// Scenario:
/// The relay-chain creates an asset class on a teyrchain and then Alice transfers her NFT into
/// that teyrchain's sovereign account, who then mints a trustless-backed-derivative locally.
///
/// Asserts that the teyrchain accounts are updated as expected.
#[test]
fn reserve_asset_class_create_and_reserve_transfer() {
MockNet::reset();
Relay::execute_with(|| {
assert_ok!(relay_chain::Uniques::force_create(
relay_chain::RuntimeOrigin::root(),
2,
ALICE,
false
));
assert_ok!(relay_chain::Uniques::mint(
relay_chain::RuntimeOrigin::signed(ALICE),
2,
69,
child_account_account_id(1, ALICE)
));
assert_eq!(relay_chain::Uniques::owner(2, 69), Some(child_account_account_id(1, ALICE)));
let message = Xcm(vec![Transact {
origin_kind: OriginKind::Xcm,
call: teyrchain::RuntimeCall::from(
pallet_uniques::Call::<teyrchain::Runtime>::create {
collection: (Parent, 2u64).into(),
admin: parent_account_id(),
},
)
.encode()
.into(),
fallback_max_weight: None,
}]);
// Send creation.
assert_ok!(RelayChainPalletXcm::send_xcm(Here, Teyrchain(1), message));
});
ParaA::execute_with(|| {
// Then transfer
let message = Xcm(vec![
WithdrawAsset((GeneralIndex(2), 69u32).into()),
DepositReserveAsset {
assets: AllCounted(1).into(),
dest: Teyrchain(1).into(),
xcm: Xcm(vec![DepositAsset {
assets: AllCounted(1).into(),
beneficiary: (AccountId32 { id: ALICE.into(), network: None },).into(),
}]),
},
]);
let alice = AccountId32 { id: ALICE.into(), network: None };
assert_ok!(TeyrchainPalletXcm::send_xcm(alice, Parent, message));
});
ParaA::execute_with(|| {
assert_eq!(teyrchain::Balances::reserved_balance(&parent_account_id()), 1000);
assert_eq!(
teyrchain::ForeignUniques::collection_owner((Parent, 2u64).into()),
Some(parent_account_id())
);
});
}
/// Scenario:
/// A teyrchain transfers funds on the relay chain to another teyrchain account.
///
/// Asserts that the teyrchain accounts are updated as expected.
#[test]
fn withdraw_and_deposit() {
MockNet::reset();
let send_amount = 10;
ParaA::execute_with(|| {
let message = Xcm(vec![
WithdrawAsset((Here, send_amount).into()),
buy_execution((Here, send_amount)),
DepositAsset { assets: AllCounted(1).into(), beneficiary: Teyrchain(2).into() },
]);
// Send withdraw and deposit
assert_ok!(TeyrchainPalletXcm::send_xcm(Here, Parent, message.clone()));
});
Relay::execute_with(|| {
assert_eq!(
relay_chain::Balances::free_balance(child_account_id(1)),
INITIAL_BALANCE - send_amount
);
assert_eq!(
relay_chain::Balances::free_balance(child_account_id(2)),
INITIAL_BALANCE + send_amount
);
});
}
/// Scenario:
/// A teyrchain wants to be notified that a transfer worked correctly.
/// It sends a `QueryHolding` after the deposit to get notified on success.
///
/// Asserts that the balances are updated correctly and the expected XCM is sent.
#[test]
fn query_holding() {
MockNet::reset();
let send_amount = 10;
let query_id_set = 1234;
// Send a message which fully succeeds on the relay chain
let expected_hash = ParaA::execute_with(|| {
let message = Xcm(vec![
WithdrawAsset((Here, send_amount).into()),
buy_execution((Here, send_amount)),
DepositAsset { assets: AllCounted(1).into(), beneficiary: Teyrchain(2).into() },
ReportHolding {
response_info: QueryResponseInfo {
destination: Teyrchain(1).into(),
query_id: query_id_set,
max_weight: Weight::from_parts(1_000_000_000, 1024 * 1024),
},
assets: All.into(),
},
]);
// Send withdraw and deposit with query holding
assert_ok!(TeyrchainPalletXcm::send_xcm(Here, Parent, message.clone(),));
VersionedXcm::from(message).using_encoded(sp_core::blake2_256)
});
// Check that transfer was executed
Relay::execute_with(|| {
// Withdraw executed
assert_eq!(
relay_chain::Balances::free_balance(child_account_id(1)),
INITIAL_BALANCE - send_amount
);
// Deposit executed
assert_eq!(
relay_chain::Balances::free_balance(child_account_id(2)),
INITIAL_BALANCE + send_amount
);
});
// Check that QueryResponse message was received
ParaA::execute_with(|| {
assert_eq!(
ReceivedDmp::<teyrchain::Runtime>::get(),
vec![Xcm(vec![
QueryResponse {
query_id: query_id_set,
response: Response::Assets(Assets::new()),
max_weight: Weight::from_parts(1_000_000_000, 1024 * 1024),
querier: Some(Here.into()),
},
SetTopic(expected_hash),
])],
);
});
}
@@ -0,0 +1,184 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Teyrchain runtime mock.
mod xcm_config;
pub use xcm_config::*;
use core::marker::PhantomData;
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{
ConstU128, ContainsPair, Disabled, EnsureOrigin, EnsureOriginWithArg, Everything, Nothing,
},
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
};
use frame_system::EnsureRoot;
use sp_core::ConstU32;
use sp_runtime::{
traits::{Get, IdentityLookup},
AccountId32,
};
use xcm::latest::prelude::*;
use xcm_builder::{EnsureXcmOrigin, SignedToAccountId32};
use xcm_executor::{traits::ConvertLocation, XcmExecutor};
use xcm_simulator::mock_message_queue;
pub type AccountId = AccountId32;
pub type Balance = u128;
parameter_types! {
pub const BlockHashCount: u64 = 250;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Block = Block;
type AccountData = pallet_balances::AccountData<Balance>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type ExistentialDeposit = ConstU128<1>;
type AccountStore = System;
}
#[cfg(feature = "runtime-benchmarks")]
pub struct UniquesHelper;
#[cfg(feature = "runtime-benchmarks")]
impl pallet_uniques::BenchmarkHelper<Location, AssetInstance> for UniquesHelper {
fn collection(i: u16) -> Location {
GeneralIndex(i as u128).into()
}
fn item(i: u16) -> AssetInstance {
AssetInstance::Index(i as u128)
}
}
impl pallet_uniques::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type CollectionId = Location;
type ItemId = AssetInstance;
type Currency = Balances;
type CreateOrigin = ForeignCreators;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type CollectionDeposit = frame_support::traits::ConstU128<1_000>;
type ItemDeposit = frame_support::traits::ConstU128<1_000>;
type MetadataDepositBase = frame_support::traits::ConstU128<1_000>;
type AttributeDepositBase = frame_support::traits::ConstU128<1_000>;
type DepositPerByte = frame_support::traits::ConstU128<1>;
type StringLimit = ConstU32<64>;
type KeyLimit = ConstU32<64>;
type ValueLimit = ConstU32<128>;
type Locker = ();
type WeightInfo = ();
#[cfg(feature = "runtime-benchmarks")]
type Helper = UniquesHelper;
}
// `EnsureOriginWithArg` impl for `CreateOrigin` which allows only XCM origins
// which are locations containing the class location.
pub struct ForeignCreators;
impl EnsureOriginWithArg<RuntimeOrigin, Location> for ForeignCreators {
type Success = AccountId;
fn try_origin(
o: RuntimeOrigin,
a: &Location,
) -> core::result::Result<Self::Success, RuntimeOrigin> {
let origin_location = pallet_xcm::EnsureXcm::<Everything>::try_origin(o.clone())?;
if !a.starts_with(&origin_location) {
return Err(o);
}
xcm_config::location_converter::LocationConverter::convert_location(&origin_location)
.ok_or(o)
}
#[cfg(feature = "runtime-benchmarks")]
fn try_successful_origin(a: &Location) -> Result<RuntimeOrigin, ()> {
Ok(pallet_xcm::Origin::Xcm(a.clone()).into())
}
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
}
impl mock_message_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
}
pub type LocalOriginToLocation =
SignedToAccountId32<RuntimeOrigin, AccountId, constants::RelayNetwork>;
pub struct TrustedLockerCase<T>(PhantomData<T>);
impl<T: Get<(Location, AssetFilter)>> ContainsPair<Location, Asset> for TrustedLockerCase<T> {
fn contains(origin: &Location, asset: &Asset) -> bool {
let (o, a) = T::get();
a.matches(asset) && &o == origin
}
}
parameter_types! {
pub RelayTokenForRelay: (Location, AssetFilter) = (Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible }));
}
pub type TrustedLockers = TrustedLockerCase<RelayTokenForRelay>;
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Nothing;
type XcmReserveTransferFilter = Everything;
type Weigher = weigher::Weigher;
type UniversalLocation = constants::UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = TrustedLockers;
type SovereignAccountOf = location_converter::LocationConverter;
type MaxLockers = ConstU32<8>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type WeightInfo = pallet_xcm::TestWeightInfo;
type AdminOrigin = EnsureRoot<AccountId>;
type AuthorizedAliasConsideration = Disabled;
}
type Block = frame_system::mocking::MockBlock<Runtime>;
construct_runtime!(
pub struct Runtime {
System: frame_system,
Balances: pallet_balances,
MsgQueue: mock_message_queue,
PezkuwiXcm: pallet_xcm,
ForeignUniques: pallet_uniques,
}
);
@@ -0,0 +1,39 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::teyrchain::{
constants::KsmLocation, location_converter::LocationConverter, AccountId, Balances,
ForeignUniques,
};
use xcm::latest::prelude::*;
use xcm_builder::{
ConvertedConcreteId, FungibleAdapter, IsConcrete, NoChecking, NonFungiblesAdapter,
};
use xcm_executor::traits::JustTry;
type LocalAssetTransactor = (
FungibleAdapter<Balances, IsConcrete<KsmLocation>, LocationConverter, AccountId, ()>,
NonFungiblesAdapter<
ForeignUniques,
ConvertedConcreteId<Location, AssetInstance, JustTry, JustTry>,
LocationConverter,
AccountId,
NoChecking,
(),
>,
);
pub type AssetTransactor = LocalAssetTransactor;
@@ -0,0 +1,20 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use frame_support::traits::Everything;
use xcm_builder::AllowUnpaidExecutionFrom;
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
@@ -0,0 +1,31 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::teyrchain::Runtime;
use frame_support::parameter_types;
use xcm::latest::prelude::*;
use xcm_simulator::mock_message_queue::TeyrchainId;
parameter_types! {
pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1, 1);
pub const MaxAssetsIntoHolding: u32 = 64;
}
parameter_types! {
pub const KsmLocation: Location = Location::parent();
pub const RelayNetwork: NetworkId = NetworkId::Kusama;
pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Teyrchain(TeyrchainId::<Runtime>::get().into())].into();
}
@@ -0,0 +1,25 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::teyrchain::{constants::RelayNetwork, AccountId};
use xcm_builder::{AccountId32Aliases, DescribeAllTerminal, DescribeFamily, HashedDescription};
type LocationToAccountId = (
HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
AccountId32Aliases<RelayNetwork, AccountId>,
);
pub type LocationConverter = LocationToAccountId;
@@ -0,0 +1,65 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
pub mod asset_transactor;
pub mod barrier;
pub mod constants;
pub mod location_converter;
pub mod origin_converter;
pub mod reserve;
pub mod teleporter;
pub mod weigher;
use crate::teyrchain::{MsgQueue, PezkuwiXcm, RuntimeCall};
use frame_support::traits::{Everything, Nothing};
use xcm_builder::{EnsureDecodableXcm, FixedRateOfFungible, FrameTransactionalProcessor};
// Generated from `decl_test_network!`
pub type XcmRouter = EnsureDecodableXcm<crate::TeyrchainXcmRouter<MsgQueue>>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter;
type XcmEventEmitter = PezkuwiXcm;
type AssetTransactor = asset_transactor::AssetTransactor;
type OriginConverter = origin_converter::OriginConverter;
type IsReserve = reserve::TrustedReserves;
type IsTeleporter = teleporter::TrustedTeleporters;
type UniversalLocation = constants::UniversalLocation;
type Barrier = barrier::Barrier;
type Weigher = weigher::Weigher;
type Trader = FixedRateOfFungible<constants::KsmPerSecondPerByte, ()>;
type ResponseHandler = ();
type AssetTrap = ();
type AssetLocker = PezkuwiXcm;
type AssetExchanger = ();
type AssetClaims = ();
type SubscriptionService = ();
type PalletInstancesInfo = ();
type FeeManager = ();
type MaxAssetsIntoHolding = constants::MaxAssetsIntoHolding;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = PezkuwiXcm;
}
@@ -0,0 +1,29 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::teyrchain::{
constants::RelayNetwork, location_converter::LocationConverter, RuntimeOrigin,
};
use pallet_xcm::XcmPassthrough;
use xcm_builder::{SignedAccountId32AsNative, SovereignSignedViaLocation};
type XcmOriginToCallOrigin = (
SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
XcmPassthrough<RuntimeOrigin>,
);
pub type OriginConverter = XcmOriginToCallOrigin;
@@ -0,0 +1,21 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::teyrchain::teleporter::TrustedTeleporters;
use frame_support::traits::EverythingBut;
use xcm_builder::NativeAsset;
pub type TrustedReserves = (NativeAsset, EverythingBut<TrustedTeleporters>);
@@ -0,0 +1,27 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use frame_support::parameter_types;
use xcm::latest::prelude::*;
parameter_types! {
pub NftCollectionOne: AssetFilter
= Wild(AllOf { fun: WildNonFungible, id: AssetId((Parent, GeneralIndex(1)).into()) });
pub NftCollectionOneForRelay: (AssetFilter, Location)
= (NftCollectionOne::get(), (Parent,).into());
}
pub type TrustedTeleporters = xcm_builder::Case<NftCollectionOneForRelay>;
@@ -0,0 +1,27 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::teyrchain::RuntimeCall;
use frame_support::parameter_types;
use xcm::latest::prelude::*;
use xcm_builder::FixedWeightBounds;
parameter_types! {
pub const UnitWeightCost: Weight = Weight::from_parts(1, 1);
pub const MaxInstructions: u32 = 100;
}
pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
@@ -0,0 +1,5 @@
hfuzz_target
hfuzz_workspace
cargo
coverage
ccov.zip
@@ -0,0 +1,73 @@
[package]
name = "xcm-simulator-fuzzer"
description = "Examples of xcm-simulator usage."
version = "1.0.0"
authors.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[[bin]]
path = "src/fuzz.rs"
name = "xcm-fuzzer"
[dependencies]
arbitrary = { workspace = true }
codec = { workspace = true, default-features = true }
honggfuzz = { workspace = true }
scale-info = { features = [
"derive",
], workspace = true, default-features = true }
frame-executive = { workspace = true, default-features = true }
frame-support = { workspace = true, default-features = true }
frame-system = { workspace = true, default-features = true }
frame-try-runtime = { workspace = true, default-features = true }
pallet-balances = { workspace = true, default-features = true }
pallet-message-queue = { workspace = true, default-features = true }
sp-core = { workspace = true, default-features = true }
sp-io = { workspace = true, default-features = true }
sp-runtime = { workspace = true, default-features = true }
pallet-xcm = { workspace = true, default-features = true }
pezkuwi-core-primitives = { workspace = true, default-features = true }
pezkuwi-runtime-teyrchains = { workspace = true, default-features = true }
pezkuwi-teyrchain-primitives = { workspace = true, default-features = true }
xcm = { workspace = true, default-features = true }
xcm-builder = { workspace = true, default-features = true }
xcm-executor = { workspace = true, default-features = true }
xcm-simulator = { workspace = true, default-features = true }
[features]
try-runtime = [
"frame-executive/try-runtime",
"frame-support/try-runtime",
"frame-system/try-runtime",
"frame-try-runtime/try-runtime",
"pallet-balances/try-runtime",
"pallet-message-queue/try-runtime",
"pallet-xcm/try-runtime",
"pezkuwi-runtime-teyrchains/try-runtime",
"sp-runtime/try-runtime",
]
runtime-benchmarks = [
"frame-executive/runtime-benchmarks",
"frame-support/runtime-benchmarks",
"frame-system/runtime-benchmarks",
"frame-try-runtime/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"pallet-message-queue/runtime-benchmarks",
"pallet-xcm/runtime-benchmarks",
"pezkuwi-core-primitives/runtime-benchmarks",
"pezkuwi-runtime-teyrchains/runtime-benchmarks",
"pezkuwi-teyrchain-primitives/runtime-benchmarks",
"sp-io/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
"xcm-simulator/runtime-benchmarks",
"xcm/runtime-benchmarks",
]
@@ -0,0 +1,40 @@
# XCM Simulator Fuzzer
This project will fuzz-test the XCM simulator. It can catch reachable panics, timeouts as well as integer overflows and
underflows.
## Install dependencies
```
cargo install honggfuzz --locked
```
## Run the fuzzer
In this directory, run this command:
```
HFUZZ_BUILD_ARGS="--features=try-runtime" cargo hfuzz run xcm-fuzzer
```
## Run a single input
In this directory, run this command:
```
cargo run --features=try-runtime -- hfuzz_workspace/xcm-fuzzer/fuzzer_input_file
```
## Generate coverage
In this directory, run these four commands:
```
RUSTFLAGS="-Zprofile -Ccodegen-units=1 -Copt-level=0 -Clink-dead-code -Coverflow-checks=off -Zpanic_abort_tests -Cpanic=abort" \
CARGO_INCREMENTAL=0 SKIP_WASM_BUILD=1 CARGO_HOME=./cargo cargo build --features=try-runtime
../../../target/debug/xcm-fuzzer hfuzz_workspace/xcm-fuzzer/input/
zip -0 ccov.zip `find ../../../target/ \( -name "*.gc*" -o -name "test-*.gc*" \) -print`
grcov ccov.zip -s ../../../ -t html --llvm --branch --ignore-not-existing -o ./coverage
```
The code coverage will be in `./coverage/index.html`.
@@ -0,0 +1,279 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
// We do not declare all features used by `construct_runtime`
#[allow(unexpected_cfgs)]
mod teyrchain;
// We do not declare all features used by `construct_runtime`
#[allow(unexpected_cfgs)]
mod relay_chain;
use codec::DecodeLimit;
use pezkuwi_core_primitives::AccountId;
use pezkuwi_teyrchain_primitives::primitives::Id as ParaId;
use sp_runtime::{traits::AccountIdConversion, BuildStorage};
use xcm_simulator::{decl_test_network, decl_test_relay_chain, decl_test_teyrchain, TestExt};
#[cfg(feature = "try-runtime")]
use frame_support::traits::{TryState, TryStateSelect::All};
use frame_support::{assert_ok, traits::IntegrityTest};
use xcm::{latest::prelude::*, MAX_XCM_DECODE_DEPTH};
use arbitrary::{Arbitrary, Error, Unstructured};
pub const INITIAL_BALANCE: u128 = 1_000_000_000;
decl_test_teyrchain! {
pub struct ParaA {
Runtime = teyrchain::Runtime,
XcmpMessageHandler = teyrchain::MsgQueue,
DmpMessageHandler = teyrchain::MsgQueue,
new_ext = para_ext(1),
}
}
decl_test_teyrchain! {
pub struct ParaB {
Runtime = teyrchain::Runtime,
XcmpMessageHandler = teyrchain::MsgQueue,
DmpMessageHandler = teyrchain::MsgQueue,
new_ext = para_ext(2),
}
}
decl_test_teyrchain! {
pub struct ParaC {
Runtime = teyrchain::Runtime,
XcmpMessageHandler = teyrchain::MsgQueue,
DmpMessageHandler = teyrchain::MsgQueue,
new_ext = para_ext(3),
}
}
decl_test_relay_chain! {
pub struct Relay {
Runtime = relay_chain::Runtime,
RuntimeCall = relay_chain::RuntimeCall,
RuntimeEvent = relay_chain::RuntimeEvent,
XcmConfig = relay_chain::XcmConfig,
MessageQueue = relay_chain::MessageQueue,
System = relay_chain::System,
new_ext = relay_ext(),
}
}
decl_test_network! {
pub struct MockNet {
relay_chain = Relay,
teyrchains = vec![
(1, ParaA),
(2, ParaB),
(3, ParaC),
],
}
}
// An XCM message that will be generated by the fuzzer through the Arbitrary trait
struct XcmMessage {
// Source chain
source: u32,
// Destination chain
destination: u32,
// XCM message
message: Xcm<()>,
}
impl<'a> Arbitrary<'a> for XcmMessage {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self, Error> {
let source: u32 = u.arbitrary()?;
let destination: u32 = u.arbitrary()?;
let mut encoded_message: &[u8] = u.arbitrary()?;
if let Ok(message) =
DecodeLimit::decode_all_with_depth_limit(MAX_XCM_DECODE_DEPTH, &mut encoded_message)
{
return Ok(XcmMessage { source, destination, message });
}
Err(Error::IncorrectFormat)
}
}
pub fn para_account_id(id: u32) -> relay_chain::AccountId {
ParaId::from(id).into_account_truncating()
}
pub fn para_ext(para_id: u32) -> sp_io::TestExternalities {
use teyrchain::{MsgQueue, Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: (0..6).map(|i| ([i; 32].into(), INITIAL_BALANCE)).collect(),
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
System::set_block_number(1);
MsgQueue::set_para_id(para_id.into());
});
ext
}
pub fn relay_ext() -> sp_io::TestExternalities {
use relay_chain::{Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
let mut balances: Vec<(AccountId, u128)> = vec![];
balances.append(&mut (1..=3).map(|i| (para_account_id(i), INITIAL_BALANCE)).collect());
balances.append(&mut (0..6).map(|i| ([i; 32].into(), INITIAL_BALANCE)).collect());
pallet_balances::GenesisConfig::<Runtime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
pub type RelayChainPalletXcm = pallet_xcm::Pallet<relay_chain::Runtime>;
pub type TeyrchainPalletXcm = pallet_xcm::Pallet<teyrchain::Runtime>;
// We check XCM messages recursively for blocklisted messages
fn recursively_matches_blocklisted_messages(message: &Instruction<()>) -> bool {
match message {
DepositReserveAsset { xcm, .. } |
ExportMessage { xcm, .. } |
InitiateReserveWithdraw { xcm, .. } |
InitiateTeleport { xcm, .. } |
TransferReserveAsset { xcm, .. } |
SetErrorHandler(xcm) |
SetAppendix(xcm) => xcm.iter().any(recursively_matches_blocklisted_messages),
// The blocklisted message is the Transact instruction.
m => matches!(m, Transact { .. }),
}
}
fn run_input(xcm_messages: [XcmMessage; 5]) {
MockNet::reset();
#[cfg(not(fuzzing))]
println!();
for xcm_message in xcm_messages {
if xcm_message.message.iter().any(recursively_matches_blocklisted_messages) {
println!(" skipping message\n");
continue;
}
if xcm_message.source % 4 == 0 {
// We get the destination for the message
let teyrchain_id = (xcm_message.destination % 3) + 1;
let destination: Location = Teyrchain(teyrchain_id).into();
#[cfg(not(fuzzing))]
{
println!(" source: Relay Chain");
println!(" destination: Teyrchain {teyrchain_id}");
println!(" message: {:?}", xcm_message.message);
}
Relay::execute_with(|| {
assert_ok!(RelayChainPalletXcm::send_xcm(Here, destination, xcm_message.message));
})
} else {
// We get the source's execution method
let execute_with = match xcm_message.source % 4 {
1 => ParaA::execute_with,
2 => ParaB::execute_with,
_ => ParaC::execute_with,
};
// We get the destination for the message
let destination: Location = match xcm_message.destination % 4 {
n @ 1..=3 => (Parent, Teyrchain(n)).into(),
_ => Parent.into(),
};
#[cfg(not(fuzzing))]
{
let destination_str = match xcm_message.destination % 4 {
n @ 1..=3 => format!("Teyrchain {n}"),
_ => "Relay Chain".to_string(),
};
println!(" source: Teyrchain {}", xcm_message.source % 4);
println!(" destination: {}", destination_str);
println!(" message: {:?}", xcm_message.message);
}
// We execute the message with the appropriate source and destination
execute_with(|| {
assert_ok!(TeyrchainPalletXcm::send_xcm(Here, destination, xcm_message.message));
});
}
#[cfg(not(fuzzing))]
println!();
// We run integrity tests and try_runtime invariants
[ParaA::execute_with, ParaB::execute_with, ParaC::execute_with].iter().for_each(
|execute_with| {
execute_with(|| {
#[cfg(feature = "try-runtime")]
teyrchain::AllPalletsWithSystem::try_state(Default::default(), All).unwrap();
teyrchain::AllPalletsWithSystem::integrity_test();
});
},
);
Relay::execute_with(|| {
#[cfg(feature = "try-runtime")]
relay_chain::AllPalletsWithSystem::try_state(Default::default(), All).unwrap();
relay_chain::AllPalletsWithSystem::integrity_test();
});
}
}
fn main() {
#[cfg(fuzzing)]
{
loop {
honggfuzz::fuzz!(|xcm_messages: [XcmMessage; 5]| {
run_input(xcm_messages);
})
}
}
#[cfg(not(fuzzing))]
{
use std::{env, fs, fs::File, io::Read};
let args: Vec<_> = env::args().collect();
let md = fs::metadata(&args[1]).unwrap();
let all_files = match md.is_dir() {
true => fs::read_dir(&args[1])
.unwrap()
.map(|x| x.unwrap().path().to_str().unwrap().to_string())
.collect::<Vec<String>>(),
false => (args[1..]).to_vec(),
};
println!("All_files {:?}", all_files);
for argument in all_files {
println!("Now doing file {:?}", argument);
let mut buffer: Vec<u8> = Vec::new();
let mut f = File::open(argument).unwrap();
f.read_to_end(&mut buffer).unwrap();
let mut unstructured = Unstructured::new(&buffer);
if let Ok(xcm_messages) = unstructured.arbitrary() {
run_input(xcm_messages);
}
}
}
}
@@ -0,0 +1,243 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Relay chain runtime mock.
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{Disabled, Everything, Nothing, ProcessMessage, ProcessMessageError},
weights::{Weight, WeightMeter},
};
use frame_system::EnsureRoot;
use sp_core::ConstU32;
use sp_runtime::{
generic,
traits::{BlakeTwo256, IdentifyAccount, Verify},
MultiAddress, MultiSignature,
};
use pezkuwi_runtime_teyrchains::{
configuration,
inclusion::{AggregateMessageOrigin, UmpQueueId},
origin, shared,
};
use pezkuwi_teyrchain_primitives::primitives::Id as ParaId;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, AllowUnpaidExecutionFrom, ChildSystemTeyrchainAsSuperuser,
ChildTeyrchainAsNative, ChildTeyrchainConvertsVia, FixedRateOfFungible, FixedWeightBounds,
FrameTransactionalProcessor, FungibleAdapter, IsConcrete, SignedAccountId32AsNative,
SignedToAccountId32, SovereignSignedViaLocation,
};
use xcm_executor::{Config, XcmExecutor};
pub type TxExtension = (frame_system::CheckNonZeroSender<Runtime>,);
pub type BlockNumber = u64;
pub type Address = MultiAddress<AccountId, ()>;
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
pub type Signature = MultiSignature;
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
pub type Balance = u128;
parameter_types! {
pub const BlockHashCount: u32 = 250;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type AccountId = AccountId;
type Lookup = sp_runtime::traits::AccountIdLookup<AccountId, ()>;
type Block = Block;
type AccountData = pallet_balances::AccountData<Balance>;
}
parameter_types! {
pub ExistentialDeposit: Balance = 1;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
impl shared::Config for Runtime {
type DisabledValidators = ();
}
impl configuration::Config for Runtime {
type WeightInfo = configuration::TestWeightInfo;
}
parameter_types! {
pub const TokenLocation: Location = Here.into_location();
pub const ThisNetwork: NetworkId = NetworkId::ByGenesis([0; 32]);
pub const AnyNetwork: Option<NetworkId> = None;
pub UniversalLocation: InteriorLocation = ThisNetwork::get().into();
}
pub type SovereignAccountOf =
(ChildTeyrchainConvertsVia<ParaId, AccountId>, AccountId32Aliases<ThisNetwork, AccountId>);
pub type LocalAssetTransactor =
FungibleAdapter<Balances, IsConcrete<TokenLocation>, SovereignAccountOf, AccountId, ()>;
type LocalOriginConverter = (
SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
ChildTeyrchainAsNative<origin::Origin, RuntimeOrigin>,
SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
ChildSystemTeyrchainAsSuperuser<ParaId, RuntimeOrigin>,
);
parameter_types! {
pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000);
pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(TokenLocation::get()), 1, 1);
pub const MaxInstructions: u32 = u32::MAX;
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub type XcmRouter = super::RelayChainXcmRouter;
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
pub struct XcmConfig;
impl Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter;
type XcmEventEmitter = ();
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = LocalOriginConverter;
type IsReserve = ();
type IsTeleporter = ();
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
type Trader = FixedRateOfFungible<KsmPerSecondPerByte, ()>;
type ResponseHandler = ();
type AssetTrap = ();
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = ();
type SubscriptionService = ();
type PalletInstancesInfo = ();
type FeeManager = ();
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = ();
}
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>;
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
// Anyone can execute XCM messages locally...
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Nothing;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Everything;
type XcmReserveTransferFilter = Everything;
type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
type UniversalLocation = UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = ();
type SovereignAccountOf = SovereignAccountOf;
type MaxLockers = ConstU32<8>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type WeightInfo = pallet_xcm::TestWeightInfo;
type AdminOrigin = EnsureRoot<AccountId>;
type AuthorizedAliasConsideration = Disabled;
}
impl origin::Config for Runtime {}
parameter_types! {
/// Amount of weight that can be spent per block to service messages.
pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000);
pub const MessageQueueHeapSize: u32 = 65_536;
pub const MessageQueueMaxStale: u32 = 16;
}
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
pub struct MessageProcessor;
impl ProcessMessage for MessageProcessor {
type Origin = AggregateMessageOrigin;
fn process_message(
message: &[u8],
origin: Self::Origin,
meter: &mut WeightMeter,
id: &mut [u8; 32],
) -> Result<bool, ProcessMessageError> {
let para = match origin {
AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
};
xcm_builder::ProcessXcmMessage::<
Junction,
xcm_executor::XcmExecutor<XcmConfig>,
RuntimeCall,
>::process_message(message, Junction::Teyrchain(para.into()), meter, id)
}
}
impl pallet_message_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Size = u32;
type HeapSize = MessageQueueHeapSize;
type MaxStale = MessageQueueMaxStale;
type ServiceWeight = MessageQueueServiceWeight;
type IdleMaxServiceWeight = ();
#[cfg(not(feature = "runtime-benchmarks"))]
type MessageProcessor = MessageProcessor;
#[cfg(feature = "runtime-benchmarks")]
type MessageProcessor =
pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
type QueueChangeHandler = ();
type QueuePausedQuery = ();
type WeightInfo = ();
}
construct_runtime!(
pub enum Runtime
{
System: frame_system,
Balances: pallet_balances,
ParasOrigin: origin,
XcmPallet: pallet_xcm,
MessageQueue: pallet_message_queue,
}
);
@@ -0,0 +1,358 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Teyrchain runtime mock.
use codec::{Decode, Encode};
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{Disabled, Everything, Nothing},
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
};
use frame_system::EnsureRoot;
use sp_runtime::{
generic,
traits::{AccountIdLookup, BlakeTwo256, Hash, IdentifyAccount, Verify},
MultiAddress, MultiSignature,
};
use pallet_xcm::XcmPassthrough;
use pezkuwi_core_primitives::BlockNumber as RelayBlockNumber;
use pezkuwi_teyrchain_primitives::primitives::{
DmpMessageHandler, Id as ParaId, Sibling, XcmpMessageFormat, XcmpMessageHandler,
};
use xcm::{latest::prelude::*, VersionedXcm};
use xcm_builder::{
AccountId32Aliases, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedRateOfFungible,
FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, NativeAsset,
ParentIsPreset, SiblingTeyrchainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation,
};
use xcm_executor::{Config, XcmExecutor};
pub type TxExtension = (frame_system::CheckNonZeroSender<Runtime>,);
pub type BlockNumber = u64;
pub type Address = MultiAddress<AccountId, ()>;
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
pub type Signature = MultiSignature;
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
pub type Balance = u128;
parameter_types! {
pub const BlockHashCount: u32 = 250;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type AccountId = AccountId;
type Lookup = AccountIdLookup<AccountId, ()>;
type Block = Block;
type AccountData = pallet_balances::AccountData<Balance>;
}
parameter_types! {
pub ExistentialDeposit: Balance = 1;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type Balance = Balance;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
}
parameter_types! {
pub const KsmLocation: Location = Location::parent();
pub const RelayNetwork: NetworkId = NetworkId::Kusama;
pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Teyrchain(MsgQueue::teyrchain_id().into())].into();
}
pub type LocationToAccountId = (
ParentIsPreset<AccountId>,
SiblingTeyrchainConvertsVia<Sibling, AccountId>,
AccountId32Aliases<RelayNetwork, AccountId>,
);
pub type XcmOriginToCallOrigin = (
SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
XcmPassthrough<RuntimeOrigin>,
);
parameter_types! {
pub const UnitWeightCost: Weight = Weight::from_parts(1, 1);
pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1, 1);
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
}
pub type LocalAssetTransactor =
FungibleAdapter<Balances, IsConcrete<KsmLocation>, LocationToAccountId, AccountId, ()>;
pub type XcmRouter = super::TeyrchainXcmRouter<MsgQueue>;
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
pub struct XcmConfig;
impl Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter;
type XcmEventEmitter = ();
type AssetTransactor = LocalAssetTransactor;
type OriginConverter = XcmOriginToCallOrigin;
type IsReserve = NativeAsset;
type IsTeleporter = ();
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type Trader = FixedRateOfFungible<KsmPerSecondPerByte, ()>;
type ResponseHandler = ();
type AssetTrap = ();
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = ();
type SubscriptionService = ();
type PalletInstancesInfo = ();
type FeeManager = ();
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = ();
}
#[frame_support::pallet]
pub mod mock_msg_queue {
use super::*;
use frame_support::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config {
#[allow(deprecated)]
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::call]
impl<T: Config> Pallet<T> {}
#[pallet::storage]
pub(super) type TeyrchainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
#[pallet::storage]
/// A queue of received DMP messages
pub(super) type ReceivedDmp<T: Config> = StorageValue<_, Vec<Xcm<T::RuntimeCall>>, ValueQuery>;
impl<T: Config> Get<ParaId> for Pallet<T> {
fn get() -> ParaId {
Self::teyrchain_id()
}
}
pub type MessageId = [u8; 32];
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
// XCMP
/// Some XCM was executed OK.
Success(Option<T::Hash>),
/// Some XCM failed.
Fail(Option<T::Hash>, XcmError),
/// Bad XCM version used.
BadVersion(Option<T::Hash>),
/// Bad XCM format used.
BadFormat(Option<T::Hash>),
// DMP
/// Downward message is invalid XCM.
InvalidFormat(MessageId),
/// Downward message is unsupported version of XCM.
UnsupportedVersion(MessageId),
/// Downward message executed with the given outcome.
ExecutedDownward(MessageId, Outcome),
}
impl<T: Config> Pallet<T> {
pub fn teyrchain_id() -> ParaId {
TeyrchainId::<T>::get()
}
pub fn received_dmp() -> Vec<Xcm<T::RuntimeCall>> {
ReceivedDmp::<T>::get()
}
pub fn set_para_id(para_id: ParaId) {
TeyrchainId::<T>::put(para_id);
}
fn handle_xcmp_message(
sender: ParaId,
_sent_at: RelayBlockNumber,
xcm: VersionedXcm<T::RuntimeCall>,
max_weight: Weight,
) -> Result<Weight, XcmError> {
let hash = Encode::using_encoded(&xcm, T::Hashing::hash);
let mut message_hash = xcm.using_encoded(sp_io::hashing::blake2_256);
let (result, event) = match Xcm::<T::RuntimeCall>::try_from(xcm) {
Ok(xcm) => {
let location = Location::new(1, [Teyrchain(sender.into())]);
match T::XcmExecutor::prepare_and_execute(
location,
xcm,
&mut message_hash,
max_weight,
Weight::zero(),
) {
Outcome::Error(InstructionError { error, .. }) =>
(Err(error), Event::Fail(Some(hash), error)),
Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))),
// As far as the caller is concerned, this was dispatched without error, so
// we just report the weight used.
Outcome::Incomplete {
used, error: InstructionError { error, .. }, ..
} => (Ok(used), Event::Fail(Some(hash), error)),
}
},
Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))),
};
Self::deposit_event(event);
result
}
}
impl<T: Config> XcmpMessageHandler for Pallet<T> {
fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
iter: I,
max_weight: Weight,
) -> Weight {
for (sender, sent_at, data) in iter {
let mut data_ref = data;
let _ = XcmpMessageFormat::decode(&mut data_ref)
.expect("Simulator encodes with versioned xcm format; qed");
let mut remaining_fragments = data_ref;
while !remaining_fragments.is_empty() {
if let Ok(xcm) =
VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
{
let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
} else {
debug_assert!(false, "Invalid incoming XCMP message data");
}
}
}
max_weight
}
}
impl<T: Config> DmpMessageHandler for Pallet<T> {
fn handle_dmp_messages(
iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
limit: Weight,
) -> Weight {
for (_i, (_sent_at, data)) in iter.enumerate() {
let mut id = sp_io::hashing::blake2_256(&data[..]);
let maybe_msg = VersionedXcm::<T::RuntimeCall>::decode(&mut &data[..])
.map(Xcm::<T::RuntimeCall>::try_from);
match maybe_msg {
Err(_) => {
Self::deposit_event(Event::InvalidFormat(id));
},
Ok(Err(())) => {
Self::deposit_event(Event::UnsupportedVersion(id));
},
Ok(Ok(x)) => {
let outcome = T::XcmExecutor::prepare_and_execute(
Parent,
x.clone(),
&mut id,
limit,
Weight::zero(),
);
<ReceivedDmp<T>>::append(x);
Self::deposit_event(Event::ExecutedDownward(id, outcome));
},
}
}
limit
}
}
}
impl mock_msg_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
}
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
impl pallet_xcm::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = Nothing;
type XcmReserveTransferFilter = Everything;
type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
type UniversalLocation = UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type TrustedLockers = ();
type SovereignAccountOf = LocationToAccountId;
type MaxLockers = frame_support::traits::ConstU32<8>;
type MaxRemoteLockConsumers = frame_support::traits::ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type WeightInfo = pallet_xcm::TestWeightInfo;
type AdminOrigin = EnsureRoot<AccountId>;
type AuthorizedAliasConsideration = Disabled;
}
construct_runtime!(
pub enum Runtime
{
System: frame_system,
Balances: pallet_balances,
MsgQueue: mock_msg_queue,
PezkuwiXcm: pallet_xcm,
}
);
+640
View File
@@ -0,0 +1,640 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Test kit to simulate cross-chain message passing and XCM execution.
/// Implementation of a simple message queue.
/// Used for sending messages.
pub mod mock_message_queue;
extern crate alloc;
pub use codec::Encode;
pub use paste;
pub use alloc::collections::vec_deque::VecDeque;
pub use core::{cell::RefCell, marker::PhantomData};
pub use frame_support::{
traits::{EnqueueMessage, Get, ProcessMessage, ProcessMessageError, ServiceQueues},
weights::{Weight, WeightMeter},
};
pub use sp_io::{hashing::blake2_256, TestExternalities};
pub use pezkuwi_core_primitives::BlockNumber as RelayBlockNumber;
pub use pezkuwi_runtime_teyrchains::{
dmp,
inclusion::{AggregateMessageOrigin, UmpQueueId},
};
pub use pezkuwi_teyrchain_primitives::primitives::{
DmpMessageHandler as DmpMessageHandlerT, Id as ParaId, XcmpMessageFormat,
XcmpMessageHandler as XcmpMessageHandlerT,
};
pub use xcm::{latest::prelude::*, VersionedXcm};
pub use xcm_builder::ProcessXcmMessage;
pub use xcm_executor::XcmExecutor;
pub trait TestExt {
/// Initialize the test environment.
fn new_ext() -> sp_io::TestExternalities;
/// Resets the state of the test environment.
fn reset_ext();
/// Execute code in the context of the test externalities, without automatic
/// message processing. All messages in the message buses can be processed
/// by calling `Self::dispatch_xcm_buses()`.
fn execute_without_dispatch<R>(execute: impl FnOnce() -> R) -> R;
/// Process all messages in the message buses
fn dispatch_xcm_buses();
/// Execute some code in the context of the test externalities, with
/// automatic message processing.
/// Messages are dispatched once the passed closure completes.
fn execute_with<R>(execute: impl FnOnce() -> R) -> R {
let result = Self::execute_without_dispatch(execute);
Self::dispatch_xcm_buses();
result
}
}
pub enum MessageKind {
Ump,
Dmp,
Xcmp,
}
/// Encodes the provided XCM message based on the `message_kind`.
pub fn encode_xcm(message: Xcm<()>, message_kind: MessageKind) -> Vec<u8> {
match message_kind {
MessageKind::Ump | MessageKind::Dmp => VersionedXcm::<()>::from(message).encode(),
MessageKind::Xcmp => {
let fmt = XcmpMessageFormat::ConcatenatedVersionedXcm;
let mut outbound = fmt.encode();
let encoded = VersionedXcm::<()>::from(message).encode();
outbound.extend_from_slice(&encoded[..]);
outbound
},
}
}
pub fn fake_message_hash<T>(message: &Xcm<T>) -> XcmHash {
message.using_encoded(blake2_256)
}
/// The macro is implementing upward message passing(UMP) for the provided relay
/// chain struct. The struct has to provide the XCM configuration for the relay
/// chain.
///
/// ```ignore
/// decl_test_relay_chain! {
/// pub struct Relay {
/// Runtime = relay_chain::Runtime,
/// XcmConfig = relay_chain::XcmConfig,
/// new_ext = relay_ext(),
/// }
/// }
/// ```
#[macro_export]
#[rustfmt::skip]
macro_rules! decl_test_relay_chain {
(
pub struct $name:ident {
Runtime = $runtime:path,
RuntimeCall = $runtime_call:path,
RuntimeEvent = $runtime_event:path,
XcmConfig = $xcm_config:path,
MessageQueue = $mq:path,
System = $system:path,
new_ext = $new_ext:expr,
}
) => {
pub struct $name;
$crate::__impl_ext!($name, $new_ext);
impl $crate::ProcessMessage for $name {
type Origin = $crate::ParaId;
fn process_message(
msg: &[u8],
para: Self::Origin,
meter: &mut $crate::WeightMeter,
id: &mut [u8; 32],
) -> Result<bool, $crate::ProcessMessageError> {
use $crate::{Weight, AggregateMessageOrigin, UmpQueueId, ServiceQueues, EnqueueMessage};
use $mq as message_queue;
use $runtime_event as runtime_event;
Self::execute_with(|| {
<$mq as EnqueueMessage<AggregateMessageOrigin>>::enqueue_message(
msg.try_into().expect("Message too long"),
AggregateMessageOrigin::Ump(UmpQueueId::Para(para.clone()))
);
<$system>::reset_events();
<$mq as ServiceQueues>::service_queues(Weight::MAX);
let events = <$system>::events();
let event = events.last().expect("There must be at least one event");
match &event.event {
runtime_event::MessageQueue(
pallet_message_queue::Event::Processed {origin, ..}) => {
assert_eq!(origin, &AggregateMessageOrigin::Ump(UmpQueueId::Para(para)));
},
event => panic!("Unexpected event: {:#?}", event),
}
Ok(true)
})
}
}
};
}
/// The macro is implementing the `XcmMessageHandlerT` and `DmpMessageHandlerT`
/// traits for the provided teyrchain struct. Expects the provided teyrchain
/// struct to define the XcmpMessageHandler and DmpMessageHandler pallets that
/// contain the message handling logic.
///
/// ```ignore
/// decl_test_teyrchain! {
/// pub struct ParaA {
/// Runtime = teyrchain::Runtime,
/// XcmpMessageHandler = teyrchain::MsgQueue,
/// DmpMessageHandler = teyrchain::MsgQueue,
/// new_ext = para_ext(),
/// }
/// }
/// ```
#[macro_export]
macro_rules! decl_test_teyrchain {
(
pub struct $name:ident {
Runtime = $runtime:path,
XcmpMessageHandler = $xcmp_message_handler:path,
DmpMessageHandler = $dmp_message_handler:path,
new_ext = $new_ext:expr,
}
) => {
pub struct $name;
$crate::__impl_ext!($name, $new_ext);
impl $crate::XcmpMessageHandlerT for $name {
fn handle_xcmp_messages<
'a,
I: Iterator<Item = ($crate::ParaId, $crate::RelayBlockNumber, &'a [u8])>,
>(
iter: I,
max_weight: $crate::Weight,
) -> $crate::Weight {
use $crate::{TestExt, XcmpMessageHandlerT};
$name::execute_with(|| {
<$xcmp_message_handler>::handle_xcmp_messages(iter, max_weight)
})
}
}
impl $crate::DmpMessageHandlerT for $name {
fn handle_dmp_messages(
iter: impl Iterator<Item = ($crate::RelayBlockNumber, Vec<u8>)>,
max_weight: $crate::Weight,
) -> $crate::Weight {
use $crate::{DmpMessageHandlerT, TestExt};
$name::execute_with(|| {
<$dmp_message_handler>::handle_dmp_messages(iter, max_weight)
})
}
}
};
}
/// Implements the `TestExt` trait for a specified struct.
#[macro_export]
macro_rules! __impl_ext {
// entry point: generate ext name
($name:ident, $new_ext:expr) => {
$crate::paste::paste! {
$crate::__impl_ext!(@impl $name, $new_ext, [<EXT_ $name:upper>]);
}
};
// impl
(@impl $name:ident, $new_ext:expr, $ext_name:ident) => {
thread_local! {
pub static $ext_name: $crate::RefCell<$crate::TestExternalities>
= $crate::RefCell::new($new_ext);
}
impl $crate::TestExt for $name {
fn new_ext() -> $crate::TestExternalities {
$new_ext
}
fn reset_ext() {
$ext_name.with(|v| *v.borrow_mut() = $new_ext);
}
fn execute_without_dispatch<R>(execute: impl FnOnce() -> R) -> R {
$ext_name.with(|v| v.borrow_mut().execute_with(execute))
}
fn dispatch_xcm_buses() {
while exists_messages_in_any_bus() {
if let Err(xcm_error) = process_relay_messages() {
panic!("Relay chain XCM execution failure: {:?}", xcm_error);
}
if let Err(xcm_error) = process_para_messages() {
panic!("Teyrchain XCM execution failure: {:?}", xcm_error);
}
}
}
}
};
}
thread_local! {
pub static PARA_MESSAGE_BUS: RefCell<VecDeque<(ParaId, Location, Xcm<()>)>>
= RefCell::new(VecDeque::new());
pub static RELAY_MESSAGE_BUS: RefCell<VecDeque<(Location, Xcm<()>)>>
= RefCell::new(VecDeque::new());
}
/// Declares a test network that consists of a relay chain and multiple
/// teyrchains. Expects a network struct as an argument and implements testing
/// functionality, `TeyrchainXcmRouter` and the `RelayChainXcmRouter`. The
/// struct needs to contain the relay chain struct and an indexed list of
/// teyrchains that are going to be in the network.
///
/// ```ignore
/// decl_test_network! {
/// pub struct ExampleNet {
/// relay_chain = Relay,
/// teyrchains = vec![
/// (1, ParaA),
/// (2, ParaB),
/// ],
/// }
/// }
/// ```
#[macro_export]
macro_rules! decl_test_network {
(
pub struct $name:ident {
relay_chain = $relay_chain:ty,
teyrchains = vec![ $( ($para_id:expr, $teyrchain:ty), )* ],
}
) => {
use $crate::Encode;
pub struct $name;
impl $name {
pub fn reset() {
use $crate::{TestExt, VecDeque};
// Reset relay chain message bus.
$crate::RELAY_MESSAGE_BUS.with(|b| b.replace(VecDeque::new()));
// Reset teyrchain message bus.
$crate::PARA_MESSAGE_BUS.with(|b| b.replace(VecDeque::new()));
<$relay_chain>::reset_ext();
$( <$teyrchain>::reset_ext(); )*
}
}
/// Check if any messages exist in either message bus.
fn exists_messages_in_any_bus() -> bool {
use $crate::{RELAY_MESSAGE_BUS, PARA_MESSAGE_BUS};
let no_relay_messages_left = RELAY_MESSAGE_BUS.with(|b| b.borrow().is_empty());
let no_teyrchain_messages_left = PARA_MESSAGE_BUS.with(|b| b.borrow().is_empty());
!(no_relay_messages_left && no_teyrchain_messages_left)
}
/// Process all messages originating from teyrchains.
fn process_para_messages() -> $crate::XcmResult {
use $crate::{ProcessMessage, XcmpMessageHandlerT};
while let Some((para_id, destination, message)) = $crate::PARA_MESSAGE_BUS.with(
|b| b.borrow_mut().pop_front()) {
match destination.unpack() {
(1, []) => {
let encoded = $crate::encode_xcm(message, $crate::MessageKind::Ump);
let mut _id = [0; 32];
let r = <$relay_chain>::process_message(
encoded.as_slice(), para_id,
&mut $crate::WeightMeter::new(),
&mut _id,
);
match r {
Err($crate::ProcessMessageError::Overweight(required)) =>
return Err($crate::XcmError::WeightLimitReached(required)),
// Not really the correct error, but there is no "undecodable".
Err(_) => return Err($crate::XcmError::Unimplemented),
Ok(_) => (),
}
},
$(
(1, [$crate::Teyrchain(id)]) if *id == $para_id => {
let encoded = $crate::encode_xcm(message, $crate::MessageKind::Xcmp);
let messages = vec![(para_id, 1, &encoded[..])];
let _weight = <$teyrchain>::handle_xcmp_messages(
messages.into_iter(),
$crate::Weight::MAX,
);
},
)*
_ => {
return Err($crate::XcmError::Unroutable);
}
}
}
Ok(())
}
/// Process all messages originating from the relay chain.
fn process_relay_messages() -> $crate::XcmResult {
use $crate::DmpMessageHandlerT;
while let Some((destination, message)) = $crate::RELAY_MESSAGE_BUS.with(
|b| b.borrow_mut().pop_front()) {
match destination.unpack() {
$(
(0, [$crate::Teyrchain(id)]) if *id == $para_id => {
let encoded = $crate::encode_xcm(message, $crate::MessageKind::Dmp);
// NOTE: RelayChainBlockNumber is hard-coded to 1
let messages = vec![(1, encoded)];
let _weight = <$teyrchain>::handle_dmp_messages(
messages.into_iter(), $crate::Weight::MAX,
);
},
)*
_ => return Err($crate::XcmError::Transport("Only sends to children teyrchain.")),
}
}
Ok(())
}
/// XCM router for teyrchain.
pub struct TeyrchainXcmRouter<T>($crate::PhantomData<T>);
impl<T: $crate::Get<$crate::ParaId>> $crate::SendXcm for TeyrchainXcmRouter<T> {
type Ticket = ($crate::ParaId, $crate::Location, $crate::Xcm<()>);
fn validate(
destination: &mut Option<$crate::Location>,
message: &mut Option<$crate::Xcm<()>>,
) -> $crate::SendResult<($crate::ParaId, $crate::Location, $crate::Xcm<()>)> {
use $crate::XcmpMessageHandlerT;
let d = destination.take().ok_or($crate::SendError::MissingArgument)?;
match d.unpack() {
(1, []) => {},
$(
(1, [$crate::Teyrchain(id)]) if id == &$para_id => {}
)*
_ => {
*destination = Some(d);
return Err($crate::SendError::NotApplicable)
},
}
let m = message.take().ok_or($crate::SendError::MissingArgument)?;
Ok(((T::get(), d, m), $crate::Assets::new()))
}
fn deliver(
triple: ($crate::ParaId, $crate::Location, $crate::Xcm<()>),
) -> Result<$crate::XcmHash, $crate::SendError> {
let hash = $crate::helpers::derive_topic_id(&triple.2);
$crate::PARA_MESSAGE_BUS.with(|b| b.borrow_mut().push_back(triple));
Ok(hash)
}
}
/// XCM router for relay chain.
pub struct RelayChainXcmRouter;
impl $crate::SendXcm for RelayChainXcmRouter {
type Ticket = ($crate::Location, $crate::Xcm<()>);
fn validate(
destination: &mut Option<$crate::Location>,
message: &mut Option<$crate::Xcm<()>>,
) -> $crate::SendResult<($crate::Location, $crate::Xcm<()>)> {
use $crate::DmpMessageHandlerT;
let d = destination.take().ok_or($crate::SendError::MissingArgument)?;
match d.unpack() {
$(
(0, [$crate::Teyrchain(id)]) if id == &$para_id => {},
)*
_ => {
*destination = Some(d);
return Err($crate::SendError::NotApplicable)
},
}
let m = message.take().ok_or($crate::SendError::MissingArgument)?;
Ok(((d, m), $crate::Assets::new()))
}
fn deliver(
pair: ($crate::Location, $crate::Xcm<()>),
) -> Result<$crate::XcmHash, $crate::SendError> {
let hash = $crate::helpers::derive_topic_id(&pair.1);
$crate::RELAY_MESSAGE_BUS.with(|b| b.borrow_mut().push_back(pair));
Ok(hash)
}
}
};
}
pub mod helpers {
use super::*;
use sp_runtime::testing::H256;
use std::collections::{HashMap, HashSet};
/// Derives a topic ID for an XCM in tests.
pub fn derive_topic_id<T>(message: &Xcm<T>) -> XcmHash {
if let Some(SetTopic(topic_id)) = message.last() {
*topic_id
} else {
fake_message_hash(message)
}
}
/// A test utility for tracking XCM topic IDs.
///
/// # Examples
///
/// ```
/// use sp_runtime::testing::H256;
/// use xcm_simulator::helpers::TopicIdTracker;
///
/// // Dummy topic IDs
/// let topic_id = H256::repeat_byte(0x42);
///
/// // Create a new tracker
/// let mut tracker = TopicIdTracker::new();
///
/// // Insert the same topic ID for three chains
/// tracker.insert("ChainA", topic_id);
/// tracker.insert_all("ChainB", &[topic_id]);
/// tracker.insert_and_assert_unique("ChainC", topic_id);
///
/// // Assert the topic ID exists everywhere
/// tracker.assert_contains("ChainA", &topic_id);
/// tracker.assert_id_seen_on_all_chains(&topic_id);
/// tracker.assert_only_id_seen_on_all_chains("ChainB");
/// tracker.assert_unique();
///
/// // You can also test that inserting inconsistent topic IDs fails:
/// let another_id = H256::repeat_byte(0x43);
/// let result = std::panic::catch_unwind(|| {
/// let mut tracker = TopicIdTracker::new();
/// tracker.insert("ChainA", topic_id);
/// tracker.insert_and_assert_unique("ChainB", another_id);
/// });
/// assert!(result.is_err());
///
/// let result = std::panic::catch_unwind(|| {
/// let mut tracker = TopicIdTracker::new();
/// tracker.insert("ChainA", topic_id);
/// tracker.insert("ChainB", another_id);
/// tracker.assert_unique();
/// });
/// assert!(result.is_err());
/// ```
#[derive(Clone, Debug)]
pub struct TopicIdTracker {
ids: HashMap<String, HashSet<H256>>,
}
impl TopicIdTracker {
/// Initialises a new, empty topic ID tracker.
pub fn new() -> Self {
TopicIdTracker { ids: HashMap::new() }
}
/// Asserts that the given topic ID has been recorded for the specified chain.
pub fn assert_contains(&self, chain: &str, id: &H256) {
let ids = self
.ids
.get(chain)
.expect(&format!("No topic IDs recorded for chain '{}'", chain));
assert!(
ids.contains(id),
"Expected topic ID {:?} not found for chain '{}'. Found topic IDs: {:?}",
id,
chain,
ids
);
}
/// Asserts that the given topic ID has been recorded on all chains.
pub fn assert_id_seen_on_all_chains(&self, id: &H256) {
self.ids.keys().for_each(|chain| {
self.assert_contains(chain, id);
});
}
/// Asserts that exactly one topic ID is recorded on the given chain, and that the same ID
/// is present on all other chains.
pub fn assert_only_id_seen_on_all_chains(&self, chain: &str) {
let ids = self
.ids
.get(chain)
.expect(&format!("No topic IDs recorded for chain '{}'", chain));
assert_eq!(
ids.len(),
1,
"Expected exactly one topic ID for chain '{}', but found {}: {:?}",
chain,
ids.len(),
ids
);
let id = *ids.iter().next().unwrap();
self.assert_id_seen_on_all_chains(&id);
}
/// Asserts that exactly one unique topic ID is present across all captured entries.
pub fn assert_unique(&self) {
let unique_ids: HashSet<_> = self.ids.values().flatten().collect();
assert_eq!(
unique_ids.len(),
1,
"Expected exactly one topic ID, found {}: {:?}",
unique_ids.len(),
unique_ids
);
}
/// Inserts a topic ID with the given chain name in the captor.
pub fn insert(&mut self, chain: &str, id: H256) {
self.ids.entry(chain.to_string()).or_default().insert(id);
}
/// Inserts all topic IDs associated with the given chain name.
pub fn insert_all(&mut self, chain: &str, ids: &[H256]) {
ids.iter().for_each(|&id| self.insert(chain, id));
}
/// Inserts a topic ID for a given chain and then asserts global uniqueness.
pub fn insert_and_assert_unique(&mut self, chain: &str, id: H256) {
if let Some(existing_ids) = self.ids.get(chain) {
assert_eq!(
existing_ids.len(),
1,
"Expected exactly one topic ID for chain '{}', but found: {:?}",
chain,
existing_ids
);
let existing_id =
*existing_ids.iter().next().expect(&format!("Topic ID for chain '{}'", chain));
assert_eq!(
id, existing_id,
"Topic ID mismatch for chain '{}': expected {:?}, got {:?}",
id, existing_id, chain
);
} else {
self.insert(chain, id);
}
self.assert_unique();
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_runtime::testing::H256;
#[test]
#[should_panic(expected = "Expected exactly one topic ID")]
fn test_assert_unique_fails_with_multiple_ids() {
let mut tracker = TopicIdTracker::new();
let id1 = H256::repeat_byte(0x42);
let id2 = H256::repeat_byte(0x43);
tracker.insert("ChainA", id1);
tracker.insert("ChainB", id2);
tracker.assert_unique();
}
#[test]
#[should_panic(expected = "Topic ID mismatch")]
fn test_insert_and_assert_unique_mismatch() {
let mut tracker = TopicIdTracker::new();
let id1 = H256::repeat_byte(0x42);
let id2 = H256::repeat_byte(0x43);
tracker.insert_and_assert_unique("ChainA", id1);
tracker.insert_and_assert_unique("ChainA", id2);
}
}
}
@@ -0,0 +1,191 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Simple mock message queue.
use codec::{Decode, Encode};
use pezkuwi_primitives::BlockNumber as RelayBlockNumber;
use pezkuwi_teyrchain_primitives::primitives::{
DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler,
};
use sp_runtime::traits::{Get, Hash};
use xcm::{latest::prelude::*, VersionedXcm};
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config {
#[allow(deprecated)]
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type XcmExecutor: ExecuteXcm<Self::RuntimeCall>;
}
#[pallet::call]
impl<T: Config> Pallet<T> {}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::storage]
pub type TeyrchainId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
#[pallet::storage]
/// A queue of received DMP messages
pub type ReceivedDmp<T: Config> = StorageValue<_, Vec<Xcm<T::RuntimeCall>>, ValueQuery>;
impl<T: Config> Get<ParaId> for Pallet<T> {
fn get() -> ParaId {
TeyrchainId::<T>::get()
}
}
pub type MessageId = [u8; 32];
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
// XCMP
/// Some XCM was executed OK.
Success { message_id: Option<T::Hash> },
/// Some XCM failed.
Fail { message_id: Option<T::Hash>, error: XcmError },
/// Bad XCM version used.
BadVersion { message_id: Option<T::Hash> },
/// Bad XCM format used.
BadFormat { message_id: Option<T::Hash> },
// DMP
/// Downward message is invalid XCM.
InvalidFormat { message_id: MessageId },
/// Downward message is unsupported version of XCM.
UnsupportedVersion { message_id: MessageId },
/// Downward message executed with the given outcome.
ExecutedDownward { message_id: MessageId, outcome: Outcome },
}
impl<T: Config> Pallet<T> {
pub fn set_para_id(para_id: ParaId) {
TeyrchainId::<T>::put(para_id);
}
fn handle_xcmp_message(
sender: ParaId,
_sent_at: RelayBlockNumber,
xcm: VersionedXcm<T::RuntimeCall>,
max_weight: xcm::latest::Weight,
) -> Result<xcm::latest::Weight, XcmError> {
let hash = Encode::using_encoded(&xcm, T::Hashing::hash);
let mut message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256);
let (result, event) = match Xcm::<T::RuntimeCall>::try_from(xcm) {
Ok(xcm) => {
let location = (Parent, Teyrchain(sender.into()));
match T::XcmExecutor::prepare_and_execute(
location,
xcm,
&mut message_hash,
max_weight,
Weight::zero(),
) {
Outcome::Error(InstructionError { error, .. }) =>
(Err(error), Event::Fail { message_id: Some(hash), error }),
Outcome::Complete { used } =>
(Ok(used), Event::Success { message_id: Some(hash) }),
// As far as the caller is concerned, this was dispatched without error, so
// we just report the weight used.
Outcome::Incomplete {
used, error: InstructionError { error, .. }, ..
} => (Ok(used), Event::Fail { message_id: Some(hash), error }),
}
},
Err(()) => (
Err(XcmError::UnhandledXcmVersion),
Event::BadVersion { message_id: Some(hash) },
),
};
Self::deposit_event(event);
result
}
}
impl<T: Config> XcmpMessageHandler for Pallet<T> {
fn handle_xcmp_messages<'a, I: Iterator<Item = (ParaId, RelayBlockNumber, &'a [u8])>>(
iter: I,
max_weight: xcm::latest::Weight,
) -> xcm::latest::Weight {
for (sender, sent_at, data) in iter {
let mut data_ref = data;
let _ = XcmpMessageFormat::decode(&mut data_ref)
.expect("Simulator encodes with versioned xcm format; qed");
let mut remaining_fragments = data_ref;
while !remaining_fragments.is_empty() {
if let Ok(xcm) =
VersionedXcm::<T::RuntimeCall>::decode(&mut remaining_fragments)
{
let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight);
} else {
debug_assert!(false, "Invalid incoming XCMP message data");
}
}
}
max_weight
}
}
impl<T: Config> DmpMessageHandler for Pallet<T> {
fn handle_dmp_messages(
iter: impl Iterator<Item = (RelayBlockNumber, Vec<u8>)>,
limit: Weight,
) -> Weight {
for (_sent_at, data) in iter {
let mut id = sp_io::hashing::blake2_256(&data[..]);
let maybe_versioned = VersionedXcm::<T::RuntimeCall>::decode(&mut &data[..]);
match maybe_versioned {
Err(_) => {
Self::deposit_event(Event::InvalidFormat { message_id: id });
},
Ok(versioned) => match Xcm::try_from(versioned) {
Err(()) =>
Self::deposit_event(Event::UnsupportedVersion { message_id: id }),
Ok(x) => {
let outcome = T::XcmExecutor::prepare_and_execute(
Parent,
x.clone(),
&mut id,
limit,
Weight::zero(),
);
ReceivedDmp::<T>::append(x);
Self::deposit_event(Event::ExecutedDownward {
message_id: id,
outcome,
});
},
},
}
}
limit
}
}
}