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
//! # Inactivity Tracking Pallet
17
//!
18
//! This pallet tracks and stores the activity of container chain and orchestrator chain collators
19
//! for configurable number of sessions. It is used to determine if a collator is inactive
20
//! for that period of time.
21
//!
22
//! The tracking functionality can be enabled or disabled with root privileges.
23
//! By default, the tracking is enabled.
24
#![cfg_attr(not(feature = "std"), no_std)]
25
use {
26
    frame_support::{
27
        dispatch::DispatchResult, dispatch::DispatchResultWithPostInfo, ensure,
28
        pallet_prelude::Weight,
29
    },
30
    parity_scale_codec::{Decode, Encode},
31
    scale_info::TypeInfo,
32
    serde::{Deserialize, Serialize},
33
    sp_core::{MaxEncodedLen, RuntimeDebug},
34
    sp_runtime::{traits::Get, BoundedBTreeSet},
35
    sp_staking::SessionIndex,
36
    tp_traits::{
37
        AuthorNotingHook, AuthorNotingInfo, ForSession, GetContainerChainsWithCollators,
38
        GetSessionIndex, InvulnerablesHelper, MaybeSelfChainBlockAuthor,
39
        NodeActivityTrackingHelper, ParaId, ParathreadHelper, StakingCandidateHelper,
40
    },
41
};
42

            
43
#[cfg(test)]
44
mod mock;
45

            
46
#[cfg(test)]
47
mod tests;
48

            
49
#[cfg(feature = "runtime-benchmarks")]
50
mod benchmarking;
51

            
52
pub mod weights;
53

            
54
pub use weights::WeightInfo;
55

            
56
#[cfg(feature = "runtime-benchmarks")]
57
use tp_traits::BlockNumber;
58

            
59
pub use pallet::*;
60
14976
#[frame_support::pallet]
61
pub mod pallet {
62
    use {
63
        super::*,
64
        crate::weights::WeightInfo,
65
        core::marker::PhantomData,
66
        frame_support::{pallet_prelude::*, storage::types::StorageMap},
67
        frame_system::pallet_prelude::*,
68
        sp_std::collections::btree_set::BTreeSet,
69
    };
70

            
71
    pub type Collator<T> = <T as frame_system::Config>::AccountId;
72

            
73
    /// The status of collator activity tracking
74
    #[derive(
75
        Clone,
76
        PartialEq,
77
        Eq,
78
        Encode,
79
        DecodeWithMemTracking,
80
        Decode,
81
3744
        TypeInfo,
82
        Serialize,
83
        Deserialize,
84
        RuntimeDebug,
85
        MaxEncodedLen,
86
    )]
87
    pub enum ActivityTrackingStatus {
88
        Enabled {
89
            /// The session in which we will start recording the collator activity after enabling it
90
            start: SessionIndex,
91
            /// The session after which the activity tracking can be disabled
92
            end: SessionIndex,
93
        },
94
        Disabled {
95
            /// The session after which the activity tracking can be enabled
96
            end: SessionIndex,
97
        },
98
    }
99
    impl Default for ActivityTrackingStatus {
100
172812
        fn default() -> Self {
101
172812
            ActivityTrackingStatus::Enabled { start: 0, end: 0 }
102
172812
        }
103
    }
104

            
105
2652
    #[pallet::pallet]
106
    pub struct Pallet<T>(PhantomData<T>);
107
    #[pallet::config]
108
    pub trait Config: frame_system::Config {
109
        /// Overarching event type.
110
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
111

            
112
        /// The maximum number of sessions for which a collator can be inactive
113
        /// before being moved to the offline queue
114
        #[pallet::constant]
115
        type MaxInactiveSessions: Get<u32>;
116

            
117
        /// The maximum amount of collators that can be stored for a session
118
        #[pallet::constant]
119
        type MaxCollatorsPerSession: Get<u32>;
120

            
121
        /// The maximum amount of container chains that can be stored
122
        #[pallet::constant]
123
        type MaxContainerChains: Get<u32>;
124

            
125
        /// Helper that returns the current session index.
126
        type CurrentSessionIndex: GetSessionIndex<SessionIndex>;
127

            
128
        /// Helper that fetches a list of collators eligible to produce blocks for the current session
129
        type CurrentCollatorsFetcher: GetContainerChainsWithCollators<Collator<Self>>;
130

            
131
        /// Helper that returns the block author for the orchestrator chain (if it exists)
132
        type GetSelfChainBlockAuthor: MaybeSelfChainBlockAuthor<Collator<Self>>;
133

            
134
        /// Helper that checks if a ParaId is a parathread
135
        type ParaFilter: ParathreadHelper;
136

            
137
        /// Helper for dealing with invulnerables.
138
        type InvulnerablesFilter: InvulnerablesHelper<Collator<Self>>;
139

            
140
        /// Helper for dealing with collator's stake
141
        type CollatorStakeHelper: StakingCandidateHelper<Collator<Self>>;
142

            
143
        /// The weight information of this pallet.
144
        type WeightInfo: weights::WeightInfo;
145
    }
146

            
147
    /// Switch to enable/disable activity tracking
148
110594
    #[pallet::storage]
149
    pub type CurrentActivityTrackingStatus<T: Config> =
150
        StorageValue<_, ActivityTrackingStatus, ValueQuery>;
151

            
152
    /// A storage map of inactive collators for a session
153
5303
    #[pallet::storage]
154
    pub type InactiveCollators<T: Config> = StorageMap<
155
        _,
156
        Twox64Concat,
157
        SessionIndex,
158
        BoundedBTreeSet<Collator<T>, T::MaxCollatorsPerSession>,
159
        ValueQuery,
160
    >;
161

            
162
    /// A list of active collators for a session. Repopulated at the start of every session
163
222704
    #[pallet::storage]
164
    pub type ActiveCollatorsForCurrentSession<T: Config> =
165
        StorageValue<_, BoundedBTreeSet<Collator<T>, T::MaxCollatorsPerSession>, ValueQuery>;
166

            
167
    /// A list of active container chains for a session. Repopulated at the start of every session
168
106086
    #[pallet::storage]
169
    pub type ActiveContainerChainsForCurrentSession<T: Config> =
170
        StorageValue<_, BoundedBTreeSet<ParaId, T::MaxContainerChains>, ValueQuery>;
171

            
172
    /// Switch to enable/disable offline marking.
173
712
    #[pallet::storage]
174
    pub type EnableMarkingOffline<T: Config> = StorageValue<_, bool, ValueQuery>;
175

            
176
    /// Storage map indicating the offline status of a collator
177
860
    #[pallet::storage]
178
    pub type OfflineCollators<T: Config> =
179
        StorageMap<_, Blake2_128Concat, Collator<T>, bool, ValueQuery>;
180

            
181
624
    #[pallet::event]
182
32
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
183
    pub enum Event<T: Config> {
184
        /// Event emitted when the activity tracking status is updated
185
        ActivityTrackingStatusSet { status: ActivityTrackingStatus },
186
        /// Collator online status updated
187
        CollatorStatusUpdated {
188
            collator: Collator<T>,
189
            is_offline: bool,
190
        },
191
    }
192

            
193
624
    #[pallet::error]
194
    pub enum Error<T> {
195
        /// The size of a collator set for a session has already reached MaxCollatorsPerSession value
196
        MaxCollatorsPerSessionReached,
197
        /// The size of a chains set for a session has already reached MaxContainerChains value
198
        MaxContainerChainsReached,
199
        /// Error returned when the activity tracking status is attempted to be updated before the end session
200
        ActivityTrackingStatusUpdateSuspended,
201
        /// Error returned when the activity tracking status is attempted to be enabled when it is already enabled
202
        ActivityTrackingStatusAlreadyEnabled,
203
        /// Error returned when the activity tracking status is attempted to be disabled when it is already disabled
204
        ActivityTrackingStatusAlreadyDisabled,
205
        /// Error returned when the collator status is attempted to be set to offline when offline marking is disabled
206
        MarkingOfflineNotEnabled,
207
        /// Error returned when the collator is not part of the sorted eligible candidates list
208
        CollatorNotEligibleCandidate,
209
        /// Error returned when the collator status is attempted to be set to offline when it is already offline
210
        CollatorNotOnline,
211
        /// Error returned when the collator status is attempted to be set to online when it is already online
212
        CollatorNotOffline,
213
        /// Error returned when the collator attempted to be set offline is invulnerable
214
        MarkingInvulnerableOfflineInvalid,
215
        /// Error returned when the collator attempted to be set offline is not inactive
216
        CollatorCannotBeNotifiedAsInactive,
217
    }
218

            
219
648
    #[pallet::call]
220
    impl<T: Config> Pallet<T> {
221
        /// Enables or disables inactivity tracking.
222
        #[pallet::call_index(0)]
223
        #[pallet::weight(T::WeightInfo::set_inactivity_tracking_status())]
224
        pub fn set_inactivity_tracking_status(
225
            origin: OriginFor<T>,
226
            enable_inactivity_tracking: bool,
227
18
        ) -> DispatchResult {
228
18
            ensure_root(origin)?;
229
17
            let current_status_end_session_index = match <CurrentActivityTrackingStatus<T>>::get() {
230
11
                ActivityTrackingStatus::Enabled { start: _, end } => {
231
11
                    ensure!(
232
11
                        !enable_inactivity_tracking,
233
1
                        Error::<T>::ActivityTrackingStatusAlreadyEnabled
234
                    );
235
10
                    end
236
                }
237
6
                ActivityTrackingStatus::Disabled { end } => {
238
6
                    ensure!(
239
6
                        enable_inactivity_tracking,
240
1
                        Error::<T>::ActivityTrackingStatusAlreadyDisabled
241
                    );
242
5
                    end
243
                }
244
            };
245
15
            let current_session_index = T::CurrentSessionIndex::session_index();
246
15
            ensure!(
247
15
                current_session_index > current_status_end_session_index,
248
1
                Error::<T>::ActivityTrackingStatusUpdateSuspended
249
            );
250
14
            Self::set_inactivity_tracking_status_inner(
251
14
                current_session_index,
252
14
                enable_inactivity_tracking,
253
14
            );
254
14
            Ok(())
255
        }
256

            
257
        /// Enables or disables the marking of collators as offline.
258
        #[pallet::call_index(1)]
259
        #[pallet::weight(T::WeightInfo::enable_offline_marking())]
260
22
        pub fn enable_offline_marking(origin: OriginFor<T>, value: bool) -> DispatchResult {
261
22
            ensure_root(origin)?;
262
21
            <EnableMarkingOffline<T>>::set(value);
263
21
            Ok(())
264
        }
265

            
266
        /// Allows a collator to mark itself offline.
267
        #[pallet::call_index(2)]
268
        #[pallet::weight(T::WeightInfo::set_offline())]
269
15
        pub fn set_offline(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
270
15
            let collator = ensure_signed(origin)?;
271
15
            Self::mark_collator_offline(&collator)
272
        }
273

            
274
        /// Allows a collator to mark itself online.
275
        #[pallet::call_index(3)]
276
        #[pallet::weight(T::WeightInfo::set_online())]
277
4
        pub fn set_online(origin: OriginFor<T>) -> DispatchResultWithPostInfo {
278
4
            let collator = ensure_signed(origin)?;
279
4
            Self::mark_collator_online(&collator)
280
        }
281

            
282
        /// Allows an account to notify inactive collator to be marked offline.
283
        #[pallet::call_index(4)]
284
        #[pallet::weight(T::WeightInfo::notify_inactive_collator())]
285
        pub fn notify_inactive_collator(
286
            origin: OriginFor<T>,
287
            collator: Collator<T>,
288
6
        ) -> DispatchResultWithPostInfo {
289
6
            ensure_signed(origin)?;
290
6
            ensure!(
291
6
                Self::is_node_inactive(&collator),
292
1
                Error::<T>::CollatorCannotBeNotifiedAsInactive
293
            );
294
5
            Self::mark_collator_offline(&collator)
295
        }
296
    }
297

            
298
66621
    #[pallet::hooks]
299
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
300
30137
        fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
301
30137
            let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
302
            // Process the orchestrator chain block author (if it exists) and activity tracking is enabled
303
30137
            if let Some(orchestrator_chain_author) = T::GetSelfChainBlockAuthor::get_block_author()
304
            {
305
26127
                total_weight.saturating_accrue(T::DbWeight::get().reads(1));
306
26127
                if let ActivityTrackingStatus::Enabled { start, end: _ } =
307
26127
                    <CurrentActivityTrackingStatus<T>>::get()
308
                {
309
26127
                    total_weight.saturating_accrue(T::DbWeight::get().reads(1));
310
26127
                    if start <= T::CurrentSessionIndex::session_index() {
311
26127
                        total_weight
312
26127
                            .saturating_accrue(Self::on_author_noted(orchestrator_chain_author));
313
26127
                    }
314
                }
315
4010
            }
316
30137
            total_weight
317
30137
        }
318
    }
319

            
320
    impl<T: Config> Pallet<T> {
321
        /// Internal function to set the activity tracking status and
322
        /// clear ActiveCollatorsForCurrentSession if disabled
323
17
        fn set_inactivity_tracking_status_inner(
324
17
            current_session_index: SessionIndex,
325
17
            enable_inactivity_tracking: bool,
326
17
        ) {
327
17
            let new_status_end_session_index =
328
17
                current_session_index.saturating_add(T::MaxInactiveSessions::get());
329
17
            let new_status = if enable_inactivity_tracking {
330
5
                ActivityTrackingStatus::Enabled {
331
5
                    start: current_session_index.saturating_add(1),
332
5
                    end: new_status_end_session_index,
333
5
                }
334
            } else {
335
12
                <ActiveCollatorsForCurrentSession<T>>::put(BoundedBTreeSet::new());
336
12
                ActivityTrackingStatus::Disabled {
337
12
                    end: new_status_end_session_index,
338
12
                }
339
            };
340
17
            <CurrentActivityTrackingStatus<T>>::put(new_status.clone());
341
17
            Self::deposit_event(Event::<T>::ActivityTrackingStatusSet { status: new_status })
342
17
        }
343

            
344
        /// Internal function to clear the active collators for the current session
345
        /// and remove the collators records that are outside the activity period.
346
        /// Triggered at the beginning of each session.
347
4039
        pub fn process_ended_session() {
348
4039
            let current_session_index = T::CurrentSessionIndex::session_index();
349
4039
            <ActiveCollatorsForCurrentSession<T>>::put(BoundedBTreeSet::new());
350
4039
            <ActiveContainerChainsForCurrentSession<T>>::put(BoundedBTreeSet::new());
351
4039

            
352
4039
            // Cleanup active collator info for sessions that are older than the maximum allowed
353
4039
            if current_session_index > T::MaxInactiveSessions::get() {
354
1529
                <crate::pallet::InactiveCollators<T>>::remove(
355
1529
                    current_session_index
356
1529
                        .saturating_sub(T::MaxInactiveSessions::get())
357
1529
                        .saturating_sub(1),
358
1529
                );
359
3050
            }
360
4039
        }
361

            
362
        /// Internal function to populate the inactivity tracking storage used for marking collator
363
        /// as inactive. Triggered at the end of a session.
364
3044
        pub fn on_before_session_ending() {
365
3044
            let current_session_index = T::CurrentSessionIndex::session_index();
366
3044
            Self::process_inactive_chains_for_session();
367
3044
            match <CurrentActivityTrackingStatus<T>>::get() {
368
16
                ActivityTrackingStatus::Disabled { .. } => return,
369
3028
                ActivityTrackingStatus::Enabled { start, end: _ } => {
370
3028
                    if start > current_session_index {
371
5
                        return;
372
3023
                    }
373
                }
374
            }
375
3023
            if let Ok(inactive_collators) =
376
3023
                BoundedBTreeSet::<Collator<T>, T::MaxCollatorsPerSession>::try_from(
377
3023
                    T::CurrentCollatorsFetcher::get_all_collators_assigned_to_chains(
378
3023
                        ForSession::Current,
379
3023
                    )
380
3023
                    .difference(&<ActiveCollatorsForCurrentSession<T>>::get())
381
3023
                    .cloned()
382
3023
                    .collect::<BTreeSet<Collator<T>>>(),
383
3023
                )
384
3023
            {
385
3023
                InactiveCollators::<T>::insert(current_session_index, inactive_collators);
386
3023
            } else {
387
                // If we reach MaxCollatorsPerSession limit there must be a bug in the pallet
388
                // so we disable the activity tracking
389
                Self::set_inactivity_tracking_status_inner(current_session_index, false);
390
            }
391
3044
        }
392

            
393
        /// Internal function to populate the current session active collator records with collators
394
        /// part of inactive chains.
395
3044
        pub fn process_inactive_chains_for_session() {
396
3044
            match <CurrentActivityTrackingStatus<T>>::get() {
397
15
                ActivityTrackingStatus::Disabled { .. } => return,
398
3029
                ActivityTrackingStatus::Enabled { start, end: _ } => {
399
3029
                    if start > T::CurrentSessionIndex::session_index() {
400
5
                        return;
401
3024
                    }
402
3024
                }
403
3024
            }
404
3024
            let mut active_chains = <ActiveContainerChainsForCurrentSession<T>>::get().into_inner();
405
3024
            // Removing the parathreads for the current session from the active chains array.
406
3024
            // In this way we handle all parathreads as inactive chains.
407
3024
            // This solution would only work if a collator either:
408
3024
            // - is assigned to one chain only
409
3024
            // - is assigned to multiple chains but all of them are parathreads
410
3024
            active_chains = active_chains
411
3024
                .difference(&T::ParaFilter::get_parathreads_for_session())
412
3024
                .cloned()
413
3024
                .collect::<BTreeSet<ParaId>>();
414
3024

            
415
3024
            let _ = <ActiveCollatorsForCurrentSession<T>>::try_mutate(
416
3024
                |active_collators| -> DispatchResult {
417
3024
                    let container_chains_with_collators =
418
3024
                        T::CurrentCollatorsFetcher::container_chains_with_collators(
419
3024
                            ForSession::Current,
420
3024
                        );
421

            
422
5163
                    for (para_id, collator_ids) in container_chains_with_collators.iter() {
423
4956
                        if !active_chains.contains(para_id) {
424
                            // Collators assigned to inactive chain are added
425
                            // to the current active collators storage
426
3766
                            for collator_id in collator_ids {
427
948
                                if active_collators.try_insert(collator_id.clone()).is_err() {
428
                                    // If we reach MaxCollatorsPerSession limit there must be a bug in the pallet
429
                                    // so we disable the activity tracking
430
1
                                    Self::set_inactivity_tracking_status_inner(
431
1
                                        T::CurrentSessionIndex::session_index(),
432
1
                                        false,
433
1
                                    );
434
1
                                    return Err(Error::<T>::MaxCollatorsPerSessionReached.into());
435
947
                                }
436
                            }
437
2137
                        }
438
                    }
439
3023
                    Ok(())
440
3024
                },
441
3024
            );
442
3044
        }
443

            
444
        /// Internal update the current session active collator records.
445
        /// This function is called when a container chain or orchestrator chain collator is noted.
446
48929
        pub fn on_author_noted(author: Collator<T>) -> Weight {
447
48929
            let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
448
48929
            let _ = <ActiveCollatorsForCurrentSession<T>>::try_mutate(
449
48929
                |active_collators| -> DispatchResult {
450
48929
                    if active_collators.try_insert(author.clone()).is_err() {
451
                        // If we reach MaxCollatorsPerSession limit there must be a bug in the pallet
452
                        // so we disable the activity tracking
453
1
                        Self::set_inactivity_tracking_status_inner(
454
1
                            T::CurrentSessionIndex::session_index(),
455
1
                            false,
456
1
                        );
457
1
                        total_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
458
1
                        return Err(Error::<T>::MaxCollatorsPerSessionReached.into());
459
48928
                    } else {
460
48928
                        total_weight.saturating_accrue(T::DbWeight::get().writes(1));
461
48928
                    }
462
48928
                    Ok(())
463
48929
                },
464
48929
            );
465
48929
            total_weight
466
48929
        }
467

            
468
        /// Internal update the current session active chains records.
469
        /// This function is called when a container chain is noted.
470
22802
        pub fn on_chain_noted(chain_id: ParaId) -> Weight {
471
22802
            let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
472
22802
            let _ = <ActiveContainerChainsForCurrentSession<T>>::try_mutate(
473
22802
                |active_chains| -> DispatchResult {
474
22802
                    if active_chains.try_insert(chain_id).is_err() {
475
                        // If we reach MaxContainerChains limit there must be a bug in the pallet
476
                        // so we disable the activity tracking
477
1
                        Self::set_inactivity_tracking_status_inner(
478
1
                            T::CurrentSessionIndex::session_index(),
479
1
                            false,
480
1
                        );
481
1
                        total_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
482
1
                        return Err(Error::<T>::MaxContainerChainsReached.into());
483
22801
                    } else {
484
22801
                        total_weight += T::DbWeight::get().writes(1);
485
22801
                    }
486
22801
                    Ok(())
487
22802
                },
488
22802
            );
489
22802
            total_weight
490
22802
        }
491

            
492
        /// Internal function to mark a collator as offline.
493
20
        pub fn mark_collator_offline(collator: &Collator<T>) -> DispatchResultWithPostInfo {
494
20
            ensure!(
495
20
                <EnableMarkingOffline<T>>::get(),
496
2
                Error::<T>::MarkingOfflineNotEnabled
497
            );
498
18
            ensure!(
499
18
                T::CollatorStakeHelper::is_candidate_selected(collator),
500
2
                Error::<T>::CollatorNotEligibleCandidate
501
            );
502
16
            ensure!(
503
16
                !<OfflineCollators<T>>::get(collator.clone()),
504
2
                Error::<T>::CollatorNotOnline
505
            );
506
14
            ensure!(
507
14
                !T::InvulnerablesFilter::is_invulnerable(collator),
508
2
                Error::<T>::MarkingInvulnerableOfflineInvalid
509
            );
510
12
            <OfflineCollators<T>>::insert(collator.clone(), true);
511
12
            // Updates the SortedEligibleCandidates list. Has to be called after the collator is marked offline.
512
12
            T::CollatorStakeHelper::on_online_status_change(collator, false)?;
513
12
            Self::deposit_event(Event::<T>::CollatorStatusUpdated {
514
12
                collator: collator.clone(),
515
12
                is_offline: true,
516
12
            });
517
12
            Ok(().into())
518
20
        }
519

            
520
4
        pub fn mark_collator_online(collator: &Collator<T>) -> DispatchResultWithPostInfo {
521
4
            ensure!(
522
4
                <OfflineCollators<T>>::get(collator),
523
1
                Error::<T>::CollatorNotOffline
524
            );
525
3
            <OfflineCollators<T>>::remove(collator.clone());
526
3
            // Updates the SortedEligibleCandidates list. Has to be called after the collator is marked online.
527
3
            T::CollatorStakeHelper::on_online_status_change(collator, true)?;
528
3
            Self::deposit_event(Event::<T>::CollatorStatusUpdated {
529
3
                collator: collator.clone(),
530
3
                is_offline: false,
531
3
            });
532
3
            Ok(().into())
533
4
        }
534
    }
535
}
536

            
537
impl<T: Config> NodeActivityTrackingHelper<Collator<T>> for Pallet<T> {
538
47
    fn is_node_inactive(node: &Collator<T>) -> bool {
539
47
        // If inactivity tracking is not enabled all nodes are considered active.
540
47
        // We don't need to check the activity records and can return false
541
47
        // Inactivity tracking is not enabled if
542
47
        // - the status is disabled
543
47
        // - the CurrentSessionIndex < start session + MaxInactiveSessions index since there won't be
544
47
        // sufficient activity records to determine inactivity
545
47
        let current_session_index = T::CurrentSessionIndex::session_index();
546
47
        let minimum_sessions_required = T::MaxInactiveSessions::get();
547
47
        match <CurrentActivityTrackingStatus<T>>::get() {
548
2
            ActivityTrackingStatus::Disabled { .. } => return false,
549
45
            ActivityTrackingStatus::Enabled { start, end: _ } => {
550
45
                if start.saturating_add(minimum_sessions_required) > current_session_index {
551
17
                    return false;
552
28
                }
553
28
            }
554
28
        }
555
28

            
556
28
        let start_session_index = current_session_index.saturating_sub(minimum_sessions_required);
557
76
        for session_index in start_session_index..current_session_index {
558
76
            if !<InactiveCollators<T>>::get(session_index).contains(node) {
559
11
                return false;
560
65
            }
561
        }
562
17
        true
563
47
    }
564
189
    fn is_node_offline(node: &Collator<T>) -> bool {
565
189
        <OfflineCollators<T>>::get(node)
566
189
    }
567

            
568
    #[cfg(feature = "runtime-benchmarks")]
569
    fn make_node_online(node: &Collator<T>) {
570
        let _ = Self::mark_collator_online(node);
571
    }
572

            
573
    #[cfg(feature = "runtime-benchmarks")]
574
    fn make_node_inactive(node: &Collator<T>) {
575
        // First we need to make sure that eniugh sessions had pass
576
        // so the node can be marked as inactive
577
        let max_inactive_sessions = T::MaxInactiveSessions::get();
578
        if T::CurrentSessionIndex::session_index() < max_inactive_sessions {
579
            T::CurrentSessionIndex::skip_to_session(max_inactive_sessions)
580
        }
581

            
582
        // Now we can insert the node as inactive for all sessions in the current inactivity window
583
        let mut inactive_nodes_set: BoundedBTreeSet<
584
            Collator<T>,
585
            <T as Config>::MaxCollatorsPerSession,
586
        > = BoundedBTreeSet::new();
587
        let _ = inactive_nodes_set.try_insert(node.clone());
588
        for session_index in 0..max_inactive_sessions {
589
            <InactiveCollators<T>>::insert(session_index, inactive_nodes_set.clone());
590
        }
591
    }
592
}
593

            
594
impl<T: Config> AuthorNotingHook<Collator<T>> for Pallet<T> {
595
22672
    fn on_container_authors_noted(info: &[AuthorNotingInfo<Collator<T>>]) -> Weight {
596
22672
        let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
597
22670
        if let ActivityTrackingStatus::Enabled { start, end: _ } =
598
22672
            <CurrentActivityTrackingStatus<T>>::get()
599
        {
600
22670
            if start <= T::CurrentSessionIndex::session_index() {
601
45470
                for author_info in info {
602
22802
                    total_weight
603
22802
                        .saturating_accrue(Self::on_author_noted(author_info.author.clone()));
604
22802
                    total_weight.saturating_accrue(Self::on_chain_noted(author_info.para_id));
605
22802
                }
606
2
            }
607
2
        }
608
22672
        total_weight
609
22672
    }
610
    #[cfg(feature = "runtime-benchmarks")]
611
    fn prepare_worst_case_for_bench(_a: &Collator<T>, _b: BlockNumber, _para_id: ParaId) {}
612
}