1#![cfg_attr(not(feature = "std"), no_std)]
76
77extern crate alloc;
78
79use alloc::vec::Vec;
80use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
81use frame_support::{
82 ensure,
83 traits::{Consideration, EnsureOrigin, Footprint, Get},
84};
85use polkadot_primitives::AbridgedHostConfiguration;
86use registrar_primitives::{
87 FailureReason, MessageToPara, MessageToParaV1, MessageToRelay, MessageToRelayV1, Outcome,
88 ParaId,
89};
90use scale_info::TypeInfo;
91use sp_core::H256;
92use sp_runtime::{
93 traits::{BlockNumberProvider, Saturating},
94 DispatchError, DispatchResult,
95};
96
97pub use pallet::*;
98pub use weights::WeightInfo;
99
100pub mod weights;
101
102#[cfg(feature = "runtime-benchmarks")]
103mod benchmarking;
104#[cfg(test)]
105mod mock;
106#[cfg(test)]
107mod tests;
108
109pub type ProvidedBlockNumberOf<T> =
115 <<T as Config>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
116
117pub trait SendToRelay {
119 type AccountId;
121
122 #[allow(clippy::result_unit_err)]
127 fn send(message: MessageToRelay<Self::AccountId>) -> Result<(), ()>;
128}
129
130#[cfg(feature = "std")]
131impl SendToRelay for () {
132 type AccountId = sp_runtime::AccountId32;
133
134 fn send(_message: MessageToRelay<Self::AccountId>) -> Result<(), ()> {
135 Ok(())
136 }
137}
138
139#[cfg(feature = "runtime-benchmarks")]
141pub trait BenchmarkHelper {
142 fn set_host_configuration(config: AbridgedHostConfiguration);
144}
145
146#[derive(
148 Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
149)]
150pub enum RegistrationState<Ticket, BlockNumber> {
151 Reserved,
153 Pending {
155 ticket: Option<Ticket>,
158 cancellable_at: BlockNumber,
165 message_id: u64,
167 },
168 Registered {
170 ticket: Option<Ticket>,
172 },
173 Deregistering {
181 ticket: Option<Ticket>,
183 can_retry_after: BlockNumber,
187 message_id: u64,
189 },
190}
191
192#[derive(
194 Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo, MaxEncodedLen, Debug,
195)]
196pub struct ParaInfo<AccountId, ReservationTicket, RegistrationTicket, BlockNumber> {
197 pub manager: AccountId,
199 pub reservation: Option<ReservationTicket>,
202 pub state: RegistrationState<RegistrationTicket, BlockNumber>,
204 pub locked: Option<bool>,
207}
208
209impl<AccountId, ReservationTicket, RegistrationTicket, BlockNumber>
210 ParaInfo<AccountId, ReservationTicket, RegistrationTicket, BlockNumber>
211{
212 pub fn is_locked(&self) -> bool {
214 self.locked.unwrap_or(false)
215 }
216}
217
218pub type ParaInfoOf<T> = ParaInfo<
220 <T as frame_system::Config>::AccountId,
221 <T as Config>::ReservationConsideration,
222 <T as Config>::RegistrationConsideration,
223 ProvidedBlockNumberOf<T>,
224>;
225
226#[frame_support::pallet]
227pub mod pallet {
228 use super::*;
229 use frame_support::pallet_prelude::{DispatchResult, *};
230 use frame_system::pallet_prelude::*;
231
232 #[pallet::config]
233 pub trait Config: frame_system::Config {
234 type ReservationConsideration: Consideration<Self::AccountId, Footprint>;
237
238 type RegistrationConsideration: Consideration<Self::AccountId, Footprint>;
241
242 type SendToRelay: SendToRelay<AccountId = Self::AccountId>;
244
245 type RelayOrigin: EnsureOrigin<Self::RuntimeOrigin>;
247
248 type ParachainOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ParaId>;
250
251 type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
253
254 #[pallet::constant]
259 type FirstPublicParaId: Get<ParaId>;
260
261 #[pallet::constant]
266 type MinCodeSize: Get<u32>;
267
268 type HostConfiguration: Get<Option<AbridgedHostConfiguration>>;
272
273 #[pallet::constant]
278 type PendingDeadline: Get<ProvidedBlockNumberOf<Self>>;
279
280 type BlockNumberProvider: BlockNumberProvider;
286
287 type WeightInfo: WeightInfo;
289
290 #[cfg(feature = "runtime-benchmarks")]
292 type BenchmarkHelper: BenchmarkHelper;
293 }
294
295 #[pallet::pallet]
296 pub struct Pallet<T>(_);
297
298 #[pallet::composite_enum]
300 pub enum HoldReason {
301 #[codec(index = 0)]
303 ParaIdReservation,
304 #[codec(index = 1)]
306 Registration,
307 }
308
309 #[pallet::storage]
311 pub type NextFreeParaId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
312
313 #[pallet::storage]
318 pub type NextMessageId<T: Config> = StorageValue<_, u64, ValueQuery>;
319
320 #[pallet::storage]
322 pub type Paras<T: Config> = StorageMap<_, Blake2_128Concat, ParaId, ParaInfoOf<T>>;
323
324 #[pallet::event]
325 #[pallet::generate_deposit(pub(super) fn deposit_event)]
326 pub enum Event<T: Config> {
327 Reserved { para_id: ParaId, who: T::AccountId },
329 RegisterRequested { para_id: ParaId, message_id: u64, manager: T::AccountId },
331 Registered { para_id: ParaId, message_id: u64, manager: T::AccountId },
333 RegistrationFailed {
335 para_id: ParaId,
336 message_id: u64,
337 manager: T::AccountId,
338 reason: FailureReason,
339 },
340 CancelRequested { para_id: ParaId, message_id: u64, manager: T::AccountId },
343 RegistrationCancelled { para_id: ParaId, message_id: u64, manager: T::AccountId },
345 ReservationDropped { para_id: ParaId, manager: T::AccountId },
347 DeregisterRequested { para_id: ParaId, message_id: u64, manager: T::AccountId },
350 Deregistered { para_id: ParaId, message_id: u64, manager: T::AccountId },
352 DeregistrationFailed {
354 para_id: ParaId,
355 message_id: u64,
356 manager: T::AccountId,
357 reason: FailureReason,
358 },
359 ParaLocked { para_id: ParaId },
361 ParaUnlocked { para_id: ParaId },
363 CodeUpgradeRequested { para_id: ParaId, message_id: u64, code_hash: H256 },
365 CodeUpgradeAuthorized { para_id: ParaId, message_id: u64, expire_at: u32 },
367 CodeUpgradeFailed { para_id: ParaId, message_id: u64, reason: FailureReason },
369 CodeUpgradeScheduled { para_id: ParaId, message_id: u64 },
371 Unexpected(UnexpectedKind),
373 HeadUpdateRequested { para_id: ParaId, message_id: u64 },
375 HeadUpdated { para_id: ParaId, message_id: u64 },
377 HeadUpdateFailed { para_id: ParaId, message_id: u64, reason: FailureReason },
379 }
380
381 #[derive(
384 Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
385 )]
386 pub enum UnexpectedKind {
387 RegisterResponseForUnknownPara { para_id: ParaId, message_id: u64 },
389 RegisterResponseNotPending { para_id: ParaId, message_id: u64 },
391 HeadNotedForUnknownPara { para_id: ParaId },
393 CancelResponseForUnknownPara { para_id: ParaId, message_id: u64 },
395 CancelRefused { para_id: ParaId, message_id: u64, reason: FailureReason },
398 HeadNotedForUnregisteredPara { para_id: ParaId },
400 DeregisterResponseForUnknownPara { para_id: ParaId, message_id: u64 },
402 DeregisterResponseNotDeregistering { para_id: ParaId, message_id: u64 },
404 StaleResponse { para_id: ParaId, message_id: u64, expected: u64 },
406 ResponseNeverArrived { para_id: ParaId, message_id: u64 },
408 DepositNotReleased { para_id: ParaId, error: DispatchError },
410 }
411
412 #[pallet::error]
413 pub enum Error<T> {
414 NotReserved,
416 NotOwner,
418 AlreadyRegistered,
420 NotPending,
422 CannotCancelYet,
424 HeadDataTooLarge,
426 CodeTooLarge,
428 CodeTooSmall,
430 SendFailed,
432 NoFreeParaId,
434 ParaLocked,
436 AlreadyLocked,
438 NotLocked,
440 NotRegistered,
442 Unimplemented,
444 CannotRetryYet,
446 SystemParaId,
448 NoHostConfiguration,
450 }
451
452 #[pallet::hooks]
453 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
454 #[cfg(feature = "try-runtime")]
455 fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
456 Self::do_try_state()
457 }
458 }
459
460 #[pallet::call]
461 impl<T: Config> Pallet<T> {
462 #[pallet::call_index(0)]
466 #[pallet::weight(T::WeightInfo::receive())]
467 pub fn receive(origin: OriginFor<T>, message: MessageToPara) -> DispatchResult {
468 T::RelayOrigin::ensure_origin_or_root(origin)?;
469
470 match message {
471 MessageToPara::V1(MessageToParaV1::RegisterResponse {
472 para_id,
473 message_id,
474 outcome,
475 }) => Self::on_register_response(para_id, message_id, outcome),
476 MessageToPara::V1(MessageToParaV1::CancelResponse {
477 para_id,
478 message_id,
479 outcome,
480 }) => Self::on_cancel_response(para_id, message_id, outcome),
481 MessageToPara::V1(MessageToParaV1::DeregisterResponse {
482 para_id,
483 message_id,
484 outcome,
485 }) => Self::on_deregister_response(para_id, message_id, outcome),
486 MessageToPara::V1(MessageToParaV1::CodeUpgradeResponse {
487 para_id,
488 message_id,
489 outcome,
490 }) => Self::on_code_upgrade_response(para_id, message_id, outcome),
491 MessageToPara::V1(MessageToParaV1::CodeUpgradeScheduled {
492 para_id,
493 message_id,
494 }) => Self::on_code_upgrade_scheduled(para_id, message_id),
495 MessageToPara::V1(MessageToParaV1::SetHeadResponse {
496 para_id,
497 message_id,
498 outcome,
499 }) => Self::on_set_head_response(para_id, message_id, outcome),
500 MessageToPara::V1(MessageToParaV1::HeadNoted { para_id }) => {
501 Self::on_head_noted(para_id)
502 },
503 }
504 }
505
506 #[pallet::call_index(1)]
511 #[pallet::weight(T::WeightInfo::reserve())]
512 pub fn reserve(origin: OriginFor<T>) -> DispatchResult {
513 let who = ensure_signed(origin)?;
514
515 let para_id = NextFreeParaId::<T>::get().max(T::FirstPublicParaId::get());
516 let next = para_id.checked_add(1).ok_or(Error::<T>::NoFreeParaId)?;
517 ensure!(!Paras::<T>::contains_key(para_id), Error::<T>::AlreadyRegistered);
518
519 let reservation =
520 T::ReservationConsideration::new(&who, Self::reservation_footprint())?;
521
522 Paras::<T>::insert(
523 para_id,
524 ParaInfo {
525 manager: who.clone(),
526 reservation: Some(reservation),
527 state: RegistrationState::Reserved,
528 locked: None,
529 },
530 );
531 NextFreeParaId::<T>::put(next);
532
533 Self::deposit_event(Event::Reserved { para_id, who });
534 Ok(())
535 }
536
537 #[pallet::call_index(2)]
552 #[pallet::weight(T::WeightInfo::register(genesis_head.len() as u32))]
553 pub fn register(
554 origin: OriginFor<T>,
555 para_id: ParaId,
556 genesis_head: Vec<u8>,
557 code_len: u32,
558 code_hash: H256,
559 ) -> DispatchResult {
560 let who = ensure_signed(origin)?;
561 ensure!(!Self::is_system(para_id), Error::<T>::SystemParaId);
562
563 let info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
564 ensure!(info.manager == who, Error::<T>::NotOwner);
565
566 Self::do_register(para_id, info, genesis_head, code_len, code_hash, false)
567 }
568
569 #[pallet::call_index(3)]
585 #[pallet::weight(T::WeightInfo::cancel_registration())]
586 pub fn cancel_registration(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
587 let who = ensure_signed(origin)?;
588
589 let mut info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
590 ensure!(info.manager == who, Error::<T>::NotOwner);
591 let RegistrationState::Pending { ticket, cancellable_at, message_id: awaited } =
592 info.state
593 else {
594 return Err(Error::<T>::NotPending.into());
595 };
596 let now = T::BlockNumberProvider::current_block_number();
597 ensure!(now >= cancellable_at, Error::<T>::CannotCancelYet);
598
599 Self::report_unexpected(UnexpectedKind::ResponseNeverArrived {
602 para_id,
603 message_id: awaited,
604 });
605
606 let message_id = Self::next_message_id();
609 info.state = RegistrationState::Pending {
610 ticket,
611 cancellable_at: now.saturating_add(T::PendingDeadline::get()),
612 message_id,
613 };
614 Paras::<T>::insert(para_id, info);
615
616 T::SendToRelay::send(MessageToRelay::V1(MessageToRelayV1::CancelRegistration {
618 para_id,
619 message_id,
620 }))
621 .map_err(|()| Error::<T>::SendFailed)?;
622
623 Self::deposit_event(Event::CancelRequested { para_id, message_id, manager: who });
624 Ok(())
625 }
626
627 #[pallet::call_index(4)]
629 #[pallet::weight(T::WeightInfo::add_lock())]
630 pub fn add_lock(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
631 let mut info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
632 Self::ensure_root_para_or_manager(origin, para_id, &info)?;
633 ensure!(!info.is_locked(), Error::<T>::AlreadyLocked);
634 ensure!(
635 matches!(info.state, RegistrationState::Registered { .. }),
636 Error::<T>::NotRegistered
637 );
638
639 info.locked = Some(true);
640 Paras::<T>::insert(para_id, info);
641
642 Self::deposit_event(Event::ParaLocked { para_id });
643 Ok(())
644 }
645
646 #[pallet::call_index(5)]
650 #[pallet::weight(T::WeightInfo::remove_lock())]
651 pub fn remove_lock(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
652 Self::ensure_root_or_para(origin, para_id)?;
653 let mut info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
654 ensure!(info.is_locked(), Error::<T>::NotLocked);
655
656 info.locked = Some(false);
657 Paras::<T>::insert(para_id, info);
658
659 Self::deposit_event(Event::ParaUnlocked { para_id });
660 Ok(())
661 }
662
663 #[pallet::call_index(6)]
671 #[pallet::weight(
672 T::WeightInfo::deregister_reserved()
673 .max(T::WeightInfo::deregister_registered())
674 .max(T::WeightInfo::deregister_retry())
675 )]
676 pub fn deregister(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
677 let mut info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
678 Self::ensure_root_para_or_manager(origin, para_id, &info)?;
679
680 let manager = info.manager.clone();
681 let now = T::BlockNumberProvider::current_block_number();
682 let ticket = match info.state {
683 RegistrationState::Reserved => {
685 if let Some(reservation) = info.reservation {
686 reservation.drop(&manager)?;
687 }
688 Paras::<T>::remove(para_id);
689 Self::deposit_event(Event::ReservationDropped { para_id, manager });
690 return Ok(());
691 },
692 RegistrationState::Pending { .. } => return Err(Error::<T>::NotRegistered.into()),
693 RegistrationState::Registered { ticket } => ticket,
694 RegistrationState::Deregistering {
695 ticket,
696 can_retry_after,
697 message_id: awaited,
698 } => {
699 ensure!(now >= can_retry_after, Error::<T>::CannotRetryYet);
700 Self::report_unexpected(UnexpectedKind::ResponseNeverArrived {
701 para_id,
702 message_id: awaited,
703 });
704 ticket
705 },
706 };
707
708 let message_id = Self::next_message_id();
709 info.state = RegistrationState::Deregistering {
710 ticket,
711 can_retry_after: now.saturating_add(T::PendingDeadline::get()),
712 message_id,
713 };
714 Paras::<T>::insert(para_id, info);
715
716 T::SendToRelay::send(MessageToRelay::V1(MessageToRelayV1::Deregister {
718 para_id,
719 message_id,
720 }))
721 .map_err(|()| Error::<T>::SendFailed)?;
722
723 Self::deposit_event(Event::DeregisterRequested { para_id, message_id, manager });
724 Ok(())
725 }
726
727 #[pallet::call_index(7)]
734 #[pallet::weight(T::WeightInfo::schedule_code_upgrade())]
735 pub fn schedule_code_upgrade(
736 origin: OriginFor<T>,
737 para_id: ParaId,
738 code_hash: H256,
739 code_len: u32,
740 ) -> DispatchResult {
741 let info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
742 Self::ensure_root_para_or_manager(origin, para_id, &info)?;
743 ensure!(
744 matches!(info.state, RegistrationState::Registered { .. }),
745 Error::<T>::NotRegistered
746 );
747 let config = T::HostConfiguration::get().ok_or(Error::<T>::NoHostConfiguration)?;
748 ensure!(code_len >= T::MinCodeSize::get(), Error::<T>::CodeTooSmall);
749 ensure!(code_len <= config.max_code_size, Error::<T>::CodeTooLarge);
750
751 let message_id = Self::next_message_id();
752 T::SendToRelay::send(MessageToRelay::V1(MessageToRelayV1::AuthorizeCodeUpgrade {
753 para_id,
754 message_id,
755 code_hash,
756 code_len,
757 }))
758 .map_err(|()| Error::<T>::SendFailed)?;
759
760 Self::deposit_event(Event::CodeUpgradeRequested { para_id, message_id, code_hash });
761 Ok(())
762 }
763
764 #[pallet::call_index(8)]
769 #[pallet::weight(T::WeightInfo::set_current_head(head.len() as u32))]
770 pub fn set_current_head(
771 origin: OriginFor<T>,
772 para_id: ParaId,
773 head: Vec<u8>,
774 ) -> DispatchResult {
775 let info = Paras::<T>::get(para_id).ok_or(Error::<T>::NotReserved)?;
776 Self::ensure_root_para_or_manager(origin, para_id, &info)?;
777 ensure!(
778 matches!(info.state, RegistrationState::Registered { .. }),
779 Error::<T>::NotRegistered
780 );
781
782 let config = T::HostConfiguration::get().ok_or(Error::<T>::NoHostConfiguration)?;
783 ensure!(head.len() as u32 <= config.max_head_data_size, Error::<T>::HeadDataTooLarge);
784
785 let message_id = Self::next_message_id();
786 T::SendToRelay::send(MessageToRelay::V1(MessageToRelayV1::SetCurrentHead {
787 para_id,
788 message_id,
789 head,
790 }))
791 .map_err(|()| Error::<T>::SendFailed)?;
792
793 Self::deposit_event(Event::HeadUpdateRequested { para_id, message_id });
794 Ok(())
795 }
796
797 #[pallet::call_index(9)]
807 #[pallet::weight(T::WeightInfo::force_register(genesis_head.len() as u32))]
808 pub fn force_register(
809 origin: OriginFor<T>,
810 para_id: ParaId,
811 manager: T::AccountId,
812 genesis_head: Vec<u8>,
813 code_len: u32,
814 code_hash: H256,
815 skip_deposit: bool,
816 ) -> DispatchResult {
817 T::ForceOrigin::ensure_origin(origin)?;
818 let skip_deposit = skip_deposit || Self::is_system(para_id);
819
820 let info = match Paras::<T>::get(para_id) {
821 Some(info) => {
822 ensure!(info.manager == manager, Error::<T>::NotOwner);
823 ensure!(!info.is_locked(), Error::<T>::ParaLocked);
824 info
825 },
826 None => {
828 let reservation = if skip_deposit {
829 None
830 } else {
831 Some(T::ReservationConsideration::new(
832 &manager,
833 Self::reservation_footprint(),
834 )?)
835 };
836 ParaInfo {
837 manager,
838 reservation,
839 state: RegistrationState::Reserved,
840 locked: None,
841 }
842 },
843 };
844
845 Self::do_register(para_id, info, genesis_head, code_len, code_hash, skip_deposit)?;
846
847 NextFreeParaId::<T>::mutate(|next| *next = (*next).max(para_id.saturating_add(1)));
850 Ok(())
851 }
852 }
853}
854
855impl<T: Config> Pallet<T> {
856 pub fn reservation_footprint() -> Footprint {
858 Footprint::from_parts(1, 0)
859 }
860
861 pub fn registration_footprint(head_len: u32, config: &AbridgedHostConfiguration) -> Footprint {
864 Footprint::from_parts(1, head_len.saturating_add(config.max_code_size) as usize)
865 }
866
867 fn is_system(para_id: ParaId) -> bool {
869 para_id < T::FirstPublicParaId::get()
870 }
871
872 #[cfg(any(feature = "try-runtime", test))]
874 pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
875 for (para_id, info) in Paras::<T>::iter() {
876 let (reserved, ticket) = match &info.state {
877 RegistrationState::Reserved => (true, None),
878 RegistrationState::Pending { ticket, .. } |
879 RegistrationState::Registered { ticket } |
880 RegistrationState::Deregistering { ticket, .. } => (false, ticket.as_ref()),
881 };
882 if Self::is_system(para_id) {
883 ensure!(!reserved, "a system para id is left reserved");
884 ensure!(
885 info.reservation.is_none() && ticket.is_none(),
886 "a system para holds a deposit"
887 );
888 } else if info.reservation.is_none() || (!reserved && ticket.is_none()) {
889 log::warn!(target: "runtime::registrar-para", "para {para_id} is missing a deposit");
891 }
892 }
893 Ok(())
894 }
895
896 fn do_register(
898 para_id: ParaId,
899 mut info: ParaInfoOf<T>,
900 genesis_head: Vec<u8>,
901 code_len: u32,
902 code_hash: H256,
903 skip_deposit: bool,
904 ) -> DispatchResult {
905 ensure!(matches!(info.state, RegistrationState::Reserved), Error::<T>::AlreadyRegistered);
906
907 let config = T::HostConfiguration::get().ok_or(Error::<T>::NoHostConfiguration)?;
908 let head_len = genesis_head.len() as u32;
909 ensure!(head_len <= config.max_head_data_size, Error::<T>::HeadDataTooLarge);
910 ensure!(code_len >= T::MinCodeSize::get(), Error::<T>::CodeTooSmall);
911 ensure!(code_len <= config.max_code_size, Error::<T>::CodeTooLarge);
912
913 let manager = info.manager.clone();
914 let ticket = if skip_deposit {
915 None
916 } else {
917 Some(T::RegistrationConsideration::new(
918 &manager,
919 Self::registration_footprint(head_len, &config),
920 )?)
921 };
922
923 let cancellable_at = T::BlockNumberProvider::current_block_number()
924 .saturating_add(T::PendingDeadline::get());
925 let message_id = Self::next_message_id();
926 info.state = RegistrationState::Pending { ticket, cancellable_at, message_id };
927 Paras::<T>::insert(para_id, info);
928
929 T::SendToRelay::send(MessageToRelay::V1(MessageToRelayV1::Register {
931 para_id,
932 message_id,
933 manager: manager.clone(),
934 genesis_head,
935 code_hash,
936 code_len,
937 }))
938 .map_err(|()| Error::<T>::SendFailed)?;
939
940 Self::deposit_event(Event::RegisterRequested { para_id, message_id, manager });
941 Ok(())
942 }
943
944 fn ensure_root_para_or_manager(
946 origin: frame_system::pallet_prelude::OriginFor<T>,
947 para_id: ParaId,
948 info: &ParaInfoOf<T>,
949 ) -> DispatchResult {
950 if let Ok(id) = T::ParachainOrigin::ensure_origin(origin.clone()) {
951 ensure!(id == para_id, Error::<T>::NotOwner);
952 return Ok(());
953 }
954 if let Ok(who) = frame_system::ensure_signed(origin.clone()) {
955 ensure!(who == info.manager, Error::<T>::NotOwner);
956 ensure!(!info.is_locked(), Error::<T>::ParaLocked);
957 return Ok(());
958 }
959 frame_system::ensure_root(origin)?;
960 Ok(())
961 }
962
963 fn ensure_root_or_para(
965 origin: frame_system::pallet_prelude::OriginFor<T>,
966 para_id: ParaId,
967 ) -> DispatchResult {
968 if frame_system::ensure_root(origin.clone()).is_ok() {
969 return Ok(());
970 }
971 let id = T::ParachainOrigin::ensure_origin(origin)?;
972 ensure!(id == para_id, Error::<T>::NotOwner);
973 Ok(())
974 }
975
976 fn store_reserved(para_id: ParaId, info: ParaInfoOf<T>) {
979 if Self::is_system(para_id) {
980 Self::release_or_report(info.reservation, &info.manager, para_id);
981 Paras::<T>::remove(para_id);
982 } else {
983 Paras::<T>::insert(para_id, info);
984 }
985 }
986
987 fn report_unexpected(kind: UnexpectedKind) {
989 log::error!(target: "runtime::registrar-para", "unexpected: {kind:?}");
990 Self::deposit_event(Event::Unexpected(kind));
991 }
992
993 fn release_or_report<C: Consideration<T::AccountId, Footprint>>(
995 ticket: Option<C>,
996 who: &T::AccountId,
997 para_id: ParaId,
998 ) {
999 let Some(ticket) = ticket else { return };
1000 if let Err(error) = ticket.drop(who) {
1001 Self::report_unexpected(UnexpectedKind::DepositNotReleased { para_id, error });
1002 }
1003 }
1004
1005 fn next_message_id() -> u64 {
1007 NextMessageId::<T>::mutate(|next| {
1008 let id = *next;
1009 *next = next.wrapping_add(1);
1010 id
1011 })
1012 }
1013
1014 fn on_register_response(para_id: ParaId, message_id: u64, outcome: Outcome) -> DispatchResult {
1020 let Some(mut info) = Paras::<T>::get(para_id) else {
1021 Self::report_unexpected(UnexpectedKind::RegisterResponseForUnknownPara {
1022 para_id,
1023 message_id,
1024 });
1025 return Ok(());
1026 };
1027 let RegistrationState::Pending { ticket, message_id: expected, .. } = info.state else {
1028 Self::report_unexpected(UnexpectedKind::RegisterResponseNotPending {
1029 para_id,
1030 message_id,
1031 });
1032 return Ok(());
1033 };
1034 if message_id != expected {
1035 Self::report_unexpected(UnexpectedKind::StaleResponse {
1036 para_id,
1037 message_id,
1038 expected,
1039 });
1040 return Ok(());
1041 }
1042
1043 let manager = info.manager.clone();
1044 match outcome {
1045 Ok(()) => {
1046 info.state = RegistrationState::Registered { ticket };
1047 Paras::<T>::insert(para_id, info);
1048 Self::deposit_event(Event::Registered { para_id, message_id, manager });
1049 },
1050 Err(reason) => {
1051 Self::release_or_report(ticket, &manager, para_id);
1052 info.state = RegistrationState::Reserved;
1053 Self::store_reserved(para_id, info);
1054 Self::deposit_event(Event::RegistrationFailed {
1055 para_id,
1056 message_id,
1057 manager,
1058 reason,
1059 });
1060 },
1061 }
1062
1063 Ok(())
1064 }
1065
1066 fn on_head_noted(para_id: ParaId) -> DispatchResult {
1068 let Some(mut info) = Paras::<T>::get(para_id) else {
1069 Self::report_unexpected(UnexpectedKind::HeadNotedForUnknownPara { para_id });
1070 return Ok(());
1071 };
1072
1073 if info.locked.is_some() {
1074 return Ok(());
1075 }
1076
1077 if !matches!(info.state, RegistrationState::Registered { .. }) {
1078 Self::report_unexpected(UnexpectedKind::HeadNotedForUnregisteredPara { para_id });
1079 }
1080
1081 info.locked = Some(true);
1082 Paras::<T>::insert(para_id, info);
1083
1084 Self::deposit_event(Event::ParaLocked { para_id });
1085
1086 Ok(())
1087 }
1088
1089 fn on_cancel_response(para_id: ParaId, message_id: u64, outcome: Outcome) -> DispatchResult {
1099 let Some(mut info) = Paras::<T>::get(para_id) else {
1100 Self::report_unexpected(UnexpectedKind::CancelResponseForUnknownPara {
1101 para_id,
1102 message_id,
1103 });
1104 return Ok(());
1105 };
1106 let RegistrationState::Pending { ticket, message_id: expected, .. } = info.state else {
1107 log::debug!(
1108 target: "runtime::registrar-para",
1109 "cancel response for para {para_id} which is no longer pending, dropping",
1110 );
1111 return Ok(());
1112 };
1113 if message_id != expected {
1114 Self::report_unexpected(UnexpectedKind::StaleResponse {
1115 para_id,
1116 message_id,
1117 expected,
1118 });
1119 return Ok(());
1120 }
1121
1122 let manager = info.manager.clone();
1123 match outcome {
1124 Ok(()) => {
1125 Self::release_or_report(ticket, &manager, para_id);
1126 info.state = RegistrationState::Reserved;
1127 Self::store_reserved(para_id, info);
1128 Self::deposit_event(Event::RegistrationCancelled { para_id, message_id, manager });
1129 },
1130 Err(FailureReason::AlreadyRegistered) => {
1131 info.state = RegistrationState::Registered { ticket };
1132 Paras::<T>::insert(para_id, info);
1133 Self::deposit_event(Event::Registered { para_id, message_id, manager });
1134 },
1135 Err(reason) => {
1138 Self::report_unexpected(UnexpectedKind::CancelRefused {
1139 para_id,
1140 message_id,
1141 reason,
1142 });
1143 },
1144 }
1145
1146 Ok(())
1147 }
1148
1149 fn on_deregister_response(
1154 para_id: ParaId,
1155 message_id: u64,
1156 outcome: Outcome,
1157 ) -> DispatchResult {
1158 let Some(mut info) = Paras::<T>::get(para_id) else {
1159 Self::report_unexpected(UnexpectedKind::DeregisterResponseForUnknownPara {
1160 para_id,
1161 message_id,
1162 });
1163 return Ok(());
1164 };
1165 let RegistrationState::Deregistering { ticket, message_id: expected, .. } = info.state
1166 else {
1167 Self::report_unexpected(UnexpectedKind::DeregisterResponseNotDeregistering {
1168 para_id,
1169 message_id,
1170 });
1171 return Ok(());
1172 };
1173 if message_id != expected {
1174 Self::report_unexpected(UnexpectedKind::StaleResponse {
1175 para_id,
1176 message_id,
1177 expected,
1178 });
1179 return Ok(());
1180 }
1181
1182 let manager = info.manager.clone();
1183 match outcome {
1184 Ok(()) => {
1185 Self::release_or_report(ticket, &manager, para_id);
1186 Self::release_or_report(info.reservation, &manager, para_id);
1187 Paras::<T>::remove(para_id);
1188 Self::deposit_event(Event::Deregistered { para_id, message_id, manager });
1189 },
1190 Err(reason) => {
1191 info.state = RegistrationState::Registered { ticket };
1192 Paras::<T>::insert(para_id, info);
1193 Self::deposit_event(Event::DeregistrationFailed {
1194 para_id,
1195 message_id,
1196 manager,
1197 reason,
1198 });
1199 },
1200 }
1201
1202 Ok(())
1203 }
1204
1205 fn on_code_upgrade_response(
1207 para_id: ParaId,
1208 message_id: u64,
1209 outcome: Result<u32, FailureReason>,
1210 ) -> DispatchResult {
1211 Self::deposit_event(match outcome {
1212 Ok(expire_at) => Event::CodeUpgradeAuthorized { para_id, message_id, expire_at },
1213 Err(reason) => Event::CodeUpgradeFailed { para_id, message_id, reason },
1214 });
1215 Ok(())
1216 }
1217
1218 fn on_code_upgrade_scheduled(para_id: ParaId, message_id: u64) -> DispatchResult {
1220 Self::deposit_event(Event::CodeUpgradeScheduled { para_id, message_id });
1221 Ok(())
1222 }
1223
1224 fn on_set_head_response(para_id: ParaId, message_id: u64, outcome: Outcome) -> DispatchResult {
1226 Self::deposit_event(match outcome {
1227 Ok(()) => Event::HeadUpdated { para_id, message_id },
1228 Err(reason) => Event::HeadUpdateFailed { para_id, message_id, reason },
1229 });
1230 Ok(())
1231 }
1232}