-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
327 lines (261 loc) · 9.62 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//! # Validator Set Pallet
//!
//! The Validator Set Pallet allows addition and removal of
//! authorities/validators via extrinsics (transaction calls), in
//! Substrate-based PoA networks. It also integrates with the im-online pallet
//! to automatically remove offline validators.
//!
//! The pallet depends on the Session pallet and implements related traits for session
//! management. Currently it uses periodic session rotation provided by the
//! session pallet to automatically rotate sessions. For this reason, the
//! validator addition and removal becomes effective only after 2 sessions
//! (queuing + applying).
#![cfg_attr(not(feature = "std"), no_std)]
mod benchmarking;
// #[cfg(test)]
// mod mock;
// #[cfg(test)]
// mod tests;
pub mod weights;
use frame_system::pallet_prelude::*;
use frame_support::{
ensure,
pallet_prelude::*,
traits::{EstimateNextSessionRotation, Get, ValidatorSet, ValidatorSetWithIdentification},
DefaultNoBound,
};
use log;
pub use pallet::*;
use pallet_babe::Committee;
use sp_runtime::traits::{Convert, Zero};
use sp_staking::offence::{Offence, OffenceError, ReportOffence};
use sp_std::prelude::*;
pub use weights::*;
pub const LOG_TARGET: &'static str = "runtime::validator-set";
#[frame_support::pallet()]
pub mod pallet {
use super::*;
/// Configure the pallet by specifying the parameters and types on which it
/// depends.
#[pallet::config]
pub trait Config: frame_system::Config + pallet_session::Config {
/// The Event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Origin for adding or removing a validator.
type AddRemoveOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Minimum number of validators to leave in the validator set during
/// auto removal.
type MinAuthorities: Get<u32>;
/// Information on runtime weights.
type WeightInfo: WeightInfo;
}
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::storage]
#[pallet::getter(fn committee)]
pub type Committee<T: Config> = StorageValue<_, Vec<(T::AccountId, u64)>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn validators)]
pub type Validators<T: Config> = StorageValue<_, Vec<T::ValidatorId>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn offline_validators)]
pub type OfflineValidators<T: Config> = StorageValue<_, Vec<T::ValidatorId>, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// New validator addition initiated. Effective in ~2 sessions.
ValidatorAdditionInitiated(T::ValidatorId),
/// Validator removal initiated. Effective in ~2 sessions.
ValidatorRemovalInitiated(T::ValidatorId),
}
// Errors inform users that something went wrong.
#[pallet::error]
pub enum Error<T> {
/// Target (post-removal) validator count is below the minimum.
TooLowValidatorCount,
/// Validator is already in the validator set.
Duplicate,
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::genesis_config]
// #[derive(DefaultNoBound)]
pub struct GenesisConfig<T: Config> {
// pub initial_validators: Vec<T::ValidatorId>,
pub initial_committee: Vec<T::AccountId>,
}
impl<T: Config> Default for GenesisConfig<T>{
fn default() -> Self{
Self{
initial_committee: Default::default()
}
}
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
fn build(&self) {
// Pallet::<T>::initialize_validators(&self.initial_validators);
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Add a new validator.
///
/// New validator's session keys should be set in Session pallet before
/// calling this.
///
/// The origin can be configured using the `AddRemoveOrigin` type in the
/// host runtime. Can also be set to sudo/root.
#[pallet::call_index(0)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::add_validator())]
pub fn add_validator(origin: OriginFor<T>, validator_id: T::ValidatorId) -> DispatchResult {
T::AddRemoveOrigin::ensure_origin(origin)?;
Self::do_add_validator(validator_id.clone())?;
Ok(())
}
/// Remove a validator.
///
/// The origin can be configured using the `AddRemoveOrigin` type in the
/// host runtime. Can also be set to sudo/root.
#[pallet::call_index(1)]
#[pallet::weight(<T as pallet::Config>::WeightInfo::remove_validator())]
pub fn remove_validator(
origin: OriginFor<T>,
validator_id: T::ValidatorId,
) -> DispatchResult {
T::AddRemoveOrigin::ensure_origin(origin)?;
Self::do_remove_validator(validator_id.clone())?;
Ok(())
}
}
}
impl<T: Config> Pallet<T> {
fn initialize_validators(validators: &[T::ValidatorId]) {
assert!(
validators.len() as u32 >= T::MinAuthorities::get(),
"Initial set of validators must be at least T::MinAuthorities"
);
assert!(<Validators<T>>::get().is_empty(), "Validators are already initialized!");
<Validators<T>>::put(validators);
}
fn do_add_validator(validator_id: T::ValidatorId) -> DispatchResult {
ensure!(!<Validators<T>>::get().contains(&validator_id), Error::<T>::Duplicate);
<Validators<T>>::mutate(|v| v.push(validator_id.clone()));
Self::deposit_event(Event::ValidatorAdditionInitiated(validator_id.clone()));
log::debug!(target: LOG_TARGET, "Validator addition initiated.");
Ok(())
}
fn do_remove_validator(validator_id: T::ValidatorId) -> DispatchResult {
let mut validators = <Validators<T>>::get();
// Ensuring that the post removal, target validator count doesn't go
// below the minimum.
ensure!(
validators.len().saturating_sub(1) as u32 >= T::MinAuthorities::get(),
Error::<T>::TooLowValidatorCount
);
validators.retain(|v| *v != validator_id);
<Validators<T>>::put(validators);
Self::deposit_event(Event::ValidatorRemovalInitiated(validator_id.clone()));
log::debug!(target: LOG_TARGET, "Validator removal initiated.");
Ok(())
}
// Adds offline validators to a local cache for removal on new session.
fn mark_for_removal(validator_id: T::ValidatorId) {
<OfflineValidators<T>>::mutate(|v| v.push(validator_id));
log::debug!(target: LOG_TARGET, "Offline validator marked for auto removal.");
}
// Removes offline validators from the validator set and clears the offline
// cache. It is called in the session change hook and removes the validators
// who were reported offline during the session that is ending. We do not
// check for `MinAuthorities` here, because the offline validators will not
// produce blocks and will have the same overall effect on the runtime.
fn remove_offline_validators() {
let validators_to_remove = <OfflineValidators<T>>::get();
// Delete from active validator set.
<Validators<T>>::mutate(|vs| vs.retain(|v| !validators_to_remove.contains(v)));
log::debug!(
target: LOG_TARGET,
"Initiated removal of {:?} offline validators.",
validators_to_remove.len()
);
// Clear the offline validator list to avoid repeated deletion.
<OfflineValidators<T>>::put(Vec::<T::ValidatorId>::new());
}
}
// Provides the new set of validators to the session module when session is
// being rotated.
impl<T: Config> pallet_session::SessionManager<T::ValidatorId> for Pallet<T> {
// Plan a new session and provide new validator set.
fn new_session(_new_index: u32) -> Option<Vec<T::ValidatorId>> {
// Remove any offline validators. This will only work when the runtime
// also has the im-online pallet.
Self::remove_offline_validators();
log::debug!(target: LOG_TARGET, "New session called; updated validator set provided.");
Some(Self::validators())
}
fn end_session(_end_index: u32) {}
fn start_session(_start_index: u32) {}
}
impl<T: Config> EstimateNextSessionRotation<BlockNumberFor<T>> for Pallet<T> {
fn average_session_length() -> BlockNumberFor<T> {
Zero::zero()
}
fn estimate_current_session_progress(
_now: BlockNumberFor<T>,
) -> (Option<sp_runtime::Permill>, sp_weights::Weight) {
(None, Zero::zero())
}
fn estimate_next_session_rotation(
_now: BlockNumberFor<T>,
) -> (Option<BlockNumberFor<T>>, sp_weights::Weight) {
(None, Zero::zero())
}
}
// Implementation of Convert trait to satisfy trait bounds in session pallet.
// Here it just returns the same ValidatorId.
pub struct ValidatorOf<T>(sp_std::marker::PhantomData<T>);
impl<T: Config> Convert<T::ValidatorId, Option<T::ValidatorId>> for ValidatorOf<T> {
fn convert(account: T::ValidatorId) -> Option<T::ValidatorId> {
Some(account)
}
}
impl<T: Config> ValidatorSet<T::ValidatorId> for Pallet<T> {
type ValidatorId = T::ValidatorId;
type ValidatorIdOf = ValidatorOf<T>;
fn session_index() -> sp_staking::SessionIndex {
pallet_session::Pallet::<T>::current_index()
}
fn validators() -> Vec<T::ValidatorId> {
pallet_session::Pallet::<T>::validators()
}
}
impl<T: Config> ValidatorSetWithIdentification<T::ValidatorId> for Pallet<T> {
type Identification = T::ValidatorId;
type IdentificationOf = ValidatorOf<T>;
}
// Offence reporting and unresponsiveness management.
// This is for the ImOnline pallet integration.
impl<T: Config, O: Offence<(T::ValidatorId, T::ValidatorId)>>
ReportOffence<T::AccountId, (T::ValidatorId, T::ValidatorId), O> for Pallet<T>
{
fn report_offence(_reporters: Vec<T::AccountId>, offence: O) -> Result<(), OffenceError> {
let offenders = offence.offenders();
for (v, _) in offenders.into_iter() {
Self::mark_for_removal(v);
}
Ok(())
}
fn is_known_offence(
_offenders: &[(T::ValidatorId, T::ValidatorId)],
_time_slot: &O::TimeSlot,
) -> bool {
false
}
}
impl<T: Config> pallet_babe::Committee<T::AccountId> for Pallet<T>{
fn get_new_committee() -> Option<Vec<(T::AccountId, u64)>> {
let mut com_vec = Default::default();
return com_vec;
}
}