Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit cc4bf91

Browse files
koushirogui1117
andauthored
pallet-session: Migrate the historical part to the new pallet macro (#9878)
* Migrate session-historical to the new pallet macro Signed-off-by: koushiro <[email protected]> * pallet-session: Migrate the historical part to the new pallet macro Signed-off-by: koushiro <[email protected]> * Fix staking test runtime Signed-off-by: koushiro <[email protected]> * Update frame/session/src/historical/mod.rs * Update frame/session/src/historical/mod.rs * update migration doc Signed-off-by: koushiro <[email protected]> * use hardcoded prefix for migration v1 Signed-off-by: koushiro <[email protected]> * cargo +nightly-2021-11-08 fmt Signed-off-by: koushiro <[email protected]> Co-authored-by: Guillaume Thiolliere <[email protected]>
1 parent 9a00c43 commit cc4bf91

File tree

8 files changed

+325
-66
lines changed

8 files changed

+325
-66
lines changed

frame/session/benchmarking/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
mod mock;
2424

25+
use sp_runtime::traits::{One, StaticLookup};
2526
use sp_std::{prelude::*, vec};
2627

2728
use frame_benchmarking::benchmarks;
@@ -30,12 +31,11 @@ use frame_support::{
3031
traits::{KeyOwnerProofSystem, OnInitialize},
3132
};
3233
use frame_system::RawOrigin;
33-
use pallet_session::{historical::Module as Historical, Pallet as Session, *};
34+
use pallet_session::{historical::Pallet as Historical, Pallet as Session, *};
3435
use pallet_staking::{
3536
benchmarking::create_validator_with_nominators, testing_utils::create_validators,
3637
RewardDestination,
3738
};
38-
use sp_runtime::traits::{One, StaticLookup};
3939

4040
const MAX_VALIDATORS: u32 = 1000;
4141

frame/session/src/historical/mod.rs

Lines changed: 74 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -26,62 +26,74 @@
2626
//! These roots and proofs of inclusion can be generated at any time during the current session.
2727
//! Afterwards, the proofs can be fed to a consensus module when reporting misbehavior.
2828
29-
use super::{Pallet as SessionModule, SessionIndex};
29+
pub mod offchain;
30+
pub mod onchain;
31+
mod shared;
32+
3033
use codec::{Decode, Encode};
31-
use frame_support::{
32-
decl_module, decl_storage, print,
33-
traits::{ValidatorSet, ValidatorSetWithIdentification},
34-
Parameter,
35-
};
3634
use sp_runtime::{
3735
traits::{Convert, OpaqueKeys},
3836
KeyTypeId,
3937
};
4038
use sp_session::{MembershipProof, ValidatorCount};
39+
use sp_staking::SessionIndex;
4140
use sp_std::prelude::*;
4241
use sp_trie::{
4342
trie_types::{TrieDB, TrieDBMut},
4443
MemoryDB, Recorder, Trie, TrieMut, EMPTY_PREFIX,
4544
};
4645

47-
pub mod offchain;
48-
pub mod onchain;
49-
mod shared;
46+
use frame_support::{
47+
print,
48+
traits::{KeyOwnerProofSystem, StorageVersion, ValidatorSet, ValidatorSetWithIdentification},
49+
Parameter,
50+
};
5051

51-
/// Config necessary for the historical module.
52-
pub trait Config: super::Config {
53-
/// Full identification of the validator.
54-
type FullIdentification: Parameter;
55-
56-
/// A conversion from validator ID to full identification.
57-
///
58-
/// This should contain any references to economic actors associated with the
59-
/// validator, since they may be outdated by the time this is queried from a
60-
/// historical trie.
61-
///
62-
/// It must return the identification for the current session index.
63-
type FullIdentificationOf: Convert<Self::ValidatorId, Option<Self::FullIdentification>>;
64-
}
52+
use crate::{self as pallet_session, Pallet as Session};
53+
54+
pub use pallet::*;
6555

66-
decl_storage! {
67-
trait Store for Module<T: Config> as Session {
68-
/// Mapping from historical session indices to session-data root hash and validator count.
69-
HistoricalSessions get(fn historical_root):
70-
map hasher(twox_64_concat) SessionIndex => Option<(T::Hash, ValidatorCount)>;
71-
/// The range of historical sessions we store. [first, last)
72-
StoredRange: Option<(SessionIndex, SessionIndex)>;
73-
/// Deprecated.
74-
CachedObsolete:
75-
map hasher(twox_64_concat) SessionIndex
76-
=> Option<Vec<(T::ValidatorId, T::FullIdentification)>>;
56+
#[frame_support::pallet]
57+
pub mod pallet {
58+
use super::*;
59+
use frame_support::pallet_prelude::*;
60+
61+
/// The current storage version.
62+
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
63+
64+
#[pallet::pallet]
65+
#[pallet::generate_store(pub(super) trait Store)]
66+
#[pallet::storage_version(STORAGE_VERSION)]
67+
pub struct Pallet<T>(_);
68+
69+
/// Config necessary for the historical pallet.
70+
#[pallet::config]
71+
pub trait Config: pallet_session::Config + frame_system::Config {
72+
/// Full identification of the validator.
73+
type FullIdentification: Parameter;
74+
75+
/// A conversion from validator ID to full identification.
76+
///
77+
/// This should contain any references to economic actors associated with the
78+
/// validator, since they may be outdated by the time this is queried from a
79+
/// historical trie.
80+
///
81+
/// It must return the identification for the current session index.
82+
type FullIdentificationOf: Convert<Self::ValidatorId, Option<Self::FullIdentification>>;
7783
}
78-
}
7984

80-
decl_module! {
81-
pub struct Module<T: Config> for enum Call where origin: T::Origin {}
85+
/// Mapping from historical session indices to session-data root hash and validator count.
86+
#[pallet::storage]
87+
#[pallet::getter(fn historical_root)]
88+
pub type HistoricalSessions<T: Config> =
89+
StorageMap<_, Twox64Concat, SessionIndex, (T::Hash, ValidatorCount), OptionQuery>;
90+
91+
/// The range of historical sessions we store. [first, last)
92+
#[pallet::storage]
93+
pub type StoredRange<T> = StorageValue<_, (SessionIndex, SessionIndex), OptionQuery>;
8294
}
8395

84-
impl<T: Config> Module<T> {
96+
impl<T: Config> Pallet<T> {
8597
/// Prune historical stored session roots up to (but not including)
8698
/// `up_to`.
8799
pub fn prune_up_to(up_to: SessionIndex) {
@@ -109,7 +121,7 @@ impl<T: Config> Module<T> {
109121
}
110122
}
111123

112-
impl<T: Config> ValidatorSet<T::AccountId> for Module<T> {
124+
impl<T: Config> ValidatorSet<T::AccountId> for Pallet<T> {
113125
type ValidatorId = T::ValidatorId;
114126
type ValidatorIdOf = T::ValidatorIdOf;
115127

@@ -122,15 +134,15 @@ impl<T: Config> ValidatorSet<T::AccountId> for Module<T> {
122134
}
123135
}
124136

125-
impl<T: Config> ValidatorSetWithIdentification<T::AccountId> for Module<T> {
137+
impl<T: Config> ValidatorSetWithIdentification<T::AccountId> for Pallet<T> {
126138
type Identification = T::FullIdentification;
127139
type IdentificationOf = T::FullIdentificationOf;
128140
}
129141

130142
/// Specialization of the crate-level `SessionManager` which returns the set of full identification
131143
/// when creating a new session.
132144
pub trait SessionManager<ValidatorId, FullIdentification>:
133-
crate::SessionManager<ValidatorId>
145+
pallet_session::SessionManager<ValidatorId>
134146
{
135147
/// If there was a validator set change, its returns the set of new validators along with their
136148
/// full identifications.
@@ -150,7 +162,7 @@ pub struct NoteHistoricalRoot<T, I>(sp_std::marker::PhantomData<(T, I)>);
150162

151163
impl<T: Config, I: SessionManager<T::ValidatorId, T::FullIdentification>> NoteHistoricalRoot<T, I> {
152164
fn do_new_session(new_index: SessionIndex, is_genesis: bool) -> Option<Vec<T::ValidatorId>> {
153-
StoredRange::mutate(|range| {
165+
<StoredRange<T>>::mutate(|range| {
154166
range.get_or_insert_with(|| (new_index, new_index)).1 = new_index + 1;
155167
});
156168

@@ -183,7 +195,7 @@ impl<T: Config, I: SessionManager<T::ValidatorId, T::FullIdentification>> NoteHi
183195
}
184196
}
185197

186-
impl<T: Config, I> crate::SessionManager<T::ValidatorId> for NoteHistoricalRoot<T, I>
198+
impl<T: Config, I> pallet_session::SessionManager<T::ValidatorId> for NoteHistoricalRoot<T, I>
187199
where
188200
I: SessionManager<T::ValidatorId, T::FullIdentification>,
189201
{
@@ -207,7 +219,7 @@ where
207219

208220
/// A tuple of the validator's ID and their full identification.
209221
pub type IdentificationTuple<T> =
210-
(<T as crate::Config>::ValidatorId, <T as Config>::FullIdentification);
222+
(<T as pallet_session::Config>::ValidatorId, <T as Config>::FullIdentification);
211223

212224
/// A trie instance for checking and generating proofs.
213225
pub struct ProvingTrie<T: Config> {
@@ -227,7 +239,7 @@ impl<T: Config> ProvingTrie<T> {
227239
let mut trie = TrieDBMut::new(&mut db, &mut root);
228240
for (i, (validator, full_id)) in validators.into_iter().enumerate() {
229241
let i = i as u32;
230-
let keys = match <SessionModule<T>>::load_keys(&validator) {
242+
let keys = match <Session<T>>::load_keys(&validator) {
231243
None => continue,
232244
Some(k) => k,
233245
};
@@ -304,15 +316,13 @@ impl<T: Config> ProvingTrie<T> {
304316
}
305317
}
306318

307-
impl<T: Config, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyTypeId, D)>
308-
for Module<T>
309-
{
319+
impl<T: Config, D: AsRef<[u8]>> KeyOwnerProofSystem<(KeyTypeId, D)> for Pallet<T> {
310320
type Proof = MembershipProof;
311321
type IdentificationTuple = IdentificationTuple<T>;
312322

313323
fn prove(key: (KeyTypeId, D)) -> Option<Self::Proof> {
314-
let session = <SessionModule<T>>::current_index();
315-
let validators = <SessionModule<T>>::validators()
324+
let session = <Session<T>>::current_index();
325+
let validators = <Session<T>>::validators()
316326
.into_iter()
317327
.filter_map(|validator| {
318328
T::FullIdentificationOf::convert(validator.clone())
@@ -335,10 +345,10 @@ impl<T: Config, D: AsRef<[u8]>> frame_support::traits::KeyOwnerProofSystem<(KeyT
335345
fn check_proof(key: (KeyTypeId, D), proof: Self::Proof) -> Option<IdentificationTuple<T>> {
336346
let (id, data) = key;
337347

338-
if proof.session == <SessionModule<T>>::current_index() {
339-
<SessionModule<T>>::key_owner(id, data.as_ref()).and_then(|owner| {
348+
if proof.session == <Session<T>>::current_index() {
349+
<Session<T>>::key_owner(id, data.as_ref()).and_then(|owner| {
340350
T::FullIdentificationOf::convert(owner.clone()).and_then(move |id| {
341-
let count = <SessionModule<T>>::validators().len() as ValidatorCount;
351+
let count = <Session<T>>::validators().len() as ValidatorCount;
342352

343353
if count != proof.validator_count {
344354
return None
@@ -374,7 +384,7 @@ pub(crate) mod tests {
374384
BasicExternalities,
375385
};
376386

377-
type Historical = Module<Test>;
387+
type Historical = Pallet<Test>;
378388

379389
pub(crate) fn new_test_ext() -> sp_io::TestExternalities {
380390
let mut t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
@@ -386,7 +396,9 @@ pub(crate) mod tests {
386396
frame_system::Pallet::<Test>::inc_providers(k);
387397
}
388398
});
389-
crate::GenesisConfig::<Test> { keys }.assimilate_storage(&mut t).unwrap();
399+
pallet_session::GenesisConfig::<Test> { keys }
400+
.assimilate_storage(&mut t)
401+
.unwrap();
390402
sp_io::TestExternalities::new(t)
391403
}
392404

@@ -436,27 +448,27 @@ pub(crate) mod tests {
436448
Session::on_initialize(i);
437449
}
438450

439-
assert_eq!(StoredRange::get(), Some((0, 100)));
451+
assert_eq!(<StoredRange<Test>>::get(), Some((0, 100)));
440452

441453
for i in 0..100 {
442454
assert!(Historical::historical_root(i).is_some())
443455
}
444456

445457
Historical::prune_up_to(10);
446-
assert_eq!(StoredRange::get(), Some((10, 100)));
458+
assert_eq!(<StoredRange<Test>>::get(), Some((10, 100)));
447459

448460
Historical::prune_up_to(9);
449-
assert_eq!(StoredRange::get(), Some((10, 100)));
461+
assert_eq!(<StoredRange<Test>>::get(), Some((10, 100)));
450462

451463
for i in 10..100 {
452464
assert!(Historical::historical_root(i).is_some())
453465
}
454466

455467
Historical::prune_up_to(99);
456-
assert_eq!(StoredRange::get(), Some((99, 100)));
468+
assert_eq!(<StoredRange<Test>>::get(), Some((99, 100)));
457469

458470
Historical::prune_up_to(100);
459-
assert_eq!(StoredRange::get(), None);
471+
assert_eq!(<StoredRange<Test>>::get(), None);
460472

461473
for i in 99..199u64 {
462474
set_next_validators(vec![i]);
@@ -466,14 +478,14 @@ pub(crate) mod tests {
466478
Session::on_initialize(i);
467479
}
468480

469-
assert_eq!(StoredRange::get(), Some((100, 200)));
481+
assert_eq!(<StoredRange<Test>>::get(), Some((100, 200)));
470482

471483
for i in 100..200 {
472484
assert!(Historical::historical_root(i).is_some())
473485
}
474486

475487
Historical::prune_up_to(9999);
476-
assert_eq!(StoredRange::get(), None);
488+
assert_eq!(<StoredRange<Test>>::get(), None);
477489

478490
for i in 100..200 {
479491
assert!(Historical::historical_root(i).is_none())

frame/session/src/historical/offchain.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ pub fn keep_newest<T: Config>(n_to_keep: usize) {
140140
mod tests {
141141
use super::*;
142142
use crate::{
143-
historical::{onchain, Module},
143+
historical::{onchain, Pallet},
144144
mock::{force_new_session, set_next_validators, Session, System, Test, NEXT_VALIDATORS},
145145
};
146146

@@ -156,7 +156,7 @@ mod tests {
156156
BasicExternalities,
157157
};
158158

159-
type Historical = Module<Test>;
159+
type Historical = Pallet<Test>;
160160

161161
pub fn new_test_ext() -> sp_io::TestExternalities {
162162
let mut t = frame_system::GenesisConfig::default()

frame/session/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@
108108

109109
#[cfg(feature = "historical")]
110110
pub mod historical;
111+
pub mod migrations;
111112
#[cfg(test)]
112113
mod mock;
113114
#[cfg(test)]

frame/session/src/migrations/mod.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// This file is part of Substrate.
2+
3+
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
4+
// SPDX-License-Identifier: Apache-2.0
5+
6+
// Licensed under the Apache License, Version 2.0 (the "License");
7+
// you may not use this file except in compliance with the License.
8+
// You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing, software
13+
// distributed under the License is distributed on an "AS IS" BASIS,
14+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
// See the License for the specific language governing permissions and
16+
// limitations under the License.
17+
18+
/// Version 1.
19+
///
20+
/// In version 0 session historical pallet uses `Session` for storage module prefix.
21+
/// In version 1 it uses its name as configured in `construct_runtime`.
22+
/// This migration moves session historical pallet storages from old prefix to new prefix.
23+
#[cfg(feature = "historical")]
24+
pub mod v1;

0 commit comments

Comments
 (0)