polkadot_runtime_parachains/paras/
mod.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// This file is part of Polkadot.
3
4// Polkadot is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Polkadot is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.
16
17//! The paras pallet acts as the main registry of paras.
18//!
19//! # Tracking State of Paras
20//!
21//! The most important responsibility of this module is to track which parachains
22//! are active and what their current state is. The current state of a para consists of the current
23//! head data and the current validation code (AKA Parachain Validation Function (PVF)).
24//!
25//! A para is not considered live until it is registered and activated in this pallet.
26//!
27//! The set of parachains cannot change except at session boundaries. This is primarily to ensure
28//! that the number and meaning of bits required for the availability bitfields does not change
29//! except at session boundaries.
30//!
31//! # Validation Code Upgrades
32//!
33//! When a para signals the validation code upgrade it will be processed by this module. This can
34//! be in turn split into more fine grained items:
35//!
36//! - Part of the acceptance criteria checks if the para can indeed signal an upgrade,
37//!
38//! - When the candidate is enacted, this module schedules code upgrade, storing the prospective
39//!   validation code.
40//!
41//! - Actually assign the prospective validation code to be the current one after all conditions are
42//!   fulfilled.
43//!
44//! The conditions that must be met before the para can use the new validation code are:
45//!
46//! 1. The validation code should have been "soaked" in the storage for a given number of blocks.
47//! That    is, the validation code should have been stored in on-chain storage for some time, so
48//! that in    case of a revert with a non-extreme height difference, that validation code can still
49//! be    found on-chain.
50//!
51//! 2. The validation code was vetted by the validators and declared as non-malicious in a processes
52//!    known as PVF pre-checking.
53//!
54//! # Validation Code Management
55//!
56//! Potentially, one validation code can be used by several different paras. For example, during
57//! initial stages of deployment several paras can use the same "shell" validation code, or
58//! there can be shards of the same para that use the same validation code.
59//!
60//! In case a validation code ceases to have any users it must be pruned from the on-chain storage.
61//!
62//! # Para Lifecycle Management
63//!
64//! A para can be in one of the two stable states: it is either a lease holding parachain or an
65//! on-demand parachain.
66//!
67//! However, in order to get into one of those two states, it must first be onboarded. Onboarding
68//! can be only enacted at session boundaries. Onboarding must take at least one full session.
69//! Moreover, a brand new validation code should go through the PVF pre-checking process.
70//!
71//! Once the para is in one of the two stable states, it can switch to the other stable state or to
72//! initiate offboarding process. The result of offboarding is removal of all data related to that
73//! para.
74//!
75//! # PVF Pre-checking
76//!
77//! As was mentioned above, a brand new validation code should go through a process of approval. As
78//! part of this process, validators from the active set will take the validation code and check if
79//! it is malicious. Once they did that and have their judgement, either accept or reject, they
80//! issue a statement in a form of an unsigned extrinsic. This extrinsic is processed by this
81//! pallet. Once supermajority is gained for accept, then the process that initiated the check is
82//! resumed (as mentioned before this can be either upgrading of validation code or onboarding). If
83//! getting a supermajority becomes impossible (>1/3 of validators have already voted against), then
84//! we reject.
85//!
86//! Below is a state diagram that depicts states of a single PVF pre-checking vote.
87//!
88//! ```text
89//!                                            ┌──────────┐
90//!                        supermajority       │          │
91//!                    ┌────────for───────────▶│ accepted │
92//!        vote────┐   │                       │          │
93//!         │      │   │                       └──────────┘
94//!         │      │   │
95//!         │  ┌───────┐
96//!         │  │       │
97//!         └─▶│ init  │──── >1/3 against      ┌──────────┐
98//!            │       │           │           │          │
99//!            └───────┘           └──────────▶│ rejected │
100//!             ▲  │                           │          │
101//!             │  │ session                   └──────────┘
102//!             │  └──change
103//!             │     │
104//!             │     ▼
105//!             ┌─────┐
106//! start──────▶│reset│
107//!             └─────┘
108//! ```
109
110use crate::{
111	configuration,
112	inclusion::{QueueFootprinter, UmpQueueId},
113	initializer::SessionChangeNotification,
114	shared,
115};
116use alloc::{collections::btree_set::BTreeSet, vec::Vec};
117use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec};
118use codec::{Decode, Encode};
119use core::{cmp, mem};
120use frame_support::{pallet_prelude::*, traits::EstimateNextSessionRotation, DefaultNoBound};
121use frame_system::pallet_prelude::*;
122use polkadot_primitives::{
123	ConsensusLog, HeadData, Id as ParaId, PvfCheckStatement, SessionIndex, UpgradeGoAhead,
124	UpgradeRestriction, ValidationCode, ValidationCodeHash, ValidatorSignature, MIN_CODE_SIZE,
125};
126use scale_info::{Type, TypeInfo};
127use sp_core::RuntimeDebug;
128use sp_runtime::{
129	traits::{AppVerify, One, Saturating},
130	DispatchResult, SaturatedConversion,
131};
132
133use serde::{Deserialize, Serialize};
134
135pub use crate::Origin as ParachainOrigin;
136
137#[cfg(feature = "runtime-benchmarks")]
138pub mod benchmarking;
139
140#[cfg(test)]
141pub(crate) mod tests;
142
143pub use pallet::*;
144
145const LOG_TARGET: &str = "runtime::paras";
146
147// the two key times necessary to track for every code replacement.
148#[derive(Default, Encode, Decode, TypeInfo)]
149#[cfg_attr(test, derive(Debug, Clone, PartialEq))]
150pub struct ReplacementTimes<N> {
151	/// The relay-chain block number that the code upgrade was expected to be activated.
152	/// This is when the code change occurs from the para's perspective - after the
153	/// first parablock included with a relay-parent with number >= this value.
154	expected_at: N,
155	/// The relay-chain block number at which the parablock activating the code upgrade was
156	/// actually included. This means considered included and available, so this is the time at
157	/// which that parablock enters the acceptance period in this fork of the relay-chain.
158	activated_at: N,
159}
160
161/// Metadata used to track previous parachain validation code that we keep in
162/// the state.
163#[derive(Default, Encode, Decode, TypeInfo)]
164#[cfg_attr(test, derive(Debug, Clone, PartialEq))]
165pub struct ParaPastCodeMeta<N> {
166	/// Block numbers where the code was expected to be replaced and where the code
167	/// was actually replaced, respectively. The first is used to do accurate look-ups
168	/// of historic code in historic contexts, whereas the second is used to do
169	/// pruning on an accurate timeframe. These can be used as indices
170	/// into the `PastCodeHash` map along with the `ParaId` to fetch the code itself.
171	upgrade_times: Vec<ReplacementTimes<N>>,
172	/// Tracks the highest pruned code-replacement, if any. This is the `activated_at` value,
173	/// not the `expected_at` value.
174	last_pruned: Option<N>,
175}
176
177/// The possible states of a para, to take into account delayed lifecycle changes.
178///
179/// If the para is in a "transition state", it is expected that the parachain is
180/// queued in the `ActionsQueue` to transition it into a stable state. Its lifecycle
181/// state will be used to determine the state transition to apply to the para.
182#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
183pub enum ParaLifecycle {
184	/// Para is new and is onboarding as an on-demand or lease holding Parachain.
185	Onboarding,
186	/// Para is a Parathread (on-demand parachain).
187	Parathread,
188	/// Para is a lease holding Parachain.
189	Parachain,
190	/// Para is a Parathread (on-demand parachain) which is upgrading to a lease holding Parachain.
191	UpgradingParathread,
192	/// Para is a lease holding Parachain which is downgrading to an on-demand parachain.
193	DowngradingParachain,
194	/// Parathread (on-demand parachain) is queued to be offboarded.
195	OffboardingParathread,
196	/// Parachain is queued to be offboarded.
197	OffboardingParachain,
198}
199
200impl ParaLifecycle {
201	/// Returns true if parachain is currently onboarding. To learn if the
202	/// parachain is onboarding as a lease holding or on-demand parachain, look at the
203	/// `UpcomingGenesis` storage item.
204	pub fn is_onboarding(&self) -> bool {
205		matches!(self, ParaLifecycle::Onboarding)
206	}
207
208	/// Returns true if para is in a stable state, i.e. it is currently
209	/// a lease holding or on-demand parachain, and not in any transition state.
210	pub fn is_stable(&self) -> bool {
211		matches!(self, ParaLifecycle::Parathread | ParaLifecycle::Parachain)
212	}
213
214	/// Returns true if para is currently treated as a parachain.
215	/// This also includes transitioning states, so you may want to combine
216	/// this check with `is_stable` if you specifically want `Paralifecycle::Parachain`.
217	pub fn is_parachain(&self) -> bool {
218		matches!(
219			self,
220			ParaLifecycle::Parachain |
221				ParaLifecycle::DowngradingParachain |
222				ParaLifecycle::OffboardingParachain
223		)
224	}
225
226	/// Returns true if para is currently treated as a parathread (on-demand parachain).
227	/// This also includes transitioning states, so you may want to combine
228	/// this check with `is_stable` if you specifically want `Paralifecycle::Parathread`.
229	pub fn is_parathread(&self) -> bool {
230		matches!(
231			self,
232			ParaLifecycle::Parathread |
233				ParaLifecycle::UpgradingParathread |
234				ParaLifecycle::OffboardingParathread
235		)
236	}
237
238	/// Returns true if para is currently offboarding.
239	pub fn is_offboarding(&self) -> bool {
240		matches!(self, ParaLifecycle::OffboardingParathread | ParaLifecycle::OffboardingParachain)
241	}
242
243	/// Returns true if para is in any transitionary state.
244	pub fn is_transitioning(&self) -> bool {
245		!Self::is_stable(self)
246	}
247}
248
249impl<N: Ord + Copy + PartialEq> ParaPastCodeMeta<N> {
250	// note a replacement has occurred at a given block number.
251	pub(crate) fn note_replacement(&mut self, expected_at: N, activated_at: N) {
252		self.upgrade_times.push(ReplacementTimes { expected_at, activated_at })
253	}
254
255	/// Returns `true` if the upgrade logs list is empty.
256	fn is_empty(&self) -> bool {
257		self.upgrade_times.is_empty()
258	}
259
260	// The block at which the most recently tracked code change occurred, from the perspective
261	// of the para.
262	#[cfg(test)]
263	fn most_recent_change(&self) -> Option<N> {
264		self.upgrade_times.last().map(|x| x.expected_at)
265	}
266
267	// prunes all code upgrade logs occurring at or before `max`.
268	// note that code replaced at `x` is the code used to validate all blocks before
269	// `x`. Thus, `max` should be outside of the slashing window when this is invoked.
270	//
271	// Since we don't want to prune anything inside the acceptance period, and the parablock only
272	// enters the acceptance period after being included, we prune based on the activation height of
273	// the code change, not the expected height of the code change.
274	//
275	// returns an iterator of block numbers at which code was replaced, where the replaced
276	// code should be now pruned, in ascending order.
277	fn prune_up_to(&'_ mut self, max: N) -> impl Iterator<Item = N> + '_ {
278		let to_prune = self.upgrade_times.iter().take_while(|t| t.activated_at <= max).count();
279		let drained = if to_prune == 0 {
280			// no-op prune.
281			self.upgrade_times.drain(self.upgrade_times.len()..)
282		} else {
283			// if we are actually pruning something, update the `last_pruned` member.
284			self.last_pruned = Some(self.upgrade_times[to_prune - 1].activated_at);
285			self.upgrade_times.drain(..to_prune)
286		};
287
288		drained.map(|times| times.expected_at)
289	}
290}
291
292/// Arguments for initializing a para.
293#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo, Serialize, Deserialize)]
294pub struct ParaGenesisArgs {
295	/// The initial head data to use.
296	pub genesis_head: HeadData,
297	/// The initial validation code to use.
298	pub validation_code: ValidationCode,
299	/// Lease holding or on-demand parachain.
300	#[serde(rename = "parachain")]
301	pub para_kind: ParaKind,
302}
303
304/// Distinguishes between lease holding Parachain and Parathread (on-demand parachain)
305#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
306pub enum ParaKind {
307	Parathread,
308	Parachain,
309}
310
311impl Serialize for ParaKind {
312	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
313	where
314		S: serde::Serializer,
315	{
316		match self {
317			ParaKind::Parachain => serializer.serialize_bool(true),
318			ParaKind::Parathread => serializer.serialize_bool(false),
319		}
320	}
321}
322
323impl<'de> Deserialize<'de> for ParaKind {
324	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
325	where
326		D: serde::Deserializer<'de>,
327	{
328		match serde::de::Deserialize::deserialize(deserializer) {
329			Ok(true) => Ok(ParaKind::Parachain),
330			Ok(false) => Ok(ParaKind::Parathread),
331			_ => Err(serde::de::Error::custom("invalid ParaKind serde representation")),
332		}
333	}
334}
335
336// Manual encoding, decoding, and TypeInfo as the parakind field in ParaGenesisArgs used to be a
337// bool
338impl Encode for ParaKind {
339	fn size_hint(&self) -> usize {
340		true.size_hint()
341	}
342
343	fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
344		match self {
345			ParaKind::Parachain => true.using_encoded(f),
346			ParaKind::Parathread => false.using_encoded(f),
347		}
348	}
349}
350
351impl Decode for ParaKind {
352	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
353		match bool::decode(input) {
354			Ok(true) => Ok(ParaKind::Parachain),
355			Ok(false) => Ok(ParaKind::Parathread),
356			_ => Err("Invalid ParaKind representation".into()),
357		}
358	}
359}
360
361impl TypeInfo for ParaKind {
362	type Identity = bool;
363	fn type_info() -> Type {
364		bool::type_info()
365	}
366}
367
368/// This enum describes a reason why a particular PVF pre-checking vote was initiated. When the
369/// PVF vote in question is concluded, this enum indicates what changes should be performed.
370#[derive(Debug, Encode, Decode, TypeInfo)]
371pub(crate) enum PvfCheckCause<BlockNumber> {
372	/// PVF vote was initiated by the initial onboarding process of the given para.
373	Onboarding(ParaId),
374	/// PVF vote was initiated by signalling of an upgrade by the given para.
375	Upgrade {
376		/// The ID of the parachain that initiated or is waiting for the conclusion of
377		/// pre-checking.
378		id: ParaId,
379		/// The relay-chain block number of **inclusion** of candidate that that initiated the
380		/// upgrade.
381		///
382		/// It's important to count upgrade enactment delay from the inclusion of this candidate
383		/// instead of its relay parent -- in order to keep PVF available in case of chain
384		/// reversions.
385		///
386		/// See https://github.com/paritytech/polkadot/issues/4601 for detailed explanation.
387		included_at: BlockNumber,
388		/// Whether or not the upgrade should be enacted directly.
389		///
390		/// If set to `Yes` it means that no `GoAheadSignal` will be set and the parachain code
391		/// will also be overwritten directly.
392		upgrade_strategy: UpgradeStrategy,
393	},
394}
395
396/// The strategy on how to handle a validation code upgrade.
397///
398/// When scheduling a parachain code upgrade the upgrade first is checked by all validators. The
399/// validators ensure that the new validation code can be compiled and instantiated. After the
400/// majority of the validators have reported their checking result the upgrade is either scheduled
401/// or aborted. This strategy then comes into play around the relay chain block this upgrade was
402/// scheduled in.
403#[derive(Debug, Copy, Clone, PartialEq, TypeInfo, Decode, Encode)]
404pub enum UpgradeStrategy {
405	/// Set the `GoAhead` signal to inform the parachain that it is time to upgrade.
406	///
407	/// The upgrade will then be applied after the first parachain block was enacted that must have
408	/// observed the `GoAhead` signal.
409	SetGoAheadSignal,
410	/// Apply the upgrade directly at the expected relay chain block.
411	///
412	/// This doesn't wait for the parachain to make any kind of progress.
413	ApplyAtExpectedBlock,
414}
415
416impl<BlockNumber> PvfCheckCause<BlockNumber> {
417	/// Returns the ID of the para that initiated or subscribed to the pre-checking vote.
418	fn para_id(&self) -> ParaId {
419		match *self {
420			PvfCheckCause::Onboarding(id) => id,
421			PvfCheckCause::Upgrade { id, .. } => id,
422		}
423	}
424}
425
426/// Specifies what was the outcome of a PVF pre-checking vote.
427#[derive(Copy, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
428enum PvfCheckOutcome {
429	Accepted,
430	Rejected,
431}
432
433/// This struct describes the current state of an in-progress PVF pre-checking vote.
434#[derive(Encode, Decode, TypeInfo)]
435pub(crate) struct PvfCheckActiveVoteState<BlockNumber> {
436	// The two following vectors have their length equal to the number of validators in the active
437	// set. They start with all zeroes. A 1 is set at an index when the validator at the that index
438	// makes a vote. Once a 1 is set for either of the vectors, that validator cannot vote anymore.
439	// Since the active validator set changes each session, the bit vectors are reinitialized as
440	// well: zeroed and resized so that each validator gets its own bit.
441	votes_accept: BitVec<u8, BitOrderLsb0>,
442	votes_reject: BitVec<u8, BitOrderLsb0>,
443
444	/// The number of session changes this PVF vote has observed. Therefore, this number is
445	/// increased at each session boundary. When created, it is initialized with 0.
446	age: SessionIndex,
447	/// The block number at which this PVF vote was created.
448	created_at: BlockNumber,
449	/// A list of causes for this PVF pre-checking. Has at least one.
450	causes: Vec<PvfCheckCause<BlockNumber>>,
451}
452
453impl<BlockNumber> PvfCheckActiveVoteState<BlockNumber> {
454	/// Returns a new instance of vote state, started at the specified block `now`, with the
455	/// number of validators in the current session `n_validators` and the originating `cause`.
456	fn new(now: BlockNumber, n_validators: usize, cause: PvfCheckCause<BlockNumber>) -> Self {
457		let mut causes = Vec::with_capacity(1);
458		causes.push(cause);
459		Self {
460			created_at: now,
461			votes_accept: bitvec::bitvec![u8, BitOrderLsb0; 0; n_validators],
462			votes_reject: bitvec::bitvec![u8, BitOrderLsb0; 0; n_validators],
463			age: 0,
464			causes,
465		}
466	}
467
468	/// Resets all votes and resizes the votes vectors corresponding to the number of validators
469	/// in the new session.
470	fn reinitialize_ballots(&mut self, n_validators: usize) {
471		let clear_and_resize = |v: &mut BitVec<_, _>| {
472			v.clear();
473			v.resize(n_validators, false);
474		};
475		clear_and_resize(&mut self.votes_accept);
476		clear_and_resize(&mut self.votes_reject);
477	}
478
479	/// Returns `Some(true)` if the validator at the given index has already cast their vote within
480	/// the ongoing session. Returns `None` in case the index is out of bounds.
481	fn has_vote(&self, validator_index: usize) -> Option<bool> {
482		let accept_vote = self.votes_accept.get(validator_index)?;
483		let reject_vote = self.votes_reject.get(validator_index)?;
484		Some(*accept_vote || *reject_vote)
485	}
486
487	/// Returns `None` if the quorum is not reached, or the direction of the decision.
488	fn quorum(&self, n_validators: usize) -> Option<PvfCheckOutcome> {
489		let accept_threshold = polkadot_primitives::supermajority_threshold(n_validators);
490		// At this threshold, a supermajority is no longer possible, so we reject.
491		let reject_threshold = n_validators - accept_threshold;
492
493		if self.votes_accept.count_ones() >= accept_threshold {
494			Some(PvfCheckOutcome::Accepted)
495		} else if self.votes_reject.count_ones() > reject_threshold {
496			Some(PvfCheckOutcome::Rejected)
497		} else {
498			None
499		}
500	}
501
502	#[cfg(test)]
503	pub(crate) fn causes(&self) -> &[PvfCheckCause<BlockNumber>] {
504		self.causes.as_slice()
505	}
506}
507
508/// Runtime hook for when a parachain head is updated.
509pub trait OnNewHead {
510	/// Called when a parachain head is updated.
511	/// Returns the weight consumed by this function.
512	fn on_new_head(id: ParaId, head: &HeadData) -> Weight;
513}
514
515#[impl_trait_for_tuples::impl_for_tuples(30)]
516impl OnNewHead for Tuple {
517	fn on_new_head(id: ParaId, head: &HeadData) -> Weight {
518		let mut weight: Weight = Default::default();
519		for_tuples!( #( weight.saturating_accrue(Tuple::on_new_head(id, head)); )* );
520		weight
521	}
522}
523
524/// Assign coretime to some parachain.
525///
526/// This assigns coretime to a parachain without using the coretime chain. Thus, this should only be
527/// used for testing purposes.
528pub trait AssignCoretime {
529	/// ONLY USE FOR TESTING OR GENESIS.
530	fn assign_coretime(id: ParaId) -> DispatchResult;
531}
532
533impl AssignCoretime for () {
534	fn assign_coretime(_: ParaId) -> DispatchResult {
535		Ok(())
536	}
537}
538
539pub trait WeightInfo {
540	fn force_set_current_code(c: u32) -> Weight;
541	fn force_set_current_head(s: u32) -> Weight;
542	fn force_set_most_recent_context() -> Weight;
543	fn force_schedule_code_upgrade(c: u32) -> Weight;
544	fn force_note_new_head(s: u32) -> Weight;
545	fn force_queue_action() -> Weight;
546	fn add_trusted_validation_code(c: u32) -> Weight;
547	fn poke_unused_validation_code() -> Weight;
548
549	fn include_pvf_check_statement_finalize_upgrade_accept() -> Weight;
550	fn include_pvf_check_statement_finalize_upgrade_reject() -> Weight;
551	fn include_pvf_check_statement_finalize_onboarding_accept() -> Weight;
552	fn include_pvf_check_statement_finalize_onboarding_reject() -> Weight;
553	fn include_pvf_check_statement() -> Weight;
554}
555
556pub struct TestWeightInfo;
557impl WeightInfo for TestWeightInfo {
558	fn force_set_current_code(_c: u32) -> Weight {
559		Weight::MAX
560	}
561	fn force_set_current_head(_s: u32) -> Weight {
562		Weight::MAX
563	}
564	fn force_set_most_recent_context() -> Weight {
565		Weight::MAX
566	}
567	fn force_schedule_code_upgrade(_c: u32) -> Weight {
568		Weight::MAX
569	}
570	fn force_note_new_head(_s: u32) -> Weight {
571		Weight::MAX
572	}
573	fn force_queue_action() -> Weight {
574		Weight::MAX
575	}
576	fn add_trusted_validation_code(_c: u32) -> Weight {
577		// Called during integration tests for para initialization.
578		Weight::zero()
579	}
580	fn poke_unused_validation_code() -> Weight {
581		Weight::MAX
582	}
583	fn include_pvf_check_statement_finalize_upgrade_accept() -> Weight {
584		Weight::MAX
585	}
586	fn include_pvf_check_statement_finalize_upgrade_reject() -> Weight {
587		Weight::MAX
588	}
589	fn include_pvf_check_statement_finalize_onboarding_accept() -> Weight {
590		Weight::MAX
591	}
592	fn include_pvf_check_statement_finalize_onboarding_reject() -> Weight {
593		Weight::MAX
594	}
595	fn include_pvf_check_statement() -> Weight {
596		// This special value is to distinguish from the finalizing variants above in tests.
597		Weight::MAX - Weight::from_parts(1, 1)
598	}
599}
600
601#[frame_support::pallet]
602pub mod pallet {
603	use super::*;
604	use sp_runtime::transaction_validity::{
605		InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
606		ValidTransaction,
607	};
608
609	#[pallet::pallet]
610	#[pallet::without_storage_info]
611	pub struct Pallet<T>(_);
612
613	#[pallet::config]
614	pub trait Config:
615		frame_system::Config
616		+ configuration::Config
617		+ shared::Config
618		+ frame_system::offchain::CreateInherent<Call<Self>>
619	{
620		type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
621
622		#[pallet::constant]
623		type UnsignedPriority: Get<TransactionPriority>;
624
625		type NextSessionRotation: EstimateNextSessionRotation<BlockNumberFor<Self>>;
626
627		/// Retrieve how many UMP messages are enqueued for this para-chain.
628		///
629		/// This is used to judge whether or not a para-chain can offboard. Per default this should
630		/// be set to the `ParaInclusion` pallet.
631		type QueueFootprinter: QueueFootprinter<Origin = UmpQueueId>;
632
633		/// Runtime hook for when a parachain head is updated.
634		type OnNewHead: OnNewHead;
635
636		/// Weight information for extrinsics in this pallet.
637		type WeightInfo: WeightInfo;
638
639		/// Runtime hook for assigning coretime for a given parachain.
640		///
641		/// This is only used at genesis or by root.
642		///
643		/// TODO: Remove once coretime is the standard across all chains.
644		type AssignCoretime: AssignCoretime;
645	}
646
647	#[pallet::event]
648	#[pallet::generate_deposit(pub(super) fn deposit_event)]
649	pub enum Event {
650		/// Current code has been updated for a Para. `para_id`
651		CurrentCodeUpdated(ParaId),
652		/// Current head has been updated for a Para. `para_id`
653		CurrentHeadUpdated(ParaId),
654		/// A code upgrade has been scheduled for a Para. `para_id`
655		CodeUpgradeScheduled(ParaId),
656		/// A new head has been noted for a Para. `para_id`
657		NewHeadNoted(ParaId),
658		/// A para has been queued to execute pending actions. `para_id`
659		ActionQueued(ParaId, SessionIndex),
660		/// The given para either initiated or subscribed to a PVF check for the given validation
661		/// code. `code_hash` `para_id`
662		PvfCheckStarted(ValidationCodeHash, ParaId),
663		/// The given validation code was accepted by the PVF pre-checking vote.
664		/// `code_hash` `para_id`
665		PvfCheckAccepted(ValidationCodeHash, ParaId),
666		/// The given validation code was rejected by the PVF pre-checking vote.
667		/// `code_hash` `para_id`
668		PvfCheckRejected(ValidationCodeHash, ParaId),
669	}
670
671	#[pallet::error]
672	pub enum Error<T> {
673		/// Para is not registered in our system.
674		NotRegistered,
675		/// Para cannot be onboarded because it is already tracked by our system.
676		CannotOnboard,
677		/// Para cannot be offboarded at this time.
678		CannotOffboard,
679		/// Para cannot be upgraded to a lease holding parachain.
680		CannotUpgrade,
681		/// Para cannot be downgraded to an on-demand parachain.
682		CannotDowngrade,
683		/// The statement for PVF pre-checking is stale.
684		PvfCheckStatementStale,
685		/// The statement for PVF pre-checking is for a future session.
686		PvfCheckStatementFuture,
687		/// Claimed validator index is out of bounds.
688		PvfCheckValidatorIndexOutOfBounds,
689		/// The signature for the PVF pre-checking is invalid.
690		PvfCheckInvalidSignature,
691		/// The given validator already has cast a vote.
692		PvfCheckDoubleVote,
693		/// The given PVF does not exist at the moment of process a vote.
694		PvfCheckSubjectInvalid,
695		/// Parachain cannot currently schedule a code upgrade.
696		CannotUpgradeCode,
697		/// Invalid validation code size.
698		InvalidCode,
699	}
700
701	/// All currently active PVF pre-checking votes.
702	///
703	/// Invariant:
704	/// - There are no PVF pre-checking votes that exists in list but not in the set and vice versa.
705	#[pallet::storage]
706	pub(super) type PvfActiveVoteMap<T: Config> = StorageMap<
707		_,
708		Twox64Concat,
709		ValidationCodeHash,
710		PvfCheckActiveVoteState<BlockNumberFor<T>>,
711		OptionQuery,
712	>;
713
714	/// The list of all currently active PVF votes. Auxiliary to `PvfActiveVoteMap`.
715	#[pallet::storage]
716	pub(super) type PvfActiveVoteList<T: Config> =
717		StorageValue<_, Vec<ValidationCodeHash>, ValueQuery>;
718
719	/// All lease holding parachains. Ordered ascending by `ParaId`. On demand parachains are not
720	/// included.
721	///
722	/// Consider using the [`ParachainsCache`] type of modifying.
723	#[pallet::storage]
724	pub type Parachains<T: Config> = StorageValue<_, Vec<ParaId>, ValueQuery>;
725
726	/// The current lifecycle of a all known Para IDs.
727	#[pallet::storage]
728	pub(super) type ParaLifecycles<T: Config> = StorageMap<_, Twox64Concat, ParaId, ParaLifecycle>;
729
730	/// The head-data of every registered para.
731	#[pallet::storage]
732	pub type Heads<T: Config> = StorageMap<_, Twox64Concat, ParaId, HeadData>;
733
734	/// The context (relay-chain block number) of the most recent parachain head.
735	#[pallet::storage]
736	pub type MostRecentContext<T: Config> = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
737
738	/// The validation code hash of every live para.
739	///
740	/// Corresponding code can be retrieved with [`CodeByHash`].
741	#[pallet::storage]
742	pub type CurrentCodeHash<T: Config> = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
743
744	/// Actual past code hash, indicated by the para id as well as the block number at which it
745	/// became outdated.
746	///
747	/// Corresponding code can be retrieved with [`CodeByHash`].
748	#[pallet::storage]
749	pub(super) type PastCodeHash<T: Config> =
750		StorageMap<_, Twox64Concat, (ParaId, BlockNumberFor<T>), ValidationCodeHash>;
751
752	/// Past code of parachains. The parachains themselves may not be registered anymore,
753	/// but we also keep their code on-chain for the same amount of time as outdated code
754	/// to keep it available for approval checkers.
755	#[pallet::storage]
756	pub type PastCodeMeta<T: Config> =
757		StorageMap<_, Twox64Concat, ParaId, ParaPastCodeMeta<BlockNumberFor<T>>, ValueQuery>;
758
759	/// Which paras have past code that needs pruning and the relay-chain block at which the code
760	/// was replaced. Note that this is the actual height of the included block, not the expected
761	/// height at which the code upgrade would be applied, although they may be equal.
762	/// This is to ensure the entire acceptance period is covered, not an offset acceptance period
763	/// starting from the time at which the parachain perceives a code upgrade as having occurred.
764	/// Multiple entries for a single para are permitted. Ordered ascending by block number.
765	#[pallet::storage]
766	pub(super) type PastCodePruning<T: Config> =
767		StorageValue<_, Vec<(ParaId, BlockNumberFor<T>)>, ValueQuery>;
768
769	/// The block number at which the planned code change is expected for a parachain.
770	///
771	/// The change will be applied after the first parablock for this ID included which executes
772	/// in the context of a relay chain block with a number >= `expected_at`.
773	#[pallet::storage]
774	pub type FutureCodeUpgrades<T: Config> = StorageMap<_, Twox64Concat, ParaId, BlockNumberFor<T>>;
775
776	/// The list of upcoming future code upgrades.
777	///
778	/// Each item is a pair of the parachain and the expected block at which the upgrade should be
779	/// applied. The upgrade will be applied at the given relay chain block. In contrast to
780	/// [`FutureCodeUpgrades`] this code upgrade will be applied regardless the parachain making any
781	/// progress or not.
782	///
783	/// Ordered ascending by block number.
784	#[pallet::storage]
785	pub(super) type FutureCodeUpgradesAt<T: Config> =
786		StorageValue<_, Vec<(ParaId, BlockNumberFor<T>)>, ValueQuery>;
787
788	/// The actual future code hash of a para.
789	///
790	/// Corresponding code can be retrieved with [`CodeByHash`].
791	#[pallet::storage]
792	pub type FutureCodeHash<T: Config> = StorageMap<_, Twox64Concat, ParaId, ValidationCodeHash>;
793
794	/// This is used by the relay-chain to communicate to a parachain a go-ahead with in the upgrade
795	/// procedure.
796	///
797	/// This value is absent when there are no upgrades scheduled or during the time the relay chain
798	/// performs the checks. It is set at the first relay-chain block when the corresponding
799	/// parachain can switch its upgrade function. As soon as the parachain's block is included, the
800	/// value gets reset to `None`.
801	///
802	/// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
803	/// the format will require migration of parachains.
804	#[pallet::storage]
805	pub(super) type UpgradeGoAheadSignal<T: Config> =
806		StorageMap<_, Twox64Concat, ParaId, UpgradeGoAhead>;
807
808	/// This is used by the relay-chain to communicate that there are restrictions for performing
809	/// an upgrade for this parachain.
810	///
811	/// This may be a because the parachain waits for the upgrade cooldown to expire. Another
812	/// potential use case is when we want to perform some maintenance (such as storage migration)
813	/// we could restrict upgrades to make the process simpler.
814	///
815	/// NOTE that this field is used by parachains via merkle storage proofs, therefore changing
816	/// the format will require migration of parachains.
817	#[pallet::storage]
818	pub type UpgradeRestrictionSignal<T: Config> =
819		StorageMap<_, Twox64Concat, ParaId, UpgradeRestriction>;
820
821	/// The list of parachains that are awaiting for their upgrade restriction to cooldown.
822	///
823	/// Ordered ascending by block number.
824	#[pallet::storage]
825	pub(super) type UpgradeCooldowns<T: Config> =
826		StorageValue<_, Vec<(ParaId, BlockNumberFor<T>)>, ValueQuery>;
827
828	/// The list of upcoming code upgrades.
829	///
830	/// Each item is a pair of which para performs a code upgrade and at which relay-chain block it
831	/// is expected at.
832	///
833	/// Ordered ascending by block number.
834	#[pallet::storage]
835	pub(super) type UpcomingUpgrades<T: Config> =
836		StorageValue<_, Vec<(ParaId, BlockNumberFor<T>)>, ValueQuery>;
837
838	/// The actions to perform during the start of a specific session index.
839	#[pallet::storage]
840	pub type ActionsQueue<T: Config> =
841		StorageMap<_, Twox64Concat, SessionIndex, Vec<ParaId>, ValueQuery>;
842
843	/// Upcoming paras instantiation arguments.
844	///
845	/// NOTE that after PVF pre-checking is enabled the para genesis arg will have it's code set
846	/// to empty. Instead, the code will be saved into the storage right away via `CodeByHash`.
847	#[pallet::storage]
848	pub(super) type UpcomingParasGenesis<T: Config> =
849		StorageMap<_, Twox64Concat, ParaId, ParaGenesisArgs>;
850
851	/// The number of reference on the validation code in [`CodeByHash`] storage.
852	#[pallet::storage]
853	pub(super) type CodeByHashRefs<T: Config> =
854		StorageMap<_, Identity, ValidationCodeHash, u32, ValueQuery>;
855
856	/// Validation code stored by its hash.
857	///
858	/// This storage is consistent with [`FutureCodeHash`], [`CurrentCodeHash`] and
859	/// [`PastCodeHash`].
860	#[pallet::storage]
861	pub type CodeByHash<T: Config> = StorageMap<_, Identity, ValidationCodeHash, ValidationCode>;
862
863	#[pallet::genesis_config]
864	#[derive(DefaultNoBound)]
865	pub struct GenesisConfig<T: Config> {
866		#[serde(skip)]
867		pub _config: core::marker::PhantomData<T>,
868		pub paras: Vec<(ParaId, ParaGenesisArgs)>,
869	}
870
871	#[pallet::genesis_build]
872	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
873		fn build(&self) {
874			let mut parachains = ParachainsCache::new();
875			for (id, genesis_args) in &self.paras {
876				if genesis_args.validation_code.0.is_empty() {
877					panic!("empty validation code is not allowed in genesis");
878				}
879				Pallet::<T>::initialize_para_now(&mut parachains, *id, genesis_args);
880				T::AssignCoretime::assign_coretime(*id)
881					.expect("Assigning coretime works at genesis; qed");
882			}
883			// parachains are flushed on drop
884		}
885	}
886
887	#[pallet::call]
888	impl<T: Config> Pallet<T> {
889		/// Set the storage for the parachain validation code immediately.
890		#[pallet::call_index(0)]
891		#[pallet::weight(<T as Config>::WeightInfo::force_set_current_code(new_code.0.len() as u32))]
892		pub fn force_set_current_code(
893			origin: OriginFor<T>,
894			para: ParaId,
895			new_code: ValidationCode,
896		) -> DispatchResult {
897			ensure_root(origin)?;
898			let new_code_hash = new_code.hash();
899			Self::increase_code_ref(&new_code_hash, &new_code);
900			Self::set_current_code(para, new_code_hash, frame_system::Pallet::<T>::block_number());
901			Self::deposit_event(Event::CurrentCodeUpdated(para));
902			Ok(())
903		}
904
905		/// Set the storage for the current parachain head data immediately.
906		#[pallet::call_index(1)]
907		#[pallet::weight(<T as Config>::WeightInfo::force_set_current_head(new_head.0.len() as u32))]
908		pub fn force_set_current_head(
909			origin: OriginFor<T>,
910			para: ParaId,
911			new_head: HeadData,
912		) -> DispatchResult {
913			ensure_root(origin)?;
914			Self::set_current_head(para, new_head);
915			Ok(())
916		}
917
918		/// Schedule an upgrade as if it was scheduled in the given relay parent block.
919		#[pallet::call_index(2)]
920		#[pallet::weight(<T as Config>::WeightInfo::force_schedule_code_upgrade(new_code.0.len() as u32))]
921		pub fn force_schedule_code_upgrade(
922			origin: OriginFor<T>,
923			para: ParaId,
924			new_code: ValidationCode,
925			relay_parent_number: BlockNumberFor<T>,
926		) -> DispatchResult {
927			ensure_root(origin)?;
928			let config = configuration::ActiveConfig::<T>::get();
929			Self::schedule_code_upgrade(
930				para,
931				new_code,
932				relay_parent_number,
933				&config,
934				UpgradeStrategy::ApplyAtExpectedBlock,
935			);
936			Self::deposit_event(Event::CodeUpgradeScheduled(para));
937			Ok(())
938		}
939
940		/// Note a new block head for para within the context of the current block.
941		#[pallet::call_index(3)]
942		#[pallet::weight(<T as Config>::WeightInfo::force_note_new_head(new_head.0.len() as u32))]
943		pub fn force_note_new_head(
944			origin: OriginFor<T>,
945			para: ParaId,
946			new_head: HeadData,
947		) -> DispatchResult {
948			ensure_root(origin)?;
949			let now = frame_system::Pallet::<T>::block_number();
950			Self::note_new_head(para, new_head, now);
951			Self::deposit_event(Event::NewHeadNoted(para));
952			Ok(())
953		}
954
955		/// Put a parachain directly into the next session's action queue.
956		/// We can't queue it any sooner than this without going into the
957		/// initializer...
958		#[pallet::call_index(4)]
959		#[pallet::weight(<T as Config>::WeightInfo::force_queue_action())]
960		pub fn force_queue_action(origin: OriginFor<T>, para: ParaId) -> DispatchResult {
961			ensure_root(origin)?;
962			let next_session = shared::CurrentSessionIndex::<T>::get().saturating_add(One::one());
963			ActionsQueue::<T>::mutate(next_session, |v| {
964				if let Err(i) = v.binary_search(&para) {
965					v.insert(i, para);
966				}
967			});
968			Self::deposit_event(Event::ActionQueued(para, next_session));
969			Ok(())
970		}
971
972		/// Adds the validation code to the storage.
973		///
974		/// The code will not be added if it is already present. Additionally, if PVF pre-checking
975		/// is running for that code, it will be instantly accepted.
976		///
977		/// Otherwise, the code will be added into the storage. Note that the code will be added
978		/// into storage with reference count 0. This is to account the fact that there are no users
979		/// for this code yet. The caller will have to make sure that this code eventually gets
980		/// used by some parachain or removed from the storage to avoid storage leaks. For the
981		/// latter prefer to use the `poke_unused_validation_code` dispatchable to raw storage
982		/// manipulation.
983		///
984		/// This function is mainly meant to be used for upgrading parachains that do not follow
985		/// the go-ahead signal while the PVF pre-checking feature is enabled.
986		#[pallet::call_index(5)]
987		#[pallet::weight(<T as Config>::WeightInfo::add_trusted_validation_code(validation_code.0.len() as u32))]
988		pub fn add_trusted_validation_code(
989			origin: OriginFor<T>,
990			validation_code: ValidationCode,
991		) -> DispatchResult {
992			ensure_root(origin)?;
993			let code_hash = validation_code.hash();
994
995			if let Some(vote) = PvfActiveVoteMap::<T>::get(&code_hash) {
996				// Remove the existing vote.
997				PvfActiveVoteMap::<T>::remove(&code_hash);
998				PvfActiveVoteList::<T>::mutate(|l| {
999					if let Ok(i) = l.binary_search(&code_hash) {
1000						l.remove(i);
1001					}
1002				});
1003
1004				let cfg = configuration::ActiveConfig::<T>::get();
1005				Self::enact_pvf_accepted(
1006					frame_system::Pallet::<T>::block_number(),
1007					&code_hash,
1008					&vote.causes,
1009					vote.age,
1010					&cfg,
1011				);
1012				return Ok(())
1013			}
1014
1015			if CodeByHash::<T>::contains_key(&code_hash) {
1016				// There is no vote, but the code exists. Nothing to do here.
1017				return Ok(())
1018			}
1019
1020			// At this point the code is unknown and there is no PVF pre-checking vote for it, so we
1021			// can just add the code into the storage.
1022			//
1023			// NOTE That we do not use `increase_code_ref` here, because the code is not yet used
1024			// by any parachain.
1025			CodeByHash::<T>::insert(code_hash, &validation_code);
1026
1027			Ok(())
1028		}
1029
1030		/// Remove the validation code from the storage iff the reference count is 0.
1031		///
1032		/// This is better than removing the storage directly, because it will not remove the code
1033		/// that was suddenly got used by some parachain while this dispatchable was pending
1034		/// dispatching.
1035		#[pallet::call_index(6)]
1036		#[pallet::weight(<T as Config>::WeightInfo::poke_unused_validation_code())]
1037		pub fn poke_unused_validation_code(
1038			origin: OriginFor<T>,
1039			validation_code_hash: ValidationCodeHash,
1040		) -> DispatchResult {
1041			ensure_root(origin)?;
1042			if CodeByHashRefs::<T>::get(&validation_code_hash) == 0 {
1043				CodeByHash::<T>::remove(&validation_code_hash);
1044			}
1045			Ok(())
1046		}
1047
1048		/// Includes a statement for a PVF pre-checking vote. Potentially, finalizes the vote and
1049		/// enacts the results if that was the last vote before achieving the supermajority.
1050		#[pallet::call_index(7)]
1051		#[pallet::weight(
1052			<T as Config>::WeightInfo::include_pvf_check_statement_finalize_upgrade_accept()
1053				.max(<T as Config>::WeightInfo::include_pvf_check_statement_finalize_upgrade_reject())
1054				.max(<T as Config>::WeightInfo::include_pvf_check_statement_finalize_onboarding_accept()
1055					.max(<T as Config>::WeightInfo::include_pvf_check_statement_finalize_onboarding_reject())
1056				)
1057		)]
1058		pub fn include_pvf_check_statement(
1059			origin: OriginFor<T>,
1060			stmt: PvfCheckStatement,
1061			signature: ValidatorSignature,
1062		) -> DispatchResultWithPostInfo {
1063			ensure_none(origin)?;
1064
1065			let validators = shared::ActiveValidatorKeys::<T>::get();
1066			let current_session = shared::CurrentSessionIndex::<T>::get();
1067			if stmt.session_index < current_session {
1068				return Err(Error::<T>::PvfCheckStatementStale.into())
1069			} else if stmt.session_index > current_session {
1070				return Err(Error::<T>::PvfCheckStatementFuture.into())
1071			}
1072			let validator_index = stmt.validator_index.0 as usize;
1073			let validator_public = validators
1074				.get(validator_index)
1075				.ok_or(Error::<T>::PvfCheckValidatorIndexOutOfBounds)?;
1076
1077			let signing_payload = stmt.signing_payload();
1078			ensure!(
1079				signature.verify(&signing_payload[..], &validator_public),
1080				Error::<T>::PvfCheckInvalidSignature,
1081			);
1082
1083			let mut active_vote = PvfActiveVoteMap::<T>::get(&stmt.subject)
1084				.ok_or(Error::<T>::PvfCheckSubjectInvalid)?;
1085
1086			// Ensure that the validator submitting this statement hasn't voted already.
1087			ensure!(
1088				!active_vote
1089					.has_vote(validator_index)
1090					.ok_or(Error::<T>::PvfCheckValidatorIndexOutOfBounds)?,
1091				Error::<T>::PvfCheckDoubleVote,
1092			);
1093
1094			// Finally, cast the vote and persist.
1095			if stmt.accept {
1096				active_vote.votes_accept.set(validator_index, true);
1097			} else {
1098				active_vote.votes_reject.set(validator_index, true);
1099			}
1100
1101			if let Some(outcome) = active_vote.quorum(validators.len()) {
1102				// The quorum has been achieved.
1103				//
1104				// Remove the PVF vote from the active map and finalize the PVF checking according
1105				// to the outcome.
1106				PvfActiveVoteMap::<T>::remove(&stmt.subject);
1107				PvfActiveVoteList::<T>::mutate(|l| {
1108					if let Ok(i) = l.binary_search(&stmt.subject) {
1109						l.remove(i);
1110					}
1111				});
1112				match outcome {
1113					PvfCheckOutcome::Accepted => {
1114						let cfg = configuration::ActiveConfig::<T>::get();
1115						Self::enact_pvf_accepted(
1116							frame_system::Pallet::<T>::block_number(),
1117							&stmt.subject,
1118							&active_vote.causes,
1119							active_vote.age,
1120							&cfg,
1121						);
1122					},
1123					PvfCheckOutcome::Rejected => {
1124						Self::enact_pvf_rejected(&stmt.subject, active_vote.causes);
1125					},
1126				}
1127
1128				// No weight refund since this statement was the last one and lead to finalization.
1129				Ok(().into())
1130			} else {
1131				// No quorum has been achieved.
1132				//
1133				// - So just store the updated state back into the storage.
1134				// - Only charge weight for simple vote inclusion.
1135				PvfActiveVoteMap::<T>::insert(&stmt.subject, active_vote);
1136				Ok(Some(<T as Config>::WeightInfo::include_pvf_check_statement()).into())
1137			}
1138		}
1139
1140		/// Set the storage for the current parachain head data immediately.
1141		#[pallet::call_index(8)]
1142		#[pallet::weight(<T as Config>::WeightInfo::force_set_most_recent_context())]
1143		pub fn force_set_most_recent_context(
1144			origin: OriginFor<T>,
1145			para: ParaId,
1146			context: BlockNumberFor<T>,
1147		) -> DispatchResult {
1148			ensure_root(origin)?;
1149			MostRecentContext::<T>::insert(&para, context);
1150			Ok(())
1151		}
1152	}
1153
1154	#[pallet::validate_unsigned]
1155	impl<T: Config> ValidateUnsigned for Pallet<T> {
1156		type Call = Call<T>;
1157
1158		fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
1159			let (stmt, signature) = match call {
1160				Call::include_pvf_check_statement { stmt, signature } => (stmt, signature),
1161				_ => return InvalidTransaction::Call.into(),
1162			};
1163
1164			let current_session = shared::CurrentSessionIndex::<T>::get();
1165			if stmt.session_index < current_session {
1166				return InvalidTransaction::Stale.into()
1167			} else if stmt.session_index > current_session {
1168				return InvalidTransaction::Future.into()
1169			}
1170
1171			let validator_index = stmt.validator_index.0 as usize;
1172			let validators = shared::ActiveValidatorKeys::<T>::get();
1173			let validator_public = match validators.get(validator_index) {
1174				Some(pk) => pk,
1175				None => return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into(),
1176			};
1177
1178			let signing_payload = stmt.signing_payload();
1179			if !signature.verify(&signing_payload[..], &validator_public) {
1180				return InvalidTransaction::BadProof.into()
1181			}
1182
1183			let active_vote = match PvfActiveVoteMap::<T>::get(&stmt.subject) {
1184				Some(v) => v,
1185				None => return InvalidTransaction::Custom(INVALID_TX_BAD_SUBJECT).into(),
1186			};
1187
1188			match active_vote.has_vote(validator_index) {
1189				Some(false) => (),
1190				Some(true) => return InvalidTransaction::Custom(INVALID_TX_DOUBLE_VOTE).into(),
1191				None => return InvalidTransaction::Custom(INVALID_TX_BAD_VALIDATOR_IDX).into(),
1192			}
1193
1194			ValidTransaction::with_tag_prefix("PvfPreCheckingVote")
1195				.priority(T::UnsignedPriority::get())
1196				.longevity(
1197					TryInto::<u64>::try_into(
1198						T::NextSessionRotation::average_session_length() / 2u32.into(),
1199					)
1200					.unwrap_or(64_u64),
1201				)
1202				.and_provides((stmt.session_index, stmt.validator_index, stmt.subject))
1203				.propagate(true)
1204				.build()
1205		}
1206
1207		fn pre_dispatch(_call: &Self::Call) -> Result<(), TransactionValidityError> {
1208			// Return `Ok` here meaning that as soon as the transaction got into the block, it will
1209			// always dispatched. This is OK, since the `include_pvf_check_statement` dispatchable
1210			// will perform the same checks anyway, so there is no point doing it here.
1211			//
1212			// On the other hand, if we did not provide the implementation, then the default
1213			// implementation would be used. The default implementation just delegates the
1214			// pre-dispatch validation to `validate_unsigned`.
1215			Ok(())
1216		}
1217	}
1218}
1219
1220// custom transaction error codes
1221const INVALID_TX_BAD_VALIDATOR_IDX: u8 = 1;
1222const INVALID_TX_BAD_SUBJECT: u8 = 2;
1223const INVALID_TX_DOUBLE_VOTE: u8 = 3;
1224
1225/// This is intermediate "fix" for this issue:
1226/// <https://github.com/paritytech/polkadot-sdk/issues/4737>
1227///
1228/// It does not actually fix it, but makes the worst case better. Without that limit someone
1229/// could completely DoS the relay chain by registering a ridiculously high amount of paras.
1230/// With this limit the same attack could lead to some parachains ceasing to being able to
1231/// communicate via offchain XCMP. Snowbridge will still work as it only cares about `BridgeHub`.
1232pub const MAX_PARA_HEADS: usize = 1024;
1233
1234impl<T: Config> Pallet<T> {
1235	/// This is a call to schedule code upgrades for parachains which is safe to be called
1236	/// outside of this module. That means this function does all checks necessary to ensure
1237	/// that some external code is allowed to trigger a code upgrade. We do not do auth checks,
1238	/// that should be handled by whomever calls this function.
1239	pub(crate) fn schedule_code_upgrade_external(
1240		id: ParaId,
1241		new_code: ValidationCode,
1242		upgrade_strategy: UpgradeStrategy,
1243	) -> DispatchResult {
1244		// Check that we can schedule an upgrade at all.
1245		ensure!(Self::can_upgrade_validation_code(id), Error::<T>::CannotUpgradeCode);
1246		let config = configuration::ActiveConfig::<T>::get();
1247		// Validation code sanity checks:
1248		ensure!(new_code.0.len() >= MIN_CODE_SIZE as usize, Error::<T>::InvalidCode);
1249		ensure!(new_code.0.len() <= config.max_code_size as usize, Error::<T>::InvalidCode);
1250
1251		let current_block = frame_system::Pallet::<T>::block_number();
1252		// Schedule the upgrade with a delay just like if a parachain triggered the upgrade.
1253		let upgrade_block = current_block.saturating_add(config.validation_upgrade_delay);
1254		Self::schedule_code_upgrade(id, new_code, upgrade_block, &config, upgrade_strategy);
1255		Self::deposit_event(Event::CodeUpgradeScheduled(id));
1256		Ok(())
1257	}
1258
1259	/// Set the current head of a parachain.
1260	pub(crate) fn set_current_head(para: ParaId, new_head: HeadData) {
1261		Heads::<T>::insert(&para, new_head);
1262		Self::deposit_event(Event::CurrentHeadUpdated(para));
1263	}
1264
1265	/// Called by the initializer to initialize the paras pallet.
1266	pub(crate) fn initializer_initialize(now: BlockNumberFor<T>) -> Weight {
1267		Self::prune_old_code(now) +
1268			Self::process_scheduled_upgrade_changes(now) +
1269			Self::process_future_code_upgrades_at(now)
1270	}
1271
1272	/// Called by the initializer to finalize the paras pallet.
1273	pub(crate) fn initializer_finalize(now: BlockNumberFor<T>) {
1274		Self::process_scheduled_upgrade_cooldowns(now);
1275	}
1276
1277	/// Called by the initializer to note that a new session has started.
1278	///
1279	/// Returns the list of outgoing paras from the actions queue.
1280	pub(crate) fn initializer_on_new_session(
1281		notification: &SessionChangeNotification<BlockNumberFor<T>>,
1282	) -> Vec<ParaId> {
1283		let outgoing_paras = Self::apply_actions_queue(notification.session_index);
1284		Self::groom_ongoing_pvf_votes(&notification.new_config, notification.validators.len());
1285		outgoing_paras
1286	}
1287
1288	/// The validation code of live para.
1289	pub(crate) fn current_code(para_id: &ParaId) -> Option<ValidationCode> {
1290		CurrentCodeHash::<T>::get(para_id).and_then(|code_hash| {
1291			let code = CodeByHash::<T>::get(&code_hash);
1292			if code.is_none() {
1293				log::error!(
1294					"Pallet paras storage is inconsistent, code not found for hash {}",
1295					code_hash,
1296				);
1297				debug_assert!(false, "inconsistent paras storages");
1298			}
1299			code
1300		})
1301	}
1302
1303	/// Get a list of the first [`MAX_PARA_HEADS`] para heads sorted by para_id.
1304	/// This method is likely to be removed in the future.
1305	pub fn sorted_para_heads() -> Vec<(u32, Vec<u8>)> {
1306		let mut heads: Vec<(u32, Vec<u8>)> =
1307			Heads::<T>::iter().map(|(id, head)| (id.into(), head.0)).collect();
1308		heads.sort_by_key(|(id, _)| *id);
1309		heads.truncate(MAX_PARA_HEADS);
1310		heads
1311	}
1312
1313	// Apply all para actions queued for the given session index.
1314	//
1315	// The actions to take are based on the lifecycle of of the paras.
1316	//
1317	// The final state of any para after the actions queue should be as a
1318	// lease holding parachain, on-demand parachain, or not registered. (stable states)
1319	//
1320	// Returns the list of outgoing paras from the actions queue.
1321	fn apply_actions_queue(session: SessionIndex) -> Vec<ParaId> {
1322		let actions = ActionsQueue::<T>::take(session);
1323		let mut parachains = ParachainsCache::new();
1324		let now = frame_system::Pallet::<T>::block_number();
1325		let mut outgoing = Vec::new();
1326
1327		for para in actions {
1328			let lifecycle = ParaLifecycles::<T>::get(&para);
1329			match lifecycle {
1330				None | Some(ParaLifecycle::Parathread) | Some(ParaLifecycle::Parachain) => { /* Nothing to do... */
1331				},
1332				Some(ParaLifecycle::Onboarding) => {
1333					if let Some(genesis_data) = UpcomingParasGenesis::<T>::take(&para) {
1334						Self::initialize_para_now(&mut parachains, para, &genesis_data);
1335					}
1336				},
1337				// Upgrade an on-demand parachain to a lease holding parachain
1338				Some(ParaLifecycle::UpgradingParathread) => {
1339					parachains.add(para);
1340					ParaLifecycles::<T>::insert(&para, ParaLifecycle::Parachain);
1341				},
1342				// Downgrade a lease holding parachain to an on-demand parachain
1343				Some(ParaLifecycle::DowngradingParachain) => {
1344					parachains.remove(para);
1345					ParaLifecycles::<T>::insert(&para, ParaLifecycle::Parathread);
1346				},
1347				// Offboard a lease holding or on-demand parachain from the system
1348				Some(ParaLifecycle::OffboardingParachain) |
1349				Some(ParaLifecycle::OffboardingParathread) => {
1350					parachains.remove(para);
1351
1352					Heads::<T>::remove(&para);
1353					MostRecentContext::<T>::remove(&para);
1354					FutureCodeUpgrades::<T>::remove(&para);
1355					UpgradeGoAheadSignal::<T>::remove(&para);
1356					UpgradeRestrictionSignal::<T>::remove(&para);
1357					ParaLifecycles::<T>::remove(&para);
1358					let removed_future_code_hash = FutureCodeHash::<T>::take(&para);
1359					if let Some(removed_future_code_hash) = removed_future_code_hash {
1360						Self::decrease_code_ref(&removed_future_code_hash);
1361					}
1362
1363					let removed_code_hash = CurrentCodeHash::<T>::take(&para);
1364					if let Some(removed_code_hash) = removed_code_hash {
1365						Self::note_past_code(para, now, now, removed_code_hash);
1366					}
1367
1368					outgoing.push(para);
1369				},
1370			}
1371		}
1372
1373		if !outgoing.is_empty() {
1374			// Filter offboarded parachains from the upcoming upgrades and upgrade cooldowns list.
1375			//
1376			// We do it after the offboarding to get away with only a single read/write per list.
1377			//
1378			// NOTE both of those iterates over the list and the outgoing. We do not expect either
1379			//      of these to be large. Thus should be fine.
1380			UpcomingUpgrades::<T>::mutate(|upcoming_upgrades| {
1381				upcoming_upgrades.retain(|(para, _)| !outgoing.contains(para));
1382			});
1383			UpgradeCooldowns::<T>::mutate(|upgrade_cooldowns| {
1384				upgrade_cooldowns.retain(|(para, _)| !outgoing.contains(para));
1385			});
1386			FutureCodeUpgradesAt::<T>::mutate(|future_upgrades| {
1387				future_upgrades.retain(|(para, _)| !outgoing.contains(para));
1388			});
1389		}
1390
1391		// Persist parachains into the storage explicitly.
1392		drop(parachains);
1393
1394		outgoing
1395	}
1396
1397	// note replacement of the code of para with given `id`, which occurred in the
1398	// context of the given relay-chain block number. provide the replaced code.
1399	//
1400	// `at` for para-triggered replacement is the block number of the relay-chain
1401	// block in whose context the parablock was executed
1402	// (i.e. number of `relay_parent` in the receipt)
1403	fn note_past_code(
1404		id: ParaId,
1405		at: BlockNumberFor<T>,
1406		now: BlockNumberFor<T>,
1407		old_code_hash: ValidationCodeHash,
1408	) -> Weight {
1409		PastCodeMeta::<T>::mutate(&id, |past_meta| {
1410			past_meta.note_replacement(at, now);
1411		});
1412
1413		PastCodeHash::<T>::insert(&(id, at), old_code_hash);
1414
1415		// Schedule pruning for this past-code to be removed as soon as it
1416		// exits the slashing window.
1417		PastCodePruning::<T>::mutate(|pruning| {
1418			let insert_idx =
1419				pruning.binary_search_by_key(&now, |&(_, b)| b).unwrap_or_else(|idx| idx);
1420			pruning.insert(insert_idx, (id, now));
1421		});
1422
1423		T::DbWeight::get().reads_writes(2, 3)
1424	}
1425
1426	// looks at old code metadata, compares them to the current acceptance window, and prunes those
1427	// that are too old.
1428	fn prune_old_code(now: BlockNumberFor<T>) -> Weight {
1429		let config = configuration::ActiveConfig::<T>::get();
1430		let code_retention_period = config.code_retention_period;
1431		if now <= code_retention_period {
1432			let weight = T::DbWeight::get().reads_writes(1, 0);
1433			return weight
1434		}
1435
1436		// The height of any changes we no longer should keep around.
1437		let pruning_height = now - (code_retention_period + One::one());
1438
1439		let pruning_tasks_done =
1440			PastCodePruning::<T>::mutate(|pruning_tasks: &mut Vec<(_, BlockNumberFor<T>)>| {
1441				let (pruning_tasks_done, pruning_tasks_to_do) = {
1442					// find all past code that has just exited the pruning window.
1443					let up_to_idx =
1444						pruning_tasks.iter().take_while(|&(_, at)| at <= &pruning_height).count();
1445					(up_to_idx, pruning_tasks.drain(..up_to_idx))
1446				};
1447
1448				for (para_id, _) in pruning_tasks_to_do {
1449					let full_deactivate = PastCodeMeta::<T>::mutate(&para_id, |meta| {
1450						for pruned_repl_at in meta.prune_up_to(pruning_height) {
1451							let removed_code_hash =
1452								PastCodeHash::<T>::take(&(para_id, pruned_repl_at));
1453
1454							if let Some(removed_code_hash) = removed_code_hash {
1455								Self::decrease_code_ref(&removed_code_hash);
1456							} else {
1457								log::warn!(
1458									target: LOG_TARGET,
1459									"Missing code for removed hash {:?}",
1460									removed_code_hash,
1461								);
1462							}
1463						}
1464
1465						meta.is_empty() && Heads::<T>::get(&para_id).is_none()
1466					});
1467
1468					// This parachain has been removed and now the vestigial code
1469					// has been removed from the state. clean up meta as well.
1470					if full_deactivate {
1471						PastCodeMeta::<T>::remove(&para_id);
1472					}
1473				}
1474
1475				pruning_tasks_done as u64
1476			});
1477
1478		// 1 read for the meta for each pruning task, 1 read for the config
1479		// 2 writes: updating the meta and pruning the code
1480		T::DbWeight::get().reads_writes(1 + pruning_tasks_done, 2 * pruning_tasks_done)
1481	}
1482
1483	/// Process the future code upgrades that should be applied directly.
1484	///
1485	/// Upgrades that should not be applied directly are being processed in
1486	/// [`Self::process_scheduled_upgrade_changes`].
1487	fn process_future_code_upgrades_at(now: BlockNumberFor<T>) -> Weight {
1488		// account weight for `FutureCodeUpgradeAt::mutate`.
1489		let mut weight = T::DbWeight::get().reads_writes(1, 1);
1490		FutureCodeUpgradesAt::<T>::mutate(
1491			|upcoming_upgrades: &mut Vec<(ParaId, BlockNumberFor<T>)>| {
1492				let num = upcoming_upgrades.iter().take_while(|&(_, at)| at <= &now).count();
1493				for (id, expected_at) in upcoming_upgrades.drain(..num) {
1494					weight += T::DbWeight::get().reads_writes(1, 1);
1495
1496					// Both should always be `Some` in this case, since a code upgrade is scheduled.
1497					let new_code_hash = if let Some(new_code_hash) = FutureCodeHash::<T>::take(&id)
1498					{
1499						new_code_hash
1500					} else {
1501						log::error!(target: LOG_TARGET, "Missing future code hash for {:?}", &id);
1502						continue
1503					};
1504
1505					weight += Self::set_current_code(id, new_code_hash, expected_at);
1506				}
1507				num
1508			},
1509		);
1510
1511		weight
1512	}
1513
1514	/// Process the timers related to upgrades. Specifically, the upgrade go ahead signals toggle
1515	/// and the upgrade cooldown restrictions. However, this function does not actually unset
1516	/// the upgrade restriction, that will happen in the `initializer_finalize` function. However,
1517	/// this function does count the number of cooldown timers expired so that we can reserve weight
1518	/// for the `initializer_finalize` function.
1519	fn process_scheduled_upgrade_changes(now: BlockNumberFor<T>) -> Weight {
1520		// account weight for `UpcomingUpgrades::mutate`.
1521		let mut weight = T::DbWeight::get().reads_writes(1, 1);
1522		let upgrades_signaled = UpcomingUpgrades::<T>::mutate(
1523			|upcoming_upgrades: &mut Vec<(ParaId, BlockNumberFor<T>)>| {
1524				let num = upcoming_upgrades.iter().take_while(|&(_, at)| at <= &now).count();
1525				for (para, _) in upcoming_upgrades.drain(..num) {
1526					UpgradeGoAheadSignal::<T>::insert(&para, UpgradeGoAhead::GoAhead);
1527				}
1528				num
1529			},
1530		);
1531		weight += T::DbWeight::get().writes(upgrades_signaled as u64);
1532
1533		// account weight for `UpgradeCooldowns::get`.
1534		weight += T::DbWeight::get().reads(1);
1535		let cooldowns_expired =
1536			UpgradeCooldowns::<T>::get().iter().take_while(|&(_, at)| at <= &now).count();
1537
1538		// reserve weight for `initializer_finalize`:
1539		// - 1 read and 1 write for `UpgradeCooldowns::mutate`.
1540		// - 1 write per expired cooldown.
1541		weight += T::DbWeight::get().reads_writes(1, 1);
1542		weight += T::DbWeight::get().reads(cooldowns_expired as u64);
1543
1544		weight
1545	}
1546
1547	/// Actually perform unsetting the expired upgrade restrictions.
1548	///
1549	/// See `process_scheduled_upgrade_changes` for more details.
1550	fn process_scheduled_upgrade_cooldowns(now: BlockNumberFor<T>) {
1551		UpgradeCooldowns::<T>::mutate(
1552			|upgrade_cooldowns: &mut Vec<(ParaId, BlockNumberFor<T>)>| {
1553				// Remove all expired signals and also prune the cooldowns.
1554				upgrade_cooldowns.retain(|(para, at)| {
1555					if at <= &now {
1556						UpgradeRestrictionSignal::<T>::remove(&para);
1557						false
1558					} else {
1559						true
1560					}
1561				});
1562			},
1563		);
1564	}
1565
1566	/// Goes over all PVF votes in progress, reinitializes ballots, increments ages and prunes the
1567	/// active votes that reached their time-to-live.
1568	fn groom_ongoing_pvf_votes(
1569		cfg: &configuration::HostConfiguration<BlockNumberFor<T>>,
1570		new_n_validators: usize,
1571	) -> Weight {
1572		let mut weight = T::DbWeight::get().reads(1);
1573
1574		let potentially_active_votes = PvfActiveVoteList::<T>::get();
1575
1576		// Initially empty list which contains all the PVF active votes that made it through this
1577		// session change.
1578		//
1579		// **Ordered** as well as `PvfActiveVoteList`.
1580		let mut actually_active_votes = Vec::with_capacity(potentially_active_votes.len());
1581
1582		for vote_subject in potentially_active_votes {
1583			let mut vote_state = match PvfActiveVoteMap::<T>::take(&vote_subject) {
1584				Some(v) => v,
1585				None => {
1586					// This branch should never be reached. This is due to the fact that the set of
1587					// `PvfActiveVoteMap`'s keys is always equal to the set of items found in
1588					// `PvfActiveVoteList`.
1589					log::warn!(
1590						target: LOG_TARGET,
1591						"The PvfActiveVoteMap is out of sync with PvfActiveVoteList!",
1592					);
1593					debug_assert!(false);
1594					continue
1595				},
1596			};
1597
1598			vote_state.age += 1;
1599			if vote_state.age < cfg.pvf_voting_ttl {
1600				weight += T::DbWeight::get().writes(1);
1601				vote_state.reinitialize_ballots(new_n_validators);
1602				PvfActiveVoteMap::<T>::insert(&vote_subject, vote_state);
1603
1604				// push maintaining the original order.
1605				actually_active_votes.push(vote_subject);
1606			} else {
1607				// TTL is reached. Reject.
1608				weight += Self::enact_pvf_rejected(&vote_subject, vote_state.causes);
1609			}
1610		}
1611
1612		weight += T::DbWeight::get().writes(1);
1613		PvfActiveVoteList::<T>::put(actually_active_votes);
1614
1615		weight
1616	}
1617
1618	fn enact_pvf_accepted(
1619		now: BlockNumberFor<T>,
1620		code_hash: &ValidationCodeHash,
1621		causes: &[PvfCheckCause<BlockNumberFor<T>>],
1622		sessions_observed: SessionIndex,
1623		cfg: &configuration::HostConfiguration<BlockNumberFor<T>>,
1624	) -> Weight {
1625		let mut weight = Weight::zero();
1626		for cause in causes {
1627			weight += T::DbWeight::get().reads_writes(3, 2);
1628			Self::deposit_event(Event::PvfCheckAccepted(*code_hash, cause.para_id()));
1629
1630			match cause {
1631				PvfCheckCause::Onboarding(id) => {
1632					weight += Self::proceed_with_onboarding(*id, sessions_observed);
1633				},
1634				PvfCheckCause::Upgrade { id, included_at, upgrade_strategy } => {
1635					weight += Self::proceed_with_upgrade(
1636						*id,
1637						code_hash,
1638						now,
1639						*included_at,
1640						cfg,
1641						*upgrade_strategy,
1642					);
1643				},
1644			}
1645		}
1646		weight
1647	}
1648
1649	fn proceed_with_onboarding(id: ParaId, sessions_observed: SessionIndex) -> Weight {
1650		let weight = T::DbWeight::get().reads_writes(2, 1);
1651
1652		// we should onboard only after `SESSION_DELAY` sessions but we should take
1653		// into account the number of sessions the PVF pre-checking occupied.
1654		//
1655		// we cannot onboard at the current session, so it must be at least one
1656		// session ahead.
1657		let onboard_at: SessionIndex = shared::CurrentSessionIndex::<T>::get() +
1658			cmp::max(shared::SESSION_DELAY.saturating_sub(sessions_observed), 1);
1659
1660		ActionsQueue::<T>::mutate(onboard_at, |v| {
1661			if let Err(i) = v.binary_search(&id) {
1662				v.insert(i, id);
1663			}
1664		});
1665
1666		weight
1667	}
1668
1669	fn proceed_with_upgrade(
1670		id: ParaId,
1671		code_hash: &ValidationCodeHash,
1672		now: BlockNumberFor<T>,
1673		relay_parent_number: BlockNumberFor<T>,
1674		cfg: &configuration::HostConfiguration<BlockNumberFor<T>>,
1675		upgrade_strategy: UpgradeStrategy,
1676	) -> Weight {
1677		let mut weight = Weight::zero();
1678
1679		// Compute the relay-chain block number starting at which the code upgrade is ready to
1680		// be applied.
1681		//
1682		// The first parablock that has a relay-parent higher or at the same height of
1683		// `expected_at` will trigger the code upgrade. The parablock that comes after that will
1684		// be validated against the new validation code.
1685		//
1686		// Here we are trying to choose the block number that will have
1687		// `validation_upgrade_delay` blocks from the relay-parent of inclusion of the the block
1688		// that scheduled code upgrade but no less than `minimum_validation_upgrade_delay`. We
1689		// want this delay out of caution so that when the last vote for pre-checking comes the
1690		// parachain will have some time until the upgrade finally takes place.
1691		let expected_at = cmp::max(
1692			relay_parent_number + cfg.validation_upgrade_delay,
1693			now + cfg.minimum_validation_upgrade_delay,
1694		);
1695
1696		match upgrade_strategy {
1697			UpgradeStrategy::ApplyAtExpectedBlock => {
1698				FutureCodeUpgradesAt::<T>::mutate(|future_upgrades| {
1699					let insert_idx = future_upgrades
1700						.binary_search_by_key(&expected_at, |&(_, b)| b)
1701						.unwrap_or_else(|idx| idx);
1702					future_upgrades.insert(insert_idx, (id, expected_at));
1703				});
1704
1705				weight += T::DbWeight::get().reads_writes(0, 2);
1706			},
1707			UpgradeStrategy::SetGoAheadSignal => {
1708				FutureCodeUpgrades::<T>::insert(&id, expected_at);
1709
1710				UpcomingUpgrades::<T>::mutate(|upcoming_upgrades| {
1711					let insert_idx = upcoming_upgrades
1712						.binary_search_by_key(&expected_at, |&(_, b)| b)
1713						.unwrap_or_else(|idx| idx);
1714					upcoming_upgrades.insert(insert_idx, (id, expected_at));
1715				});
1716
1717				weight += T::DbWeight::get().reads_writes(1, 3);
1718			},
1719		}
1720
1721		let expected_at = expected_at.saturated_into();
1722		let log = ConsensusLog::ParaScheduleUpgradeCode(id, *code_hash, expected_at);
1723		frame_system::Pallet::<T>::deposit_log(log.into());
1724
1725		weight
1726	}
1727
1728	fn enact_pvf_rejected(
1729		code_hash: &ValidationCodeHash,
1730		causes: Vec<PvfCheckCause<BlockNumberFor<T>>>,
1731	) -> Weight {
1732		let mut weight = Weight::zero();
1733
1734		for cause in causes {
1735			// Whenever PVF pre-checking is started or a new cause is added to it, the RC is bumped.
1736			// Now we need to unbump it.
1737			weight += Self::decrease_code_ref(code_hash);
1738
1739			weight += T::DbWeight::get().reads_writes(3, 2);
1740			Self::deposit_event(Event::PvfCheckRejected(*code_hash, cause.para_id()));
1741
1742			match cause {
1743				PvfCheckCause::Onboarding(id) => {
1744					// Here we need to undo everything that was done during
1745					// `schedule_para_initialize`. Essentially, the logic is similar to offboarding,
1746					// with exception that before actual onboarding the parachain did not have a
1747					// chance to reach to upgrades. Therefore we can skip all the upgrade related
1748					// storage items here.
1749					weight += T::DbWeight::get().writes(3);
1750					UpcomingParasGenesis::<T>::remove(&id);
1751					CurrentCodeHash::<T>::remove(&id);
1752					ParaLifecycles::<T>::remove(&id);
1753				},
1754				PvfCheckCause::Upgrade { id, .. } => {
1755					weight += T::DbWeight::get().writes(2);
1756					UpgradeGoAheadSignal::<T>::insert(&id, UpgradeGoAhead::Abort);
1757					FutureCodeHash::<T>::remove(&id);
1758				},
1759			}
1760		}
1761
1762		weight
1763	}
1764
1765	/// Verify that `schedule_para_initialize` can be called successfully.
1766	///
1767	/// Returns false if para is already registered in the system.
1768	pub fn can_schedule_para_initialize(id: &ParaId) -> bool {
1769		ParaLifecycles::<T>::get(id).is_none()
1770	}
1771
1772	/// Schedule a para to be initialized. If the validation code is not already stored in the
1773	/// code storage, then a PVF pre-checking process will be initiated.
1774	///
1775	/// Only after the PVF pre-checking succeeds can the para be onboarded. Note, that calling this
1776	/// does not guarantee that the parachain will eventually be onboarded. This can happen in case
1777	/// the PVF does not pass PVF pre-checking.
1778	///
1779	/// The Para ID should be not activated in this pallet. The validation code supplied in
1780	/// `genesis_data` should not be empty. If those conditions are not met, then the para cannot
1781	/// be onboarded.
1782	pub(crate) fn schedule_para_initialize(
1783		id: ParaId,
1784		mut genesis_data: ParaGenesisArgs,
1785	) -> DispatchResult {
1786		// Make sure parachain isn't already in our system and that the onboarding parameters are
1787		// valid.
1788		ensure!(Self::can_schedule_para_initialize(&id), Error::<T>::CannotOnboard);
1789		ensure!(!genesis_data.validation_code.0.is_empty(), Error::<T>::CannotOnboard);
1790		ParaLifecycles::<T>::insert(&id, ParaLifecycle::Onboarding);
1791
1792		// HACK: here we are doing something nasty.
1793		//
1794		// In order to fix the [soaking issue] we insert the code eagerly here. When the onboarding
1795		// is finally enacted, we do not need to insert the code anymore. Therefore, there is no
1796		// reason for the validation code to be copied into the `ParaGenesisArgs`. We also do not
1797		// want to risk it by copying the validation code needlessly to not risk adding more
1798		// memory pressure.
1799		//
1800		// That said, we also want to preserve `ParaGenesisArgs` as it is, for now. There are two
1801		// reasons:
1802		//
1803		// - Doing it within the context of the PR that introduces this change is undesirable, since
1804		//   it is already a big change, and that change would require a migration. Moreover, if we
1805		//   run the new version of the runtime, there will be less things to worry about during the
1806		//   eventual proper migration.
1807		//
1808		// - This data type already is used for generating genesis, and changing it will probably
1809		//   introduce some unnecessary burden.
1810		//
1811		// So instead of going through it right now, we will do something sneaky. Specifically:
1812		//
1813		// - Insert the `CurrentCodeHash` now, instead during the onboarding. That would allow to
1814		//   get rid of hashing of the validation code when onboarding.
1815		//
1816		// - Replace `validation_code` with a sentinel value: an empty vector. This should be fine
1817		//   as long we do not allow registering parachains with empty code. At the moment of
1818		//   writing this should already be the case.
1819		//
1820		// - Empty value is treated as the current code is already inserted during the onboarding.
1821		//
1822		// This is only an intermediate solution and should be fixed in foreseeable future.
1823		//
1824		// [soaking issue]: https://github.com/paritytech/polkadot/issues/3918
1825		let validation_code =
1826			mem::replace(&mut genesis_data.validation_code, ValidationCode(Vec::new()));
1827		UpcomingParasGenesis::<T>::insert(&id, genesis_data);
1828		let validation_code_hash = validation_code.hash();
1829		CurrentCodeHash::<T>::insert(&id, validation_code_hash);
1830
1831		let cfg = configuration::ActiveConfig::<T>::get();
1832		Self::kick_off_pvf_check(
1833			PvfCheckCause::Onboarding(id),
1834			validation_code_hash,
1835			validation_code,
1836			&cfg,
1837		);
1838
1839		Ok(())
1840	}
1841
1842	/// Schedule a para to be cleaned up at the start of the next session.
1843	///
1844	/// Will return error if either is true:
1845	///
1846	/// - para is not a stable parachain (i.e. [`ParaLifecycle::is_stable`] is `false`)
1847	/// - para has a pending upgrade.
1848	/// - para has unprocessed messages in its UMP queue.
1849	///
1850	/// No-op if para is not registered at all.
1851	pub(crate) fn schedule_para_cleanup(id: ParaId) -> DispatchResult {
1852		// Disallow offboarding in case there is a PVF pre-checking in progress.
1853		//
1854		// This is not a fundamental limitation but rather simplification: it allows us to get
1855		// away without introducing additional logic for pruning and, more importantly, enacting
1856		// ongoing PVF pre-checking votes. It also removes some nasty edge cases.
1857		//
1858		// However, an upcoming upgrade on its own imposes no restrictions. An upgrade is enacted
1859		// with a new para head, so if a para never progresses we still should be able to offboard
1860		// it.
1861		//
1862		// This implicitly assumes that the given para exists, i.e. it's lifecycle != None.
1863		if let Some(future_code_hash) = FutureCodeHash::<T>::get(&id) {
1864			let active_prechecking = PvfActiveVoteList::<T>::get();
1865			if active_prechecking.contains(&future_code_hash) {
1866				return Err(Error::<T>::CannotOffboard.into())
1867			}
1868		}
1869
1870		let lifecycle = ParaLifecycles::<T>::get(&id);
1871		match lifecycle {
1872			// If para is not registered, nothing to do!
1873			None => return Ok(()),
1874			Some(ParaLifecycle::Parathread) => {
1875				ParaLifecycles::<T>::insert(&id, ParaLifecycle::OffboardingParathread);
1876			},
1877			Some(ParaLifecycle::Parachain) => {
1878				ParaLifecycles::<T>::insert(&id, ParaLifecycle::OffboardingParachain);
1879			},
1880			_ => return Err(Error::<T>::CannotOffboard.into()),
1881		}
1882
1883		let scheduled_session = Self::scheduled_session();
1884		ActionsQueue::<T>::mutate(scheduled_session, |v| {
1885			if let Err(i) = v.binary_search(&id) {
1886				v.insert(i, id);
1887			}
1888		});
1889
1890		if <T as Config>::QueueFootprinter::message_count(UmpQueueId::Para(id)) != 0 {
1891			return Err(Error::<T>::CannotOffboard.into())
1892		}
1893
1894		Ok(())
1895	}
1896
1897	/// Schedule a parathread (on-demand parachain) to be upgraded to a lease holding parachain.
1898	///
1899	/// Will return error if `ParaLifecycle` is not `Parathread`.
1900	pub(crate) fn schedule_parathread_upgrade(id: ParaId) -> DispatchResult {
1901		let scheduled_session = Self::scheduled_session();
1902		let lifecycle = ParaLifecycles::<T>::get(&id).ok_or(Error::<T>::NotRegistered)?;
1903
1904		ensure!(lifecycle == ParaLifecycle::Parathread, Error::<T>::CannotUpgrade);
1905
1906		ParaLifecycles::<T>::insert(&id, ParaLifecycle::UpgradingParathread);
1907		ActionsQueue::<T>::mutate(scheduled_session, |v| {
1908			if let Err(i) = v.binary_search(&id) {
1909				v.insert(i, id);
1910			}
1911		});
1912
1913		Ok(())
1914	}
1915
1916	/// Schedule a lease holding parachain to be downgraded to an on-demand parachain.
1917	///
1918	/// Noop if `ParaLifecycle` is not `Parachain`.
1919	pub(crate) fn schedule_parachain_downgrade(id: ParaId) -> DispatchResult {
1920		let scheduled_session = Self::scheduled_session();
1921		let lifecycle = ParaLifecycles::<T>::get(&id).ok_or(Error::<T>::NotRegistered)?;
1922
1923		ensure!(lifecycle == ParaLifecycle::Parachain, Error::<T>::CannotDowngrade);
1924
1925		ParaLifecycles::<T>::insert(&id, ParaLifecycle::DowngradingParachain);
1926		ActionsQueue::<T>::mutate(scheduled_session, |v| {
1927			if let Err(i) = v.binary_search(&id) {
1928				v.insert(i, id);
1929			}
1930		});
1931
1932		Ok(())
1933	}
1934
1935	/// Schedule a future code upgrade of the given parachain.
1936	///
1937	/// If the new code is not known, then the PVF pre-checking will be started for that validation
1938	/// code. In case the validation code does not pass the PVF pre-checking process, the
1939	/// upgrade will be aborted.
1940	///
1941	/// Only after the code is approved by the process, the upgrade can be scheduled. Specifically,
1942	/// the relay-chain block number will be determined at which the upgrade will take place. We
1943	/// call that block `expected_at`.
1944	///
1945	/// Once the candidate with the relay-parent >= `expected_at` is enacted, the new validation
1946	/// code will be applied. Therefore, the new code will be used to validate the next candidate.
1947	///
1948	/// The new code should not be equal to the current one, otherwise the upgrade will be aborted.
1949	/// If there is already a scheduled code upgrade for the para, this is a no-op.
1950	///
1951	/// Inclusion block number specifies relay parent which enacted candidate initiating the
1952	/// upgrade.
1953	pub(crate) fn schedule_code_upgrade(
1954		id: ParaId,
1955		new_code: ValidationCode,
1956		inclusion_block_number: BlockNumberFor<T>,
1957		cfg: &configuration::HostConfiguration<BlockNumberFor<T>>,
1958		upgrade_strategy: UpgradeStrategy,
1959	) {
1960		// Should be prevented by checks in `schedule_code_upgrade_external`
1961		let new_code_len = new_code.0.len();
1962		if new_code_len < MIN_CODE_SIZE as usize || new_code_len > cfg.max_code_size as usize {
1963			log::warn!(target: LOG_TARGET, "attempted to schedule an upgrade with invalid new validation code",);
1964			return
1965		}
1966
1967		// Enacting this should be prevented by the `can_upgrade_validation_code`
1968		if FutureCodeHash::<T>::contains_key(&id) {
1969			// This branch should never be reached. Signalling an upgrade is disallowed for a para
1970			// that already has one upgrade scheduled.
1971			//
1972			// Any candidate that attempts to do that should be rejected by
1973			// `can_upgrade_validation_code`.
1974			//
1975			// NOTE: we cannot set `UpgradeGoAheadSignal` signal here since this will be reset by
1976			//       the following call `note_new_head`
1977			log::warn!(target: LOG_TARGET, "ended up scheduling an upgrade while one is pending",);
1978			return
1979		}
1980
1981		let code_hash = new_code.hash();
1982
1983		// para signals an update to the same code? This does not make a lot of sense, so abort the
1984		// process right away.
1985		//
1986		// We do not want to allow this since it will mess with the code reference counting.
1987		if CurrentCodeHash::<T>::get(&id) == Some(code_hash) {
1988			// NOTE: we cannot set `UpgradeGoAheadSignal` signal here since this will be reset by
1989			//       the following call `note_new_head`
1990			log::warn!(
1991				target: LOG_TARGET,
1992				"para tried to upgrade to the same code. Abort the upgrade",
1993			);
1994			return
1995		}
1996
1997		// This is the start of the upgrade process. Prevent any further attempts at upgrading.
1998		FutureCodeHash::<T>::insert(&id, &code_hash);
1999		UpgradeRestrictionSignal::<T>::insert(&id, UpgradeRestriction::Present);
2000
2001		let next_possible_upgrade_at = inclusion_block_number + cfg.validation_upgrade_cooldown;
2002		UpgradeCooldowns::<T>::mutate(|upgrade_cooldowns| {
2003			let insert_idx = upgrade_cooldowns
2004				.binary_search_by_key(&next_possible_upgrade_at, |&(_, b)| b)
2005				.unwrap_or_else(|idx| idx);
2006			upgrade_cooldowns.insert(insert_idx, (id, next_possible_upgrade_at));
2007		});
2008
2009		Self::kick_off_pvf_check(
2010			PvfCheckCause::Upgrade { id, included_at: inclusion_block_number, upgrade_strategy },
2011			code_hash,
2012			new_code,
2013			cfg,
2014		);
2015	}
2016
2017	/// Makes sure that the given code hash has passed pre-checking.
2018	///
2019	/// If the given code hash has already passed pre-checking, then the approval happens
2020	/// immediately.
2021	///
2022	/// If the code is unknown, but the pre-checking for that PVF is already running then we perform
2023	/// "coalescing". We save the cause for this PVF pre-check request and just add it to the
2024	/// existing active PVF vote.
2025	///
2026	/// And finally, if the code is unknown and pre-checking is not running, we start the
2027	/// pre-checking process anew.
2028	///
2029	/// Unconditionally increases the reference count for the passed `code`.
2030	fn kick_off_pvf_check(
2031		cause: PvfCheckCause<BlockNumberFor<T>>,
2032		code_hash: ValidationCodeHash,
2033		code: ValidationCode,
2034		cfg: &configuration::HostConfiguration<BlockNumberFor<T>>,
2035	) -> Weight {
2036		let mut weight = Weight::zero();
2037
2038		weight += T::DbWeight::get().reads_writes(3, 2);
2039		Self::deposit_event(Event::PvfCheckStarted(code_hash, cause.para_id()));
2040
2041		weight += T::DbWeight::get().reads(1);
2042		match PvfActiveVoteMap::<T>::get(&code_hash) {
2043			None => {
2044				// We deliberately are using `CodeByHash` here instead of the `CodeByHashRefs`. This
2045				// is because the code may have been added by `add_trusted_validation_code`.
2046				let known_code = CodeByHash::<T>::contains_key(&code_hash);
2047				weight += T::DbWeight::get().reads(1);
2048
2049				if known_code {
2050					// The code is known and there is no active PVF vote for it meaning it is
2051					// already checked -- fast track the PVF checking into the accepted state.
2052					weight += T::DbWeight::get().reads(1);
2053					let now = frame_system::Pallet::<T>::block_number();
2054					weight += Self::enact_pvf_accepted(now, &code_hash, &[cause], 0, cfg);
2055				} else {
2056					// PVF is not being pre-checked and it is not known. Start a new pre-checking
2057					// process.
2058					weight += T::DbWeight::get().reads_writes(3, 2);
2059					let now = frame_system::Pallet::<T>::block_number();
2060					let n_validators = shared::ActiveValidatorKeys::<T>::get().len();
2061					PvfActiveVoteMap::<T>::insert(
2062						&code_hash,
2063						PvfCheckActiveVoteState::new(now, n_validators, cause),
2064					);
2065					PvfActiveVoteList::<T>::mutate(|l| {
2066						if let Err(idx) = l.binary_search(&code_hash) {
2067							l.insert(idx, code_hash);
2068						}
2069					});
2070				}
2071			},
2072			Some(mut vote_state) => {
2073				// Coalescing: the PVF is already being pre-checked so we just need to piggy back
2074				// on it.
2075				weight += T::DbWeight::get().writes(1);
2076				vote_state.causes.push(cause);
2077				PvfActiveVoteMap::<T>::insert(&code_hash, vote_state);
2078			},
2079		}
2080
2081		// We increase the code RC here in any case. Intuitively the parachain that requested this
2082		// action is now a user of that PVF.
2083		//
2084		// If the result of the pre-checking is reject, then we would decrease the RC for each
2085		// cause, including the current.
2086		//
2087		// If the result of the pre-checking is accept, then we do nothing to the RC because the PVF
2088		// will continue be used by the same users.
2089		//
2090		// If the PVF was fast-tracked (i.e. there is already non zero RC) and there is no
2091		// pre-checking, we also do not change the RC then.
2092		weight += Self::increase_code_ref(&code_hash, &code);
2093
2094		weight
2095	}
2096
2097	/// Note that a para has progressed to a new head, where the new head was executed in the
2098	/// context of a relay-chain block with given number. This will apply pending code upgrades
2099	/// based on the relay-parent block number provided.
2100	pub(crate) fn note_new_head(
2101		id: ParaId,
2102		new_head: HeadData,
2103		execution_context: BlockNumberFor<T>,
2104	) {
2105		Heads::<T>::insert(&id, &new_head);
2106		MostRecentContext::<T>::insert(&id, execution_context);
2107
2108		if let Some(expected_at) = FutureCodeUpgrades::<T>::get(&id) {
2109			if expected_at <= execution_context {
2110				FutureCodeUpgrades::<T>::remove(&id);
2111				UpgradeGoAheadSignal::<T>::remove(&id);
2112
2113				// Both should always be `Some` in this case, since a code upgrade is scheduled.
2114				let new_code_hash = if let Some(new_code_hash) = FutureCodeHash::<T>::take(&id) {
2115					new_code_hash
2116				} else {
2117					log::error!(target: LOG_TARGET, "Missing future code hash for {:?}", &id);
2118					return
2119				};
2120
2121				Self::set_current_code(id, new_code_hash, expected_at);
2122			}
2123		} else {
2124			// This means there is no upgrade scheduled.
2125			//
2126			// In case the upgrade was aborted by the relay-chain we should reset
2127			// the `Abort` signal.
2128			UpgradeGoAheadSignal::<T>::remove(&id);
2129		};
2130
2131		T::OnNewHead::on_new_head(id, &new_head);
2132	}
2133
2134	/// Set the current code for the given parachain.
2135	// `at` for para-triggered replacement is the block number of the relay-chain
2136	// block in whose context the parablock was executed
2137	// (i.e. number of `relay_parent` in the receipt)
2138	pub(crate) fn set_current_code(
2139		id: ParaId,
2140		new_code_hash: ValidationCodeHash,
2141		at: BlockNumberFor<T>,
2142	) -> Weight {
2143		let maybe_prior_code_hash = CurrentCodeHash::<T>::get(&id);
2144		CurrentCodeHash::<T>::insert(&id, &new_code_hash);
2145
2146		let log = ConsensusLog::ParaUpgradeCode(id, new_code_hash);
2147		<frame_system::Pallet<T>>::deposit_log(log.into());
2148
2149		// `now` is only used for registering pruning as part of `fn note_past_code`
2150		let now = <frame_system::Pallet<T>>::block_number();
2151
2152		let weight = if let Some(prior_code_hash) = maybe_prior_code_hash {
2153			Self::note_past_code(id, at, now, prior_code_hash)
2154		} else {
2155			log::error!(target: LOG_TARGET, "Missing prior code hash for para {:?}", &id);
2156			Weight::zero()
2157		};
2158
2159		weight + T::DbWeight::get().writes(1)
2160	}
2161
2162	/// Returns the list of PVFs (aka validation code) that require casting a vote by a validator in
2163	/// the active validator set.
2164	pub(crate) fn pvfs_require_precheck() -> Vec<ValidationCodeHash> {
2165		PvfActiveVoteList::<T>::get()
2166	}
2167
2168	/// Submits a given PVF check statement with corresponding signature as an unsigned transaction
2169	/// into the memory pool. Ultimately, that disseminates the transaction across the network.
2170	///
2171	/// This function expects an offchain context and cannot be callable from the on-chain logic.
2172	///
2173	/// The signature assumed to pertain to `stmt`.
2174	pub(crate) fn submit_pvf_check_statement(
2175		stmt: PvfCheckStatement,
2176		signature: ValidatorSignature,
2177	) {
2178		use frame_system::offchain::SubmitTransaction;
2179
2180		let xt = T::create_inherent(Call::include_pvf_check_statement { stmt, signature }.into());
2181		if let Err(e) = SubmitTransaction::<T, Call<T>>::submit_transaction(xt) {
2182			log::error!(target: LOG_TARGET, "Error submitting pvf check statement: {:?}", e,);
2183		}
2184	}
2185
2186	/// Returns the current lifecycle state of the para.
2187	pub fn lifecycle(id: ParaId) -> Option<ParaLifecycle> {
2188		ParaLifecycles::<T>::get(&id)
2189	}
2190
2191	/// Returns whether the given ID refers to a valid para.
2192	///
2193	/// Paras that are onboarding or offboarding are not included.
2194	pub fn is_valid_para(id: ParaId) -> bool {
2195		if let Some(state) = ParaLifecycles::<T>::get(&id) {
2196			!state.is_onboarding() && !state.is_offboarding()
2197		} else {
2198			false
2199		}
2200	}
2201
2202	/// Returns whether the given ID refers to a para that is offboarding.
2203	///
2204	/// An invalid or non-offboarding para ID will return `false`.
2205	pub fn is_offboarding(id: ParaId) -> bool {
2206		ParaLifecycles::<T>::get(&id).map_or(false, |state| state.is_offboarding())
2207	}
2208
2209	/// Whether a para ID corresponds to any live lease holding parachain.
2210	///
2211	/// Includes lease holding parachains which will downgrade to a on-demand parachains in the
2212	/// future.
2213	pub fn is_parachain(id: ParaId) -> bool {
2214		if let Some(state) = ParaLifecycles::<T>::get(&id) {
2215			state.is_parachain()
2216		} else {
2217			false
2218		}
2219	}
2220
2221	/// Whether a para ID corresponds to any live parathread (on-demand parachain).
2222	///
2223	/// Includes on-demand parachains which will upgrade to lease holding parachains in the future.
2224	pub fn is_parathread(id: ParaId) -> bool {
2225		if let Some(state) = ParaLifecycles::<T>::get(&id) {
2226			state.is_parathread()
2227		} else {
2228			false
2229		}
2230	}
2231
2232	/// If a candidate from the specified parachain were submitted at the current block, this
2233	/// function returns if that candidate passes the acceptance criteria.
2234	pub(crate) fn can_upgrade_validation_code(id: ParaId) -> bool {
2235		FutureCodeHash::<T>::get(&id).is_none() && UpgradeRestrictionSignal::<T>::get(&id).is_none()
2236	}
2237
2238	/// Return the session index that should be used for any future scheduled changes.
2239	fn scheduled_session() -> SessionIndex {
2240		shared::Pallet::<T>::scheduled_session()
2241	}
2242
2243	/// Store the validation code if not already stored, and increase the number of reference.
2244	///
2245	/// Returns the weight consumed.
2246	fn increase_code_ref(code_hash: &ValidationCodeHash, code: &ValidationCode) -> Weight {
2247		let mut weight = T::DbWeight::get().reads_writes(1, 1);
2248		CodeByHashRefs::<T>::mutate(code_hash, |refs| {
2249			if *refs == 0 {
2250				weight += T::DbWeight::get().writes(1);
2251				CodeByHash::<T>::insert(code_hash, code);
2252			}
2253			*refs += 1;
2254		});
2255		weight
2256	}
2257
2258	/// Decrease the number of reference of the validation code and remove it from storage if zero
2259	/// is reached.
2260	///
2261	/// Returns the weight consumed.
2262	fn decrease_code_ref(code_hash: &ValidationCodeHash) -> Weight {
2263		let mut weight = T::DbWeight::get().reads(1);
2264		let refs = CodeByHashRefs::<T>::get(code_hash);
2265		if refs == 0 {
2266			log::error!(target: LOG_TARGET, "Code refs is already zero for {:?}", code_hash);
2267			return weight
2268		}
2269		if refs <= 1 {
2270			weight += T::DbWeight::get().writes(2);
2271			CodeByHash::<T>::remove(code_hash);
2272			CodeByHashRefs::<T>::remove(code_hash);
2273		} else {
2274			weight += T::DbWeight::get().writes(1);
2275			CodeByHashRefs::<T>::insert(code_hash, refs - 1);
2276		}
2277		weight
2278	}
2279
2280	/// Test function for triggering a new session in this pallet.
2281	#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2282	pub fn test_on_new_session() {
2283		Self::initializer_on_new_session(&SessionChangeNotification {
2284			session_index: shared::CurrentSessionIndex::<T>::get(),
2285			..Default::default()
2286		});
2287	}
2288
2289	#[cfg(any(feature = "runtime-benchmarks", test))]
2290	pub fn heads_insert(para_id: &ParaId, head_data: HeadData) {
2291		Heads::<T>::insert(para_id, head_data);
2292	}
2293
2294	/// A low-level function to eagerly initialize a given para.
2295	pub(crate) fn initialize_para_now(
2296		parachains: &mut ParachainsCache<T>,
2297		id: ParaId,
2298		genesis_data: &ParaGenesisArgs,
2299	) {
2300		match genesis_data.para_kind {
2301			ParaKind::Parachain => {
2302				parachains.add(id);
2303				ParaLifecycles::<T>::insert(&id, ParaLifecycle::Parachain);
2304			},
2305			ParaKind::Parathread => ParaLifecycles::<T>::insert(&id, ParaLifecycle::Parathread),
2306		}
2307
2308		// HACK: see the notice in `schedule_para_initialize`.
2309		//
2310		// Apparently, this is left over from a prior version of the runtime.
2311		// To handle this we just insert the code and link the current code hash
2312		// to it.
2313		if !genesis_data.validation_code.0.is_empty() {
2314			let code_hash = genesis_data.validation_code.hash();
2315			Self::increase_code_ref(&code_hash, &genesis_data.validation_code);
2316			CurrentCodeHash::<T>::insert(&id, code_hash);
2317		}
2318
2319		Heads::<T>::insert(&id, &genesis_data.genesis_head);
2320		MostRecentContext::<T>::insert(&id, BlockNumberFor::<T>::from(0u32));
2321	}
2322
2323	#[cfg(test)]
2324	pub(crate) fn active_vote_state(
2325		code_hash: &ValidationCodeHash,
2326	) -> Option<PvfCheckActiveVoteState<BlockNumberFor<T>>> {
2327		PvfActiveVoteMap::<T>::get(code_hash)
2328	}
2329}
2330
2331/// An overlay over the `Parachains` storage entry that provides a convenient interface for adding
2332/// or removing parachains in bulk.
2333pub(crate) struct ParachainsCache<T: Config> {
2334	// `None` here means the parachains list has not been accessed yet, nevermind modified.
2335	parachains: Option<BTreeSet<ParaId>>,
2336	_config: PhantomData<T>,
2337}
2338
2339impl<T: Config> ParachainsCache<T> {
2340	pub fn new() -> Self {
2341		Self { parachains: None, _config: PhantomData }
2342	}
2343
2344	fn ensure_initialized(&mut self) -> &mut BTreeSet<ParaId> {
2345		self.parachains
2346			.get_or_insert_with(|| Parachains::<T>::get().into_iter().collect())
2347	}
2348
2349	/// Adds the given para id to the list.
2350	pub fn add(&mut self, id: ParaId) {
2351		let parachains = self.ensure_initialized();
2352		parachains.insert(id);
2353	}
2354
2355	/// Removes the given para id from the list of parachains. Does nothing if the id is not in the
2356	/// list.
2357	pub fn remove(&mut self, id: ParaId) {
2358		let parachains = self.ensure_initialized();
2359		parachains.remove(&id);
2360	}
2361}
2362
2363impl<T: Config> Drop for ParachainsCache<T> {
2364	fn drop(&mut self) {
2365		if let Some(parachains) = self.parachains.take() {
2366			Parachains::<T>::put(parachains.into_iter().collect::<Vec<ParaId>>());
2367		}
2368	}
2369}