use frame_support::pallet_prelude::*;
use primitives::v2::{SessionIndex, ValidatorId, ValidatorIndex};
use sp_std::vec::Vec;
use rand::{seq::SliceRandom, SeedableRng};
use rand_chacha::ChaCha20Rng;
use crate::configuration::HostConfiguration;
pub use pallet::*;
pub(crate) const SESSION_DELAY: SessionIndex = 2;
#[cfg(test)]
mod tests;
#[frame_support::pallet]
pub mod pallet {
use super::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {}
#[pallet::storage]
#[pallet::getter(fn session_index)]
pub(super) type CurrentSessionIndex<T: Config> = StorageValue<_, SessionIndex, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn active_validator_indices)]
pub(super) type ActiveValidatorIndices<T: Config> =
StorageValue<_, Vec<ValidatorIndex>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn active_validator_keys)]
pub(super) type ActiveValidatorKeys<T: Config> = StorageValue<_, Vec<ValidatorId>, ValueQuery>;
#[pallet::call]
impl<T: Config> Pallet<T> {}
}
impl<T: Config> Pallet<T> {
pub(crate) fn initializer_initialize(_now: T::BlockNumber) -> Weight {
Weight::zero()
}
pub(crate) fn initializer_finalize() {}
pub(crate) fn initializer_on_new_session(
session_index: SessionIndex,
random_seed: [u8; 32],
new_config: &HostConfiguration<T::BlockNumber>,
all_validators: Vec<ValidatorId>,
) -> Vec<ValidatorId> {
CurrentSessionIndex::<T>::set(session_index);
let mut rng: ChaCha20Rng = SeedableRng::from_seed(random_seed);
let mut shuffled_indices: Vec<_> = (0..all_validators.len())
.enumerate()
.map(|(i, _)| ValidatorIndex(i as _))
.collect();
shuffled_indices.shuffle(&mut rng);
if let Some(max) = new_config.max_validators {
shuffled_indices.truncate(max as usize);
}
let active_validator_keys =
crate::util::take_active_subset(&shuffled_indices, &all_validators);
ActiveValidatorIndices::<T>::set(shuffled_indices);
ActiveValidatorKeys::<T>::set(active_validator_keys.clone());
active_validator_keys
}
pub fn scheduled_session() -> SessionIndex {
Self::session_index().saturating_add(SESSION_DELAY)
}
#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
pub fn set_session_index(index: SessionIndex) {
CurrentSessionIndex::<T>::set(index);
}
#[cfg(any(feature = "runtime-benchmarks", test))]
pub(crate) fn set_active_validators_ascending(active: Vec<ValidatorId>) {
ActiveValidatorIndices::<T>::set(
(0..active.len()).map(|i| ValidatorIndex(i as _)).collect(),
);
ActiveValidatorKeys::<T>::set(active);
}
#[cfg(test)]
pub(crate) fn set_active_validators_with_indices(
indices: Vec<ValidatorIndex>,
keys: Vec<ValidatorId>,
) {
assert_eq!(indices.len(), keys.len());
ActiveValidatorIndices::<T>::set(indices);
ActiveValidatorKeys::<T>::set(keys);
}
}