referrerpolicy=no-referrer-when-downgrade

bridge_hub_rococo_runtime/
bridge_to_westend_config.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Cumulus.
3// SPDX-License-Identifier: Apache-2.0
4
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// 	http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17//! Bridge definitions used on BridgeHubRococo for bridging to BridgeHubWestend.
18
19use crate::{
20	bridge_common_config::{
21		BridgeParachainWestendInstance, DeliveryRewardInBalance,
22		RelayersForLegacyLaneIdsMessagesInstance,
23	},
24	weights,
25	xcm_config::UniversalLocation,
26	AccountId, Balance, Balances, BridgeWestendMessages, PolkadotXcm, Runtime, RuntimeEvent,
27	RuntimeHoldReason, XcmOverBridgeHubWestend, XcmRouter, XcmpQueue,
28};
29use bp_messages::{
30	source_chain::FromBridgedChainMessagesDeliveryProof,
31	target_chain::FromBridgedChainMessagesProof, LegacyLaneId,
32};
33use bridge_hub_common::xcm_version::XcmVersionOfDestAndRemoteBridge;
34use pallet_xcm_bridge_hub::{BridgeId, XcmAsPlainPayload};
35
36use frame_support::{parameter_types, traits::PalletInfoAccess};
37use frame_system::{EnsureNever, EnsureRoot};
38use pallet_bridge_messages::LaneIdOf;
39use pallet_bridge_relayers::extension::{
40	BridgeRelayersTransactionExtension, WithMessagesExtensionConfig,
41};
42use parachains_common::xcm_config::{AllSiblingSystemParachains, RelayOrOtherSystemParachains};
43use polkadot_parachain_primitives::primitives::Sibling;
44use testnet_parachains_constants::rococo::currency::UNITS as ROC;
45use xcm::{
46	latest::{prelude::*, WESTEND_GENESIS_HASH},
47	prelude::{InteriorLocation, NetworkId},
48};
49use xcm_builder::{BridgeBlobDispatcher, ParentIsPreset, SiblingParachainConvertsVia};
50
51parameter_types! {
52	pub BridgeRococoToWestendMessagesPalletInstance: InteriorLocation = [PalletInstance(<BridgeWestendMessages as PalletInfoAccess>::index() as u8)].into();
53	pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
54	pub WestendGlobalConsensusNetworkLocation: Location = Location::new(
55		2,
56		[GlobalConsensus(WestendGlobalConsensusNetwork::get())]
57	);
58	// see the `FEE_BOOST_PER_RELAY_HEADER` constant get the meaning of this value
59	pub PriorityBoostPerRelayHeader: u64 = 32_007_814_407_814;
60	// see the `FEE_BOOST_PER_PARACHAIN_HEADER` constant get the meaning of this value
61	pub PriorityBoostPerParachainHeader: u64 = 1_396_340_903_540_903;
62	// see the `FEE_BOOST_PER_MESSAGE` constant to get the meaning of this value
63	pub PriorityBoostPerMessage: u64 = 364_088_888_888_888;
64
65	pub BridgeHubWestendLocation: Location = Location::new(
66		2,
67		[
68			GlobalConsensus(WestendGlobalConsensusNetwork::get()),
69			Parachain(<bp_bridge_hub_westend::BridgeHubWestend as bp_runtime::Parachain>::PARACHAIN_ID)
70		]
71	);
72
73	pub storage BridgeDeposit: Balance = 5 * ROC;
74}
75
76/// Proof of messages, coming from Westend.
77pub type FromWestendBridgeHubMessagesProof<MI> =
78	FromBridgedChainMessagesProof<bp_bridge_hub_westend::Hash, LaneIdOf<Runtime, MI>>;
79/// Messages delivery proof for Rococo Bridge Hub -> Westend Bridge Hub messages.
80pub type ToWestendBridgeHubMessagesDeliveryProof<MI> =
81	FromBridgedChainMessagesDeliveryProof<bp_bridge_hub_westend::Hash, LaneIdOf<Runtime, MI>>;
82
83/// Dispatches received XCM messages from other bridge
84type FromWestendMessageBlobDispatcher =
85	BridgeBlobDispatcher<XcmRouter, UniversalLocation, BridgeRococoToWestendMessagesPalletInstance>;
86
87/// Transaction extension that refunds relayers that are delivering messages from the Westend
88/// parachain.
89pub type OnBridgeHubRococoRefundBridgeHubWestendMessages = BridgeRelayersTransactionExtension<
90	Runtime,
91	WithMessagesExtensionConfig<
92		StrOnBridgeHubRococoRefundBridgeHubWestendMessages,
93		Runtime,
94		WithBridgeHubWestendMessagesInstance,
95		RelayersForLegacyLaneIdsMessagesInstance,
96		PriorityBoostPerMessage,
97	>,
98>;
99bp_runtime::generate_static_str_provider!(OnBridgeHubRococoRefundBridgeHubWestendMessages);
100
101/// Add XCM messages support for BridgeHubRococo to support Rococo->Westend XCM messages
102pub type WithBridgeHubWestendMessagesInstance = pallet_bridge_messages::Instance3;
103impl pallet_bridge_messages::Config<WithBridgeHubWestendMessagesInstance> for Runtime {
104	type RuntimeEvent = RuntimeEvent;
105	type WeightInfo = weights::pallet_bridge_messages_rococo_to_westend::WeightInfo<Runtime>;
106
107	type ThisChain = bp_bridge_hub_rococo::BridgeHubRococo;
108	type BridgedChain = bp_bridge_hub_westend::BridgeHubWestend;
109	type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders<
110		Runtime,
111		BridgeParachainWestendInstance,
112		bp_bridge_hub_westend::BridgeHubWestend,
113	>;
114
115	type OutboundPayload = XcmAsPlainPayload;
116	type InboundPayload = XcmAsPlainPayload;
117	type LaneId = LegacyLaneId;
118
119	type DeliveryPayments = ();
120	type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter<
121		Runtime,
122		WithBridgeHubWestendMessagesInstance,
123		RelayersForLegacyLaneIdsMessagesInstance,
124		DeliveryRewardInBalance,
125	>;
126
127	type MessageDispatch = XcmOverBridgeHubWestend;
128	type OnMessagesDelivered = XcmOverBridgeHubWestend;
129}
130
131/// Add support for the export and dispatch of XCM programs withing
132/// `WithBridgeHubWestendMessagesInstance`.
133pub type XcmOverBridgeHubWestendInstance = pallet_xcm_bridge_hub::Instance1;
134impl pallet_xcm_bridge_hub::Config<XcmOverBridgeHubWestendInstance> for Runtime {
135	type RuntimeEvent = RuntimeEvent;
136
137	type UniversalLocation = UniversalLocation;
138	type BridgedNetwork = WestendGlobalConsensusNetworkLocation;
139	type BridgeMessagesPalletInstance = WithBridgeHubWestendMessagesInstance;
140
141	type MessageExportPrice = ();
142	type DestinationVersion =
143		XcmVersionOfDestAndRemoteBridge<PolkadotXcm, BridgeHubWestendLocation>;
144
145	type ForceOrigin = EnsureRoot<AccountId>;
146	// We don't want to allow creating bridges for this instance with `LegacyLaneId`.
147	type OpenBridgeOrigin = EnsureNever<Location>;
148	// Converter aligned with `OpenBridgeOrigin`.
149	type BridgeOriginAccountIdConverter =
150		(ParentIsPreset<AccountId>, SiblingParachainConvertsVia<Sibling, AccountId>);
151
152	type BridgeDeposit = BridgeDeposit;
153	type Currency = Balances;
154	type RuntimeHoldReason = RuntimeHoldReason;
155	// Do not require deposit from system parachains or relay chain
156	type AllowWithoutBridgeDeposit =
157		RelayOrOtherSystemParachains<AllSiblingSystemParachains, Runtime>;
158
159	type LocalXcmChannelManager = CongestionManager;
160	type BlobDispatcher = FromWestendMessageBlobDispatcher;
161}
162
163/// Implementation of `bp_xcm_bridge_hub::LocalXcmChannelManager` for congestion management.
164pub struct CongestionManager;
165impl pallet_xcm_bridge_hub::LocalXcmChannelManager for CongestionManager {
166	type Error = SendError;
167
168	fn is_congested(with: &Location) -> bool {
169		// This is used to check the inbound bridge queue/messages to determine if they can be
170		// dispatched and sent to the sibling parachain. Therefore, checking outbound `XcmpQueue`
171		// is sufficient here.
172		use bp_xcm_bridge_hub_router::XcmChannelStatusProvider;
173		cumulus_pallet_xcmp_queue::bridging::OutXcmpChannelStatusProvider::<Runtime>::is_congested(
174			with,
175		)
176	}
177
178	fn suspend_bridge(local_origin: &Location, bridge: BridgeId) -> Result<(), Self::Error> {
179		// This bridge is intended for AH<>AH communication with a hard-coded/static lane,
180		// so `local_origin` is expected to represent only the local AH.
181		send_xcm::<XcmpQueue>(
182			local_origin.clone(),
183			bp_asset_hub_rococo::build_congestion_message(bridge.inner(), true).into(),
184		)
185		.map(|_| ())
186	}
187
188	fn resume_bridge(local_origin: &Location, bridge: BridgeId) -> Result<(), Self::Error> {
189		// This bridge is intended for AH<>AH communication with a hard-coded/static lane,
190		// so `local_origin` is expected to represent only the local AH.
191		send_xcm::<XcmpQueue>(
192			local_origin.clone(),
193			bp_asset_hub_rococo::build_congestion_message(bridge.inner(), false).into(),
194		)
195		.map(|_| ())
196	}
197}
198
199#[cfg(feature = "runtime-benchmarks")]
200pub(crate) fn open_bridge_for_benchmarks<R, XBHI, C>(
201	with: pallet_xcm_bridge_hub::LaneIdOf<R, XBHI>,
202	sibling_para_id: u32,
203) -> InteriorLocation
204where
205	R: pallet_xcm_bridge_hub::Config<XBHI>,
206	XBHI: 'static,
207	C: xcm_executor::traits::ConvertLocation<
208		bp_runtime::AccountIdOf<pallet_xcm_bridge_hub::ThisChainOf<R, XBHI>>,
209	>,
210{
211	use pallet_xcm_bridge_hub::{Bridge, BridgeId, BridgeState};
212	use sp_runtime::traits::Zero;
213	use xcm::{latest::ROCOCO_GENESIS_HASH, VersionedInteriorLocation};
214
215	// insert bridge metadata
216	let lane_id = with;
217	let sibling_parachain = Location::new(1, [Parachain(sibling_para_id)]);
218	let universal_source =
219		[GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(sibling_para_id)].into();
220	let universal_destination =
221		[GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2075)].into();
222	let bridge_id = BridgeId::new(&universal_source, &universal_destination);
223
224	// insert only bridge metadata, because the benchmarks create lanes
225	pallet_xcm_bridge_hub::Bridges::<R, XBHI>::insert(
226		bridge_id,
227		Bridge {
228			bridge_origin_relative_location: alloc::boxed::Box::new(
229				sibling_parachain.clone().into(),
230			),
231			bridge_origin_universal_location: alloc::boxed::Box::new(
232				VersionedInteriorLocation::from(universal_source.clone()),
233			),
234			bridge_destination_universal_location: alloc::boxed::Box::new(
235				VersionedInteriorLocation::from(universal_destination),
236			),
237			state: BridgeState::Opened,
238			bridge_owner_account: C::convert_location(&sibling_parachain).expect("valid AccountId"),
239			deposit: Zero::zero(),
240			lane_id,
241		},
242	);
243	pallet_xcm_bridge_hub::LaneToBridge::<R, XBHI>::insert(lane_id, bridge_id);
244
245	universal_source
246}
247
248#[cfg(test)]
249mod tests {
250	use super::*;
251	use crate::bridge_common_config::BridgeGrandpaWestendInstance;
252	use bridge_runtime_common::{
253		assert_complete_bridge_types,
254		integrity::{
255			assert_complete_with_parachain_bridge_constants, check_message_lane_weights,
256			AssertChainConstants, AssertCompleteBridgeConstants,
257		},
258	};
259
260	/// Every additional message in the message delivery transaction boosts its priority.
261	/// So the priority of transaction with `N+1` messages is larger than priority of
262	/// transaction with `N` messages by the `PriorityBoostPerMessage`.
263	///
264	/// Economically, it is an equivalent of adding tip to the transaction with `N` messages.
265	/// The `FEE_BOOST_PER_MESSAGE` constant is the value of this tip.
266	///
267	/// We want this tip to be large enough (delivery transactions with more messages = less
268	/// operational costs and a faster bridge), so this value should be significant.
269	const FEE_BOOST_PER_MESSAGE: Balance = 2 * ROC;
270
271	// see `FEE_BOOST_PER_MESSAGE` comment
272	const FEE_BOOST_PER_RELAY_HEADER: Balance = 2 * ROC;
273	// see `FEE_BOOST_PER_MESSAGE` comment
274	const FEE_BOOST_PER_PARACHAIN_HEADER: Balance = 2 * ROC;
275
276	#[test]
277	fn ensure_bridge_hub_rococo_message_lane_weights_are_correct() {
278		check_message_lane_weights::<
279			bp_bridge_hub_rococo::BridgeHubRococo,
280			Runtime,
281			WithBridgeHubWestendMessagesInstance,
282		>(
283			bp_bridge_hub_westend::EXTRA_STORAGE_PROOF_SIZE,
284			bp_bridge_hub_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX,
285			bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX,
286			true,
287		);
288	}
289
290	#[test]
291	fn ensure_bridge_integrity() {
292		assert_complete_bridge_types!(
293			runtime: Runtime,
294			with_bridged_chain_messages_instance: WithBridgeHubWestendMessagesInstance,
295			this_chain: bp_bridge_hub_rococo::BridgeHubRococo,
296			bridged_chain: bp_bridge_hub_westend::BridgeHubWestend,
297			expected_payload_type: XcmAsPlainPayload,
298		);
299
300		assert_complete_with_parachain_bridge_constants::<
301			Runtime,
302			BridgeGrandpaWestendInstance,
303			WithBridgeHubWestendMessagesInstance,
304		>(AssertCompleteBridgeConstants {
305			this_chain_constants: AssertChainConstants {
306				block_length: bp_bridge_hub_rococo::BlockLength::get(),
307				block_weights: bp_bridge_hub_rococo::BlockWeightsForAsyncBacking::get(),
308			},
309		});
310
311		pallet_bridge_relayers::extension::per_relay_header::ensure_priority_boost_is_sane::<
312			Runtime,
313			BridgeGrandpaWestendInstance,
314			PriorityBoostPerRelayHeader,
315		>(FEE_BOOST_PER_RELAY_HEADER);
316
317		pallet_bridge_relayers::extension::per_parachain_header::ensure_priority_boost_is_sane::<
318			Runtime,
319			WithBridgeHubWestendMessagesInstance,
320			bp_bridge_hub_westend::BridgeHubWestend,
321			PriorityBoostPerParachainHeader,
322		>(FEE_BOOST_PER_PARACHAIN_HEADER);
323
324		pallet_bridge_relayers::extension::per_message::ensure_priority_boost_is_sane::<
325			Runtime,
326			WithBridgeHubWestendMessagesInstance,
327			PriorityBoostPerMessage,
328		>(FEE_BOOST_PER_MESSAGE);
329
330		let expected: InteriorLocation = [PalletInstance(
331			bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX,
332		)]
333		.into();
334
335		assert_eq!(BridgeRococoToWestendMessagesPalletInstance::get(), expected,);
336	}
337}
338
339/// Contains the migration for the AssetHubRococo<>AssetHubWestend bridge.
340pub mod migration {
341	use super::*;
342	use frame_support::traits::ConstBool;
343
344	parameter_types! {
345		pub AssetHubRococoToAssetHubWestendMessagesLane: LegacyLaneId = LegacyLaneId([0, 0, 0, 2]);
346		pub AssetHubRococoLocation: Location = Location::new(1, [Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID)]);
347		pub AssetHubWestendUniversalLocation: InteriorLocation = [GlobalConsensus(WestendGlobalConsensusNetwork::get()), Parachain(bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID)].into();
348	}
349
350	/// Ensure that the existing lanes for the AHR<>AHW bridge are correctly configured.
351	pub type StaticToDynamicLanes = pallet_xcm_bridge_hub::migration::OpenBridgeForLane<
352		Runtime,
353		XcmOverBridgeHubWestendInstance,
354		AssetHubRococoToAssetHubWestendMessagesLane,
355		// the lanes are already created for AHR<>AHW, but we need to link them to the bridge
356		// structs
357		ConstBool<false>,
358		AssetHubRococoLocation,
359		AssetHubWestendUniversalLocation,
360	>;
361
362	mod v1_wrong {
363		use bp_messages::{LaneState, MessageNonce, UnrewardedRelayer};
364		use bp_runtime::AccountIdOf;
365		use codec::{Decode, Encode};
366		use pallet_bridge_messages::BridgedChainOf;
367		use sp_std::collections::vec_deque::VecDeque;
368
369		#[derive(Encode, Decode, Clone, PartialEq, Eq)]
370		pub(crate) struct StoredInboundLaneData<T: pallet_bridge_messages::Config<I>, I: 'static>(
371			pub(crate) InboundLaneData<AccountIdOf<BridgedChainOf<T, I>>>,
372		);
373		#[derive(Encode, Decode, Clone, PartialEq, Eq)]
374		pub(crate) struct InboundLaneData<RelayerId> {
375			pub state: LaneState,
376			pub(crate) relayers: VecDeque<UnrewardedRelayer<RelayerId>>,
377			pub(crate) last_confirmed_nonce: MessageNonce,
378		}
379		#[derive(Encode, Decode, Clone, PartialEq, Eq)]
380		pub(crate) struct OutboundLaneData {
381			pub state: LaneState,
382			pub(crate) oldest_unpruned_nonce: MessageNonce,
383			pub(crate) latest_received_nonce: MessageNonce,
384			pub(crate) latest_generated_nonce: MessageNonce,
385		}
386	}
387
388	mod v1 {
389		pub use bp_messages::{InboundLaneData, LaneState, OutboundLaneData};
390		pub use pallet_bridge_messages::{InboundLanes, OutboundLanes, StoredInboundLaneData};
391	}
392
393	/// Fix for v1 migration - corrects data for OutboundLaneData/InboundLaneData (it is needed only
394	/// for Rococo/Westend).
395	pub struct FixMessagesV1Migration<T, I>(sp_std::marker::PhantomData<(T, I)>);
396
397	impl<T: pallet_bridge_messages::Config<I>, I: 'static> frame_support::traits::OnRuntimeUpgrade
398		for FixMessagesV1Migration<T, I>
399	{
400		fn on_runtime_upgrade() -> Weight {
401			use sp_core::Get;
402			let mut weight = T::DbWeight::get().reads(1);
403
404			// `InboundLanes` - add state to the old structs
405			let translate_inbound =
406				|pre: v1_wrong::StoredInboundLaneData<T, I>| -> Option<v1::StoredInboundLaneData<T, I>> {
407					weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
408					Some(v1::StoredInboundLaneData(v1::InboundLaneData {
409						state: v1::LaneState::Opened,
410						relayers: pre.0.relayers,
411						last_confirmed_nonce: pre.0.last_confirmed_nonce,
412					}))
413				};
414			v1::InboundLanes::<T, I>::translate_values(translate_inbound);
415
416			// `OutboundLanes` - add state to the old structs
417			let translate_outbound =
418				|pre: v1_wrong::OutboundLaneData| -> Option<v1::OutboundLaneData> {
419					weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
420					Some(v1::OutboundLaneData {
421						state: v1::LaneState::Opened,
422						oldest_unpruned_nonce: pre.oldest_unpruned_nonce,
423						latest_received_nonce: pre.latest_received_nonce,
424						latest_generated_nonce: pre.latest_generated_nonce,
425					})
426				};
427			v1::OutboundLanes::<T, I>::translate_values(translate_outbound);
428
429			weight
430		}
431	}
432}