difftreelog
refactor xcm transact forbidden test
in: master
17 files changed
runtime/common/tests/mod.rsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617use sp_runtime::BuildStorage;17use sp_runtime::{BuildStorage, Storage};18use sp_core::{Public, Pair};18use sp_core::{Public, Pair};19use sp_std::vec;19use sp_std::vec;20use up_common::types::AuraId;20use up_common::types::AuraId;21use crate::{GenesisConfig, ParachainInfoConfig};21use crate::{Runtime, GenesisConfig, ParachainInfoConfig, RuntimeEvent, System};2223pub use sp_runtime::AccountId32 as AccountId;24pub type Balance = u128;222523pub mod xcm;26pub mod xcm;2728#[cfg(any(feature = "opal-runtime", feature = "quartz-runtime"))]29/// PARA_ID for Opal/Sapphire/Quartz30const PARA_ID: u32 = 2095;3132#[cfg(feature = "unique-runtime")]33/// PARA_ID for Unique34const PARA_ID: u32 = 2037;243525fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {36fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {26 TPublic::Pair::from_string(&format!("//{}", seed), None)37 TPublic::Pair::from_string(&format!("//{}", seed), None)27 .expect("static values are valid; qed")38 .expect("static values are valid; qed")28 .public()39 .public()29}40}4142fn last_events(n: usize) -> Vec<RuntimeEvent> {43 System::events().into_iter().map(|e| e.event).rev().take(n).rev().collect()44}4546fn new_test_ext(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {47 let mut storage = make_basic_storage();4849 pallet_balances::GenesisConfig::<Runtime> { balances }50 .assimilate_storage(&mut storage)51 .unwrap();5253 let mut ext = sp_io::TestExternalities::new(storage);54 ext.execute_with(|| System::set_block_number(1));55 ext56}305731#[cfg(feature = "collator-selection")]58#[cfg(feature = "collator-selection")]32fn new_test_ext(para_id: u32) -> sp_io::TestExternalities {59fn make_basic_storage() -> Storage {33 use sp_core::{sr25519};60 use sp_core::{sr25519};34 use sp_runtime::traits::{IdentifyAccount, Verify};61 use sp_runtime::traits::{IdentifyAccount, Verify};35 use crate::{AccountId, Signature, SessionKeys, CollatorSelectionConfig, SessionConfig};62 use crate::{AccountId, Signature, SessionKeys, CollatorSelectionConfig, SessionConfig};66 collator_selection: CollatorSelectionConfig { invulnerables },93 collator_selection: CollatorSelectionConfig { invulnerables },67 session: SessionConfig { keys },94 session: SessionConfig { keys },68 parachain_info: ParachainInfoConfig {95 parachain_info: ParachainInfoConfig {69 parachain_id: para_id.into(),96 parachain_id: PARA_ID.into(),70 },97 },71 ..GenesisConfig::default()98 ..GenesisConfig::default()72 };99 };75}102}7610377#[cfg(not(feature = "collator-selection"))]104#[cfg(not(feature = "collator-selection"))]78fn new_test_ext(para_id: u32) -> sp_io::TestExternalities {105fn make_basic_storage() -> Storage {79 use crate::AuraConfig;106 use crate::AuraConfig;8010781 let cfg = GenesisConfig {108 let cfg = GenesisConfig {86 ],113 ],87 },114 },88 parachain_info: ParachainInfoConfig {115 parachain_info: ParachainInfoConfig {89 parachain_id: para_id.into(),116 parachain_id: PARA_ID.into(),90 },117 },91 ..GenesisConfig::default()118 ..GenesisConfig::default()92 };119 };runtime/common/tests/xcm.rsdiffbeforeafterboth14// You should have received a copy of the GNU General Public License14// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.161617use xcm_executor::traits::ShouldExecute;18use xcm::latest::prelude::*;17use xcm::{18 VersionedXcm,19 latest::{prelude::*, Error}20};19use logtest::Logger;21use codec::Encode;20use crate::RuntimeCall;22use crate::{Runtime, RuntimeCall, RuntimeOrigin, RuntimeEvent, PolkadotXcm};21use super::new_test_ext;23use super::{new_test_ext, last_events, AccountId};22use frame_support::pallet_prelude::Weight;24use frame_support::{2325 pallet_prelude::Weight,24fn catch_xcm_barrier_log(logger: &mut Logger, expected_msg: &str) -> Result<(), String> {26};25 for record in logger {26 if record.target() == "xcm::barrier" && record.args() == expected_msg {27 return Ok(());28 }29 }3031 Err(format!(32 "the expected XCM barrier log `{}` is not found",33 expected_msg34 ))35}3637/// WARNING: Uses log capturing38/// See https://docs.rs/logtest/latest/logtest/index.html#constraints39pub fn barrier_denies_transact<B: ShouldExecute>(logger: &mut Logger) {40 let location = MultiLocation {41 parents: 0,42 interior: Junctions::Here,43 };4445 // We will never decode this "call",46 // so it is irrelevant what we are passing to the `transact` cmd.47 let fake_encoded_call = vec![0u8];4849 let transact_inst: Instruction<RuntimeCall> = Transact {50 origin_kind: OriginKind::Superuser,51 require_weight_at_most: Weight::default(),52 call: fake_encoded_call.into(),53 };5455 let mut xcm_program = vec![transact_inst];5657 let max_weight = Weight::from_parts(100_000, 100_000);58 let mut weight_credit = Weight::from_parts(100_000_000, 100_000_000);5960 let result = B::should_execute(&location, &mut xcm_program, max_weight, &mut weight_credit);6162 assert!(63 result.is_err(),64 "the barrier should disallow the XCM transact cmd"65 );6667 catch_xcm_barrier_log(logger, "transact XCM rejected").unwrap();68}6970fn xcm_execute<B: ShouldExecute>(71 self_para_id: u32,72 location: &MultiLocation,73 xcm: &mut [Instruction<RuntimeCall>],74) -> Result<(), ()> {75 new_test_ext(self_para_id).execute_with(|| {76 let max_weight = Weight::from_parts(100_000, 100_000);77 let mut weight_credit = Weight::from_parts(100_000_000, 100_000_000);7879 B::should_execute(&location, xcm, max_weight, &mut weight_credit)80 })81}8283fn make_multiassets(location: &MultiLocation) -> MultiAssets {84 let id = AssetId::Concrete(location.clone());85 let fun = Fungibility::Fungible(42);86 let multiasset = MultiAsset { id, fun };8788 multiasset.into()89}902791fn make_transfer_reserve_asset(location: &MultiLocation) -> Xcm<RuntimeCall> {28const ALICE: AccountId = AccountId::new([0u8; 32]);92 let assets = make_multiassets(location);93 let inst = TransferReserveAsset {94 assets,95 dest: location.clone(),96 xcm: Xcm(vec![]),97 };9899 Xcm::<RuntimeCall>(vec![inst])100}101102fn make_deposit_reserve_asset(location: &MultiLocation) -> Xcm<RuntimeCall> {29const BOB: AccountId = AccountId::new([1u8; 32]);103 let assets = make_multiassets(location);30104 let inst = DepositReserveAsset {105 assets: assets.into(),106 dest: location.clone(),107 xcm: Xcm(vec![]),108 };109110 Xcm::<RuntimeCall>(vec![inst])111}112113fn expect_transfer_location_denied<B: ShouldExecute>(114 logger: &mut Logger,31const INITIAL_BALANCE: u128 = 1000000000000000000_0000; // 1000 UNQ 115 self_para_id: u32,32116 location: &MultiLocation,33#[test]117 xcm: &mut [Instruction<RuntimeCall>],118) -> Result<(), String> {119 let result = xcm_execute::<B>(self_para_id, location, xcm);120121 if result.is_ok() {122 return Err("the barrier should deny the unknown location".into());123 }124125 catch_xcm_barrier_log(logger, "Unexpected deposit or transfer location")126}127128/// WARNING: Uses log capturing129/// See https://docs.rs/logtest/latest/logtest/index.html#constraints130pub fn barrier_denies_transfer_from_unknown_location<B>(34pub fn xcm_transact_is_forbidden() {131 logger: &mut Logger,132 self_para_id: u32,133) -> Result<(), String>35 new_test_ext(vec![(ALICE, INITIAL_BALANCE)]).execute_with(|| {134where36 PolkadotXcm::execute(135 B: ShouldExecute,37 RuntimeOrigin::signed(ALICE),136{38 Box::new(VersionedXcm::from(Xcm(vec![137 const UNKNOWN_PARACHAIN_ID: u32 = 4057;39 Transact {13840 origin_kind: OriginKind::Native,139 let unknown_location = MultiLocation {140 parents: 1,41 require_weight_at_most: Weight::from_parts(1000, 1000),141 interior: X1(Parachain(UNKNOWN_PARACHAIN_ID)),42 call: RuntimeCall::Balances(142 };43 pallet_balances::Call::<Runtime>::transfer {14344 dest: BOB.into(),45 value: INITIAL_BALANCE / 2,46 }47 ).encode().into(),48 }49 ]))),50 Weight::from_parts(1001000, 2000),144 let mut transfer_reserve_asset = make_transfer_reserve_asset(&unknown_location);51 ).expect("XCM execute must succeed, the error should be in the `PolkadotXcm::Attempted` event");52145 let mut deposit_reserve_asset = make_deposit_reserve_asset(&unknown_location);53 let xcm_event = &last_events(1)[0];14654 match xcm_event {147 expect_transfer_location_denied::<B>(55 RuntimeEvent::PolkadotXcm(148 logger,149 self_para_id,150 &unknown_location,151 &mut transfer_reserve_asset.0,152 )?;153154 expect_transfer_location_denied::<B>(56 pallet_xcm::Event::<Runtime>::Attempted(155 logger,156 self_para_id,157 &unknown_location,57 Outcome::Incomplete(_weight, Error::NoPermission)158 &mut deposit_reserve_asset.0,159 )?;58 )16059 ) => { /* Pass */ },161 Ok(())60 _ => panic!(162}61 "Expected PolkadotXcm.Attempted(Incomplete(_weight, NoPermission)),\62 found: {xcm_event:#?}"63 )64 }65 });66}16367runtime/opal/Cargo.tomldiffbeforeafterboth307307308impl-trait-for-tuples = { workspace = true }308impl-trait-for-tuples = { workspace = true }309310[dev-dependencies]311logtest = { workspace = true }312309313[build-dependencies]310[build-dependencies]314substrate-wasm-builder = { workspace = true }311substrate-wasm-builder = { workspace = true }runtime/opal/src/lib.rsdiffbeforeafterboth414142pub mod xcm_barrier;42pub mod xcm_barrier;4344#[cfg(test)]45mod tests;464347pub use runtime_common::*;44pub use runtime_common::*;4845runtime/opal/src/tests/logcapture.rsdiffbeforeafterbothno changes
runtime/opal/src/tests/mod.rsdiffbeforeafterbothno changes
runtime/opal/src/tests/xcm.rsdiffbeforeafterbothno changes
runtime/quartz/Cargo.tomldiffbeforeafterboth300300301impl-trait-for-tuples = { workspace = true }301impl-trait-for-tuples = { workspace = true }302303[dev-dependencies]304logtest = { workspace = true }305302306[build-dependencies]303[build-dependencies]307substrate-wasm-builder = { workspace = true }304substrate-wasm-builder = { workspace = true }runtime/quartz/src/lib.rsdiffbeforeafterboth414142pub mod xcm_barrier;42pub mod xcm_barrier;4344#[cfg(test)]45mod tests;464347pub use runtime_common::*;44pub use runtime_common::*;4845runtime/quartz/src/tests/logcapture.rsdiffbeforeafterbothno changes
runtime/quartz/src/tests/mod.rsdiffbeforeafterbothno changes
runtime/quartz/src/tests/xcm.rsdiffbeforeafterbothno changes
runtime/unique/Cargo.tomldiffbeforeafterboth298298299impl-trait-for-tuples = { workspace = true }299impl-trait-for-tuples = { workspace = true }300301[dev-dependencies]302logtest = { workspace = true }303300304[build-dependencies]301[build-dependencies]305substrate-wasm-builder = { workspace = true }302substrate-wasm-builder = { workspace = true }runtime/unique/src/lib.rsdiffbeforeafterboth414142pub mod xcm_barrier;42pub mod xcm_barrier;4344#[cfg(test)]45mod tests;464347pub use runtime_common::*;44pub use runtime_common::*;4845runtime/unique/src/tests/logcapture.rsdiffbeforeafterbothno changes
runtime/unique/src/tests/mod.rsdiffbeforeafterbothno changes
runtime/unique/src/tests/xcm.rsdiffbeforeafterbothno changes