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

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

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

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

            
115
466
                let genesis_data_size = genesis_data.encoded_size();
116
466
                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
465
                }
124
465
                <ParaGenesisData<T>>::insert(para_id, genesis_data);
125

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

            
131
1320
            <RegisteredParaIds<T>>::put(bounded_para_ids);
132
1320
        }
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 maintenance extrinsics for container owner
142
        type RegistrarOrigin: EnsureOriginWithArg<Self::RuntimeOrigin, ParaId>;
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
        type RegistrarHooks: RegistrarHooks;
175

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

            
184
        type WeightInfo: WeightInfo;
185

            
186
        #[pallet::constant]
187
        type DataDepositPerByte: Get<<Self::Currency as Inspect<Self::AccountId>>::Balance>;
188
    }
189

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

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

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

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

            
236
10646
    #[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
62758
    #[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
1236
        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
1036
    #[pallet::storage]
284
    pub type RegistrarDeposit<T: Config> = StorageMap<_, Blake2_128Concat, ParaId, DepositInfo<T>>;
285

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

            
290
618
    #[pallet::event]
291
608
    #[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
19
        /// 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
116
    #[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
347
        RegistrarDeposit,
353
    }
354

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

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

            
362
30905
            for para_id in buffered_paras {
363
65
                weight.saturating_accrue(T::InnerRegistrar::deregister_weight());
364
65
                // Deregister (in the relay context) each paraId present inside the buffer
365
65
                T::InnerRegistrar::deregister(para_id);
366
65
            }
367
30840
            weight
368
30840
        }
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
2099
    #[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
230
        ) -> DispatchResult {
484
230
            let account = ensure_signed(origin)?;
485
229
            Self::do_register(account, para_id, genesis_data, head_data)?;
486
213
            Self::deposit_event(Event::ParaIdRegistered { para_id });
487
213

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

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

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

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

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

            
525
23
            Self::schedule_paused_parachain_change(|para_ids, paused| {
526
23
                match paused.binary_search(&para_id) {
527
1
                    Ok(_) => return Err(Error::<T>::ParaIdAlreadyPaused.into()),
528
22
                    Err(index) => {
529
22
                        paused
530
22
                            .try_insert(index, para_id)
531
22
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
532
                    }
533
                }
534
22
                match para_ids.binary_search(&para_id) {
535
21
                    Ok(index) => {
536
21
                        para_ids.remove(index);
537
21
                    }
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
21
                Self::deposit_event(Event::ParaIdPaused { para_id });
543
21

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

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

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

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

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

            
598
40
            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
10
        ) -> DispatchResult {
609
10
            T::RegistrarOrigin::ensure_origin(origin, &para_id)?;
610

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

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

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

            
619
9
            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
16
        ) -> DispatchResult {
629
            // Allow root to force set para manager.
630
16
            if let Some(origin) = ensure_signed_or_root(origin)? {
631
6
                let creator =
632
6
                    RegistrarDeposit::<T>::get(para_id).map(|deposit_info| deposit_info.creator);
633
6

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

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

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

            
644
16
            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
13
        ) -> DispatchResult {
660
13
            let account = T::RegisterWithRelayProofOrigin::ensure_origin(origin)?;
661
12
            let relay_storage_root =
662
13
                T::RelayStorageRootProvider::get_relay_storage_root(relay_proof_block_number)
663
13
                    .ok_or(Error::<T>::RelayStorageRootNotFound)?;
664
11
            let relay_state_proof =
665
12
                GenericStateProof::<cumulus_primitives_core::relay_chain::Block>::new(
666
12
                    relay_storage_root,
667
12
                    relay_storage_proof,
668
12
                )
669
12
                .map_err(|_| Error::<T>::InvalidRelayStorageProof)?;
670

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

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

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

            
694
7
            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
11
        ) -> DispatchResult {
709
11
            let account = T::RegisterWithRelayProofOrigin::ensure_origin(origin)?;
710

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

            
721
9
            let bytes = para_id.twox_64_concat();
722
9
            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
9
            let relay_para_info = relay_state_proof
726
9
                .read_optional_entry::<ParaInfo<
727
9
                    cumulus_primitives_core::relay_chain::AccountId,
728
9
                    cumulus_primitives_core::relay_chain::Balance,
729
9
                >>(key.as_slice())
730
9
                .map_err(|_| Error::<T>::InvalidRelayStorageProof)?;
731
9
            if relay_para_info.is_some() {
732
1
                return Err(Error::<T>::ParaStillExistsInRelay.into());
733
8
            }
734

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

            
750
8
            Self::do_deregister(para_id)?;
751

            
752
8
            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
223
        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
223
            if let Some(manager) = ParaManager::<T>::get(para_id) {
769
214
                manager == *account
770
            } else {
771
9
                RegistrarDeposit::<T>::get(para_id)
772
9
                    .map(|deposit_info| deposit_info.creator)
773
9
                    .as_ref()
774
9
                    == Some(account)
775
            }
776
223
        }
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

            
785
            let mut storage = BoundedVec::try_from(vec![]).unwrap();
786
            storage
787
                .try_push((b":code".to_vec(), vec![1; 10]).into())
788
                .unwrap();
789
            let genesis_data = ContainerChainGenesisData {
790
                storage,
791
                name: Default::default(),
792
                id: Default::default(),
793
                fork_id: Default::default(),
794
                extensions: Default::default(),
795
                properties: Default::default(),
796
            };
797

            
798
            // Return container chain manager, or register container chain as ALICE if it does not exist
799
            if !ParaGenesisData::<T>::contains_key(para_id) {
800
                // Register as a new user
801

            
802
                /// Create a funded user.
803
                /// Used for generating the necessary amount for registering
804
                fn create_funded_user<T: Config>(
805
                    string: &'static str,
806
                    n: u32,
807
                    total: DepositBalanceOf<T>,
808
                ) -> (T::AccountId, DepositBalanceOf<T>) {
809
                    const SEED: u32 = 0;
810
                    let user = account(string, n, SEED);
811
                    assert_ok!(T::Currency::mint_into(&user, total));
812
                    (user, total)
813
                }
814

            
815
                let deposit = Self::get_genesis_cost(genesis_data.encoded_size());
816
                let new_balance = T::Currency::minimum_balance()
817
                    .saturating_mul(10_000_000u32.into())
818
                    .saturating_add(deposit);
819
                let account = create_funded_user::<T>("caller", 1000, new_balance).0;
820
                T::InnerRegistrar::prepare_chain_registration(*para_id, account.clone());
821
                let origin = RawOrigin::Signed(account);
822

            
823
                assert_ok!(Self::register(
824
                    origin.into(),
825
                    *para_id,
826
                    genesis_data.clone(),
827
                    T::InnerRegistrar::bench_head_data(),
828
                ));
829
            }
830

            
831
            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");
832

            
833
            let deposit = Self::get_genesis_cost(genesis_data.encoded_size());
834
            // Fund deposit creator, just in case it is not a new account
835
            let new_balance = (T::Currency::minimum_balance().saturating_add(deposit))
836
                .saturating_mul(2u32.into());
837
            assert_ok!(T::Currency::mint_into(&deposit_info.creator, new_balance));
838

            
839
            deposit_info.creator
840
        }
841

            
842
276
        pub fn get_genesis_cost(size: usize) -> <T::Currency as Inspect<T::AccountId>>::Balance {
843
276
            T::DataDepositPerByte::get().saturating_mul((size as u32).into())
844
276
        }
845

            
846
276
        fn do_register(
847
276
            account: T::AccountId,
848
276
            para_id: ParaId,
849
276
            genesis_data: ContainerChainGenesisData,
850
276
            head_data: Option<HeadData>,
851
276
        ) -> DispatchResult {
852
276
            // The actual registration takes place 2 sessions after the call to
853
276
            // `mark_valid_for_collating`, but the genesis data is inserted now.
854
276
            // This is because collators should be able to start syncing the new container chain
855
276
            // before the first block is mined. However, we could store the genesis data in a
856
276
            // different key, like PendingParaGenesisData.
857
276
            // TODO: for benchmarks, this call to .encoded_size is O(n) with respect to the number
858
276
            // of key-values in `genesis_data.storage`, even if those key-values are empty. And we
859
276
            // won't detect that the size is too big until after iterating over all of them, so the
860
276
            // limit in that case would be the transaction size.
861
276
            let genesis_data_size = genesis_data.encoded_size();
862
276

            
863
276
            let deposit = Self::get_genesis_cost(genesis_data_size);
864
276
            // Verify we can hold
865
276
            if !T::Currency::can_hold(&HoldReason::RegistrarDeposit.into(), &account, deposit) {
866
                return Err(Error::<T>::NotSufficientDeposit.into());
867
276
            }
868
276

            
869
276
            // Check if the para id is already registered by looking at the genesis data
870
276
            if ParaGenesisData::<T>::contains_key(para_id) {
871
11
                return Err(Error::<T>::ParaIdAlreadyRegistered.into());
872
265
            }
873
265

            
874
265
            // Check if the para id is already in PendingVerification (unreachable)
875
265
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
876
265
            if is_pending_verification {
877
                return Err(Error::<T>::ParaIdAlreadyRegistered.into());
878
265
            }
879
265

            
880
265
            // Insert para id into PendingVerification
881
265
            PendingVerification::<T>::insert(para_id, ());
882
265

            
883
265
            if genesis_data_size > T::MaxGenesisDataSize::get() as usize {
884
1
                return Err(Error::<T>::GenesisDataTooBig.into());
885
264
            }
886
264

            
887
264
            // Hold the deposit, we verified we can do this
888
264
            T::Currency::hold(&HoldReason::RegistrarDeposit.into(), &account, deposit)?;
889

            
890
            // Register the paraId also in the relay context (if any).
891
264
            T::InnerRegistrar::register(
892
264
                account.clone(),
893
264
                para_id,
894
264
                &genesis_data.storage,
895
264
                head_data,
896
264
            )?;
897

            
898
            // Update DepositInfo
899
260
            RegistrarDeposit::<T>::insert(
900
260
                para_id,
901
260
                DepositInfo {
902
260
                    creator: account.clone(),
903
260
                    deposit,
904
260
                },
905
260
            );
906
260
            ParaGenesisData::<T>::insert(para_id, genesis_data);
907
260

            
908
260
            ParaManager::<T>::insert(para_id, account);
909
260

            
910
260
            Ok(())
911
276
        }
912

            
913
119
        fn do_deregister(para_id: ParaId) -> DispatchResult {
914
119
            // Check if the para id is in "PendingVerification".
915
119
            // This is a special case because then we can remove it immediately, instead of waiting 2 sessions.
916
119
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
917
119
            if is_pending_verification {
918
15
                Self::deposit_event(Event::ParaIdDeregistered { para_id });
919
15
                // Cleanup immediately
920
15
                Self::cleanup_deregistered_para_id(para_id);
921
15
                BufferedParasToDeregister::<T>::try_mutate(|v| v.try_push(para_id)).map_err(
922
15
                    |_e| {
923
                        DispatchError::Other(
924
                            "Failed to add paraId to deregistration list: buffer is full",
925
                        )
926
15
                    },
927
15
                )?;
928
            } else {
929
104
                Self::schedule_paused_parachain_change(|para_ids, paused| {
930
104
                    // We have to find out where, in the sorted vec the para id is, if anywhere.
931
104

            
932
104
                    match para_ids.binary_search(&para_id) {
933
99
                        Ok(index) => {
934
99
                            para_ids.remove(index);
935
99
                        }
936
                        Err(_) => {
937
                            // If the para id is not registered, it may be paused. In that case, remove it from there
938
5
                            match paused.binary_search(&para_id) {
939
3
                                Ok(index) => {
940
3
                                    paused.remove(index);
941
3
                                }
942
                                Err(_) => {
943
2
                                    return Err(Error::<T>::ParaIdNotRegistered.into());
944
                                }
945
                            }
946
                        }
947
                    }
948

            
949
102
                    Ok(())
950
104
                })?;
951
                // Mark this para id for cleanup later
952
102
                Self::schedule_parachain_cleanup(para_id)?;
953

            
954
                // If we have InnerRegistrar set to a relay context (like Dancelight),
955
                // we first need to downgrade the paraId (if it was a parachain before)
956
                // and convert it to a parathread before deregistering it. Otherwise
957
                // the deregistration process will fail in the scheduled session.
958
                //
959
                // We only downgrade if the paraId is a parachain in the context of
960
                // this pallet.
961
102
                if ParathreadParams::<T>::get(para_id).is_none() {
962
100
                    T::InnerRegistrar::schedule_para_downgrade(para_id)?;
963
2
                }
964

            
965
102
                Self::deposit_event(Event::ParaIdDeregistered { para_id });
966
            }
967

            
968
117
            Ok(())
969
119
        }
970

            
971
185
        fn do_mark_valid_for_collating(para_id: ParaId) -> DispatchResult {
972
185
            let is_pending_verification = PendingVerification::<T>::take(para_id).is_some();
973
185
            if !is_pending_verification {
974
3
                return Err(Error::<T>::ParaIdNotInPendingVerification.into());
975
182
            }
976
182

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

            
982
182
                match para_ids.binary_search(&para_id) {
983
                    // This Ok is unreachable
984
                    Ok(_) => return Err(Error::<T>::ParaIdAlreadyRegistered.into()),
985
182
                    Err(index) => {
986
182
                        para_ids
987
182
                            .try_insert(index, para_id)
988
182
                            .map_err(|_e| Error::<T>::ParaIdListFull)?;
989
                    }
990
                }
991

            
992
182
                Ok(())
993
182
            })?;
994

            
995
182
            T::RegistrarHooks::check_valid_for_collating(para_id)?;
996

            
997
178
            Self::deposit_event(Event::ParaIdValidForCollating { para_id });
998
178

            
999
178
            T::RegistrarHooks::para_marked_valid_for_collating(para_id);
178

            
178
            // If we execute mark_valid_for_collating, we automatically upgrade
178
            // the paraId to a parachain (in the relay context) at the end of the execution.
178
            //
178
            // We only upgrade if the paraId is a parachain in the context of
178
            // this pallet.
178
            if ParathreadParams::<T>::get(para_id).is_none() {
138
                T::InnerRegistrar::schedule_para_upgrade(para_id)?;
40
            }
176
            Ok(())
185
        }
        /// Relay parachain manager signature message. Includes:
        /// * 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.
16
        pub fn relay_signature_msg(
16
            para_id: ParaId,
16
            tanssi_account: &T::AccountId,
16
            relay_storage_root: H256,
16
        ) -> Vec<u8> {
16
            (para_id, tanssi_account, relay_storage_root).encode()
16
        }
182
        fn schedule_parachain_change(
182
            updater: impl FnOnce(&mut BoundedVec<ParaId, T::MaxLengthParaIds>) -> DispatchResult,
182
        ) -> DispatchResult {
182
            let mut pending_paras = PendingParaIds::<T>::get();
182
            // First, we need to decide what we should use as the base paras.
182
            let mut base_paras = pending_paras
182
                .last()
182
                .map(|(_, paras)| paras.clone())
182
                .unwrap_or_else(Self::registered_para_ids);
182

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

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

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

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

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

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

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

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

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

            
18
                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",
                    );
18
                }
18
                let new_params = past_and_present.pop().map(|(_, params)| params);
18
                if let Some(ref new_params) = new_params {
17
                    for (para_id, params) in new_params {
8
                        <ParathreadParams<T>>::insert(para_id, params);
8
                    }
9
                    <PendingParathreadParams<T>>::put(future);
9
                }
4799
            }
4817
            let pending_to_remove = <PendingToRemove<T>>::get();
4817
            if !pending_to_remove.is_empty() {
169
                let (past_and_present, future) =
169
                    pending_to_remove.into_iter().partition::<Vec<_>, _>(
170
                        |&(apply_at_session, _)| apply_at_session <= *session_index,
169
                    );
169

            
169
                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.
85
                    let mut removed_para_ids = BTreeSet::new();
170
                    for (_, new_paras) in &past_and_present {
185
                        for para_id in new_paras {
100
                            Self::cleanup_deregistered_para_id(*para_id);
100
                            removed_para_ids.insert(*para_id);
                            if let Err(id) =
100
                                BufferedParasToDeregister::<T>::try_mutate(|v| v.try_push(*para_id))
                            {
                                log::error!(
                                    target: LOG_TARGET,
                                    "Failed to add paraId {:?} to deregistration list",
                                    id
                                );
100
                            }
                        }
                    }
                    // Also need to remove PendingParams to avoid setting params for a para id that does not exist
85
                    let mut pending_parathread_params = <PendingParathreadParams<T>>::get();
86
                    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
                    }
85
                    <PendingParathreadParams<T>>::put(pending_parathread_params);
85
                    <PendingToRemove<T>>::put(future);
84
                }
4648
            }
4817
            SessionChangeOutcome {
4817
                prev_paras,
4817
                new_paras,
4817
            }
4817
        }
        /// Remove all para id storage in this pallet,
        /// and execute para_deregistered hook to clean up other pallets as well
115
        fn cleanup_deregistered_para_id(para_id: ParaId) {
115
            ParaGenesisData::<T>::remove(para_id);
115
            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
115
            if let Some(asset_info) = RegistrarDeposit::<T>::take(para_id) {
38
                // Release hold
38
                let _ = T::Currency::release(
38
                    &HoldReason::RegistrarDeposit.into(),
38
                    &asset_info.creator,
38
                    asset_info.deposit,
38
                    Precision::Exact,
38
                );
96
            }
115
            ParaManager::<T>::remove(para_id);
115

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

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

            
102
            Ok(())
102
        }
65320
        pub fn registered_para_ids() -> BoundedVec<ParaId, T::MaxLengthParaIds> {
65320
            RegisteredParaIds::<T>::get()
65320
        }
31145
        pub fn pending_registered_para_ids(
31145
        ) -> Vec<(T::SessionIndex, BoundedVec<ParaId, T::MaxLengthParaIds>)> {
31145
            PendingParaIds::<T>::get()
31145
        }
97
        pub fn para_genesis_data(para_id: ParaId) -> Option<ContainerChainGenesisData> {
97
            ParaGenesisData::<T>::get(para_id)
97
        }
        pub fn pending_verification(para_id: ParaId) -> Option<()> {
            PendingVerification::<T>::get(para_id)
        }
139
        pub fn paused() -> BoundedVec<ParaId, T::MaxLengthParaIds> {
139
            Paused::<T>::get()
139
        }
        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()
        }
103
        pub fn parathread_params(para_id: ParaId) -> Option<ParathreadParamsTy> {
103
            ParathreadParams::<T>::get(para_id)
103
        }
        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;
34236
        fn current_container_chains() -> BoundedVec<ParaId, Self::MaxContainerChains> {
34236
            Self::registered_para_ids()
34236
        }
        #[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> {
31112
        fn session_container_chains(session_index: T::SessionIndex) -> SessionContainerChains {
31112
            let (past_and_present, _) = Pallet::<T>::pending_registered_para_ids()
31112
                .into_iter()
31112
                .partition::<Vec<_>, _>(|&(apply_at_session, _)| apply_at_session <= session_index);
31112
            let paras = if let Some(last) = past_and_present.last() {
353
                last.1.clone()
            } else {
30759
                Pallet::<T>::registered_para_ids()
            };
31112
            let mut parachains = vec![];
31112
            let mut parathreads = vec![];
88498
            for para_id in paras {
                // TODO: sweet O(n) db reads
57386
                if let Some(parathread_params) = ParathreadParams::<T>::get(para_id) {
1623
                    parathreads.push((para_id, parathread_params));
55931
                } else {
55763
                    parachains.push(para_id);
55763
                }
            }
31112
            SessionContainerChains {
31112
                parachains,
31112
                parathreads,
31112
            }
31112
        }
        #[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;
383
    fn try_origin(
383
        o: T::RuntimeOrigin,
383
        para_id: &ParaId,
383
    ) -> Result<Self::Success, T::RuntimeOrigin> {
223
        let signed_account =
383
            <frame_system::EnsureSigned<_> as EnsureOrigin<_>>::try_origin(o.clone())?;
223
        if !Pallet::<T>::is_para_manager(para_id, &signed_account) {
17
            return Err(frame_system::RawOrigin::Signed(signed_account).into());
206
        }
206

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