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
//! # Collator Assignment Pallet
18
//!
19
//! This pallet assigns a list of collators to:
20
//!    - the orchestrator chain
21
//!    - a set of container chains
22
//!
23
//! The set of container chains is retrieved thanks to the GetContainerChains trait
24
//! The number of collators to assign to the orchestrator chain and the number
25
//! of collators to assign to each container chain is retrieved through the GetHostConfiguration
26
//! trait.
27
//!  
28
//! The pallet uses the following approach:
29
//!
30
//! - First, it aims at filling the necessary collators to serve the orchestrator chain
31
//! - Second, it aims at filling in-order (FIFO) the existing containerChains
32
//!
33
//! Upon new session, this pallet takes whatever assignation was in the PendingCollatorContainerChain
34
//! storage, and assigns it as the current CollatorContainerChain. In addition, it takes the next
35
//! queued set of parachains and collators and calculates the assignment for the next session, storing
36
//! it in the PendingCollatorContainerChain storage item.
37
//!
38
//! The reason for the collator-assignment pallet to work with a one-session delay assignment is because
39
//! we want collators to know at least one session in advance the container chain/orchestrator that they
40
//! are assigned to.
41

            
42
#![cfg_attr(not(feature = "std"), no_std)]
43

            
44
use {
45
    crate::assignment::{Assignment, ChainNumCollators},
46
    core::ops::Mul,
47
    frame_support::{pallet_prelude::*, traits::Currency},
48
    frame_system::pallet_prelude::BlockNumberFor,
49
    rand::{seq::SliceRandom, SeedableRng},
50
    rand_chacha::ChaCha20Rng,
51
    sp_runtime::{
52
        traits::{AtLeast32BitUnsigned, One, Zero},
53
        Perbill, Saturating,
54
    },
55
    sp_std::{collections::btree_set::BTreeSet, fmt::Debug, prelude::*, vec},
56
    tp_traits::{
57
        CollatorAssignmentTip, ForSession, FullRotationModes, GetContainerChainAuthor,
58
        GetContainerChainsWithCollators, GetHostConfiguration, GetSessionContainerChains, ParaId,
59
        ParaIdAssignmentHooks, RemoveInvulnerables, ShouldRotateAllCollators, Slot,
60
    },
61
};
62
pub use {dp_collator_assignment::AssignedCollators, pallet::*};
63

            
64
mod assignment;
65
#[cfg(feature = "runtime-benchmarks")]
66
mod benchmarking;
67
pub mod weights;
68
pub use weights::WeightInfo;
69

            
70
#[cfg(test)]
71
mod mock;
72

            
73
#[cfg(test)]
74
mod tests;
75

            
76
#[derive(Encode, Decode, Debug, TypeInfo)]
77
pub struct CoreAllocationConfiguration {
78
    pub core_count: u32,
79
    pub max_parachain_percentage: Perbill,
80
}
81

            
82
5293
#[frame_support::pallet]
83
pub mod pallet {
84
    use super::*;
85

            
86
1184
    #[pallet::pallet]
87
    pub struct Pallet<T>(_);
88

            
89
    /// Configure the pallet by specifying the parameters and types on which it depends.
90
    #[pallet::config]
91
    pub trait Config: frame_system::Config {
92
        /// The overarching event type.
93
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
94
        type SessionIndex: parity_scale_codec::FullCodec
95
            + TypeInfo
96
            + Copy
97
            + AtLeast32BitUnsigned
98
            + Debug;
99
        // `SESSION_DELAY` is used to delay any changes to Paras registration or configurations.
100
        // Wait until the session index is 2 larger then the current index to apply any changes,
101
        // which guarantees that at least one full session has passed before any changes are applied.
102
        type HostConfiguration: GetHostConfiguration<Self::SessionIndex>;
103
        type ContainerChains: GetSessionContainerChains<Self::SessionIndex>;
104
        type SelfParaId: Get<ParaId>;
105
        type ShouldRotateAllCollators: ShouldRotateAllCollators<Self::SessionIndex>;
106
        type GetRandomnessForNextBlock: GetRandomnessForNextBlock<BlockNumberFor<Self>>;
107
        type RemoveInvulnerables: RemoveInvulnerables<Self::AccountId>;
108
        type ParaIdAssignmentHooks: ParaIdAssignmentHooks<BalanceOf<Self>, Self::AccountId>;
109
        type Currency: Currency<Self::AccountId>;
110
        type CollatorAssignmentTip: CollatorAssignmentTip<BalanceOf<Self>>;
111
        type ForceEmptyOrchestrator: Get<bool>;
112
        type CoreAllocationConfiguration: Get<Option<CoreAllocationConfiguration>>;
113
        /// The weight information of this pallet.
114
        type WeightInfo: WeightInfo;
115
    }
116

            
117
588
    #[pallet::event]
118
3289
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
119
    pub enum Event<T: Config> {
120
20
        NewPendingAssignment {
121
            random_seed: [u8; 32],
122
            full_rotation: bool,
123
            target_session: T::SessionIndex,
124
            full_rotation_mode: FullRotationModes,
125
        },
126
    }
127

            
128
200946
    #[pallet::storage]
129
    #[pallet::unbounded]
130
    pub(crate) type CollatorContainerChain<T: Config> =
131
        StorageValue<_, AssignedCollators<T::AccountId>, ValueQuery>;
132

            
133
    /// Pending configuration changes.
134
    ///
135
    /// This is a list of configuration changes, each with a session index at which it should
136
    /// be applied.
137
    ///
138
    /// The list is sorted ascending by session index. Also, this list can only contain at most
139
    /// 2 items: for the next session and for the `scheduled_session`.
140
16580
    #[pallet::storage]
141
    #[pallet::unbounded]
142
    pub(crate) type PendingCollatorContainerChain<T: Config> =
143
        StorageValue<_, Option<AssignedCollators<T::AccountId>>, ValueQuery>;
144

            
145
    /// Randomness from previous block. Used to shuffle collators on session change.
146
    /// Should only be set on the last block of each session and should be killed on the on_initialize of the next block.
147
    /// The default value of [0; 32] disables randomness in the pallet.
148
12682
    #[pallet::storage]
149
    pub(crate) type Randomness<T: Config> = StorageValue<_, [u8; 32], ValueQuery>;
150

            
151
    /// Ratio of assigned collators to max collators.
152
7166
    #[pallet::storage]
153
    pub type CollatorFullnessRatio<T: Config> = StorageValue<_, Perbill, OptionQuery>;
154

            
155
588
    #[pallet::call]
156
    impl<T: Config> Pallet<T> {}
157

            
158
    /// A struct that holds the assignment that is active after the session change and optionally
159
    /// the assignment that becomes active after the next session change.
160
    pub struct SessionChangeOutcome<T: Config> {
161
        /// New active assignment.
162
        pub active_assignment: AssignedCollators<T::AccountId>,
163
        /// Next session active assignment.
164
        pub next_assignment: AssignedCollators<T::AccountId>,
165
        /// Total number of registered parachains before filtering them out, used as a weight hint
166
        pub num_total_registered_paras: u32,
167
    }
168

            
169
    impl<T: Config> Pallet<T> {
170
3297
        pub(crate) fn enough_collators_for_all_chains(
171
3297
            bulk_paras: &Vec<ChainNumCollators>,
172
3297
            pool_paras: &Vec<ChainNumCollators>,
173
3297
            target_session_index: T::SessionIndex,
174
3297
            number_of_collators: u32,
175
3297
            collators_per_container: u32,
176
3297
            collators_per_parathread: u32,
177
3297
        ) -> bool {
178
3297
            number_of_collators
179
3297
                >= T::HostConfiguration::min_collators_for_orchestrator(target_session_index)
180
3297
                    .saturating_add(collators_per_container.saturating_mul(bulk_paras.len() as u32))
181
3297
                    .saturating_add(
182
3297
                        collators_per_parathread.saturating_mul(pool_paras.len() as u32),
183
3297
                    )
184
3297
        }
185

            
186
        /// Takes the bulk paras (parachains) and pool paras (parathreads)
187
        /// and checks if we if a) Do we have enough collators? b) Do we have enough cores?
188
        /// If either of the answer is yes. We  separately sort bulk_paras and pool_paras and
189
        /// then append the two vectors.
190
506
        pub(crate) fn order_paras_with_core_config(
191
506
            mut bulk_paras: Vec<ChainNumCollators>,
192
506
            mut pool_paras: Vec<ChainNumCollators>,
193
506
            core_allocation_configuration: &CoreAllocationConfiguration,
194
506
            target_session_index: T::SessionIndex,
195
506
            number_of_collators: u32,
196
506
            collators_per_container: u32,
197
506
            collators_per_parathread: u32,
198
506
        ) -> (Vec<ChainNumCollators>, bool) {
199
506
            let core_count = core_allocation_configuration.core_count;
200
506
            let max_number_of_bulk_paras = core_allocation_configuration
201
506
                .max_parachain_percentage
202
506
                .mul(core_count);
203
506

            
204
506
            let enough_cores_for_bulk_paras = bulk_paras.len() <= max_number_of_bulk_paras as usize;
205
506

            
206
506
            let enough_collators = Self::enough_collators_for_all_chains(
207
506
                &bulk_paras,
208
506
                &pool_paras,
209
506
                target_session_index,
210
506
                number_of_collators,
211
506
                collators_per_container,
212
506
                collators_per_parathread,
213
506
            );
214

            
215
            // We should charge tip if parachain demand exceeds the `max_number_of_bulk_paras` OR
216
            // if `num_collators` is not enough to satisfy  collation need of all paras.
217
506
            let should_charge_tip = !enough_cores_for_bulk_paras || !enough_collators;
218

            
219
            // Currently, we are sorting both bulk and pool paras by tip, even when for example
220
            // only number of bulk paras are restricted due to core availability since we deduct tip from
221
            // all paras.
222
            // We need to sort both separately as we have fixed space for parachains at the moment
223
            // which means even when we have some parathread cores empty we cannot schedule parachain there.
224
506
            if should_charge_tip {
225
397
                bulk_paras.sort_by(|a, b| {
226
250
                    T::CollatorAssignmentTip::get_para_tip(b.para_id)
227
250
                        .cmp(&T::CollatorAssignmentTip::get_para_tip(a.para_id))
228
397
                });
229
340

            
230
369
                pool_paras.sort_by(|a, b| {
231
71
                    T::CollatorAssignmentTip::get_para_tip(b.para_id)
232
71
                        .cmp(&T::CollatorAssignmentTip::get_para_tip(a.para_id))
233
369
                });
234
340
            }
235

            
236
506
            bulk_paras.truncate(max_number_of_bulk_paras as usize);
237
506
            // We are not truncating pool paras, since their workload is not continuous one core
238
506
            // can be shared by many paras during the session.
239
506

            
240
506
            let chains: Vec<_> = bulk_paras.into_iter().chain(pool_paras).collect();
241
506

            
242
506
            (chains, should_charge_tip)
243
506
        }
244

            
245
2791
        pub(crate) fn order_paras(
246
2791
            bulk_paras: Vec<ChainNumCollators>,
247
2791
            pool_paras: Vec<ChainNumCollators>,
248
2791
            target_session_index: T::SessionIndex,
249
2791
            number_of_collators: u32,
250
2791
            collators_per_container: u32,
251
2791
            collators_per_parathread: u32,
252
2791
        ) -> (Vec<ChainNumCollators>, bool) {
253
2791
            // Are there enough collators to satisfy the minimum demand?
254
2791
            let enough_collators_for_all_chain = Self::enough_collators_for_all_chains(
255
2791
                &bulk_paras,
256
2791
                &pool_paras,
257
2791
                target_session_index,
258
2791
                number_of_collators,
259
2791
                collators_per_container,
260
2791
                collators_per_parathread,
261
2791
            );
262
2791

            
263
2791
            let mut chains: Vec<_> = bulk_paras.into_iter().chain(pool_paras).collect();
264
2791

            
265
2791
            // Prioritize paras by tip on congestion
266
2791
            // As of now this doesn't distinguish between bulk paras and pool paras
267
2791
            if !enough_collators_for_all_chain {
268
2060
                chains.sort_by(|a, b| {
269
2060
                    T::CollatorAssignmentTip::get_para_tip(b.para_id)
270
2060
                        .cmp(&T::CollatorAssignmentTip::get_para_tip(a.para_id))
271
2060
                });
272
2071
            }
273

            
274
2791
            (chains, !enough_collators_for_all_chain)
275
2791
        }
276

            
277
        /// Assign new collators
278
        /// collators should be queued collators
279
3289
        pub fn assign_collators(
280
3289
            current_session_index: &T::SessionIndex,
281
3289
            random_seed: [u8; 32],
282
3289
            collators: Vec<T::AccountId>,
283
3289
        ) -> SessionChangeOutcome<T> {
284
3289
            let maybe_core_allocation_configuration = T::CoreAllocationConfiguration::get();
285
3289
            // We work with one session delay to calculate assignments
286
3289
            let session_delay = T::SessionIndex::one();
287
3289
            let target_session_index = current_session_index.saturating_add(session_delay);
288
3289

            
289
3289
            let collators_per_container =
290
3289
                T::HostConfiguration::collators_per_container(target_session_index);
291
3289
            let collators_per_parathread =
292
3289
                T::HostConfiguration::collators_per_parathread(target_session_index);
293
3289

            
294
3289
            // We get the containerChains that we will have at the target session
295
3289
            let container_chains =
296
3289
                T::ContainerChains::session_container_chains(target_session_index);
297
3289
            let num_total_registered_paras =
298
3289
                (container_chains.parachains.len() + container_chains.parathreads.len()) as u32;
299
3289
            let mut container_chain_ids = container_chains.parachains;
300
3289
            let mut parathreads: Vec<_> = container_chains
301
3289
                .parathreads
302
3289
                .into_iter()
303
3289
                .map(|(para_id, _)| para_id)
304
3289
                .collect();
305
3289

            
306
3289
            // We read current assigned collators
307
3289
            let old_assigned = Self::read_assigned_collators();
308
3289
            let old_assigned_para_ids: BTreeSet<ParaId> =
309
3289
                old_assigned.container_chains.keys().cloned().collect();
310
3289

            
311
3289
            // Remove the containerChains that do not have enough credits for block production
312
3289
            T::ParaIdAssignmentHooks::pre_assignment(
313
3289
                &mut container_chain_ids,
314
3289
                &old_assigned_para_ids,
315
3289
            );
316
3289
            // TODO: parathreads should be treated a bit differently, they don't need to have the same amount of credits
317
3289
            // as parathreads because they will not be producing blocks on every slot.
318
3289
            T::ParaIdAssignmentHooks::pre_assignment(&mut parathreads, &old_assigned_para_ids);
319
3289

            
320
3289
            let mut shuffle_collators = None;
321
3289
            // If the random_seed is all zeros, we don't shuffle the list of collators nor the list
322
3289
            // of container chains.
323
3289
            // This should only happen in tests_without_core_config, and in the genesis block.
324
3289
            if random_seed != [0; 32] {
325
119
                let mut rng: ChaCha20Rng = SeedableRng::from_seed(random_seed);
326
119
                container_chain_ids.shuffle(&mut rng);
327
119
                parathreads.shuffle(&mut rng);
328
215
                shuffle_collators = Some(move |collators: &mut Vec<T::AccountId>| {
329
215
                    collators.shuffle(&mut rng);
330
215
                })
331
3170
            }
332

            
333
3289
            let orchestrator_chain: ChainNumCollators = if T::ForceEmptyOrchestrator::get() {
334
498
                ChainNumCollators {
335
498
                    para_id: T::SelfParaId::get(),
336
498
                    min_collators: 0u32,
337
498
                    max_collators: 0u32,
338
498
                    parathread: false,
339
498
                }
340
            } else {
341
2791
                ChainNumCollators {
342
2791
                    para_id: T::SelfParaId::get(),
343
2791
                    min_collators: T::HostConfiguration::min_collators_for_orchestrator(
344
2791
                        target_session_index,
345
2791
                    ),
346
2791
                    max_collators: T::HostConfiguration::max_collators_for_orchestrator(
347
2791
                        target_session_index,
348
2791
                    ),
349
2791
                    parathread: false,
350
2791
                }
351
            };
352

            
353
            // Initialize list of chains as `[container1, container2, parathread1, parathread2]`.
354
            // The order means priority: the first chain in the list will be the first one to get assigned collators.
355
            // Chains will not be assigned less than `min_collators`, except the orchestrator chain.
356
            // First all chains will be assigned `min_collators`, and then the first one will be assigned up to `max`,
357
            // then the second one, and so on.
358
3289
            let mut bulk_paras = vec![];
359
3289
            let mut pool_paras = vec![];
360

            
361
8170
            for para_id in &container_chain_ids {
362
4881
                bulk_paras.push(ChainNumCollators {
363
4881
                    para_id: *para_id,
364
4881
                    min_collators: collators_per_container,
365
4881
                    max_collators: collators_per_container,
366
4881
                    parathread: false,
367
4881
                });
368
4881
            }
369
3619
            for para_id in &parathreads {
370
330
                pool_paras.push(ChainNumCollators {
371
330
                    para_id: *para_id,
372
330
                    min_collators: collators_per_parathread,
373
330
                    max_collators: collators_per_parathread,
374
330
                    parathread: true,
375
330
                });
376
330
            }
377

            
378
3289
            let (chains, need_to_charge_tip) =
379
3289
                if let Some(core_allocation_configuration) = maybe_core_allocation_configuration {
380
498
                    Self::order_paras_with_core_config(
381
498
                        bulk_paras,
382
498
                        pool_paras,
383
498
                        &core_allocation_configuration,
384
498
                        target_session_index,
385
498
                        collators.len() as u32,
386
498
                        collators_per_container,
387
498
                        collators_per_parathread,
388
498
                    )
389
                } else {
390
2791
                    Self::order_paras(
391
2791
                        bulk_paras,
392
2791
                        pool_paras,
393
2791
                        target_session_index,
394
2791
                        collators.len() as u32,
395
2791
                        collators_per_container,
396
2791
                        collators_per_parathread,
397
2791
                    )
398
                };
399

            
400
            // We assign new collators
401
            // we use the config scheduled at the target_session_index
402
3289
            let full_rotation =
403
3289
                T::ShouldRotateAllCollators::should_rotate_all_collators(target_session_index);
404
3289
            if full_rotation {
405
375
                log::info!(
406
342
                    "Collator assignment: rotating collators. Session {:?}, Seed: {:?}",
407
342
                    current_session_index.encode(),
408
                    random_seed
409
                );
410
            } else {
411
2914
                log::info!(
412
1734
                    "Collator assignment: keep old assigned. Session {:?}, Seed: {:?}",
413
1734
                    current_session_index.encode(),
414
                    random_seed
415
                );
416
            }
417

            
418
3289
            let full_rotation_mode = if full_rotation {
419
375
                T::HostConfiguration::full_rotation_mode(target_session_index)
420
            } else {
421
                // On sessions where there is no rotation, we try to keep all collators assigned to the same chains
422
2914
                FullRotationModes::keep_all()
423
            };
424

            
425
3289
            Self::deposit_event(Event::NewPendingAssignment {
426
3289
                random_seed,
427
3289
                full_rotation,
428
3289
                target_session: target_session_index,
429
3289
                full_rotation_mode: full_rotation_mode.clone(),
430
3289
            });
431
3289

            
432
3289
            let new_assigned = Assignment::<T>::assign_collators_always_keep_old(
433
3289
                collators,
434
3289
                orchestrator_chain,
435
3289
                chains,
436
3289
                old_assigned.clone(),
437
3289
                shuffle_collators,
438
3289
                full_rotation_mode,
439
3289
            );
440

            
441
3289
            let mut new_assigned = match new_assigned {
442
3285
                Ok(x) => x,
443
4
                Err(e) => {
444
4
                    log::error!(
445
4
                        "Error in collator assignment, will keep previous assignment. {:?}",
446
                        e
447
                    );
448

            
449
4
                    old_assigned.clone()
450
                }
451
            };
452

            
453
3289
            let mut assigned_containers = new_assigned.container_chains.clone();
454
5271
            assigned_containers.retain(|_, v| !v.is_empty());
455

            
456
            // On congestion, prioritized chains need to pay the minimum tip of the prioritized chains
457
3289
            let maybe_tip: Option<BalanceOf<T>> = if !need_to_charge_tip {
458
1000
                None
459
            } else {
460
2289
                assigned_containers
461
2289
                    .into_keys()
462
2289
                    .filter_map(T::CollatorAssignmentTip::get_para_tip)
463
2289
                    .min()
464
            };
465

            
466
            // TODO: this probably is asking for a refactor
467
            // only apply the onCollatorAssignedHook if sufficient collators
468
3289
            T::ParaIdAssignmentHooks::post_assignment(
469
3289
                &old_assigned_para_ids,
470
3289
                &mut new_assigned.container_chains,
471
3289
                &maybe_tip,
472
3289
            );
473
3289

            
474
3289
            Self::store_collator_fullness(
475
3289
                &new_assigned,
476
3289
                T::HostConfiguration::max_collators(target_session_index),
477
3289
            );
478
3289

            
479
3289
            let mut pending = PendingCollatorContainerChain::<T>::get();
480
3289

            
481
3289
            let old_assigned_changed = old_assigned != new_assigned;
482
3289
            let mut pending_changed = false;
483
            // Update CollatorContainerChain using last entry of pending, if needed
484
3289
            if let Some(current) = pending.take() {
485
888
                pending_changed = true;
486
888
                CollatorContainerChain::<T>::put(current);
487
2427
            }
488
3289
            if old_assigned_changed {
489
829
                pending = Some(new_assigned.clone());
490
829
                pending_changed = true;
491
2649
            }
492
            // Update PendingCollatorContainerChain, if it changed
493
3289
            if pending_changed {
494
1391
                PendingCollatorContainerChain::<T>::put(pending);
495
2381
            }
496

            
497
            // Only applies to session index 0
498
3289
            if current_session_index == &T::SessionIndex::zero() {
499
450
                CollatorContainerChain::<T>::put(new_assigned.clone());
500
450
                return SessionChangeOutcome {
501
450
                    active_assignment: new_assigned.clone(),
502
450
                    next_assignment: new_assigned,
503
450
                    num_total_registered_paras,
504
450
                };
505
2839
            }
506
2839

            
507
2839
            SessionChangeOutcome {
508
2839
                active_assignment: old_assigned,
509
2839
                next_assignment: new_assigned,
510
2839
                num_total_registered_paras,
511
2839
            }
512
3289
        }
513

            
514
        /// Count number of collators assigned to any chain, divide that by `max_collators` and store
515
        /// in pallet storage.
516
3289
        fn store_collator_fullness(
517
3289
            new_assigned: &AssignedCollators<T::AccountId>,
518
3289
            max_collators: u32,
519
3289
        ) {
520
3289
            // Count number of assigned collators
521
3289
            let mut num_collators = 0;
522
3289
            num_collators += new_assigned.orchestrator_chain.len();
523
8484
            for (_para_id, collators) in &new_assigned.container_chains {
524
5195
                num_collators += collators.len();
525
5195
            }
526

            
527
3289
            let mut num_collators = num_collators as u32;
528
3289
            if num_collators > max_collators {
529
148
                // Shouldn't happen but just in case
530
148
                num_collators = max_collators;
531
3289
            }
532

            
533
3289
            let ratio = Perbill::from_rational(num_collators, max_collators);
534
3289

            
535
3289
            CollatorFullnessRatio::<T>::put(ratio);
536
3289
        }
537

            
538
        // Returns the assigned collators as read from storage.
539
        // If there is any item in PendingCollatorContainerChain, returns that element.
540
        // Otherwise, reads and returns the current CollatorContainerChain
541
3289
        fn read_assigned_collators() -> AssignedCollators<T::AccountId> {
542
3289
            let mut pending_collator_list = PendingCollatorContainerChain::<T>::get();
543

            
544
3289
            if let Some(assigned_collators) = pending_collator_list.take() {
545
888
                assigned_collators
546
            } else {
547
                // Read current
548
2401
                CollatorContainerChain::<T>::get()
549
            }
550
3289
        }
551

            
552
3289
        pub fn initializer_on_new_session(
553
3289
            session_index: &T::SessionIndex,
554
3289
            collators: Vec<T::AccountId>,
555
3289
        ) -> SessionChangeOutcome<T> {
556
3289
            let random_seed = Randomness::<T>::take();
557
3289
            let num_collators = collators.len();
558
3289
            let assigned_collators = Self::assign_collators(session_index, random_seed, collators);
559
3289
            let num_total_registered_paras = assigned_collators.num_total_registered_paras;
560
3289

            
561
3289
            frame_system::Pallet::<T>::register_extra_weight_unchecked(
562
3289
                T::WeightInfo::new_session(num_collators as u32, num_total_registered_paras),
563
3289
                DispatchClass::Mandatory,
564
3289
            );
565
3289

            
566
3289
            assigned_collators
567
3289
        }
568

            
569
74476
        pub fn collator_container_chain() -> AssignedCollators<T::AccountId> {
570
74476
            CollatorContainerChain::<T>::get()
571
74476
        }
572

            
573
25
        pub fn pending_collator_container_chain() -> Option<AssignedCollators<T::AccountId>> {
574
25
            PendingCollatorContainerChain::<T>::get()
575
25
        }
576

            
577
1
        pub fn randomness() -> [u8; 32] {
578
1
            Randomness::<T>::get()
579
1
        }
580
    }
581

            
582
    impl<T: Config> GetContainerChainAuthor<T::AccountId> for Pallet<T> {
583
        // TODO: pending collator container chain if the block is a session change!
584
71658
        fn author_for_slot(slot: Slot, para_id: ParaId) -> Option<T::AccountId> {
585
71658
            let assigned_collators = Pallet::<T>::collator_container_chain();
586
71658
            let collators = if para_id == T::SelfParaId::get() {
587
50222
                Some(&assigned_collators.orchestrator_chain)
588
            } else {
589
21436
                assigned_collators.container_chains.get(&para_id)
590
            }?;
591

            
592
71658
            if collators.is_empty() {
593
                // Avoid division by zero below
594
                return None;
595
71658
            }
596
71658
            let author_index = u64::from(slot) % collators.len() as u64;
597
71658
            collators.get(author_index as usize).cloned()
598
71658
        }
599

            
600
        #[cfg(feature = "runtime-benchmarks")]
601
        fn set_authors_for_para_id(para_id: ParaId, authors: Vec<T::AccountId>) {
602
            let mut assigned_collators = Pallet::<T>::collator_container_chain();
603
            assigned_collators.container_chains.insert(para_id, authors);
604
            CollatorContainerChain::<T>::put(assigned_collators);
605
        }
606
    }
607

            
608
57059
    #[pallet::hooks]
609
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
610
29326
        fn on_initialize(n: BlockNumberFor<T>) -> Weight {
611
29326
            let mut weight = Weight::zero();
612
29326

            
613
29326
            // Account reads and writes for on_finalize
614
29326
            if T::GetRandomnessForNextBlock::should_end_session(n.saturating_add(One::one())) {
615
2760
                weight += T::DbWeight::get().reads_writes(1, 1);
616
26566
            }
617

            
618
29326
            weight
619
29326
        }
620

            
621
28991
        fn on_finalize(n: BlockNumberFor<T>) {
622
28991
            // If the next block is a session change, read randomness and store in pallet storage
623
28991
            if T::GetRandomnessForNextBlock::should_end_session(n.saturating_add(One::one())) {
624
2757
                let random_seed = T::GetRandomnessForNextBlock::get_randomness();
625
2757
                Randomness::<T>::put(random_seed);
626
26234
            }
627
28991
        }
628
    }
629

            
630
    impl<T: Config> GetContainerChainsWithCollators<T::AccountId> for Pallet<T> {
631
21846
        fn container_chains_with_collators(
632
21846
            for_session: ForSession,
633
21846
        ) -> Vec<(ParaId, Vec<T::AccountId>)> {
634
21846
            // If next session has None then current session data will stay.
635
21846
            let chains = (for_session == ForSession::Next)
636
21846
                .then(|| PendingCollatorContainerChain::<T>::get())
637
21846
                .flatten()
638
21846
                .unwrap_or_else(|| CollatorContainerChain::<T>::get());
639
21846

            
640
21846
            chains.container_chains.into_iter().collect()
641
21846
        }
642

            
643
        #[cfg(feature = "runtime-benchmarks")]
644
        fn set_container_chains_with_collators(
645
            for_session: ForSession,
646
            container_chains: &[(ParaId, Vec<T::AccountId>)],
647
        ) {
648
            match for_session {
649
                ForSession::Current => {
650
                    let mut collators = CollatorContainerChain::<T>::get();
651
                    collators.container_chains = container_chains.iter().cloned().collect();
652
                    CollatorContainerChain::<T>::put(collators);
653
                }
654
                ForSession::Next => {
655
                    let mut collators =
656
                        PendingCollatorContainerChain::<T>::get().unwrap_or_default();
657
                    collators.container_chains = container_chains.iter().cloned().collect();
658
                    PendingCollatorContainerChain::<T>::put(Some(collators));
659
                }
660
            }
661
        }
662
    }
663
}
664

            
665
/// Balance used by this pallet
666
pub type BalanceOf<T> =
667
    <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
668

            
669
pub struct RotateCollatorsEveryNSessions<Period>(PhantomData<Period>);
670

            
671
impl<Period> ShouldRotateAllCollators<u32> for RotateCollatorsEveryNSessions<Period>
672
where
673
    Period: Get<u32>,
674
{
675
3125
    fn should_rotate_all_collators(session_index: u32) -> bool {
676
3125
        let period = Period::get();
677
3125

            
678
3125
        if period == 0 {
679
            // A period of 0 disables rotation
680
532
            false
681
        } else {
682
2593
            session_index % Period::get() == 0
683
        }
684
3125
    }
685
}
686

            
687
pub trait GetRandomnessForNextBlock<BlockNumber> {
688
    fn should_end_session(block_number: BlockNumber) -> bool;
689
    fn get_randomness() -> [u8; 32];
690
}
691

            
692
impl<BlockNumber> GetRandomnessForNextBlock<BlockNumber> for () {
693
2041
    fn should_end_session(_block_number: BlockNumber) -> bool {
694
2041
        false
695
2041
    }
696

            
697
    fn get_randomness() -> [u8; 32] {
698
        [0; 32]
699
    }
700
}