referrerpolicy=no-referrer-when-downgrade

pallet_hrmp_relay/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Relay-chain HRMP deposit pallet
19//!
20//! Forward the HRMP channel deposit operations between the relay chain HRMP pallet and the
21//! parachain handling deposits.
22//! Implements [`ChannelDepositProvider`] and [`OnDepositSet`] for the relay chain HRMP pallet.
23//! Forward the deposit operations with [`SendToPara`] following the protocol defined in
24//! hrmp-primitives and get results back through [`Call::receive`].
25//!
26//! [`Call::force_answer`] is called by governance to fix potential inconsistent state.
27
28#![cfg_attr(not(feature = "std"), no_std)]
29
30extern crate alloc;
31
32use frame_support::{
33	pallet_prelude::*,
34	weights::{Weight, WeightMeter},
35};
36use hrmp_primitives::{
37	ChannelId, DepositError as WireDepositError, DepositSide, MessageToPara, MessageToParaV1,
38	MessageToRelay, MessageToRelayV1,
39};
40use polkadot_primitives::{HrmpChannelId, Id as ParaId};
41use polkadot_runtime_parachains::{
42	ensure_parachain,
43	hrmp::deposits::{
44		ChannelDepositProvider, DepositAction, DepositChangeRequest, DepositChangeResponse,
45		DepositError, OnDepositSet,
46	},
47	Origin as ParachainOrigin,
48};
49
50pub use pallet::*;
51pub use weights::WeightInfo;
52
53pub mod weights;
54
55#[cfg(feature = "runtime-benchmarks")]
56mod benchmarking;
57#[cfg(test)]
58mod integration_tests;
59#[cfg(test)]
60mod mock;
61#[cfg(test)]
62mod tests;
63
64/// The index of [`Call::receive`] that receives [`MessageToPara`].
65pub const RECEIVE_CALL_INDEX: u8 = 0;
66
67const LOG_TARGET: &str = "runtime::hrmp-relay";
68
69/// Used to send an XCM `Transact` to `pallet-hrmp-para` on the chain that holds the deposits.
70pub trait SendToPara {
71	/// Send `message` to the parachain.
72	#[allow(clippy::result_unit_err)]
73	fn send(message: MessageToPara) -> Result<(), ()>;
74}
75
76/// A [`MessageToParaV1::Release`] the transport refused, waiting in [`FailedReleases`] to be
77/// retried.
78#[derive(Encode, Decode, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen)]
79pub struct ReleaseMessageToPara {
80	/// The channel whose deposits are given back.
81	pub channel: ChannelId,
82	/// Whether the sender's deposit is given back.
83	pub sender: bool,
84	/// Whether the recipient's deposit is given back.
85	pub recipient: bool,
86}
87
88impl From<ReleaseMessageToPara> for MessageToPara {
89	fn from(release: ReleaseMessageToPara) -> Self {
90		let ReleaseMessageToPara { channel, sender, recipient } = release;
91		MessageToPara::V1(MessageToParaV1::Release { channel, sender, recipient })
92	}
93}
94
95#[cfg(feature = "std")]
96impl SendToPara for () {
97	fn send(_message: MessageToPara) -> Result<(), ()> {
98		Ok(())
99	}
100}
101
102/// Prepares the runtime for this pallet's benchmarks.
103#[cfg(feature = "runtime-benchmarks")]
104pub trait BenchmarkHelper {
105	/// Makes [`Config::SendToPara`] take messages.
106	fn ensure_send_to_para();
107}
108
109#[cfg(feature = "runtime-benchmarks")]
110impl BenchmarkHelper for () {
111	fn ensure_send_to_para() {}
112}
113
114#[frame_support::pallet]
115pub mod pallet {
116	use super::*;
117	use frame_system::pallet_prelude::*;
118
119	#[pallet::config]
120	pub trait Config:
121		frame_system::Config<
122		RuntimeOrigin: Into<Result<ParachainOrigin, <Self as frame_system::Config>::RuntimeOrigin>>,
123	>
124	{
125		/// Receives the outcome of each pending request: the `hrmp` pallet.
126		type OnDepositSet: OnDepositSet;
127
128		/// The para that holds the deposits.
129		///
130		/// Only it may answer requests.
131		#[pallet::constant]
132		type HolderParaId: Get<ParaId>;
133
134		/// Sends messages to the parachain that holds the deposits.
135		type SendToPara: SendToPara;
136
137		/// How many releases may wait in [`FailedReleases`] to be retried.
138		#[pallet::constant]
139		type MaxFailedReleases: Get<u32>;
140
141		/// Weight information for the extrinsics in this pallet.
142		type WeightInfo: WeightInfo;
143
144		/// Prepares the runtime for the benchmarks.
145		#[cfg(feature = "runtime-benchmarks")]
146		type BenchmarkHelper: BenchmarkHelper;
147	}
148
149	#[pallet::pallet]
150	pub struct Pallet<T>(_);
151
152	/// The id of the next [`MessageToParaV1::SetDeposits`].
153	#[pallet::storage]
154	pub type NextRequestId<T: Config> = StorageValue<_, u64, ValueQuery>;
155
156	/// The requests waiting for their answer, handed back unchanged once it comes.
157	#[pallet::storage]
158	pub type PendingRequests<T: Config> =
159		StorageMap<_, Twox64Concat, u64, DepositChangeRequest, OptionQuery>;
160
161	/// The pending request of each channel side, at most one.
162	#[pallet::storage]
163	pub type PendingSides<T: Config> =
164		StorageMap<_, Twox64Concat, (ChannelId, DepositSide), u64, OptionQuery>;
165
166	/// Releases that could not be sent yet, oldest first.
167	///
168	/// A release cannot fail: [`ChannelDepositProvider`] requires it to be applied. So when
169	/// [`Config::SendToPara`] refuses a release, it waits here instead of being dropped, and is
170	/// retried in `on_poll`. Any later release joins the queue behind it, to keep releases in
171	/// order.
172	///
173	/// Normally nothing waits here. It only fills when the transport to the parachain is broken.
174	/// While it is not empty, other deposit requests are refused with [`Error::TransportBusy`] so
175	/// that they do not overtake a waiting release. Once it is full, further releases are dropped
176	/// with [`Event::ReleaseDropped`]; governance then has to fix the deposits on the parachain
177	/// with `force_set_deposit` of `pallet-hrmp-para`.
178	#[pallet::storage]
179	pub type FailedReleases<T: Config> =
180		StorageValue<_, BoundedVec<ReleaseMessageToPara, T::MaxFailedReleases>, ValueQuery>;
181
182	#[pallet::event]
183	#[pallet::generate_deposit(pub(super) fn deposit_event)]
184	pub enum Event<T: Config> {
185		/// The parachain was asked to set the deposits of a channel.
186		DepositRequested { id: u64, channel: ChannelId },
187		/// The parachain answered a request.
188		DepositAnswered { id: u64, result: Result<(), WireDepositError> },
189		/// An answer came for no pending request. It was ignored.
190		UnknownAnswer { id: u64 },
191		/// The parachain was asked to release deposits of a channel.
192		ReleaseSent { channel: ChannelId },
193		/// A release could not be sent nor kept, and was dropped.
194		ReleaseDropped { channel: ChannelId },
195	}
196
197	#[pallet::error]
198	pub enum Error<T> {
199		/// A request for one side of the channel is still pending.
200		DepositPending,
201		/// Earlier releases still wait for the transport.
202		TransportBusy,
203		/// The request could not be handed to the transport.
204		SendFailed,
205	}
206
207	#[pallet::hooks]
208	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
209		fn on_poll(_: BlockNumberFor<T>, meter: &mut WeightMeter) {
210			Self::retry_failed_releases(meter);
211		}
212
213		#[cfg(feature = "try-runtime")]
214		fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
215			Self::do_try_state()
216		}
217	}
218
219	#[pallet::call]
220	impl<T: Config> Pallet<T> {
221		/// Take a message from the parachain that holds the HRMP deposits.
222		///
223		/// The origin must be the parachain holding HRMP deposits.
224		// The index must equal `RECEIVE_CALL_INDEX`.
225		#[pallet::call_index(0)]
226		#[pallet::weight(T::WeightInfo::receive().saturating_add(Pallet::<T>::max_answer_weight()))]
227		pub fn receive(origin: OriginFor<T>, message: MessageToRelay) -> DispatchResult {
228			let para = ensure_parachain(origin)?;
229			ensure!(para == T::HolderParaId::get(), DispatchError::BadOrigin);
230
231			match message {
232				MessageToRelay::V1(MessageToRelayV1::DepositsSet { id, result }) => {
233					Self::answer(id, result)
234				},
235			}
236
237			Ok(())
238		}
239
240		/// Answer the pending request `id` on the parachain's behalf, for an answer that never
241		/// arrived.
242		///
243		/// An answer for no pending request is ignored, with [`Event::UnknownAnswer`].
244		#[pallet::call_index(1)]
245		#[pallet::weight(T::WeightInfo::receive().saturating_add(Pallet::<T>::max_answer_weight()))]
246		pub fn force_answer(
247			origin: OriginFor<T>,
248			id: u64,
249			result: Result<(), WireDepositError>,
250		) -> DispatchResult {
251			ensure_root(origin)?;
252
253			Self::answer(id, result);
254
255			Ok(())
256		}
257	}
258}
259
260impl<T: Config> Pallet<T> {
261	fn to_wire(channel_id: &HrmpChannelId) -> ChannelId {
262		ChannelId { sender: channel_id.sender.into(), recipient: channel_id.recipient.into() }
263	}
264
265	/// The sides `request` changes.
266	fn sides(request: &DepositChangeRequest) -> impl Iterator<Item = DepositSide> {
267		[
268			request.sender.map(|_| DepositSide::Sender),
269			request.recipient.map(|_| DepositSide::Recipient),
270		]
271		.into_iter()
272		.flatten()
273	}
274
275	/// The most [`Config::OnDepositSet`] may spend on an answer.
276	fn max_answer_weight() -> Weight {
277		[
278			DepositAction::InitOpenChannel {
279				max_capacity: 1,
280				max_message_size: 1,
281				max_total_size: 1,
282			},
283			DepositAction::InitAndAcceptOpenChannel {
284				max_capacity: 1,
285				max_message_size: 1,
286				max_total_size: 1,
287			},
288			DepositAction::AcceptOpenChannel { max_capacity: 1, max_message_size: 1 },
289			DepositAction::PokeChannelDeposits,
290		]
291		.iter()
292		.map(T::OnDepositSet::weight_of_on_deposit_set)
293		.fold(Weight::zero(), |max, w| max.max(w))
294	}
295
296	/// Hands the answer to request `id` back to [`Config::OnDepositSet`].
297	fn answer(id: u64, result: Result<(), WireDepositError>) {
298		let Some(request) = PendingRequests::<T>::take(id) else {
299			Self::deposit_event(Event::UnknownAnswer { id });
300			return;
301		};
302		let channel = Self::to_wire(&request.channel_id);
303
304		for side in Self::sides(&request) {
305			PendingSides::<T>::remove((channel, side));
306		}
307		Self::deposit_event(Event::DepositAnswered { id, result });
308		let result = result.map_err(|e| match e {
309			WireDepositError::InsufficientFunds => DepositError::InsufficientFunds,
310			WireDepositError::Other => DepositError::Other,
311		});
312		T::OnDepositSet::on_deposit_set(request, result);
313	}
314
315	/// Retries the releases in [`FailedReleases`], oldest first, until `meter` has no room for the
316	/// next one or the transport refuses it.
317	fn retry_failed_releases(meter: &mut WeightMeter) {
318		if meter.try_consume(T::WeightInfo::retry_failed_releases(0)).is_err() {
319			return;
320		}
321
322		let mut releases = FailedReleases::<T>::get();
323		let mut sent = 0u32;
324		for release in releases.iter() {
325			// What one more message adds to the retry.
326			let weight = T::WeightInfo::retry_failed_releases(sent + 1)
327				.saturating_sub(T::WeightInfo::retry_failed_releases(sent));
328			if meter.try_consume(weight).is_err() {
329				break;
330			}
331			if T::SendToPara::send(release.clone().into()).is_err() {
332				break;
333			}
334			Self::deposit_event(Event::ReleaseSent { channel: release.channel });
335			sent += 1;
336		}
337
338		if sent > 0 {
339			releases.drain(..sent as usize);
340			FailedReleases::<T>::put(releases);
341		}
342	}
343
344	/// Whether no release waits in [`FailedReleases`].
345	fn failed_releases_is_empty() -> bool {
346		FailedReleases::<T>::decode_len().unwrap_or_default() == 0
347	}
348
349	/// Sends a release, or keeps it in [`FailedReleases`] behind those already waiting there.
350	fn release(channel: ChannelId, sender: bool, recipient: bool) {
351		let release = ReleaseMessageToPara { channel, sender, recipient };
352		if Self::failed_releases_is_empty() && T::SendToPara::send(release.clone().into()).is_ok() {
353			Self::deposit_event(Event::ReleaseSent { channel });
354			return;
355		}
356		if FailedReleases::<T>::try_append(release).is_err() {
357			log::error!(
358				target: LOG_TARGET,
359				"no room for failed releases, dropped the release of {channel:?}"
360			);
361			Self::deposit_event(Event::ReleaseDropped { channel });
362		}
363	}
364
365	/// Checks that the pending requests and the sides they lock agree.
366	#[cfg(any(feature = "try-runtime", test))]
367	pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
368		for ((channel, side), id) in PendingSides::<T>::iter() {
369			let request = PendingRequests::<T>::get(id)
370				.ok_or("hrmp-relay: a side is locked by no pending request")?;
371			ensure!(
372				Self::to_wire(&request.channel_id) == channel &&
373					Self::sides(&request).any(|s| s == side),
374				"hrmp-relay: a side is locked by a request for another side"
375			);
376		}
377
378		for (id, request) in PendingRequests::<T>::iter() {
379			let channel = Self::to_wire(&request.channel_id);
380			for side in Self::sides(&request) {
381				ensure!(
382					PendingSides::<T>::get((channel, side)) == Some(id),
383					"hrmp-relay: a pending request does not lock its side"
384				);
385			}
386		}
387
388		Ok(())
389	}
390}
391
392impl<T: Config> ChannelDepositProvider for Pallet<T> {
393	type OnDepositSet = T::OnDepositSet;
394
395	fn try_set_deposit(
396		request: DepositChangeRequest,
397	) -> Result<DepositChangeResponse, DispatchError> {
398		let channel = Self::to_wire(&request.channel_id);
399
400		// A release only gives back: it is sent in order and never refused. Everything held for
401		// the side is released.
402		if request.action == DepositAction::Release {
403			Self::release(channel, request.sender.is_some(), request.recipient.is_some());
404			return Ok(DepositChangeResponse::Applied);
405		}
406
407		ensure!(
408			Self::sides(&request).all(|side| !PendingSides::<T>::contains_key((channel, side))),
409			Error::<T>::DepositPending
410		);
411		// A request must not overtake a release made before it.
412		ensure!(Self::failed_releases_is_empty(), Error::<T>::TransportBusy);
413
414		let id = NextRequestId::<T>::get();
415		let message = MessageToPara::V1(MessageToParaV1::SetDeposits {
416			id,
417			channel,
418			sender: request.sender.map(|c| c.target),
419			recipient: request.recipient.map(|c| c.target),
420		});
421		T::SendToPara::send(message).map_err(|()| Error::<T>::SendFailed)?;
422
423		NextRequestId::<T>::put(id.wrapping_add(1));
424		for side in Self::sides(&request) {
425			PendingSides::<T>::insert((channel, side), id);
426		}
427		PendingRequests::<T>::insert(id, request);
428		Self::deposit_event(Event::DepositRequested { id, channel });
429		Ok(DepositChangeResponse::Pending)
430	}
431
432	fn weight_of_try_set_deposit() -> Weight {
433		T::WeightInfo::try_set_deposit_both_sides().max(T::WeightInfo::try_set_deposit_release())
434	}
435}