referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Cumulus.

// Cumulus 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.

// Cumulus 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 Cumulus.  If not, see <http://www.gnu.org/licenses/>.

//! Module contains predefined test-case scenarios for `Runtime` with bridging capabilities.
//!
//! This file contains tests, suitable for all bridge runtimes. See `from_parachain` and
//! `from_grandpa_chain` submodules for tests, that are specific to the bridged chain type.

pub mod from_grandpa_chain;
pub mod from_parachain;

pub(crate) mod helpers;

use crate::{test_cases::bridges_prelude::*, test_data};

use asset_test_utils::BasicParachainRuntime;
use bp_messages::{
	target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch},
	LaneState, MessageKey, MessagesOperatingMode, OutboundLaneData,
};
use bp_runtime::BasicOperatingMode;
use bp_xcm_bridge_hub::{Bridge, BridgeState, XcmAsPlainPayload};
use codec::Encode;
use frame_support::{
	assert_ok,
	dispatch::GetDispatchInfo,
	traits::{Contains, Get, OnFinalize, OnInitialize, OriginTrait},
};
use frame_system::pallet_prelude::BlockNumberFor;
use parachains_common::AccountId;
use parachains_runtimes_test_utils::{
	mock_open_hrmp_channel, AccountIdOf, BalanceOf, CollatorSessionKeys, ExtBuilder, RuntimeCallOf,
	SlotDurations, XcmReceivedFrom,
};
use sp_runtime::{traits::Zero, AccountId32};
use xcm::{latest::prelude::*, AlwaysLatest};
use xcm_builder::DispatchBlobError;
use xcm_executor::{
	traits::{ConvertLocation, TransactAsset, WeightBounds},
	XcmExecutor,
};

/// Common bridges exports.
pub(crate) mod bridges_prelude {
	pub use bp_parachains::{RelayBlockHash, RelayBlockNumber};
	pub use pallet_bridge_grandpa::{Call as BridgeGrandpaCall, Config as BridgeGrandpaConfig};
	pub use pallet_bridge_messages::{
		Call as BridgeMessagesCall, Config as BridgeMessagesConfig, LanesManagerError,
	};
	pub use pallet_bridge_parachains::{
		Call as BridgeParachainsCall, Config as BridgeParachainsConfig,
	};
	pub use pallet_xcm_bridge_hub::{
		Call as BridgeXcmOverBridgeCall, Config as BridgeXcmOverBridgeConfig, LanesManagerOf,
		XcmBlobMessageDispatchResult,
	};
}

// Re-export test_case from assets
pub use asset_test_utils::include_teleports_for_native_asset_works;
use pallet_bridge_messages::LaneIdOf;

pub type RuntimeHelper<Runtime, AllPalletsWithoutSystem = ()> =
	parachains_runtimes_test_utils::RuntimeHelper<Runtime, AllPalletsWithoutSystem>;

// Re-export test_case from `parachains-runtimes-test-utils`
use crate::test_cases::helpers::open_bridge_with_extrinsic;
pub use parachains_runtimes_test_utils::test_cases::{
	change_storage_constant_by_governance_works, set_storage_keys_by_governance_works,
};

/// Prepare default runtime storage and run test within this context.
pub fn run_test<Runtime, T>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
	balances: Vec<(Runtime::AccountId, Runtime::Balance)>,
	test: impl FnOnce() -> T,
) -> T
where
	Runtime: BasicParachainRuntime,
{
	ExtBuilder::<Runtime>::default()
		.with_collators(collator_session_key.collators())
		.with_session_keys(collator_session_key.session_keys())
		.with_safe_xcm_version(XCM_VERSION)
		.with_para_id(runtime_para_id.into())
		.with_balances(balances)
		.with_tracing()
		.build()
		.execute_with(|| test())
}

/// Test-case makes sure that `Runtime` can process bridging initialize via governance-like call
pub fn initialize_bridge_by_governance_works<Runtime, GrandpaPalletInstance>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
) where
	Runtime: BasicParachainRuntime + BridgeGrandpaConfig<GrandpaPalletInstance>,
	GrandpaPalletInstance: 'static,
	RuntimeCallOf<Runtime>:
		GetDispatchInfo + From<BridgeGrandpaCall<Runtime, GrandpaPalletInstance>>,
{
	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		// check mode before
		assert_eq!(
			pallet_bridge_grandpa::PalletOperatingMode::<Runtime, GrandpaPalletInstance>::try_get(),
			Err(())
		);

		// prepare the `initialize` call
		let initialize_call = RuntimeCallOf::<Runtime>::from(BridgeGrandpaCall::<
			Runtime,
			GrandpaPalletInstance,
		>::initialize {
			init_data: test_data::initialization_data::<Runtime, GrandpaPalletInstance>(12345),
		});

		// execute XCM with Transacts to `initialize bridge` as governance does
		assert_ok!(RuntimeHelper::<Runtime>::execute_as_governance(initialize_call.encode(),)
			.ensure_complete());

		// check mode after
		assert_eq!(
			pallet_bridge_grandpa::PalletOperatingMode::<Runtime, GrandpaPalletInstance>::try_get(),
			Ok(BasicOperatingMode::Normal)
		);
	})
}

/// Test-case makes sure that `Runtime` can change bridge GRANDPA pallet operating mode via
/// governance-like call.
pub fn change_bridge_grandpa_pallet_mode_by_governance_works<Runtime, GrandpaPalletInstance>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
) where
	Runtime: BasicParachainRuntime + BridgeGrandpaConfig<GrandpaPalletInstance>,
	GrandpaPalletInstance: 'static,
	RuntimeCallOf<Runtime>:
		GetDispatchInfo + From<BridgeGrandpaCall<Runtime, GrandpaPalletInstance>>,
{
	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		let dispatch_set_operating_mode_call = |old_mode, new_mode| {
			// check old mode
			assert_eq!(
				pallet_bridge_grandpa::PalletOperatingMode::<Runtime, GrandpaPalletInstance>::get(),
				old_mode,
			);

			// prepare the `set_operating_mode` call
			let set_operating_mode_call = <Runtime as frame_system::Config>::RuntimeCall::from(
				pallet_bridge_grandpa::Call::<Runtime, GrandpaPalletInstance>::set_operating_mode {
					operating_mode: new_mode,
				},
			);

			// execute XCM with Transacts to `initialize bridge` as governance does
			assert_ok!(RuntimeHelper::<Runtime>::execute_as_governance(
				set_operating_mode_call.encode(),
			)
			.ensure_complete());

			// check mode after
			assert_eq!(
				pallet_bridge_grandpa::PalletOperatingMode::<Runtime, GrandpaPalletInstance>::try_get(),
				Ok(new_mode)
			);
		};

		// check mode before
		assert_eq!(
			pallet_bridge_grandpa::PalletOperatingMode::<Runtime, GrandpaPalletInstance>::try_get(),
			Err(())
		);

		dispatch_set_operating_mode_call(BasicOperatingMode::Normal, BasicOperatingMode::Halted);
		dispatch_set_operating_mode_call(BasicOperatingMode::Halted, BasicOperatingMode::Normal);
	});
}

/// Test-case makes sure that `Runtime` can change bridge parachains pallet operating mode via
/// governance-like call.
pub fn change_bridge_parachains_pallet_mode_by_governance_works<Runtime, ParachainsPalletInstance>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
) where
	Runtime: BasicParachainRuntime + BridgeParachainsConfig<ParachainsPalletInstance>,
	ParachainsPalletInstance: 'static,
	RuntimeCallOf<Runtime>:
		GetDispatchInfo + From<BridgeParachainsCall<Runtime, ParachainsPalletInstance>>,
{
	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		let dispatch_set_operating_mode_call = |old_mode, new_mode| {
			// check old mode
			assert_eq!(
				pallet_bridge_parachains::PalletOperatingMode::<Runtime, ParachainsPalletInstance>::get(),
				old_mode,
			);

			// prepare the `set_operating_mode` call
			let set_operating_mode_call =
				RuntimeCallOf::<Runtime>::from(pallet_bridge_parachains::Call::<
					Runtime,
					ParachainsPalletInstance,
				>::set_operating_mode {
					operating_mode: new_mode,
				});

			// execute XCM with Transacts to `initialize bridge` as governance does
			assert_ok!(RuntimeHelper::<Runtime>::execute_as_governance(
				set_operating_mode_call.encode(),
			)
			.ensure_complete());

			// check mode after
			assert_eq!(
				pallet_bridge_parachains::PalletOperatingMode::<Runtime, ParachainsPalletInstance>::try_get(),
				Ok(new_mode)
			);
		};

		// check mode before
		assert_eq!(
			pallet_bridge_parachains::PalletOperatingMode::<Runtime, ParachainsPalletInstance>::try_get(),
			Err(())
		);

		dispatch_set_operating_mode_call(BasicOperatingMode::Normal, BasicOperatingMode::Halted);
		dispatch_set_operating_mode_call(BasicOperatingMode::Halted, BasicOperatingMode::Normal);
	});
}

/// Test-case makes sure that `Runtime` can change bridge messaging pallet operating mode via
/// governance-like call.
pub fn change_bridge_messages_pallet_mode_by_governance_works<Runtime, MessagesPalletInstance>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
) where
	Runtime: BasicParachainRuntime + BridgeMessagesConfig<MessagesPalletInstance>,
	MessagesPalletInstance: 'static,
	RuntimeCallOf<Runtime>:
		GetDispatchInfo + From<BridgeMessagesCall<Runtime, MessagesPalletInstance>>,
{
	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		let dispatch_set_operating_mode_call = |old_mode, new_mode| {
			// check old mode
			assert_eq!(
				pallet_bridge_messages::PalletOperatingMode::<Runtime, MessagesPalletInstance>::get(
				),
				old_mode,
			);

			// encode `set_operating_mode` call
			let set_operating_mode_call = RuntimeCallOf::<Runtime>::from(BridgeMessagesCall::<
				Runtime,
				MessagesPalletInstance,
			>::set_operating_mode {
				operating_mode: new_mode,
			});

			// execute XCM with Transacts to `initialize bridge` as governance does
			assert_ok!(RuntimeHelper::<Runtime>::execute_as_governance(
				set_operating_mode_call.encode(),
			)
			.ensure_complete());

			// check mode after
			assert_eq!(
				pallet_bridge_messages::PalletOperatingMode::<Runtime, MessagesPalletInstance>::try_get(),
				Ok(new_mode)
			);
		};

		// check mode before
		assert_eq!(
			pallet_bridge_messages::PalletOperatingMode::<Runtime, MessagesPalletInstance>::try_get(
			),
			Err(())
		);

		dispatch_set_operating_mode_call(
			MessagesOperatingMode::Basic(BasicOperatingMode::Normal),
			MessagesOperatingMode::RejectingOutboundMessages,
		);
		dispatch_set_operating_mode_call(
			MessagesOperatingMode::RejectingOutboundMessages,
			MessagesOperatingMode::Basic(BasicOperatingMode::Halted),
		);
		dispatch_set_operating_mode_call(
			MessagesOperatingMode::Basic(BasicOperatingMode::Halted),
			MessagesOperatingMode::Basic(BasicOperatingMode::Normal),
		);
	});
}

/// Test-case makes sure that `Runtime` can handle xcm `ExportMessage`:
/// Checks if received XCM messages is correctly added to the message outbound queue for delivery.
/// For SystemParachains we expect unpaid execution.
pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
	Runtime,
	XcmConfig,
	MessagesPalletInstance,
>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
	sibling_parachain_id: u32,
	unwrap_pallet_bridge_messages_event: Box<
		dyn Fn(Vec<u8>) -> Option<pallet_bridge_messages::Event<Runtime, MessagesPalletInstance>>,
	>,
	export_message_instruction: fn() -> Instruction<XcmConfig::RuntimeCall>,
	existential_deposit: Option<Asset>,
	maybe_paid_export_message: Option<Asset>,
	prepare_configuration: impl Fn() -> LaneIdOf<Runtime, MessagesPalletInstance>,
) where
	Runtime: BasicParachainRuntime + BridgeMessagesConfig<MessagesPalletInstance>,
	XcmConfig: xcm_executor::Config,
	MessagesPalletInstance: 'static,
{
	assert_ne!(runtime_para_id, sibling_parachain_id);
	let sibling_parachain_location = Location::new(1, [Parachain(sibling_parachain_id)]);

	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		let expected_lane_id = prepare_configuration();

		// check queue before
		assert_eq!(
			pallet_bridge_messages::OutboundLanes::<Runtime, MessagesPalletInstance>::try_get(
				expected_lane_id
			),
			Ok(OutboundLaneData {
				state: LaneState::Opened,
				oldest_unpruned_nonce: 1,
				latest_received_nonce: 0,
				latest_generated_nonce: 0
			})
		);

		// prepare `ExportMessage`
		let xcm = if let Some(fee) = maybe_paid_export_message {
			// deposit ED to origin (if needed)
			if let Some(ed) = existential_deposit {
				XcmConfig::AssetTransactor::deposit_asset(
					&ed,
					&sibling_parachain_location,
					Some(&XcmContext::with_message_id([0; 32])),
				)
				.expect("deposited ed");
			}
			// deposit fee to origin
			XcmConfig::AssetTransactor::deposit_asset(
				&fee,
				&sibling_parachain_location,
				Some(&XcmContext::with_message_id([0; 32])),
			)
			.expect("deposited fee");

			Xcm(vec![
				WithdrawAsset(Assets::from(vec![fee.clone()])),
				BuyExecution { fees: fee, weight_limit: Unlimited },
				export_message_instruction(),
			])
		} else {
			Xcm(vec![
				UnpaidExecution { weight_limit: Unlimited, check_origin: None },
				export_message_instruction(),
			])
		};

		// execute XCM
		let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256);
		assert_ok!(XcmExecutor::<XcmConfig>::prepare_and_execute(
			sibling_parachain_location,
			xcm,
			&mut hash,
			RuntimeHelper::<Runtime>::xcm_max_weight(XcmReceivedFrom::Sibling),
			Weight::zero(),
		)
		.ensure_complete());

		// check queue after
		assert_eq!(
			pallet_bridge_messages::OutboundLanes::<Runtime, MessagesPalletInstance>::try_get(
				expected_lane_id
			),
			Ok(OutboundLaneData {
				state: LaneState::Opened,
				oldest_unpruned_nonce: 1,
				latest_received_nonce: 0,
				latest_generated_nonce: 1,
			})
		);

		// check events
		let mut events = <frame_system::Pallet<Runtime>>::events()
			.into_iter()
			.filter_map(|e| unwrap_pallet_bridge_messages_event(e.event.encode()));
		assert!(events.any(|e| matches!(e, pallet_bridge_messages::Event::MessageAccepted { .. })));
	})
}

/// Test-case makes sure that Runtime can route XCM messages received in inbound queue,
/// We just test here `MessageDispatch` configuration.
/// We expect that runtime can route messages:
///     1. to Parent (relay chain)
///     2. to Sibling parachain
pub fn message_dispatch_routing_works<
	Runtime,
	AllPalletsWithoutSystem,
	XcmConfig,
	HrmpChannelOpener,
	MessagesPalletInstance,
	RuntimeNetwork,
	BridgedNetwork,
	NetworkDistanceAsParentCount,
>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	slot_durations: SlotDurations,
	runtime_para_id: u32,
	sibling_parachain_id: u32,
	unwrap_cumulus_pallet_parachain_system_event: Box<
		dyn Fn(Vec<u8>) -> Option<cumulus_pallet_parachain_system::Event<Runtime>>,
	>,
	unwrap_cumulus_pallet_xcmp_queue_event: Box<
		dyn Fn(Vec<u8>) -> Option<cumulus_pallet_xcmp_queue::Event<Runtime>>,
	>,
	prepare_configuration: impl Fn(),
) where
	Runtime: BasicParachainRuntime
		+ cumulus_pallet_xcmp_queue::Config
		+ BridgeMessagesConfig<MessagesPalletInstance, InboundPayload = XcmAsPlainPayload>,
	AllPalletsWithoutSystem:
		OnInitialize<BlockNumberFor<Runtime>> + OnFinalize<BlockNumberFor<Runtime>>,
	AccountIdOf<Runtime>: From<AccountId32>
		+ Into<<<Runtime as frame_system::Config>::RuntimeOrigin as OriginTrait>::AccountId>,
	XcmConfig: xcm_executor::Config,
	MessagesPalletInstance: 'static,
	HrmpChannelOpener: frame_support::inherent::ProvideInherent<
		Call = cumulus_pallet_parachain_system::Call<Runtime>,
	>,
	RuntimeNetwork: Get<NetworkId>,
	BridgedNetwork: Get<NetworkId>,
	NetworkDistanceAsParentCount: Get<u8>,
{
	struct NetworkWithParentCount<N, C>(core::marker::PhantomData<(N, C)>);
	impl<N: Get<NetworkId>, C: Get<u8>> Get<Location> for NetworkWithParentCount<N, C> {
		fn get() -> Location {
			Location::new(C::get(), [GlobalConsensus(N::get())])
		}
	}

	assert_ne!(runtime_para_id, sibling_parachain_id);

	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		prepare_configuration();

		let dummy_lane_id = LaneIdOf::<Runtime, MessagesPalletInstance>::default();
		let mut alice = [0u8; 32];
		alice[0] = 1;

		let included_head = RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::run_to_block(
			2,
			AccountId::from(alice).into(),
		);
		// 1. this message is sent from other global consensus with destination of this Runtime
		//    relay chain (UMP)
		let bridging_message = test_data::simulate_message_exporter_on_bridged_chain::<
			BridgedNetwork,
			NetworkWithParentCount<RuntimeNetwork, NetworkDistanceAsParentCount>,
			AlwaysLatest,
		>((RuntimeNetwork::get(), Here));
		let result =
			<<Runtime as BridgeMessagesConfig<MessagesPalletInstance>>::MessageDispatch>::dispatch(
				test_data::dispatch_message(dummy_lane_id, 1, bridging_message),
			);
		assert_eq!(
			format!("{:?}", result.dispatch_level_result),
			format!("{:?}", XcmBlobMessageDispatchResult::Dispatched)
		);

		// check events - UpwardMessageSent
		let mut events = <frame_system::Pallet<Runtime>>::events()
			.into_iter()
			.filter_map(|e| unwrap_cumulus_pallet_parachain_system_event(e.event.encode()));
		assert!(events.any(|e| matches!(
			e,
			cumulus_pallet_parachain_system::Event::UpwardMessageSent { .. }
		)));

		// 2. this message is sent from other global consensus with destination of this Runtime
		//    sibling parachain (HRMP)
		let bridging_message =
			test_data::simulate_message_exporter_on_bridged_chain::<
				BridgedNetwork,
				NetworkWithParentCount<RuntimeNetwork, NetworkDistanceAsParentCount>,
				AlwaysLatest,
			>((RuntimeNetwork::get(), [Parachain(sibling_parachain_id)].into()));

		// 2.1. WITHOUT opened hrmp channel -> RoutingError
		let result =
			<<Runtime as BridgeMessagesConfig<MessagesPalletInstance>>::MessageDispatch>::dispatch(
				DispatchMessage {
					key: MessageKey { lane_id: dummy_lane_id, nonce: 1 },
					data: DispatchMessageData { payload: Ok(bridging_message.clone()) },
				},
			);
		assert_eq!(
			format!("{:?}", result.dispatch_level_result),
			format!(
				"{:?}",
				XcmBlobMessageDispatchResult::NotDispatched(Some(DispatchBlobError::RoutingError))
			)
		);

		// check events - no XcmpMessageSent
		assert_eq!(
			<frame_system::Pallet<Runtime>>::events()
				.into_iter()
				.filter_map(|e| unwrap_cumulus_pallet_xcmp_queue_event(e.event.encode()))
				.count(),
			0
		);

		// 2.1. WITH hrmp channel -> Ok
		mock_open_hrmp_channel::<Runtime, HrmpChannelOpener>(
			runtime_para_id.into(),
			sibling_parachain_id.into(),
			included_head,
			&alice,
			&slot_durations,
		);
		let result =
			<<Runtime as BridgeMessagesConfig<MessagesPalletInstance>>::MessageDispatch>::dispatch(
				DispatchMessage {
					key: MessageKey { lane_id: dummy_lane_id, nonce: 1 },
					data: DispatchMessageData { payload: Ok(bridging_message) },
				},
			);
		assert_eq!(
			format!("{:?}", result.dispatch_level_result),
			format!("{:?}", XcmBlobMessageDispatchResult::Dispatched)
		);

		// check events - XcmpMessageSent
		let mut events = <frame_system::Pallet<Runtime>>::events()
			.into_iter()
			.filter_map(|e| unwrap_cumulus_pallet_xcmp_queue_event(e.event.encode()));
		assert!(
			events.any(|e| matches!(e, cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }))
		);
	})
}

/// Estimates XCM execution fee for paid `ExportMessage` processing.
pub fn can_calculate_weight_for_paid_export_message_with_reserve_transfer<
	Runtime,
	XcmConfig,
	WeightToFee,
>() -> u128
where
	Runtime: frame_system::Config + pallet_balances::Config,
	XcmConfig: xcm_executor::Config,
	WeightToFee: frame_support::weights::WeightToFee<Balance = BalanceOf<Runtime>>,
	<WeightToFee as frame_support::weights::WeightToFee>::Balance: From<u128> + Into<u128>,
{
	// data here are not relevant for weighing
	let mut xcm = Xcm(vec![
		WithdrawAsset(Assets::from(vec![Asset {
			id: AssetId(Location::new(1, [])),
			fun: Fungible(34333299),
		}])),
		BuyExecution {
			fees: Asset { id: AssetId(Location::new(1, [])), fun: Fungible(34333299) },
			weight_limit: Unlimited,
		},
		SetAppendix(Xcm(vec![DepositAsset {
			assets: Wild(AllCounted(1)),
			beneficiary: Location::new(1, [Parachain(1000)]),
		}])),
		ExportMessage {
			network: Polkadot,
			destination: [Parachain(1000)].into(),
			xcm: Xcm(vec![
				ReserveAssetDeposited(Assets::from(vec![Asset {
					id: AssetId(Location::new(2, [GlobalConsensus(Kusama)])),
					fun: Fungible(1000000000000),
				}])),
				ClearOrigin,
				BuyExecution {
					fees: Asset {
						id: AssetId(Location::new(2, [GlobalConsensus(Kusama)])),
						fun: Fungible(1000000000000),
					},
					weight_limit: Unlimited,
				},
				DepositAsset {
					assets: Wild(AllCounted(1)),
					beneficiary: Location::new(
						0,
						[xcm::latest::prelude::AccountId32 {
							network: None,
							id: [
								212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159,
								214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165,
								109, 162, 125,
							],
						}],
					),
				},
				SetTopic([
					116, 82, 194, 132, 171, 114, 217, 165, 23, 37, 161, 177, 165, 179, 247, 114,
					137, 101, 147, 70, 28, 157, 168, 32, 154, 63, 74, 228, 152, 180, 5, 63,
				]),
			]),
		},
		SetTopic([
			36, 224, 250, 165, 82, 195, 67, 110, 160, 170, 140, 87, 217, 62, 201, 164, 42, 98, 219,
			157, 124, 105, 248, 25, 131, 218, 199, 36, 109, 173, 100, 122,
		]),
	]);

	// get weight
	let weight = XcmConfig::Weigher::weight(&mut xcm);
	assert_ok!(weight);
	let weight = weight.unwrap();
	// check if sane
	let max_expected = Runtime::BlockWeights::get().max_block / 10;
	assert!(
		weight.all_lte(max_expected),
		"calculated weight: {:?}, max_expected: {:?}",
		weight,
		max_expected
	);

	// check fee, should not be 0
	let estimated_fee = WeightToFee::weight_to_fee(&weight);
	assert!(estimated_fee > BalanceOf::<Runtime>::zero());

	estimated_fee.into()
}

/// Test-case makes sure that `Runtime` can open/close bridges.
pub fn open_and_close_bridge_works<Runtime, XcmOverBridgePalletInstance, LocationToAccountId, TokenLocation>(
	collator_session_key: CollatorSessionKeys<Runtime>,
	runtime_para_id: u32,
	expected_source: Location,
	destination: InteriorLocation,
	origin_with_origin_kind: (Location, OriginKind),
	is_paid_xcm_execution: bool,
) where
	Runtime: BasicParachainRuntime + BridgeXcmOverBridgeConfig<XcmOverBridgePalletInstance>,
	XcmOverBridgePalletInstance: 'static,
	<Runtime as frame_system::Config>::RuntimeCall: GetDispatchInfo + From<BridgeXcmOverBridgeCall<Runtime, XcmOverBridgePalletInstance>>,
	<Runtime as pallet_balances::Config>::Balance: From<<<Runtime as pallet_bridge_messages::Config<<Runtime as pallet_xcm_bridge_hub::Config<XcmOverBridgePalletInstance>>::BridgeMessagesPalletInstance>>::ThisChain as bp_runtime::Chain>::Balance>,
	<Runtime as pallet_balances::Config>::Balance: From<u128>,
	<<Runtime as pallet_bridge_messages::Config<<Runtime as pallet_xcm_bridge_hub::Config<XcmOverBridgePalletInstance>>::BridgeMessagesPalletInstance>>::ThisChain as bp_runtime::Chain>::AccountId: From<<Runtime as frame_system::Config>::AccountId>,
	LocationToAccountId: ConvertLocation<AccountIdOf<Runtime>>,
	TokenLocation: Get<Location>,
{
	run_test::<Runtime, _>(collator_session_key, runtime_para_id, vec![], || {
		// construct expected bridge configuration
		let locations = pallet_xcm_bridge_hub::Pallet::<Runtime, XcmOverBridgePalletInstance>::bridge_locations(
			expected_source.clone().into(),
			destination.clone().into(),
		).expect("valid bridge locations");
		let expected_lane_id =
			locations.calculate_lane_id(xcm::latest::VERSION).expect("valid laneId");
		let lanes_manager = LanesManagerOf::<Runtime, XcmOverBridgePalletInstance>::new();

		let expected_deposit = if <Runtime as pallet_xcm_bridge_hub::Config<
			XcmOverBridgePalletInstance,
		>>::AllowWithoutBridgeDeposit::contains(
			locations.bridge_origin_relative_location()
		) {
			Zero::zero()
		} else {
			<Runtime as pallet_xcm_bridge_hub::Config<
				XcmOverBridgePalletInstance,
			>>::BridgeDeposit::get()
		};

		// check bridge/lane DOES not exist
		assert_eq!(
			pallet_xcm_bridge_hub::Bridges::<Runtime, XcmOverBridgePalletInstance>::get(
				locations.bridge_id()
			),
			None
		);
		assert_eq!(
			lanes_manager.active_inbound_lane(expected_lane_id).map(drop),
			Err(LanesManagerError::UnknownInboundLane)
		);
		assert_eq!(
			lanes_manager.active_outbound_lane(expected_lane_id).map(drop),
			Err(LanesManagerError::UnknownOutboundLane)
		);

		// open bridge with Transact call
		assert_eq!(
			helpers::ensure_opened_bridge::<
				Runtime,
				XcmOverBridgePalletInstance,
				LocationToAccountId,
				TokenLocation,
			>(
				expected_source.clone(),
				destination.clone(),
				is_paid_xcm_execution,
				|locations, maybe_paid_execution| open_bridge_with_extrinsic::<
					Runtime,
					XcmOverBridgePalletInstance,
				>(
					origin_with_origin_kind.clone(),
					locations.bridge_destination_universal_location().clone(),
					maybe_paid_execution
				)
			)
			.0
			.bridge_id(),
			locations.bridge_id()
		);

		// check bridge/lane DOES exist
		assert_eq!(
			pallet_xcm_bridge_hub::Bridges::<Runtime, XcmOverBridgePalletInstance>::get(
				locations.bridge_id()
			),
			Some(Bridge {
				bridge_origin_relative_location: Box::new(expected_source.clone().into()),
				bridge_origin_universal_location: Box::new(
					locations.bridge_origin_universal_location().clone().into()
				),
				bridge_destination_universal_location: Box::new(
					locations.bridge_destination_universal_location().clone().into()
				),
				state: BridgeState::Opened,
				bridge_owner_account: LocationToAccountId::convert_location(&expected_source)
					.expect("valid location")
					.into(),
				deposit: expected_deposit,
				lane_id: expected_lane_id
			})
		);
		assert_eq!(
			lanes_manager.active_inbound_lane(expected_lane_id).map(|lane| lane.state()),
			Ok(LaneState::Opened)
		);
		assert_eq!(
			lanes_manager.active_outbound_lane(expected_lane_id).map(|lane| lane.state()),
			Ok(LaneState::Opened)
		);

		// close bridge with Transact call
		helpers::close_bridge::<
			Runtime,
			XcmOverBridgePalletInstance,
			LocationToAccountId,
			TokenLocation,
		>(expected_source, destination, origin_with_origin_kind, is_paid_xcm_execution);

		// check bridge/lane DOES not exist
		assert_eq!(
			pallet_xcm_bridge_hub::Bridges::<Runtime, XcmOverBridgePalletInstance>::get(
				locations.bridge_id()
			),
			None
		);
		assert_eq!(
			lanes_manager.active_inbound_lane(expected_lane_id).map(drop),
			Err(LanesManagerError::UnknownInboundLane)
		);
		assert_eq!(
			lanes_manager.active_outbound_lane(expected_lane_id).map(drop),
			Err(LanesManagerError::UnknownOutboundLane)
		);
	});
}