referrerpolicy=no-referrer-when-downgrade

polkadot_runtime_parachains/
hrmp.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
17use crate::{
18	configuration::{self, HostConfiguration},
19	dmp, ensure_parachain, initializer, paras,
20};
21use alloc::{
22	collections::{btree_map::BTreeMap, btree_set::BTreeSet},
23	vec,
24	vec::Vec,
25};
26use codec::{Decode, Encode};
27use core::{fmt, mem};
28use frame_support::{pallet_prelude::*, traits::ReservableCurrency, DefaultNoBound};
29use frame_system::pallet_prelude::*;
30use polkadot_parachain_primitives::primitives::{HorizontalMessages, IsSystem};
31use polkadot_primitives::{
32	Balance, Hash, HrmpChannelId, Id as ParaId, InboundHrmpMessage, OutboundHrmpMessage,
33	SessionIndex,
34};
35use scale_info::TypeInfo;
36use sp_runtime::traits::{AccountIdConversion, BlakeTwo256, Hash as HashT, UniqueSaturatedInto};
37
38pub use pallet::*;
39
40/// Maximum bound that can be set for inbound channels.
41///
42/// If inaccurate, the weighing of this pallet might become inaccurate. It is expected form the
43/// `configurations` pallet to check these values before setting
44pub const HRMP_MAX_INBOUND_CHANNELS_BOUND: u32 = 128;
45/// Same as [`HRMP_MAX_INBOUND_CHANNELS_BOUND`], but for outbound channels.
46pub const HRMP_MAX_OUTBOUND_CHANNELS_BOUND: u32 = 128;
47
48#[cfg(test)]
49pub(crate) mod tests;
50
51#[cfg(test)]
52mod remote_deposit_tests;
53
54#[cfg(feature = "runtime-benchmarks")]
55mod benchmarking;
56
57pub mod deposits;
58use deposits::{
59	ChannelDepositProvider, DepositAction, DepositChange, DepositChangeRequest, DepositError,
60};
61
62const LOG_TARGET: &str = "runtime::hrmp";
63
64pub trait WeightInfo {
65	fn hrmp_init_open_channel() -> Weight;
66	fn hrmp_accept_open_channel() -> Weight;
67	fn hrmp_close_channel() -> Weight;
68	fn force_clean_hrmp(i: u32, e: u32) -> Weight;
69	fn force_process_hrmp_open(c: u32) -> Weight;
70	fn force_process_hrmp_close(c: u32) -> Weight;
71	fn hrmp_cancel_open_request(c: u32) -> Weight;
72	fn clean_open_channel_requests(c: u32) -> Weight;
73	fn force_open_hrmp_channel(c: u32) -> Weight;
74	fn establish_system_channel() -> Weight;
75	fn poke_channel_deposits() -> Weight;
76	fn establish_channel_with_system() -> Weight;
77}
78
79/// A weight info that is only suitable for testing.
80pub struct TestWeightInfo;
81
82impl WeightInfo for TestWeightInfo {
83	fn hrmp_accept_open_channel() -> Weight {
84		Weight::MAX
85	}
86	fn force_clean_hrmp(_: u32, _: u32) -> Weight {
87		Weight::MAX
88	}
89	fn force_process_hrmp_close(_: u32) -> Weight {
90		Weight::MAX
91	}
92	fn force_process_hrmp_open(_: u32) -> Weight {
93		Weight::MAX
94	}
95	fn hrmp_cancel_open_request(_: u32) -> Weight {
96		Weight::MAX
97	}
98	fn hrmp_close_channel() -> Weight {
99		Weight::MAX
100	}
101	fn hrmp_init_open_channel() -> Weight {
102		Weight::MAX
103	}
104	fn clean_open_channel_requests(_: u32) -> Weight {
105		Weight::MAX
106	}
107	fn force_open_hrmp_channel(_: u32) -> Weight {
108		Weight::MAX
109	}
110	fn establish_system_channel() -> Weight {
111		Weight::MAX
112	}
113	fn poke_channel_deposits() -> Weight {
114		Weight::MAX
115	}
116	fn establish_channel_with_system() -> Weight {
117		Weight::MAX
118	}
119}
120
121/// A description of a request to open an HRMP channel.
122#[derive(Encode, Decode, TypeInfo)]
123pub struct HrmpOpenChannelRequest {
124	/// Indicates if this request was confirmed by the recipient.
125	pub confirmed: bool,
126	/// NOTE: this field is deprecated. Channel open requests became non-expiring and this value
127	/// became unused.
128	pub _age: SessionIndex,
129	/// The amount that the sender supplied at the time of creation of this request.
130	pub sender_deposit: Balance,
131	/// The maximum message size that could be put into the channel.
132	pub max_message_size: u32,
133	/// The maximum number of messages that can be pending in the channel at once.
134	pub max_capacity: u32,
135	/// The maximum total size of the messages that can be pending in the channel at once.
136	pub max_total_size: u32,
137}
138
139/// A metadata of an HRMP channel.
140#[derive(Encode, Decode, TypeInfo)]
141#[cfg_attr(test, derive(Debug))]
142pub struct HrmpChannel {
143	// NOTE: This structure is used by parachains via merkle proofs. Therefore, this struct
144	// requires special treatment.
145	//
146	// A parachain requested this struct can only depend on the subset of this struct.
147	// Specifically, only a first few fields can be depended upon (See `AbridgedHrmpChannel`).
148	// These fields cannot be changed without corresponding migration of parachains.
149	/// The maximum number of messages that can be pending in the channel at once.
150	pub max_capacity: u32,
151	/// The maximum total size of the messages that can be pending in the channel at once.
152	pub max_total_size: u32,
153	/// The maximum message size that could be put into the channel.
154	pub max_message_size: u32,
155	/// The current number of messages pending in the channel.
156	/// Invariant: should be less or equal to `max_capacity`.s`.
157	pub msg_count: u32,
158	/// The total size in bytes of all message payloads in the channel.
159	/// Invariant: should be less or equal to `max_total_size`.
160	pub total_size: u32,
161	/// A head of the Message Queue Chain for this channel. Each link in this chain has a form:
162	/// `(prev_head, B, H(M))`, where
163	/// - `prev_head`: is the previous value of `mqc_head` or zero if none.
164	/// - `B`: is the [relay-chain] block number in which a message was appended
165	/// - `H(M)`: is the hash of the message being appended.
166	/// This value is initialized to a special value that consists of all zeroes which indicates
167	/// that no messages were previously added.
168	pub mqc_head: Option<Hash>,
169	/// The amount that the sender supplied as a deposit when opening this channel.
170	pub sender_deposit: Balance,
171	/// The amount that the recipient supplied as a deposit when accepting opening this channel.
172	pub recipient_deposit: Balance,
173}
174
175/// An error returned by [`Pallet::check_hrmp_watermark`] that indicates an acceptance criteria
176/// check didn't pass.
177pub(crate) enum HrmpWatermarkAcceptanceErr<BlockNumber> {
178	AdvancementRule { new_watermark: BlockNumber, last_watermark: BlockNumber },
179	AheadRelayParent { new_watermark: BlockNumber, relay_chain_parent_number: BlockNumber },
180	LandsOnBlockWithNoMessages { new_watermark: BlockNumber },
181}
182
183/// An error returned by [`Pallet::check_outbound_hrmp`] that indicates an acceptance criteria check
184/// didn't pass.
185pub(crate) enum OutboundHrmpAcceptanceErr {
186	MoreMessagesThanPermitted { sent: u32, permitted: u32 },
187	NotSorted { idx: u32 },
188	NoSuchChannel { idx: u32, channel_id: HrmpChannelId },
189	MaxMessageSizeExceeded { idx: u32, msg_size: u32, max_size: u32 },
190	TotalSizeExceeded { idx: u32, total_size: u32, limit: u32 },
191	CapacityExceeded { idx: u32, count: u32, limit: u32 },
192}
193
194impl<BlockNumber> fmt::Debug for HrmpWatermarkAcceptanceErr<BlockNumber>
195where
196	BlockNumber: fmt::Debug,
197{
198	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
199		use HrmpWatermarkAcceptanceErr::*;
200		match self {
201			AdvancementRule { new_watermark, last_watermark } => write!(
202				fmt,
203				"the HRMP watermark is not advanced relative to the last watermark ({:?} > {:?})",
204				new_watermark, last_watermark,
205			),
206			AheadRelayParent { new_watermark, relay_chain_parent_number } => write!(
207				fmt,
208				"the HRMP watermark is ahead the relay-parent ({:?} > {:?})",
209				new_watermark, relay_chain_parent_number
210			),
211			LandsOnBlockWithNoMessages { new_watermark } => write!(
212				fmt,
213				"the HRMP watermark ({:?}) doesn't land on a block with messages received",
214				new_watermark
215			),
216		}
217	}
218}
219
220impl fmt::Debug for OutboundHrmpAcceptanceErr {
221	fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
222		use OutboundHrmpAcceptanceErr::*;
223		match self {
224			MoreMessagesThanPermitted { sent, permitted } => write!(
225				fmt,
226				"more HRMP messages than permitted by config ({} > {})",
227				sent, permitted,
228			),
229			NotSorted { idx } => {
230				write!(fmt, "the HRMP messages are not sorted (first unsorted is at index {})", idx,)
231			},
232			NoSuchChannel { idx, channel_id } => write!(
233				fmt,
234				"the HRMP message at index {} is sent to a non existent channel {:?}->{:?}",
235				idx, channel_id.sender, channel_id.recipient,
236			),
237			MaxMessageSizeExceeded { idx, msg_size, max_size } => write!(
238				fmt,
239				"the HRMP message at index {} exceeds the negotiated channel maximum message size ({} > {})",
240				idx, msg_size, max_size,
241			),
242			TotalSizeExceeded { idx, total_size, limit } => write!(
243				fmt,
244				"sending the HRMP message at index {} would exceed the negotiated channel total size  ({} > {})",
245				idx, total_size, limit,
246			),
247			CapacityExceeded { idx, count, limit } => write!(
248				fmt,
249				"sending the HRMP message at index {} would exceed the negotiated channel capacity  ({} > {})",
250				idx, count, limit,
251			),
252		}
253	}
254}
255
256#[frame_support::pallet]
257pub mod pallet {
258	use super::*;
259
260	#[pallet::pallet]
261	#[pallet::without_storage_info]
262	pub struct Pallet<T>(_);
263
264	#[pallet::config]
265	pub trait Config:
266		frame_system::Config + configuration::Config + paras::Config + dmp::Config
267	{
268		/// The outer event type.
269		#[allow(deprecated)]
270		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
271
272		type RuntimeOrigin: From<crate::Origin>
273			+ From<<Self as frame_system::Config>::RuntimeOrigin>
274			+ Into<Result<crate::Origin, <Self as Config>::RuntimeOrigin>>;
275
276		/// The origin that can perform "force" actions on channels.
277		type ChannelManager: EnsureOrigin<<Self as frame_system::Config>::RuntimeOrigin>;
278
279		/// Holds the channel deposits when this pallet is its own [`Config::DepositProvider`].
280		///
281		/// NOTE that this Currency instance will be charged with the amounts defined in the
282		/// `Configuration` pallet. Specifically, that means that the `Balance` of the `Currency`
283		/// implementation should be the same as `Balance` as used in the `Configuration`.
284		type Currency: ReservableCurrency<Self::AccountId>;
285
286		/// Where the channel deposits are held, see [`deposits`]. `Pallet<Self>` holds them in
287		/// [`Config::Currency`].
288		type DepositProvider: ChannelDepositProvider<OnDepositSet = Pallet<Self>>;
289
290		/// The default channel size and capacity to use when opening a channel to a system
291		/// parachain.
292		type DefaultChannelSizeAndCapacityWithSystem: Get<(u32, u32)>;
293
294		/// Means of converting an `Xcm` into a `VersionedXcm`. This pallet sends HRMP XCM
295		/// notifications to the channel-related parachains, while the `WrapVersion` implementation
296		/// attempts to wrap them into the most suitable XCM version for the destination parachain.
297		///
298		/// NOTE: For example, `pallet_xcm` provides an accurate implementation (recommended), or
299		/// the default `()` implementation uses the latest XCM version for all parachains.
300		type VersionWrapper: xcm::WrapVersion;
301
302		/// Something that provides the weight of this pallet.
303		type WeightInfo: WeightInfo;
304	}
305
306	#[pallet::event]
307	#[pallet::generate_deposit(pub(super) fn deposit_event)]
308	pub enum Event<T: Config> {
309		/// Open HRMP channel requested.
310		OpenChannelRequested {
311			sender: ParaId,
312			recipient: ParaId,
313			proposed_max_capacity: u32,
314			proposed_max_message_size: u32,
315		},
316		/// An HRMP channel request sent by the receiver was canceled by either party.
317		OpenChannelCanceled { by_parachain: ParaId, channel_id: HrmpChannelId },
318		/// Open HRMP channel accepted.
319		OpenChannelAccepted { sender: ParaId, recipient: ParaId },
320		/// HRMP channel closed.
321		ChannelClosed { by_parachain: ParaId, channel_id: HrmpChannelId },
322		/// An HRMP channel was opened via Root origin, once both deposits were taken.
323		HrmpChannelForceOpened {
324			sender: ParaId,
325			recipient: ParaId,
326			proposed_max_capacity: u32,
327			proposed_max_message_size: u32,
328		},
329		/// An HRMP channel was opened with a system chain.
330		HrmpSystemChannelOpened {
331			sender: ParaId,
332			recipient: ParaId,
333			proposed_max_capacity: u32,
334			proposed_max_message_size: u32,
335		},
336		/// An HRMP channel's deposits were updated.
337		OpenChannelDepositsUpdated { sender: ParaId, recipient: ParaId },
338		/// The deposit provider refused a pending deposit change. Nothing was recorded.
339		DepositRefused { channel_id: HrmpChannelId, error: DepositError },
340		/// A pending deposit change came back after its checks stopped passing. The deposits it
341		/// took were given back and nothing was recorded.
342		DepositReturned { channel_id: HrmpChannelId, error: DispatchError },
343	}
344
345	#[pallet::error]
346	pub enum Error<T> {
347		/// The sender tried to open a channel to themselves.
348		OpenHrmpChannelToSelf,
349		/// The recipient is not a valid para.
350		OpenHrmpChannelInvalidRecipient,
351		/// The requested capacity is zero.
352		OpenHrmpChannelZeroCapacity,
353		/// The requested capacity exceeds the global limit.
354		OpenHrmpChannelCapacityExceedsLimit,
355		/// The requested maximum message size is 0.
356		OpenHrmpChannelZeroMessageSize,
357		/// The open request requested the message size that exceeds the global limit.
358		OpenHrmpChannelMessageSizeExceedsLimit,
359		/// The channel already exists
360		OpenHrmpChannelAlreadyExists,
361		/// There is already a request to open the same channel.
362		OpenHrmpChannelAlreadyRequested,
363		/// The sender already has the maximum number of allowed outbound channels.
364		OpenHrmpChannelLimitExceeded,
365		/// The channel from the sender to the origin doesn't exist.
366		AcceptHrmpChannelDoesntExist,
367		/// The channel is already confirmed.
368		AcceptHrmpChannelAlreadyConfirmed,
369		/// The recipient already has the maximum number of allowed inbound channels.
370		AcceptHrmpChannelLimitExceeded,
371		/// The origin tries to close a channel where it is neither the sender nor the recipient.
372		CloseHrmpChannelUnauthorized,
373		/// The channel to be closed doesn't exist.
374		CloseHrmpChannelDoesntExist,
375		/// The channel close request is already requested.
376		CloseHrmpChannelAlreadyUnderway,
377		/// Canceling is requested by neither the sender nor recipient of the open channel request.
378		CancelHrmpOpenChannelUnauthorized,
379		/// The open request doesn't exist.
380		OpenHrmpChannelDoesntExist,
381		/// Cannot cancel an HRMP open channel request because it is already confirmed.
382		OpenHrmpChannelAlreadyConfirmed,
383		/// The provided witness data is wrong.
384		WrongWitness,
385		/// The channel between these two chains cannot be authorized.
386		ChannelCreationNotAuthorized,
387		/// The sender is not a valid para.
388		OpenHrmpChannelInvalidSender,
389		/// The recipient's deposit changed while it was being taken.
390		AcceptHrmpChannelDepositChanged,
391		/// The open channel request was canceled and made anew with other limits while the
392		/// recipient's deposit was being taken.
393		AcceptHrmpChannelRequestChanged,
394		/// The channel's deposits changed while they were being updated.
395		ChannelDepositsChanged,
396	}
397
398	/// The set of pending HRMP open channel requests.
399	///
400	/// The set is accompanied by a list for iteration.
401	///
402	/// Invariant:
403	/// - There are no channels that exists in list but not in the set and vice versa.
404	#[pallet::storage]
405	pub type HrmpOpenChannelRequests<T: Config> =
406		StorageMap<_, Twox64Concat, HrmpChannelId, HrmpOpenChannelRequest>;
407
408	// NOTE: could become bounded, but we don't have a global maximum for this.
409	// `HRMP_MAX_INBOUND_CHANNELS_BOUND` are per parachain, while this storage tracks the
410	// global state.
411	#[pallet::storage]
412	pub type HrmpOpenChannelRequestsList<T: Config> =
413		StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
414
415	/// This mapping tracks how many open channel requests are initiated by a given sender para.
416	/// Invariant: `HrmpOpenChannelRequests` should contain the same number of items that has
417	/// `(X, _)` as the number of `HrmpOpenChannelRequestCount` for `X`.
418	#[pallet::storage]
419	pub type HrmpOpenChannelRequestCount<T: Config> =
420		StorageMap<_, Twox64Concat, ParaId, u32, ValueQuery>;
421
422	/// This mapping tracks how many open channel requests were accepted by a given recipient para.
423	/// Invariant: `HrmpOpenChannelRequests` should contain the same number of items `(_, X)` with
424	/// `confirmed` set to true, as the number of `HrmpAcceptedChannelRequestCount` for `X`.
425	#[pallet::storage]
426	pub type HrmpAcceptedChannelRequestCount<T: Config> =
427		StorageMap<_, Twox64Concat, ParaId, u32, ValueQuery>;
428
429	/// A set of pending HRMP close channel requests that are going to be closed during the session
430	/// change. Used for checking if a given channel is registered for closure.
431	///
432	/// The set is accompanied by a list for iteration.
433	///
434	/// Invariant:
435	/// - There are no channels that exists in list but not in the set and vice versa.
436	#[pallet::storage]
437	pub type HrmpCloseChannelRequests<T: Config> = StorageMap<_, Twox64Concat, HrmpChannelId, ()>;
438
439	#[pallet::storage]
440	pub type HrmpCloseChannelRequestsList<T: Config> =
441		StorageValue<_, Vec<HrmpChannelId>, ValueQuery>;
442
443	/// The HRMP watermark associated with each para.
444	/// Invariant:
445	/// - each para `P` used here as a key should satisfy `Paras::is_valid_para(P)` within a
446	///   session.
447	#[pallet::storage]
448	pub type HrmpWatermarks<T: Config> = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
449
450	/// HRMP channel data associated with each para.
451	/// Invariant:
452	/// - each participant in the channel should satisfy `Paras::is_valid_para(P)` within a session.
453	#[pallet::storage]
454	pub type HrmpChannels<T: Config> = StorageMap<_, Twox64Concat, HrmpChannelId, HrmpChannel>;
455
456	/// Ingress/egress indexes allow to find all the senders and receivers given the opposite side.
457	/// I.e.
458	///
459	/// (a) ingress index allows to find all the senders for a given recipient.
460	/// (b) egress index allows to find all the recipients for a given sender.
461	///
462	/// Invariants:
463	/// - for each ingress index entry for `P` each item `I` in the index should present in
464	///   `HrmpChannels` as `(I, P)`.
465	/// - for each egress index entry for `P` each item `E` in the index should present in
466	///   `HrmpChannels` as `(P, E)`.
467	/// - there should be no other dangling channels in `HrmpChannels`.
468	/// - the vectors are sorted.
469	#[pallet::storage]
470	pub type HrmpIngressChannelsIndex<T: Config> =
471		StorageMap<_, Twox64Concat, ParaId, Vec<ParaId>, ValueQuery>;
472
473	// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
474	// the format will require migration of parachains.
475	#[pallet::storage]
476	pub type HrmpEgressChannelsIndex<T: Config> =
477		StorageMap<_, Twox64Concat, ParaId, Vec<ParaId>, ValueQuery>;
478
479	/// Storage for the messages for each channel.
480	/// Invariant: cannot be non-empty if the corresponding channel in `HrmpChannels` is `None`.
481	#[pallet::storage]
482	pub type HrmpChannelContents<T: Config> = StorageMap<
483		_,
484		Twox64Concat,
485		HrmpChannelId,
486		Vec<InboundHrmpMessage<BlockNumberFor<T>>>,
487		ValueQuery,
488	>;
489
490	/// Maintains a mapping that can be used to answer the question: What paras sent a message at
491	/// the given block number for a given receiver. Invariants:
492	/// - The inner `Vec<ParaId>` is never empty.
493	/// - The inner `Vec<ParaId>` cannot store two same `ParaId`.
494	/// - The outer vector is sorted ascending by block number and cannot store two items with the
495	///   same block number.
496	#[pallet::storage]
497	pub type HrmpChannelDigests<T: Config> =
498		StorageMap<_, Twox64Concat, ParaId, Vec<(BlockNumberFor<T>, Vec<ParaId>)>, ValueQuery>;
499
500	/// Preopen the given HRMP channels.
501	///
502	/// The values in the tuple corresponds to
503	/// `(sender, recipient, max_capacity, max_message_size)`, i.e. similar to `init_open_channel`.
504	/// In fact, the initialization is performed as if the `init_open_channel` and
505	/// `accept_open_channel` were called with the respective parameters and the session change take
506	///  place.
507	///
508	/// As such, each channel initializer should satisfy the same constraints, namely:
509	///
510	/// 1. `max_capacity` and `max_message_size` should be within the limits set by the
511	///    configuration pallet.
512	/// 2. `sender` and `recipient` must be valid paras.
513	#[pallet::genesis_config]
514	#[derive(DefaultNoBound)]
515	pub struct GenesisConfig<T: Config> {
516		#[serde(skip)]
517		_config: core::marker::PhantomData<T>,
518		preopen_hrmp_channels: Vec<(ParaId, ParaId, u32, u32)>,
519	}
520
521	#[pallet::genesis_build]
522	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
523		fn build(&self) {
524			initialize_storage::<T>(&self.preopen_hrmp_channels);
525		}
526	}
527
528	#[pallet::call]
529	impl<T: Config> Pallet<T> {
530		/// Initiate opening a channel from a parachain to a given recipient with given channel
531		/// parameters.
532		///
533		/// - `proposed_max_capacity` - specifies how many messages can be in the channel at once.
534		/// - `proposed_max_message_size` - specifies the maximum size of the messages.
535		///
536		/// These numbers are a subject to the relay-chain configuration limits.
537		///
538		/// The channel can be opened only after the recipient confirms it and only on a session
539		/// change.
540		///
541		/// If the deposit provider answers later, the request is recorded once it does. Until then,
542		/// other deposit requests for the sender's side of the channel are refused.
543		#[pallet::call_index(0)]
544		#[pallet::weight(
545			<T as Config>::WeightInfo::hrmp_init_open_channel()
546				.saturating_add(T::DepositProvider::weight_of_try_set_deposit())
547		)]
548		pub fn hrmp_init_open_channel(
549			origin: OriginFor<T>,
550			recipient: ParaId,
551			proposed_max_capacity: u32,
552			proposed_max_message_size: u32,
553		) -> DispatchResult {
554			let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
555			// `OpenChannelRequested` is emitted once the deposit is set and the request recorded.
556			Self::init_open_channel(
557				origin,
558				recipient,
559				proposed_max_capacity,
560				proposed_max_message_size,
561			)
562		}
563
564		/// Accept a pending open channel request from the given sender.
565		///
566		/// The channel will be opened only on the next session boundary.
567		///
568		/// If the deposit provider answers later, the request is confirmed once it does. Until
569		/// then, other deposit requests for the recipient's side of the channel are refused.
570		#[pallet::call_index(1)]
571		#[pallet::weight(
572			<T as Config>::WeightInfo::hrmp_accept_open_channel()
573				.saturating_add(T::DepositProvider::weight_of_try_set_deposit())
574		)]
575		pub fn hrmp_accept_open_channel(origin: OriginFor<T>, sender: ParaId) -> DispatchResult {
576			let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
577			// `OpenChannelAccepted` is emitted once the deposit is set and the request confirmed.
578			Self::accept_open_channel(origin, sender)
579		}
580
581		/// Initiate unilateral closing of a channel. The origin must be either the sender or the
582		/// recipient in the channel being closed.
583		///
584		/// The closure can only happen on a session change.
585		#[pallet::call_index(2)]
586		#[pallet::weight(<T as Config>::WeightInfo::hrmp_close_channel())]
587		pub fn hrmp_close_channel(
588			origin: OriginFor<T>,
589			channel_id: HrmpChannelId,
590		) -> DispatchResult {
591			let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
592			Self::close_channel(origin, channel_id.clone())?;
593			Self::deposit_event(Event::ChannelClosed { by_parachain: origin, channel_id });
594			Ok(())
595		}
596
597		/// This extrinsic triggers the cleanup of all the HRMP storage items that a para may have.
598		/// Normally this happens once per session, but this allows you to trigger the cleanup
599		/// immediately for a specific parachain.
600		///
601		/// Number of inbound and outbound channels for `para` must be provided as witness data.
602		///
603		/// Origin must be the `ChannelManager`.
604		#[pallet::call_index(3)]
605		#[pallet::weight(<T as Config>::WeightInfo::force_clean_hrmp(*num_inbound, *num_outbound))]
606		pub fn force_clean_hrmp(
607			origin: OriginFor<T>,
608			para: ParaId,
609			num_inbound: u32,
610			num_outbound: u32,
611		) -> DispatchResult {
612			T::ChannelManager::ensure_origin(origin)?;
613
614			ensure!(
615				HrmpIngressChannelsIndex::<T>::decode_len(para).unwrap_or_default() <=
616					num_inbound as usize,
617				Error::<T>::WrongWitness
618			);
619			ensure!(
620				HrmpEgressChannelsIndex::<T>::decode_len(para).unwrap_or_default() <=
621					num_outbound as usize,
622				Error::<T>::WrongWitness
623			);
624
625			Self::clean_hrmp_after_outgoing(&para);
626			Ok(())
627		}
628
629		/// Force process HRMP open channel requests.
630		///
631		/// If there are pending HRMP open channel requests, you can use this function to process
632		/// all of those requests immediately.
633		///
634		/// Total number of opening channels must be provided as witness data.
635		///
636		/// Origin must be the `ChannelManager`.
637		#[pallet::call_index(4)]
638		#[pallet::weight(<T as Config>::WeightInfo::force_process_hrmp_open(*channels))]
639		pub fn force_process_hrmp_open(origin: OriginFor<T>, channels: u32) -> DispatchResult {
640			T::ChannelManager::ensure_origin(origin)?;
641
642			ensure!(
643				HrmpOpenChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32 <=
644					channels,
645				Error::<T>::WrongWitness
646			);
647
648			let host_config = configuration::ActiveConfig::<T>::get();
649			Self::process_hrmp_open_channel_requests(&host_config);
650			Ok(())
651		}
652
653		/// Force process HRMP close channel requests.
654		///
655		/// If there are pending HRMP close channel requests, you can use this function to process
656		/// all of those requests immediately.
657		///
658		/// Total number of closing channels must be provided as witness data.
659		///
660		/// Origin must be the `ChannelManager`.
661		#[pallet::call_index(5)]
662		#[pallet::weight(<T as Config>::WeightInfo::force_process_hrmp_close(*channels))]
663		pub fn force_process_hrmp_close(origin: OriginFor<T>, channels: u32) -> DispatchResult {
664			T::ChannelManager::ensure_origin(origin)?;
665
666			ensure!(
667				HrmpCloseChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32 <=
668					channels,
669				Error::<T>::WrongWitness
670			);
671
672			Self::process_hrmp_close_channel_requests();
673			Ok(())
674		}
675
676		/// This cancels a pending open channel request. It can be canceled by either of the sender
677		/// or the recipient for that request. The origin must be either of those.
678		///
679		/// The cancellation happens immediately. It is not possible to cancel the request if it is
680		/// already accepted.
681		///
682		/// Total number of open requests (i.e. `HrmpOpenChannelRequestsList`) must be provided as
683		/// witness data.
684		#[pallet::call_index(6)]
685		#[pallet::weight(
686			<T as Config>::WeightInfo::hrmp_cancel_open_request(*open_requests)
687				.saturating_add(T::DepositProvider::weight_of_try_set_deposit())
688		)]
689		pub fn hrmp_cancel_open_request(
690			origin: OriginFor<T>,
691			channel_id: HrmpChannelId,
692			open_requests: u32,
693		) -> DispatchResult {
694			let origin = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
695			ensure!(
696				HrmpOpenChannelRequestsList::<T>::decode_len().unwrap_or_default() as u32 <=
697					open_requests,
698				Error::<T>::WrongWitness
699			);
700			Self::cancel_open_request(origin, channel_id.clone())?;
701			Self::deposit_event(Event::OpenChannelCanceled { by_parachain: origin, channel_id });
702			Ok(())
703		}
704
705		/// Open a channel from a `sender` to a `recipient` `ParaId`. Although opened by governance,
706		/// the `max_capacity` and `max_message_size` are still subject to the Relay Chain's
707		/// configured limits.
708		///
709		/// Expected use is when one (and only one) of the `ParaId`s involved in the channel is
710		/// governed by the system, e.g. a system parachain.
711		///
712		/// Origin must be the `ChannelManager`.
713		///
714		/// If the deposit provider answers later, the request is recorded and confirmed once it
715		/// does. Until then, other deposit requests for both sides of the channel are refused.
716		#[pallet::call_index(7)]
717		#[pallet::weight(
718			// A cancel and an init_and_accept_open each ask the provider.
719			<T as Config>::WeightInfo::force_open_hrmp_channel(1)
720				.saturating_add(T::DepositProvider::weight_of_try_set_deposit().saturating_mul(2))
721		)]
722		pub fn force_open_hrmp_channel(
723			origin: OriginFor<T>,
724			sender: ParaId,
725			recipient: ParaId,
726			max_capacity: u32,
727			max_message_size: u32,
728		) -> DispatchResultWithPostInfo {
729			T::ChannelManager::ensure_origin(origin)?;
730
731			// Guard against a common footgun where someone makes a channel request to a system
732			// parachain and then makes a proposal to open the channel via governance, which fails
733			// because `init_and_accept_open_channel` fails if there is an existing request. This
734			// check will clear an existing request such that `init_and_accept_open_channel` should
735			// otherwise succeed.
736			let channel_id = HrmpChannelId { sender, recipient };
737			let cancel_request: u32 =
738				if let Some(_open_channel) = HrmpOpenChannelRequests::<T>::get(&channel_id) {
739					Self::cancel_open_request(sender, channel_id)?;
740					1
741				} else {
742					0
743				};
744
745			// Now we open the channel, requested and accepted at once. Deposits are only free with
746			// or amongst the system. `HrmpChannelForceOpened` is emitted once both are taken.
747			Self::init_and_accept_open_channel(sender, recipient, max_capacity, max_message_size)?;
748
749			Ok(Some(<T as Config>::WeightInfo::force_open_hrmp_channel(cancel_request)).into())
750		}
751
752		/// Establish an HRMP channel between two system chains. If the channel does not already
753		/// exist, the transaction fees will be refunded to the caller. The system does not take
754		/// deposits for channels between system chains, and automatically sets the message number
755		/// and size limits to the maximum allowed by the network's configuration.
756		///
757		/// Arguments:
758		///
759		/// - `sender`: A system chain, `ParaId`.
760		/// - `recipient`: A system chain, `ParaId`.
761		///
762		/// Any signed origin can call this function, but _both_ inputs MUST be system chains. If
763		/// the channel does not exist yet, there is no fee.
764		#[pallet::call_index(8)]
765		#[pallet::weight(<T as Config>::WeightInfo::establish_system_channel())]
766		pub fn establish_system_channel(
767			origin: OriginFor<T>,
768			sender: ParaId,
769			recipient: ParaId,
770		) -> DispatchResultWithPostInfo {
771			let _caller = ensure_signed(origin)?;
772
773			// both chains must be system
774			ensure!(
775				sender.is_system() && recipient.is_system(),
776				Error::<T>::ChannelCreationNotAuthorized
777			);
778
779			let config = configuration::ActiveConfig::<T>::get();
780			let max_message_size = config.hrmp_channel_max_message_size;
781			let max_capacity = config.hrmp_channel_max_capacity;
782
783			Self::init_open_channel(sender, recipient, max_capacity, max_message_size)?;
784			Self::accept_open_channel(recipient, sender)?;
785
786			Self::deposit_event(Event::HrmpSystemChannelOpened {
787				sender,
788				recipient,
789				proposed_max_capacity: max_capacity,
790				proposed_max_message_size: max_message_size,
791			});
792
793			Ok(Pays::No.into())
794		}
795
796		/// Update the deposits held for an HRMP channel to the latest `Configuration`. Channels
797		/// with system chains do not require a deposit.
798		///
799		/// Arguments:
800		///
801		/// - `sender`: A chain, `ParaId`.
802		/// - `recipient`: A chain, `ParaId`.
803		///
804		/// Any signed origin can call this function.
805		///
806		/// If the deposit provider answers later, the deposits are recorded once it does. Until
807		/// then, other deposit requests for both sides of the channel are refused.
808		#[pallet::call_index(9)]
809		#[pallet::weight(
810			<T as Config>::WeightInfo::poke_channel_deposits()
811				.saturating_add(T::DepositProvider::weight_of_try_set_deposit())
812		)]
813		pub fn poke_channel_deposits(
814			origin: OriginFor<T>,
815			sender: ParaId,
816			recipient: ParaId,
817		) -> DispatchResult {
818			let _caller = ensure_signed(origin)?;
819
820			let channel_id = HrmpChannelId { sender, recipient };
821			let channel = HrmpChannels::<T>::get(&channel_id)
822				.ok_or(Error::<T>::OpenHrmpChannelDoesntExist)?;
823
824			let config = configuration::ActiveConfig::<T>::get();
825			let (sender_deposit, recipient_deposit) = Self::required_deposits(&channel_id, &config);
826			// nothing to update
827			if (channel.sender_deposit, channel.recipient_deposit) ==
828				(sender_deposit, recipient_deposit)
829			{
830				Self::deposit_event(Event::OpenChannelDepositsUpdated { sender, recipient });
831				return Ok(());
832			}
833
834			// `OpenChannelDepositsUpdated` is emitted once the deposits are set and recorded.
835			Self::set_deposit(DepositChangeRequest {
836				channel_id,
837				sender: Some(DepositChange {
838					current: channel.sender_deposit,
839					target: sender_deposit,
840				}),
841				recipient: Some(DepositChange {
842					current: channel.recipient_deposit,
843					target: recipient_deposit,
844				}),
845				action: DepositAction::PokeChannelDeposits,
846			})
847		}
848
849		/// Establish a bidirectional HRMP channel between a parachain and a system chain.
850		///
851		/// Arguments:
852		///
853		/// - `target_system_chain`: A system chain, `ParaId`.
854		///
855		/// The origin needs to be the parachain origin.
856		#[pallet::call_index(10)]
857		#[pallet::weight(<T as Config>::WeightInfo::establish_channel_with_system())]
858		pub fn establish_channel_with_system(
859			origin: OriginFor<T>,
860			target_system_chain: ParaId,
861		) -> DispatchResultWithPostInfo {
862			let sender = ensure_parachain(<T as Config>::RuntimeOrigin::from(origin))?;
863
864			ensure!(target_system_chain.is_system(), Error::<T>::ChannelCreationNotAuthorized);
865
866			let (max_message_size, max_capacity) =
867				T::DefaultChannelSizeAndCapacityWithSystem::get();
868
869			// create bidirectional channel
870			Self::init_open_channel(sender, target_system_chain, max_capacity, max_message_size)?;
871			Self::accept_open_channel(target_system_chain, sender)?;
872
873			Self::init_open_channel(target_system_chain, sender, max_capacity, max_message_size)?;
874			Self::accept_open_channel(sender, target_system_chain)?;
875
876			Self::deposit_event(Event::HrmpSystemChannelOpened {
877				sender,
878				recipient: target_system_chain,
879				proposed_max_capacity: max_capacity,
880				proposed_max_message_size: max_message_size,
881			});
882
883			Self::deposit_event(Event::HrmpSystemChannelOpened {
884				sender: target_system_chain,
885				recipient: sender,
886				proposed_max_capacity: max_capacity,
887				proposed_max_message_size: max_message_size,
888			});
889
890			Ok(Pays::No.into())
891		}
892	}
893}
894
895fn initialize_storage<T: Config>(preopen_hrmp_channels: &[(ParaId, ParaId, u32, u32)]) {
896	let host_config = configuration::ActiveConfig::<T>::get();
897	for &(sender, recipient, max_capacity, max_message_size) in preopen_hrmp_channels {
898		if let Err(err) =
899			preopen_hrmp_channel::<T>(sender, recipient, max_capacity, max_message_size)
900		{
901			panic!("failed to initialize the genesis storage: {:?}", err);
902		}
903	}
904	Pallet::<T>::process_hrmp_open_channel_requests(&host_config);
905}
906
907fn preopen_hrmp_channel<T: Config>(
908	sender: ParaId,
909	recipient: ParaId,
910	max_capacity: u32,
911	max_message_size: u32,
912) -> DispatchResult {
913	Pallet::<T>::init_and_accept_open_channel(sender, recipient, max_capacity, max_message_size)
914}
915
916/// Routines and getters related to HRMP.
917impl<T: Config> Pallet<T> {
918	/// Block initialization logic, called by initializer.
919	pub(crate) fn initializer_initialize(_now: BlockNumberFor<T>) -> Weight {
920		Weight::zero()
921	}
922
923	/// Block finalization logic, called by initializer.
924	pub(crate) fn initializer_finalize() {}
925
926	/// Called by the initializer to note that a new session has started.
927	pub(crate) fn initializer_on_new_session(
928		notification: &initializer::SessionChangeNotification<BlockNumberFor<T>>,
929		outgoing_paras: &[ParaId],
930	) -> Weight {
931		let (w1, released_outgoing) =
932			Self::perform_outgoing_para_cleanup(&notification.prev_config, outgoing_paras);
933		let released_open = Self::process_hrmp_open_channel_requests(&notification.prev_config);
934		let released_close = Self::process_hrmp_close_channel_requests();
935		let releases =
936			released_outgoing.saturating_add(released_open).saturating_add(released_close);
937		w1.saturating_add(<T as Config>::WeightInfo::force_process_hrmp_open(
938			outgoing_paras.len() as u32
939		))
940		.saturating_add(<T as Config>::WeightInfo::force_process_hrmp_close(
941			outgoing_paras.len() as u32
942		))
943		.saturating_add(
944			T::DepositProvider::weight_of_try_set_deposit().saturating_mul(releases.into()),
945		)
946	}
947
948	/// Iterate over all paras that were noted for offboarding and remove all the data
949	/// associated with them.
950	///
951	/// Returns the weight, and how many times deposits were given back.
952	fn perform_outgoing_para_cleanup(
953		config: &HostConfiguration<BlockNumberFor<T>>,
954		outgoing: &[ParaId],
955	) -> (Weight, u32) {
956		let (mut w, mut releases) = Self::clean_open_channel_requests(config, outgoing);
957		for outgoing_para in outgoing {
958			// we need a few extra bits of data to weigh this -- all of this is read internally
959			// anyways, so no overhead.
960			let ingress_count =
961				HrmpIngressChannelsIndex::<T>::decode_len(outgoing_para).unwrap_or_default() as u32;
962			let egress_count =
963				HrmpEgressChannelsIndex::<T>::decode_len(outgoing_para).unwrap_or_default() as u32;
964
965			Self::clean_hrmp_after_outgoing(outgoing_para);
966
967			w = w.saturating_add(<T as Config>::WeightInfo::force_clean_hrmp(
968				ingress_count,
969				egress_count,
970			));
971			releases = releases.saturating_add(ingress_count).saturating_add(egress_count);
972		}
973		(w, releases)
974	}
975
976	// Go over the HRMP open channel requests and remove all in which offboarding paras participate.
977	//
978	// This also gives back the deposits of both sides, and returns the weight and how many
979	// requests were removed.
980	pub(crate) fn clean_open_channel_requests(
981		config: &HostConfiguration<BlockNumberFor<T>>,
982		outgoing: &[ParaId],
983	) -> (Weight, u32) {
984		// First collect all the channel ids of the open requests in which there is at least one
985		// party presents in the outgoing list.
986		//
987		// Both the open channel request list and outgoing list are expected to be small enough.
988		// In the most common case there will be only single outgoing para.
989		let open_channel_reqs = HrmpOpenChannelRequestsList::<T>::get();
990		let (go, stay): (Vec<HrmpChannelId>, Vec<HrmpChannelId>) = open_channel_reqs
991			.into_iter()
992			.partition(|req_id| outgoing.iter().any(|id| req_id.is_participant(*id)));
993		HrmpOpenChannelRequestsList::<T>::put(stay);
994		let removed = go.len() as u32;
995
996		// Then iterate over all open requests to be removed, pull them out of the set and perform
997		// the refunds.
998		for req_id in go {
999			let req_data = match HrmpOpenChannelRequests::<T>::take(&req_id) {
1000				Some(req_data) => req_data,
1001				None => {
1002					// Can't normally happen but no need to panic.
1003					continue;
1004				},
1005			};
1006
1007			// Return the deposit of the sender. An offboarding sender gets it back too, the same
1008			// way `close_hrmp_channel` returns the deposits of its channels.
1009			let sender_deposit = Some(req_data.sender_deposit);
1010
1011			// If the request was confirmed, then it means it was confirmed in the finished session.
1012			// Therefore, the config's recipient deposit represents the actual value of the
1013			// deposit. None is taken for a channel with or amongst the system.
1014			let recipient_deposit = if req_data.confirmed {
1015				Self::decrease_accepted_channel_request_count(req_id.recipient);
1016				Some(Self::required_deposits(&req_id, config).1)
1017			} else {
1018				None
1019			};
1020			Self::release_deposits(&req_id, sender_deposit, recipient_deposit);
1021
1022			// The request no longer counts against the sender's outbound limit. An outgoing
1023			// sender's counter is removed altogether by `clean_hrmp_after_outgoing`.
1024			if !outgoing.contains(&req_id.sender) {
1025				Self::decrease_open_channel_request_count(req_id.sender);
1026			}
1027		}
1028
1029		(<T as Config>::WeightInfo::clean_open_channel_requests(outgoing.len() as u32), removed)
1030	}
1031
1032	/// Remove all storage entries associated with the given para.
1033	fn clean_hrmp_after_outgoing(outgoing_para: &ParaId) {
1034		HrmpOpenChannelRequestCount::<T>::remove(outgoing_para);
1035		HrmpAcceptedChannelRequestCount::<T>::remove(outgoing_para);
1036
1037		let ingress = HrmpIngressChannelsIndex::<T>::take(outgoing_para)
1038			.into_iter()
1039			.map(|sender| HrmpChannelId { sender, recipient: *outgoing_para });
1040		let egress = HrmpEgressChannelsIndex::<T>::take(outgoing_para)
1041			.into_iter()
1042			.map(|recipient| HrmpChannelId { sender: *outgoing_para, recipient });
1043		let mut to_close = ingress.chain(egress).collect::<Vec<_>>();
1044		to_close.sort();
1045		to_close.dedup();
1046
1047		for channel in to_close {
1048			Self::close_hrmp_channel(&channel);
1049		}
1050	}
1051
1052	/// Iterate over all open channel requests and:
1053	///
1054	/// - prune the stale requests
1055	/// - enact the confirmed requests
1056	///
1057	/// Returns how many times deposits were given back.
1058	fn process_hrmp_open_channel_requests(config: &HostConfiguration<BlockNumberFor<T>>) -> u32 {
1059		let mut open_req_channels = HrmpOpenChannelRequestsList::<T>::get();
1060		if open_req_channels.is_empty() {
1061			return 0;
1062		}
1063		let mut releases = 0u32;
1064
1065		// iterate the vector starting from the end making our way to the beginning. This way we
1066		// can leverage `swap_remove` to efficiently remove an item during iteration.
1067		let mut idx = open_req_channels.len();
1068		loop {
1069			// bail if we've iterated over all items.
1070			if idx == 0 {
1071				break;
1072			}
1073
1074			idx -= 1;
1075			let channel_id = open_req_channels[idx].clone();
1076			let request = HrmpOpenChannelRequests::<T>::get(&channel_id).expect(
1077				"can't be `None` due to the invariant that the list contains the same items as the set; qed",
1078			);
1079
1080			let sender_deposit = request.sender_deposit;
1081			let (_, recipient_deposit) = Self::required_deposits(&channel_id, config);
1082
1083			if request.confirmed {
1084				if paras::Pallet::<T>::is_valid_para(channel_id.sender) &&
1085					paras::Pallet::<T>::is_valid_para(channel_id.recipient)
1086				{
1087					HrmpChannels::<T>::insert(
1088						&channel_id,
1089						HrmpChannel {
1090							sender_deposit,
1091							recipient_deposit,
1092							max_capacity: request.max_capacity,
1093							max_total_size: request.max_total_size,
1094							max_message_size: request.max_message_size,
1095							msg_count: 0,
1096							total_size: 0,
1097							mqc_head: None,
1098						},
1099					);
1100
1101					HrmpIngressChannelsIndex::<T>::mutate(&channel_id.recipient, |v| {
1102						if let Err(i) = v.binary_search(&channel_id.sender) {
1103							v.insert(i, channel_id.sender);
1104						}
1105					});
1106					HrmpEgressChannelsIndex::<T>::mutate(&channel_id.sender, |v| {
1107						if let Err(i) = v.binary_search(&channel_id.recipient) {
1108							v.insert(i, channel_id.recipient);
1109						}
1110					});
1111				} else {
1112					// The channel is not created, so the deposits taken for it are given back.
1113					Self::release_deposits(
1114						&channel_id,
1115						Some(sender_deposit),
1116						Some(recipient_deposit),
1117					);
1118					releases = releases.saturating_add(1);
1119				}
1120
1121				Self::decrease_open_channel_request_count(channel_id.sender);
1122				Self::decrease_accepted_channel_request_count(channel_id.recipient);
1123
1124				let _ = open_req_channels.swap_remove(idx);
1125				HrmpOpenChannelRequests::<T>::remove(&channel_id);
1126			}
1127		}
1128
1129		HrmpOpenChannelRequestsList::<T>::put(open_req_channels);
1130		releases
1131	}
1132
1133	/// Iterate over all close channel requests unconditionally closing the channels.
1134	///
1135	/// Returns how many channels were closed, each giving back its deposits.
1136	fn process_hrmp_close_channel_requests() -> u32 {
1137		let close_reqs = HrmpCloseChannelRequestsList::<T>::take();
1138		let closed = close_reqs.len() as u32;
1139		for condemned_ch_id in close_reqs {
1140			HrmpCloseChannelRequests::<T>::remove(&condemned_ch_id);
1141			Self::close_hrmp_channel(&condemned_ch_id);
1142		}
1143		closed
1144	}
1145
1146	/// Close and remove the designated HRMP channel.
1147	///
1148	/// This includes returning the deposits.
1149	///
1150	/// This function is idempotent, meaning that after the first application it should have no
1151	/// effect (i.e. it won't return the deposits twice).
1152	fn close_hrmp_channel(channel_id: &HrmpChannelId) {
1153		if let Some(HrmpChannel { sender_deposit, recipient_deposit, .. }) =
1154			HrmpChannels::<T>::take(channel_id)
1155		{
1156			Self::release_deposits(channel_id, Some(sender_deposit), Some(recipient_deposit));
1157		}
1158
1159		HrmpChannelContents::<T>::remove(channel_id);
1160
1161		HrmpEgressChannelsIndex::<T>::mutate(&channel_id.sender, |v| {
1162			if let Ok(i) = v.binary_search(&channel_id.recipient) {
1163				v.remove(i);
1164			}
1165		});
1166		HrmpIngressChannelsIndex::<T>::mutate(&channel_id.recipient, |v| {
1167			if let Ok(i) = v.binary_search(&channel_id.sender) {
1168				v.remove(i);
1169			}
1170		});
1171	}
1172
1173	/// Check that the candidate of the given recipient controls the HRMP watermark properly.
1174	pub(crate) fn check_hrmp_watermark(
1175		recipient: ParaId,
1176		relay_chain_parent_number: BlockNumberFor<T>,
1177		new_hrmp_watermark: BlockNumberFor<T>,
1178	) -> Result<(), HrmpWatermarkAcceptanceErr<BlockNumberFor<T>>> {
1179		// First, check where the watermark CANNOT legally land.
1180		//
1181		// (a) For ensuring that messages are eventually processed, we require each parablock's
1182		//     watermark to be greater than the last one. The exception to this is if the previous
1183		//     watermark was already equal to the current relay-parent number.
1184		//
1185		// (b) However, a parachain cannot read into "the future", therefore the watermark should
1186		//     not be greater than the relay-chain context block which the parablock refers to.
1187		if new_hrmp_watermark == relay_chain_parent_number {
1188			return Ok(());
1189		}
1190
1191		if new_hrmp_watermark > relay_chain_parent_number {
1192			return Err(HrmpWatermarkAcceptanceErr::AheadRelayParent {
1193				new_watermark: new_hrmp_watermark,
1194				relay_chain_parent_number,
1195			});
1196		}
1197
1198		if let Some(last_watermark) = HrmpWatermarks::<T>::get(&recipient) {
1199			if new_hrmp_watermark < last_watermark {
1200				return Err(HrmpWatermarkAcceptanceErr::AdvancementRule {
1201					new_watermark: new_hrmp_watermark,
1202					last_watermark,
1203				});
1204			}
1205
1206			if new_hrmp_watermark == last_watermark {
1207				return Ok(());
1208			}
1209		}
1210
1211		// Second, check where the watermark CAN land. It's one of the following:
1212		//
1213		// (a) The relay parent block number (checked above).
1214		// (b) A relay-chain block in which this para received at least one message (checked here)
1215		let digest = HrmpChannelDigests::<T>::get(&recipient);
1216		if !digest
1217			.binary_search_by_key(&new_hrmp_watermark, |(block_no, _)| *block_no)
1218			.is_ok()
1219		{
1220			return Err(HrmpWatermarkAcceptanceErr::LandsOnBlockWithNoMessages {
1221				new_watermark: new_hrmp_watermark,
1222			});
1223		}
1224		Ok(())
1225	}
1226
1227	/// Returns HRMP watermarks of previously sent messages to a given para.
1228	pub(crate) fn valid_watermarks(recipient: ParaId) -> Vec<BlockNumberFor<T>> {
1229		let mut valid_watermarks: Vec<_> = HrmpChannelDigests::<T>::get(&recipient)
1230			.into_iter()
1231			.map(|(block_no, _)| block_no)
1232			.collect();
1233
1234		// The current watermark will remain valid until updated.
1235		if let Some(last_watermark) = HrmpWatermarks::<T>::get(&recipient) {
1236			if valid_watermarks.first().map_or(false, |w| w > &last_watermark) {
1237				valid_watermarks.insert(0, last_watermark);
1238			}
1239		}
1240
1241		valid_watermarks
1242	}
1243
1244	pub(crate) fn check_outbound_hrmp(
1245		config: &HostConfiguration<BlockNumberFor<T>>,
1246		sender: ParaId,
1247		out_hrmp_msgs: &[OutboundHrmpMessage<ParaId>],
1248	) -> Result<(), OutboundHrmpAcceptanceErr> {
1249		if out_hrmp_msgs.len() as u32 > config.hrmp_max_message_num_per_candidate {
1250			return Err(OutboundHrmpAcceptanceErr::MoreMessagesThanPermitted {
1251				sent: out_hrmp_msgs.len() as u32,
1252				permitted: config.hrmp_max_message_num_per_candidate,
1253			});
1254		}
1255
1256		let mut last_recipient = None::<ParaId>;
1257
1258		for (idx, out_msg) in
1259			out_hrmp_msgs.iter().enumerate().map(|(idx, out_msg)| (idx as u32, out_msg))
1260		{
1261			match last_recipient {
1262				// the messages must be sorted in ascending order and there must be no two messages
1263				// sent to the same recipient. Thus we can check that every recipient is strictly
1264				// greater than the previous one.
1265				Some(last_recipient) if out_msg.recipient <= last_recipient => {
1266					return Err(OutboundHrmpAcceptanceErr::NotSorted { idx })
1267				},
1268				_ => last_recipient = Some(out_msg.recipient),
1269			}
1270
1271			let channel_id = HrmpChannelId { sender, recipient: out_msg.recipient };
1272
1273			let channel = match HrmpChannels::<T>::get(&channel_id) {
1274				Some(channel) => channel,
1275				None => return Err(OutboundHrmpAcceptanceErr::NoSuchChannel { channel_id, idx }),
1276			};
1277
1278			let msg_size = out_msg.data.len() as u32;
1279			if msg_size > channel.max_message_size {
1280				return Err(OutboundHrmpAcceptanceErr::MaxMessageSizeExceeded {
1281					idx,
1282					msg_size,
1283					max_size: channel.max_message_size,
1284				});
1285			}
1286
1287			let new_total_size = channel.total_size + out_msg.data.len() as u32;
1288			if new_total_size > channel.max_total_size {
1289				return Err(OutboundHrmpAcceptanceErr::TotalSizeExceeded {
1290					idx,
1291					total_size: new_total_size,
1292					limit: channel.max_total_size,
1293				});
1294			}
1295
1296			let new_msg_count = channel.msg_count + 1;
1297			if new_msg_count > channel.max_capacity {
1298				return Err(OutboundHrmpAcceptanceErr::CapacityExceeded {
1299					idx,
1300					count: new_msg_count,
1301					limit: channel.max_capacity,
1302				});
1303			}
1304		}
1305
1306		Ok(())
1307	}
1308
1309	/// Returns remaining outbound channels capacity in messages and in bytes per recipient para.
1310	pub(crate) fn outbound_remaining_capacity(sender: ParaId) -> Vec<(ParaId, (u32, u32))> {
1311		let recipients = HrmpEgressChannelsIndex::<T>::get(&sender);
1312		let mut remaining = Vec::with_capacity(recipients.len());
1313
1314		for recipient in recipients {
1315			let Some(channel) = HrmpChannels::<T>::get(&HrmpChannelId { sender, recipient }) else {
1316				continue;
1317			};
1318			remaining.push((
1319				recipient,
1320				(
1321					channel.max_capacity - channel.msg_count,
1322					channel.max_total_size - channel.total_size,
1323				),
1324			));
1325		}
1326
1327		remaining
1328	}
1329
1330	pub(crate) fn prune_hrmp(recipient: ParaId, new_hrmp_watermark: BlockNumberFor<T>) {
1331		// sift through the incoming messages digest to collect the paras that sent at least one
1332		// message to this parachain between the old and new watermarks.
1333		let senders = HrmpChannelDigests::<T>::mutate(&recipient, |digest| {
1334			let mut senders = BTreeSet::new();
1335			let mut leftover = Vec::with_capacity(digest.len());
1336			for (block_no, paras_sent_msg) in mem::replace(digest, Vec::new()) {
1337				if block_no <= new_hrmp_watermark {
1338					senders.extend(paras_sent_msg);
1339				} else {
1340					leftover.push((block_no, paras_sent_msg));
1341				}
1342			}
1343			*digest = leftover;
1344			senders
1345		});
1346
1347		// having all senders we can trivially find out the channels which we need to prune.
1348		let channels_to_prune =
1349			senders.into_iter().map(|sender| HrmpChannelId { sender, recipient });
1350		for channel_id in channels_to_prune {
1351			// prune each channel up to the new watermark keeping track how many messages we removed
1352			// and what is the total byte size of them.
1353			let (mut pruned_cnt, mut pruned_size) = (0, 0);
1354
1355			let contents = HrmpChannelContents::<T>::get(&channel_id);
1356			let mut leftover = Vec::with_capacity(contents.len());
1357			for msg in contents {
1358				if msg.sent_at <= new_hrmp_watermark {
1359					pruned_cnt += 1;
1360					pruned_size += msg.data.len();
1361				} else {
1362					leftover.push(msg);
1363				}
1364			}
1365			if !leftover.is_empty() {
1366				HrmpChannelContents::<T>::insert(&channel_id, leftover);
1367			} else {
1368				HrmpChannelContents::<T>::remove(&channel_id);
1369			}
1370
1371			// update the channel metadata.
1372			HrmpChannels::<T>::mutate(&channel_id, |channel| {
1373				if let Some(ref mut channel) = channel {
1374					channel.msg_count -= pruned_cnt as u32;
1375					channel.total_size -= pruned_size as u32;
1376				}
1377			});
1378		}
1379
1380		HrmpWatermarks::<T>::insert(&recipient, new_hrmp_watermark);
1381	}
1382
1383	/// Process the outbound HRMP messages by putting them into the appropriate recipient queues.
1384	pub(crate) fn queue_outbound_hrmp(sender: ParaId, out_hrmp_msgs: HorizontalMessages) {
1385		let now = frame_system::Pallet::<T>::block_number();
1386
1387		for out_msg in out_hrmp_msgs {
1388			let channel_id = HrmpChannelId { sender, recipient: out_msg.recipient };
1389
1390			let mut channel = match HrmpChannels::<T>::get(&channel_id) {
1391				Some(channel) => channel,
1392				None => {
1393					// apparently, that since acceptance of this candidate the recipient was
1394					// offboarded and the channel no longer exists.
1395					continue;
1396				},
1397			};
1398
1399			let inbound = InboundHrmpMessage { sent_at: now, data: out_msg.data };
1400
1401			// book keeping
1402			channel.msg_count += 1;
1403			channel.total_size += inbound.data.len() as u32;
1404
1405			// compute the new MQC head of the channel
1406			let prev_head = channel.mqc_head.unwrap_or(Default::default());
1407			let new_head = BlakeTwo256::hash_of(&(
1408				prev_head,
1409				inbound.sent_at,
1410				T::Hashing::hash_of(&inbound.data),
1411			));
1412			channel.mqc_head = Some(new_head);
1413
1414			HrmpChannels::<T>::insert(&channel_id, channel);
1415			HrmpChannelContents::<T>::append(&channel_id, inbound);
1416
1417			// The digests are sorted in ascending by block number order. There are only two
1418			// possible scenarios here ("the current" is the block of candidate's inclusion):
1419			//
1420			// (a) It's the first time anybody sends a message to this recipient within this block.
1421			//     In this case, the digest vector would be empty or the block number of the latest
1422			//     entry is smaller than the current.
1423			//
1424			// (b) Somebody has already sent a message within the current block. That means that
1425			//     the block number of the latest entry is equal to the current.
1426			//
1427			// Note that having the latest entry greater than the current block number is a logical
1428			// error.
1429			let mut recipient_digest = HrmpChannelDigests::<T>::get(&channel_id.recipient);
1430			if let Some(cur_block_digest) = recipient_digest
1431				.last_mut()
1432				.filter(|(block_no, _)| *block_no == now)
1433				.map(|(_, ref mut d)| d)
1434			{
1435				cur_block_digest.push(sender);
1436			} else {
1437				recipient_digest.push((now, vec![sender]));
1438			}
1439			HrmpChannelDigests::<T>::insert(&channel_id.recipient, recipient_digest);
1440		}
1441	}
1442
1443	/// Initiate opening a channel from a parachain to a given recipient with given channel
1444	/// parameters. If neither chain is part of the system, then a deposit from the `Configuration`
1445	/// will be required for `origin` (the sender) upon opening the request and the `recipient` upon
1446	/// accepting it.
1447	///
1448	/// Basically the same as [`hrmp_init_open_channel`](Pallet::hrmp_init_open_channel) but
1449	/// intended for calling directly from other pallets rather than dispatched.
1450	pub fn init_open_channel(
1451		origin: ParaId,
1452		recipient: ParaId,
1453		proposed_max_capacity: u32,
1454		proposed_max_message_size: u32,
1455	) -> DispatchResult {
1456		let config = configuration::ActiveConfig::<T>::get();
1457		let channel_id = HrmpChannelId { sender: origin, recipient };
1458		Self::check_init_open_channel(
1459			&channel_id,
1460			proposed_max_capacity,
1461			proposed_max_message_size,
1462			&config,
1463		)?;
1464
1465		let (sender_deposit, _) = Self::required_deposits(&channel_id, &config);
1466		Self::set_deposit(DepositChangeRequest {
1467			channel_id,
1468			sender: Some(DepositChange { current: 0, target: sender_deposit }),
1469			recipient: None,
1470			action: DepositAction::InitOpenChannel {
1471				max_capacity: proposed_max_capacity,
1472				max_message_size: proposed_max_message_size,
1473				max_total_size: config.hrmp_channel_max_total_size,
1474			},
1475		})
1476	}
1477
1478	/// Opens a channel as if the sender initiated it and the recipient accepted it, e.g. by
1479	/// governance. Deposits are taken as usual, so they are only free with or amongst the system.
1480	///
1481	/// Both deposits are asked for at once, and the request is recorded and accepted once both
1482	/// are taken, which may be after this returns. It is opened whole or not at all, and emits
1483	/// [`Event::HrmpChannelForceOpened`] once done.
1484	pub fn init_and_accept_open_channel(
1485		sender: ParaId,
1486		recipient: ParaId,
1487		max_capacity: u32,
1488		max_message_size: u32,
1489	) -> DispatchResult {
1490		let config = configuration::ActiveConfig::<T>::get();
1491		let channel_id = HrmpChannelId { sender, recipient };
1492		Self::check_init_open_channel(&channel_id, max_capacity, max_message_size, &config)?;
1493		Self::check_accept_limit(recipient, &config)?;
1494
1495		let (sender_deposit, recipient_deposit) = Self::required_deposits(&channel_id, &config);
1496		Self::set_deposit(DepositChangeRequest {
1497			channel_id,
1498			sender: Some(DepositChange { current: 0, target: sender_deposit }),
1499			recipient: Some(DepositChange { current: 0, target: recipient_deposit }),
1500			action: DepositAction::InitAndAcceptOpenChannel {
1501				max_capacity,
1502				max_message_size,
1503				max_total_size: config.hrmp_channel_max_total_size,
1504			},
1505		})
1506	}
1507
1508	/// Whether `channel_id.sender` may request to open `channel_id` with these limits now.
1509	pub(super) fn check_init_open_channel(
1510		channel_id: &HrmpChannelId,
1511		proposed_max_capacity: u32,
1512		proposed_max_message_size: u32,
1513		config: &HostConfiguration<BlockNumberFor<T>>,
1514	) -> DispatchResult {
1515		let HrmpChannelId { sender: origin, recipient } = *channel_id;
1516		ensure!(origin != recipient, Error::<T>::OpenHrmpChannelToSelf);
1517		// The sender may be offboarded while its deposit is pending.
1518		ensure!(
1519			paras::Pallet::<T>::is_valid_para(origin),
1520			Error::<T>::OpenHrmpChannelInvalidSender
1521		);
1522		ensure!(
1523			paras::Pallet::<T>::is_valid_para(recipient),
1524			Error::<T>::OpenHrmpChannelInvalidRecipient,
1525		);
1526
1527		ensure!(proposed_max_capacity > 0, Error::<T>::OpenHrmpChannelZeroCapacity);
1528		ensure!(
1529			proposed_max_capacity <= config.hrmp_channel_max_capacity,
1530			Error::<T>::OpenHrmpChannelCapacityExceedsLimit,
1531		);
1532		ensure!(proposed_max_message_size > 0, Error::<T>::OpenHrmpChannelZeroMessageSize);
1533		ensure!(
1534			proposed_max_message_size <= config.hrmp_channel_max_message_size,
1535			Error::<T>::OpenHrmpChannelMessageSizeExceedsLimit,
1536		);
1537
1538		ensure!(
1539			HrmpOpenChannelRequests::<T>::get(channel_id).is_none(),
1540			Error::<T>::OpenHrmpChannelAlreadyRequested,
1541		);
1542		ensure!(
1543			HrmpChannels::<T>::get(channel_id).is_none(),
1544			Error::<T>::OpenHrmpChannelAlreadyExists,
1545		);
1546
1547		let egress_cnt = HrmpEgressChannelsIndex::<T>::decode_len(&origin).unwrap_or(0) as u32;
1548		let open_req_cnt = HrmpOpenChannelRequestCount::<T>::get(&origin);
1549		let channel_num_limit = config.hrmp_max_parachain_outbound_channels;
1550		ensure!(
1551			egress_cnt + open_req_cnt < channel_num_limit,
1552			Error::<T>::OpenHrmpChannelLimitExceeded,
1553		);
1554		Ok(())
1555	}
1556
1557	/// Second half of [`Self::init_open_channel`], run once the sender's deposit is taken.
1558	fn finish_init_open_channel(
1559		channel_id: &HrmpChannelId,
1560		sender_deposit: Balance,
1561		max_capacity: u32,
1562		max_message_size: u32,
1563		max_total_size: u32,
1564	) {
1565		let config = configuration::ActiveConfig::<T>::get();
1566		let (sender, recipient) = (channel_id.sender, channel_id.recipient);
1567
1568		HrmpOpenChannelRequestCount::<T>::mutate(&sender, |count| *count += 1);
1569		HrmpOpenChannelRequests::<T>::insert(
1570			channel_id,
1571			HrmpOpenChannelRequest {
1572				confirmed: false,
1573				_age: 0,
1574				sender_deposit,
1575				max_capacity,
1576				max_message_size,
1577				max_total_size,
1578			},
1579		);
1580		HrmpOpenChannelRequestsList::<T>::append(channel_id);
1581
1582		Self::send_to_para(
1583			"init_open_channel",
1584			&config,
1585			recipient,
1586			Self::wrap_notification(|| {
1587				use xcm::opaque::latest::{prelude::*, Xcm};
1588				Xcm(vec![HrmpNewChannelOpenRequest {
1589					sender: sender.into(),
1590					max_capacity,
1591					max_message_size,
1592				}])
1593			}),
1594		);
1595
1596		Self::deposit_event(Event::OpenChannelRequested {
1597			sender,
1598			recipient,
1599			proposed_max_capacity: max_capacity,
1600			proposed_max_message_size: max_message_size,
1601		});
1602	}
1603
1604	/// Accept a pending open channel request from the given sender.
1605	///
1606	/// Basically the same as [`hrmp_accept_open_channel`](Pallet::hrmp_accept_open_channel) but
1607	/// intended for calling directly from other pallets rather than dispatched.
1608	pub fn accept_open_channel(origin: ParaId, sender: ParaId) -> DispatchResult {
1609		let config = configuration::ActiveConfig::<T>::get();
1610		let channel_id = HrmpChannelId { sender, recipient: origin };
1611		let channel_req = Self::check_accept_open_channel(&channel_id, &config)?;
1612
1613		let (_, recipient_deposit) = Self::required_deposits(&channel_id, &config);
1614		Self::set_deposit(DepositChangeRequest {
1615			channel_id,
1616			sender: None,
1617			recipient: Some(DepositChange { current: 0, target: recipient_deposit }),
1618			action: DepositAction::AcceptOpenChannel {
1619				max_capacity: channel_req.max_capacity,
1620				max_message_size: channel_req.max_message_size,
1621			},
1622		})
1623	}
1624
1625	/// Whether `channel_id.recipient` may accept the open request of `channel_id` now. Returns
1626	/// the request.
1627	pub(super) fn check_accept_open_channel(
1628		channel_id: &HrmpChannelId,
1629		config: &HostConfiguration<BlockNumberFor<T>>,
1630	) -> Result<HrmpOpenChannelRequest, DispatchError> {
1631		let channel_req = HrmpOpenChannelRequests::<T>::get(channel_id)
1632			.ok_or(Error::<T>::AcceptHrmpChannelDoesntExist)?;
1633		ensure!(!channel_req.confirmed, Error::<T>::AcceptHrmpChannelAlreadyConfirmed);
1634		Self::check_accept_limit(channel_id.recipient, config)?;
1635		Ok(channel_req)
1636	}
1637
1638	/// Whether `origin` may accept one more inbound channel now.
1639	pub(super) fn check_accept_limit(
1640		origin: ParaId,
1641		config: &HostConfiguration<BlockNumberFor<T>>,
1642	) -> DispatchResult {
1643		// check if by accepting this open channel request, this parachain would exceed the
1644		// number of inbound channels.
1645		let channel_num_limit = config.hrmp_max_parachain_inbound_channels;
1646		let ingress_cnt = HrmpIngressChannelsIndex::<T>::decode_len(&origin).unwrap_or(0) as u32;
1647		let accepted_cnt = HrmpAcceptedChannelRequestCount::<T>::get(&origin);
1648		ensure!(
1649			ingress_cnt + accepted_cnt < channel_num_limit,
1650			Error::<T>::AcceptHrmpChannelLimitExceeded,
1651		);
1652		Ok(())
1653	}
1654
1655	/// Second half of [`Self::accept_open_channel`], run once the recipient's deposit is taken.
1656	fn finish_accept_open_channel(channel_id: &HrmpChannelId) {
1657		let config = configuration::ActiveConfig::<T>::get();
1658		let (sender, recipient) = (channel_id.sender, channel_id.recipient);
1659		let Some(mut channel_req) = HrmpOpenChannelRequests::<T>::get(channel_id) else {
1660			// `check_accept_open_channel` passed, or the request was recorded, right before.
1661			frame_support::defensive!("accepted open request is missing", channel_id);
1662			return;
1663		};
1664
1665		// persist the updated open channel request and then increment the number of accepted
1666		// channels.
1667		channel_req.confirmed = true;
1668		HrmpOpenChannelRequests::<T>::insert(channel_id, channel_req);
1669		HrmpAcceptedChannelRequestCount::<T>::mutate(&recipient, |count| *count += 1);
1670
1671		Self::send_to_para(
1672			"accept_open_channel",
1673			&config,
1674			sender,
1675			Self::wrap_notification(|| {
1676				use xcm::opaque::latest::{prelude::*, Xcm};
1677				Xcm(vec![HrmpChannelAccepted { recipient: recipient.into() }])
1678			}),
1679		);
1680
1681		Self::deposit_event(Event::OpenChannelAccepted { sender, recipient });
1682	}
1683
1684	/// Second half of [`Self::poke_channel_deposits`], run once both deposits are changed.
1685	///
1686	/// Fails if the channel no longer exists or no longer records the deposits the poke set out
1687	/// from. A channel closed meanwhile is refused so that what the poke took is given back: its
1688	/// close gave back what the channel recorded, which is nothing when it was opened free of
1689	/// deposits, while the poke may have taken some by then. A channel closed and opened anew
1690	/// meanwhile records the deposits of its new opening, and the poke took other amounts: it is
1691	/// refused for the same reason.
1692	fn finish_poke_channel_deposits(
1693		channel_id: &HrmpChannelId,
1694		sender: Option<DepositChange>,
1695		recipient: Option<DepositChange>,
1696	) -> DispatchResult {
1697		HrmpChannels::<T>::try_mutate(channel_id, |channel| -> DispatchResult {
1698			let channel = channel.as_mut().ok_or(Error::<T>::OpenHrmpChannelDoesntExist)?;
1699			let unchanged = |change: Option<DepositChange>, recorded: Balance| {
1700				change.is_none_or(|c| c.current == recorded)
1701			};
1702			ensure!(
1703				unchanged(sender, channel.sender_deposit) &&
1704					unchanged(recipient, channel.recipient_deposit),
1705				Error::<T>::ChannelDepositsChanged
1706			);
1707			if let Some(change) = sender {
1708				channel.sender_deposit = change.target;
1709			}
1710			if let Some(change) = recipient {
1711				channel.recipient_deposit = change.target;
1712			}
1713			Ok(())
1714		})?;
1715		let HrmpChannelId { sender, recipient } = *channel_id;
1716		Self::deposit_event(Event::OpenChannelDepositsUpdated { sender, recipient });
1717		Ok(())
1718	}
1719
1720	fn cancel_open_request(origin: ParaId, channel_id: HrmpChannelId) -> DispatchResult {
1721		// check if the origin is allowed to close the channel.
1722		ensure!(channel_id.is_participant(origin), Error::<T>::CancelHrmpOpenChannelUnauthorized);
1723
1724		let open_channel_req = HrmpOpenChannelRequests::<T>::get(&channel_id)
1725			.ok_or(Error::<T>::OpenHrmpChannelDoesntExist)?;
1726		ensure!(!open_channel_req.confirmed, Error::<T>::OpenHrmpChannelAlreadyConfirmed);
1727
1728		// Remove the request by the channel id and sync the accompanying list with the set.
1729		HrmpOpenChannelRequests::<T>::remove(&channel_id);
1730		HrmpOpenChannelRequestsList::<T>::mutate(|open_req_channels| {
1731			if let Some(pos) = open_req_channels.iter().position(|x| x == &channel_id) {
1732				open_req_channels.swap_remove(pos);
1733			}
1734		});
1735
1736		Self::decrease_open_channel_request_count(channel_id.sender);
1737		// Don't decrease `HrmpAcceptedChannelRequestCount` because we don't consider confirmed
1738		// requests here.
1739
1740		// Unreserve the sender's deposit. The recipient could not have left their deposit because
1741		// we ensured that the request is not confirmed.
1742		Self::release_deposits(&channel_id, Some(open_channel_req.sender_deposit), None);
1743
1744		Ok(())
1745	}
1746
1747	fn close_channel(origin: ParaId, channel_id: HrmpChannelId) -> Result<(), Error<T>> {
1748		// check if the origin is allowed to close the channel.
1749		ensure!(channel_id.is_participant(origin), Error::<T>::CloseHrmpChannelUnauthorized);
1750
1751		// check if the channel requested to close does exist.
1752		ensure!(
1753			HrmpChannels::<T>::get(&channel_id).is_some(),
1754			Error::<T>::CloseHrmpChannelDoesntExist,
1755		);
1756
1757		// check that there is no outstanding close request for this channel
1758		ensure!(
1759			HrmpCloseChannelRequests::<T>::get(&channel_id).is_none(),
1760			Error::<T>::CloseHrmpChannelAlreadyUnderway,
1761		);
1762
1763		HrmpCloseChannelRequests::<T>::insert(&channel_id, ());
1764		HrmpCloseChannelRequestsList::<T>::append(channel_id.clone());
1765
1766		let config = configuration::ActiveConfig::<T>::get();
1767		let opposite_party =
1768			if origin == channel_id.sender { channel_id.recipient } else { channel_id.sender };
1769
1770		Self::send_to_para(
1771			"close_channel",
1772			&config,
1773			opposite_party,
1774			Self::wrap_notification(|| {
1775				use xcm::opaque::latest::{prelude::*, Xcm};
1776				Xcm(vec![HrmpChannelClosing {
1777					initiator: origin.into(),
1778					sender: channel_id.sender.into(),
1779					recipient: channel_id.recipient.into(),
1780				}])
1781			}),
1782		);
1783
1784		Ok(())
1785	}
1786
1787	/// Returns the list of MQC heads for the inbound channels of the given recipient para paired
1788	/// with the sender para ids. This vector is sorted ascending by the para id and doesn't contain
1789	/// multiple entries with the same sender.
1790	#[cfg(test)]
1791	fn hrmp_mqc_heads(recipient: ParaId) -> Vec<(ParaId, Hash)> {
1792		let sender_set = HrmpIngressChannelsIndex::<T>::get(&recipient);
1793
1794		// The ingress channels vector is sorted, thus `mqc_heads` is sorted as well.
1795		let mut mqc_heads = Vec::with_capacity(sender_set.len());
1796		for sender in sender_set {
1797			let channel_metadata = HrmpChannels::<T>::get(&HrmpChannelId { sender, recipient });
1798			let mqc_head = channel_metadata
1799				.and_then(|metadata| metadata.mqc_head)
1800				.unwrap_or(Hash::default());
1801			mqc_heads.push((sender, mqc_head));
1802		}
1803
1804		mqc_heads
1805	}
1806
1807	/// Returns contents of all channels addressed to the given recipient. Channels that have no
1808	/// messages in them are also included.
1809	pub(crate) fn inbound_hrmp_channels_contents(
1810		recipient: ParaId,
1811	) -> BTreeMap<ParaId, Vec<InboundHrmpMessage<BlockNumberFor<T>>>> {
1812		let sender_set = HrmpIngressChannelsIndex::<T>::get(&recipient);
1813
1814		let mut inbound_hrmp_channels_contents = BTreeMap::new();
1815		for sender in sender_set {
1816			let channel_contents =
1817				HrmpChannelContents::<T>::get(&HrmpChannelId { sender, recipient });
1818			inbound_hrmp_channels_contents.insert(sender, channel_contents);
1819		}
1820
1821		inbound_hrmp_channels_contents
1822	}
1823}
1824
1825impl<T: Config> Pallet<T> {
1826	/// Decreases the open channel request count for the given sender. If the value reaches zero
1827	/// it is removed completely.
1828	fn decrease_open_channel_request_count(sender: ParaId) {
1829		HrmpOpenChannelRequestCount::<T>::mutate_exists(&sender, |opt_rc| {
1830			*opt_rc = opt_rc.and_then(|rc| match rc.saturating_sub(1) {
1831				0 => None,
1832				n => Some(n),
1833			});
1834		});
1835	}
1836
1837	/// Decreases the accepted channel request count for the given sender. If the value reaches
1838	/// zero it is removed completely.
1839	fn decrease_accepted_channel_request_count(recipient: ParaId) {
1840		HrmpAcceptedChannelRequestCount::<T>::mutate_exists(&recipient, |opt_rc| {
1841			*opt_rc = opt_rc.and_then(|rc| match rc.saturating_sub(1) {
1842				0 => None,
1843				n => Some(n),
1844			});
1845		});
1846	}
1847
1848	#[cfg(any(feature = "runtime-benchmarks", test))]
1849	fn assert_storage_consistency_exhaustive() {
1850		fn assert_is_sorted<T: Ord>(slice: &[T], id: &str) {
1851			assert!(slice.windows(2).all(|xs| xs[0] <= xs[1]), "{} supposed to be sorted", id);
1852		}
1853
1854		let assert_contains_only_onboarded = |paras: Vec<ParaId>, cause: &str| {
1855			for para in paras {
1856				assert!(
1857					crate::paras::Pallet::<T>::is_valid_para(para),
1858					"{}: {:?} para is offboarded",
1859					cause,
1860					para
1861				);
1862			}
1863		};
1864
1865		assert_eq!(
1866			HrmpOpenChannelRequests::<T>::iter().map(|(k, _)| k).collect::<BTreeSet<_>>(),
1867			HrmpOpenChannelRequestsList::<T>::get().into_iter().collect::<BTreeSet<_>>(),
1868		);
1869
1870		// verify that the set of keys in `HrmpOpenChannelRequestCount` corresponds to the set
1871		// of _senders_ in `HrmpOpenChannelRequests`.
1872		//
1873		// having ensured that, we can go ahead and go over all counts and verify that they match.
1874		assert_eq!(
1875			HrmpOpenChannelRequestCount::<T>::iter()
1876				.map(|(k, _)| k)
1877				.collect::<BTreeSet<_>>(),
1878			HrmpOpenChannelRequests::<T>::iter()
1879				.map(|(k, _)| k.sender)
1880				.collect::<BTreeSet<_>>(),
1881		);
1882		for (open_channel_initiator, expected_num) in HrmpOpenChannelRequestCount::<T>::iter() {
1883			let actual_num = HrmpOpenChannelRequests::<T>::iter()
1884				.filter(|(ch, _)| ch.sender == open_channel_initiator)
1885				.count() as u32;
1886			assert_eq!(expected_num, actual_num);
1887		}
1888
1889		// The same as above, but for accepted channel request count. Note that we are interested
1890		// only in confirmed open requests.
1891		assert_eq!(
1892			HrmpAcceptedChannelRequestCount::<T>::iter()
1893				.map(|(k, _)| k)
1894				.collect::<BTreeSet<_>>(),
1895			HrmpOpenChannelRequests::<T>::iter()
1896				.filter(|(_, v)| v.confirmed)
1897				.map(|(k, _)| k.recipient)
1898				.collect::<BTreeSet<_>>(),
1899		);
1900		for (channel_recipient, expected_num) in HrmpAcceptedChannelRequestCount::<T>::iter() {
1901			let actual_num = HrmpOpenChannelRequests::<T>::iter()
1902				.filter(|(ch, v)| ch.recipient == channel_recipient && v.confirmed)
1903				.count() as u32;
1904			assert_eq!(expected_num, actual_num);
1905		}
1906
1907		assert_eq!(
1908			HrmpCloseChannelRequests::<T>::iter().map(|(k, _)| k).collect::<BTreeSet<_>>(),
1909			HrmpCloseChannelRequestsList::<T>::get().into_iter().collect::<BTreeSet<_>>(),
1910		);
1911
1912		// A HRMP watermark can be None for an onboarded parachain. However, an offboarded parachain
1913		// cannot have an HRMP watermark: it should've been cleanup.
1914		assert_contains_only_onboarded(
1915			HrmpWatermarks::<T>::iter().map(|(k, _)| k).collect::<Vec<_>>(),
1916			"HRMP watermarks should contain only onboarded paras",
1917		);
1918
1919		// An entry in `HrmpChannels` indicates that the channel is open. Only open channels can
1920		// have contents.
1921		for (non_empty_channel, contents) in HrmpChannelContents::<T>::iter() {
1922			assert!(HrmpChannels::<T>::contains_key(&non_empty_channel));
1923
1924			// pedantic check: there should be no empty vectors in storage, those should be modeled
1925			// by a removed kv pair.
1926			assert!(!contents.is_empty());
1927		}
1928
1929		// Senders and recipients must be onboarded. Otherwise, all channels associated with them
1930		// are removed.
1931		assert_contains_only_onboarded(
1932			HrmpChannels::<T>::iter()
1933				.flat_map(|(k, _)| vec![k.sender, k.recipient])
1934				.collect::<Vec<_>>(),
1935			"senders and recipients in all channels should be onboarded",
1936		);
1937
1938		// Check the docs for `HrmpIngressChannelsIndex` and `HrmpEgressChannelsIndex` in decl
1939		// storage to get an index what are the channel mappings indexes.
1940		//
1941		// Here, from indexes.
1942		//
1943		// ingress         egress
1944		//
1945		// a -> [x, y]     x -> [a, b]
1946		// b -> [x, z]     y -> [a]
1947		//                 z -> [b]
1948		//
1949		// we derive a list of channels they represent.
1950		//
1951		//   (a, x)         (a, x)
1952		//   (a, y)         (a, y)
1953		//   (b, x)         (b, x)
1954		//   (b, z)         (b, z)
1955		//
1956		// and then that we compare that to the channel list in the `HrmpChannels`.
1957		let channel_set_derived_from_ingress = HrmpIngressChannelsIndex::<T>::iter()
1958			.flat_map(|(p, v)| v.into_iter().map(|i| (i, p)).collect::<Vec<_>>())
1959			.collect::<BTreeSet<_>>();
1960		let channel_set_derived_from_egress = HrmpEgressChannelsIndex::<T>::iter()
1961			.flat_map(|(p, v)| v.into_iter().map(|e| (p, e)).collect::<Vec<_>>())
1962			.collect::<BTreeSet<_>>();
1963		let channel_set_ground_truth = HrmpChannels::<T>::iter()
1964			.map(|(k, _)| (k.sender, k.recipient))
1965			.collect::<BTreeSet<_>>();
1966		assert_eq!(channel_set_derived_from_ingress, channel_set_derived_from_egress);
1967		assert_eq!(channel_set_derived_from_egress, channel_set_ground_truth);
1968
1969		HrmpIngressChannelsIndex::<T>::iter()
1970			.map(|(_, v)| v)
1971			.for_each(|v| assert_is_sorted(&v, "HrmpIngressChannelsIndex"));
1972		HrmpEgressChannelsIndex::<T>::iter()
1973			.map(|(_, v)| v)
1974			.for_each(|v| assert_is_sorted(&v, "HrmpIngressChannelsIndex"));
1975
1976		assert_contains_only_onboarded(
1977			HrmpChannelDigests::<T>::iter().map(|(k, _)| k).collect::<Vec<_>>(),
1978			"HRMP channel digests should contain only onboarded paras",
1979		);
1980		for (_digest_for_para, digest) in HrmpChannelDigests::<T>::iter() {
1981			// Assert that items are in **strictly** ascending order. The strictness also implies
1982			// there are no duplicates.
1983			assert!(digest.windows(2).all(|xs| xs[0].0 < xs[1].0));
1984
1985			for (_, mut senders) in digest {
1986				assert!(!senders.is_empty());
1987
1988				// check for duplicates. For that we sort the vector, then perform deduplication.
1989				// if the vector stayed the same, there are no duplicates.
1990				senders.sort();
1991				let orig_senders = senders.clone();
1992				senders.dedup();
1993				assert_eq!(
1994					orig_senders, senders,
1995					"duplicates removed implies existence of duplicates"
1996				);
1997			}
1998		}
1999	}
2000}
2001
2002impl<T: Config> Pallet<T> {
2003	/// Wraps HRMP XCM notifications to the most suitable XCM version for the destination para.
2004	/// If the XCM version is unknown, the latest XCM version is used as a best effort.
2005	fn wrap_notification(
2006		mut notification: impl FnMut() -> xcm::opaque::latest::opaque::Xcm,
2007	) -> impl FnOnce(ParaId) -> polkadot_primitives::DownwardMessage {
2008		use xcm::{
2009			opaque::VersionedXcm,
2010			prelude::{Junction, Location},
2011			WrapVersion,
2012		};
2013
2014		// Return a closure that can prepare notifications.
2015		move |dest| {
2016			// Attempt to wrap the notification for the destination parachain.
2017			T::VersionWrapper::wrap_version(
2018				&Location::new(0, [Junction::Parachain(dest.into())]),
2019				notification(),
2020			)
2021			.unwrap_or_else(|_| {
2022				// As a best effort, if we cannot resolve the version, fallback to using the latest
2023				// version.
2024				VersionedXcm::from(notification())
2025			})
2026			.encode()
2027		}
2028	}
2029
2030	/// Sends/enqueues notification to the destination parachain.
2031	fn send_to_para(
2032		log_label: &str,
2033		config: &HostConfiguration<BlockNumberFor<T>>,
2034		dest: ParaId,
2035		notification_bytes_for: impl FnOnce(ParaId) -> polkadot_primitives::DownwardMessage,
2036	) {
2037		// prepare notification
2038		let notification_bytes = notification_bytes_for(dest);
2039
2040		// try to enqueue
2041		if let Err(dmp::QueueDownwardMessageError::ExceedsMaxMessageSize) =
2042			dmp::Pallet::<T>::queue_downward_message(&config, dest, notification_bytes)
2043		{
2044			// this should never happen unless the max downward message size is configured to a
2045			// jokingly small number.
2046			log::error!(
2047				target: LOG_TARGET,
2048				"sending '{log_label}::notification_bytes' failed."
2049			);
2050			debug_assert!(false);
2051		}
2052	}
2053}