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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#![cfg_attr(not(feature = "std"), no_std)]
use frame_support::traits::OneSessionHandler;
use sp_authority_discovery::AuthorityId;
use sp_std::prelude::*;
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + pallet_session::Config {}
#[pallet::storage]
#[pallet::getter(fn keys)]
pub(super) type Keys<T: Config> = StorageValue<_, Vec<AuthorityId>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn next_keys)]
pub(super) type NextKeys<T: Config> = StorageValue<_, Vec<AuthorityId>, ValueQuery>;
#[pallet::genesis_config]
pub struct GenesisConfig {
pub keys: Vec<AuthorityId>,
}
#[cfg(feature = "std")]
impl Default for GenesisConfig {
fn default() -> Self {
Self { keys: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig {
fn build(&self) {
Pallet::<T>::initialize_keys(&self.keys)
}
}
}
impl<T: Config> Pallet<T> {
pub fn authorities() -> Vec<AuthorityId> {
let mut keys = Keys::<T>::get();
let next = NextKeys::<T>::get();
keys.extend(next);
keys.sort();
keys.dedup();
keys
}
pub fn current_authorities() -> Vec<AuthorityId> {
Keys::<T>::get()
}
pub fn next_authorities() -> Vec<AuthorityId> {
NextKeys::<T>::get()
}
fn initialize_keys(keys: &[AuthorityId]) {
if !keys.is_empty() {
assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
Keys::<T>::put(keys);
NextKeys::<T>::put(keys);
}
}
}
impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
type Public = AuthorityId;
}
impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
type Key = AuthorityId;
fn on_genesis_session<'a, I: 'a>(authorities: I)
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
Self::initialize_keys(&authorities.map(|x| x.1).collect::<Vec<_>>());
}
fn on_new_session<'a, I: 'a>(changed: bool, validators: I, queued_validators: I)
where
I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{
if changed {
let keys = validators.map(|x| x.1);
Keys::<T>::put(keys.collect::<Vec<_>>());
let next_keys = queued_validators.map(|x| x.1);
NextKeys::<T>::put(next_keys.collect::<Vec<_>>());
}
}
fn on_disabled(_i: usize) {
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate as pallet_authority_discovery;
use frame_support::{parameter_types, traits::GenesisBuild};
use sp_application_crypto::Pair;
use sp_authority_discovery::AuthorityPair;
use sp_core::{crypto::key_types, H256};
use sp_io::TestExternalities;
use sp_runtime::{
testing::{Header, UintAuthorityId},
traits::{ConvertInto, IdentityLookup, OpaqueKeys},
KeyTypeId, Perbill,
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},
AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config},
}
);
impl Config for Test {}
parameter_types! {
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33);
}
impl pallet_session::Config for Test {
type SessionManager = ();
type Keys = UintAuthorityId;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type SessionHandler = TestSessionHandler;
type Event = Event;
type ValidatorId = AuthorityId;
type ValidatorIdOf = ConvertInto;
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;
type WeightInfo = ();
}
impl pallet_session::historical::Config for Test {
type FullIdentification = ();
type FullIdentificationOf = ();
}
pub type BlockNumber = u64;
parameter_types! {
pub const Period: BlockNumber = 1;
pub const Offset: BlockNumber = 0;
pub const UncleGenerations: u64 = 0;
pub const BlockHashCount: u64 = 250;
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(1024);
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Index = u64;
type BlockNumber = BlockNumber;
type Call = Call;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AuthorityId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
}
pub struct TestSessionHandler;
impl pallet_session::SessionHandler<AuthorityId> for TestSessionHandler {
const KEY_TYPE_IDS: &'static [KeyTypeId] = &[key_types::DUMMY];
fn on_new_session<Ks: OpaqueKeys>(
_changed: bool,
_validators: &[(AuthorityId, Ks)],
_queued_validators: &[(AuthorityId, Ks)],
) {
}
fn on_disabled(_validator_index: usize) {}
fn on_genesis_session<Ks: OpaqueKeys>(_validators: &[(AuthorityId, Ks)]) {}
}
#[test]
fn authorities_returns_current_and_next_authority_set() {
let account_id = AuthorityPair::from_seed_slice(vec![10; 32].as_ref()).unwrap().public();
let mut first_authorities: Vec<AuthorityId> = vec![0, 1]
.into_iter()
.map(|i| AuthorityPair::from_seed_slice(vec![i; 32].as_ref()).unwrap().public())
.map(AuthorityId::from)
.collect();
let second_authorities: Vec<AuthorityId> = vec![2, 3]
.into_iter()
.map(|i| AuthorityPair::from_seed_slice(vec![i; 32].as_ref()).unwrap().public())
.map(AuthorityId::from)
.collect();
let second_authorities_and_account_ids = second_authorities
.clone()
.into_iter()
.map(|id| (&account_id, id))
.collect::<Vec<(&AuthorityId, AuthorityId)>>();
let mut third_authorities: Vec<AuthorityId> = vec![4, 5]
.into_iter()
.map(|i| AuthorityPair::from_seed_slice(vec![i; 32].as_ref()).unwrap().public())
.map(AuthorityId::from)
.collect();
let third_authorities_and_account_ids = third_authorities
.clone()
.into_iter()
.map(|id| (&account_id, id))
.collect::<Vec<(&AuthorityId, AuthorityId)>>();
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
GenesisBuild::<Test>::assimilate_storage(
&pallet_authority_discovery::GenesisConfig { keys: vec![] },
&mut t,
)
.unwrap();
let mut externalities = TestExternalities::new(t);
externalities.execute_with(|| {
use frame_support::traits::OneSessionHandler;
AuthorityDiscovery::on_genesis_session(
first_authorities.iter().map(|id| (id, id.clone())),
);
first_authorities.sort();
let mut authorities_returned = AuthorityDiscovery::authorities();
authorities_returned.sort();
assert_eq!(first_authorities, authorities_returned);
AuthorityDiscovery::on_new_session(
false,
second_authorities_and_account_ids.clone().into_iter(),
third_authorities_and_account_ids.clone().into_iter(),
);
let authorities_returned = AuthorityDiscovery::authorities();
assert_eq!(
first_authorities, authorities_returned,
"Expected authority set not to change as `changed` was set to false.",
);
AuthorityDiscovery::on_new_session(
true,
second_authorities_and_account_ids.into_iter(),
third_authorities_and_account_ids.clone().into_iter(),
);
let mut second_and_third_authorities = second_authorities
.iter()
.chain(third_authorities.iter())
.cloned()
.collect::<Vec<AuthorityId>>();
second_and_third_authorities.sort();
assert_eq!(
second_and_third_authorities,
AuthorityDiscovery::authorities(),
"Expected authority set to contain both the authorities of the new as well as the \
next session."
);
AuthorityDiscovery::on_new_session(
true,
third_authorities_and_account_ids.clone().into_iter(),
third_authorities_and_account_ids.clone().into_iter(),
);
third_authorities.sort();
assert_eq!(
third_authorities,
AuthorityDiscovery::authorities(),
"Expected authority set to be deduplicated."
);
});
}
}