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

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

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

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

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

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

            
206
1185
            let enough_collators = Self::enough_collators_for_all_chains(
207
1185
                &bulk_paras,
208
1185
                &pool_paras,
209
1185
                target_session_index,
210
1185
                number_of_collators,
211
1185
                collators_per_container,
212
1185
                collators_per_parathread,
213
1185
            );
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
1185
            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
1185
            if should_charge_tip {
225
905
                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
905
                });
229
848

            
230
877
                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
877
                });
234
848
            }
235

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

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

            
242
1185
            (chains, should_charge_tip)
243
1185
        }
244

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

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

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

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

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

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

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

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

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

            
323
4831
            let mut shuffle_collators = None;
324
4831
            // If the random_seed is all zeros, we don't shuffle the list of collators nor the list
325
4831
            // of container chains.
326
4831
            // This should only happen in tests_without_core_config, and in the genesis block.
327
4831
            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
4710
            }
335

            
336
4831
            let orchestrator_chain: ChainNumCollators = if T::ForceEmptyOrchestrator::get() {
337
1177
                ChainNumCollators {
338
1177
                    para_id: T::SelfParaId::get(),
339
1177
                    min_collators: 0u32,
340
1177
                    max_collators: 0u32,
341
1177
                    parathread: false,
342
1177
                }
343
            } else {
344
3654
                ChainNumCollators {
345
3654
                    para_id: T::SelfParaId::get(),
346
3654
                    min_collators: T::HostConfiguration::min_collators_for_orchestrator(
347
3654
                        target_session_index,
348
3654
                    ),
349
3654
                    max_collators: T::HostConfiguration::max_collators_for_orchestrator(
350
3654
                        target_session_index,
351
3654
                    ),
352
3654
                    parathread: false,
353
3654
                }
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
4831
            let mut bulk_paras = vec![];
362
4831
            let mut pool_paras = vec![];
363

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

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

            
403
            // We assign new collators
404
            // we use the config scheduled at the target_session_index
405
4831
            let full_rotation =
406
4831
                T::ShouldRotateAllCollators::should_rotate_all_collators(target_session_index);
407
4831
            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
4431
                log::info!(
415
1866
                    "Collator assignment: keep old assigned. Session {:?}, Seed: {:?}",
416
1866
                    current_session_index.encode(),
417
                    random_seed
418
                );
419
            }
420

            
421
4831
            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
4431
                FullRotationModes::keep_all()
426
            };
427

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

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

            
444
4831
            let mut new_assigned = match new_assigned {
445
4827
                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
4831
            let mut assigned_containers = new_assigned.container_chains.clone();
457
7047
            assigned_containers.retain(|_, v| !v.is_empty());
458

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

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

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

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

            
484
4831
            let old_assigned_changed = old_assigned != new_assigned;
485
4831
            let mut pending_changed = false;
486
            // Update CollatorContainerChain using last entry of pending, if needed
487
4831
            if let Some(current) = pending.take() {
488
1143
                pending_changed = true;
489
1143
                CollatorContainerChain::<T>::put(current);
490
3714
            }
491
4831
            if old_assigned_changed {
492
1552
                pending = Some(new_assigned.clone());
493
1552
                pending_changed = true;
494
3992
            }
495
            // Update PendingCollatorContainerChain, if it changed
496
4831
            if pending_changed {
497
2273
                PendingCollatorContainerChain::<T>::put(pending);
498
3722
            }
499

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

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

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

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

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

            
538
4831
            CollatorFullnessRatio::<T>::put(ratio);
539
4831
        }
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
4831
        fn read_assigned_collators() -> AssignedCollators<T::AccountId> {
545
4831
            let mut pending_collator_list = PendingCollatorContainerChain::<T>::get();
546

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

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

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

            
569
4831
            assigned_collators
570
4831
        }
571

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

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

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

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

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

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

            
612
34983
            // Account reads and writes for on_finalize
613
34983
            weight.saturating_accrue(T::Randomness::prepare_randomness_weight(n));
614
34983

            
615
34983
            weight
616
34983
        }
617

            
618
34452
        fn on_finalize(n: BlockNumberFor<T>) {
619
34452
            // If the next block is a session change, read randomness and store in pallet storage
620
34452
            T::Randomness::prepare_randomness(n);
621
34452
        }
622
    }
623

            
624
    impl<T: Config> GetContainerChainsWithCollators<T::AccountId> for Pallet<T> {
625
29370
        fn container_chains_with_collators(
626
29370
            for_session: ForSession,
627
29370
        ) -> Vec<(ParaId, Vec<T::AccountId>)> {
628
29370
            // If next session has None then current session data will stay.
629
29370
            let chains = (for_session == ForSession::Next)
630
29370
                .then(|| PendingCollatorContainerChain::<T>::get())
631
29370
                .flatten()
632
29370
                .unwrap_or_else(|| CollatorContainerChain::<T>::get());
633
29370

            
634
29370
            chains.container_chains.into_iter().collect()
635
29370
        }
636

            
637
2951
        fn get_all_collators_assigned_to_chains(for_session: ForSession) -> BTreeSet<T::AccountId> {
638
2951
            let mut all_chains: Vec<T::AccountId> =
639
2951
                Self::container_chains_with_collators(for_session)
640
2951
                    .iter()
641
4988
                    .flat_map(|(_para_id, collators)| collators.iter())
642
2951
                    .cloned()
643
2951
                    .collect();
644
2951
            all_chains.extend(
645
2951
                Self::collator_container_chain()
646
2951
                    .orchestrator_chain
647
2951
                    .iter()
648
2951
                    .cloned(),
649
2951
            );
650
2951
            all_chains.into_iter().collect()
651
2951
        }
652

            
653
        #[cfg(feature = "runtime-benchmarks")]
654
        fn set_container_chains_with_collators(
655
            for_session: ForSession,
656
            container_chains: &[(ParaId, Vec<T::AccountId>)],
657
        ) {
658
            match for_session {
659
                ForSession::Current => {
660
                    let mut collators = CollatorContainerChain::<T>::get();
661
                    collators.container_chains = container_chains.iter().cloned().collect();
662
                    CollatorContainerChain::<T>::put(collators);
663
                }
664
                ForSession::Next => {
665
                    let mut collators =
666
                        PendingCollatorContainerChain::<T>::get().unwrap_or_default();
667
                    collators.container_chains = container_chains.iter().cloned().collect();
668
                    PendingCollatorContainerChain::<T>::put(Some(collators));
669
                }
670
            }
671
        }
672
    }
673
}
674

            
675
/// Balance used by this pallet
676
pub type BalanceOf<T> =
677
    <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
678

            
679
pub struct RotateCollatorsEveryNSessions<Period>(PhantomData<Period>);
680

            
681
impl<Period> ShouldRotateAllCollators<u32> for RotateCollatorsEveryNSessions<Period>
682
where
683
    Period: Get<u32>,
684
{
685
4664
    fn should_rotate_all_collators(session_index: u32) -> bool {
686
4664
        let period = Period::get();
687
4664

            
688
4664
        if period == 0 {
689
            // A period of 0 disables rotation
690
1709
            false
691
        } else {
692
2955
            session_index % Period::get() == 0
693
        }
694
4664
    }
695
}
696

            
697
/// Only works on parachains because in relaychains it is not possible to know for sure if the next
698
/// block will be in the same session as the current one, as it depends on slots and validators can
699
/// skip slots.
700
pub trait GetRandomnessForNextBlock<BlockNumber> {
701
    fn should_end_session(block_number: BlockNumber) -> bool;
702
    fn get_randomness() -> [u8; 32];
703
}
704

            
705
impl<BlockNumber> GetRandomnessForNextBlock<BlockNumber> for () {
706
    fn should_end_session(_block_number: BlockNumber) -> bool {
707
        false
708
    }
709

            
710
    fn get_randomness() -> [u8; 32] {
711
        [0; 32]
712
    }
713
}
714

            
715
pub trait CollatorAssignmentRandomness<BlockNumber> {
716
    /// Called in on_initialize, returns weight needed by prepare_randomness call.
717
    fn prepare_randomness_weight(n: BlockNumber) -> Weight;
718
    /// Called in on_finalize.
719
    /// Prepares randomness for the next block if the next block is a new session start.
720
    fn prepare_randomness(n: BlockNumber);
721
    /// Called once at the start of each session in on_initialize of pallet_initializer
722
    fn take_randomness() -> [u8; 32];
723
}
724

            
725
impl<BlockNumber> CollatorAssignmentRandomness<BlockNumber> for () {
726
1057
    fn prepare_randomness_weight(_n: BlockNumber) -> Weight {
727
1057
        Weight::zero()
728
1057
    }
729
987
    fn prepare_randomness(_n: BlockNumber) {}
730
167
    fn take_randomness() -> [u8; 32] {
731
167
        [0; 32]
732
167
    }
733
}
734

            
735
/// Parachain randomness impl.
736
///
737
/// Reads relay chain randomness in the last block of the session and stores it in pallet storage.
738
/// When new session starts, takes that value from storage removing it.
739
/// Relay randomness cannot be accessed in `on_initialize`, so `prepare_randomness` is executed in
740
/// `on_finalize`, with `prepare_randomness_weight` reserving the weight needed.
741
pub struct ParachainRandomness<T, Runtime>(PhantomData<(T, Runtime)>);
742

            
743
impl<BlockNumber, T, Runtime> CollatorAssignmentRandomness<BlockNumber>
744
    for ParachainRandomness<T, Runtime>
745
where
746
    BlockNumber: Saturating + One,
747
    T: GetRandomnessForNextBlock<BlockNumber>,
748
    Runtime: frame_system::Config + crate::Config,
749
{
750
26656
    fn prepare_randomness_weight(n: BlockNumber) -> Weight {
751
26656
        let mut weight = Weight::zero();
752
26656

            
753
26656
        if T::should_end_session(n.saturating_add(One::one())) {
754
2607
            weight.saturating_accrue(Runtime::DbWeight::get().reads_writes(1, 1));
755
24049
        }
756

            
757
26656
        weight
758
26656
    }
759

            
760
26532
    fn prepare_randomness(n: BlockNumber) {
761
26532
        if T::should_end_session(n.saturating_add(One::one())) {
762
2604
            let random_seed = T::get_randomness();
763
2604
            Randomness::<Runtime>::put(random_seed);
764
23928
        }
765
26532
    }
766

            
767
3487
    fn take_randomness() -> [u8; 32] {
768
3487
        Randomness::<Runtime>::take()
769
3487
    }
770
}
771

            
772
/// Solochain randomness.
773
///
774
/// Uses current block randomness. This randomness exists in `on_initialize` so we don't need to
775
/// `prepare_randomness` in the previous block.
776
pub struct SolochainRandomness<T>(PhantomData<T>);
777

            
778
impl<BlockNumber, T> CollatorAssignmentRandomness<BlockNumber> for SolochainRandomness<T>
779
where
780
    T: Get<[u8; 32]>,
781
{
782
7270
    fn prepare_randomness_weight(_n: BlockNumber) -> Weight {
783
7270
        Weight::zero()
784
7270
    }
785

            
786
6933
    fn prepare_randomness(_n: BlockNumber) {}
787

            
788
1177
    fn take_randomness() -> [u8; 32] {
789
1177
        #[cfg(feature = "runtime-benchmarks")]
790
1177
        if let Some(x) =
791
1177
            frame_support::storage::unhashed::take(b"__bench_collator_assignment_randomness")
792
1177
        {
793
1177
            return x;
794
1177
        }
795
1177

            
796
1177
        T::get()
797
1177
    }
798
}