referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_common/
xcm_sender.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! XCM sender for relay chain.
18
19use alloc::{collections::btree_set::BTreeSet, vec::Vec};
20use codec::{DecodeLimit, Encode};
21use core::marker::PhantomData;
22use frame_support::traits::Get;
23use frame_system::pallet_prelude::BlockNumberFor;
24use polkadot_primitives::Id as ParaId;
25use polkadot_runtime_parachains::{
26	configuration::{self, HostConfiguration},
27	dmp, FeeTracker,
28};
29use sp_runtime::FixedPointNumber;
30use xcm::{prelude::*, MAX_XCM_DECODE_DEPTH};
31use xcm_builder::InspectMessageQueues;
32use SendError::*;
33
34/// Simple value-bearing trait for determining/expressing the assets required to be paid for a
35/// messages to be delivered to a parachain.
36pub trait PriceForMessageDelivery {
37	/// Type used for charging different prices to different destinations
38	type Id;
39	/// Return the assets required to deliver `message` to the given `para` destination.
40	fn price_for_delivery(id: Self::Id, message: &Xcm<()>) -> Assets;
41}
42impl PriceForMessageDelivery for () {
43	type Id = ();
44
45	fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> Assets {
46		Assets::new()
47	}
48}
49
50pub struct NoPriceForMessageDelivery<Id>(PhantomData<Id>);
51impl<Id> PriceForMessageDelivery for NoPriceForMessageDelivery<Id> {
52	type Id = Id;
53
54	fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> Assets {
55		Assets::new()
56	}
57}
58
59/// Implementation of [`PriceForMessageDelivery`] which returns a fixed price.
60pub struct ConstantPrice<T>(core::marker::PhantomData<T>);
61impl<T: Get<Assets>> PriceForMessageDelivery for ConstantPrice<T> {
62	type Id = ();
63
64	fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> Assets {
65		T::get()
66	}
67}
68
69/// Implementation of [`PriceForMessageDelivery`] which returns an exponentially increasing price.
70/// The formula for the fee is based on the sum of a base fee plus a message length fee, multiplied
71/// by a specified factor. In mathematical form:
72///
73/// `F * (B + encoded_msg_len * M)`
74///
75/// Thus, if F = 1 and M = 0, this type is equivalent to [`ConstantPrice<B>`].
76///
77/// The type parameters are understood as follows:
78///
79/// - `A`: Used to denote the asset ID that will be used for paying the delivery fee.
80/// - `B`: The base fee to pay for message delivery.
81/// - `M`: The fee to pay for each and every byte of the message after encoding it.
82/// - `F`: A fee factor multiplier. It can be understood as the exponent term in the formula.
83pub struct ExponentialPrice<A, B, M, F>(core::marker::PhantomData<(A, B, M, F)>);
84impl<A: Get<AssetId>, B: Get<u128>, M: Get<u128>, F: FeeTracker> PriceForMessageDelivery
85	for ExponentialPrice<A, B, M, F>
86{
87	type Id = F::Id;
88
89	fn price_for_delivery(id: Self::Id, msg: &Xcm<()>) -> Assets {
90		let msg_fee = (msg.encoded_size() as u128).saturating_mul(M::get());
91		let fee_sum = B::get().saturating_add(msg_fee);
92		let amount = F::get_fee_factor(id).saturating_mul_int(fee_sum);
93		(A::get(), amount).into()
94	}
95}
96
97/// XCM sender for relay chain. It only sends downward message.
98pub struct ChildParachainRouter<T, W, P>(PhantomData<(T, W, P)>);
99
100impl<T: configuration::Config + dmp::Config, W: xcm::WrapVersion, P> SendXcm
101	for ChildParachainRouter<T, W, P>
102where
103	P: PriceForMessageDelivery<Id = ParaId>,
104{
105	type Ticket = (HostConfiguration<BlockNumberFor<T>>, ParaId, Vec<u8>);
106
107	fn validate(
108		dest: &mut Option<Location>,
109		msg: &mut Option<Xcm<()>>,
110	) -> SendResult<(HostConfiguration<BlockNumberFor<T>>, ParaId, Vec<u8>)> {
111		let d = dest.take().ok_or(MissingArgument)?;
112		let id = if let (0, [Parachain(id)]) = d.unpack() {
113			*id
114		} else {
115			*dest = Some(d);
116			return Err(NotApplicable);
117		};
118
119		// Downward message passing.
120		let xcm = msg.take().ok_or(MissingArgument)?;
121		let config = configuration::ActiveConfig::<T>::get();
122		let para = id.into();
123		let price = P::price_for_delivery(para, &xcm);
124		let versioned_xcm = W::wrap_version(&d, xcm).map_err(|()| DestinationUnsupported)?;
125		versioned_xcm.check_is_decodable().map_err(|()| ExceedsMaxMessageSize)?;
126		let blob = versioned_xcm.encode();
127		dmp::Pallet::<T>::can_queue_downward_message(&config, &para, &blob)
128			.map_err(Into::<SendError>::into)?;
129
130		Ok(((config, para, blob), price))
131	}
132
133	fn deliver(
134		(config, para, blob): (HostConfiguration<BlockNumberFor<T>>, ParaId, Vec<u8>),
135	) -> Result<XcmHash, SendError> {
136		let hash = sp_io::hashing::blake2_256(&blob[..]);
137		dmp::Pallet::<T>::queue_downward_message(&config, para, blob)
138			.map(|()| hash)
139			.map_err(|error| {
140				log::debug!(
141					target: "xcm::xcm_sender::deliver",
142					"Failed to place into DMP queue: error: {error:?}, id: {hash:?}",
143				);
144				SendError::Transport(&"Error placing into DMP queue")
145			})
146	}
147
148	#[cfg(feature = "runtime-benchmarks")]
149	fn ensure_successful_delivery(location: Option<Location>) {
150		if let Some((0, [Parachain(id)])) = location.as_ref().map(|l| l.unpack()) {
151			dmp::Pallet::<T>::make_parachain_reachable(*id);
152		}
153	}
154}
155
156impl<T: dmp::Config, W, P> InspectMessageQueues for ChildParachainRouter<T, W, P> {
157	fn clear_messages() {
158		// Best effort: clear all dmp storage maps.
159		let _ = dmp::DownwardMessageQueueMeta::<T>::clear(u32::MAX, None);
160		let _ = dmp::DownwardMessageQueuePages::<T>::clear(u32::MAX, None);
161		let _ = dmp::DownwardMessageQueueLazyDelete::<T>::clear(u32::MAX, None);
162	}
163
164	fn get_messages() -> Vec<(VersionedLocation, Vec<VersionedXcm<()>>)> {
165		let para_ids: BTreeSet<_> = dmp::DownwardMessageQueueMeta::<T>::iter_keys()
166			.chain(dmp::migration::v0::DownwardMessageQueues::<T>::iter_keys())
167			.collect();
168
169		para_ids
170			.into_iter()
171			.map(|para_id| {
172				let decoded_messages: Vec<VersionedXcm<()>> =
173					dmp::Pallet::<T>::dmq_contents_do_not_call_in_consensus(para_id)
174						.iter()
175						.map(|downward_message| {
176							let message = VersionedXcm::<()>::decode_all_with_depth_limit(
177								MAX_XCM_DECODE_DEPTH,
178								&mut &downward_message.msg[..],
179							)
180							.unwrap();
181							log::trace!(
182								target: "xcm::DownwardMessageQueues::get_messages",
183								"Message: {:?}, sent at: {:?}", message, downward_message.sent_at
184							);
185							message
186						})
187						.collect();
188				(
189					VersionedLocation::from(Location::from(Parachain(para_id.into()))),
190					decoded_messages,
191				)
192			})
193			.collect()
194	}
195}
196
197/// Implementation of `xcm_builder::EnsureDelivery` which helps to ensure delivery to the
198/// `ParaId` parachain (sibling or child). Deposits existential deposit for origin (if needed).
199/// Deposits estimated fee to the origin account (if needed).
200/// Allows to trigger additional logic for specific `ParaId` (e.g. open HRMP channel) (if needed).
201#[cfg(feature = "runtime-benchmarks")]
202pub struct ToParachainDeliveryHelper<
203	XcmConfig,
204	ExistentialDeposit,
205	PriceForDelivery,
206	ParaId,
207	ToParaIdHelper,
208>(
209	core::marker::PhantomData<(
210		XcmConfig,
211		ExistentialDeposit,
212		PriceForDelivery,
213		ParaId,
214		ToParaIdHelper,
215	)>,
216);
217
218#[cfg(feature = "runtime-benchmarks")]
219impl<
220		XcmConfig: xcm_executor::Config,
221		ExistentialDeposit: Get<Option<Asset>>,
222		PriceForDelivery: PriceForMessageDelivery<Id = ParaId>,
223		Parachain: Get<ParaId>,
224		ToParachainHelper: polkadot_runtime_parachains::EnsureForParachain,
225	> xcm_builder::EnsureDelivery
226	for ToParachainDeliveryHelper<
227		XcmConfig,
228		ExistentialDeposit,
229		PriceForDelivery,
230		Parachain,
231		ToParachainHelper,
232	>
233{
234	fn ensure_successful_delivery(
235		origin_ref: &Location,
236		dest: &Location,
237		fee_reason: xcm_executor::traits::FeeReason,
238	) -> (Option<xcm_executor::FeesMode>, Option<Assets>) {
239		use alloc::vec;
240		use xcm::{latest::MAX_ITEMS_IN_ASSETS, MAX_INSTRUCTIONS_TO_DECODE};
241		use xcm_executor::{
242			traits::{FeeManager, TransactAsset},
243			FeesMode,
244		};
245
246		// check if the destination matches the expected `Parachain`.
247		if let Some(Parachain(para_id)) = dest.first_interior() {
248			if ParaId::from(*para_id) != Parachain::get().into() {
249				return (None, None);
250			}
251		} else {
252			return (None, None);
253		}
254
255		// allow more initialization for target parachain
256		ToParachainHelper::ensure(Parachain::get());
257
258		let mut fees_mode = None;
259		if !XcmConfig::FeeManager::is_waived(Some(origin_ref), fee_reason) {
260			// if not waived, we need to set up accounts for paying and receiving fees
261			let context = XcmContext { origin: None, message_id: XcmHash::default(), topic: None };
262
263			// mint ED to origin if needed
264			if let Some(ed) = ExistentialDeposit::get() {
265				let holdings = XcmConfig::AssetTransactor::mint_asset(&ed, &context).unwrap();
266				XcmConfig::AssetTransactor::deposit_asset(holdings, &origin_ref, Some(&context))
267					.unwrap();
268			}
269
270			// overestimate delivery fee
271			let mut max_assets: Vec<Asset> = Vec::new();
272			for i in 0..MAX_ITEMS_IN_ASSETS {
273				max_assets.push((GeneralIndex(i as u128), 100u128).into());
274			}
275			let overestimated_xcm =
276				vec![WithdrawAsset(max_assets.into()); MAX_INSTRUCTIONS_TO_DECODE as usize].into();
277			let overestimated_fees =
278				PriceForDelivery::price_for_delivery(Parachain::get(), &overestimated_xcm);
279
280			// mint overestimated fee to origin
281			for fee in overestimated_fees.inner() {
282				let holdings = XcmConfig::AssetTransactor::mint_asset(fee, &context).unwrap();
283				XcmConfig::AssetTransactor::deposit_asset(holdings, &origin_ref, Some(&context))
284					.unwrap();
285			}
286
287			// expected worst case - direct withdraw
288			fees_mode = Some(FeesMode { jit_withdraw: true });
289		}
290		(fees_mode, None)
291	}
292}
293
294#[cfg(test)]
295mod tests {
296	use super::*;
297	use crate::integration_tests::new_test_ext;
298	use alloc::vec;
299	use frame_support::{assert_ok, parameter_types};
300	use polkadot_runtime_parachains::FeeTracker;
301	use sp_runtime::FixedU128;
302	use xcm::MAX_XCM_DECODE_DEPTH;
303
304	parameter_types! {
305		pub const BaseDeliveryFee: u128 = 300_000_000;
306		pub const TransactionByteFee: u128 = 1_000_000;
307		pub FeeAssetId: AssetId = AssetId(Here.into());
308	}
309
310	struct TestFeeTracker;
311	impl FeeTracker for TestFeeTracker {
312		type Id = ParaId;
313
314		fn get_fee_factor(_: Self::Id) -> FixedU128 {
315			FixedU128::from_rational(101, 100)
316		}
317
318		fn set_fee_factor(_id: Self::Id, _val: FixedU128) {}
319
320		fn increase_fee_factor(_: Self::Id, _: u128) {}
321
322		fn decrease_fee_factor(_: Self::Id) -> bool {
323			true
324		}
325	}
326
327	type TestExponentialPrice =
328		ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, TestFeeTracker>;
329
330	#[test]
331	fn exponential_price_correct_price_calculation() {
332		let id: ParaId = 123.into();
333		let b: u128 = BaseDeliveryFee::get();
334		let m: u128 = TransactionByteFee::get();
335
336		// F * (B + msg_length * M)
337		// message_length = 1
338		let result: u128 = TestFeeTracker::get_fee_factor(id).saturating_mul_int(b + m);
339		assert_eq!(
340			TestExponentialPrice::price_for_delivery(id, &Xcm(vec![])),
341			(FeeAssetId::get(), result).into()
342		);
343
344		// message size = 2
345		let result: u128 = TestFeeTracker::get_fee_factor(id).saturating_mul_int(b + (2 * m));
346		assert_eq!(
347			TestExponentialPrice::price_for_delivery(id, &Xcm(vec![ClearOrigin])),
348			(FeeAssetId::get(), result).into()
349		);
350
351		// message size = 4
352		let result: u128 = TestFeeTracker::get_fee_factor(id).saturating_mul_int(b + (4 * m));
353		assert_eq!(
354			TestExponentialPrice::price_for_delivery(
355				id,
356				&Xcm(vec![SetAppendix(Xcm(vec![ClearOrigin]))])
357			),
358			(FeeAssetId::get(), result).into()
359		);
360	}
361
362	#[test]
363	fn child_parachain_router_validate_nested_xcm_works() {
364		let dest = Parachain(5555);
365
366		type Router = ChildParachainRouter<
367			crate::integration_tests::Test,
368			(),
369			NoPriceForMessageDelivery<ParaId>,
370		>;
371
372		// Message that is not too deeply nested:
373		let mut good = Xcm(vec![ClearOrigin]);
374		for _ in 0..MAX_XCM_DECODE_DEPTH - 1 {
375			good = Xcm(vec![SetAppendix(good)]);
376		}
377
378		new_test_ext().execute_with(|| {
379			configuration::ActiveConfig::<crate::integration_tests::Test>::mutate(|c| {
380				c.max_downward_message_size = u32::MAX;
381			});
382
383			dmp::Pallet::<crate::integration_tests::Test>::make_parachain_reachable(5555);
384
385			// Check that the good message is validated:
386			assert_ok!(<Router as SendXcm>::validate(
387				&mut Some(dest.into()),
388				&mut Some(good.clone())
389			));
390
391			// Nesting the message one more time should reject it:
392			let bad = Xcm(vec![SetAppendix(good)]);
393			assert_eq!(
394				Err(ExceedsMaxMessageSize),
395				<Router as SendXcm>::validate(&mut Some(dest.into()), &mut Some(bad))
396			);
397		});
398	}
399
400	#[test]
401	fn get_messages_surfaces_v0_only_paras() {
402		use polkadot_primitives::InboundDownwardMessage;
403
404		type Test = crate::integration_tests::Test;
405		type Router = ChildParachainRouter<Test, (), NoPriceForMessageDelivery<ParaId>>;
406
407		let para_v1: ParaId = 5000.into();
408		let para_v0: ParaId = 6000.into();
409		let xcm_v1 = VersionedXcm::from(Xcm::<()>(vec![ClearOrigin]));
410		let xcm_v0 = VersionedXcm::from(Xcm::<()>(vec![ClearOrigin]));
411
412		new_test_ext().execute_with(|| {
413			configuration::ActiveConfig::<Test>::mutate(|c| {
414				c.max_downward_message_size = 1024;
415			});
416			dmp::Pallet::<Test>::make_parachain_reachable(para_v1);
417			let config = configuration::ActiveConfig::<Test>::get();
418			assert_ok!(dmp::Pallet::<Test>::queue_downward_message(
419				&config,
420				para_v1,
421				xcm_v1.encode()
422			));
423
424			dmp::migration::v0::DownwardMessageQueues::<Test>::insert(
425				para_v0,
426				vec![InboundDownwardMessage { sent_at: 1, msg: xcm_v0.encode() }],
427			);
428
429			assert_eq!(
430				<Router as InspectMessageQueues>::get_messages(),
431				vec![
432					(
433						VersionedLocation::from(Location::from(Parachain(u32::from(para_v1)))),
434						vec![xcm_v1],
435					),
436					(
437						VersionedLocation::from(Location::from(Parachain(u32::from(para_v0)))),
438						vec![xcm_v0],
439					),
440				]
441			);
442		});
443	}
444}