referrerpolicy=no-referrer-when-downgrade

pallet_registrar_relay/
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//! # Relay-chain registrar pallet
19//!
20//! Relay half of the parachain registrar. Runs on the relay chain, applying registrations
21//! authorized on a parachain (`pallet-registrar-para`) and driving the relay's legacy `paras`
22//! state.
23//!
24//! ## Two-phase registration
25//!
26//! Pushing a multi-megabyte validation code through XCM would be wasteful when the parachain can
27//! commit to the exact bytes and let anybody upload them here directly, so registration arrives in
28//! two pieces:
29//!
30//! 1. [`Pallet::receive`] takes the parachain's request, which carries the head data plus the hash
31//!    and length of the code that is coming, and parks it in [`PendingRegistrations`]. Only
32//!    callable by a trusted XCM origin (e.g. the Coretime chain).
33//! 2. [`Pallet::apply_authorized_code`] takes the blob itself. It needs no signature: anybody may
34//!    push the code, because a pending entry already pins down exactly which bytes are acceptable,
35//!    and the parachain has already made the manager pay for them. If the blob matches, the para is
36//!    onboarded and the outcome is reported back to the parachain.
37//!
38//! A registration authorization never times out here. The parachain sends
39//! [`MessageToRelayV1::CancelRegistration`] when the manager gives up, this pallet drops the entry
40//! and confirms, and the parachain releases the deposit. So the relay chain runs no per-block
41//! sweep, and whoever wants the deposit back pays for the round trip. No deposit is taken here.
42//!
43//! Code upgrade authorizations do lapse instead: no deposit is at stake, and their validity
44//! depends on relay-chain state the parachain does not track.
45//!
46//! ## Deregistration
47//!
48//! Applied as it arrives and answered once. A para already gone is confirmed, so the parachain's
49//! retry after a lost answer settles instead of being refused.
50//!
51//! ## Locking
52//!
53//! The relay chain also tells the parachain when a para produces a head, so the chain holding the
54//! manager relationship can lock the para. Add this pallet to `paras::Config::OnNewHead`.
55//!
56//! ## Code upgrades
57//!
58//! [`Pallet::apply_authorized_code_upgrade`] splits the same way, but the authorization does lapse
59//! after [`Config::CodeUpgradeValidPeriod`]: whether an upgrade may be scheduled at all depends on
60//! relay-chain state that moves on its own. No deposit is involved, so nothing has to be given
61//! back and no cancellation round trip exists.
62//!
63//! ## Runtime requirement
64//!
65//! `apply_authorized_code` authorizes itself through [`frame_support::pallet_macros::authorize`],
66//! so the runtime must carry `frame_system::AuthorizeCall` in its transaction extension pipeline.
67
68#![cfg_attr(not(feature = "std"), no_std)]
69
70extern crate alloc;
71
72use alloc::vec::Vec;
73use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
74use frame_support::{traits::Get, weights::Weight};
75pub use pallet::*;
76use polkadot_primitives::{HeadData, Id};
77use polkadot_runtime_parachains::paras::OnNewHead;
78use registrar_primitives::{
79	FailureReason, MessageToPara, MessageToParaV1, MessageToRelay, MessageToRelayV1, Outcome,
80	ParaId, ParachainRegistrar,
81};
82use scale_info::TypeInfo;
83use sp_core::H256;
84pub use weights::WeightInfo;
85
86pub mod weights;
87
88const LOG_TARGET: &str = "runtime::registrar-relay";
89
90#[cfg(feature = "runtime-benchmarks")]
91mod benchmarking;
92#[cfg(test)]
93mod mock;
94#[cfg(test)]
95mod tests;
96
97pub trait SendToPara {
98	/// Send `message` to the parachain.
99	///
100	/// `Err(())` means the transport refused the message; callers log and carry on rather than
101	/// unwind committed state.
102	#[allow(clippy::result_unit_err)]
103	fn send(message: MessageToPara) -> Result<(), ()>;
104}
105
106#[cfg(feature = "std")]
107impl SendToPara for () {
108	fn send(_message: MessageToPara) -> Result<(), ()> {
109		Ok(())
110	}
111}
112
113/// A registration the parachain has asked for, waiting on its validation code.
114#[derive(
115	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo, MaxEncodedLen, Debug,
116)]
117#[scale_info(skip_type_params(MaxHeadDataSize))]
118pub struct PendingRegistration<AccountId, MaxHeadDataSize: Get<u32>> {
119	/// The id of the [`MessageToRelayV1::Register`] that created this entry, echoed back in the
120	/// response once the code arrives.
121	pub message_id: u64,
122	/// The account managing this registration on the parachain.
123	pub manager: AccountId,
124	/// The genesis head data, held here until the code arrives.
125	pub genesis_head: frame_support::BoundedVec<u8, MaxHeadDataSize>,
126	/// Blake2-256 hash the validation code must have.
127	pub code_hash: H256,
128	/// Exact length the validation code must have, as declared by the parachain.
129	pub code_len: u32,
130}
131
132/// [`PendingRegistration`] as this pallet stores it.
133pub type PendingRegistrationOf<T> =
134	PendingRegistration<<T as frame_system::Config>::AccountId, <T as Config>::MaxHeadDataSize>;
135
136/// A code upgrade the parachain has authorized, waiting on its validation code.
137#[derive(
138	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, TypeInfo, MaxEncodedLen, Debug,
139)]
140pub struct PendingCodeUpgrade<BlockNumber> {
141	/// The id of the [`MessageToRelayV1::AuthorizeCodeUpgrade`] that created this entry.
142	pub message_id: u64,
143	/// Blake2-256 hash the validation code must have.
144	pub code_hash: H256,
145	/// Exact length the validation code must have.
146	pub code_len: u32,
147	/// The block from which the blob is no longer accepted.
148	pub expire_at: BlockNumber,
149}
150
151#[frame_support::pallet]
152pub mod pallet {
153	use super::*;
154	use frame_support::pallet_prelude::*;
155	use frame_system::pallet_prelude::*;
156	use sp_runtime::traits::{BlakeTwo256, Hash, SaturatedConversion, Saturating};
157
158	#[pallet::config]
159	pub trait Config: frame_system::Config {
160		/// The overarching event type.
161		#[allow(deprecated)]
162		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
163
164		/// A trusted parachain parachain authorized to drive registrations.
165		type ParaOrigin: EnsureOrigin<Self::RuntimeOrigin>;
166
167		/// Sends messages to the parachain.
168		type SendToPara: SendToPara;
169
170		/// The relay chain's parachain registry.
171		type Registrar: ParachainRegistrar<AccountId = Self::AccountId>;
172
173		/// The largest head data this pallet will hold onto while waiting for code.
174		///
175		/// Should be at least the relay chain's `max_head_data_size`.
176		#[pallet::constant]
177		type MaxHeadDataSize: Get<u32>;
178
179		/// The largest validation code [`Pallet::apply_authorized_code`] will accept.
180		///
181		/// Should be at least the relay chain's `max_code_size`.
182		#[pallet::constant]
183		type MaxCodeSize: Get<u32>;
184
185		/// How many registrations may be waiting on their code at once.
186		///
187		/// Bounds the head data stored here, where no deposit is held.
188		#[pallet::constant]
189		type MaxPendingRegistrations: Get<u32>;
190
191		/// How long an authorized code upgrade stays valid for.
192		#[pallet::constant]
193		type CodeUpgradeValidPeriod: Get<BlockNumberFor<Self>>;
194
195		/// Priority given to a valid code upload in the transaction pool.
196		#[pallet::constant]
197		type UnsignedPriority: Get<TransactionPriority>;
198
199		/// Weight information for the extrinsics in this pallet.
200		type WeightInfo: WeightInfo;
201	}
202
203	#[pallet::pallet]
204	pub struct Pallet<T>(_);
205
206	/// Registrations waiting on their validation code, by para id.
207	///
208	/// Counted so [`Config::MaxPendingRegistrations`] can be enforced with a single read.
209	#[pallet::storage]
210	pub type PendingRegistrations<T: Config> =
211		CountedStorageMap<_, Blake2_128Concat, ParaId, PendingRegistrationOf<T>>;
212
213	/// Paras registered here that have not produced their first head yet, by para id.
214	#[pallet::storage]
215	pub type AwaitingFirstHead<T: Config> = StorageMap<_, Blake2_128Concat, ParaId, ()>;
216
217	/// Code upgrades waiting on their validation code, by para id.
218	#[pallet::storage]
219	pub type PendingCodeUpgrades<T: Config> =
220		StorageMap<_, Blake2_128Concat, ParaId, PendingCodeUpgrade<BlockNumberFor<T>>>;
221
222	#[pallet::event]
223	#[pallet::generate_deposit(pub(super) fn deposit_event)]
224	pub enum Event<T: Config> {
225		/// A registration request was accepted and is waiting on its validation code.
226		RegistrationPending { para_id: ParaId, message_id: u64, code_hash: H256 },
227		/// A registration request was rejected out of hand.
228		RegistrationRejected { para_id: ParaId, message_id: u64, reason: FailureReason },
229		/// A para was onboarded.
230		Registered { para_id: ParaId, message_id: u64, manager: T::AccountId },
231		/// An authorization was dropped at the parachain's request.
232		AuthorizationCancelled { para_id: ParaId, message_id: u64 },
233		/// A cancellation arrived after the para had already been onboarded, and was refused.
234		CancellationRefused { para_id: ParaId, message_id: u64 },
235		/// A code upgrade was authorized and is waiting on its validation code.
236		CodeUpgradePending {
237			para_id: ParaId,
238			message_id: u64,
239			code_hash: H256,
240			expire_at: BlockNumberFor<T>,
241		},
242		/// A code upgrade request was refused.
243		CodeUpgradeRejected { para_id: ParaId, message_id: u64, reason: FailureReason },
244		/// An authorized code upgrade was scheduled.
245		CodeUpgradeApplied { para_id: ParaId, message_id: u64 },
246		/// A report could not be sent back to the parachain.
247		ReportFailed { para_id: ParaId, message_id: u64 },
248		/// The parachain was told that a para produced its first head.
249		HeadNoted { para_id: ParaId },
250		/// A para's first head could not be reported to the parachain.
251		HeadNoteFailed { para_id: ParaId },
252		/// A para was dropped from the registry, or had already left it.
253		Deregistered { para_id: ParaId, message_id: u64 },
254		/// The registry refused to drop a para.
255		DeregistrationRejected { para_id: ParaId, message_id: u64 },
256		/// A para's current head was set at the parachain's request.
257		HeadUpdated { para_id: ParaId, message_id: u64 },
258		/// A head update was refused.
259		HeadUpdateRejected { para_id: ParaId, message_id: u64, reason: FailureReason },
260	}
261
262	#[pallet::error]
263	pub enum Error<T> {
264		/// No registration is waiting on code for this para id.
265		NothingPending,
266		/// The validation code does not match the hash the parachain committed to.
267		CodeHashMismatch,
268		/// The validation code is not the length the parachain committed to.
269		CodeLenMismatch,
270		/// The validation code is larger than this pallet will accept.
271		CodeTooLarge,
272		/// The code upgrade authorization has lapsed.
273		AuthorizationExpired,
274		/// The registry would refuse this code upgrade right now.
275		CannotUpgradeCode,
276	}
277
278	#[pallet::call]
279	impl<T: Config> Pallet<T> {
280		/// Accept a control-plane message from the parachain's registrar pallet.
281		///
282		/// The origin is a trusted XCM origin, not a user. A rejected request still returns `Ok`:
283		/// failing would roll back the rejection report and leave the parachain holding a deposit
284		/// for news that never comes.
285		#[pallet::call_index(0)]
286		#[pallet::weight(match message {
287			MessageToRelay::V1(MessageToRelayV1::Register { genesis_head, .. }) =>
288				T::WeightInfo::receive_register(genesis_head.len() as u32),
289			MessageToRelay::V1(MessageToRelayV1::CancelRegistration { .. }) =>
290				T::WeightInfo::receive_cancel_registration(),
291			MessageToRelay::V1(MessageToRelayV1::Deregister { .. }) =>
292				T::WeightInfo::receive_deregister(),
293			MessageToRelay::V1(MessageToRelayV1::SetCurrentHead { head, .. }) =>
294				T::WeightInfo::receive_set_current_head(head.len() as u32),
295			MessageToRelay::V1(MessageToRelayV1::AuthorizeCodeUpgrade { .. }) =>
296				T::WeightInfo::receive_authorize_code_upgrade(),
297		})]
298		pub fn receive(
299			origin: OriginFor<T>,
300			message: MessageToRelay<T::AccountId>,
301		) -> DispatchResult {
302			T::ParaOrigin::ensure_origin_or_root(origin)?;
303
304			match message {
305				MessageToRelay::V1(MessageToRelayV1::Register {
306					para_id,
307					message_id,
308					manager,
309					genesis_head,
310					code_hash,
311					code_len,
312				}) => Self::on_register_request(
313					para_id,
314					message_id,
315					manager,
316					genesis_head,
317					code_hash,
318					code_len,
319				),
320				MessageToRelay::V1(MessageToRelayV1::CancelRegistration {
321					para_id,
322					message_id,
323				}) => Self::on_cancel_request(para_id, message_id),
324				MessageToRelay::V1(MessageToRelayV1::Deregister { para_id, message_id }) => {
325					Self::on_deregister_request(para_id, message_id)
326				},
327				MessageToRelay::V1(MessageToRelayV1::AuthorizeCodeUpgrade {
328					para_id,
329					message_id,
330					code_hash,
331					code_len,
332				}) => Self::on_authorize_code_upgrade_request(
333					para_id, message_id, code_hash, code_len,
334				),
335				MessageToRelay::V1(MessageToRelayV1::SetCurrentHead {
336					para_id,
337					message_id,
338					head,
339				}) => Self::on_set_current_head_request(para_id, message_id, head),
340			}
341
342			Ok(())
343		}
344
345		/// Upload the validation code for a pending authorization, onboarding the para.
346		///
347		/// Unsigned and free: the pending entry already pins the exact bytes accepted, and the
348		/// manager has paid for them on the parachain.
349		#[pallet::call_index(1)]
350		#[pallet::authorize(Self::authorize_apply_authorized_code)]
351		#[pallet::weight_of_authorize(T::WeightInfo::authorize_apply_authorized_code(validation_code.len() as u32))]
352		#[pallet::weight(T::WeightInfo::apply_authorized_code(validation_code.len() as u32))]
353		pub fn apply_authorized_code(
354			origin: OriginFor<T>,
355			para_id: ParaId,
356			validation_code: Vec<u8>,
357		) -> DispatchResultWithPostInfo {
358			ensure_authorized(origin)?;
359
360			let pending = Self::validate_pending_code(para_id, &validation_code)?;
361
362			T::Registrar::register(
363				pending.manager.clone(),
364				para_id,
365				pending.genesis_head.into_inner(),
366				validation_code,
367			)?;
368			PendingRegistrations::<T>::remove(para_id);
369
370			let message_id = pending.message_id;
371			Self::report_registration(para_id, message_id, Ok(()));
372			Self::deposit_event(Event::Registered {
373				para_id,
374				message_id,
375				manager: pending.manager,
376			});
377			Ok(Pays::No.into())
378		}
379
380		/// Upload the validation code for an authorized upgrade, scheduling it.
381		///
382		/// Needs no signature and pays no fee, for the same reason as
383		/// [`Pallet::apply_authorized_code`]: the authorization already fixes the exact bytes.
384		#[pallet::call_index(2)]
385		#[pallet::authorize(Self::authorize_apply_authorized_code_upgrade)]
386		#[pallet::weight_of_authorize(T::WeightInfo::authorize_apply_authorized_code_upgrade(validation_code.len() as u32))]
387		#[pallet::weight(T::WeightInfo::apply_authorized_code_upgrade(validation_code.len() as u32))]
388		pub fn apply_authorized_code_upgrade(
389			origin: OriginFor<T>,
390			para_id: ParaId,
391			validation_code: Vec<u8>,
392		) -> DispatchResultWithPostInfo {
393			ensure_authorized(origin)?;
394
395			let pending = Self::validate_pending_upgrade(para_id, &validation_code)?;
396
397			// A refusal here fails the extrinsic and leaves the authorization in place, so the
398			// upload can be retried once whatever blocked it clears.
399			T::Registrar::schedule_code_upgrade(para_id, validation_code)?;
400			PendingCodeUpgrades::<T>::remove(para_id);
401
402			let message_id = pending.message_id;
403			Self::report_code_upgrade_scheduled(para_id, message_id);
404			Self::deposit_event(Event::CodeUpgradeApplied { para_id, message_id });
405			Ok(Pays::No.into())
406		}
407	}
408
409	impl<T: Config> Pallet<T> {
410		/// Validate an unsigned [`Pallet::apply_authorized_code`], with the same checks as the
411		/// dispatch so the pool and the block cannot disagree.
412		// `#[pallet::authorize]` passes the call arguments by reference, so the types must mirror
413		// the call's exactly; `&[u8]` would not compile.
414		#[allow(clippy::ptr_arg)]
415		pub fn authorize_apply_authorized_code(
416			_source: TransactionSource,
417			para_id: &ParaId,
418			validation_code: &Vec<u8>,
419		) -> TransactionValidityWithRefund {
420			let pending = Self::validate_pending_code(*para_id, validation_code)
421				.map_err(|e| InvalidTransaction::Custom(Self::err_to_code(e)))?;
422
423			// No longevity bound: an authorization does not expire, so the transaction stays valid
424			// until the code is applied or the parachain cancels, and revalidation drops it then.
425			let validity = ValidTransaction::with_tag_prefix("RegistrarApplyAuthorizedCode")
426				.priority(T::UnsignedPriority::get())
427				.and_provides((*para_id, pending.code_hash))
428				.propagate(true)
429				.build()?;
430
431			Ok((validity, Weight::zero()))
432		}
433
434		/// Decide whether an unsigned [`Pallet::apply_authorized_code_upgrade`] may enter the pool
435		/// and a block.
436		#[allow(clippy::ptr_arg)]
437		pub fn authorize_apply_authorized_code_upgrade(
438			_source: TransactionSource,
439			para_id: &ParaId,
440			validation_code: &Vec<u8>,
441		) -> TransactionValidityWithRefund {
442			let pending = Self::validate_pending_upgrade(*para_id, validation_code)
443				.map_err(|e| InvalidTransaction::Custom(Self::err_to_code(e)))?;
444
445			// This one does expire, so it must not outlive the authorization in the pool.
446			let now = frame_system::Pallet::<T>::block_number();
447			let longevity = pending.expire_at.saturating_sub(now);
448
449			let validity = ValidTransaction::with_tag_prefix("RegistrarApplyCodeUpgrade")
450				.priority(T::UnsignedPriority::get())
451				.longevity(longevity.try_into().unwrap_or(64))
452				.and_provides((*para_id, pending.code_hash))
453				.propagate(true)
454				.build()?;
455
456			Ok((validity, Weight::zero()))
457		}
458
459		/// Apply a registration request from the parachain, accepting or rejecting it.
460		fn on_register_request(
461			para_id: ParaId,
462			message_id: u64,
463			manager: T::AccountId,
464			genesis_head: Vec<u8>,
465			code_hash: H256,
466			code_len: u32,
467		) {
468			let Ok(head_len) = u32::try_from(genesis_head.len()) else {
469				return Self::reject(para_id, message_id, FailureReason::InvalidOnboardingData);
470			};
471
472			if T::Registrar::is_registered(para_id) ||
473				PendingRegistrations::<T>::contains_key(para_id)
474			{
475				return Self::reject(para_id, message_id, FailureReason::AlreadyRegistered);
476			}
477			if PendingRegistrations::<T>::count() >= T::MaxPendingRegistrations::get() {
478				return Self::reject(para_id, message_id, FailureReason::TooManyPending);
479			}
480			if code_len > T::MaxCodeSize::get() ||
481				T::Registrar::check_onboarding(head_len, code_len).is_err()
482			{
483				return Self::reject(para_id, message_id, FailureReason::InvalidOnboardingData);
484			}
485			let Ok(genesis_head) = BoundedVec::try_from(genesis_head) else {
486				return Self::reject(para_id, message_id, FailureReason::InvalidOnboardingData);
487			};
488
489			PendingRegistrations::<T>::insert(
490				para_id,
491				PendingRegistration { message_id, manager, genesis_head, code_hash, code_len },
492			);
493
494			AwaitingFirstHead::<T>::insert(para_id, ());
495
496			Self::deposit_event(Event::RegistrationPending { para_id, message_id, code_hash });
497		}
498
499		/// Turn a request away and tell the parachain to release the deposit.
500		fn reject(para_id: ParaId, message_id: u64, reason: FailureReason) {
501			Self::report_registration(para_id, message_id, Err(reason.clone()));
502			Self::deposit_event(Event::RegistrationRejected { para_id, message_id, reason });
503		}
504
505		/// Drop the authorization for `para_id` and tell the parachain to release the deposit.
506		///
507		/// If the code already landed the cancellation is refused and the deposit is kept. Nothing
508		/// pending still gets an `Ok`: the request may have been rejected here and the report lost.
509		fn on_cancel_request(para_id: ParaId, message_id: u64) {
510			PendingRegistrations::<T>::remove(para_id);
511
512			if T::Registrar::is_registered(para_id) {
513				Self::report_cancellation(
514					para_id,
515					message_id,
516					Err(FailureReason::AlreadyRegistered),
517				);
518				return Self::deposit_event(Event::CancellationRefused { para_id, message_id });
519			}
520
521			AwaitingFirstHead::<T>::remove(para_id);
522
523			Self::report_cancellation(para_id, message_id, Ok(()));
524			Self::deposit_event(Event::AuthorizationCancelled { para_id, message_id });
525		}
526
527		/// Check `validation_code` against the pending entry for `para_id`.
528		fn validate_pending_code(
529			para_id: ParaId,
530			validation_code: &[u8],
531		) -> Result<PendingRegistrationOf<T>, Error<T>> {
532			// Bound the work before hashing, so an oversized blob is rejected cheaply.
533			let code_len =
534				u32::try_from(validation_code.len()).map_err(|_| Error::<T>::CodeTooLarge)?;
535			ensure!(code_len <= T::MaxCodeSize::get(), Error::<T>::CodeTooLarge);
536
537			let pending =
538				PendingRegistrations::<T>::get(para_id).ok_or(Error::<T>::NothingPending)?;
539			ensure!(code_len == pending.code_len, Error::<T>::CodeLenMismatch);
540			ensure!(
541				BlakeTwo256::hash(validation_code) == pending.code_hash,
542				Error::<T>::CodeHashMismatch
543			);
544
545			Ok(pending)
546		}
547
548		/// Check `validation_code` against the authorized upgrade for `para_id`, and that the
549		/// registry would still take it.
550		fn validate_pending_upgrade(
551			para_id: ParaId,
552			validation_code: &[u8],
553		) -> Result<PendingCodeUpgrade<BlockNumberFor<T>>, Error<T>> {
554			let code_len =
555				u32::try_from(validation_code.len()).map_err(|_| Error::<T>::CodeTooLarge)?;
556			ensure!(code_len <= T::MaxCodeSize::get(), Error::<T>::CodeTooLarge);
557
558			let pending =
559				PendingCodeUpgrades::<T>::get(para_id).ok_or(Error::<T>::NothingPending)?;
560			ensure!(
561				frame_system::Pallet::<T>::block_number() <= pending.expire_at,
562				Error::<T>::AuthorizationExpired
563			);
564			ensure!(code_len == pending.code_len, Error::<T>::CodeLenMismatch);
565			// Otherwise a blocked upload passes the pool and fails, for free, in every block.
566			ensure!(
567				T::Registrar::check_code_upgrade(para_id, code_len).is_ok(),
568				Error::<T>::CannotUpgradeCode
569			);
570			ensure!(
571				BlakeTwo256::hash(validation_code) == pending.code_hash,
572				Error::<T>::CodeHashMismatch
573			);
574
575			Ok(pending)
576		}
577
578		/// Map a validation failure onto the `InvalidTransaction::Custom` code it reports.
579		pub fn err_to_code(error: Error<T>) -> u8 {
580			match error {
581				Error::<T>::NothingPending => 0,
582				Error::<T>::CodeHashMismatch => 1,
583				Error::<T>::CodeLenMismatch => 2,
584				Error::<T>::CodeTooLarge => 3,
585				Error::<T>::AuthorizationExpired => 4,
586				Error::<T>::CannotUpgradeCode => 5,
587			}
588		}
589
590		/// Tell the parachain how a registration ended.
591		fn report_registration(para_id: ParaId, message_id: u64, outcome: Outcome) {
592			Self::report(
593				para_id,
594				message_id,
595				MessageToParaV1::RegisterResponse { para_id, message_id, outcome },
596			);
597		}
598
599		/// Tell the parachain what became of its cancellation.
600		fn report_cancellation(para_id: ParaId, message_id: u64, outcome: Outcome) {
601			Self::report(
602				para_id,
603				message_id,
604				MessageToParaV1::CancelResponse { para_id, message_id, outcome },
605			);
606		}
607
608		/// Drop `para_id` at the parachain's request.
609		///
610		/// A para already gone is confirmed rather than refused, so a retried request settles.
611		fn on_deregister_request(para_id: ParaId, message_id: u64) {
612			if let Err(e) = T::Registrar::deregister(para_id) {
613				log::debug!(
614					target: LOG_TARGET,
615					"registry refused to drop para {para_id}: {e:?}",
616				);
617				Self::report_deregistration(
618					para_id,
619					message_id,
620					Err(FailureReason::NotDeregisterable),
621				);
622				return Self::deposit_event(Event::DeregistrationRejected { para_id, message_id });
623			}
624
625			AwaitingFirstHead::<T>::remove(para_id);
626			// Nothing prunes it, and not every registry refuses an offboarding para.
627			PendingCodeUpgrades::<T>::remove(para_id);
628			Self::report_deregistration(para_id, message_id, Ok(()));
629			Self::deposit_event(Event::Deregistered { para_id, message_id });
630		}
631
632		/// Park an upgrade authorization for `para_id`, or refuse it, and report either way.
633		///
634		/// Any authorization the para already had is replaced: only the newest one was paid for,
635		/// and this is what keeps the map from growing past one entry per registered para.
636		fn on_authorize_code_upgrade_request(
637			para_id: ParaId,
638			message_id: u64,
639			code_hash: H256,
640			code_len: u32,
641		) {
642			let reason = if code_len > T::MaxCodeSize::get() {
643				Some(FailureReason::InvalidCodeSize)
644			} else if !T::Registrar::is_registered(para_id) {
645				Some(FailureReason::NotRegistered)
646			} else if T::Registrar::check_code_upgrade(para_id, code_len).is_err() {
647				Some(FailureReason::CannotUpgradeCode)
648			} else {
649				None
650			};
651
652			if let Some(reason) = reason {
653				Self::report_code_upgrade(para_id, message_id, Err(reason.clone()));
654				return Self::deposit_event(Event::CodeUpgradeRejected {
655					para_id,
656					message_id,
657					reason,
658				});
659			}
660
661			let expire_at = frame_system::Pallet::<T>::block_number()
662				.saturating_add(T::CodeUpgradeValidPeriod::get());
663			PendingCodeUpgrades::<T>::insert(
664				para_id,
665				PendingCodeUpgrade { message_id, code_hash, code_len, expire_at },
666			);
667
668			Self::report_code_upgrade(para_id, message_id, Ok(expire_at.saturated_into()));
669			Self::deposit_event(Event::CodeUpgradePending {
670				para_id,
671				message_id,
672				code_hash,
673				expire_at,
674			});
675		}
676
677		/// Set `para_id`'s head if the para is known and the head fits, and report either way.
678		///
679		/// Registration is re-checked here since a deregistration can land before an earlier head.
680		fn on_set_current_head_request(para_id: ParaId, message_id: u64, head: Vec<u8>) {
681			let fits = u32::try_from(head.len())
682				.is_ok_and(|len| T::Registrar::check_head_data(len).is_ok());
683			let reason = if !T::Registrar::is_registered(para_id) {
684				Some(FailureReason::NotRegistered)
685			} else if !fits {
686				Some(FailureReason::HeadDataTooLarge)
687			} else {
688				None
689			};
690			if let Some(reason) = reason {
691				Self::report_set_head(para_id, message_id, Err(reason.clone()));
692				Self::deposit_event(Event::HeadUpdateRejected { para_id, message_id, reason });
693				return;
694			}
695
696			T::Registrar::set_current_head(para_id, head);
697			Self::report_set_head(para_id, message_id, Ok(()));
698			Self::deposit_event(Event::HeadUpdated { para_id, message_id });
699		}
700
701		/// Tell the parachain how a deregistration ended.
702		fn report_deregistration(para_id: ParaId, message_id: u64, outcome: Outcome) {
703			Self::report(
704				para_id,
705				message_id,
706				MessageToParaV1::DeregisterResponse { para_id, message_id, outcome },
707			);
708		}
709
710		/// Tell the parachain whether the upgrade was authorized, and until when.
711		fn report_code_upgrade(
712			para_id: ParaId,
713			message_id: u64,
714			outcome: Result<u32, FailureReason>,
715		) {
716			Self::report(
717				para_id,
718				message_id,
719				MessageToParaV1::CodeUpgradeResponse { para_id, message_id, outcome },
720			);
721		}
722
723		/// Tell the parachain that the uploaded code is now scheduled.
724		fn report_code_upgrade_scheduled(para_id: ParaId, message_id: u64) {
725			Self::report(
726				para_id,
727				message_id,
728				MessageToParaV1::CodeUpgradeScheduled { para_id, message_id },
729			);
730		}
731
732		/// Tell the parachain whether the head was set.
733		fn report_set_head(para_id: ParaId, message_id: u64, outcome: Outcome) {
734			Self::report(
735				para_id,
736				message_id,
737				MessageToParaV1::SetHeadResponse { para_id, message_id, outcome },
738			);
739		}
740
741		/// Hand a report to the transport.
742		///
743		/// A failure is only logged and evented: callers have committed relay-chain state that must
744		/// not unwind because a report bounced.
745		fn report(para_id: ParaId, message_id: u64, message: MessageToParaV1) {
746			if T::SendToPara::send(MessageToPara::V1(message)).is_err() {
747				log::error!(
748					target: LOG_TARGET,
749					"failed to report the outcome for para {para_id} back to the parachain",
750				);
751				Self::deposit_event(Event::ReportFailed { para_id, message_id });
752			}
753		}
754	}
755}
756
757/// Tells the parachain the first time a para produces a head, so it can lock the para.
758///
759/// The caller is a hook that cannot fail, so a send failure is only logged and evented. Nothing is
760/// recorded in that case, so the next head retries.
761impl<T: Config> OnNewHead for Pallet<T> {
762	fn on_new_head(id: Id, _head: &HeadData) -> Weight {
763		let para_id: ParaId = id.into();
764		if !AwaitingFirstHead::<T>::contains_key(para_id) {
765			return T::WeightInfo::on_new_head_already_noted();
766		}
767
768		if T::SendToPara::send(MessageToPara::V1(MessageToParaV1::HeadNoted { para_id })).is_err() {
769			log::error!(
770				target: LOG_TARGET,
771				"failed to tell the parachain about a new head for para {para_id}",
772			);
773			Self::deposit_event(Event::HeadNoteFailed { para_id });
774		} else {
775			AwaitingFirstHead::<T>::remove(para_id);
776			Self::deposit_event(Event::HeadNoted { para_id });
777		}
778
779		T::WeightInfo::on_new_head()
780	}
781}