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
//! ExternalValidators pallet.
18
//!
19
//! A pallet to manage external validators for a solochain.
20
//!
21
//! ## Terminology
22
//!
23
//! - WhitelistedValidators: Fixed validators set by root/governance. Have priority over the external validators.
24
//!      Are not rewarded.
25
//! - ExternalValidators: Validators set using storage proofs from another blockchain. Can be disabled by setting
26
//!     `SkipExternalValidators` to true.
27
//!
28
//! Validators only change once per era. By default the era changes after a fixed number of sessions, but new eras
29
//! can be forced or disabled using a root extrinsic.
30
//!
31
//! The structure of this pallet and the concept of eras is inspired by `pallet_staking` from Polkadot.
32

            
33
#![cfg_attr(not(feature = "std"), no_std)]
34

            
35
pub use pallet::*;
36
use {
37
    frame_support::pallet_prelude::Weight,
38
    log::log,
39
    parity_scale_codec::{Decode, Encode, MaxEncodedLen},
40
    scale_info::TypeInfo,
41
    sp_runtime::{traits::Get, RuntimeDebug},
42
    sp_staking::SessionIndex,
43
    sp_std::{collections::btree_set::BTreeSet, vec::Vec},
44
    tp_traits::{
45
        ActiveEraInfo, EraIndex, EraIndexProvider, ExternalIndexProvider, InvulnerablesProvider,
46
        OnEraEnd, OnEraStart, ValidatorProvider,
47
    },
48
};
49

            
50
#[cfg(test)]
51
mod mock;
52

            
53
#[cfg(test)]
54
mod tests;
55

            
56
#[cfg(feature = "runtime-benchmarks")]
57
mod benchmarking;
58
pub mod weights;
59

            
60
82
#[frame_support::pallet]
61
pub mod pallet {
62
    pub use crate::weights::WeightInfo;
63

            
64
    #[cfg(feature = "runtime-benchmarks")]
65
    use frame_support::traits::Currency;
66
    use {
67
        super::*,
68
        frame_support::{
69
            pallet_prelude::*,
70
            traits::{EnsureOrigin, UnixTime, ValidatorRegistration},
71
            BoundedVec, DefaultNoBound,
72
        },
73
        frame_system::pallet_prelude::*,
74
        sp_runtime::{traits::Convert, SaturatedConversion},
75
        sp_std::vec::Vec,
76
    };
77

            
78
    /// Configure the pallet by specifying the parameters and types on which it depends.
79
    #[pallet::config]
80
    pub trait Config: frame_system::Config {
81
        /// Overarching event type.
82
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
83

            
84
        /// Origin that can dictate updating parameters of this pallet.
85
        type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
86

            
87
        /// Number of eras to keep in history.
88
        ///
89
        /// Following information is kept for eras in `[current_era -
90
        /// HistoryDepth, current_era]`: `ErasStartSessionIndex`
91
        ///
92
        /// Must be more than the number of eras delayed by session.
93
        /// I.e. active era must always be in history. I.e. `active_era >
94
        /// current_era - history_depth` must be guaranteed.
95
        ///
96
        /// If migrating an existing pallet from storage value to config value,
97
        /// this should be set to same value or greater as in storage.
98
        #[pallet::constant]
99
        type HistoryDepth: Get<u32>;
100

            
101
        /// Maximum number of whitelisted validators.
102
        #[pallet::constant]
103
        type MaxWhitelistedValidators: Get<u32>;
104

            
105
        /// Maximum number of external validators.
106
        #[pallet::constant]
107
        type MaxExternalValidators: Get<u32>;
108

            
109
        /// A stable ID for a validator.
110
        type ValidatorId: Member
111
            + Parameter
112
            + Ord
113
            + MaybeSerializeDeserialize
114
            + MaxEncodedLen
115
            + TryFrom<Self::AccountId>;
116

            
117
        /// A conversion from account ID to validator ID.
118
        ///
119
        /// Its cost must be at most one storage read.
120
        type ValidatorIdOf: Convert<Self::AccountId, Option<Self::ValidatorId>>;
121

            
122
        /// Validate a user is registered
123
        type ValidatorRegistration: ValidatorRegistration<Self::ValidatorId>;
124

            
125
        /// Time used for computing era duration.
126
        ///
127
        /// It is guaranteed to start being called from the first `on_finalize`. Thus value at
128
        /// genesis is not used.
129
        type UnixTime: UnixTime;
130

            
131
        /// Number of sessions per era.
132
        #[pallet::constant]
133
        type SessionsPerEra: Get<SessionIndex>;
134

            
135
        type OnEraStart: OnEraStart;
136
        type OnEraEnd: OnEraEnd;
137

            
138
        /// The weight information of this pallet.
139
        type WeightInfo: WeightInfo;
140

            
141
        #[cfg(feature = "runtime-benchmarks")]
142
        type Currency: Currency<Self::AccountId>
143
            + frame_support::traits::fungible::Balanced<Self::AccountId>;
144
    }
145

            
146
326
    #[pallet::pallet]
147
    pub struct Pallet<T>(_);
148

            
149
    /// Fixed validators set by root/governance. Have priority over the external validators.
150
4582
    #[pallet::storage]
151
    pub type WhitelistedValidators<T: Config> =
152
        StorageValue<_, BoundedVec<T::ValidatorId, T::MaxWhitelistedValidators>, ValueQuery>;
153

            
154
    /// Copy of `WhitelistedValidators` at the start of this active era.
155
    /// Used to check which validators we don't need to reward.
156
17096
    #[pallet::storage]
157
    pub type WhitelistedValidatorsActiveEra<T: Config> =
158
        StorageValue<_, BoundedVec<T::ValidatorId, T::MaxWhitelistedValidators>, ValueQuery>;
159

            
160
    /// Same as `WhitelistedValidatorsActiveEra` but only exists for a brief period of time when the
161
    /// next era has been planned but not enacted yet.
162
4042
    #[pallet::storage]
163
    pub type WhitelistedValidatorsActiveEraPending<T: Config> =
164
        StorageValue<_, BoundedVec<T::ValidatorId, T::MaxWhitelistedValidators>, ValueQuery>;
165

            
166
    /// Validators set using storage proofs from another blockchain. Ignored if `SkipExternalValidators` is true.
167
2768
    #[pallet::storage]
168
    pub type ExternalValidators<T: Config> =
169
        StorageValue<_, BoundedVec<T::ValidatorId, T::MaxExternalValidators>, ValueQuery>;
170

            
171
    /// Allow to disable external validators.
172
2692
    #[pallet::storage]
173
    pub type SkipExternalValidators<T: Config> = StorageValue<_, bool, ValueQuery>;
174

            
175
    /// The current era information, it is either ActiveEra or ActiveEra + 1 if the new era validators have been queued.
176
6908
    #[pallet::storage]
177
    pub type CurrentEra<T: Config> = StorageValue<_, EraIndex>;
178

            
179
    /// The active era information, it holds index and start.
180
24382
    #[pallet::storage]
181
    pub type ActiveEra<T: Config> = StorageValue<_, ActiveEraInfo>;
182

            
183
    /// The session index at which the era start for the last [`Config::HistoryDepth`] eras.
184
    ///
185
    /// Note: This tracks the starting session (i.e. session index when era start being active)
186
    /// for the eras in `[CurrentEra - HISTORY_DEPTH, CurrentEra]`.
187
4719
    #[pallet::storage]
188
    pub type ErasStartSessionIndex<T> = StorageMap<_, Twox64Concat, EraIndex, SessionIndex>;
189

            
190
    /// Mode of era forcing.
191
3066
    #[pallet::storage]
192
    pub type ForceEra<T> = StorageValue<_, Forcing, ValueQuery>;
193

            
194
    /// Latest received external index. This index can be a timestamp
195
    /// a set-id, an epoch or in general anything that identifies
196
    /// a particular set of validators selected at a given point in time
197
1678
    #[pallet::storage]
198
    pub type ExternalIndex<T> = StorageValue<_, u64, ValueQuery>;
199

            
200
    /// Pending external index to be applied in the upcoming era
201
2980
    #[pallet::storage]
202
    pub type PendingExternalIndex<T> = StorageValue<_, u64, ValueQuery>;
203

            
204
    /// Current external index attached to the latest validators
205
1496
    #[pallet::storage]
206
    pub type CurrentExternalIndex<T> = StorageValue<_, u64, ValueQuery>;
207

            
208
    #[pallet::genesis_config]
209
    #[derive(DefaultNoBound)]
210
    pub struct GenesisConfig<T: Config> {
211
        pub skip_external_validators: bool,
212
        pub whitelisted_validators: Vec<T::ValidatorId>,
213
        pub external_validators: Vec<T::ValidatorId>,
214
    }
215

            
216
368
    #[pallet::genesis_build]
217
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
218
531
        fn build(&self) {
219
531
            let duplicate_validators = self
220
531
                .whitelisted_validators
221
531
                .iter()
222
531
                // T::ValidatorId does not impl Ord or Hash so we cannot collect into set directly,
223
531
                // but we can check for duplicates if we encode them first.
224
902
                .map(|x| x.encode())
225
531
                .collect::<sp_std::collections::btree_set::BTreeSet<_>>();
226
531
            assert!(
227
531
                duplicate_validators.len() == self.whitelisted_validators.len(),
228
                "duplicate validators in genesis."
229
            );
230

            
231
531
            let bounded_validators = BoundedVec::<_, T::MaxWhitelistedValidators>::try_from(
232
531
                self.whitelisted_validators.clone(),
233
531
            )
234
531
            .expect("genesis validators are more than T::MaxWhitelistedValidators");
235
531

            
236
531
            let bounded_external_validators = BoundedVec::<_, T::MaxExternalValidators>::try_from(
237
531
                self.external_validators.clone(),
238
531
            )
239
531
            .expect("genesis external validators are more than T::MaxExternalValidators");
240
531

            
241
531
            <SkipExternalValidators<T>>::put(self.skip_external_validators);
242
531
            <WhitelistedValidators<T>>::put(&bounded_validators);
243
531
            <WhitelistedValidatorsActiveEra<T>>::put(&bounded_validators);
244
531
            <WhitelistedValidatorsActiveEraPending<T>>::put(&bounded_validators);
245
531
            <ExternalValidators<T>>::put(&bounded_external_validators);
246
531
        }
247
    }
248

            
249
    #[pallet::event]
250
826
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
251
    pub enum Event<T: Config> {
252
3
        /// A new whitelisted validator was added.
253
        WhitelistedValidatorAdded { account_id: T::AccountId },
254
1
        /// A whitelisted validator was removed.
255
        WhitelistedValidatorRemoved { account_id: T::AccountId },
256
14
        /// A new era has started.
257
        NewEra { era: EraIndex },
258
        /// A new force era mode was set.
259
        ForceEra { mode: Forcing },
260
4
        /// External validators were set.
261
        ExternalValidatorsSet {
262
            validators: Vec<T::ValidatorId>,
263
            external_index: u64,
264
        },
265
    }
266

            
267
16
    #[pallet::error]
268
    pub enum Error<T> {
269
        /// There are too many whitelisted validators.
270
        TooManyWhitelisted,
271
        /// Account is already whitelisted.
272
        AlreadyWhitelisted,
273
        /// Account is not whitelisted.
274
        NotWhitelisted,
275
        /// Account does not have keys registered
276
        NoKeysRegistered,
277
        /// Unable to derive validator id from account id
278
        UnableToDeriveValidatorId,
279
    }
280

            
281
    #[pallet::call]
282
    impl<T: Config> Pallet<T> {
283
        /// Allow to ignore external validators and use only whitelisted ones.
284
        ///
285
        /// The origin for this call must be the `UpdateOrigin`.
286
        #[pallet::call_index(0)]
287
        #[pallet::weight(T::WeightInfo::skip_external_validators())]
288
13
        pub fn skip_external_validators(origin: OriginFor<T>, skip: bool) -> DispatchResult {
289
13
            T::UpdateOrigin::ensure_origin(origin)?;
290

            
291
13
            <SkipExternalValidators<T>>::put(skip);
292
13

            
293
13
            Ok(())
294
        }
295

            
296
        /// Add a new account `who` to the list of `WhitelistedValidators`.
297
        ///
298
        /// The origin for this call must be the `UpdateOrigin`.
299
        #[pallet::call_index(1)]
300
        #[pallet::weight(T::WeightInfo::add_whitelisted(
301
			T::MaxWhitelistedValidators::get().saturating_sub(1),
302
		))]
303
30
        pub fn add_whitelisted(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
304
30
            T::UpdateOrigin::ensure_origin(origin)?;
305
            // don't let one unprepared validator ruin things for everyone.
306
29
            let maybe_validator_id = T::ValidatorIdOf::convert(who.clone())
307
29
                .filter(T::ValidatorRegistration::is_registered);
308

            
309
29
            let validator_id = maybe_validator_id.ok_or(Error::<T>::NoKeysRegistered)?;
310

            
311
28
            <WhitelistedValidators<T>>::try_mutate(|whitelisted| -> DispatchResult {
312
28
                if whitelisted.contains(&validator_id) {
313
1
                    Err(Error::<T>::AlreadyWhitelisted)?;
314
27
                }
315
27
                whitelisted
316
27
                    .try_push(validator_id.clone())
317
27
                    .map_err(|_| Error::<T>::TooManyWhitelisted)?;
318
26
                Ok(())
319
28
            })?;
320

            
321
26
            Self::deposit_event(Event::WhitelistedValidatorAdded { account_id: who });
322
26

            
323
26
            Ok(())
324
        }
325

            
326
        /// Remove an account `who` from the list of `WhitelistedValidators` collators.
327
        ///
328
        /// The origin for this call must be the `UpdateOrigin`.
329
        #[pallet::call_index(2)]
330
        #[pallet::weight(T::WeightInfo::remove_whitelisted(T::MaxWhitelistedValidators::get()))]
331
31
        pub fn remove_whitelisted(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
332
31
            T::UpdateOrigin::ensure_origin(origin)?;
333

            
334
30
            let validator_id = T::ValidatorIdOf::convert(who.clone())
335
30
                .ok_or(Error::<T>::UnableToDeriveValidatorId)?;
336

            
337
30
            <WhitelistedValidators<T>>::try_mutate(|whitelisted| -> DispatchResult {
338
30
                let pos = whitelisted
339
30
                    .iter()
340
33
                    .position(|x| x == &validator_id)
341
30
                    .ok_or(Error::<T>::NotWhitelisted)?;
342
29
                whitelisted.remove(pos);
343
29
                Ok(())
344
30
            })?;
345

            
346
29
            Self::deposit_event(Event::WhitelistedValidatorRemoved { account_id: who });
347
29
            Ok(())
348
        }
349

            
350
        /// Force when the next era will start. Possible values: next session, never, same as always.
351
        #[pallet::call_index(3)]
352
        #[pallet::weight(T::WeightInfo::force_era())]
353
6
        pub fn force_era(origin: OriginFor<T>, mode: Forcing) -> DispatchResult {
354
6
            T::UpdateOrigin::ensure_origin(origin)?;
355
6
            Self::set_force_era(mode);
356
6
            Ok(())
357
        }
358

            
359
        /// Manually set external validators. Should only be needed for tests, validators are set
360
        /// automatically by the bridge.
361
        #[pallet::call_index(4)]
362
        #[pallet::weight(T::WeightInfo::set_external_validators())]
363
        pub fn set_external_validators(
364
            origin: OriginFor<T>,
365
            validators: Vec<T::ValidatorId>,
366
            external_index: u64,
367
        ) -> DispatchResult {
368
            T::UpdateOrigin::ensure_origin(origin)?;
369

            
370
            Self::set_external_validators_inner(validators, external_index)
371
        }
372
    }
373

            
374
    impl<T: Config> Pallet<T> {
375
56
        pub fn set_external_validators_inner(
376
56
            validators: Vec<T::ValidatorId>,
377
56
            external_index: u64,
378
56
        ) -> DispatchResult {
379
56
            // If more validators than max, take the first n
380
56
            let validators = BoundedVec::truncate_from(validators);
381
56
            <ExternalValidators<T>>::put(&validators);
382
56
            <ExternalIndex<T>>::put(external_index);
383
56

            
384
56
            Self::deposit_event(Event::<T>::ExternalValidatorsSet {
385
56
                validators: validators.into_inner(),
386
56
                external_index,
387
56
            });
388
56
            Ok(())
389
56
        }
390

            
391
        /// Helper to set a new `ForceEra` mode.
392
8
        pub(crate) fn set_force_era(mode: Forcing) {
393
8
            log::info!("Setting force era mode {:?}.", mode);
394
8
            ForceEra::<T>::put(mode);
395
8
            Self::deposit_event(Event::<T>::ForceEra { mode });
396
8
        }
397

            
398
60
        pub fn whitelisted_validators() -> Vec<T::ValidatorId> {
399
60
            <WhitelistedValidators<T>>::get().into()
400
60
        }
401

            
402
2019
        pub fn active_era() -> Option<ActiveEraInfo> {
403
2019
            <ActiveEra<T>>::get()
404
2019
        }
405

            
406
1888
        pub fn current_era() -> Option<EraIndex> {
407
1888
            <CurrentEra<T>>::get()
408
1888
        }
409

            
410
3288
        pub fn eras_start_session_index(era: EraIndex) -> Option<u32> {
411
3288
            <ErasStartSessionIndex<T>>::get(era)
412
3288
        }
413

            
414
        /// Returns validators for the next session. Whitelisted validators first, then external validators.
415
        /// The returned list is deduplicated, but the order is respected.
416
        /// If `SkipExternalValidators` is true, this function will ignore external validators.
417
802
        pub fn validators() -> Vec<T::ValidatorId> {
418
802
            let mut validators: Vec<_> = WhitelistedValidators::<T>::get().into();
419
802

            
420
802
            if !SkipExternalValidators::<T>::get() {
421
797
                validators.extend(ExternalValidators::<T>::get())
422
5
            }
423

            
424
802
            remove_duplicates(validators)
425
802
        }
426

            
427
        /// Plan a new session potentially trigger a new era.
428
1804
        pub(crate) fn new_session(session_index: SessionIndex) -> Option<Vec<T::ValidatorId>> {
429
1804
            if let Some(current_era) = Self::current_era() {
430
                // Initial era has been set.
431
1273
                let current_era_start_session_index = Self::eras_start_session_index(current_era)
432
1273
                    .unwrap_or_else(|| {
433
                        frame_support::print(
434
                            "Error: start_session_index must be set for current_era",
435
                        );
436
                        0
437
1273
                    });
438
1273

            
439
1273
                let era_length = session_index.saturating_sub(current_era_start_session_index); // Must never happen.
440

            
441
1257
                match ForceEra::<T>::get() {
442
                    // Will be set to `NotForcing` again if a new era has been triggered.
443
2
                    Forcing::ForceNew => (),
444
                    // Short circuit to `try_trigger_new_era`.
445
8
                    Forcing::ForceAlways => (),
446
                    // Only go to `try_trigger_new_era` if deadline reached.
447
1257
                    Forcing::NotForcing if era_length >= T::SessionsPerEra::get() => (),
448
                    _ => {
449
                        // Either `Forcing::ForceNone`,
450
                        // or `Forcing::NotForcing if era_length < T::SessionsPerEra::get()`.
451
1021
                        return None;
452
                    }
453
                }
454

            
455
                // New era.
456
252
                let maybe_new_era_validators = Self::try_trigger_new_era(session_index);
457
252
                if maybe_new_era_validators.is_some()
458
252
                    && matches!(ForceEra::<T>::get(), Forcing::ForceNew)
459
2
                {
460
2
                    Self::set_force_era(Forcing::NotForcing);
461
250
                }
462

            
463
252
                maybe_new_era_validators
464
            } else {
465
                // Set initial era.
466
531
                log!(log::Level::Debug, "Starting the first era.");
467
531
                Self::try_trigger_new_era(session_index)
468
            }
469
1804
        }
470

            
471
        /// Start a session potentially starting an era.
472
1273
        pub(crate) fn start_session(start_session: SessionIndex) {
473
1273
            let next_active_era = Self::active_era()
474
1273
                .map(|e| e.index.saturating_add(1))
475
1273
                .unwrap_or(0);
476
            // This is only `Some` when current era has already progressed to the next era, while the
477
            // active era is one behind (i.e. in the *last session of the active era*, or *first session
478
            // of the new current era*, depending on how you look at it).
479
707
            if let Some(next_active_era_start_session_index) =
480
1273
                Self::eras_start_session_index(next_active_era)
481
            {
482
707
                if next_active_era_start_session_index == start_session {
483
707
                    Self::start_era(start_session);
484
707
                } else if next_active_era_start_session_index < start_session {
485
                    // This arm should never happen, but better handle it than to stall the pallet.
486
                    frame_support::print("Warning: A session appears to have been skipped.");
487
                    Self::start_era(start_session);
488
                }
489
566
            }
490
1273
        }
491

            
492
        /// End a session potentially ending an era.
493
742
        pub(crate) fn end_session(session_index: SessionIndex) {
494
742
            if let Some(active_era) = Self::active_era() {
495
176
                if let Some(next_active_era_start_session_index) =
496
742
                    Self::eras_start_session_index(active_era.index.saturating_add(1))
497
                {
498
176
                    if next_active_era_start_session_index == session_index.saturating_add(1) {
499
176
                        Self::end_era(active_era, session_index);
500
176
                    }
501
566
                }
502
            }
503
742
        }
504

            
505
        /// Start a new era. It does:
506
        /// * Increment `active_era.index`,
507
        /// * reset `active_era.start`,
508
        /// * emit `NewEra` event,
509
        /// * call `OnEraStart` hook,
510
707
        pub(crate) fn start_era(start_session: SessionIndex) {
511
707
            let active_era = ActiveEra::<T>::mutate(|active_era| {
512
707
                let new_index = active_era
513
707
                    .as_ref()
514
707
                    .map(|info| info.index.saturating_add(1))
515
707
                    .unwrap_or(0);
516
707
                *active_era = Some(ActiveEraInfo {
517
707
                    index: new_index,
518
707
                    // Set new active era start in next `on_finalize`. To guarantee usage of `Time`
519
707
                    start: None,
520
707
                });
521
707
                new_index
522
707
            });
523
707
            WhitelistedValidatorsActiveEra::<T>::put(
524
707
                WhitelistedValidatorsActiveEraPending::<T>::take(),
525
707
            );
526
707
            let external_idx = PendingExternalIndex::<T>::take();
527
707
            CurrentExternalIndex::<T>::put(external_idx);
528
707
            Self::deposit_event(Event::NewEra { era: active_era });
529
707
            T::OnEraStart::on_era_start(active_era, start_session, external_idx);
530
707
        }
531

            
532
        /// End era. It does:
533
        /// * call `OnEraEnd` hook,
534
176
        pub(crate) fn end_era(active_era: ActiveEraInfo, _session_index: SessionIndex) {
535
176
            // Note: active_era.start can be None if end era is called during genesis config.
536
176
            T::OnEraEnd::on_era_end(active_era.index);
537
176
        }
538

            
539
        /// Plan a new era.
540
        ///
541
        /// * Bump the current era storage (which holds the latest planned era).
542
        /// * Store start session index for the new planned era.
543
        /// * Clean old era information.
544
        ///
545
        /// Returns the new validator set.
546
783
        pub fn trigger_new_era(start_session_index: SessionIndex) -> Vec<T::ValidatorId> {
547
783
            // Increment or set current era.
548
783
            let new_planned_era = CurrentEra::<T>::mutate(|s| {
549
783
                *s = Some(s.map(|s| s.saturating_add(1)).unwrap_or(0));
550
783
                s.unwrap()
551
783
            });
552
783
            ErasStartSessionIndex::<T>::insert(&new_planned_era, &start_session_index);
553

            
554
            // Clean old era information.
555
            if let Some(old_era) =
556
783
                new_planned_era.checked_sub(T::HistoryDepth::get().saturating_add(1))
557
            {
558
                Self::clear_era_information(old_era);
559
783
            }
560

            
561
            // Save whitelisted validators for when the era truly changes (start_era)
562
783
            WhitelistedValidatorsActiveEraPending::<T>::put(WhitelistedValidators::<T>::get());
563
783
            // Save the external index for when the era truly changes (start_era)
564
783
            PendingExternalIndex::<T>::put(ExternalIndex::<T>::get());
565
783

            
566
783
            // Returns new validators
567
783
            Self::validators()
568
783
        }
569

            
570
        /// Potentially plan a new era.
571
        ///
572
        /// In case a new era is planned, the new validator set is returned.
573
783
        pub(crate) fn try_trigger_new_era(
574
783
            start_session_index: SessionIndex,
575
783
        ) -> Option<Vec<T::ValidatorId>> {
576
783
            Some(Self::trigger_new_era(start_session_index))
577
783
        }
578

            
579
        /// Clear all era information for given era.
580
        pub(crate) fn clear_era_information(era_index: EraIndex) {
581
            ErasStartSessionIndex::<T>::remove(era_index);
582
        }
583
    }
584

            
585
669
    #[pallet::hooks]
586
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
587
333
        fn on_initialize(_now: BlockNumberFor<T>) -> Weight {
588
333
            // just return the weight of the on_finalize.
589
333
            T::DbWeight::get().reads(1)
590
333
        }
591

            
592
333
        fn on_finalize(_n: BlockNumberFor<T>) {
593
            // Set the start of the first era.
594
333
            if let Some(mut active_era) = <ActiveEra<T>>::get() {
595
333
                if active_era.start.is_none() {
596
23
                    let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::<u64>();
597
23
                    active_era.start = Some(now_as_millis_u64);
598
23
                    // This write only ever happens once, we don't include it in the weight in
599
23
                    // general
600
23
                    ActiveEra::<T>::put(active_era);
601
310
                }
602
            }
603
            // `on_finalize` weight is tracked in `on_initialize`
604
333
        }
605
    }
606

            
607
    impl<T: Config> ExternalIndexProvider for Pallet<T> {
608
41
        fn get_external_index() -> u64 {
609
41
            CurrentExternalIndex::<T>::get()
610
41
        }
611
    }
612
}
613

            
614
/// Keeps only the first instance of each element in the input vec. Respects ordering of elements.
615
802
fn remove_duplicates<T: Ord + Clone>(input: Vec<T>) -> Vec<T> {
616
802
    let mut seen = BTreeSet::new();
617
802
    let mut result = Vec::with_capacity(input.len());
618

            
619
2443
    for item in input {
620
1641
        if seen.insert(item.clone()) {
621
1634
            result.push(item);
622
1634
        }
623
    }
624

            
625
802
    result
626
802
}
627

            
628
impl<T: Config> pallet_session::SessionManager<T::ValidatorId> for Pallet<T> {
629
1772
    fn new_session(new_index: SessionIndex) -> Option<Vec<T::ValidatorId>> {
630
1772
        log!(log::Level::Trace, "planning new session {}", new_index);
631
1772
        Self::new_session(new_index)
632
1772
    }
633
32
    fn new_session_genesis(new_index: SessionIndex) -> Option<Vec<T::ValidatorId>> {
634
32
        log!(
635
32
            log::Level::Trace,
636
            "planning new session {} at genesis",
637
            new_index
638
        );
639
32
        Self::new_session(new_index)
640
32
    }
641
1273
    fn start_session(start_index: SessionIndex) {
642
1273
        log!(log::Level::Trace, "starting session {}", start_index);
643
1273
        Self::start_session(start_index)
644
1273
    }
645
742
    fn end_session(end_index: SessionIndex) {
646
742
        log!(log::Level::Trace, "ending session {}", end_index);
647
742
        Self::end_session(end_index)
648
742
    }
649
}
650

            
651
impl<T: Config> pallet_session::historical::SessionManager<T::ValidatorId, ()> for Pallet<T> {
652
1708
    fn new_session(new_index: SessionIndex) -> Option<Vec<(T::ValidatorId, ())>> {
653
1708
        <Self as pallet_session::SessionManager<_>>::new_session(new_index)
654
1744
            .map(|r| r.into_iter().map(|v| (v, Default::default())).collect())
655
1708
    }
656

            
657
1193
    fn start_session(start_index: SessionIndex) {
658
1193
        <Self as pallet_session::SessionManager<_>>::start_session(start_index)
659
1193
    }
660

            
661
678
    fn end_session(end_index: SessionIndex) {
662
678
        <Self as pallet_session::SessionManager<_>>::end_session(end_index)
663
678
    }
664
}
665

            
666
impl<T: Config> EraIndexProvider for Pallet<T> {
667
8402
    fn active_era() -> ActiveEraInfo {
668
8402
        <ActiveEra<T>>::get().unwrap_or(ActiveEraInfo {
669
8402
            index: 0,
670
8402
            start: None,
671
8402
        })
672
8402
    }
673

            
674
648
    fn era_to_session_start(era_index: EraIndex) -> Option<u32> {
675
648
        <ErasStartSessionIndex<T>>::get(era_index)
676
648
    }
677
}
678

            
679
impl<T: Config> ValidatorProvider<T::ValidatorId> for Pallet<T> {
680
1
    fn validators() -> Vec<T::ValidatorId> {
681
1
        Self::validators()
682
1
    }
683
}
684

            
685
impl<T: Config> InvulnerablesProvider<T::ValidatorId> for Pallet<T> {
686
24
    fn invulnerables() -> Vec<T::ValidatorId> {
687
24
        Self::whitelisted_validators()
688
24
    }
689
}
690

            
691
/// Mode of era-forcing.
692
#[derive(
693
    Copy, Clone, PartialEq, Eq, Default, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen,
694
)]
695
pub enum Forcing {
696
10
    /// Not forcing anything - just let whatever happen.
697
    #[default]
698
    NotForcing,
699
4
    /// Force a new era on the next session start, then reset to `NotForcing` as soon as it is done.
700
    ForceNew,
701
6
    /// Avoid a new era indefinitely.
702
    ForceNone,
703
16
    /// Force a new era at the end of all sessions indefinitely.
704
    ForceAlways,
705
}