1#![cfg_attr(not(feature = "std"), no_std)]
19#![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
56const XDM_TRANSACTION_LONGEVITY: u64 = 10;
59
60pub(crate) mod verification_errors {
62 pub(crate) const INVALID_NONCE: u8 = 201;
66 pub(crate) const XDM_NONCE_OVERFLOW: u8 = 202;
68 pub(crate) const INVALID_CHANNEL: u8 = 203;
70 pub(crate) const IN_FUTURE_NONCE: u8 = 204;
71 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 Ok,
79 Err(DispatchError),
81}
82
83#[derive(
85 PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DecodeWithMemTracking,
86)]
87pub enum RawOrigin {
88 ValidatedUnsigned,
89}
90
91pub 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#[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#[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo, Copy)]
139pub(crate) enum CloseChannelBy<AccountId> {
140 Owner(AccountId),
141 Sudo,
142}
143
144pub trait HoldIdentifier<T: Config> {
146 fn messenger_channel() -> FungibleHoldId<T>;
147}
148
149const 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 type SelfChainId: Get<ChainId>;
200 fn get_endpoint_handler(endpoint: &Endpoint)
202 -> Option<Box<dyn EndpointHandler<MessageId>>>;
203 type Currency: Mutate<Self::AccountId>
205 + InspectHold<Self::AccountId>
206 + MutateHold<Self::AccountId>
207 + Balanced<Self::AccountId>;
208 type WeightInfo: WeightInfo;
210 type WeightToFee: WeightToFee<Balance = BalanceOf<Self>>;
212 type AdjustedWeightToFee: WeightToFee<Balance = BalanceOf<Self>>;
215 #[pallet::constant]
218 type FeeMultiplier: Get<u32>;
219 type OnXDMRewards: OnXDMRewards<BalanceOf<Self>>;
221 type MmrHash: Parameter + Member + Default + Clone;
223 type MmrProofVerifier: MmrProofVerifier<Self::MmrHash, BlockNumberFor<Self>, StateRootOf<Self>>;
225 type StorageKeys: StorageKeys;
227 type DomainOwner: DomainOwner<Self::AccountId>;
229 type HoldIdentifier: HoldIdentifier<Self>;
231 #[pallet::constant]
233 type ChannelReserveFee: Get<BalanceOf<Self>>;
234 #[pallet::constant]
237 type ChannelInitReservePortion: Get<Perbill>;
238 type DomainRegistration: DomainRegistration;
240 #[pallet::constant]
242 type MaxOutgoingMessages: Get<u32>;
243 type MessengerOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ()>;
245 type NoteChainTransfer: NoteChainTransfer<BalanceOf<Self>>;
247 type ExtensionWeightInfo: ExtensionWeightInfo;
249 }
250
251 #[pallet::pallet]
253 #[pallet::without_storage_info]
254 #[pallet::storage_version(STORAGE_VERSION)]
255 pub struct Pallet<T>(_);
256
257 #[pallet::storage]
259 #[pallet::getter(fn next_channel_id)]
260 pub(super) type NextChannelId<T: Config> =
261 StorageMap<_, Identity, ChainId, ChannelId, ValueQuery>;
262
263 #[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 #[pallet::storage]
280 #[pallet::getter(fn inbox)]
281 pub(super) type Inbox<T: Config> = StorageValue<_, Message<BalanceOf<T>>, OptionQuery>;
282
283 #[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 #[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 #[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 #[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 #[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 #[pallet::storage]
321 #[pallet::getter(fn outbox_responses)]
322 pub(super) type OutboxResponses<T: Config> =
323 StorageValue<_, Message<BalanceOf<T>>, OptionQuery>;
324
325 #[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 #[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 #[pallet::storage]
339 #[pallet::getter(fn chain_allowlist)]
340 pub(super) type ChainAllowlist<T: Config> = StorageValue<_, BTreeSet<ChainId>, ValueQuery>;
341
342 #[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 #[pallet::storage]
353 pub(super) type UpdatedChannels<T: Config> =
354 StorageValue<_, BTreeSet<(ChainId, ChannelId)>, ValueQuery>;
355
356 #[pallet::storage]
363 pub(super) type InboxFeesOnHold<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
364
365 #[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::event]
379 #[pallet::generate_deposit(pub (super) fn deposit_event)]
380 pub enum Event<T: Config> {
381 ChannelInitiated {
383 chain_id: ChainId,
385 channel_id: ChannelId,
387 },
388
389 ChannelClosed {
391 chain_id: ChainId,
393 channel_id: ChannelId,
395 },
396
397 ChannelOpen {
399 chain_id: ChainId,
401 channel_id: ChannelId,
403 },
404
405 OutboxMessage {
407 chain_id: ChainId,
408 channel_id: ChannelId,
409 nonce: Nonce,
410 },
411
412 OutboxMessageResponse {
414 chain_id: ChainId,
416 channel_id: ChannelId,
418 nonce: Nonce,
419 },
420
421 OutboxMessageResult {
423 chain_id: ChainId,
424 channel_id: ChannelId,
425 nonce: Nonce,
426 result: OutboxMessageResult,
427 },
428
429 InboxMessage {
431 chain_id: ChainId,
432 channel_id: ChannelId,
433 nonce: Nonce,
434 },
435
436 InboxMessageResponse {
438 chain_id: ChainId,
440 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 Call::update_domain_allowlist { .. } => Ok(()),
462 _ => Err(InvalidTransaction::Call.into()),
463 }
464 }
465
466 fn validate_unsigned(
468 _source: TransactionSource,
469 _call: &Self::Call,
470 ) -> TransactionValidity {
471 InvalidTransaction::Call.into()
472 }
473 }
474
475 #[pallet::error]
477 pub enum Error<T> {
478 InvalidChain,
480
481 MissingChannel,
483
484 InvalidChannelState,
486
487 NoOpenChannel,
489
490 NoMessageHandler,
492
493 OutboxFull,
495
496 InvalidMessagePayload,
498
499 InvalidMessageDestination,
501
502 MessageVerification(VerificationError),
504
505 MissingMessage,
507
508 WeightTagNotMatch,
511
512 BalanceOverflow,
514
515 BalanceUnderflow,
517
518 InvalidAllowedChain,
520
521 OperationNotAllowed,
523
524 NotDomainOwner,
526
527 ChainNotAllowed,
529
530 InsufficientBalance,
532
533 BalanceHold,
535
536 ChannelOwner,
538
539 BalanceUnlock,
541
542 InvalidChannelReserveFee,
544
545 InvalidMaxOutgoingMessages,
547
548 MessageCountOverflow,
550
551 MessageCountUnderflow,
553
554 FailedToNoteTransferIn,
556
557 FailedToNoteTransferOut,
559 }
560
561 #[pallet::call]
562 impl<T: Config> Pallet<T> {
563 #[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 let hold_id = T::HoldIdentifier::messenger_channel();
573 let amount = T::ChannelReserveFee::get();
574
575 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 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 Self::new_outbox_message(T::SelfChainId::get(), dst_chain_id, channel_id, payload)?;
603
604 Ok(())
605 }
606
607 #[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 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 #[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 #[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 #[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 #[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 #[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.into_iter().for_each(|chain_id| {
762 list.remove(&chain_id);
763 });
764
765 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 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 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 #[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 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 .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 .unwrap_or(Weight::zero())
903 }
904 MessageWeightTag::None => Weight::zero(),
905 }
906 }
907
908 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 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 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!(
1026 init_params.max_outgoing_messages >= 1u32,
1027 Error::<T>::InvalidMaxOutgoingMessages
1028 );
1029
1030 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 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 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 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 ProtocolMessageRequest::ChannelOpen(_) => maybe_channel.is_none(),
1116 ProtocolMessageRequest::ChannelClose => {
1118 if let Some(ref channel) = maybe_channel {
1119 !(channel.state == ChannelState::Closed)
1120 } else {
1121 false
1122 }
1123 }
1124 }
1125 }
1126 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 _ => false,
1140 };
1141
1142 if !is_valid_call {
1143 log::error!("Unexpected XDM message: {msg:?}",);
1144 return Err(InvalidTransaction::Call.into());
1145 }
1146
1147 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 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 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 let next_nonce =
1225 match Channels::<T>::get(xdm.src_chain_id, xdm.channel_id) {
1226 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 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 let msg = Self::do_verify_xdm(next_nonce, key, consensus_state_root, xdm)?;
1252
1253 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 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 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 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 ensure!(
1315 xdm.nonce >= next_nonce,
1316 InvalidTransaction::Custom(crate::verification_errors::INVALID_NONCE)
1317 );
1318
1319 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 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 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 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 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 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 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 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 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}