Skip to main content

pallet_messenger/
lib.rs

1// Copyright (C) 2021 Subspace Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Pallet messenger used to communicate between domains and other blockchains.
17
18#![cfg_attr(not(feature = "std"), no_std)]
19// TODO: Remove once FRAME macros stop generating `.clone()` calls on `Copy` types with user spans
20#![expect(clippy::clone_on_copy, reason = "Comes from Substrate")]
21#![forbid(unsafe_code)]
22#![warn(rust_2018_idioms)]
23#![cfg_attr(test, feature(variant_count))]
24
25#[cfg(feature = "runtime-benchmarks")]
26mod benchmarking;
27pub mod extensions;
28mod fees;
29mod messages;
30#[cfg(test)]
31mod mock;
32#[cfg(test)]
33mod tests;
34pub mod weights;
35
36#[cfg(not(feature = "std"))]
37extern crate alloc;
38
39use frame_support::pallet_prelude::{EnsureOrigin, MaxEncodedLen, StorageVersion};
40use frame_support::traits::fungible::{Inspect, InspectHold};
41use frame_system::pallet_prelude::BlockNumberFor;
42pub use pallet::*;
43use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
44use scale_info::TypeInfo;
45use sp_core::U256;
46use sp_domains::{DomainAllowlistUpdates, DomainId};
47use sp_messenger::MAX_FUTURE_ALLOWED_NONCES;
48use sp_messenger::messages::{
49    ChainId, Channel, ChannelId, ChannelState, CrossDomainMessage, Message, Nonce,
50};
51use sp_runtime::DispatchError;
52use sp_runtime::traits::Hash;
53use subspace_runtime_primitives::CreateUnsigned;
54pub use weights::WeightInfo;
55
56/// Transaction validity for a given validated XDM extrinsic.
57/// If the extrinsic is not included in the bundle, extrinsic is removed from the TxPool.
58const XDM_TRANSACTION_LONGEVITY: u64 = 10;
59
60/// XDM verification errors.
61pub(crate) mod verification_errors {
62    // When updating these error codes, check for clashes between:
63    // <https://github.com/autonomys/subspace/blob/main/domains/primitives/runtime/src/lib.rs#L85-L88>
64    // <https://github.com/autonomys/subspace/blob/main/crates/sp-domains-fraud-proof/src/lib.rs#L49-L64>
65    pub(crate) const INVALID_NONCE: u8 = 201;
66    // Custom error code when a messenger nonce overflows.
67    pub(crate) const XDM_NONCE_OVERFLOW: u8 = 202;
68    // This error code was previously 200, but that clashed with ERR_BALANCE_OVERFLOW.
69    pub(crate) const INVALID_CHANNEL: u8 = 203;
70    pub(crate) const IN_FUTURE_NONCE: u8 = 204;
71    // Failed to update next nonce during the pre_dispatch
72    pub(crate) const NEXT_NONCE_UPDATE: u8 = 205;
73}
74
75#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Copy, DecodeWithMemTracking)]
76pub enum OutboxMessageResult {
77    /// Message response handler returned Ok.
78    Ok,
79    /// Message response handler failed with Err.
80    Err(DispatchError),
81}
82
83/// Custom origin for validated unsigned extrinsics.
84#[derive(
85    PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DecodeWithMemTracking,
86)]
87pub enum RawOrigin {
88    ValidatedUnsigned,
89}
90
91/// Ensure the messenger origin.
92pub struct EnsureMessengerOrigin;
93impl<O: Into<Result<RawOrigin, O>> + From<RawOrigin>> EnsureOrigin<O> for EnsureMessengerOrigin {
94    type Success = ();
95
96    fn try_origin(o: O) -> Result<Self::Success, O> {
97        o.into().map(|o| match o {
98            RawOrigin::ValidatedUnsigned => (),
99        })
100    }
101
102    #[cfg(feature = "runtime-benchmarks")]
103    fn try_successful_origin() -> Result<O, ()> {
104        Ok(O::from(RawOrigin::ValidatedUnsigned))
105    }
106}
107
108pub(crate) type StateRootOf<T> = <<T as frame_system::Config>::Hashing as Hash>::Output;
109pub(crate) type BalanceOf<T> =
110    <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
111pub(crate) type FungibleHoldId<T> =
112    <<T as Config>::Currency as InspectHold<<T as frame_system::Config>::AccountId>>::Reason;
113
114/// Parameter to update chain allow list.
115#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Copy, DecodeWithMemTracking)]
116pub enum ChainAllowlistUpdate {
117    Add(ChainId),
118    Remove(ChainId),
119}
120
121impl ChainAllowlistUpdate {
122    fn chain_id(&self) -> ChainId {
123        match self {
124            ChainAllowlistUpdate::Add(chain_id) => *chain_id,
125            ChainAllowlistUpdate::Remove(chain_id) => *chain_id,
126        }
127    }
128}
129
130#[derive(Debug, Encode, Decode, TypeInfo)]
131pub struct ValidatedRelayMessage<T: Config> {
132    pub message: Message<BalanceOf<T>>,
133    pub should_init_channel: bool,
134    pub next_nonce: Nonce,
135}
136
137/// Channel can be closed either by Channel owner or Sudo
138#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Copy)]
139pub(crate) enum CloseChannelBy<AccountId> {
140    Owner(AccountId),
141    Sudo,
142}
143
144/// Hold identifier trait for messenger specific balance holds
145pub trait HoldIdentifier<T: Config> {
146    fn messenger_channel() -> FungibleHoldId<T>;
147}
148
149/// The current storage version.
150const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
151
152#[frame_support::pallet]
153mod pallet {
154    pub use crate::extensions::weights::WeightInfo as ExtensionWeightInfo;
155    use crate::weights::WeightInfo;
156    use crate::{
157        BalanceOf, ChainAllowlistUpdate, Channel, ChannelId, ChannelState, CloseChannelBy,
158        HoldIdentifier, Nonce, OutboxMessageResult, RawOrigin, STORAGE_VERSION, StateRootOf, U256,
159        ValidatedRelayMessage,
160    };
161    #[cfg(not(feature = "std"))]
162    use alloc::boxed::Box;
163    #[cfg(not(feature = "std"))]
164    use alloc::collections::BTreeSet;
165    #[cfg(not(feature = "std"))]
166    use alloc::vec::Vec;
167    use core::cmp::Ordering;
168    use frame_support::ensure;
169    use frame_support::pallet_prelude::*;
170    use frame_support::storage::with_storage_layer;
171    use frame_support::traits::fungible::{Balanced, Inspect, InspectHold, Mutate, MutateHold};
172    use frame_support::traits::tokens::{Fortitude, Precision, Preservation};
173    use frame_support::weights::WeightToFee;
174    use frame_system::pallet_prelude::*;
175    use sp_core::storage::StorageKey;
176    use sp_domains::proof_provider_and_verifier::{StorageProofVerifier, VerificationError};
177    use sp_domains::{DomainAllowlistUpdates, DomainId, DomainOwner};
178    use sp_messenger::endpoint::{
179        Endpoint, EndpointHandler, EndpointRequest, EndpointRequestWithCollectedFee, Sender,
180    };
181    use sp_messenger::messages::{
182        ChainId, ChannelOpenParamsV1, ChannelStateWithNonce, CrossDomainMessage, Message,
183        MessageId, MessageKey, MessageWeightTag, PayloadV1, ProtocolMessageRequest,
184        RequestResponse, VersionedPayload,
185    };
186    use sp_messenger::{
187        ChannelNonce, DomainRegistration, INHERENT_IDENTIFIER, InherentError, InherentType,
188        NoteChainTransfer, OnXDMRewards, StorageKeys,
189    };
190    use sp_runtime::traits::Zero;
191    use sp_runtime::{ArithmeticError, Perbill, Saturating};
192    use sp_subspace_mmr::MmrProofVerifier;
193    #[cfg(feature = "std")]
194    use std::collections::BTreeSet;
195
196    #[pallet::config]
197    pub trait Config: frame_system::Config<RuntimeEvent: From<Event<Self>>> {
198        /// Gets the chain_id that is treated as src_chain_id for outgoing messages.
199        type SelfChainId: Get<ChainId>;
200        /// function to fetch endpoint response handler by Endpoint.
201        fn get_endpoint_handler(endpoint: &Endpoint)
202        -> Option<Box<dyn EndpointHandler<MessageId>>>;
203        /// Currency type pallet uses for fees and deposits.
204        type Currency: Mutate<Self::AccountId>
205            + InspectHold<Self::AccountId>
206            + MutateHold<Self::AccountId>
207            + Balanced<Self::AccountId>;
208        /// Weight information for extrinsics in this pallet.
209        type WeightInfo: WeightInfo;
210        /// Weight to fee conversion.
211        type WeightToFee: WeightToFee<Balance = BalanceOf<Self>>;
212        /// Adjusted Weight to fee conversion.
213        /// This includes the TransactionPayment Multiper at the time of fee deduction.
214        type AdjustedWeightToFee: WeightToFee<Balance = BalanceOf<Self>>;
215        /// Fee Multiper for XDM
216        /// Final fee calculated will fee_multiplier * adjusted_weight_to_fee.
217        #[pallet::constant]
218        type FeeMultiplier: Get<u32>;
219        /// Handle XDM rewards.
220        type OnXDMRewards: OnXDMRewards<BalanceOf<Self>>;
221        /// Hash type of MMR
222        type MmrHash: Parameter + Member + Default + Clone;
223        /// MMR proof verifier
224        type MmrProofVerifier: MmrProofVerifier<Self::MmrHash, BlockNumberFor<Self>, StateRootOf<Self>>;
225        /// Storage key provider.
226        type StorageKeys: StorageKeys;
227        /// Domain owner provider.
228        type DomainOwner: DomainOwner<Self::AccountId>;
229        /// A variation of the Identifier used for holding the funds used for Messenger
230        type HoldIdentifier: HoldIdentifier<Self>;
231        /// Channel reserve fee to open a channel.
232        #[pallet::constant]
233        type ChannelReserveFee: Get<BalanceOf<Self>>;
234        /// Portion of Channel reserve taken by the protocol
235        /// if the channel is in init state and is requested to be closed.
236        #[pallet::constant]
237        type ChannelInitReservePortion: Get<Perbill>;
238        /// Type to check if a given domain is registered on Consensus chain.
239        type DomainRegistration: DomainRegistration;
240        /// Maximum outgoing messages from a given channel
241        #[pallet::constant]
242        type MaxOutgoingMessages: Get<u32>;
243        /// Origin for messenger call.
244        type MessengerOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ()>;
245        /// Helper to note cross chain XDM fee transfer
246        type NoteChainTransfer: NoteChainTransfer<BalanceOf<Self>>;
247        /// Weight info for extensions
248        type ExtensionWeightInfo: ExtensionWeightInfo;
249    }
250
251    /// Pallet messenger used to communicate between chains and other blockchains.
252    #[pallet::pallet]
253    #[pallet::without_storage_info]
254    #[pallet::storage_version(STORAGE_VERSION)]
255    pub struct Pallet<T>(_);
256
257    /// Stores the next channel id for a foreign chain.
258    #[pallet::storage]
259    #[pallet::getter(fn next_channel_id)]
260    pub(super) type NextChannelId<T: Config> =
261        StorageMap<_, Identity, ChainId, ChannelId, ValueQuery>;
262
263    /// Stores channel config between two chains.
264    /// Key points to the foreign chain wrt own chain's storage name space
265    #[pallet::storage]
266    #[pallet::getter(fn channels)]
267    pub(super) type Channels<T: Config> = StorageDoubleMap<
268        _,
269        Identity,
270        ChainId,
271        Identity,
272        ChannelId,
273        Channel<BalanceOf<T>, T::AccountId>,
274        OptionQuery,
275    >;
276
277    /// A temporary storage for storing decoded inbox message between `pre_dispatch_relay_message`
278    /// and `relay_message`.
279    #[pallet::storage]
280    #[pallet::getter(fn inbox)]
281    pub(super) type Inbox<T: Config> = StorageValue<_, Message<BalanceOf<T>>, OptionQuery>;
282
283    /// A temporary storage of fees for executing an inbox message.
284    /// The storage is cleared when the acknowledgement of inbox response is received
285    /// from the src_chain.
286    #[pallet::storage]
287    #[pallet::getter(fn inbox_fees)]
288    pub(super) type InboxFee<T: Config> =
289        StorageMap<_, Identity, (ChainId, MessageId), BalanceOf<T>, OptionQuery>;
290
291    /// A temporary storage of fees for executing an outbox message and its response from dst_chain.
292    /// The storage is cleared when src_chain receives the response from dst_chain.
293    #[pallet::storage]
294    #[pallet::getter(fn outbox_fees)]
295    pub(super) type OutboxFee<T: Config> =
296        StorageMap<_, Identity, (ChainId, MessageId), BalanceOf<T>, OptionQuery>;
297
298    /// Stores the message responses of the incoming processed responses.
299    /// Used by the dst_chains to verify the message response.
300    #[pallet::storage]
301    #[pallet::getter(fn inbox_responses)]
302    pub(super) type InboxResponses<T: Config> =
303        StorageMap<_, Identity, (ChainId, ChannelId, Nonce), Message<BalanceOf<T>>, OptionQuery>;
304
305    /// Stores the outgoing messages that are awaiting message responses from the dst_chain.
306    /// Messages are processed in the outbox nonce order of chain's channel.
307    #[pallet::storage]
308    #[pallet::getter(fn outbox)]
309    pub(super) type Outbox<T: Config> =
310        StorageMap<_, Identity, (ChainId, ChannelId, Nonce), Message<BalanceOf<T>>, OptionQuery>;
311
312    /// Stores the outgoing messages count that are awaiting message responses from the dst_chain.
313    #[pallet::storage]
314    #[pallet::getter(fn outbox_message_count)]
315    pub(super) type OutboxMessageCount<T: Config> =
316        StorageMap<_, Identity, (ChainId, ChannelId), u32, ValueQuery>;
317
318    /// A temporary storage for storing decoded outbox response message between `pre_dispatch_relay_message_response`
319    /// and `relay_message_response`.
320    #[pallet::storage]
321    #[pallet::getter(fn outbox_responses)]
322    pub(super) type OutboxResponses<T: Config> =
323        StorageValue<_, Message<BalanceOf<T>>, OptionQuery>;
324
325    /// Storage to store the weight tags for all the outbox messages.
326    #[pallet::storage]
327    #[pallet::getter(fn outbox_message_weight_tags)]
328    pub(super) type OutboxMessageWeightTags<T: Config> =
329        StorageMap<_, Identity, (ChainId, MessageId), MessageWeightTag>;
330
331    /// Storage to store the weight tags for all the inbox responses messages.
332    #[pallet::storage]
333    #[pallet::getter(fn inbox_response_message_weight_tags)]
334    pub(super) type InboxResponseMessageWeightTags<T: Config> =
335        StorageMap<_, Identity, (ChainId, MessageId), MessageWeightTag>;
336
337    /// An allowlist of chains that can open channel with this chain.
338    #[pallet::storage]
339    #[pallet::getter(fn chain_allowlist)]
340    pub(super) type ChainAllowlist<T: Config> = StorageValue<_, BTreeSet<ChainId>, ValueQuery>;
341
342    /// A storage to store any allowlist updates to domain. The updates will be cleared in the next block
343    /// once the previous block has a domain bundle, but a empty value should be left because in the invalid
344    /// extrinsic root fraud proof the prover need to generate a proof-of-empty-value for the domain.
345    #[pallet::storage]
346    #[pallet::getter(fn domain_chain_allowlist_updates)]
347    pub(super) type DomainChainAllowlistUpdate<T: Config> =
348        StorageMap<_, Identity, DomainId, DomainAllowlistUpdates, OptionQuery>;
349
350    /// Temporary storage to store the updated channels between this chain and other chain.
351    /// Storage is cleared on block initialization.
352    #[pallet::storage]
353    pub(super) type UpdatedChannels<T: Config> =
354        StorageValue<_, BTreeSet<(ChainId, ChannelId)>, ValueQuery>;
355
356    /// Storage to track the inbox fees that is hold on the chain before distributing.
357    ///
358    /// NOTE: The inbox fees is accounted to the chain's total issuance but not hold on any account
359    /// because an account with balance below ED will be reaped, in this way, we can manage small
360    /// inbox fee that less than ED easier. It also means whenever `InboxFeesOnHold` is increase/decrease
361    /// we need to increase/decrease the total issuance manually.
362    #[pallet::storage]
363    pub(super) type InboxFeesOnHold<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
364
365    /// Storage to track the outbox fees that is hold on the chain before distributing.
366    ///
367    /// NOTE: The outbox fees is accounted to the chain's total issuance but not hold on any account
368    /// because an account with balance below ED will be reaped, in this way, we can manage small
369    /// outbox fee that less than ED easier. It also means whenever `OutboxFeesOnHold` is increase/decrease
370    /// we need to increase/decrease the total issuance manually.
371    #[pallet::storage]
372    pub(super) type OutboxFeesOnHold<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
373
374    #[pallet::origin]
375    pub type Origin = RawOrigin;
376
377    /// `pallet-messenger` events
378    #[pallet::event]
379    #[pallet::generate_deposit(pub (super) fn deposit_event)]
380    pub enum Event<T: Config> {
381        /// Emits when a channel between two chains is initiated.
382        ChannelInitiated {
383            /// Foreign chain id this channel connects to.
384            chain_id: ChainId,
385            /// Channel ID of the said channel.
386            channel_id: ChannelId,
387        },
388
389        /// Emits when a channel between two chains is closed.
390        ChannelClosed {
391            /// Foreign chain id this channel connects to.
392            chain_id: ChainId,
393            /// Channel ID of the said channel.
394            channel_id: ChannelId,
395        },
396
397        /// Emits when a channel between two chain is open.
398        ChannelOpen {
399            /// Foreign chain id this channel connects to.
400            chain_id: ChainId,
401            /// Channel ID of the said channel.
402            channel_id: ChannelId,
403        },
404
405        /// Emits when a new message is added to the outbox.
406        OutboxMessage {
407            chain_id: ChainId,
408            channel_id: ChannelId,
409            nonce: Nonce,
410        },
411
412        /// Emits when a message response is available for Outbox message.
413        OutboxMessageResponse {
414            /// Destination chain ID.
415            chain_id: ChainId,
416            /// Channel Is
417            channel_id: ChannelId,
418            nonce: Nonce,
419        },
420
421        /// Emits outbox message result.
422        OutboxMessageResult {
423            chain_id: ChainId,
424            channel_id: ChannelId,
425            nonce: Nonce,
426            result: OutboxMessageResult,
427        },
428
429        /// Emits when a new inbox message is validated and added to Inbox.
430        InboxMessage {
431            chain_id: ChainId,
432            channel_id: ChannelId,
433            nonce: Nonce,
434        },
435
436        /// Emits when a message response is available for Inbox message.
437        InboxMessageResponse {
438            /// Destination chain ID.
439            chain_id: ChainId,
440            /// Channel Is
441            channel_id: ChannelId,
442            nonce: Nonce,
443        },
444    }
445
446    #[pallet::hooks]
447    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
448        fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
449            UpdatedChannels::<T>::take();
450            T::DbWeight::get().reads_writes(0, 1)
451        }
452    }
453
454    #[pallet::validate_unsigned]
455    impl<T: Config> ValidateUnsigned for Pallet<T> {
456        type Call = Call<T>;
457
458        fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
459            match call {
460                // always accept inherent extrinsic
461                Call::update_domain_allowlist { .. } => Ok(()),
462                _ => Err(InvalidTransaction::Call.into()),
463            }
464        }
465
466        /// Validate unsigned call to this module.
467        fn validate_unsigned(
468            _source: TransactionSource,
469            _call: &Self::Call,
470        ) -> TransactionValidity {
471            InvalidTransaction::Call.into()
472        }
473    }
474
475    /// `pallet-messenger` errors
476    #[pallet::error]
477    pub enum Error<T> {
478        /// Emits when the chain is neither consensus not chain.
479        InvalidChain,
480
481        /// Emits when there is no channel for a given Channel ID.
482        MissingChannel,
483
484        /// Emits when the said channel is not in an open state.
485        InvalidChannelState,
486
487        /// Emits when there are no open channels for a chain
488        NoOpenChannel,
489
490        /// Emits when there are not message handler with given endpoint ID.
491        NoMessageHandler,
492
493        /// Emits when the outbox is full for a channel.
494        OutboxFull,
495
496        /// Emits when the message payload is invalid.
497        InvalidMessagePayload,
498
499        /// Emits when the message destination is not valid.
500        InvalidMessageDestination,
501
502        /// Emits when the message verification failed.
503        MessageVerification(VerificationError),
504
505        /// Emits when there is no message available for the given nonce.
506        MissingMessage,
507
508        /// Emits when there is mismatch between the message's weight tag and the message's
509        /// actual processing path
510        WeightTagNotMatch,
511
512        /// Emits when the there is balance overflow.
513        BalanceOverflow,
514
515        /// Emits when the there is balance underflow.
516        BalanceUnderflow,
517
518        /// Invalid allowed chain.
519        InvalidAllowedChain,
520
521        /// Operation not allowed.
522        OperationNotAllowed,
523
524        /// Account is not a Domain owner.
525        NotDomainOwner,
526
527        /// Chain not allowed to open channel
528        ChainNotAllowed,
529
530        /// Not enough balance to do the operation
531        InsufficientBalance,
532
533        /// Failed to hold balance
534        BalanceHold,
535
536        /// Not a channel owner
537        ChannelOwner,
538
539        /// Failed to unlock the balance
540        BalanceUnlock,
541
542        /// Invalid channel reserve fee
543        InvalidChannelReserveFee,
544
545        /// Invalid max outgoing messages
546        InvalidMaxOutgoingMessages,
547
548        /// Message count overflow
549        MessageCountOverflow,
550
551        /// Message count underflow
552        MessageCountUnderflow,
553
554        /// Failed to note transfer in
555        FailedToNoteTransferIn,
556
557        /// Failed to note transfer out
558        FailedToNoteTransferOut,
559    }
560
561    #[pallet::call]
562    impl<T: Config> Pallet<T> {
563        /// A new Channel is initiated with a foreign chain.
564        /// Next Channel ID is used to assign the new channel.
565        /// Channel is set to initiated and do not accept or receive any messages.
566        #[pallet::call_index(0)]
567        #[pallet::weight(T::WeightInfo::initiate_channel())]
568        pub fn initiate_channel(origin: OriginFor<T>, dst_chain_id: ChainId) -> DispatchResult {
569            let owner = ensure_signed(origin)?;
570
571            // reserve channel open fees
572            let hold_id = T::HoldIdentifier::messenger_channel();
573            let amount = T::ChannelReserveFee::get();
574
575            // ensure there is enough free balance to lock
576            ensure!(
577                T::Currency::reducible_balance(&owner, Preservation::Preserve, Fortitude::Polite)
578                    >= amount,
579                Error::<T>::InsufficientBalance
580            );
581            T::Currency::hold(&hold_id, &owner, amount).map_err(|_| Error::<T>::BalanceHold)?;
582
583            // initiate the channel config
584            let channel_open_params = ChannelOpenParamsV1 {
585                max_outgoing_messages: T::MaxOutgoingMessages::get(),
586            };
587            let channel_id = Self::do_init_channel(
588                dst_chain_id,
589                channel_open_params,
590                Some(owner.clone()),
591                true,
592                amount,
593            )?;
594
595            let payload = VersionedPayload::V1(PayloadV1::Protocol(RequestResponse::Request(
596                ProtocolMessageRequest::ChannelOpen(ChannelOpenParamsV1 {
597                    max_outgoing_messages: channel_open_params.max_outgoing_messages,
598                }),
599            )));
600
601            // send message to dst_chain
602            Self::new_outbox_message(T::SelfChainId::get(), dst_chain_id, channel_id, payload)?;
603
604            Ok(())
605        }
606
607        /// An open channel is closed with a foreign chain.
608        /// Channel is set to Closed and do not accept or receive any messages.
609        #[pallet::call_index(1)]
610        #[pallet::weight(T::WeightInfo::close_channel())]
611        pub fn close_channel(
612            origin: OriginFor<T>,
613            chain_id: ChainId,
614            channel_id: ChannelId,
615        ) -> DispatchResult {
616            // either owner can close the channel
617            // or sudo can close the channel
618            let close_channel_by = match ensure_signed_or_root(origin)? {
619                Some(owner) => CloseChannelBy::Owner(owner),
620                None => CloseChannelBy::Sudo,
621            };
622            Self::do_close_channel(chain_id, channel_id, close_channel_by)?;
623
624            let payload = VersionedPayload::V1(PayloadV1::Protocol(RequestResponse::Request(
625                ProtocolMessageRequest::ChannelClose,
626            )));
627
628            Self::new_outbox_message(T::SelfChainId::get(), chain_id, channel_id, payload)?;
629
630            Ok(())
631        }
632
633        /// Receives an Inbox message that needs to be validated and processed.
634        #[pallet::call_index(2)]
635        #[pallet::weight(T::WeightInfo::relay_message().saturating_add(Pallet::< T >::message_weight(& msg.weight_tag))
636        )]
637        pub fn relay_message(
638            origin: OriginFor<T>,
639            msg: CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
640        ) -> DispatchResult {
641            T::MessengerOrigin::ensure_origin(origin)?;
642            let inbox_msg = Inbox::<T>::take().ok_or(Error::<T>::MissingMessage)?;
643            Self::process_inbox_messages(inbox_msg, msg.weight_tag)?;
644            Ok(())
645        }
646
647        /// Receives a response from the dst_chain for a message in Outbox.
648        #[pallet::call_index(3)]
649        #[pallet::weight(T::WeightInfo::relay_message_response().saturating_add(Pallet::< T >::message_weight(& msg.weight_tag))
650        )]
651        pub fn relay_message_response(
652            origin: OriginFor<T>,
653            msg: CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
654        ) -> DispatchResult {
655            T::MessengerOrigin::ensure_origin(origin)?;
656            let outbox_resp_msg = OutboxResponses::<T>::take().ok_or(Error::<T>::MissingMessage)?;
657            Self::process_outbox_message_responses(outbox_resp_msg, msg.weight_tag)?;
658            Ok(())
659        }
660
661        /// A call to update consensus chain allow list.
662        #[pallet::call_index(4)]
663        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(1, 1))]
664        pub fn update_consensus_chain_allowlist(
665            origin: OriginFor<T>,
666            update: ChainAllowlistUpdate,
667        ) -> DispatchResult {
668            ensure_root(origin)?;
669            ensure!(
670                T::SelfChainId::get().is_consensus_chain(),
671                Error::<T>::OperationNotAllowed
672            );
673
674            ensure!(
675                update.chain_id() != T::SelfChainId::get(),
676                Error::<T>::InvalidAllowedChain
677            );
678
679            if let ChainAllowlistUpdate::Add(ChainId::Domain(domain_id)) = update {
680                ensure!(
681                    T::DomainRegistration::is_domain_registered(domain_id),
682                    Error::<T>::InvalidChain
683                );
684            }
685
686            ChainAllowlist::<T>::mutate(|list| match update {
687                ChainAllowlistUpdate::Add(chain_id) => list.insert(chain_id),
688                ChainAllowlistUpdate::Remove(chain_id) => list.remove(&chain_id),
689            });
690            Ok(())
691        }
692
693        /// A call to initiate chain allowlist update on domains
694        #[pallet::call_index(5)]
695        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(1, 1))]
696        pub fn initiate_domain_update_chain_allowlist(
697            origin: OriginFor<T>,
698            domain_id: DomainId,
699            update: ChainAllowlistUpdate,
700        ) -> DispatchResult {
701            let domain_owner = ensure_signed(origin)?;
702            ensure!(
703                T::DomainOwner::is_domain_owner(domain_id, domain_owner),
704                Error::<T>::NotDomainOwner
705            );
706
707            ensure!(
708                T::SelfChainId::get().is_consensus_chain(),
709                Error::<T>::OperationNotAllowed
710            );
711
712            if let Some(dst_domain_id) = update.chain_id().maybe_domain_chain() {
713                ensure!(dst_domain_id != domain_id, Error::<T>::InvalidAllowedChain);
714            }
715
716            if let ChainAllowlistUpdate::Add(ChainId::Domain(domain_id)) = update {
717                ensure!(
718                    T::DomainRegistration::is_domain_registered(domain_id),
719                    Error::<T>::InvalidChain
720                );
721            }
722
723            DomainChainAllowlistUpdate::<T>::mutate(domain_id, |maybe_domain_updates| {
724                let mut domain_updates = maybe_domain_updates.take().unwrap_or_default();
725                match update {
726                    ChainAllowlistUpdate::Add(chain_id) => {
727                        domain_updates.remove_chains.remove(&chain_id);
728                        domain_updates.allow_chains.insert(chain_id);
729                    }
730                    ChainAllowlistUpdate::Remove(chain_id) => {
731                        domain_updates.allow_chains.remove(&chain_id);
732                        domain_updates.remove_chains.insert(chain_id);
733                    }
734                }
735
736                *maybe_domain_updates = Some(domain_updates)
737            });
738            Ok(())
739        }
740
741        /// An inherent call to update allowlist for domain.
742        #[pallet::call_index(6)]
743        #[pallet::weight((T::DbWeight::get().reads_writes(1, 1), DispatchClass::Mandatory))]
744        pub fn update_domain_allowlist(
745            origin: OriginFor<T>,
746            updates: DomainAllowlistUpdates,
747        ) -> DispatchResult {
748            ensure_none(origin)?;
749            ensure!(
750                !T::SelfChainId::get().is_consensus_chain(),
751                Error::<T>::OperationNotAllowed
752            );
753
754            let DomainAllowlistUpdates {
755                allow_chains,
756                remove_chains,
757            } = updates;
758
759            ChainAllowlist::<T>::mutate(|list| {
760                // remove chains from set
761                remove_chains.into_iter().for_each(|chain_id| {
762                    list.remove(&chain_id);
763                });
764
765                // add new chains
766                allow_chains.into_iter().for_each(|chain_id| {
767                    list.insert(chain_id);
768                });
769            });
770
771            Ok(())
772        }
773    }
774
775    #[pallet::inherent]
776    impl<T: Config> ProvideInherent for Pallet<T> {
777        type Call = Call<T>;
778        type Error = InherentError;
779        const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
780
781        fn create_inherent(data: &InherentData) -> Option<Self::Call> {
782            let inherent_data = data
783                .get_data::<InherentType>(&INHERENT_IDENTIFIER)
784                .expect("Messenger inherent data not correctly encoded")
785                .expect("Messenger inherent data must be provided");
786
787            inherent_data
788                .maybe_updates
789                .map(|updates| Call::update_domain_allowlist { updates })
790        }
791
792        fn is_inherent_required(data: &InherentData) -> Result<Option<Self::Error>, Self::Error> {
793            let inherent_data = data
794                .get_data::<InherentType>(&INHERENT_IDENTIFIER)
795                .expect("Messenger inherent data not correctly encoded")
796                .expect("Messenger inherent data must be provided");
797
798            Ok(if inherent_data.maybe_updates.is_none() {
799                None
800            } else {
801                Some(InherentError::MissingAllowlistUpdates)
802            })
803        }
804
805        fn check_inherent(call: &Self::Call, data: &InherentData) -> Result<(), Self::Error> {
806            let inherent_data = data
807                .get_data::<InherentType>(&INHERENT_IDENTIFIER)
808                .expect("Messenger inherent data not correctly encoded")
809                .expect("Messenger inherent data must be provided");
810
811            if let Some(provided_updates) = inherent_data.maybe_updates {
812                if let Call::update_domain_allowlist { updates } = call
813                    && updates != &provided_updates
814                {
815                    return Err(InherentError::IncorrectAllowlistUpdates);
816                }
817            } else {
818                return Err(InherentError::MissingAllowlistUpdates);
819            }
820
821            Ok(())
822        }
823
824        fn is_inherent(call: &Self::Call) -> bool {
825            matches!(call, Call::update_domain_allowlist { .. })
826        }
827    }
828
829    impl<T: Config> Sender<T::AccountId> for Pallet<T> {
830        type MessageId = MessageId;
831
832        fn send_message(
833            sender: &T::AccountId,
834            dst_chain_id: ChainId,
835            req: EndpointRequest,
836        ) -> Result<Self::MessageId, DispatchError> {
837            let allowed_chains = ChainAllowlist::<T>::get();
838            ensure!(
839                allowed_chains.contains(&dst_chain_id),
840                Error::<T>::ChainNotAllowed
841            );
842
843            let channel_id =
844                Self::get_open_channel_for_chain(dst_chain_id).ok_or(Error::<T>::NoOpenChannel)?;
845
846            let src_endpoint = req.src_endpoint.clone();
847
848            let message_id = {
849                // collect the fees from the sender
850                let collected_fee = Self::collect_fees_for_message_v1(sender, &src_endpoint)?;
851                let src_chain_fee = collected_fee.src_chain_fee;
852                let dst_chain_fee = collected_fee.dst_chain_fee;
853                let nonce = Self::new_outbox_message(
854                    T::SelfChainId::get(),
855                    dst_chain_id,
856                    channel_id,
857                    VersionedPayload::V1(PayloadV1::Endpoint(RequestResponse::Request(
858                        EndpointRequestWithCollectedFee { req, collected_fee },
859                    ))),
860                )?;
861
862                // store src_chain, this chain, fee to OutboxFee
863                let message_id = (channel_id, nonce);
864                Self::store_outbox_fee(dst_chain_id, message_id, src_chain_fee, dst_chain_fee)?;
865                message_id
866            };
867
868            Ok(message_id)
869        }
870
871        /// Only used in benchmark to prepare for a upcoming `send_message` call to
872        /// ensure it will succeed.
873        #[cfg(feature = "runtime-benchmarks")]
874        fn unchecked_open_channel(dst_chain_id: ChainId) -> Result<(), DispatchError> {
875            let init_params = ChannelOpenParamsV1 {
876                max_outgoing_messages: 100,
877            };
878            ChainAllowlist::<T>::mutate(|list| list.insert(dst_chain_id));
879            let channel_id =
880                Self::do_init_channel(dst_chain_id, init_params, None, true, Zero::zero())?;
881            Self::do_open_channel(dst_chain_id, channel_id)?;
882            Ok(())
883        }
884    }
885
886    impl<T: Config> Pallet<T> {
887        // Get the weight according the given weight tag
888        fn message_weight(weight_tag: &MessageWeightTag) -> Weight {
889            match weight_tag {
890                MessageWeightTag::ProtocolChannelOpen => T::WeightInfo::do_open_channel(),
891                MessageWeightTag::ProtocolChannelClose => T::WeightInfo::do_close_channel(),
892                MessageWeightTag::EndpointRequest(endpoint) => {
893                    T::get_endpoint_handler(endpoint)
894                        .map(|endpoint_handler| endpoint_handler.message_weight())
895                        // If there is no endpoint handler the request won't be handled thus return zero weight
896                        .unwrap_or(Weight::zero())
897                }
898                MessageWeightTag::EndpointResponse(endpoint) => {
899                    T::get_endpoint_handler(endpoint)
900                        .map(|endpoint_handler| endpoint_handler.message_response_weight())
901                        // If there is no endpoint handler the request won't be handled thus return zero weight
902                        .unwrap_or(Weight::zero())
903                }
904                MessageWeightTag::None => Weight::zero(),
905            }
906        }
907
908        /// Returns the last open channel for a given chain.
909        pub fn get_open_channel_for_chain(dst_chain_id: ChainId) -> Option<ChannelId> {
910            let mut next_channel_id = NextChannelId::<T>::get(dst_chain_id);
911
912            // loop through channels in descending order until open channel is found.
913            // we always prefer latest opened channel.
914            while let Some(channel_id) = next_channel_id.checked_sub(ChannelId::one()) {
915                let message_count = OutboxMessageCount::<T>::get((dst_chain_id, channel_id));
916                if let Some(channel) = Channels::<T>::get(dst_chain_id, channel_id)
917                    && channel.state == ChannelState::Open
918                    && message_count < channel.max_outgoing_messages
919                {
920                    return Some(channel_id);
921                }
922
923                next_channel_id = channel_id
924            }
925
926            None
927        }
928
929        /// Opens an initiated channel.
930        pub(crate) fn do_open_channel(chain_id: ChainId, channel_id: ChannelId) -> DispatchResult {
931            Channels::<T>::try_mutate(chain_id, channel_id, |maybe_channel| -> DispatchResult {
932                let channel = maybe_channel.as_mut().ok_or(Error::<T>::MissingChannel)?;
933
934                ensure!(
935                    channel.state == ChannelState::Initiated,
936                    Error::<T>::InvalidChannelState
937                );
938
939                channel.state = ChannelState::Open;
940                Ok(())
941            })?;
942
943            Self::deposit_event(Event::ChannelOpen {
944                chain_id,
945                channel_id,
946            });
947
948            Ok(())
949        }
950
951        pub(crate) fn do_close_channel(
952            chain_id: ChainId,
953            channel_id: ChannelId,
954            close_channel_by: CloseChannelBy<T::AccountId>,
955        ) -> DispatchResult {
956            Channels::<T>::try_mutate(chain_id, channel_id, |maybe_channel| -> DispatchResult {
957                let channel = maybe_channel.as_mut().ok_or(Error::<T>::MissingChannel)?;
958
959                ensure!(
960                    channel.state != ChannelState::Closed,
961                    Error::<T>::InvalidChannelState
962                );
963
964                if let CloseChannelBy::Owner(owner) = close_channel_by {
965                    ensure!(channel.maybe_owner == Some(owner), Error::<T>::ChannelOwner);
966                }
967
968                if let Some(owner) = &channel.maybe_owner {
969                    let hold_id = T::HoldIdentifier::messenger_channel();
970                    let locked_amount = channel.channel_reserve_fee;
971                    let (amount_to_release, maybe_amount_to_burn) = {
972                        if channel.state == ChannelState::Open {
973                            (locked_amount, None)
974                        } else {
975                            let protocol_fee = T::ChannelInitReservePortion::get() * locked_amount;
976                            let release_amount = locked_amount.saturating_sub(protocol_fee);
977                            (release_amount, Some(protocol_fee))
978                        }
979                    };
980
981                    with_storage_layer(|| {
982                        if let Some(protocol_fee) = maybe_amount_to_burn {
983                            T::Currency::burn_held(
984                                &hold_id,
985                                owner,
986                                protocol_fee,
987                                Precision::Exact,
988                                Fortitude::Force,
989                            )?;
990                            T::OnXDMRewards::on_chain_protocol_fees(chain_id, protocol_fee);
991                        }
992
993                        T::Currency::release(&hold_id, owner, amount_to_release, Precision::Exact)
994                            .map_err(|_| Error::<T>::BalanceUnlock)?;
995
996                        Ok::<(), DispatchError>(())
997                    })?;
998                }
999
1000                channel.state = ChannelState::Closed;
1001                Ok(())
1002            })?;
1003
1004            Self::deposit_event(Event::ChannelClosed {
1005                chain_id,
1006                channel_id,
1007            });
1008
1009            Ok(())
1010        }
1011
1012        pub(crate) fn do_init_channel(
1013            dst_chain_id: ChainId,
1014            init_params: ChannelOpenParamsV1,
1015            maybe_owner: Option<T::AccountId>,
1016            check_allowlist: bool,
1017            channel_reserve_fee: BalanceOf<T>,
1018        ) -> Result<ChannelId, DispatchError> {
1019            ensure!(
1020                T::SelfChainId::get() != dst_chain_id,
1021                Error::<T>::InvalidChain,
1022            );
1023
1024            // ensure max outgoing messages is at least 1
1025            ensure!(
1026                init_params.max_outgoing_messages >= 1u32,
1027                Error::<T>::InvalidMaxOutgoingMessages
1028            );
1029
1030            // If the channel owner is in this chain then the channel reserve fee
1031            // must not be empty
1032            ensure!(
1033                maybe_owner.is_none() || !channel_reserve_fee.is_zero(),
1034                Error::<T>::InvalidChannelReserveFee,
1035            );
1036
1037            if check_allowlist {
1038                let chain_allowlist = ChainAllowlist::<T>::get();
1039                ensure!(
1040                    chain_allowlist.contains(&dst_chain_id),
1041                    Error::<T>::ChainNotAllowed
1042                );
1043            }
1044
1045            let channel_id = NextChannelId::<T>::get(dst_chain_id);
1046            let next_channel_id = channel_id
1047                .checked_add(U256::one())
1048                .ok_or(DispatchError::Arithmetic(ArithmeticError::Overflow))?;
1049
1050            Channels::<T>::insert(
1051                dst_chain_id,
1052                channel_id,
1053                Channel {
1054                    channel_id,
1055                    state: ChannelState::Initiated,
1056                    next_inbox_nonce: Default::default(),
1057                    next_outbox_nonce: Default::default(),
1058                    latest_response_received_message_nonce: Default::default(),
1059                    max_outgoing_messages: init_params.max_outgoing_messages,
1060                    maybe_owner,
1061                    channel_reserve_fee,
1062                },
1063            );
1064
1065            NextChannelId::<T>::insert(dst_chain_id, next_channel_id);
1066            Self::deposit_event(Event::ChannelInitiated {
1067                chain_id: dst_chain_id,
1068                channel_id,
1069            });
1070            Ok(channel_id)
1071        }
1072
1073        pub fn validate_relay_message(
1074            xdm: &CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
1075            consensus_state_root: StateRootOf<T>,
1076        ) -> Result<ValidatedRelayMessage<T>, TransactionValidityError> {
1077            let (next_nonce, maybe_channel) =
1078                match Channels::<T>::get(xdm.src_chain_id, xdm.channel_id) {
1079                    None => {
1080                        // if there is no channel config, this must the Channel open request.
1081                        // so nonce is 0
1082                        log::debug!(
1083                            "Initiating new channel: {:?} to chain: {:?}",
1084                            xdm.channel_id,
1085                            xdm.src_chain_id
1086                        );
1087                        (Nonce::zero(), None)
1088                    }
1089                    Some(channel) => {
1090                        log::debug!(
1091                            "Message to channel: {:?} from chain: {:?}",
1092                            xdm.channel_id,
1093                            xdm.src_chain_id
1094                        );
1095                        (channel.next_inbox_nonce, Some(channel))
1096                    }
1097                };
1098
1099            // derive the key as stored on the src_chain.
1100            let key = StorageKey(
1101                T::StorageKeys::outbox_storage_key(
1102                    xdm.src_chain_id,
1103                    (T::SelfChainId::get(), xdm.channel_id, xdm.nonce),
1104                )
1105                .ok_or(UnknownTransaction::CannotLookup)?,
1106            );
1107
1108            // verify and decode message
1109            let msg = Self::do_verify_xdm(next_nonce, key, consensus_state_root, xdm)?;
1110
1111            let is_valid_call = match &msg.payload {
1112                VersionedPayload::V1(PayloadV1::Protocol(RequestResponse::Request(req))) => {
1113                    match req {
1114                        // channel open should ensure there is no Channel present already
1115                        ProtocolMessageRequest::ChannelOpen(_) => maybe_channel.is_none(),
1116                        // we allow channel close only if it is init or open state
1117                        ProtocolMessageRequest::ChannelClose => {
1118                            if let Some(ref channel) = maybe_channel {
1119                                !(channel.state == ChannelState::Closed)
1120                            } else {
1121                                false
1122                            }
1123                        }
1124                    }
1125                }
1126                // endpoint request messages are only allowed when
1127                // channel is open, or
1128                // channel is closed. Channel can be closed by dst_chain simultaneously
1129                // while src_chain already sent a message. We allow the message but return an
1130                // error in the response so that src_chain can revert any necessary actions
1131                VersionedPayload::V1(PayloadV1::Endpoint(RequestResponse::Request(_))) => {
1132                    if let Some(ref channel) = maybe_channel {
1133                        !(channel.state == ChannelState::Initiated)
1134                    } else {
1135                        false
1136                    }
1137                }
1138                // any other message variants are not allowed
1139                _ => false,
1140            };
1141
1142            if !is_valid_call {
1143                log::error!("Unexpected XDM message: {msg:?}",);
1144                return Err(InvalidTransaction::Call.into());
1145            }
1146
1147            // Reject stale message
1148            if msg.nonce.cmp(&next_nonce) == Ordering::Less {
1149                return Err(InvalidTransaction::Stale.into());
1150            }
1151
1152            let validated_relay_msg = ValidatedRelayMessage {
1153                message: msg,
1154                should_init_channel: maybe_channel.is_none(),
1155                next_nonce,
1156            };
1157
1158            Ok(validated_relay_msg)
1159        }
1160
1161        pub(crate) fn pre_dispatch_relay_message(
1162            msg: Message<BalanceOf<T>>,
1163            should_init_channel: bool,
1164        ) -> Result<(), TransactionValidityError> {
1165            if should_init_channel {
1166                if let VersionedPayload::V1(PayloadV1::Protocol(RequestResponse::Request(
1167                    ProtocolMessageRequest::ChannelOpen(params),
1168                ))) = msg.payload
1169                {
1170                    // channel is being opened without an owner since this is a relay message
1171                    // from other chain
1172                    // we do not check the allowlist to finish the end to end flow
1173                    Self::do_init_channel(msg.src_chain_id, params, None, false, Zero::zero())
1174                        .map_err(|err| {
1175                            log::error!(
1176                                "Error initiating channel: {:?} with chain: {:?}: {:?}",
1177                                msg.channel_id,
1178                                msg.src_chain_id,
1179                                err
1180                            );
1181                            InvalidTransaction::Call
1182                        })?;
1183                } else {
1184                    log::error!("Unexpected call instead of channel open request: {msg:?}");
1185                    return Err(InvalidTransaction::Call.into());
1186                }
1187            }
1188
1189            let (dst_chain_id, channel_id, nonce) = (msg.src_chain_id, msg.channel_id, msg.nonce);
1190            // future nonce check is already validated by the extension
1191            // it is safe to increment the next nonce here before processing.
1192            Channels::<T>::mutate(
1193                dst_chain_id,
1194                channel_id,
1195                |maybe_channel| -> sp_runtime::DispatchResult {
1196                    let channel = maybe_channel.as_mut().ok_or(Error::<T>::MissingChannel)?;
1197                    channel.next_inbox_nonce = nonce
1198                        .checked_add(Nonce::one())
1199                        .ok_or(DispatchError::Arithmetic(ArithmeticError::Overflow))?;
1200                    Ok(())
1201                },
1202            )
1203                .map_err(|err| {
1204                    log::error!(
1205                        "Failed to increment the next relay message nonce for Chain[{dst_chain_id:?}] with Channel[{channel_id:?}]: {err:?}"
1206                    );
1207                    InvalidTransaction::Custom(crate::verification_errors::NEXT_NONCE_UPDATE)
1208                })?;
1209
1210            Self::deposit_event(Event::InboxMessage {
1211                chain_id: msg.src_chain_id,
1212                channel_id: msg.channel_id,
1213                nonce: msg.nonce,
1214            });
1215            Inbox::<T>::put(msg);
1216            Ok(())
1217        }
1218
1219        pub fn validate_relay_message_response(
1220            xdm: &CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
1221            consensus_state_root: StateRootOf<T>,
1222        ) -> Result<ValidatedRelayMessage<T>, TransactionValidityError> {
1223            // channel should be open and message should be present in outbox
1224            let next_nonce =
1225                match Channels::<T>::get(xdm.src_chain_id, xdm.channel_id) {
1226                    // unknown channel. return
1227                    None => {
1228                        log::error!("Unexpected inbox message response: {xdm:?}",);
1229                        return Err(InvalidTransaction::Call.into());
1230                    }
1231                    Some(channel) => match channel.latest_response_received_message_nonce {
1232                        None => Nonce::zero(),
1233                        Some(last_nonce) => last_nonce.checked_add(Nonce::one()).ok_or(
1234                            InvalidTransaction::Custom(
1235                                crate::verification_errors::XDM_NONCE_OVERFLOW,
1236                            ),
1237                        )?,
1238                    },
1239                };
1240
1241            // derive the key as stored on the src_chain.
1242            let key = StorageKey(
1243                T::StorageKeys::inbox_responses_storage_key(
1244                    xdm.src_chain_id,
1245                    (T::SelfChainId::get(), xdm.channel_id, xdm.nonce),
1246                )
1247                .ok_or(UnknownTransaction::CannotLookup)?,
1248            );
1249
1250            // verify, decode, and store the message
1251            let msg = Self::do_verify_xdm(next_nonce, key, consensus_state_root, xdm)?;
1252
1253            // Reject stale message
1254            if msg.nonce.cmp(&next_nonce) == Ordering::Less {
1255                return Err(InvalidTransaction::Stale.into());
1256            }
1257
1258            let validated_relay_msg = ValidatedRelayMessage {
1259                message: msg,
1260                next_nonce,
1261                // not applicable in relay message response, default should be fine here
1262                should_init_channel: false,
1263            };
1264
1265            Ok(validated_relay_msg)
1266        }
1267
1268        pub(crate) fn pre_dispatch_relay_message_response(
1269            msg: Message<BalanceOf<T>>,
1270        ) -> Result<(), TransactionValidityError> {
1271            // future nonce check is already validated by the extension
1272            // it is safe to increment the next nonce here before processing.
1273            let (dst_chain_id, channel_id, nonce) = (msg.src_chain_id, msg.channel_id, msg.nonce);
1274            Channels::<T>::mutate(
1275                dst_chain_id,
1276                channel_id,
1277                |maybe_channel| -> sp_runtime::DispatchResult {
1278                    let channel = maybe_channel.as_mut().ok_or(Error::<T>::MissingChannel)?;
1279                    channel.latest_response_received_message_nonce = Some(nonce);
1280                    Ok(())
1281                },
1282            )
1283                .map_err(|err| { log::error!(
1284                    "Failed to increment the next relay message response nonce for Chain[{dst_chain_id:?}] with Channel[{channel_id:?}]: {err:?}",
1285                );
1286                    InvalidTransaction::Custom(crate::verification_errors::NEXT_NONCE_UPDATE)
1287                })?;
1288
1289            Self::deposit_event(Event::OutboxMessageResponse {
1290                chain_id: msg.src_chain_id,
1291                channel_id: msg.channel_id,
1292                nonce: msg.nonce,
1293            });
1294
1295            OutboxResponses::<T>::put(msg);
1296            Ok(())
1297        }
1298
1299        pub(crate) fn do_verify_xdm(
1300            next_nonce: Nonce,
1301            storage_key: StorageKey,
1302            consensus_state_root: StateRootOf<T>,
1303            xdm: &CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
1304        ) -> Result<Message<BalanceOf<T>>, TransactionValidityError> {
1305            // channel should be either already be created or match the next channelId for chain.
1306            let next_channel_id = NextChannelId::<T>::get(xdm.src_chain_id);
1307            ensure!(
1308                xdm.channel_id <= next_channel_id,
1309                InvalidTransaction::Custom(crate::verification_errors::INVALID_CHANNEL)
1310            );
1311
1312            // verify nonce
1313            // nonce should be either be next or in future.
1314            ensure!(
1315                xdm.nonce >= next_nonce,
1316                InvalidTransaction::Custom(crate::verification_errors::INVALID_NONCE)
1317            );
1318
1319            // if the message is from domain, verify domain confirmation proof
1320            let state_root = if let Some(domain_proof) = xdm.proof.domain_proof().clone()
1321                && let Some(domain_id) = xdm.src_chain_id.maybe_domain_chain()
1322            {
1323                let confirmed_domain_block_storage_key =
1324                    T::StorageKeys::confirmed_domain_block_storage_key(domain_id)
1325                        .ok_or(UnknownTransaction::CannotLookup)?;
1326
1327                *StorageProofVerifier::<T::Hashing>::get_decoded_value::<
1328                    sp_domains::execution_receipt::ExecutionReceipt<
1329                        BlockNumberFor<T>,
1330                        T::Hash,
1331                        BlockNumberFor<T>,
1332                        T::Hash,
1333                        BalanceOf<T>,
1334                    >,
1335                >(
1336                    &consensus_state_root,
1337                    domain_proof,
1338                    StorageKey(confirmed_domain_block_storage_key),
1339                )
1340                .map_err(|err| {
1341                    log::error!(
1342                        "Failed to verify storage proof for confirmed Domain block: {err:?}",
1343                    );
1344                    TransactionValidityError::Invalid(InvalidTransaction::BadProof)
1345                })?
1346                .final_state_root()
1347            } else {
1348                consensus_state_root
1349            };
1350
1351            // verify and decode the message
1352            let msg =
1353                StorageProofVerifier::<T::Hashing>::get_decoded_value::<Message<BalanceOf<T>>>(
1354                    &state_root,
1355                    xdm.proof.message_proof(),
1356                    storage_key,
1357                )
1358                .map_err(|err| {
1359                    log::error!("Failed to verify storage proof for message: {err:?}");
1360                    TransactionValidityError::Invalid(InvalidTransaction::BadProof)
1361                })?;
1362
1363            Ok(msg)
1364        }
1365
1366        pub fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1367            Outbox::<T>::hashed_key_for(message_key)
1368        }
1369
1370        pub fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1371            InboxResponses::<T>::hashed_key_for(message_key)
1372        }
1373
1374        pub fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1375            Channels::<T>::hashed_key_for(chain_id, channel_id)
1376        }
1377
1378        pub fn domain_chains_allowlist_update(
1379            domain_id: DomainId,
1380        ) -> Option<DomainAllowlistUpdates> {
1381            DomainChainAllowlistUpdate::<T>::get(domain_id).filter(|updates| !updates.is_empty())
1382        }
1383
1384        pub fn domain_allow_list_update_storage_key(domain_id: DomainId) -> Vec<u8> {
1385            DomainChainAllowlistUpdate::<T>::hashed_key_for(domain_id)
1386        }
1387
1388        pub fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1389            UpdatedChannels::<T>::get()
1390        }
1391
1392        pub fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1393            Channels::<T>::iter_keys().collect()
1394        }
1395
1396        pub fn channels_and_states() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1397            let keys: Vec<(ChainId, ChannelId)> = Channels::<T>::iter_keys().collect();
1398            keys.into_iter()
1399                .filter_map(|(chain_id, channel_id)| {
1400                    Channels::<T>::get(chain_id, channel_id).map(|channel| {
1401                        let state = channel.state;
1402                        let state_with_nonce = match state {
1403                            ChannelState::Initiated => ChannelStateWithNonce::Initiated,
1404                            ChannelState::Open => ChannelStateWithNonce::Open,
1405                            ChannelState::Closed => ChannelStateWithNonce::Closed {
1406                                next_outbox_nonce: channel.next_outbox_nonce,
1407                                next_inbox_nonce: channel.next_inbox_nonce,
1408                            },
1409                        };
1410
1411                        (chain_id, channel_id, state_with_nonce)
1412                    })
1413                })
1414                .collect()
1415        }
1416
1417        pub fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1418            Channels::<T>::get(chain_id, channel_id).map(|channel| {
1419                let last_inbox_nonce = channel.next_inbox_nonce.checked_sub(U256::one());
1420                ChannelNonce {
1421                    relay_msg_nonce: last_inbox_nonce,
1422                    relay_response_msg_nonce: channel.latest_response_received_message_nonce,
1423                }
1424            })
1425        }
1426
1427        pub fn store_inbox_fee(
1428            src_chain_id: ChainId,
1429            message_id: MessageId,
1430            inbox_fees: BalanceOf<T>,
1431        ) -> DispatchResult {
1432            InboxFeesOnHold::<T>::mutate(|inbox_fees_on_hold| {
1433                *inbox_fees_on_hold = inbox_fees_on_hold
1434                    .checked_add(&inbox_fees)
1435                    .ok_or(Error::<T>::BalanceOverflow)?;
1436
1437                // If the `imbalance` is dropped without consuming it will reduce the total issuance by
1438                // the same amount as we issued here, thus we need to manually `mem::forget` it.
1439                let imbalance = T::Currency::issue(inbox_fees);
1440                core::mem::forget(imbalance);
1441
1442                Ok::<(), Error<T>>(())
1443            })?;
1444
1445            InboxFee::<T>::insert((src_chain_id, message_id), inbox_fees);
1446
1447            // Note `dst_chain_fee` as transfer in
1448            if !T::NoteChainTransfer::note_transfer_in(inbox_fees, src_chain_id) {
1449                return Err(Error::<T>::FailedToNoteTransferIn.into());
1450            }
1451
1452            Ok(())
1453        }
1454
1455        pub fn store_outbox_fee(
1456            dst_chain_id: ChainId,
1457            message_id: MessageId,
1458            outbox_fees: BalanceOf<T>,
1459            inbox_fees: BalanceOf<T>,
1460        ) -> DispatchResult {
1461            OutboxFeesOnHold::<T>::mutate(|outbox_fees_on_hold| {
1462                *outbox_fees_on_hold = outbox_fees_on_hold
1463                    .checked_add(&outbox_fees)
1464                    .ok_or(Error::<T>::BalanceOverflow)?;
1465
1466                // If the `imbalance` is dropped without consuming it will reduce the total issuance by
1467                // the same amount as we issued here, thus we need to manually `mem::forget` it.
1468                let imbalance = T::Currency::issue(outbox_fees);
1469                core::mem::forget(imbalance);
1470
1471                Ok::<(), Error<T>>(())
1472            })?;
1473
1474            OutboxFee::<T>::insert((dst_chain_id, message_id), outbox_fees);
1475
1476            // Note `dst_chain_fee` as transfer out
1477            if !T::NoteChainTransfer::note_transfer_out(inbox_fees, dst_chain_id) {
1478                return Err(Error::<T>::FailedToNoteTransferOut.into());
1479            }
1480
1481            Ok(())
1482        }
1483    }
1484}
1485
1486impl<T> Pallet<T>
1487where
1488    T: Config + CreateUnsigned<Call<T>>,
1489{
1490    pub fn outbox_message_unsigned(
1491        msg: CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
1492    ) -> Option<T::Extrinsic> {
1493        let call = Call::relay_message { msg };
1494        Some(T::create_unsigned(call.into()))
1495    }
1496
1497    pub fn inbox_response_message_unsigned(
1498        msg: CrossDomainMessage<BlockNumberFor<T>, T::Hash, T::MmrHash>,
1499    ) -> Option<T::Extrinsic> {
1500        let call = Call::relay_message_response { msg };
1501        Some(T::create_unsigned(call.into()))
1502    }
1503
1504    /// Returns the first outbox message nonce that should be relayed to the dst_chain.
1505    pub fn first_outbox_message_nonce_to_relay(
1506        dst_chain_id: ChainId,
1507        channel_id: ChannelId,
1508        from_nonce: Nonce,
1509    ) -> Option<Nonce> {
1510        Self::first_relay_message(
1511            dst_chain_id,
1512            channel_id,
1513            from_nonce,
1514            Outbox::<T>::contains_key,
1515        )
1516    }
1517
1518    /// Returns the first inbox response message nonce that should be relayed to the dst_chain.
1519    pub fn first_inbox_message_response_nonce_to_relay(
1520        dst_chain_id: ChainId,
1521        channel_id: ChannelId,
1522        from_nonce: Nonce,
1523    ) -> Option<Nonce> {
1524        Self::first_relay_message(
1525            dst_chain_id,
1526            channel_id,
1527            from_nonce,
1528            InboxResponses::<T>::contains_key,
1529        )
1530    }
1531
1532    fn first_relay_message<Check>(
1533        dst_chain_id: ChainId,
1534        channel_id: ChannelId,
1535        from_nonce: Nonce,
1536        check: Check,
1537    ) -> Option<Nonce>
1538    where
1539        Check: Fn((ChainId, ChannelId, Nonce)) -> bool,
1540    {
1541        let mut nonce = from_nonce;
1542        let to_nonce = from_nonce.saturating_add(MAX_FUTURE_ALLOWED_NONCES.into());
1543        while nonce <= to_nonce {
1544            if check((dst_chain_id, channel_id, nonce)) {
1545                return Some(nonce);
1546            }
1547
1548            nonce = nonce.saturating_add(Nonce::one())
1549        }
1550
1551        None
1552    }
1553}
1554
1555impl<T: Config> sp_domains::DomainBundleSubmitted for Pallet<T> {
1556    fn domain_bundle_submitted(domain_id: DomainId) {
1557        // NOTE: clear the updates leave an empty value but does not delete the value for the
1558        // domain completely because in the invalid extrinsic root fraud proof the prover need
1559        // to generate a proof-of-empty-value for the domain.
1560        DomainChainAllowlistUpdate::<T>::mutate(domain_id, |maybe_updates| {
1561            if let Some(updates) = maybe_updates {
1562                updates.clear();
1563            }
1564        });
1565    }
1566}
1567
1568impl<T: Config> sp_domains::OnDomainInstantiated for Pallet<T> {
1569    fn on_domain_instantiated(domain_id: DomainId) {
1570        DomainChainAllowlistUpdate::<T>::insert(domain_id, DomainAllowlistUpdates::default());
1571    }
1572}