1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi 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
// Tanssi 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 Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
//! # Registrar Pallet
18
//!
19
//! This pallet is in charge of registering containerChains (identified by their Id)
20
//! that have to be served by the orchestrator chain. Parachains registrations and de-
21
//! registrations are not immediately applied, but rather they take T::SessionDelay sessions
22
//! to be applied.
23
//!
24
//! Registered container chains are stored in the PendingParaIds storage item until the session
25
//! in which they can be onboarded arrives, in which case they are added to the RegisteredParaIds
26
//! storage item.
27

            
28
#![cfg_attr(not(feature = "std"), no_std)]
29

            
30
#[cfg(test)]
31
mod mock;
32

            
33
#[cfg(test)]
34
mod tests;
35

            
36
#[cfg(any(test, feature = "runtime-benchmarks"))]
37
mod benchmark_blob;
38
#[cfg(any(test, feature = "runtime-benchmarks"))]
39
mod benchmarks;
40
pub mod weights;
41
pub use weights::WeightInfo;
42

            
43
pub use pallet::*;
44

            
45
use {
46
    cumulus_primitives_core::relay_chain::HeadData,
47
    dp_chain_state_snapshot::GenericStateProof,
48
    dp_container_chain_genesis_data::ContainerChainGenesisData,
49
    frame_support::{
50
        pallet_prelude::*,
51
        traits::{
52
            fungible::{Inspect, InspectHold, Mutate, MutateHold},
53
            tokens::{Fortitude, Precision, Restriction},
54
            EnsureOriginWithArg,
55
        },
56
        DefaultNoBound, Hashable, LOG_TARGET,
57
    },
58
    frame_system::pallet_prelude::*,
59
    parity_scale_codec::{Decode, Encode},
60
    sp_core::H256,
61
    sp_runtime::{
62
        traits::{AtLeast32BitUnsigned, Verify},
63
        Saturating,
64
    },
65
    sp_std::{collections::btree_set::BTreeSet, prelude::*},
66
    tp_traits::{
67
        GetCurrentContainerChains, GetSessionContainerChains, GetSessionIndex, ParaId,
68
        ParathreadParams as ParathreadParamsTy, RegistrarHandler, RelayStorageRootProvider,
69
        SessionContainerChains, SlotFrequency,
70
    },
71
};
72

            
73
2548
#[frame_support::pallet]
74
pub mod pallet {
75
    use super::*;
76

            
77
1698
    #[pallet::pallet]
78
    pub struct Pallet<T>(_);
79

            
80
    #[pallet::genesis_config]
81
    #[derive(DefaultNoBound)]
82
    pub struct GenesisConfig<T: Config> {
83
        /// Para ids
84
        pub para_ids: Vec<(
85
            ParaId,
86
            ContainerChainGenesisData,
87
            Option<ParathreadParamsTy>,
88
        )>,
89
        #[serde(skip)]
90
        pub phantom: PhantomData<T>,
91
    }
92

            
93
    #[pallet::genesis_build]
94
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
95
3
        fn build(&self) {
96
3
            // Sort para ids and detect duplicates, but do it using a vector of
97
3
            // references to avoid cloning the genesis data, which may be big.
98
3
            let mut para_ids: Vec<&_> = self.para_ids.iter().collect();
99
3
            para_ids.sort_by(|a, b| a.0.cmp(&b.0));
100
3
            para_ids.dedup_by(|a, b| {
101
                if a.0 == b.0 {
102
                    panic!("Duplicate para_id: {}", u32::from(a.0));
103
                } else {
104
                    false
105
                }
106
3
            });
107
3

            
108
3
            let mut bounded_para_ids = BoundedVec::default();
109

            
110
3
            for (para_id, genesis_data, parathread_params) in para_ids {
111
                bounded_para_ids
112
                    .try_push(*para_id)
113
                    .expect("too many para ids in genesis: bounded vec full");
114

            
115
                let genesis_data_size = genesis_data.encoded_size();
116
                if genesis_data_size > T::MaxGenesisDataSize::get() as usize {
117
                    panic!(
118
                        "genesis data for para_id {:?} is too large: {} bytes (limit is {})",
119
                        u32::from(*para_id),
120
                        genesis_data_size,
121
                        T::MaxGenesisDataSize::get()
122
                    );
123
                }
124
                <ParaGenesisData<T>>::insert(para_id, genesis_data);
125

            
126
                if let Some(parathread_params) = parathread_params {
127
                    <ParathreadParams<T>>::insert(para_id, parathread_params);
128
                }
129
            }
130

            
131
3
            <RegisteredParaIds<T>>::put(bounded_para_ids);
132
3
        }
133
    }
134

            
135
    /// Configure the pallet by specifying the parameters and types on which it depends.
136
    #[pallet::config]
137
    pub trait Config: frame_system::Config {
138
        /// Because this pallet emits events, it depends on the runtime's definition of an event.
139
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
140

            
141
        /// Origin that is allowed to call register and deregister
142
        type RegistrarOrigin: EnsureOrigin<Self::RuntimeOrigin>;
143

            
144
        /// Origin that is allowed to call mark_valid_for_collating
145
        type MarkValidForCollatingOrigin: EnsureOrigin<Self::RuntimeOrigin>;
146

            
147
        /// Max length of para id list
148
        #[pallet::constant]
149
        type MaxLengthParaIds: Get<u32>;
150

            
151
        /// Max length of encoded genesis data
152
        #[pallet::constant]
153
        type MaxGenesisDataSize: Get<u32>;
154

            
155
        type RegisterWithRelayProofOrigin: EnsureOrigin<
156
            Self::RuntimeOrigin,
157
            Success = Self::AccountId,
158
        >;
159

            
160
        type RelayStorageRootProvider: RelayStorageRootProvider;
161

            
162
        type SessionIndex: parity_scale_codec::FullCodec + TypeInfo + Copy + AtLeast32BitUnsigned;
163

            
164
        #[pallet::constant]
165
        type SessionDelay: Get<Self::SessionIndex>;
166

            
167
        type CurrentSessionIndex: GetSessionIndex<Self::SessionIndex>;
168

            
169
        type Currency: Mutate<Self::AccountId>
170
            + MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>;
171

            
172
        type RuntimeHoldReason: From<HoldReason>;
173

            
174
        #[pallet::constant]
175
        type DepositAmount: Get<<Self::Currency as Inspect<Self::AccountId>>::Balance>;
176

            
177
        type RegistrarHooks: RegistrarHooks;
178

            
179
        /// External manager that takes care of executing specific operations
180
        /// when register-like functions of this pallet are called.
181
        ///
182
        /// Mostly used when we are in a relay-chain configuration context (Dancelight)
183
        /// to also register, deregister and upgrading paraIds in polkadot's
184
        /// paras_registrar pallet.
185
        type InnerRegistrar: RegistrarHandler<Self::AccountId>;
186

            
187
        type WeightInfo: WeightInfo;
188
    }
189

            
190
1534542
    #[pallet::storage]
191
    pub type RegisteredParaIds<T: Config> =
192
        StorageValue<_, BoundedVec<ParaId, T::MaxLengthParaIds>, ValueQuery>;
193

            
194
862758
    #[pallet::storage]
195
    #[pallet::unbounded]
196
    pub type PendingParaIds<T: Config> = StorageValue<
197
        _,
198
        Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)>,
199
        ValueQuery,
200
    >;
201

            
202
108348
    #[pallet::storage]
203
    // TODO: this is not unbounded because we check the encoded size in register
204
    #[pallet::unbounded]
205
    pub type ParaGenesisData<T: Config> =
206
        StorageMap<_, Blake2_128Concat, ParaId, ContainerChainGenesisData, OptionQuery>;
207

            
208
109422
    #[pallet::storage]
209
    pub type PendingVerification<T: Config> =
210
        StorageMap<_, Blake2_128Concat, ParaId, (), OptionQuery>;
211

            
212
214548
    #[pallet::storage]
213
    pub type Paused<T: Config> =
214
        StorageValue<_, BoundedVec<ParaId, T::MaxLengthParaIds>, ValueQuery>;
215

            
216
592290
    #[pallet::storage]
217
    #[pallet::unbounded]
218
    pub type PendingPaused<T: Config> = StorageValue<
219
        _,
220
        Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)>,
221
        ValueQuery,
222
    >;
223

            
224
592290
    #[pallet::storage]
225
    #[pallet::unbounded]
226
    pub type PendingToRemove<T: Config> = StorageValue<
227
        _,
228
        Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)>,
229
        ValueQuery,
230
    >;
231

            
232
    #[pallet::storage]
233
    pub type ParathreadParams<T: Config> =
234
        StorageMap<_, Blake2_128Concat, ParaId, ParathreadParamsTy, OptionQuery>;
235

            
236
270468
    #[pallet::storage]
237
    #[pallet::unbounded]
238
    pub type PendingParathreadParams<T: Config> = StorageValue<
239
        _,
240
        Vec<(
241
            T::SessionIndex,
242
            BoundedVec<(ParaId, ParathreadParamsTy), T::MaxLengthParaIds>,
243
        )>,
244
        ValueQuery,
245
    >;
246

            
247
    /// This storage aims to act as a 'buffer' for paraIds that must be deregistered at the
248
    /// end of the block execution by calling 'T::InnerRegistrar::deregister()' implementation.
249
    ///
250
    /// We need this buffer because when we are using this pallet on a relay-chain environment
251
    /// like Dancelight (where 'T::InnerRegistrar' implementation is usually the
252
    /// 'paras_registrar' pallet) we need to deregister (via 'paras_registrar::deregister')
253
    /// the same paraIds we have in 'PendingToRemove<T>', and we need to do this deregistration
254
    /// process inside 'on_finalize' hook.
255
    ///
256
    /// It can be the case that some paraIds need to be downgraded to a parathread before
257
    /// deregistering on 'paras_registrar'. This process usually takes 2 sessions,
258
    /// and the actual downgrade happens when the block finalizes.
259
    ///
260
    /// Therefore, if we tried to perform this relay deregistration process at the beginning
261
    /// of the session/block inside ('on_initialize') initializer_on_new_session() as we do
262
    /// for this pallet, it would fail due to the downgrade process could have not taken
263
    /// place yet.  
264
389526
    #[pallet::storage]
265
    pub type BufferedParasToDeregister<T: Config> =
266
        StorageValue<_, BoundedVec<ParaId, T::MaxLengthParaIds>, ValueQuery>;
267

            
268
    pub type DepositBalanceOf<T> =
269
        <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;
270

            
271
    #[derive(
272
        Default, Clone, Encode, Decode, RuntimeDebug, PartialEq, scale_info::TypeInfo, MaxEncodedLen,
273
    )]
274
    #[scale_info(skip_type_params(T))]
275
    pub struct DepositInfo<T: Config> {
276
        pub creator: T::AccountId,
277
        pub deposit: DepositBalanceOf<T>,
278
    }
279

            
280
    /// Registrar deposits, a mapping from paraId to a struct
281
    /// holding the creator (from which the deposit was reserved) and
282
    /// the deposit amount
283
107403
    #[pallet::storage]
284
    pub type RegistrarDeposit<T: Config> = StorageMap<_, Blake2_128Concat, ParaId, DepositInfo<T>>;
285

            
286
96
    #[pallet::storage]
287
    pub type ParaManager<T: Config> =
288
        StorageMap<_, Blake2_128Concat, ParaId, T::AccountId, OptionQuery>;
289

            
290
    #[pallet::event]
291
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
292
    pub enum Event<T: Config> {
293
        /// A new para id has been registered. [para_id]
294
        ParaIdRegistered { para_id: ParaId },
295
        /// A para id has been deregistered. [para_id]
296
        ParaIdDeregistered { para_id: ParaId },
297
        /// A new para id is now valid for collating. [para_id]
298
        ParaIdValidForCollating { para_id: ParaId },
299
        /// A para id has been paused from collating.
300
        ParaIdPaused { para_id: ParaId },
301
        /// A para id has been unpaused.
302
        ParaIdUnpaused { para_id: ParaId },
303
        /// Parathread params changed
304
        ParathreadParamsChanged { para_id: ParaId },
305
        /// Para manager has changed
306
        ParaManagerChanged {
307
            para_id: ParaId,
308
            manager_address: T::AccountId,
309
        },
310
    }
311

            
312
2340
    #[pallet::error]
313
    pub enum Error<T> {
314
        /// Attempted to register a ParaId that was already registered
315
        ParaIdAlreadyRegistered,
316
        /// Attempted to deregister a ParaId that is not registered
317
        ParaIdNotRegistered,
318
        /// Attempted to deregister a ParaId that is already being deregistered
319
        ParaIdAlreadyDeregistered,
320
        /// Attempted to pause a ParaId that was already paused
321
        ParaIdAlreadyPaused,
322
        /// Attempted to unpause a ParaId that was not paused
323
        ParaIdNotPaused,
324
        /// The bounded list of ParaIds has reached its limit
325
        ParaIdListFull,
326
        /// Attempted to register a ParaId with a genesis data size greater than the limit
327
        GenesisDataTooBig,
328
        /// Tried to mark_valid_for_collating a ParaId that is not in PendingVerification
329
        ParaIdNotInPendingVerification,
330
        /// Tried to register a ParaId with an account that did not have enough balance for the deposit
331
        NotSufficientDeposit,
332
        /// Tried to change parathread params for a para id that is not a registered parathread
333
        NotAParathread,
334
        /// Attempted to execute an extrinsic meant only for the para creator
335
        NotParaCreator,
336
        /// The relay storage root for the corresponding block number could not be retrieved
337
        RelayStorageRootNotFound,
338
        /// The provided relay storage proof is not valid
339
        InvalidRelayStorageProof,
340
        /// The provided signature from the parachain manager in the relay is not valid
341
        InvalidRelayManagerSignature,
342
        /// Tried to deregister a parachain that was not deregistered from the relay chain
343
        ParaStillExistsInRelay,
344
        /// Tried to register a paraId in a relay context without specifying a proper HeadData.
345
        HeadDataNecessary,
346
        /// Tried to register a paraId in a relay context without specifying a wasm chain code.
347
        WasmCodeNecessary,
348
    }
349

            
350
    #[pallet::composite_enum]
351
    pub enum HoldReason {
352
        RegistrarDeposit,
353
    }
354

            
355
514679
    #[pallet::hooks]
356
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
357
194763
        fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
358
194763
            let mut weight = Weight::zero().saturating_add(T::DbWeight::get().reads_writes(1, 1));
359
194763

            
360
194763
            let buffered_paras = BufferedParasToDeregister::<T>::take();
361

            
362
194763
            for para_id in buffered_paras {
363
                weight += T::InnerRegistrar::deregister_weight();
364
                // Deregister (in the relay context) each paraId present inside the buffer
365
                T::InnerRegistrar::deregister(para_id);
366
            }
367
194763
            weight
368
194763
        }
369

            
370
        #[cfg(feature = "try-runtime")]
371
53637
        fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
372
            use {scale_info::prelude::format, sp_std::collections::btree_set::BTreeSet};
373
            // A para id can only be in 1 of [`RegisteredParaIds`, `PendingVerification`, `Paused`]
374
            // Get all those para ids and check for duplicates
375
53637
            let mut para_ids: Vec<ParaId> = vec![];
376
53637
            para_ids.extend(RegisteredParaIds::<T>::get());
377
53637
            para_ids.extend(PendingVerification::<T>::iter_keys());
378
53637
            para_ids.extend(Paused::<T>::get());
379
53637
            para_ids.sort();
380
53637
            para_ids.dedup_by(|a, b| {
381
                if a == b {
382
                    panic!("Duplicate para id: {}", u32::from(*a));
383
                } else {
384
                    false
385
                }
386
53637
            });
387

            
388
            // All para ids have an entry in `ParaGenesisData`
389
53637
            for para_id in &para_ids {
390
                assert!(
391
                    ParaGenesisData::<T>::contains_key(para_id),
392
                    "Para id {} missing genesis data",
393
                    u32::from(*para_id)
394
                );
395
            }
396

            
397
            // All entries in `RegistrarDeposit` and `ParaGenesisData` are in one of the other lists
398
53637
            let mut para_id_set = BTreeSet::from_iter(para_ids.iter().cloned());
399
53637
            // Also add the Pending lists here
400
53637
            para_id_set.extend(
401
53637
                PendingParaIds::<T>::get()
402
53637
                    .into_iter()
403
53637
                    .flat_map(|(_session_index, x)| x),
404
53637
            );
405
53637
            para_id_set.extend(
406
53637
                PendingPaused::<T>::get()
407
53637
                    .into_iter()
408
53637
                    .flat_map(|(_session_index, x)| x),
409
53637
            );
410
53637
            para_id_set.extend(
411
53637
                PendingToRemove::<T>::get()
412
53637
                    .into_iter()
413
53637
                    .flat_map(|(_session_index, x)| x),
414
53637
            );
415
53637
            let entries: Vec<_> = RegistrarDeposit::<T>::iter().map(|(k, _v)| k).collect();
416
53637
            for para_id in entries {
417
                assert!(
418
                    para_id_set.contains(&para_id),
419
                    "Found RegistrarDeposit for unknown para id: {}",
420
                    u32::from(para_id)
421
                );
422
            }
423
53637
            let entries: Vec<_> = ParaGenesisData::<T>::iter().map(|(k, _v)| k).collect();
424
53637
            for para_id in entries {
425
                assert!(
426
                    para_id_set.contains(&para_id),
427
                    "Found ParaGenesisData for unknown para id: {}",
428
                    u32::from(para_id)
429
                );
430
            }
431

            
432
            // Sorted storage items are sorted
433
268185
            fn assert_is_sorted_and_unique<T: Ord>(x: &[T], name: &str) {
434
268185
                assert!(
435
268185
                    x.windows(2).all(|w| w[0] < w[1]),
436
                    "sorted list not sorted or not unique: {}",
437
                    name,
438
                );
439
268185
            }
440
53637
            assert_is_sorted_and_unique(&RegisteredParaIds::<T>::get(), "RegisteredParaIds");
441
53637
            assert_is_sorted_and_unique(&Paused::<T>::get(), "Paused");
442
53637
            for (i, (_session_index, x)) in PendingParaIds::<T>::get().into_iter().enumerate() {
443
                assert_is_sorted_and_unique(&x, &format!("PendingParaIds[{}]", i));
444
            }
445
53637
            for (i, (_session_index, x)) in PendingPaused::<T>::get().into_iter().enumerate() {
446
                assert_is_sorted_and_unique(&x, &format!("PendingPaused[{}]", i));
447
            }
448
53637
            for (i, (_session_index, x)) in PendingToRemove::<T>::get().into_iter().enumerate() {
449
                assert_is_sorted_and_unique(&x, &format!("PendingToRemove[{}]", i));
450
            }
451

            
452
            // Pending storage items are sorted and session index is unique
453
53637
            let pending: Vec<_> = PendingParaIds::<T>::get()
454
53637
                .into_iter()
455
53637
                .map(|(session_index, _x)| session_index)
456
53637
                .collect();
457
53637
            assert_is_sorted_and_unique(&pending, "PendingParaIds");
458
53637
            let pending: Vec<_> = PendingPaused::<T>::get()
459
53637
                .into_iter()
460
53637
                .map(|(session_index, _x)| session_index)
461
53637
                .collect();
462
53637
            assert_is_sorted_and_unique(&pending, "PendingPaused");
463
53637
            let pending: Vec<_> = PendingToRemove::<T>::get()
464
53637
                .into_iter()
465
53637
                .map(|(session_index, _x)| session_index)
466
53637
                .collect();
467
53637
            assert_is_sorted_and_unique(&pending, "PendingToRemove");
468
53637

            
469
53637
            Ok(())
470
53637
        }
471
    }
472

            
473
14874
    #[pallet::call]
474
    impl<T: Config> Pallet<T> {
475
        /// Register container-chain
476
        #[pallet::call_index(0)]
477
        #[pallet::weight(T::WeightInfo::register(genesis_data.encoded_size() as u32, genesis_data.storage.len() as u32))]
478
        pub fn register(
479
            origin: OriginFor<T>,
480
            para_id: ParaId,
481
            genesis_data: ContainerChainGenesisData,
482
            head_data: Option<HeadData>,
483
1137
        ) -> DispatchResult {
484
1137
            let account = ensure_signed(origin)?;
485
1137
            Self::do_register(account, para_id, genesis_data, head_data)?;
486
            Self::deposit_event(Event::ParaIdRegistered { para_id });
487

            
488
            Ok(())
489
        }
490

            
491
        /// Deregister container-chain.
492
        ///
493
        /// If a container-chain is registered but not marked as valid_for_collating, this will remove it
494
        /// from `PendingVerification` as well.
495
        #[pallet::call_index(1)]
496
        #[pallet::weight(T::WeightInfo::deregister_immediate(
497
        ).max(T::WeightInfo::deregister_scheduled(
498
        )))]
499
93
        pub fn deregister(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
500
93
            T::RegistrarOrigin::ensure_origin(origin)?;
501

            
502
            Self::do_deregister(para_id)?;
503

            
504
            Ok(())
505
        }
506

            
507
        /// Mark container-chain valid for collating
508
        #[pallet::call_index(2)]
509
        #[pallet::weight(T::WeightInfo::mark_valid_for_collating())]
510
96
        pub fn mark_valid_for_collating(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
511
96
            T::MarkValidForCollatingOrigin::ensure_origin(origin)?;
512

            
513
            Self::do_mark_valid_for_collating(para_id)?;
514

            
515
            Ok(())
516
        }
517

            
518
        /// Pause container-chain from collating. Does not remove its boot nodes nor its genesis config.
519
        /// Only container-chains that have been marked as valid_for_collating can be paused.
520
        #[pallet::call_index(4)]
521
        #[pallet::weight(T::WeightInfo::pause_container_chain())]
522
90
        pub fn pause_container_chain(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
523
90
            T::RegistrarOrigin::ensure_origin(origin)?;
524

            
525
            Self::schedule_paused_parachain_change(|para_ids, paused| {
526
                match paused.binary_search(&para_id) {
527
                    Ok(_) => return Err(Error::<T>::ParaIdAlreadyPaused.into()),
528
                    Err(index) => {
529
                        paused
530
                            .try_insert(index, para_id)
531
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
532
                    }
533
                }
534
                match para_ids.binary_search(&para_id) {
535
                    Ok(index) => {
536
                        para_ids.remove(index);
537
                    }
538
                    // We can only pause para ids that are marked as valid,
539
                    // otherwise unpausing them later would cause problems
540
                    Err(_) => return Err(Error::<T>::ParaIdNotRegistered.into()),
541
                }
542
                Self::deposit_event(Event::ParaIdPaused { para_id });
543

            
544
                Ok(())
545
            })?;
546

            
547
            Ok(())
548
        }
549

            
550
        /// Unpause container-chain.
551
        /// Only container-chains that have been paused can be unpaused.
552
        #[pallet::call_index(5)]
553
        #[pallet::weight(T::WeightInfo::unpause_container_chain())]
554
219
        pub fn unpause_container_chain(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
555
219
            T::RegistrarOrigin::ensure_origin(origin)?;
556

            
557
            Self::schedule_paused_parachain_change(|para_ids, paused| {
558
                match paused.binary_search(&para_id) {
559
                    Ok(index) => {
560
                        paused.remove(index);
561
                    }
562
                    Err(_) => return Err(Error::<T>::ParaIdNotPaused.into()),
563
                }
564
                match para_ids.binary_search(&para_id) {
565
                    // This Ok is unreachable, a para id cannot be in "RegisteredParaIds" and "Paused" at the same time
566
                    Ok(_) => return Err(Error::<T>::ParaIdAlreadyRegistered.into()),
567
                    Err(index) => {
568
                        para_ids
569
                            .try_insert(index, para_id)
570
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
571
                    }
572
                }
573
                Self::deposit_event(Event::ParaIdUnpaused { para_id });
574

            
575
                Ok(())
576
            })?;
577

            
578
            Ok(())
579
        }
580

            
581
        /// Register parathread
582
        #[pallet::call_index(6)]
583
        #[pallet::weight(T::WeightInfo::register_parathread(genesis_data.encoded_size() as u32, genesis_data.storage.len() as u32))]
584
        pub fn register_parathread(
585
            origin: OriginFor<T>,
586
            para_id: ParaId,
587
            slot_frequency: SlotFrequency,
588
            genesis_data: ContainerChainGenesisData,
589
            head_data: Option<HeadData>,
590
        ) -> DispatchResult {
591
            let account = ensure_signed(origin)?;
592
            Self::do_register(account, para_id, genesis_data, head_data)?;
593
            // Insert parathread params
594
            let params = ParathreadParamsTy { slot_frequency };
595
            ParathreadParams::<T>::insert(para_id, params);
596
            Self::deposit_event(Event::ParaIdRegistered { para_id });
597

            
598
            Ok(())
599
        }
600

            
601
        /// Change parathread params
602
        #[pallet::call_index(7)]
603
        #[pallet::weight(T::WeightInfo::set_parathread_params())]
604
        pub fn set_parathread_params(
605
            origin: OriginFor<T>,
606
            para_id: ParaId,
607
            slot_frequency: SlotFrequency,
608
66
        ) -> DispatchResult {
609
66
            T::RegistrarOrigin::ensure_origin(origin)?;
610

            
611
            Self::schedule_parathread_params_change(para_id, |params| {
612
                params.slot_frequency = slot_frequency;
613

            
614
                Self::deposit_event(Event::ParathreadParamsChanged { para_id });
615

            
616
                Ok(())
617
            })?;
618

            
619
            Ok(())
620
        }
621

            
622
        #[pallet::call_index(8)]
623
        #[pallet::weight(T::WeightInfo::set_para_manager())]
624
        pub fn set_para_manager(
625
            origin: OriginFor<T>,
626
            para_id: ParaId,
627
            manager_address: T::AccountId,
628
33
        ) -> DispatchResult {
629
            // Allow root to force set para manager.
630
33
            if let Some(origin) = ensure_signed_or_root(origin)? {
631
33
                let creator =
632
33
                    RegistrarDeposit::<T>::get(para_id).map(|deposit_info| deposit_info.creator);
633
33

            
634
33
                ensure!(Some(origin) == creator, Error::<T>::NotParaCreator);
635
            }
636

            
637
            ParaManager::<T>::insert(para_id, manager_address.clone());
638

            
639
            Self::deposit_event(Event::<T>::ParaManagerChanged {
640
                para_id,
641
                manager_address,
642
            });
643

            
644
            Ok(())
645
        }
646

            
647
        /// Register parachain or parathread
648
        #[pallet::call_index(9)]
649
        #[pallet::weight(T::WeightInfo::register_with_relay_proof(genesis_data.encoded_size() as u32, genesis_data.storage.len() as u32))]
650
        pub fn register_with_relay_proof(
651
            origin: OriginFor<T>,
652
            para_id: ParaId,
653
            parathread_params: Option<ParathreadParamsTy>,
654
            relay_proof_block_number: u32,
655
            relay_storage_proof: sp_trie::StorageProof,
656
            manager_signature: cumulus_primitives_core::relay_chain::Signature,
657
            genesis_data: ContainerChainGenesisData,
658
            head_data: Option<HeadData>,
659
249
        ) -> DispatchResult {
660
249
            let account = T::RegisterWithRelayProofOrigin::ensure_origin(origin)?;
661
            let relay_storage_root =
662
                T::RelayStorageRootProvider::get_relay_storage_root(relay_proof_block_number)
663
                    .ok_or(Error::<T>::RelayStorageRootNotFound)?;
664
            let relay_state_proof =
665
                GenericStateProof::<cumulus_primitives_core::relay_chain::Block>::new(
666
                    relay_storage_root,
667
                    relay_storage_proof,
668
                )
669
                .map_err(|_| Error::<T>::InvalidRelayStorageProof)?;
670

            
671
            let bytes = para_id.twox_64_concat();
672
            let key = [REGISTRAR_PARAS_INDEX, bytes.as_slice()].concat();
673
            let relay_para_info = relay_state_proof
674
                .read_entry::<ParaInfo<
675
                    cumulus_primitives_core::relay_chain::AccountId,
676
                    cumulus_primitives_core::relay_chain::Balance,
677
                >>(key.as_slice(), None)
678
                .map_err(|_| Error::<T>::InvalidRelayStorageProof)?;
679
            let relay_manager = relay_para_info.manager;
680

            
681
            // Verify manager signature
682
            let signature_msg = Self::relay_signature_msg(para_id, &account, relay_storage_root);
683
            if !manager_signature.verify(&*signature_msg, &relay_manager) {
684
                return Err(Error::<T>::InvalidRelayManagerSignature.into());
685
            }
686

            
687
            Self::do_register(account, para_id, genesis_data, head_data)?;
688
            // Insert parathread params
689
            if let Some(parathread_params) = parathread_params {
690
                ParathreadParams::<T>::insert(para_id, parathread_params);
691
            }
692
            Self::deposit_event(Event::ParaIdRegistered { para_id });
693

            
694
            Ok(())
695
        }
696

            
697
        /// Deregister a parachain that no longer exists in the relay chain. The origin of this
698
        /// extrinsic will be rewarded with the parachain deposit.
699
        #[pallet::call_index(10)]
700
        #[pallet::weight(T::WeightInfo::deregister_with_relay_proof_immediate(
701
        ).max(T::WeightInfo::deregister_with_relay_proof_scheduled(
702
        )))]
703
        pub fn deregister_with_relay_proof(
704
            origin: OriginFor<T>,
705
            para_id: ParaId,
706
            relay_proof_block_number: u32,
707
            relay_storage_proof: sp_trie::StorageProof,
708
555
        ) -> DispatchResult {
709
555
            let account = T::RegisterWithRelayProofOrigin::ensure_origin(origin)?;
710

            
711
            let relay_storage_root =
712
                T::RelayStorageRootProvider::get_relay_storage_root(relay_proof_block_number)
713
                    .ok_or(Error::<T>::RelayStorageRootNotFound)?;
714
            let relay_state_proof =
715
                GenericStateProof::<cumulus_primitives_core::relay_chain::Block>::new(
716
                    relay_storage_root,
717
                    relay_storage_proof,
718
                )
719
                .map_err(|_| Error::<T>::InvalidRelayStorageProof)?;
720

            
721
            let bytes = para_id.twox_64_concat();
722
            let key = [REGISTRAR_PARAS_INDEX, bytes.as_slice()].concat();
723
            // TODO: we don't even need to decode the value, only check if it exists
724
            // Need to add exists_storage method to dancekit
725
            let relay_para_info = relay_state_proof
726
                .read_optional_entry::<ParaInfo<
727
                    cumulus_primitives_core::relay_chain::AccountId,
728
                    cumulus_primitives_core::relay_chain::Balance,
729
                >>(key.as_slice())
730
                .map_err(|_| Error::<T>::InvalidRelayStorageProof)?;
731
            if relay_para_info.is_some() {
732
                return Err(Error::<T>::ParaStillExistsInRelay.into());
733
            }
734

            
735
            // Take the deposit immediately and give it to origin account
736
            if let Some(asset_info) = RegistrarDeposit::<T>::take(para_id) {
737
                // Slash deposit from parachain creator
738
                // TODO: error handling
739
                let _ = T::Currency::transfer_on_hold(
740
                    &HoldReason::RegistrarDeposit.into(),
741
                    &asset_info.creator,
742
                    &account,
743
                    asset_info.deposit,
744
                    Precision::Exact,
745
                    Restriction::Free,
746
                    Fortitude::Force,
747
                );
748
            }
749

            
750
            Self::do_deregister(para_id)?;
751

            
752
            Ok(())
753
        }
754
    }
755

            
756
    pub struct SessionChangeOutcome<T: Config> {
757
        /// Previously active parachains.
758
        pub prev_paras: BoundedVec<ParaId, T::MaxLengthParaIds>,
759
        /// If new parachains have been applied in the new session, this is the new  list.
760
        pub new_paras: Option<BoundedVec<ParaId, T::MaxLengthParaIds>>,
761
    }
762

            
763
    impl<T: Config> Pallet<T> {
764
96
        pub fn is_para_manager(para_id: &ParaId, account: &T::AccountId) -> bool {
765
            // This check will only pass if both are true:
766
            // * The para_id has a deposit in pallet_registrar
767
            // * The signed_account is the para manager (or creator if None)
768
96
            if let Some(manager) = ParaManager::<T>::get(para_id) {
769
                manager == *account
770
            } else {
771
96
                RegistrarDeposit::<T>::get(para_id)
772
96
                    .map(|deposit_info| deposit_info.creator)
773
96
                    .as_ref()
774
96
                    == Some(account)
775
            }
776
96
        }
777

            
778
        #[cfg(feature = "runtime-benchmarks")]
779
        pub fn benchmarks_get_or_create_para_manager(para_id: &ParaId) -> T::AccountId {
780
            use {
781
                frame_benchmarking::account,
782
                frame_support::{assert_ok, dispatch::RawOrigin},
783
            };
784
            // Return container chain manager, or register container chain as ALICE if it does not exist
785
            if !ParaGenesisData::<T>::contains_key(para_id) {
786
                // Register as a new user
787

            
788
                /// Create a funded user.
789
                /// Used for generating the necessary amount for registering
790
                fn create_funded_user<T: Config>(
791
                    string: &'static str,
792
                    n: u32,
793
                    total: DepositBalanceOf<T>,
794
                ) -> (T::AccountId, DepositBalanceOf<T>) {
795
                    const SEED: u32 = 0;
796
                    let user = account(string, n, SEED);
797
                    assert_ok!(T::Currency::mint_into(&user, total));
798
                    (user, total)
799
                }
800
                let new_balance =
801
                    T::Currency::minimum_balance() * 10_000_000u32.into() + T::DepositAmount::get();
802
                let account = create_funded_user::<T>("caller", 1000, new_balance).0;
803
                let origin = RawOrigin::Signed(account);
804
                let mut storage = vec![];
805
                storage.push((b":code".to_vec(), vec![1; 10]).into());
806
                let genesis_data = ContainerChainGenesisData {
807
                    storage,
808
                    name: Default::default(),
809
                    id: Default::default(),
810
                    fork_id: Default::default(),
811
                    extensions: Default::default(),
812
                    properties: Default::default(),
813
                };
814
                assert_ok!(Self::register(
815
                    origin.into(),
816
                    *para_id,
817
                    genesis_data,
818
                    T::InnerRegistrar::bench_head_data(),
819
                ));
820
            }
821

            
822
            let deposit_info = RegistrarDeposit::<T>::get(para_id).expect("Cannot return signed origin for a container chain that was registered by root. Try using a different para id");
823

            
824
            // Fund deposit creator, just in case it is not a new account
825
            let new_balance =
826
                (T::Currency::minimum_balance() + T::DepositAmount::get()) * 2u32.into();
827
            assert_ok!(T::Currency::mint_into(&deposit_info.creator, new_balance));
828

            
829
            deposit_info.creator
830
        }
831

            
832
1137
        fn do_register(
833
1137
            account: T::AccountId,
834
1137
            para_id: ParaId,
835
1137
            genesis_data: ContainerChainGenesisData,
836
1137
            head_data: Option<HeadData>,
837
1137
        ) -> DispatchResult {
838
1137
            let deposit = T::DepositAmount::get();
839
1137
            // Verify we can hold
840
1137
            if !T::Currency::can_hold(&HoldReason::RegistrarDeposit.into(), &account, deposit) {
841
63
                return Err(Error::<T>::NotSufficientDeposit.into());
842
1074
            }
843
1074

            
844
1074
            // Check if the para id is already registered by looking at the genesis data
845
1074
            if ParaGenesisData::<T>::contains_key(para_id) {
846
                return Err(Error::<T>::ParaIdAlreadyRegistered.into());
847
1074
            }
848
1074

            
849
1074
            // Check if the para id is already in PendingVerification (unreachable)
850
1074
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
851
1074
            if is_pending_verification {
852
                return Err(Error::<T>::ParaIdAlreadyRegistered.into());
853
1074
            }
854
1074

            
855
1074
            // Insert para id into PendingVerification
856
1074
            PendingVerification::<T>::insert(para_id, ());
857
1074

            
858
1074
            // The actual registration takes place 2 sessions after the call to
859
1074
            // `mark_valid_for_collating`, but the genesis data is inserted now.
860
1074
            // This is because collators should be able to start syncing the new container chain
861
1074
            // before the first block is mined. However, we could store the genesis data in a
862
1074
            // different key, like PendingParaGenesisData.
863
1074
            // TODO: for benchmarks, this call to .encoded_size is O(n) with respect to the number
864
1074
            // of key-values in `genesis_data.storage`, even if those key-values are empty. And we
865
1074
            // won't detect that the size is too big until after iterating over all of them, so the
866
1074
            // limit in that case would be the transaction size.
867
1074
            let genesis_data_size = genesis_data.encoded_size();
868
1074
            if genesis_data_size > T::MaxGenesisDataSize::get() as usize {
869
                return Err(Error::<T>::GenesisDataTooBig.into());
870
1074
            }
871
1074

            
872
1074
            // Hold the deposit, we verified we can do this
873
1074
            T::Currency::hold(&HoldReason::RegistrarDeposit.into(), &account, deposit)?;
874

            
875
            // Register the paraId also in the relay context (if any).
876
1074
            T::InnerRegistrar::register(
877
1074
                account.clone(),
878
1074
                para_id,
879
1074
                &genesis_data.storage,
880
1074
                head_data,
881
1074
            )?;
882

            
883
            // Update DepositInfo
884
            RegistrarDeposit::<T>::insert(
885
                para_id,
886
                DepositInfo {
887
                    creator: account.clone(),
888
                    deposit,
889
                },
890
            );
891
            ParaGenesisData::<T>::insert(para_id, genesis_data);
892

            
893
            ParaManager::<T>::insert(para_id, account);
894

            
895
            Ok(())
896
1137
        }
897

            
898
        fn do_deregister(para_id: ParaId) -> DispatchResult {
899
            // Check if the para id is in "PendingVerification".
900
            // This is a special case because then we can remove it immediately, instead of waiting 2 sessions.
901
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
902
            if is_pending_verification {
903
                Self::deposit_event(Event::ParaIdDeregistered { para_id });
904
                // Cleanup immediately
905
                Self::cleanup_deregistered_para_id(para_id);
906
                BufferedParasToDeregister::<T>::try_mutate(|v| v.try_push(para_id)).map_err(
907
                    |_e| {
908
                        DispatchError::Other(
909
                            "Failed to add paraId to deregistration list: buffer is full",
910
                        )
911
                    },
912
                )?;
913
            } else {
914
                Self::schedule_paused_parachain_change(|para_ids, paused| {
915
                    // We have to find out where, in the sorted vec the para id is, if anywhere.
916

            
917
                    match para_ids.binary_search(&para_id) {
918
                        Ok(index) => {
919
                            para_ids.remove(index);
920
                        }
921
                        Err(_) => {
922
                            // If the para id is not registered, it may be paused. In that case, remove it from there
923
                            match paused.binary_search(&para_id) {
924
                                Ok(index) => {
925
                                    paused.remove(index);
926
                                }
927
                                Err(_) => {
928
                                    return Err(Error::<T>::ParaIdNotRegistered.into());
929
                                }
930
                            }
931
                        }
932
                    }
933

            
934
                    Ok(())
935
                })?;
936
                // Mark this para id for cleanup later
937
                Self::schedule_parachain_cleanup(para_id)?;
938

            
939
                // If we have InnerRegistrar set to a relay context (like Dancelight),
940
                // we first need to downgrade the paraId (if it was a parachain before)
941
                // and convert it to a parathread before deregistering it. Otherwise
942
                // the deregistration process will fail in the scheduled session.
943
                //
944
                // We only downgrade if the paraId is a parachain in the context of
945
                // this pallet.
946
                if ParathreadParams::<T>::get(para_id).is_none() {
947
                    T::InnerRegistrar::schedule_para_downgrade(para_id)?;
948
                }
949

            
950
                Self::deposit_event(Event::ParaIdDeregistered { para_id });
951
            }
952

            
953
            Ok(())
954
        }
955

            
956
        fn do_mark_valid_for_collating(para_id: ParaId) -> DispatchResult {
957
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
958
            if !is_pending_verification {
959
                return Err(Error::<T>::ParaIdNotInPendingVerification.into());
960
            }
961

            
962
            Self::schedule_parachain_change(|para_ids| {
963
                // We don't want to add duplicate para ids, so we check whether the potential new
964
                // para id is already present in the list. Because the list is always ordered, we can
965
                // leverage the binary search which makes this check O(log n).
966

            
967
                match para_ids.binary_search(&para_id) {
968
                    // This Ok is unreachable
969
                    Ok(_) => return Err(Error::<T>::ParaIdAlreadyRegistered.into()),
970
                    Err(index) => {
971
                        para_ids
972
                            .try_insert(index, para_id)
973
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
974
                    }
975
                }
976

            
977
                Ok(())
978
            })?;
979

            
980
            T::RegistrarHooks::check_valid_for_collating(para_id)?;
981

            
982
            Self::deposit_event(Event::ParaIdValidForCollating { para_id });
983

            
984
            T::RegistrarHooks::para_marked_valid_for_collating(para_id);
985

            
986
            // If we execute mark_valid_for_collating, we automatically upgrade
987
            // the paraId to a parachain (in the relay context) at the end of the execution.
988
            //
989
            // We only upgrade if the paraId is a parachain in the context of
990
            // this pallet.
991
            if ParathreadParams::<T>::get(para_id).is_none() {
992
                T::InnerRegistrar::schedule_para_upgrade(para_id)?;
993
            }
994

            
995
            Ok(())
996
        }
997

            
998
        /// Relay parachain manager signature message. Includes:
999
        /// * para_id, in case the manager has more than 1 para in the relay
        /// * accountid in tanssi, to ensure that the creator role is assigned to the desired account
        /// * relay_storage_root, to make the signature network-specific, and also make it expire
        ///     when the relay storage root expires.
        pub fn relay_signature_msg(
            para_id: ParaId,
            tanssi_account: &T::AccountId,
            relay_storage_root: H256,
        ) -> Vec<u8> {
            (para_id, tanssi_account, relay_storage_root).encode()
        }
        fn schedule_parachain_change(
            updater: impl FnOnce(&mut BoundedVec<ParaId, T::MaxLengthParaIds>) -> DispatchResult,
        ) -> DispatchResult {
            let mut pending_paras = PendingParaIds::<T>::get();
            // First, we need to decide what we should use as the base paras.
            let mut base_paras = pending_paras
                .last()
                .map(|(_, paras)| paras.clone())
                .unwrap_or_else(Self::registered_para_ids);
            updater(&mut base_paras)?;
            let new_paras = base_paras;
            let scheduled_session = Self::scheduled_session();
            if let Some(&mut (_, ref mut paras)) = pending_paras
                .iter_mut()
                .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
            {
                *paras = new_paras;
            } else {
                // We are scheduling a new parachains change for the scheduled session.
                pending_paras.push((scheduled_session, new_paras));
            }
            <PendingParaIds<T>>::put(pending_paras);
            Ok(())
        }
        fn schedule_paused_parachain_change(
            updater: impl FnOnce(
                &mut BoundedVec<ParaId, T::MaxLengthParaIds>,
                &mut BoundedVec<ParaId, T::MaxLengthParaIds>,
            ) -> DispatchResult,
        ) -> DispatchResult {
            let mut pending_paras = PendingParaIds::<T>::get();
            let mut pending_paused = PendingPaused::<T>::get();
            // First, we need to decide what we should use as the base paras.
            let mut base_paras = pending_paras
                .last()
                .map(|(_, paras)| paras.clone())
                .unwrap_or_else(Self::registered_para_ids);
            let mut base_paused = pending_paused
                .last()
                .map(|(_, paras)| paras.clone())
                .unwrap_or_else(Self::paused);
            let old_base_paras = base_paras.clone();
            let old_base_paused = base_paused.clone();
            updater(&mut base_paras, &mut base_paused)?;
            if base_paras != old_base_paras {
                let new_paras = base_paras;
                let scheduled_session = Self::scheduled_session();
                if let Some(&mut (_, ref mut paras)) = pending_paras
                    .iter_mut()
                    .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
                {
                    *paras = new_paras;
                } else {
                    // We are scheduling a new parachains change for the scheduled session.
                    pending_paras.push((scheduled_session, new_paras));
                }
                <PendingParaIds<T>>::put(pending_paras);
            }
            if base_paused != old_base_paused {
                let new_paused = base_paused;
                let scheduled_session = Self::scheduled_session();
                if let Some(&mut (_, ref mut paras)) = pending_paused
                    .iter_mut()
                    .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
                {
                    *paras = new_paused;
                } else {
                    // We are scheduling a new parachains change for the scheduled session.
                    pending_paused.push((scheduled_session, new_paused));
                }
                <PendingPaused<T>>::put(pending_paused);
            }
            Ok(())
        }
        fn schedule_parathread_params_change(
            para_id: ParaId,
            updater: impl FnOnce(&mut ParathreadParamsTy) -> DispatchResult,
        ) -> DispatchResult {
            // Check that the para id is a parathread by reading the old params
            let params = match ParathreadParams::<T>::get(para_id) {
                Some(x) => x,
                None => {
                    return Err(Error::<T>::NotAParathread.into());
                }
            };
            let mut pending_params = PendingParathreadParams::<T>::get();
            // First, we need to decide what we should use as the base params.
            let mut base_params = pending_params
                .last()
                .and_then(|(_, para_id_params)| {
                    match para_id_params
                        .binary_search_by_key(&para_id, |(para_id, _params)| *para_id)
                    {
                        Ok(idx) => {
                            let (_para_id, params) = &para_id_params[idx];
                            Some(params.clone())
                        }
                        Err(_idx) => None,
                    }
                })
                .unwrap_or(params);
            updater(&mut base_params)?;
            let new_params = base_params;
            let scheduled_session = Self::scheduled_session();
            if let Some(&mut (_, ref mut para_id_params)) = pending_params
                .iter_mut()
                .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
            {
                match para_id_params.binary_search_by_key(&para_id, |(para_id, _params)| *para_id) {
                    Ok(idx) => {
                        let (_para_id, params) = &mut para_id_params[idx];
                        *params = new_params;
                    }
                    Err(idx) => {
                        para_id_params
                            .try_insert(idx, (para_id, new_params))
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
                    }
                }
            } else {
                // We are scheduling a new parathread params change for the scheduled session.
                pending_params.push((
                    scheduled_session,
                    BoundedVec::truncate_from(vec![(para_id, new_params)]),
                ));
            }
            <PendingParathreadParams<T>>::put(pending_params);
            Ok(())
        }
        /// Return the session index that should be used for any future scheduled changes.
        fn scheduled_session() -> T::SessionIndex {
            T::CurrentSessionIndex::session_index().saturating_add(T::SessionDelay::get())
        }
        /// Called by the initializer to note that a new session has started.
        ///
        /// Returns the parachain list that was actual before the session change and the parachain list
        /// that became active after the session change. If there were no scheduled changes, both will
        /// be the same.
135234
        pub fn initializer_on_new_session(
135234
            session_index: &T::SessionIndex,
135234
        ) -> SessionChangeOutcome<T> {
135234
            let pending_paras = <PendingParaIds<T>>::get();
135234
            let prev_paras = RegisteredParaIds::<T>::get();
135234
            let new_paras = if !pending_paras.is_empty() {
                let (mut past_and_present, future) = pending_paras
                    .into_iter()
                    .partition::<Vec<_>, _>(|&(apply_at_session, _)| {
                        apply_at_session <= *session_index
                    });
                if past_and_present.len() > 1 {
                    // This should never happen since we schedule parachain changes only into the future
                    // sessions and this handler called for each session change.
                    log::error!(
                        target: LOG_TARGET,
                        "Skipping applying parachain changes scheduled sessions in the past",
                    );
                }
                let new_paras = past_and_present.pop().map(|(_, paras)| paras);
                if let Some(ref new_paras) = new_paras {
                    // Apply the new parachain list.
                    RegisteredParaIds::<T>::put(new_paras);
                    <PendingParaIds<T>>::put(future);
                }
                new_paras
            } else {
                // pending_paras.is_empty, so parachain list did not change
135234
                None
            };
135234
            let pending_paused = <PendingPaused<T>>::get();
135234
            if !pending_paused.is_empty() {
                let (mut past_and_present, future) = pending_paused
                    .into_iter()
                    .partition::<Vec<_>, _>(|&(apply_at_session, _)| {
                        apply_at_session <= *session_index
                    });
                if past_and_present.len() > 1 {
                    // This should never happen since we schedule parachain changes only into the future
                    // sessions and this handler called for each session change.
                    log::error!(
                        target: LOG_TARGET,
                        "Skipping applying paused parachain changes scheduled sessions in the past",
                    );
                }
                let new_paused = past_and_present.pop().map(|(_, paras)| paras);
                if let Some(ref new_paused) = new_paused {
                    // Apply the new parachain list.
                    Paused::<T>::put(new_paused);
                    <PendingPaused<T>>::put(future);
                }
135234
            }
135234
            let pending_parathread_params = <PendingParathreadParams<T>>::get();
135234
            if !pending_parathread_params.is_empty() {
                let (mut past_and_present, future) = pending_parathread_params
                    .into_iter()
                    .partition::<Vec<_>, _>(|&(apply_at_session, _)| {
                        apply_at_session <= *session_index
                    });
                if past_and_present.len() > 1 {
                    // This should never happen since we schedule parachain changes only into the future
                    // sessions and this handler called for each session change.
                    log::error!(
                        target: LOG_TARGET,
                        "Skipping applying parathread params changes scheduled sessions in the past",
                    );
                }
                let new_params = past_and_present.pop().map(|(_, params)| params);
                if let Some(ref new_params) = new_params {
                    for (para_id, params) in new_params {
                        <ParathreadParams<T>>::insert(para_id, params);
                    }
                    <PendingParathreadParams<T>>::put(future);
                }
135234
            }
135234
            let pending_to_remove = <PendingToRemove<T>>::get();
135234
            if !pending_to_remove.is_empty() {
                let (past_and_present, future) =
                    pending_to_remove.into_iter().partition::<Vec<_>, _>(
                        |&(apply_at_session, _)| apply_at_session <= *session_index,
                    );
                if !past_and_present.is_empty() {
                    // Unlike `PendingParaIds`, this cannot skip items because we must cleanup all parachains.
                    // But this will only happen if `initializer_on_new_session` is not called for a big range of
                    // sessions, and many parachains are deregistered in the meantime.
                    let mut removed_para_ids = BTreeSet::new();
                    for (_, new_paras) in &past_and_present {
                        for para_id in new_paras {
                            Self::cleanup_deregistered_para_id(*para_id);
                            removed_para_ids.insert(*para_id);
                            if let Err(id) =
                                BufferedParasToDeregister::<T>::try_mutate(|v| v.try_push(*para_id))
                            {
                                log::error!(
                                    target: LOG_TARGET,
                                    "Failed to add paraId {:?} to deregistration list",
                                    id
                                );
                            }
                        }
                    }
                    // Also need to remove PendingParams to avoid setting params for a para id that does not exist
                    let mut pending_parathread_params = <PendingParathreadParams<T>>::get();
                    for (_, new_params) in &mut pending_parathread_params {
                        new_params.retain(|(para_id, _params)| {
                            // Retain para ids that are not in the list of removed para ids
                            !removed_para_ids.contains(para_id)
                        });
                    }
                    <PendingParathreadParams<T>>::put(pending_parathread_params);
                    <PendingToRemove<T>>::put(future);
                }
135234
            }
135234
            SessionChangeOutcome {
135234
                prev_paras,
135234
                new_paras,
135234
            }
135234
        }
        /// Remove all para id storage in this pallet,
        /// and execute para_deregistered hook to clean up other pallets as well
        fn cleanup_deregistered_para_id(para_id: ParaId) {
            ParaGenesisData::<T>::remove(para_id);
            ParathreadParams::<T>::remove(para_id);
            // Get asset creator and deposit amount
            // Deposit may not exist, for example if the para id was registered on genesis
            if let Some(asset_info) = RegistrarDeposit::<T>::take(para_id) {
                // Release hold
                let _ = T::Currency::release(
                    &HoldReason::RegistrarDeposit.into(),
                    &asset_info.creator,
                    asset_info.deposit,
                    Precision::Exact,
                );
            }
            ParaManager::<T>::remove(para_id);
            T::RegistrarHooks::para_deregistered(para_id);
        }
        fn schedule_parachain_cleanup(para_id: ParaId) -> DispatchResult {
            let scheduled_session = Self::scheduled_session();
            let mut pending_paras = PendingToRemove::<T>::get();
            // First, we need to decide what we should use as the base paras.
            let base_paras = match pending_paras
                .binary_search_by_key(&scheduled_session, |(session, _paras)| *session)
            {
                Ok(i) => &mut pending_paras[i].1,
                Err(i) => {
                    pending_paras.insert(i, (scheduled_session, Default::default()));
                    &mut pending_paras[i].1
                }
            };
            // Add the para_id to the entry for the scheduled session.
            match base_paras.binary_search(&para_id) {
                // This Ok is unreachable
                Ok(_) => return Err(Error::<T>::ParaIdAlreadyDeregistered.into()),
                Err(index) => {
                    base_paras
                        .try_insert(index, para_id)
                        .map_err(|_e| Error::<T>::ParaIdListFull)?;
                }
            }
            // Save the updated list of pending parachains for removal.
            <PendingToRemove<T>>::put(pending_paras);
            Ok(())
        }
524760
        pub fn registered_para_ids() -> BoundedVec<ParaId, T::MaxLengthParaIds> {
524760
            RegisteredParaIds::<T>::get()
524760
        }
135234
        pub fn pending_registered_para_ids(
135234
        ) -> Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)> {
135234
            PendingParaIds::<T>::get()
135234
        }
        pub fn para_genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
            ParaGenesisData::<T>::get(para_id)
        }
        pub fn pending_verification(para_id: ParaId) -> Option<()> {
            PendingVerification::<T>::get(para_id)
        }
        pub fn paused() -> BoundedVec<ParaId, T::MaxLengthParaIds> {
            Paused::<T>::get()
        }
        pub fn pending_paused() -> Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)> {
            PendingPaused::<T>::get()
        }
        pub fn pending_to_remove() -> Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)>
        {
            PendingToRemove::<T>::get()
        }
        pub fn parathread_params(para_id: ParaId) -> Option<ParathreadParamsTy> {
            ParathreadParams::<T>::get(para_id)
        }
        pub fn pending_parathread_params() -> Vec<(
            T::SessionIndex,
            BoundedVec<(ParaId, ParathreadParamsTy), T::MaxLengthParaIds>,
        )> {
            PendingParathreadParams::<T>::get()
        }
        pub fn registrar_deposit(para_id: ParaId) -> Option<DepositInfo<T>> {
            RegistrarDeposit::<T>::get(para_id)
        }
    }
    impl<T: Config> GetCurrentContainerChains for Pallet<T> {
        type MaxContainerChains = T::MaxLengthParaIds;
389526
        fn current_container_chains() -> BoundedVec<ParaId, Self::MaxContainerChains> {
389526
            Self::registered_para_ids()
389526
        }
        #[cfg(feature = "runtime-benchmarks")]
        fn set_current_container_chains(container_chains: &[ParaId]) {
            let paras: BoundedVec<ParaId, T::MaxLengthParaIds> =
                container_chains.to_vec().try_into().unwrap();
            RegisteredParaIds::<T>::put(paras);
        }
    }
    impl<T: Config> GetSessionContainerChains<T::SessionIndex> for Pallet<T> {
135234
        fn session_container_chains(session_index: T::SessionIndex) -> SessionContainerChains {
135234
            let (past_and_present, _) = Pallet::<T>::pending_registered_para_ids()
135234
                .into_iter()
135234
                .partition::<Vec<_>, _>(|&(apply_at_session, _)| apply_at_session <= session_index);
135234
            let paras = if let Some(last) = past_and_present.last() {
                last.1.clone()
            } else {
135234
                Pallet::<T>::registered_para_ids()
            };
135234
            let mut parachains = vec![];
135234
            let mut parathreads = vec![];
135234
            for para_id in paras {
                // TODO: sweet O(n) db reads
                if let Some(parathread_params) = ParathreadParams::<T>::get(para_id) {
                    parathreads.push((para_id, parathread_params));
                } else {
                    parachains.push(para_id);
                }
            }
135234
            SessionContainerChains {
135234
                parachains,
135234
                parathreads,
135234
            }
135234
        }
        #[cfg(feature = "runtime-benchmarks")]
        fn set_session_container_chains(
            _session_index: T::SessionIndex,
            container_chains: &[ParaId],
        ) {
            // TODO: this assumes session_index == current
            let paras: BoundedVec<ParaId, T::MaxLengthParaIds> =
                container_chains.to_vec().try_into().unwrap();
            RegisteredParaIds::<T>::put(paras);
        }
    }
}
pub trait RegistrarHooks {
    fn para_marked_valid_for_collating(_para_id: ParaId) -> Weight {
        Weight::default()
    }
    fn para_deregistered(_para_id: ParaId) -> Weight {
        Weight::default()
    }
    fn check_valid_for_collating(_para_id: ParaId) -> DispatchResult {
        Ok(())
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn benchmarks_ensure_valid_for_collating(_para_id: ParaId) {}
}
impl RegistrarHooks for () {}
pub struct EnsureSignedByManager<T>(sp_std::marker::PhantomData<T>);
impl<T> EnsureOriginWithArg<T::RuntimeOrigin, ParaId> for EnsureSignedByManager<T>
where
    T: Config,
{
    type Success = T::AccountId;
96
    fn try_origin(
96
        o: T::RuntimeOrigin,
96
        para_id: &ParaId,
96
    ) -> Result<Self::Success, T::RuntimeOrigin> {
96
        let signed_account =
96
            <frame_system::EnsureSigned<_> as EnsureOrigin<_>>::try_origin(o.clone())?;
96
        if !Pallet::<T>::is_para_manager(para_id, &signed_account) {
96
            return Err(frame_system::RawOrigin::Signed(signed_account).into());
        }
        Ok(signed_account)
96
    }
    #[cfg(feature = "runtime-benchmarks")]
    fn try_successful_origin(para_id: &ParaId) -> Result<T::RuntimeOrigin, ()> {
        let manager = Pallet::<T>::benchmarks_get_or_create_para_manager(para_id);
        Ok(frame_system::RawOrigin::Signed(manager).into())
    }
}
// TODO: import this from dancekit
pub const REGISTRAR_PARAS_INDEX: &[u8] =
    &hex_literal::hex!["3fba98689ebed1138735e0e7a5a790abcd710b30bd2eab0352ddcc26417aa194"];
// Need to copy ParaInfo from
// polkadot-sdk/polkadot/runtime/common/src/paras_registrar/mod.rs
// Because its fields are not public...
// TODO: import this from dancekit
#[derive(Encode, Decode, Clone, PartialEq, Eq, Default, TypeInfo)]
pub struct ParaInfo<Account, Balance> {
    /// The account that has placed a deposit for registering this para.
    manager: Account,
    /// The amount reserved by the `manager` account for the registration.
    deposit: Balance,
    /// Whether the para registration should be locked from being controlled by the manager.
    /// None means the lock had not been explicitly set, and should be treated as false.
    locked: Option<bool>,
}