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

            
26
use {
27
    frame_support::{dispatch::DispatchResult, pallet_prelude::Weight},
28
    parity_scale_codec::{Decode, Encode},
29
    scale_info::TypeInfo,
30
    serde::{Deserialize, Serialize},
31
    sp_core::{MaxEncodedLen, RuntimeDebug},
32
    sp_runtime::{traits::Get, BoundedBTreeSet},
33
    sp_staking::SessionIndex,
34
    tp_traits::{
35
        AuthorNotingHook, AuthorNotingInfo, ForSession, GetContainerChainsWithCollators,
36
        GetSessionIndex, MaybeSelfChainBlockAuthor, NodeActivityTrackingHelper, ParaId,
37
        ParathreadHelper,
38
    },
39
};
40

            
41
#[cfg(test)]
42
mod mock;
43

            
44
#[cfg(test)]
45
mod tests;
46

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

            
50
pub mod weights;
51
pub use weights::WeightInfo;
52

            
53
#[cfg(feature = "runtime-benchmarks")]
54
use tp_traits::BlockNumber;
55

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

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

            
99
2640
    #[pallet::pallet]
100
    pub struct Pallet<T>(PhantomData<T>);
101
    #[pallet::config]
102
    pub trait Config: frame_system::Config {
103
        /// Overarching event type.
104
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
105

            
106
        /// A stable identifier for a collator.
107
        type CollatorId: Member
108
            + Parameter
109
            + Ord
110
            + MaybeSerializeDeserialize
111
            + MaxEncodedLen
112
            + TryFrom<Self::AccountId>;
113

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

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

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

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

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

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

            
136
        /// Helper that checks if a ParaId is a parathread
137
        type ParaFilter: ParathreadHelper;
138

            
139
        /// The weight information of this pallet.
140
        type WeightInfo: weights::WeightInfo;
141
    }
142

            
143
    /// Switch to enable/disable activity tracking
144
109028
    #[pallet::storage]
145
    pub type CurrentActivityTrackingStatus<T: Config> =
146
        StorageValue<_, ActivityTrackingStatus, ValueQuery>;
147

            
148
    /// A storage map of inactive collators for a session
149
5231
    #[pallet::storage]
150
    pub type InactiveCollators<T: Config> = StorageMap<
151
        _,
152
        Twox64Concat,
153
        SessionIndex,
154
        BoundedBTreeSet<T::CollatorId, T::MaxCollatorsPerSession>,
155
        ValueQuery,
156
    >;
157

            
158
    /// A list of active collators for a session. Repopulated at the start of every session
159
219614
    #[pallet::storage]
160
    pub type ActiveCollatorsForCurrentSession<T: Config> =
161
        StorageValue<_, BoundedBTreeSet<T::CollatorId, T::MaxCollatorsPerSession>, ValueQuery>;
162

            
163
    /// A list of active container chains for a session. Repopulated at the start of every session
164
104948
    #[pallet::storage]
165
    pub type ActiveContainerChainsForCurrentSession<T: Config> =
166
        StorageValue<_, BoundedBTreeSet<ParaId, T::MaxContainerChains>, ValueQuery>;
167

            
168
618
    #[pallet::event]
169
17
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
170
    pub enum Event<T: Config> {
171
        /// Event emitted when the activity tracking status is updated
172
        ActivityTrackingStatusSet { status: ActivityTrackingStatus },
173
    }
174

            
175
18
    #[pallet::error]
176
    pub enum Error<T> {
177
        /// The size of a collator set for a session has already reached MaxCollatorsPerSession value
178
        MaxCollatorsPerSessionReached,
179
        /// The size of a chains set for a session has already reached MaxContainerChains value
180
        MaxContainerChainsReached,
181
        /// Error returned when the activity tracking status is attempted to be updated before the end session
182
        ActivityTrackingStatusUpdateSuspended,
183
        /// Error returned when the activity tracking status is attempted to be enabled when it is already enabled
184
        ActivityTrackingStatusAlreadyEnabled,
185
        /// Error returned when the activity tracking status is attempted to be disabled when it is already disabled
186
        ActivityTrackingStatusAlreadyDisabled,
187
    }
188

            
189
    #[pallet::call]
190
    impl<T: Config> Pallet<T> {
191
        #[pallet::call_index(0)]
192
        #[pallet::weight(T::WeightInfo::set_inactivity_tracking_status())]
193
        pub fn set_inactivity_tracking_status(
194
            origin: OriginFor<T>,
195
            enable_inactivity_tracking: bool,
196
18
        ) -> DispatchResult {
197
18
            ensure_root(origin)?;
198
17
            let current_status_end_session_index = match <CurrentActivityTrackingStatus<T>>::get() {
199
11
                ActivityTrackingStatus::Enabled { start: _, end } => {
200
11
                    ensure!(
201
11
                        !enable_inactivity_tracking,
202
1
                        Error::<T>::ActivityTrackingStatusAlreadyEnabled
203
                    );
204
10
                    end
205
                }
206
6
                ActivityTrackingStatus::Disabled { end } => {
207
6
                    ensure!(
208
6
                        enable_inactivity_tracking,
209
1
                        Error::<T>::ActivityTrackingStatusAlreadyDisabled
210
                    );
211
5
                    end
212
                }
213
            };
214
15
            let current_session_index = T::CurrentSessionIndex::session_index();
215
15
            ensure!(
216
15
                current_session_index > current_status_end_session_index,
217
1
                Error::<T>::ActivityTrackingStatusUpdateSuspended
218
            );
219
14
            Self::set_inactivity_tracking_status_inner(
220
14
                current_session_index,
221
14
                enable_inactivity_tracking,
222
14
            );
223
14
            Ok(())
224
        }
225
    }
226

            
227
58901
    #[pallet::hooks]
228
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
229
29586
        fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
230
29586
            let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
231
            // Process the orchestrator chain block author (if it exists) and activity tracking is enabled
232
29586
            if let Some(orchestrator_chain_author) = T::GetSelfChainBlockAuthor::get_block_author()
233
            {
234
25685
                total_weight.saturating_accrue(T::DbWeight::get().reads(1));
235
25685
                if let ActivityTrackingStatus::Enabled { start, end: _ } =
236
25685
                    <CurrentActivityTrackingStatus<T>>::get()
237
                {
238
25685
                    total_weight.saturating_accrue(T::DbWeight::get().reads(1));
239
25685
                    if start <= T::CurrentSessionIndex::session_index() {
240
25685
                        total_weight
241
25685
                            .saturating_accrue(Self::on_author_noted(orchestrator_chain_author));
242
25685
                    }
243
                }
244
3901
            }
245
29586
            total_weight
246
29586
        }
247
    }
248

            
249
    impl<T: Config> Pallet<T> {
250
        /// Internal function to set the activity tracking status and
251
        /// clear ActiveCollatorsForCurrentSession if disabled
252
17
        fn set_inactivity_tracking_status_inner(
253
17
            current_session_index: SessionIndex,
254
17
            enable_inactivity_tracking: bool,
255
17
        ) {
256
17
            let new_status_end_session_index =
257
17
                current_session_index.saturating_add(T::MaxInactiveSessions::get());
258
17
            let new_status = if enable_inactivity_tracking {
259
5
                ActivityTrackingStatus::Enabled {
260
5
                    start: current_session_index.saturating_add(1),
261
5
                    end: new_status_end_session_index,
262
5
                }
263
            } else {
264
12
                <ActiveCollatorsForCurrentSession<T>>::put(BoundedBTreeSet::new());
265
12
                ActivityTrackingStatus::Disabled {
266
12
                    end: new_status_end_session_index,
267
12
                }
268
            };
269
17
            <CurrentActivityTrackingStatus<T>>::put(new_status.clone());
270
17
            Self::deposit_event(Event::<T>::ActivityTrackingStatusSet { status: new_status })
271
17
        }
272

            
273
        /// Internal function to clear the active collators for the current session
274
        /// and remove the collators records that are outside the activity period.
275
        /// Triggered at the beginning of each session.
276
3987
        pub fn process_ended_session() {
277
3987
            let current_session_index = T::CurrentSessionIndex::session_index();
278
3987
            <ActiveCollatorsForCurrentSession<T>>::put(BoundedBTreeSet::new());
279
3987
            <ActiveContainerChainsForCurrentSession<T>>::put(BoundedBTreeSet::new());
280
3987

            
281
3987
            // Cleanup active collator info for sessions that are older than the maximum allowed
282
3987
            if current_session_index > T::MaxInactiveSessions::get() {
283
1529
                <crate::pallet::InactiveCollators<T>>::remove(
284
1529
                    current_session_index
285
1529
                        .saturating_sub(T::MaxInactiveSessions::get())
286
1529
                        .saturating_sub(1),
287
1529
                );
288
3022
            }
289
3987
        }
290

            
291
        /// Internal function to populate the inactivity tracking storage used for marking collator
292
        /// as inactive. Triggered at the end of a session.
293
2998
        pub fn on_before_session_ending() {
294
2998
            let current_session_index = T::CurrentSessionIndex::session_index();
295
2998
            Self::process_inactive_chains_for_session();
296
2998
            match <CurrentActivityTrackingStatus<T>>::get() {
297
16
                ActivityTrackingStatus::Disabled { .. } => return,
298
2982
                ActivityTrackingStatus::Enabled { start, end: _ } => {
299
2982
                    if start > current_session_index {
300
5
                        return;
301
2977
                    }
302
                }
303
            }
304
2977
            if let Ok(inactive_collators) =
305
2977
                BoundedBTreeSet::<T::CollatorId, T::MaxCollatorsPerSession>::try_from(
306
2977
                    T::CurrentCollatorsFetcher::get_all_collators_assigned_to_chains(
307
2977
                        ForSession::Current,
308
2977
                    )
309
2977
                    .difference(&<ActiveCollatorsForCurrentSession<T>>::get())
310
2977
                    .cloned()
311
2977
                    .collect::<BTreeSet<T::CollatorId>>(),
312
2977
                )
313
2977
            {
314
2977
                InactiveCollators::<T>::insert(current_session_index, inactive_collators);
315
2977
            } else {
316
                // If we reach MaxCollatorsPerSession limit there must be a bug in the pallet
317
                // so we disable the activity tracking
318
                Self::set_inactivity_tracking_status_inner(current_session_index, false);
319
            }
320
2998
        }
321

            
322
        /// Internal function to populate the current session active collator records with collators
323
        /// part of inactive chains.
324
2998
        pub fn process_inactive_chains_for_session() {
325
2998
            match <CurrentActivityTrackingStatus<T>>::get() {
326
15
                ActivityTrackingStatus::Disabled { .. } => return,
327
2983
                ActivityTrackingStatus::Enabled { start, end: _ } => {
328
2983
                    if start > T::CurrentSessionIndex::session_index() {
329
5
                        return;
330
2978
                    }
331
2978
                }
332
2978
            }
333
2978
            let mut active_chains = <ActiveContainerChainsForCurrentSession<T>>::get().into_inner();
334
2978
            // Removing the parathreads for the current session from the active chains array.
335
2978
            // In this way we handle all parathreads as inactive chains.
336
2978
            // This solution would only work if a collator either:
337
2978
            // - is assigned to one chain only
338
2978
            // - is assigned to multiple chains but all of them are parathreads
339
2978
            active_chains = active_chains
340
2978
                .difference(&T::ParaFilter::get_parathreads_for_session())
341
2978
                .cloned()
342
2978
                .collect::<BTreeSet<ParaId>>();
343
2978

            
344
2978
            let _ = <ActiveCollatorsForCurrentSession<T>>::try_mutate(
345
2978
                |active_collators| -> DispatchResult {
346
2978
                    let container_chains_with_collators =
347
2978
                        T::CurrentCollatorsFetcher::container_chains_with_collators(
348
2978
                            ForSession::Current,
349
2978
                        );
350

            
351
5067
                    for (para_id, collator_ids) in container_chains_with_collators.iter() {
352
4854
                        if !active_chains.contains(para_id) {
353
                            // Collators assigned to inactive chain are added
354
                            // to the current active collators storage
355
3618
                            for collator_id in collator_ids {
356
878
                                if let Err(_) = active_collators.try_insert(collator_id.clone()) {
357
                                    // If we reach MaxCollatorsPerSession limit there must be a bug in the pallet
358
                                    // so we disable the activity tracking
359
1
                                    Self::set_inactivity_tracking_status_inner(
360
1
                                        T::CurrentSessionIndex::session_index(),
361
1
                                        false,
362
1
                                    );
363
1
                                    return Err(Error::<T>::MaxCollatorsPerSessionReached.into());
364
877
                                }
365
                            }
366
2113
                        }
367
                    }
368
2977
                    Ok(())
369
2978
                },
370
2978
            );
371
2998
        }
372

            
373
        /// Internal update the current session active collator records.
374
        /// This function is called when a container chain or orchestrator chain collator is noted.
375
48253
        pub fn on_author_noted(author: T::CollatorId) -> Weight {
376
48253
            let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
377
48253
            let _ = <ActiveCollatorsForCurrentSession<T>>::try_mutate(
378
48253
                |active_collators| -> DispatchResult {
379
48253
                    if let Err(_) = active_collators.try_insert(author.clone()) {
380
                        // If we reach MaxCollatorsPerSession limit there must be a bug in the pallet
381
                        // so we disable the activity tracking
382
1
                        Self::set_inactivity_tracking_status_inner(
383
1
                            T::CurrentSessionIndex::session_index(),
384
1
                            false,
385
1
                        );
386
1
                        total_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
387
1
                        return Err(Error::<T>::MaxCollatorsPerSessionReached.into());
388
48252
                    } else {
389
48252
                        total_weight.saturating_accrue(T::DbWeight::get().writes(1));
390
48252
                    }
391
48252
                    Ok(())
392
48253
                },
393
48253
            );
394
48253
            total_weight
395
48253
        }
396

            
397
        /// Internal update the current session active chains records.
398
        /// This function is called when a container chain is noted.
399
22568
        pub fn on_chain_noted(chain_id: ParaId) -> Weight {
400
22568
            let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
401
22568
            let _ = <ActiveContainerChainsForCurrentSession<T>>::try_mutate(
402
22568
                |active_chains| -> DispatchResult {
403
22568
                    if let Err(_) = active_chains.try_insert(chain_id) {
404
                        // If we reach MaxContainerChains limit there must be a bug in the pallet
405
                        // so we disable the activity tracking
406
1
                        Self::set_inactivity_tracking_status_inner(
407
1
                            T::CurrentSessionIndex::session_index(),
408
1
                            false,
409
1
                        );
410
1
                        total_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
411
1
                        return Err(Error::<T>::MaxContainerChainsReached.into());
412
22567
                    } else {
413
22567
                        total_weight += T::DbWeight::get().writes(1);
414
22567
                    }
415
22567
                    Ok(())
416
22568
                },
417
22568
            );
418
22568
            total_weight
419
22568
        }
420
    }
421
}
422

            
423
impl<T: Config> NodeActivityTrackingHelper<T::CollatorId> for Pallet<T> {
424
41
    fn is_node_inactive(node: &T::CollatorId) -> bool {
425
41
        // If inactivity tracking is not enabled all nodes are considered active.
426
41
        // We don't need to check the activity records and can return false
427
41
        // Inactivity tracking is not enabled if
428
41
        // - the status is disabled
429
41
        // - the CurrentSessionIndex < start session + MaxInactiveSessions index since there won't be
430
41
        // sufficient activity records to determine inactivity
431
41
        let current_session_index = T::CurrentSessionIndex::session_index();
432
41
        let minimum_sessions_required = T::MaxInactiveSessions::get();
433
41
        match <CurrentActivityTrackingStatus<T>>::get() {
434
2
            ActivityTrackingStatus::Disabled { .. } => return false,
435
39
            ActivityTrackingStatus::Enabled { start, end: _ } => {
436
39
                if start.saturating_add(minimum_sessions_required) > current_session_index {
437
16
                    return false;
438
23
                }
439
23
            }
440
23
        }
441
23

            
442
23
        let start_session_index = current_session_index.saturating_sub(minimum_sessions_required);
443
66
        for session_index in start_session_index..current_session_index {
444
66
            if !<InactiveCollators<T>>::get(session_index).contains(node) {
445
11
                return false;
446
55
            }
447
        }
448
12
        true
449
41
    }
450
}
451

            
452
impl<T: Config> AuthorNotingHook<T::CollatorId> for Pallet<T> {
453
22432
    fn on_container_authors_noted(info: &[AuthorNotingInfo<T::CollatorId>]) -> Weight {
454
22432
        let mut total_weight = T::DbWeight::get().reads_writes(1, 0);
455
22430
        if let ActivityTrackingStatus::Enabled { start, end: _ } =
456
22432
            <CurrentActivityTrackingStatus<T>>::get()
457
        {
458
22430
            if start <= T::CurrentSessionIndex::session_index() {
459
44996
                for author_info in info {
460
22568
                    total_weight
461
22568
                        .saturating_accrue(Self::on_author_noted(author_info.author.clone()));
462
22568
                    total_weight.saturating_accrue(Self::on_chain_noted(author_info.para_id));
463
22568
                }
464
2
            }
465
2
        }
466
22432
        total_weight
467
22432
    }
468
    #[cfg(feature = "runtime-benchmarks")]
469
    fn prepare_worst_case_for_bench(_a: &T::CollatorId, _b: BlockNumber, _para_id: ParaId) {}
470
}