referrerpolicy=no-referrer-when-downgrade

registrar_primitives/
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 shared primitives
19//!
20//! Types shared by the parachain registrar pallet (`pallet-registrar-para`) and relay-chain
21//! registrar pallet (`pallet-registrar-relay`). This crate is deliberately free of any FRAME,
22//! XCM, or network-specific dependency, so a single version of the wire types serves Westend,
23//! Kusama and Polkadot, and so both pallets can depend on it without forming a dependency cycle.
24//!
25//! For the same reason the types here are plain: a para id is a `u32` (byte-compatible with the
26//! relay chain's `Id` newtype), head data and validation code are `Vec<u8>`, and a validation
27//! code hash is an [`H256`] (what `ValidationCodeHash` wraps). The same holds for
28//! [`ParachainRegistrar`], the interface the relay pallet drives the registry through: conversion
29//! to the relay chain's own types happens in the pallet implementing it.
30
31#![cfg_attr(not(feature = "std"), no_std)]
32
33extern crate alloc;
34
35use alloc::vec::Vec;
36use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
37use scale_info::TypeInfo;
38use sp_core::H256;
39
40/// A parachain id.
41///
42/// Byte-compatible with the relay chain's `Id`, which is a transparent `u32` newtype.
43pub type ParaId = u32;
44
45/// Registrar control-plane messages sent to the relay chain.
46///
47/// The variant's `#[codec(index)]` is the on-wire version tag.
48#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo)]
49pub enum MessageToRelay<AccountId> {
50	/// Version 1 of the registrar control-plane messages to the relay chain.
51	#[codec(index = 0)]
52	V1(MessageToRelayV1<AccountId>),
53}
54
55/// Version 1 payloads for [`MessageToRelay`].
56#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo)]
57pub enum MessageToRelayV1<AccountId> {
58	/// Ask the relay chain to accept a registration for `para_id`.
59	///
60	/// The deposit for this registration is already held on the parachain; the relay chain takes
61	/// nothing. The validation code itself is not included: only its hash and length are, and the
62	/// blob is uploaded to the relay chain separately.
63	#[codec(index = 0)]
64	Register {
65		/// The para id being registered. Already reserved on the parachain.
66		para_id: ParaId,
67		/// The parachain's id for this message, echoed back in the response.
68		message_id: u64,
69		/// The account that manages this registration and holds the deposit on the parachain.
70		manager: AccountId,
71		/// The genesis head data of the new parachain.
72		genesis_head: Vec<u8>,
73		/// Blake2-256 hash of the validation code that will be uploaded.
74		code_hash: H256,
75		/// Length of the validation code that will be uploaded, in bytes.
76		///
77		/// The deposit on the parachain was computed from this, so the relay chain must reject any
78		/// blob whose length differs.
79		code_len: u32,
80	},
81	/// Ask the relay chain to drop the authorization it is holding for `para_id`.
82	///
83	/// Sent when the manager gives up on a registration whose validation code never arrived. The
84	/// relay chain never abandons an authorization by itself, so this is what ends a registration
85	/// that is going nowhere, and the manager pays for it. Answered with
86	/// [`MessageToParaV1::CancelResponse`].
87	#[codec(index = 1)]
88	CancelRegistration {
89		/// The para id whose authorization should be dropped.
90		para_id: ParaId,
91		/// The parachain's id for this message, echoed back in the response.
92		message_id: u64,
93	},
94	/// Ask the relay chain to drop `para_id` from the registry.
95	///
96	/// The parachain has already checked that it holds neither a lease nor a region, but only the
97	/// relay chain knows whether the para is still live, locked, or has messages left in flight,
98	/// so the deposits stay held until it answers with [`MessageToParaV1::DeregisterResponse`].
99	///
100	/// Idempotent, so this is also the retry when an answer never arrives: a para already gone or
101	/// on its way out is answered `Ok(())` rather than refused, which is what lets the parachain
102	/// tell a lost verdict from a refusal without a second kind of message.
103	#[codec(index = 2)]
104	Deregister {
105		/// The para id to drop.
106		para_id: ParaId,
107		/// The parachain's id for this message, echoed back in the response.
108		message_id: u64,
109	},
110	/// Ask the relay chain to authorize a validation code upgrade for `para_id`.
111	///
112	/// As with a registration, the blob itself is not sent: the relay chain is told which bytes to
113	/// accept and they are uploaded to it separately. Ownership and the lock are checked on the
114	/// parachain, so nothing about the caller travels with this. Answered with
115	/// [`MessageToParaV1::CodeUpgradeResponse`].
116	#[codec(index = 3)]
117	AuthorizeCodeUpgrade {
118		/// The para id being upgraded.
119		para_id: ParaId,
120		/// The parachain's id for this message, echoed back in the response.
121		message_id: u64,
122		/// Blake2-256 hash of the validation code that will be uploaded.
123		code_hash: H256,
124		/// Length of the validation code that will be uploaded, in bytes.
125		code_len: u32,
126	},
127	/// Ask the relay chain to set the current head data of `para_id`.
128	///
129	/// The head data is small enough to travel with the request, so unlike a code upgrade this is
130	/// a single round trip. Answered with [`MessageToParaV1::SetHeadResponse`].
131	#[codec(index = 4)]
132	SetCurrentHead {
133		/// The para id whose head is being set.
134		para_id: ParaId,
135		/// The parachain's id for this message, echoed back in the response.
136		message_id: u64,
137		/// The new head data.
138		head: Vec<u8>,
139	},
140}
141
142/// Registrar report messages sent back to the parachain.
143///
144/// The variant's `#[codec(index)]` is the on-wire version tag.
145#[derive(
146	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
147)]
148pub enum MessageToPara {
149	/// Version 1 of the registrar report messages to the parachain.
150	#[codec(index = 0)]
151	V1(MessageToParaV1),
152}
153
154/// Version 1 payloads for [`MessageToPara`].
155#[derive(
156	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
157)]
158pub enum MessageToParaV1 {
159	/// Report how a registration requested with [`MessageToRelayV1::Register`] ended.
160	///
161	/// `para_id` correlates the response with its request: a parachain only sends
162	/// [`MessageToRelayV1::Register`] for a para id that is reserved and otherwise idle, so at
163	/// most one request per para id is ever in flight. `message_id` echoes the request's id on
164	/// top, tying the two together across chains and in events.
165	#[codec(index = 0)]
166	RegisterResponse {
167		/// The para id the report is about.
168		para_id: ParaId,
169		/// The id of the [`MessageToRelayV1::Register`] this answers, echoed back.
170		message_id: u64,
171		/// Whether the registration was applied on the relay chain.
172		outcome: Outcome,
173	},
174	/// Answer a [`MessageToRelayV1::CancelRegistration`].
175	///
176	/// `Ok(())` means the relay chain is no longer holding an authorization for this para id, so
177	/// the deposit can be released. The only refusal is
178	/// [`FailureReason::AlreadyRegistered`]: the code did land after all and the para is
179	/// registered, so the deposit stays where it is.
180	#[codec(index = 1)]
181	CancelResponse {
182		/// The para id the answer is about.
183		para_id: ParaId,
184		/// The id of the [`MessageToRelayV1::CancelRegistration`] this answers, echoed back.
185		message_id: u64,
186		/// Whether the authorization was dropped.
187		outcome: Outcome,
188	},
189	/// Answer a [`MessageToRelayV1::Deregister`].
190	///
191	/// `Ok(())` means the para is gone from the relay chain's registry, so every deposit the
192	/// parachain is holding for it can be released.
193	#[codec(index = 2)]
194	DeregisterResponse {
195		/// The para id the answer is about.
196		para_id: ParaId,
197		/// The id of the [`MessageToRelayV1::Deregister`] this answers, echoed back.
198		message_id: u64,
199		/// Whether the para was dropped.
200		outcome: Outcome,
201	},
202	/// Answer a [`MessageToRelayV1::AuthorizeCodeUpgrade`].
203	///
204	/// `Ok(expire_at)` means the relay chain is holding the authorization and will accept the blob
205	/// until that relay-chain block. The upgrade is not scheduled yet: that is reported separately
206	/// with [`MessageToParaV1::CodeUpgradeScheduled`] once the code lands.
207	#[codec(index = 3)]
208	CodeUpgradeResponse {
209		/// The para id the answer is about.
210		para_id: ParaId,
211		/// The id of the [`MessageToRelayV1::AuthorizeCodeUpgrade`] this answers, echoed back.
212		message_id: u64,
213		/// The relay-chain block the authorization lapses at, or why it was refused.
214		outcome: Result<u32, FailureReason>,
215	},
216	/// Report that an authorized code upgrade has been scheduled on the relay chain.
217	///
218	/// Sent when the blob is uploaded, which may be many blocks after the authorization and is not
219	/// something the parachain asked for, so this carries no outcome: a failure to upload simply
220	/// leaves the authorization to lapse.
221	#[codec(index = 4)]
222	CodeUpgradeScheduled {
223		/// The para id the report is about.
224		para_id: ParaId,
225		/// The id of the [`MessageToRelayV1::AuthorizeCodeUpgrade`] this concludes, echoed back.
226		message_id: u64,
227	},
228	/// Answer a [`MessageToRelayV1::SetCurrentHead`].
229	///
230	/// The parachain checks that it holds the para and that the head fits its own mirror of the
231	/// relay chain's limits first, so a refusal here means the two have drifted apart.
232	#[codec(index = 5)]
233	SetHeadResponse {
234		/// The para id the answer is about.
235		para_id: ParaId,
236		/// The id of the [`MessageToRelayV1::SetCurrentHead`] this answers, echoed back.
237		message_id: u64,
238		/// Whether the head was set.
239		outcome: Outcome,
240	},
241	/// Note that `para_id` has produced a head on the relay chain.
242	///
243	/// Correlates with no request, so it carries no `message_id` and is not answered.
244	#[codec(index = 6)]
245	HeadNoted {
246		/// The para id that produced a head.
247		para_id: ParaId,
248	},
249}
250
251/// How a request ended.
252///
253/// `Ok(())` means the relay chain applied it, `Err(reason)` that it did not. Shared by every
254/// response in this protocol rather than one outcome type per request, the same way a pallet has
255/// one `Error` enum instead of one per extrinsic. Encodes as `0x00` for success and `0x01` plus
256/// the reason for failure.
257pub type Outcome = Result<(), FailureReason>;
258
259/// Why a request was rejected by the relay chain.
260#[derive(
261	Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo, MaxEncodedLen,
262)]
263pub enum FailureReason {
264	/// The relay chain already knows this para id.
265	///
266	/// Also the answer to a [`MessageToRelayV1::CancelRegistration`] that came too late, because
267	/// the validation code landed first.
268	#[codec(index = 0)]
269	AlreadyRegistered,
270	/// The head data or the declared code length is not acceptable to the relay chain.
271	#[codec(index = 1)]
272	InvalidOnboardingData,
273	/// The relay chain does not know this para id, e.g. a deregistration overtook the request.
274	#[codec(index = 2)]
275	NotRegistered,
276	/// The relay chain is already holding as many pending registrations as it will accept.
277	#[codec(index = 3)]
278	TooManyPending,
279	/// The relay chain will not drop this para: it is not an on-demand parathread, or its
280	/// offboarding could not be scheduled (e.g. a PVF pre-check is still in progress).
281	#[codec(index = 4)]
282	NotDeregisterable,
283	/// The head data is larger than the relay chain accepts.
284	#[codec(index = 5)]
285	HeadDataTooLarge,
286	/// The registry will not take this upgrade now, e.g. one is already in flight or the para is
287	/// in its post-upgrade cooldown.
288	#[codec(index = 6)]
289	CannotUpgradeCode,
290	/// The declared validation code length is outside what the relay chain accepts.
291	#[codec(index = 7)]
292	InvalidCodeSize,
293}
294
295/// The parachain registry, as `pallet-registrar-relay` needs to see it.
296///
297/// Implemented by whichever pallet owns parachain registration, typically `paras_registrar` on the
298/// relay chain. Lives here so neither side of the protocol has to depend on the other.
299pub trait ParachainRegistrar {
300	/// The account id used to identify a registration's manager.
301	type AccountId;
302
303	/// Whether head data and code of these sizes could be onboarded right now.
304	///
305	/// Checked against the relay chain's live configuration so a doomed request can be rejected
306	/// before the user goes and uploads megabytes of code.
307	#[allow(clippy::result_unit_err)]
308	fn check_onboarding(head_len: u32, code_len: u32) -> Result<(), ()>;
309
310	/// Whether the relay chain already knows this para id.
311	fn is_registered(para_id: ParaId) -> bool;
312
313	/// Onboard `para_id` under `manager`.
314	///
315	/// No deposit is taken: the manager's funds are held on the chain running
316	/// `pallet-registrar-para`.
317	fn register(
318		manager: Self::AccountId,
319		para_id: ParaId,
320		genesis_head: Vec<u8>,
321		validation_code: Vec<u8>,
322	) -> sp_runtime::DispatchResult;
323
324	/// Drop `para_id` from the registry.
325	///
326	/// Idempotent: a para already gone, or still being cleaned up, answers `Ok(())` rather than
327	/// refusing, so a second [`MessageToRelayV1::Deregister`] settles instead of telling the
328	/// parachain the para is still there. Nothing here retries on its own: the parachain waits,
329	/// and if no answer turns up the manager sends the request again. That second request is how
330	/// the parachain learns the first answer never came, and it reports it as an unexpected event.
331	fn deregister(para_id: ParaId) -> sp_runtime::DispatchResult;
332
333	/// Leave `para_id` where [`Self::deregister`] does the most work and still succeeds.
334	#[cfg(feature = "runtime-benchmarks")]
335	fn setup_worst_case_deregister(para_id: ParaId) -> sp_runtime::DispatchResult;
336
337	/// Whether head data of this size is acceptable right now.
338	#[allow(clippy::result_unit_err)]
339	fn check_head_data(head_len: u32) -> Result<(), ()>;
340
341	/// Set the current head of `para_id`.
342	fn set_current_head(para_id: ParaId, head: Vec<u8>);
343
344	/// Whether `para_id` could take a code upgrade of this size right now.
345	#[allow(clippy::result_unit_err)]
346	fn check_code_upgrade(para_id: ParaId, code_len: u32) -> Result<(), ()>;
347
348	/// Leave `para_id` registered and free to take a code upgrade.
349	#[cfg(feature = "runtime-benchmarks")]
350	fn setup_worst_case_code_upgrade(para_id: ParaId) -> sp_runtime::DispatchResult;
351
352	/// Schedule a validation code upgrade for `para_id`.
353	fn schedule_code_upgrade(
354		para_id: ParaId,
355		validation_code: Vec<u8>,
356	) -> sp_runtime::DispatchResult;
357}
358
359/// State of migrated para at the source chain.
360#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo)]
361pub enum MigratedParaState {
362	/// The para id is held by its manager, but nothing is registered on the relay chain.
363	Reserved,
364	/// The relay chain has onboarded this para.
365	Registered {
366		/// Length of the para's current head data, so the destination prices the registration
367		/// the way it prices a fresh one.
368		head_len: u32,
369	},
370}
371
372/// One para, as it arrives from source chain that used to own the registry.
373///
374/// Carries no deposit. [`ReceiveMigratedParas::receive_para`] takes the reservation deposit,
375/// and for a registered para the registration deposit, from `manager` at the destination's own
376/// prices.
377///
378/// Note: We recreate even if there is not enough fund to pay for the deposit so no RC para
379/// is dropped.
380#[derive(Encode, Decode, DecodeWithMemTracking, Clone, Eq, PartialEq, Debug, TypeInfo)]
381pub struct MigratedPara<AccountId> {
382	/// The para id.
383	pub para_id: ParaId,
384	/// The account that reserved the para id and controls it.
385	pub manager: AccountId,
386	/// Where this para id sits in the registration flow.
387	pub state: MigratedParaState,
388	/// Whether the manager is locked out of controlling this para. `None` until the lock is set
389	/// for the first time, and read as unlocked.
390	pub locked: Option<bool>,
391}
392
393/// Takes migrated para ids into the pallet that owns registration on the destination.
394pub trait ReceiveMigratedParas<AccountId> {
395	/// Take one para, charging its deposits at this chain's prices.
396	///
397	/// Note: We recreate even if there is not enough fund to pay for the deposit so no RC para
398	/// gets dropped.
399	fn receive_para(para: MigratedPara<AccountId>) -> sp_runtime::DispatchResult;
400
401	/// Adopt the next free para id from the source chain.
402	fn receive_next_free_para_id(para_id: ParaId);
403}
404
405impl<AccountId> ReceiveMigratedParas<AccountId> for () {
406	fn receive_para(_: MigratedPara<AccountId>) -> sp_runtime::DispatchResult {
407		Err(sp_runtime::DispatchError::Unavailable)
408	}
409
410	fn receive_next_free_para_id(_: ParaId) {}
411}