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
5510
#[frame_support::pallet]
83
pub mod pallet {
84
    use super::*;
85

            
86
2770
    #[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
612
    #[pallet::event]
118
4806
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
119
    pub enum Event<T: Config> {
120
29
        NewPendingAssignment {
121
            random_seed: [u8; 32],
122
            full_rotation: bool,
123
            target_session: T::SessionIndex,
124
            full_rotation_mode: FullRotationModes,
125
        },
126
    }
127

            
128
292418
    #[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
24426
    #[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
16770
    #[pallet::storage]
149
    pub(crate) type Randomness<T: Config> = StorageValue<_, [u8; 32], ValueQuery>;
150

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

            
155
612
    #[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
4814
        pub(crate) fn enough_collators_for_all_chains(
171
4814
            bulk_paras: &Vec<ChainNumCollators>,
172
4814
            pool_paras: &Vec<ChainNumCollators>,
173
4814
            target_session_index: T::SessionIndex,
174
4814
            number_of_collators: u32,
175
4814
            collators_per_container: u32,
176
4814
            collators_per_parathread: u32,
177
4814
        ) -> bool {
178
4814
            number_of_collators
179
4814
                >= T::HostConfiguration::min_collators_for_orchestrator(target_session_index)
180
4814
                    .saturating_add(collators_per_container.saturating_mul(bulk_paras.len() as u32))
181
4814
                    .saturating_add(
182
4814
                        collators_per_parathread.saturating_mul(pool_paras.len() as u32),
183
4814
                    )
184
4814
        }
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
1168
        pub(crate) fn order_paras_with_core_config(
191
1168
            mut bulk_paras: Vec<ChainNumCollators>,
192
1168
            mut pool_paras: Vec<ChainNumCollators>,
193
1168
            core_allocation_configuration: &CoreAllocationConfiguration,
194
1168
            target_session_index: T::SessionIndex,
195
1168
            number_of_collators: u32,
196
1168
            collators_per_container: u32,
197
1168
            collators_per_parathread: u32,
198
1168
        ) -> (Vec<ChainNumCollators>, bool) {
199
1168
            let core_count = core_allocation_configuration.core_count;
200
1168
            let max_number_of_bulk_paras = core_allocation_configuration
201
1168
                .max_parachain_percentage
202
1168
                .mul(core_count);
203
1168

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

            
206
1168
            let enough_collators = Self::enough_collators_for_all_chains(
207
1168
                &bulk_paras,
208
1168
                &pool_paras,
209
1168
                target_session_index,
210
1168
                number_of_collators,
211
1168
                collators_per_container,
212
1168
                collators_per_parathread,
213
1168
            );
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
1168
            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
1168
            if should_charge_tip {
225
892
                bulk_paras.sort_by(|a, b| {
226
443
                    T::CollatorAssignmentTip::get_para_tip(b.para_id)
227
443
                        .cmp(&T::CollatorAssignmentTip::get_para_tip(a.para_id))
228
892
                });
229
835

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

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

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

            
242
1168
            (chains, should_charge_tip)
243
1168
        }
244

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

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

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

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

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

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

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

            
309
4806
            // We read current assigned collators
310
4806
            let old_assigned = Self::read_assigned_collators();
311
4806
            let old_assigned_para_ids: BTreeSet<ParaId> =
312
4806
                old_assigned.container_chains.keys().cloned().collect();
313
4806

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

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

            
336
4806
            let orchestrator_chain: ChainNumCollators = if T::ForceEmptyOrchestrator::get() {
337
1160
                ChainNumCollators {
338
1160
                    para_id: T::SelfParaId::get(),
339
1160
                    min_collators: 0u32,
340
1160
                    max_collators: 0u32,
341
1160
                    parathread: false,
342
1160
                }
343
            } else {
344
3646
                ChainNumCollators {
345
3646
                    para_id: T::SelfParaId::get(),
346
3646
                    min_collators: T::HostConfiguration::min_collators_for_orchestrator(
347
3646
                        target_session_index,
348
3646
                    ),
349
3646
                    max_collators: T::HostConfiguration::max_collators_for_orchestrator(
350
3646
                        target_session_index,
351
3646
                    ),
352
3646
                    parathread: false,
353
3646
                }
354
            };
355

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

            
364
10404
            for para_id in &container_chain_ids {
365
5598
                bulk_paras.push(ChainNumCollators {
366
5598
                    para_id: *para_id,
367
5598
                    min_collators: collators_per_container,
368
5598
                    max_collators: collators_per_container,
369
5598
                    parathread: false,
370
5598
                });
371
5598
            }
372
5333
            for para_id in &parathreads {
373
527
                pool_paras.push(ChainNumCollators {
374
527
                    para_id: *para_id,
375
527
                    min_collators: collators_per_parathread,
376
527
                    max_collators: collators_per_parathread,
377
527
                    parathread: true,
378
527
                });
379
527
            }
380

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

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

            
421
4806
            let full_rotation_mode = if full_rotation {
422
400
                T::HostConfiguration::full_rotation_mode(target_session_index)
423
            } else {
424
                // On sessions where there is no rotation, we try to keep all collators assigned to the same chains
425
4406
                FullRotationModes::keep_all()
426
            };
427

            
428
4806
            Self::deposit_event(Event::NewPendingAssignment {
429
4806
                random_seed,
430
4806
                full_rotation,
431
4806
                target_session: target_session_index,
432
4806
                full_rotation_mode: full_rotation_mode.clone(),
433
4806
            });
434
4806

            
435
4806
            let new_assigned = Assignment::<T>::assign_collators_always_keep_old(
436
4806
                collators,
437
4806
                orchestrator_chain,
438
4806
                chains,
439
4806
                old_assigned.clone(),
440
4806
                shuffle_collators,
441
4806
                full_rotation_mode,
442
4806
            );
443

            
444
4806
            let mut new_assigned = match new_assigned {
445
4802
                Ok(x) => x,
446
4
                Err(e) => {
447
4
                    log::error!(
448
4
                        "Error in collator assignment, will keep previous assignment. {:?}",
449
                        e
450
                    );
451

            
452
4
                    old_assigned.clone()
453
                }
454
            };
455

            
456
4806
            let mut assigned_containers = new_assigned.container_chains.clone();
457
7009
            assigned_containers.retain(|_, v| !v.is_empty());
458

            
459
            // On congestion, prioritized chains need to pay the minimum tip of the prioritized chains
460
4806
            let maybe_tip: Option<BalanceOf<T>> = if !need_to_charge_tip {
461
1924
                None
462
            } else {
463
2882
                assigned_containers
464
2882
                    .into_keys()
465
2882
                    .filter_map(T::CollatorAssignmentTip::get_para_tip)
466
2882
                    .min()
467
            };
468

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

            
477
4806
            Self::store_collator_fullness(
478
4806
                &new_assigned,
479
4806
                T::HostConfiguration::max_collators(target_session_index),
480
4806
            );
481
4806

            
482
4806
            let mut pending = PendingCollatorContainerChain::<T>::get();
483
4806

            
484
4806
            let old_assigned_changed = old_assigned != new_assigned;
485
4806
            let mut pending_changed = false;
486
            // Update CollatorContainerChain using last entry of pending, if needed
487
4806
            if let Some(current) = pending.take() {
488
1134
                pending_changed = true;
489
1134
                CollatorContainerChain::<T>::put(current);
490
3698
            }
491
4806
            if old_assigned_changed {
492
1551
                pending = Some(new_assigned.clone());
493
1551
                pending_changed = true;
494
3968
            }
495
            // Update PendingCollatorContainerChain, if it changed
496
4806
            if pending_changed {
497
2263
                PendingCollatorContainerChain::<T>::put(pending);
498
3697
            }
499

            
500
            // Only applies to session index 0
501
4806
            if current_session_index == &T::SessionIndex::zero() {
502
1309
                CollatorContainerChain::<T>::put(new_assigned.clone());
503
1309
                return SessionChangeOutcome {
504
1309
                    active_assignment: new_assigned.clone(),
505
1309
                    next_assignment: new_assigned,
506
1309
                    num_total_registered_paras,
507
1309
                };
508
3497
            }
509
3497

            
510
3497
            SessionChangeOutcome {
511
3497
                active_assignment: old_assigned,
512
3497
                next_assignment: new_assigned,
513
3497
                num_total_registered_paras,
514
3497
            }
515
4806
        }
516

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

            
530
4806
            let mut num_collators = num_collators as u32;
531
4806
            if num_collators > max_collators {
532
148
                // Shouldn't happen but just in case
533
148
                num_collators = max_collators;
534
4806
            }
535

            
536
4806
            let ratio = Perbill::from_rational(num_collators, max_collators);
537
4806

            
538
4806
            CollatorFullnessRatio::<T>::put(ratio);
539
4806
        }
540

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

            
547
4806
            if let Some(assigned_collators) = pending_collator_list.take() {
548
1134
                assigned_collators
549
            } else {
550
                // Read current
551
3672
                CollatorContainerChain::<T>::get()
552
            }
553
4806
        }
554

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

            
564
4806
            frame_system::Pallet::<T>::register_extra_weight_unchecked(
565
4806
                T::WeightInfo::new_session(num_collators as u32, num_total_registered_paras),
566
4806
                DispatchClass::Mandatory,
567
4806
            );
568
4806

            
569
4806
            assigned_collators
570
4806
        }
571

            
572
113332
        pub fn collator_container_chain() -> AssignedCollators<T::AccountId> {
573
113332
            CollatorContainerChain::<T>::get()
574
113332
        }
575

            
576
30
        pub fn pending_collator_container_chain() -> Option<AssignedCollators<T::AccountId>> {
577
30
            PendingCollatorContainerChain::<T>::get()
578
30
        }
579

            
580
2
        pub fn randomness() -> [u8; 32] {
581
2
            Randomness::<T>::get()
582
2
        }
583
    }
584

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

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

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

            
611
67770
    #[pallet::hooks]
612
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
613
34773
        fn on_initialize(n: BlockNumberFor<T>) -> Weight {
614
34773
            let mut weight = Weight::zero();
615
34773

            
616
34773
            // Account reads and writes for on_finalize
617
34773
            if T::GetRandomnessForNextBlock::should_end_session(n.saturating_add(One::one())) {
618
3274
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
619
31499
            }
620

            
621
34773
            weight
622
34773
        }
623

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

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

            
643
26338
            chains.container_chains.into_iter().collect()
644
26338
        }
645

            
646
2946
        fn get_all_collators_assigned_to_chains(for_session: ForSession) -> BTreeSet<T::AccountId> {
647
2946
            let mut all_chains: Vec<T::AccountId> =
648
2946
                Self::container_chains_with_collators(for_session)
649
2946
                    .iter()
650
4973
                    .flat_map(|(_para_id, collators)| collators.iter())
651
2946
                    .cloned()
652
2946
                    .collect();
653
2946
            all_chains.extend(
654
2946
                Self::collator_container_chain()
655
2946
                    .orchestrator_chain
656
2946
                    .iter()
657
2946
                    .cloned(),
658
2946
            );
659
2946
            all_chains.into_iter().collect()
660
2946
        }
661

            
662
        #[cfg(feature = "runtime-benchmarks")]
663
        fn set_container_chains_with_collators(
664
            for_session: ForSession,
665
            container_chains: &[(ParaId, Vec<T::AccountId>)],
666
        ) {
667
            match for_session {
668
                ForSession::Current => {
669
                    let mut collators = CollatorContainerChain::<T>::get();
670
                    collators.container_chains = container_chains.iter().cloned().collect();
671
                    CollatorContainerChain::<T>::put(collators);
672
                }
673
                ForSession::Next => {
674
                    let mut collators =
675
                        PendingCollatorContainerChain::<T>::get().unwrap_or_default();
676
                    collators.container_chains = container_chains.iter().cloned().collect();
677
                    PendingCollatorContainerChain::<T>::put(Some(collators));
678
                }
679
            }
680
        }
681
    }
682
}
683

            
684
/// Balance used by this pallet
685
pub type BalanceOf<T> =
686
    <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
687

            
688
pub struct RotateCollatorsEveryNSessions<Period>(PhantomData<Period>);
689

            
690
impl<Period> ShouldRotateAllCollators<u32> for RotateCollatorsEveryNSessions<Period>
691
where
692
    Period: Get<u32>,
693
{
694
4639
    fn should_rotate_all_collators(session_index: u32) -> bool {
695
4639
        let period = Period::get();
696
4639

            
697
4639
        if period == 0 {
698
            // A period of 0 disables rotation
699
1698
            false
700
        } else {
701
2941
            session_index % Period::get() == 0
702
        }
703
4639
    }
704
}
705

            
706
pub trait GetRandomnessForNextBlock<BlockNumber> {
707
    fn should_end_session(block_number: BlockNumber) -> bool;
708
    fn get_randomness() -> [u8; 32];
709
}
710

            
711
impl<BlockNumber> GetRandomnessForNextBlock<BlockNumber> for () {
712
2044
    fn should_end_session(_block_number: BlockNumber) -> bool {
713
2044
        false
714
2044
    }
715

            
716
    fn get_randomness() -> [u8; 32] {
717
        [0; 32]
718
    }
719
}