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
9275
#[frame_support::pallet]
74
pub mod pallet {
75
    use super::*;
76

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

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

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

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

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

            
131
332
            <RegisteredParaIds<T>>::put(bounded_para_ids);
132
332
        }
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
105084
    #[pallet::storage]
191
    pub type RegisteredParaIds<T: Config> =
192
        StorageValue<_, BoundedVec<ParaId, T::MaxLengthParaIds>, ValueQuery>;
193

            
194
38190
    #[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
795
    #[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
584
    #[pallet::storage]
209
    pub type PendingVerification<T: Config> =
210
        StorageMap<_, Blake2_128Concat, ParaId, (), OptionQuery>;
211

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

            
216
4826
    #[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
4954
    #[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
31600
    #[pallet::storage]
233
    pub type ParathreadParams<T: Config> =
234
        StorageMap<_, Blake2_128Concat, ParaId, ParathreadParamsTy, OptionQuery>;
235

            
236
4854
    #[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
32960
    #[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
776
        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
283
    #[pallet::storage]
284
    pub type RegistrarDeposit<T: Config> = StorageMap<_, Blake2_128Concat, ParaId, DepositInfo<T>>;
285

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

            
290
    #[pallet::event]
291
412
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
292
    pub enum Event<T: Config> {
293
10
        /// A new para id has been registered. [para_id]
294
        ParaIdRegistered { para_id: ParaId },
295
15
        /// A para id has been deregistered. [para_id]
296
        ParaIdDeregistered { para_id: ParaId },
297
4
        /// A new para id is now valid for collating. [para_id]
298
        ParaIdValidForCollating { para_id: ParaId },
299
2
        /// 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
104
    #[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
197
        RegistrarDeposit,
353
    }
354

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

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

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

            
370
        #[cfg(feature = "try-runtime")]
371
        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
            let mut para_ids: Vec<ParaId> = vec![];
376
            para_ids.extend(RegisteredParaIds::<T>::get());
377
            para_ids.extend(PendingVerification::<T>::iter_keys());
378
            para_ids.extend(Paused::<T>::get());
379
            para_ids.sort();
380
            para_ids.dedup_by(|a, b| {
381
                if a == b {
382
                    panic!("Duplicate para id: {}", u32::from(*a));
383
                } else {
384
                    false
385
                }
386
            });
387

            
388
            // All para ids have an entry in `ParaGenesisData`
389
            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
            let mut para_id_set = BTreeSet::from_iter(para_ids.iter().cloned());
399
            // Also add the Pending lists here
400
            para_id_set.extend(
401
                PendingParaIds::<T>::get()
402
                    .into_iter()
403
                    .flat_map(|(_session_index, x)| x),
404
            );
405
            para_id_set.extend(
406
                PendingPaused::<T>::get()
407
                    .into_iter()
408
                    .flat_map(|(_session_index, x)| x),
409
            );
410
            para_id_set.extend(
411
                PendingToRemove::<T>::get()
412
                    .into_iter()
413
                    .flat_map(|(_session_index, x)| x),
414
            );
415
            let entries: Vec<_> = RegistrarDeposit::<T>::iter().map(|(k, _v)| k).collect();
416
            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
            let entries: Vec<_> = ParaGenesisData::<T>::iter().map(|(k, _v)| k).collect();
424
            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
            fn assert_is_sorted_and_unique<T: Ord>(x: &[T], name: &str) {
434
                assert!(
435
                    x.windows(2).all(|w| w[0] < w[1]),
436
                    "sorted list not sorted or not unique: {}",
437
                    name,
438
                );
439
            }
440
            assert_is_sorted_and_unique(&RegisteredParaIds::<T>::get(), "RegisteredParaIds");
441
            assert_is_sorted_and_unique(&Paused::<T>::get(), "Paused");
442
            for (i, (_session_index, x)) in PendingParaIds::<T>::get().into_iter().enumerate() {
443
                assert_is_sorted_and_unique(&x, &format!("PendingParaIds[{}]", i));
444
            }
445
            for (i, (_session_index, x)) in PendingPaused::<T>::get().into_iter().enumerate() {
446
                assert_is_sorted_and_unique(&x, &format!("PendingPaused[{}]", i));
447
            }
448
            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
            let pending: Vec<_> = PendingParaIds::<T>::get()
454
                .into_iter()
455
                .map(|(session_index, _x)| session_index)
456
                .collect();
457
            assert_is_sorted_and_unique(&pending, "PendingParaIds");
458
            let pending: Vec<_> = PendingPaused::<T>::get()
459
                .into_iter()
460
                .map(|(session_index, _x)| session_index)
461
                .collect();
462
            assert_is_sorted_and_unique(&pending, "PendingPaused");
463
            let pending: Vec<_> = PendingToRemove::<T>::get()
464
                .into_iter()
465
                .map(|(session_index, _x)| session_index)
466
                .collect();
467
            assert_is_sorted_and_unique(&pending, "PendingToRemove");
468

            
469
            Ok(())
470
        }
471
    }
472

            
473
809
    #[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
160
        ) -> DispatchResult {
484
160
            let account = ensure_signed(origin)?;
485
159
            Self::do_register(account, para_id, genesis_data, head_data)?;
486
151
            Self::deposit_event(Event::ParaIdRegistered { para_id });
487
151

            
488
151
            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
72
        pub fn deregister(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
500
72
            T::RegistrarOrigin::ensure_origin(origin)?;
501

            
502
71
            Self::do_deregister(para_id)?;
503

            
504
69
            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
138
        pub fn mark_valid_for_collating(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
511
138
            T::MarkValidForCollatingOrigin::ensure_origin(origin)?;
512

            
513
137
            Self::do_mark_valid_for_collating(para_id)?;
514

            
515
130
            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
13
        pub fn pause_container_chain(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
523
13
            T::RegistrarOrigin::ensure_origin(origin)?;
524

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

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

            
547
10
            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
8
        pub fn unpause_container_chain(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
555
8
            T::RegistrarOrigin::ensure_origin(origin)?;
556

            
557
8
            Self::schedule_paused_parachain_change(|para_ids, paused| {
558
8
                match paused.binary_search(&para_id) {
559
5
                    Ok(index) => {
560
5
                        paused.remove(index);
561
5
                    }
562
3
                    Err(_) => return Err(Error::<T>::ParaIdNotPaused.into()),
563
                }
564
5
                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
5
                    Err(index) => {
568
5
                        para_ids
569
5
                            .try_insert(index, para_id)
570
5
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
571
                    }
572
                }
573
5
                Self::deposit_event(Event::ParaIdUnpaused { para_id });
574
5

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

            
578
5
            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
24
        ) -> DispatchResult {
591
24
            let account = ensure_signed(origin)?;
592
24
            Self::do_register(account, para_id, genesis_data, head_data)?;
593
            // Insert parathread params
594
24
            let params = ParathreadParamsTy { slot_frequency };
595
24
            ParathreadParams::<T>::insert(para_id, params);
596
24
            Self::deposit_event(Event::ParaIdRegistered { para_id });
597
24

            
598
24
            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
8
        ) -> DispatchResult {
609
8
            T::RegistrarOrigin::ensure_origin(origin)?;
610

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

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

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

            
619
7
            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
4
        ) -> DispatchResult {
629
4
            let origin = ensure_signed(origin)?;
630

            
631
4
            let creator =
632
4
                RegistrarDeposit::<T>::get(para_id).map(|deposit_info| deposit_info.creator);
633
4

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

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

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

            
643
4
            Ok(())
644
        }
645

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

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

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

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

            
693
5
            Ok(())
694
        }
695

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

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

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

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

            
749
6
            Self::do_deregister(para_id)?;
750

            
751
6
            Ok(())
752
        }
753
    }
754

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

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

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

            
787
                /// Create a funded user.
788
                /// Used for generating the necessary amount for registering
789
                fn create_funded_user<T: Config>(
790
                    string: &'static str,
791
                    n: u32,
792
                    total: DepositBalanceOf<T>,
793
                ) -> (T::AccountId, DepositBalanceOf<T>) {
794
                    const SEED: u32 = 0;
795
                    let user = account(string, n, SEED);
796
                    assert_ok!(T::Currency::mint_into(&user, total));
797
                    (user, total)
798
                }
799
                let new_balance =
800
                    (T::Currency::minimum_balance() + T::DepositAmount::get()) * 2u32.into();
801
                let account = create_funded_user::<T>("caller", 1000, new_balance).0;
802
                let origin = RawOrigin::Signed(account);
803
                assert_ok!(Self::register(
804
                    origin.into(),
805
                    *para_id,
806
                    Default::default(),
807
                    None
808
                ));
809
            }
810

            
811
            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");
812

            
813
            // Fund deposit creator, just in case it is not a new account
814
            let new_balance =
815
                (T::Currency::minimum_balance() + T::DepositAmount::get()) * 2u32.into();
816
            assert_ok!(T::Currency::mint_into(&deposit_info.creator, new_balance));
817

            
818
            deposit_info.creator
819
        }
820

            
821
188
        fn do_register(
822
188
            account: T::AccountId,
823
188
            para_id: ParaId,
824
188
            genesis_data: ContainerChainGenesisData,
825
188
            head_data: Option<HeadData>,
826
188
        ) -> DispatchResult {
827
188
            let deposit = T::DepositAmount::get();
828
188
            // Verify we can hold
829
188
            if !T::Currency::can_hold(&HoldReason::RegistrarDeposit.into(), &account, deposit) {
830
                return Err(Error::<T>::NotSufficientDeposit.into());
831
188
            }
832
188

            
833
188
            // Check if the para id is already registered by looking at the genesis data
834
188
            if ParaGenesisData::<T>::contains_key(para_id) {
835
7
                return Err(Error::<T>::ParaIdAlreadyRegistered.into());
836
181
            }
837
181

            
838
181
            // Check if the para id is already in PendingVerification (unreachable)
839
181
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
840
181
            if is_pending_verification {
841
                return Err(Error::<T>::ParaIdAlreadyRegistered.into());
842
181
            }
843
181

            
844
181
            // Insert para id into PendingVerification
845
181
            PendingVerification::<T>::insert(para_id, ());
846
181

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

            
861
180
            // Hold the deposit, we verified we can do this
862
180
            T::Currency::hold(&HoldReason::RegistrarDeposit.into(), &account, deposit)?;
863

            
864
            // Register the paraId also in the relay context (if any).
865
180
            T::InnerRegistrar::register(
866
180
                account.clone(),
867
180
                para_id,
868
180
                &genesis_data.storage,
869
180
                head_data,
870
180
            )?;
871

            
872
            // Update DepositInfo
873
180
            RegistrarDeposit::<T>::insert(
874
180
                para_id,
875
180
                DepositInfo {
876
180
                    creator: account.clone(),
877
180
                    deposit,
878
180
                },
879
180
            );
880
180
            ParaGenesisData::<T>::insert(para_id, genesis_data);
881
180

            
882
180
            ParaManager::<T>::insert(para_id, account);
883
180

            
884
180
            Ok(())
885
188
        }
886

            
887
77
        fn do_deregister(para_id: ParaId) -> DispatchResult {
888
77
            // Check if the para id is in "PendingVerification".
889
77
            // This is a special case because then we can remove it immediately, instead of waiting 2 sessions.
890
77
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
891
77
            if is_pending_verification {
892
12
                Self::deposit_event(Event::ParaIdDeregistered { para_id });
893
12
                // Cleanup immediately
894
12
                Self::cleanup_deregistered_para_id(para_id);
895
12
                BufferedParasToDeregister::<T>::try_mutate(|v| v.try_push(para_id)).map_err(
896
12
                    |_e| {
897
                        DispatchError::Other(
898
                            "Failed to add paraId to deregistration list: buffer is full",
899
                        )
900
12
                    },
901
12
                )?;
902
            } else {
903
65
                Self::schedule_paused_parachain_change(|para_ids, paused| {
904
65
                    // We have to find out where, in the sorted vec the para id is, if anywhere.
905
65

            
906
65
                    match para_ids.binary_search(&para_id) {
907
60
                        Ok(index) => {
908
60
                            para_ids.remove(index);
909
60
                        }
910
                        Err(_) => {
911
                            // If the para id is not registered, it may be paused. In that case, remove it from there
912
5
                            match paused.binary_search(&para_id) {
913
3
                                Ok(index) => {
914
3
                                    paused.remove(index);
915
3
                                }
916
                                Err(_) => {
917
2
                                    return Err(Error::<T>::ParaIdNotRegistered.into());
918
                                }
919
                            }
920
                        }
921
                    }
922

            
923
63
                    Ok(())
924
65
                })?;
925
                // Mark this para id for cleanup later
926
63
                Self::schedule_parachain_cleanup(para_id)?;
927

            
928
                // If we have InnerRegistrar set to a relay context (like Dancelight),
929
                // we first need to downgrade the paraId (if it was a parachain before)
930
                // and convert it to a parathread before deregistering it. Otherwise
931
                // the deregistration process will fail in the scheduled session.
932
                //
933
                // We only downgrade if the paraId is a parachain in the context of
934
                // this pallet.
935
63
                if ParathreadParams::<T>::get(para_id).is_none() {
936
61
                    T::InnerRegistrar::schedule_para_downgrade(para_id)?;
937
2
                }
938

            
939
63
                Self::deposit_event(Event::ParaIdDeregistered { para_id });
940
            }
941

            
942
75
            Ok(())
943
77
        }
944

            
945
137
        fn do_mark_valid_for_collating(para_id: ParaId) -> DispatchResult {
946
137
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
947
137
            if !is_pending_verification {
948
3
                return Err(Error::<T>::ParaIdNotInPendingVerification.into());
949
134
            }
950
134

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

            
956
134
                match para_ids.binary_search(&para_id) {
957
                    // This Ok is unreachable
958
                    Ok(_) => return Err(Error::<T>::ParaIdAlreadyRegistered.into()),
959
134
                    Err(index) => {
960
134
                        para_ids
961
134
                            .try_insert(index, para_id)
962
134
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
963
                    }
964
                }
965

            
966
134
                Ok(())
967
134
            })?;
968

            
969
134
            T::RegistrarHooks::check_valid_for_collating(para_id)?;
970

            
971
131
            Self::deposit_event(Event::ParaIdValidForCollating { para_id });
972
131

            
973
131
            T::RegistrarHooks::para_marked_valid_for_collating(para_id);
974
131

            
975
131
            // If we execute mark_valid_for_collating, we automatically upgrade
976
131
            // the paraId to a parachain (in the relay context) at the end of the execution.
977
131
            //
978
131
            // We only upgrade if the paraId is a parachain in the context of
979
131
            // this pallet.
980
131
            if ParathreadParams::<T>::get(para_id).is_none() {
981
107
                T::InnerRegistrar::schedule_para_upgrade(para_id)?;
982
24
            }
983

            
984
130
            Ok(())
985
137
        }
986

            
987
        /// Relay parachain manager signature message. Includes:
988
        /// * para_id, in case the manager has more than 1 para in the relay
989
        /// * accountid in tanssi, to ensure that the creator role is assigned to the desired account
990
        /// * relay_storage_root, to make the signature network-specific, and also make it expire
991
        ///     when the relay storage root expires.
992
14
        pub fn relay_signature_msg(
993
14
            para_id: ParaId,
994
14
            tanssi_account: &T::AccountId,
995
14
            relay_storage_root: H256,
996
14
        ) -> Vec<u8> {
997
14
            (para_id, tanssi_account, relay_storage_root).encode()
998
14
        }
999

            
134
        fn schedule_parachain_change(
134
            updater: impl FnOnce(&mut BoundedVec<ParaId, T::MaxLengthParaIds>) -> DispatchResult,
134
        ) -> DispatchResult {
134
            let mut pending_paras = PendingParaIds::<T>::get();
134
            // First, we need to decide what we should use as the base paras.
134
            let mut base_paras = pending_paras
134
                .last()
134
                .map(|(_, paras)| paras.clone())
134
                .unwrap_or_else(Self::registered_para_ids);
134

            
134
            updater(&mut base_paras)?;
134
            let new_paras = base_paras;
134

            
134
            let scheduled_session = Self::scheduled_session();
134
            if let Some(&mut (_, ref mut paras)) = pending_paras
134
                .iter_mut()
134
                .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
7
            {
7
                *paras = new_paras;
127
            } else {
127
                // We are scheduling a new parachains change for the scheduled session.
127
                pending_paras.push((scheduled_session, new_paras));
127
            }
134
            <PendingParaIds<T>>::put(pending_paras);
134

            
134
            Ok(())
134
        }
85
        fn schedule_paused_parachain_change(
85
            updater: impl FnOnce(
85
                &mut BoundedVec<ParaId, T::MaxLengthParaIds>,
85
                &mut BoundedVec<ParaId, T::MaxLengthParaIds>,
85
            ) -> DispatchResult,
85
        ) -> DispatchResult {
85
            let mut pending_paras = PendingParaIds::<T>::get();
85
            let mut pending_paused = PendingPaused::<T>::get();
85
            // First, we need to decide what we should use as the base paras.
85
            let mut base_paras = pending_paras
85
                .last()
85
                .map(|(_, paras)| paras.clone())
85
                .unwrap_or_else(Self::registered_para_ids);
85
            let mut base_paused = pending_paused
85
                .last()
85
                .map(|(_, paras)| paras.clone())
85
                .unwrap_or_else(Self::paused);
85
            let old_base_paras = base_paras.clone();
85
            let old_base_paused = base_paused.clone();
85

            
85
            updater(&mut base_paras, &mut base_paused)?;
78
            if base_paras != old_base_paras {
75
                let new_paras = base_paras;
75
                let scheduled_session = Self::scheduled_session();
75
                if let Some(&mut (_, ref mut paras)) = pending_paras
75
                    .iter_mut()
75
                    .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
22
                {
22
                    *paras = new_paras;
57
                } else {
53
                    // We are scheduling a new parachains change for the scheduled session.
53
                    pending_paras.push((scheduled_session, new_paras));
53
                }
75
                <PendingParaIds<T>>::put(pending_paras);
3
            }
78
            if base_paused != old_base_paused {
18
                let new_paused = base_paused;
18
                let scheduled_session = Self::scheduled_session();
18
                if let Some(&mut (_, ref mut paras)) = pending_paused
18
                    .iter_mut()
18
                    .find(|&&mut (apply_at_session, _)| apply_at_session >= scheduled_session)
2
                {
2
                    *paras = new_paused;
16
                } else {
16
                    // We are scheduling a new parachains change for the scheduled session.
16
                    pending_paused.push((scheduled_session, new_paused));
16
                }
18
                <PendingPaused<T>>::put(pending_paused);
60
            }
78
            Ok(())
85
        }
8
        fn schedule_parathread_params_change(
8
            para_id: ParaId,
8
            updater: impl FnOnce(&mut ParathreadParamsTy) -> DispatchResult,
8
        ) -> DispatchResult {
            // Check that the para id is a parathread by reading the old params
8
            let params = match ParathreadParams::<T>::get(para_id) {
7
                Some(x) => x,
                None => {
1
                    return Err(Error::<T>::NotAParathread.into());
                }
            };
7
            let mut pending_params = PendingParathreadParams::<T>::get();
7
            // First, we need to decide what we should use as the base params.
7
            let mut base_params = pending_params
7
                .last()
7
                .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,
                    }
7
                })
7
                .unwrap_or(params);
7

            
7
            updater(&mut base_params)?;
7
            let new_params = base_params;
7

            
7
            let scheduled_session = Self::scheduled_session();
7
            if let Some(&mut (_, ref mut para_id_params)) = pending_params
7
                .iter_mut()
7
                .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)?;
                    }
                }
7
            } else {
7
                // We are scheduling a new parathread params change for the scheduled session.
7
                pending_params.push((
7
                    scheduled_session,
7
                    BoundedVec::truncate_from(vec![(para_id, new_params)]),
7
                ));
7
            }
7
            <PendingParathreadParams<T>>::put(pending_params);
7

            
7
            Ok(())
8
        }
        /// Return the session index that should be used for any future scheduled changes.
297
        fn scheduled_session() -> T::SessionIndex {
297
            T::CurrentSessionIndex::session_index().saturating_add(T::SessionDelay::get())
297
        }
        /// 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.
2296
        pub fn initializer_on_new_session(
2296
            session_index: &T::SessionIndex,
2296
        ) -> SessionChangeOutcome<T> {
2296
            let pending_paras = <PendingParaIds<T>>::get();
2296
            let prev_paras = RegisteredParaIds::<T>::get();
2296
            let new_paras = if !pending_paras.is_empty() {
310
                let (mut past_and_present, future) = pending_paras
310
                    .into_iter()
314
                    .partition::<Vec<_>, _>(|&(apply_at_session, _)| {
314
                        apply_at_session <= *session_index
314
                    });
310

            
310
                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",
                    );
310
                }
310
                let new_paras = past_and_present.pop().map(|(_, paras)| paras);
310
                if let Some(ref new_paras) = new_paras {
157
                    // Apply the new parachain list.
157
                    RegisteredParaIds::<T>::put(new_paras);
157
                    <PendingParaIds<T>>::put(future);
157
                }
310
                new_paras
            } else {
                // pending_paras.is_empty, so parachain list did not change
1986
                None
            };
2296
            let pending_paused = <PendingPaused<T>>::get();
2296
            if !pending_paused.is_empty() {
27
                let (mut past_and_present, future) = pending_paused
27
                    .into_iter()
28
                    .partition::<Vec<_>, _>(|&(apply_at_session, _)| {
28
                        apply_at_session <= *session_index
28
                    });
27

            
27
                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",
                    );
27
                }
27
                let new_paused = past_and_present.pop().map(|(_, paras)| paras);
27
                if let Some(ref new_paused) = new_paused {
14
                    // Apply the new parachain list.
14
                    Paused::<T>::put(new_paused);
14
                    <PendingPaused<T>>::put(future);
14
                }
2269
            }
2296
            let pending_parathread_params = <PendingParathreadParams<T>>::get();
2296
            if !pending_parathread_params.is_empty() {
14
                let (mut past_and_present, future) = pending_parathread_params
14
                    .into_iter()
14
                    .partition::<Vec<_>, _>(|&(apply_at_session, _)| {
14
                        apply_at_session <= *session_index
14
                    });
14

            
14
                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",
                    );
14
                }
14
                let new_params = past_and_present.pop().map(|(_, params)| params);
14
                if let Some(ref new_params) = new_params {
13
                    for (para_id, params) in new_params {
6
                        <ParathreadParams<T>>::insert(para_id, params);
6
                    }
7
                    <PendingParathreadParams<T>>::put(future);
7
                }
2282
            }
2296
            let pending_to_remove = <PendingToRemove<T>>::get();
2296
            if !pending_to_remove.is_empty() {
109
                let (past_and_present, future) =
109
                    pending_to_remove.into_iter().partition::<Vec<_>, _>(
110
                        |&(apply_at_session, _)| apply_at_session <= *session_index,
109
                    );
109

            
109
                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.
55
                    let mut removed_para_ids = BTreeSet::new();
110
                    for (_, new_paras) in &past_and_present {
116
                        for para_id in new_paras {
61
                            Self::cleanup_deregistered_para_id(*para_id);
61
                            removed_para_ids.insert(*para_id);
                            if let Err(id) =
61
                                BufferedParasToDeregister::<T>::try_mutate(|v| v.try_push(*para_id))
                            {
                                log::error!(
                                    target: LOG_TARGET,
                                    "Failed to add paraId {:?} to deregistration list",
                                    id
                                );
61
                            }
                        }
                    }
                    // Also need to remove PendingParams to avoid setting params for a para id that does not exist
55
                    let mut pending_parathread_params = <PendingParathreadParams<T>>::get();
56
                    for (_, new_params) in &mut pending_parathread_params {
1
                        new_params.retain(|(para_id, _params)| {
1
                            // Retain para ids that are not in the list of removed para ids
1
                            !removed_para_ids.contains(para_id)
1
                        });
1
                    }
55
                    <PendingParathreadParams<T>>::put(pending_parathread_params);
55
                    <PendingToRemove<T>>::put(future);
54
                }
2187
            }
2296
            SessionChangeOutcome {
2296
                prev_paras,
2296
                new_paras,
2296
            }
2296
        }
        /// Remove all para id storage in this pallet,
        /// and execute para_deregistered hook to clean up other pallets as well
73
        fn cleanup_deregistered_para_id(para_id: ParaId) {
73
            ParaGenesisData::<T>::remove(para_id);
73
            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
73
            if let Some(asset_info) = RegistrarDeposit::<T>::take(para_id) {
32
                // Release hold
32
                let _ = T::Currency::release(
32
                    &HoldReason::RegistrarDeposit.into(),
32
                    &asset_info.creator,
32
                    asset_info.deposit,
32
                    Precision::Exact,
32
                );
60
            }
73
            ParaManager::<T>::remove(para_id);
73

            
73
            T::RegistrarHooks::para_deregistered(para_id);
73
        }
63
        fn schedule_parachain_cleanup(para_id: ParaId) -> DispatchResult {
63
            let scheduled_session = Self::scheduled_session();
63
            let mut pending_paras = PendingToRemove::<T>::get();
            // First, we need to decide what we should use as the base paras.
63
            let base_paras = match pending_paras
63
                .binary_search_by_key(&scheduled_session, |(session, _paras)| *session)
            {
6
                Ok(i) => &mut pending_paras[i].1,
57
                Err(i) => {
57
                    pending_paras.insert(i, (scheduled_session, Default::default()));
57

            
57
                    &mut pending_paras[i].1
                }
            };
            // Add the para_id to the entry for the scheduled session.
63
            match base_paras.binary_search(&para_id) {
                // This Ok is unreachable
                Ok(_) => return Err(Error::<T>::ParaIdAlreadyDeregistered.into()),
63
                Err(index) => {
63
                    base_paras
63
                        .try_insert(index, para_id)
63
                        .map_err(|_e| Error::<T>::ParaIdListFull)?;
                }
            }
            // Save the updated list of pending parachains for removal.
63
            <PendingToRemove<T>>::put(pending_paras);
63

            
63
            Ok(())
63
        }
49755
        pub fn registered_para_ids() -> BoundedVec<ParaId, T::MaxLengthParaIds> {
49755
            RegisteredParaIds::<T>::get()
49755
        }
16212
        pub fn pending_registered_para_ids(
16212
        ) -> Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)> {
16212
            PendingParaIds::<T>::get()
16212
        }
80
        pub fn para_genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
80
            ParaGenesisData::<T>::get(para_id)
80
        }
        pub fn pending_verification(para_id: ParaId) -> Option<()> {
            PendingVerification::<T>::get(para_id)
        }
87
        pub fn paused() -> BoundedVec<ParaId, T::MaxLengthParaIds> {
87
            Paused::<T>::get()
87
        }
        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()
        }
27
        pub fn parathread_params(para_id: ParaId) -> Option<ParathreadParamsTy> {
27
            ParathreadParams::<T>::get(para_id)
27
        }
        pub fn pending_parathread_params() -> Vec<(
            T::SessionIndex,
            BoundedVec<(ParaId, ParathreadParamsTy), T::MaxLengthParaIds>,
        )> {
            PendingParathreadParams::<T>::get()
        }
14
        pub fn registrar_deposit(para_id: ParaId) -> Option<DepositInfo<T>> {
14
            RegistrarDeposit::<T>::get(para_id)
14
        }
    }
    impl<T: Config> GetCurrentContainerChains for Pallet<T> {
        type MaxContainerChains = T::MaxLengthParaIds;
33513
        fn current_container_chains() -> BoundedVec<ParaId, Self::MaxContainerChains> {
33513
            Self::registered_para_ids()
33513
        }
        #[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> {
16182
        fn session_container_chains(session_index: T::SessionIndex) -> SessionContainerChains {
16182
            let (past_and_present, _) = Pallet::<T>::pending_registered_para_ids()
16182
                .into_iter()
16182
                .partition::<Vec<_>, _>(|&(apply_at_session, _)| apply_at_session <= session_index);
16182
            let paras = if let Some(last) = past_and_present.last() {
181
                last.1.clone()
            } else {
16001
                Pallet::<T>::registered_para_ids()
            };
16182
            let mut parachains = vec![];
16182
            let mut parathreads = vec![];
47428
            for para_id in paras {
                // TODO: sweet O(n) db reads
31246
                if let Some(parathread_params) = ParathreadParams::<T>::get(para_id) {
593
                    parathreads.push((para_id, parathread_params));
30653
                } else {
30653
                    parachains.push(para_id);
30653
                }
            }
16182
            SessionContainerChains {
16182
                parachains,
16182
                parathreads,
16182
            }
16182
        }
        #[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;
157
    fn try_origin(
157
        o: T::RuntimeOrigin,
157
        para_id: &ParaId,
157
    ) -> Result<Self::Success, T::RuntimeOrigin> {
131
        let signed_account =
157
            <frame_system::EnsureSigned<_> as EnsureOrigin<_>>::try_origin(o.clone())?;
131
        if !Pallet::<T>::is_para_manager(para_id, &signed_account) {
4
            return Err(frame_system::RawOrigin::Signed(signed_account).into());
127
        }
127

            
127
        Ok(signed_account)
157
    }
    #[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>,
}