referrerpolicy=no-referrer-when-downgrade

pallet_registrar_para/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! # Parachain registrar pallet
19//!
20//! The user-facing half of parachain registration. It hands out para ids, takes the manager's
21//! deposits as [`Consideration`] tickets, and coordinates the registration itself asynchronously
22//! with the chain that owns the parachain registry.
23//!
24//! Both directions of that coordination are abstract: requests go out through [`SendToRelay`],
25//! verdicts come back in through [`Pallet::receive`], gated by [`Config::RelayOrigin`]. Nothing
26//! here depends on XCM or on the other chain's extrinsics.
27//!
28//! ## Registration flow
29//!
30//! Registration takes two transactions on two chains. Sending a multi-megabyte validation code
31//! through the messaging layer would be wasteful, so this chain only commits to its hash and
32//! length and the blob is uploaded to the relay chain directly:
33//!
34//! 1. [`Pallet::reserve`] allocates a para id here and takes [`Config::ReservationConsideration`].
35//! 2. [`Pallet::register`] takes [`Config::RegistrationConsideration`] for the head data and a
36//!    full-sized validation code, then asks the relay chain to accept the registration. Only the
37//!    code hash and length are sent.
38//! 3. The manager uploads the validation code to the relay chain, which accepts it only if it
39//!    matches the hash and length committed to in step 2.
40//! 4. The verdict arrives back as [`Pallet::receive`], which either finalises the registration or
41//!    releases the registration deposit.
42//!
43//! ## Giving up
44//!
45//! Nothing on the relay chain times a registration out, so a request whose code never turns up
46//! waits until the manager ends it with [`Pallet::cancel_registration`]. That asks the relay chain
47//! to drop the authorization and only releases the deposit once it confirms, which is what
48//! keeps a cancellation from freeing the deposit on a para that did register after all.
49//!
50//! ## Giving up a para id
51//!
52//! [`Pallet::deregister`] on an id that is only reserved releases the reservation right away, as
53//! the relay chain never heard of it. A registered para has to be dropped on the relay chain
54//! first, so both deposits stay held until it answers. If the answer never arrives, the manager
55//! calls [`Pallet::deregister`] again.
56//!
57//! ## Forcing
58//!
59//! [`Pallet::force_register`] is the same request from [`Config::ForceOrigin`], for an id that need
60//! not have been reserved first. The manager still pays, unless the id is a system one or the
61//! origin passes `skip_deposit`. A system id whose registration falls through is dropped, not kept
62//! reserved.
63//!
64//! ## Locking
65//!
66//! [`Pallet::add_lock`] shuts the manager out of a registered para, leaving it to the para's own
67//! governance. Only root or the para itself can lift it again with [`Pallet::remove_lock`].
68//!
69//! A para is also locked the first time the relay chain reports that it produced a head, which
70//! arrives as [`MessageToParaV1::HeadNoted`]. A lock lifted with [`Pallet::remove_lock`] outranks
71//! that, so it is never re-applied.
72//!
73//! Deposits only ever live on this chain; the relay chain takes nothing.
74
75#![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
109/// Block number used for registration deadlines.
110///
111/// On a parachain, configure [`Config::BlockNumberProvider`] to
112/// `cumulus_pallet_parachain_system::RelaychainDataProvider`, so deadlines are expressed in
113/// relay-chain blocks and keep their meaning through a stall in this chain's own block production.
114pub type ProvidedBlockNumberOf<T> =
115	<<T as Config>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
116
117/// Used to send an XCM `Transact` to the registrar pallet on the remote relay chain.
118pub trait SendToRelay {
119	/// The account id used to identify a registration's manager on both chains.
120	type AccountId;
121
122	/// Send `message` to the relay chain.
123	///
124	/// `Err(())` means the message could not be handed to the transport at all. Callers are
125	/// expected to fail the whole extrinsic, so nothing is left half-done.
126	#[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/// Benchmark setup the runtime provides.
140#[cfg(feature = "runtime-benchmarks")]
141pub trait BenchmarkHelper {
142	/// Make [`Config::HostConfiguration`] return `Some(config)`.
143	fn set_host_configuration(config: AbridgedHostConfiguration);
144}
145
146/// Where a para id sits in the registration flow.
147#[derive(
148	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
149)]
150pub enum RegistrationState<Ticket, BlockNumber> {
151	/// The para id is held by its manager, but nothing is registered on the relay chain yet.
152	Reserved,
153	/// The relay chain has been asked to register this para and has not reported back.
154	Pending {
155		/// The registration's [`Consideration`] ticket, returned if the registration fails.
156		/// `None` if [`Pallet::force_register`] skipped the deposit.
157		ticket: Option<Ticket>,
158		/// The block from which the manager may give up on this registration.
159		///
160		/// Expressed in [`Config::BlockNumberProvider`] blocks. Long enough that a verdict already
161		/// on its way arrives first, so a cancellation is only ever sent for a registration that
162		/// really has gone quiet. Pushed out again by every [`Pallet::cancel_registration`], so a
163		/// cancellation that gets lost can be retried but not spammed.
164		cancellable_at: BlockNumber,
165		/// The request this state is waiting on; a response carrying any other id is stale.
166		message_id: u64,
167	},
168	/// The relay chain has onboarded this para.
169	Registered {
170		/// The registration's [`Consideration`] ticket, kept while the para is registered.
171		ticket: Option<Ticket>,
172	},
173	/// The relay chain has been asked to drop this para and has not reported back.
174	///
175	/// Both deposits stay held: only the relay chain knows whether the para really went away, and
176	/// a refusal puts it straight back to [`RegistrationState::Registered`].
177	///
178	/// There is nothing to cancel from here: if no answer turns up, the manager calls
179	/// [`Pallet::deregister`] again once `can_retry_after` has passed.
180	Deregistering {
181		/// The registration's [`Consideration`] ticket, released once the relay chain confirms.
182		ticket: Option<Ticket>,
183		/// The block from which the manager may send the [`MessageToRelayV1::Deregister`] again,
184		/// if the answer never arrived. Retrying reports the missing answer as
185		/// [`UnexpectedKind::ResponseNeverArrived`].
186		can_retry_after: BlockNumber,
187		/// The request this state is waiting on; a response carrying any other id is stale.
188		message_id: u64,
189	},
190}
191
192/// Everything this chain knows about one para id.
193#[derive(
194	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo, MaxEncodedLen, Debug,
195)]
196pub struct ParaInfo<AccountId, ReservationTicket, RegistrationTicket, BlockNumber> {
197	/// The account that reserved the para id and controls it.
198	pub manager: AccountId,
199	/// The [`Consideration`] ticket for the para id itself. `None` if
200	/// [`Pallet::force_register`] skipped the deposit.
201	pub reservation: Option<ReservationTicket>,
202	/// Where this para id sits in the registration flow.
203	pub state: RegistrationState<RegistrationTicket, BlockNumber>,
204	/// Whether the manager is locked out of controlling this para. `None` until the lock is set
205	/// for the first time, and read as unlocked.
206	pub locked: Option<bool>,
207}
208
209impl<AccountId, ReservationTicket, RegistrationTicket, BlockNumber>
210	ParaInfo<AccountId, ReservationTicket, RegistrationTicket, BlockNumber>
211{
212	/// Whether the manager is locked out of this para.
213	pub fn is_locked(&self) -> bool {
214		self.locked.unwrap_or(false)
215	}
216}
217
218/// The [`ParaInfo`] type as configured.
219pub 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		/// The cost of reserving a para id. The footprint is a single zero-sized item, so a flat
235		/// price fits.
236		type ReservationConsideration: Consideration<Self::AccountId, Footprint>;
237
238		/// The cost of a registration, on top of the reservation. The footprint is one item sized
239		/// as head data plus the relay chain's `max_code_size`, so a per-byte price fits.
240		type RegistrationConsideration: Consideration<Self::AccountId, Footprint>;
241
242		/// Sends messages to the relay chain.
243		type SendToRelay: SendToRelay<AccountId = Self::AccountId>;
244
245		/// An origin that is sure to be the relay chain's registrar pallet.
246		type RelayOrigin: EnsureOrigin<Self::RuntimeOrigin>;
247
248		/// An origin a parachain uses to act as itself, resolved to its para id.
249		type ParachainOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ParaId>;
250
251		/// The origin allowed to call [`Pallet::force_register`].
252		type ForceOrigin: EnsureOrigin<Self::RuntimeOrigin>;
253
254		/// The lowest para id this pallet will hand out.
255		///
256		/// Mirrors the relay chain's `LOWEST_PUBLIC_ID`. Ids below it are reserved for system
257		/// parachains and are not obtainable here.
258		#[pallet::constant]
259		type FirstPublicParaId: Get<ParaId>;
260
261		/// The smallest validation code the relay chain will accept.
262		///
263		/// A local mirror of the relay chain's `MIN_CODE_SIZE`, used to fail early. The relay
264		/// chain checks the real thing against its own live configuration.
265		#[pallet::constant]
266		type MinCodeSize: Get<u32>;
267
268		/// The relay chain's host configuration, `None` until this chain has received it.
269		///
270		/// On a parachain, read `cumulus_pallet_parachain_system::HostConfiguration`.
271		type HostConfiguration: Get<Option<AbridgedHostConfiguration>>;
272
273		/// How long a manager waits for the relay chain before giving up on a registration.
274		///
275		/// Measured in [`Config::BlockNumberProvider`] blocks. Should comfortably cover a round
276		/// trip, so that a verdict that is merely slow lands before anybody tries to cancel.
277		#[pallet::constant]
278		type PendingDeadline: Get<ProvidedBlockNumberOf<Self>>;
279
280		/// Source of block numbers for registration deadlines.
281		///
282		/// On a parachain this should be
283		/// `cumulus_pallet_parachain_system::RelaychainDataProvider`, so
284		/// [`Config::PendingDeadline`] is in relay-chain blocks.
285		type BlockNumberProvider: BlockNumberProvider;
286
287		/// Weight information for the extrinsics in this pallet.
288		type WeightInfo: WeightInfo;
289
290		/// Puts a [`Config::HostConfiguration`] in place for the benchmarks.
291		#[cfg(feature = "runtime-benchmarks")]
292		type BenchmarkHelper: BenchmarkHelper;
293	}
294
295	#[pallet::pallet]
296	pub struct Pallet<T>(_);
297
298	/// Hold reasons for runtimes that pay the considerations out of held funds.
299	#[pallet::composite_enum]
300	pub enum HoldReason {
301		/// Held for keeping a para id reserved.
302		#[codec(index = 0)]
303		ParaIdReservation,
304		/// Held for the head data and validation code of a registration.
305		#[codec(index = 1)]
306		Registration,
307	}
308
309	/// The next para id that [`Pallet::reserve`] will hand out.
310	#[pallet::storage]
311	pub type NextFreeParaId<T: Config> = StorageValue<_, ParaId, ValueQuery>;
312
313	/// The id the next message to the relay chain will carry.
314	///
315	/// One per message sent, echoed back in the relay chain's response, so a request, its
316	/// response and the events on both chains can be tied together.
317	#[pallet::storage]
318	pub type NextMessageId<T: Config> = StorageValue<_, u64, ValueQuery>;
319
320	/// Every para id reserved through this pallet, and what is happening with it.
321	#[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		/// A para id was reserved.
328		Reserved { para_id: ParaId, who: T::AccountId },
329		/// A registration was requested and the relay chain has been asked to accept it.
330		RegisterRequested { para_id: ParaId, message_id: u64, manager: T::AccountId },
331		/// The relay chain confirmed a registration.
332		Registered { para_id: ParaId, message_id: u64, manager: T::AccountId },
333		/// The relay chain rejected a registration. The registration consideration was returned.
334		RegistrationFailed {
335			para_id: ParaId,
336			message_id: u64,
337			manager: T::AccountId,
338			reason: FailureReason,
339		},
340		/// A manager gave up on a pending registration, and the relay chain has been asked to
341		/// drop the authorization. The consideration stays taken until it answers.
342		CancelRequested { para_id: ParaId, message_id: u64, manager: T::AccountId },
343		/// The relay chain confirmed a cancellation. The registration consideration was returned.
344		RegistrationCancelled { para_id: ParaId, message_id: u64, manager: T::AccountId },
345		/// A para id that was never registered was given up. The reservation was returned.
346		ReservationDropped { para_id: ParaId, manager: T::AccountId },
347		/// The relay chain has been asked to drop a para. Both considerations stay taken until it
348		/// answers.
349		DeregisterRequested { para_id: ParaId, message_id: u64, manager: T::AccountId },
350		/// The relay chain dropped the para. Every consideration was returned and the id is gone.
351		Deregistered { para_id: ParaId, message_id: u64, manager: T::AccountId },
352		/// The relay chain refused to drop the para. It stays registered, considerations included.
353		DeregistrationFailed {
354			para_id: ParaId,
355			message_id: u64,
356			manager: T::AccountId,
357			reason: FailureReason,
358		},
359		/// The manager is locked out of this para.
360		ParaLocked { para_id: ParaId },
361		/// The manager may control this para again.
362		ParaUnlocked { para_id: ParaId },
363		/// The relay chain has been asked to authorize a code upgrade.
364		CodeUpgradeRequested { para_id: ParaId, message_id: u64, code_hash: H256 },
365		/// The relay chain will accept the code until `expire_at`, one of its own block numbers.
366		CodeUpgradeAuthorized { para_id: ParaId, message_id: u64, expire_at: u32 },
367		/// The relay chain refused the upgrade.
368		CodeUpgradeFailed { para_id: ParaId, message_id: u64, reason: FailureReason },
369		/// The relay chain scheduled the upgrade.
370		CodeUpgradeScheduled { para_id: ParaId, message_id: u64 },
371		/// Something that should never happen did. The pallet carried on regardless.
372		Unexpected(UnexpectedKind),
373		/// The relay chain has been asked to set this para's current head.
374		HeadUpdateRequested { para_id: ParaId, message_id: u64 },
375		/// The relay chain set the head.
376		HeadUpdated { para_id: ParaId, message_id: u64 },
377		/// The relay chain refused the head.
378		HeadUpdateFailed { para_id: ParaId, message_id: u64, reason: FailureReason },
379	}
380
381	/// A defensive check that failed, reported as [`Event::Unexpected`] so it is visible on chain
382	/// and not just in the node's logs.
383	#[derive(
384		Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
385	)]
386	pub enum UnexpectedKind {
387		/// A register response for a para id this pallet does not know.
388		RegisterResponseForUnknownPara { para_id: ParaId, message_id: u64 },
389		/// A register response for a para with no registration in flight.
390		RegisterResponseNotPending { para_id: ParaId, message_id: u64 },
391		/// A head was noted for a para id this pallet does not know.
392		HeadNotedForUnknownPara { para_id: ParaId },
393		/// A cancel response for a para id this pallet does not know.
394		CancelResponseForUnknownPara { para_id: ParaId, message_id: u64 },
395		/// The relay chain refused a cancellation for a reason that is not one of the refusals
396		/// this pallet knows how to settle.
397		CancelRefused { para_id: ParaId, message_id: u64, reason: FailureReason },
398		/// A head was noted for a para that is not registered.
399		HeadNotedForUnregisteredPara { para_id: ParaId },
400		/// A deregister response for a para id this pallet does not know.
401		DeregisterResponseForUnknownPara { para_id: ParaId, message_id: u64 },
402		/// A deregister response for a para with no deregistration in flight.
403		DeregisterResponseNotDeregistering { para_id: ParaId, message_id: u64 },
404		/// A response answering a request this pallet is no longer waiting on.
405		StaleResponse { para_id: ParaId, message_id: u64, expected: u64 },
406		/// The relay chain never answered this request and the manager gave up waiting.
407		ResponseNeverArrived { para_id: ParaId, message_id: u64 },
408		/// Releasing a deposit failed while applying a relay chain answer, so it is still held.
409		DepositNotReleased { para_id: ParaId, error: DispatchError },
410	}
411
412	#[pallet::error]
413	pub enum Error<T> {
414		/// The para id has not been reserved.
415		NotReserved,
416		/// The caller does not manage this para id.
417		NotOwner,
418		/// The para id is already registered, or a registration is already in flight for it.
419		AlreadyRegistered,
420		/// There is no registration in flight for this para id.
421		NotPending,
422		/// The manager may not abandon this registration yet.
423		CannotCancelYet,
424		/// The head data is larger than the relay chain will accept.
425		HeadDataTooLarge,
426		/// The validation code is larger than the relay chain will accept.
427		CodeTooLarge,
428		/// The validation code is smaller than the relay chain will accept.
429		CodeTooSmall,
430		/// The message could not be handed to the transport.
431		SendFailed,
432		/// There are no more para ids to hand out.
433		NoFreeParaId,
434		/// The para is locked, so the manager may not act on it.
435		ParaLocked,
436		/// The para is already locked.
437		AlreadyLocked,
438		/// The para is not locked.
439		NotLocked,
440		/// The para is not registered on the relay chain.
441		NotRegistered,
442		/// The call is scaffolded but not implemented yet.
443		Unimplemented,
444		/// The manager may not ask the relay chain to drop this para again yet.
445		CannotRetryYet,
446		/// System para ids are only registered through [`Pallet::force_register`].
447		SystemParaId,
448		/// The relay chain's host configuration has not been received yet.
449		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		/// Accept a report from the relay chain's registrar pallet.
463		///
464		/// Not callable by users: the origin must be the relay chain.
465		#[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		/// Reserve the next free para id for the caller.
507		///
508		/// Takes [`Config::ReservationConsideration`]. The caller becomes the manager of the new
509		/// id and is the only account that may [`Pallet::register`] against it.
510		#[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		/// Ask the relay chain to register head data and validation code for a reserved para id.
538		///
539		/// Only `code_hash` and `code_len` are sent, never the validation code. The caller uploads
540		/// the blob to the relay chain separately, which accepts it only if it hashes to
541		/// `code_hash` and is exactly `code_len` bytes long.
542		///
543		/// ## Costs
544		///
545		/// Takes [`Config::RegistrationConsideration`] for the head data and a code of the relay
546		/// chain's `max_code_size`, on top of the para id reservation: a para pays for the largest
547		/// code it could ever have on chain, not the one it registers with. It is returned if the
548		/// relay chain rejects the registration or if the caller later abandons it.
549		///
550		/// Ids below [`Config::FirstPublicParaId`] are refused, see [`Pallet::force_register`].
551		#[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		/// Give up on a registration the relay chain never reported on.
570		///
571		/// Callable from [`Config::PendingDeadline`] blocks after the request. Nothing on the
572		/// relay chain abandons a registration on its own, so this is what ends one whose code
573		/// never turned up, and the manager pays for the round trip rather than every relay-chain
574		/// block paying for a sweep.
575		///
576		/// The deposit is not released here: the relay chain is asked to drop the authorization
577		/// first, and [`Pallet::receive`] releases the deposit when it confirms. Waiting for that
578		/// answer is the point. A registration that did go through, with a verdict that got lost on
579		/// the way here, must not have its deposit refunded, and only the relay chain knows
580		/// which of the two happened.
581		///
582		/// The para id itself stays reserved either way, so the manager can simply try again. A
583		/// system id is dropped instead, as only [`Pallet::force_register`] may register one.
584		#[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			// Getting here means the relay chain's answer to `awaited` never turned up. That should
600			// not happen, so say so on chain instead of quietly retrying.
601			Self::report_unexpected(UnexpectedKind::ResponseNeverArrived {
602				para_id,
603				message_id: awaited,
604			});
605
606			// Another deadline's grace before the manager may ask again, so a request that goes
607			// missing can be retried without the relay chain being asked once per block.
608			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			// A transport failure returns `Err` and unwinds the new deadline with it.
617			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		/// Lock a registered para, keeping the manager out of it.
628		#[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		/// Unlock a para, handing control back to the manager.
647		///
648		/// The manager is not accepted here: a lock it could lift would not be a lock.
649		#[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		/// Give up a para id, releasing every consideration held for it.
664		///
665		/// An id that is only reserved is released immediately. A registered para has to be
666		/// dropped on the relay chain first, so the considerations stay taken until it answers.
667		///
668		/// Can be called again on a para that is already deregistering, once `can_retry_after`
669		/// has passed. This resends the request.
670		#[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				// The relay chain never knew this id, so there is nobody to ask.
684				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			// A transport failure returns `Err` and unwinds the new state with it.
717			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		/// Ask the relay chain to authorize a validation code upgrade.
728		///
729		/// Root, the para itself, or its manager while unlocked. As with [`Pallet::register`] only
730		/// `code_hash` and `code_len` are sent: the caller uploads the code to the relay chain
731		/// separately, and it is accepted only if it matches both. Nothing is recorded and no
732		/// deposit is taken; the outcome comes back through [`Pallet::receive`] as an event.
733		#[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		/// Set the current head of a registered para.
765		///
766		/// Root, the para itself, or its manager while unlocked. Nothing is recorded here: the
767		/// outcome comes back through [`Pallet::receive`] as an event.
768		#[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		/// Ask the relay chain to register a para id under `manager`, on [`Config::ForceOrigin`]'s
798		/// say-so.
799		///
800		/// The relay chain's `paras_registrar::force_register`, moved here: the same checks and the
801		/// same deposits, except that the id need not have been reserved first, so the origin can
802		/// onboard an id nobody holds, the system range included.
803		///
804		/// System ids never take a deposit, as on Polkadot, and `skip_deposit` waives it for a
805		/// public id too. A reservation the manager already holds stays held.
806		#[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				// Unreserved ids are the point of this call, so take the reservation now.
827				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			// `reserve` errors rather than skipping an id it finds taken, so leaving the counter
848			// behind a forced id would brick it for good.
849			NextFreeParaId::<T>::mutate(|next| *next = (*next).max(para_id.saturating_add(1)));
850			Ok(())
851		}
852	}
853}
854
855impl<T: Config> Pallet<T> {
856	/// The footprint a para id reservation is charged for.
857	pub fn reservation_footprint() -> Footprint {
858		Footprint::from_parts(1, 0)
859	}
860
861	/// The footprint a registration is charged for: the head data plus a full-sized validation
862	/// code, whatever length the registration itself declares.
863	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	/// Whether `para_id` is in the system range, below [`Config::FirstPublicParaId`].
868	fn is_system(para_id: ParaId) -> bool {
869		para_id < T::FirstPublicParaId::get()
870	}
871
872	/// Check the pallet's storage invariants.
873	#[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				// `skip_deposit` and migrated paras may lack one, so only warn.
890				log::warn!(target: "runtime::registrar-para", "para {para_id} is missing a deposit");
891			}
892		}
893		Ok(())
894	}
895
896	/// Take the registration deposit from `info.manager` and ask the relay chain to register.
897	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		// A transport failure returns `Err` and unwinds everything above, tickets included.
930		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	/// Ensure `origin` may manage `para_id`: the para itself, its manager while unlocked, or root.
945	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	/// Ensure `origin` is root or `para_id` itself.
964	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	/// Store `info`, back to [`RegistrationState::Reserved`] after its registration fell through.
977	/// A system id is dropped instead, as only [`Pallet::force_register`] may register one.
978	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	/// Report a failed defensive check: loud in the logs, and visible on chain.
988	fn report_unexpected(kind: UnexpectedKind) {
989		log::error!(target: "runtime::registrar-para", "unexpected: {kind:?}");
990		Self::deposit_event(Event::Unexpected(kind));
991	}
992
993	/// Drop `ticket` without failing: the relay chain already acted on the answer being applied.
994	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	/// Take the id for the next message to the relay chain.
1006	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	/// Apply the relay chain's verdict on a registration.
1015	///
1016	/// A response about a para id we are not expecting one for is dropped rather than treated as a
1017	/// dispatch error: erroring here would unwind the whole incoming message for something we can
1018	/// do nothing about anyway. They are reported as [`Event::Unexpected`] instead.
1019	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	/// Lock a para the relay chain has seen produce a head.
1067	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	/// Apply the relay chain's answer to a cancellation.
1090	///
1091	/// `Ok(())` means the authorization is gone, so the deposit goes back. The one refusal is
1092	/// [`FailureReason::AlreadyRegistered`]: the code landed after all and the earlier verdict was
1093	/// simply lost, so the para is recorded as registered and the deposit stays held.
1094	///
1095	/// Unlike a register response, an answer for a para that is no longer pending is expected
1096	/// rather than unexpected: a verdict already in flight when the cancellation was sent settles
1097	/// the registration first, and this then has nothing left to do.
1098	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			// Nothing else is a cancellation the relay chain refuses, so leave the registration
1136			// pending: the manager can ask again once the deadline comes round.
1137			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	/// Apply the relay chain's verdict on a deregistration.
1150	///
1151	/// `Ok(())` releases every consideration and the entry with them; a refusal puts the para back
1152	/// to [`RegistrationState::Registered`].
1153	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	/// Nothing was recorded for the request, so the answer is only surfaced as an event.
1206	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	/// The blob landed on the relay chain, so the upgrade is on its way.
1219	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	/// Nothing was recorded for the request, so the answer is only surfaced as an event.
1225	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}