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

Commit

Permalink
Fix most things
Browse files Browse the repository at this point in the history
  • Loading branch information
gui1117 committed Jan 15, 2020
1 parent b1ed143 commit 3b7db30
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 99 deletions.
2 changes: 1 addition & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ parameter_types! {
}

impl pallet_session::Trait for Runtime {
type OnSessionEnding = Staking;
type SessionManager = Staking;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type ShouldEndSession = Babe;
type Event = Event;
Expand Down
12 changes: 5 additions & 7 deletions frame/authority-discovery/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,26 +109,24 @@ mod tests {
pub struct Test;
impl Trait for Test {}

pub struct TestOnSessionEnding;
impl pallet_session::OnSessionEnding<AuthorityId> for TestOnSessionEnding {
fn on_session_ending(_: SessionIndex, _: SessionIndex) -> Option<Vec<AuthorityId>> {
None
}
pub struct TestSessionManager;
impl pallet_session::SessionManager<AuthorityId> for TestSessionManager {
fn new_session(_: SessionIndex) -> Option<Vec<AuthorityId>> { None }
fn end_session(_: SessionIndex) {}
}

parameter_types! {
pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(33);
}

impl pallet_session::Trait for Test {
type OnSessionEnding = TestOnSessionEnding;
type SessionManager = TestSessionManager;
type Keys = UintAuthorityId;
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type SessionHandler = TestSessionHandler;
type Event = ();
type ValidatorId = AuthorityId;
type ValidatorIdOf = ConvertInto;
type SelectInitialValidators = ();
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}

Expand Down
3 changes: 1 addition & 2 deletions frame/babe/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,8 @@ impl pallet_session::Trait for Test {
type ValidatorId = <Self as frame_system::Trait>::AccountId;
type ShouldEndSession = Babe;
type SessionHandler = (Babe,Babe,);
type OnSessionEnding = ();
type SessionManager = ();
type ValidatorIdOf = ();
type SelectInitialValidators = ();
type Keys = MockSessionKeys;
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}
Expand Down
22 changes: 9 additions & 13 deletions frame/im-online/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,25 @@ thread_local! {
pub static VALIDATORS: RefCell<Option<Vec<u64>>> = RefCell::new(Some(vec![1, 2, 3]));
}

pub struct TestOnSessionEnding;
impl pallet_session::OnSessionEnding<u64> for TestOnSessionEnding {
fn on_session_ending(_ending_index: SessionIndex, _will_apply_at: SessionIndex)
-> Option<Vec<u64>>
{
pub struct TestSessionManager;
impl pallet_session::SessionManager<u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<u64>> {
VALIDATORS.with(|l| l.borrow_mut().take())
}
fn end_session(_: SessionIndex) {}
}

impl pallet_session::historical::OnSessionEnding<u64, u64> for TestOnSessionEnding {
fn on_session_ending(_ending_index: SessionIndex, _will_apply_at: SessionIndex)
-> Option<(Vec<u64>, Vec<(u64, u64)>)>
{
impl pallet_session::historical::SessionManager<u64, u64> for TestSessionManager {
fn new_session(_new_index: SessionIndex) -> Option<Vec<(u64, u64)>> {
VALIDATORS.with(|l| l
.borrow_mut()
.take()
.map(|validators| {
let full_identification = validators.iter().map(|v| (*v, *v)).collect();
(validators, full_identification)
validators.iter().map(|v| (*v, *v)).collect()
})
)
}
fn end_session(_: SessionIndex) {}
}

/// An extrinsic type used for tests.
Expand Down Expand Up @@ -131,13 +128,12 @@ parameter_types! {

impl pallet_session::Trait for Runtime {
type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;
type OnSessionEnding = pallet_session::historical::NoteHistoricalRoot<Runtime, TestOnSessionEnding>;
type SessionManager = pallet_session::historical::NoteHistoricalRoot<Runtime, TestSessionManager>;
type SessionHandler = (ImOnline, );
type ValidatorId = u64;
type ValidatorIdOf = ConvertInto;
type Keys = UintAuthorityId;
type Event = ();
type SelectInitialValidators = ();
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}

Expand Down
21 changes: 9 additions & 12 deletions frame/session/src/historical.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.

// TODO TODO: make at genesis the current session using fullidentificationof
//! An opt-in utility for tracking historical sessions in SRML-session.
//!
//! This is generally useful when implementing blockchains that require accountable
Expand Down Expand Up @@ -116,7 +117,7 @@ impl<T: Trait, I> crate::SessionManager<T::ValidatorId> for NoteHistoricalRoot<T
{
fn new_session(new_index: SessionIndex) -> Option<Vec<T::ValidatorId>> {
StoredRange::mutate(|range| {
range.get_or_insert_with(|| (new_index, new_index)).1 = new_index;
range.get_or_insert_with(|| (new_index, new_index)).1 = new_index + 1;
});

let new_validators_and_id = <I as SessionManager<_, _>>::new_session(new_index);
Expand All @@ -125,6 +126,7 @@ impl<T: Trait, I> crate::SessionManager<T::ValidatorId> for NoteHistoricalRoot<T
});

if let Some(new_validators) = new_validators_and_id {
println!("new validator set for {}", new_index);
let count = new_validators.len() as u32;
match ProvingTrie::<T>::generate_for(new_validators) {
Ok(trie) => <HistoricalSessions<T>>::insert(new_index, &(trie.root, count)),
Expand Down Expand Up @@ -338,13 +340,10 @@ mod tests {
set_next_validators(vec![1, 2, 4]);
force_new_session();

assert!(Historical::cached_obsolete(&(proof.session + 1)).is_none());

System::set_block_number(2);
Session::on_initialize(2);

assert!(Historical::cached_obsolete(&(proof.session + 1)).is_some());

println!("proof session: {}", proof.session);
assert!(Historical::historical_root(proof.session).is_some());
assert!(Session::current_index() > proof.session);

Expand All @@ -356,15 +355,13 @@ mod tests {
force_new_session();
System::set_block_number(3);
Session::on_initialize(3);

assert!(Historical::cached_obsolete(&(proof.session + 1)).is_none());
});
}

#[test]
fn prune_up_to_works() {
new_test_ext().execute_with(|| {
for i in 1..101u64 {
for i in 1..99u64 {
set_next_validators(vec![i]);
force_new_session();

Expand All @@ -375,7 +372,7 @@ mod tests {

assert_eq!(StoredRange::get(), Some((0, 100)));

for i in 1..100 {
for i in 0..100 {
assert!(Historical::historical_root(i).is_some())
}

Expand All @@ -395,7 +392,7 @@ mod tests {
Historical::prune_up_to(100);
assert_eq!(StoredRange::get(), None);

for i in 101..201u64 {
for i in 99..199u64 {
set_next_validators(vec![i]);
force_new_session();

Expand All @@ -406,14 +403,14 @@ mod tests {

assert_eq!(StoredRange::get(), Some((100, 200)));

for i in 101..200 {
for i in 100..200 {
assert!(Historical::historical_root(i).is_some())
}

Historical::prune_up_to(9999);
assert_eq!(StoredRange::get(), None);

for i in 101..200 {
for i in 100..200 {
assert!(Historical::historical_root(i).is_none())
}
});
Expand Down
37 changes: 13 additions & 24 deletions frame/session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,21 +317,6 @@ impl<AId> SessionHandler<AId> for TestSessionHandler {
fn on_disabled(_: usize) {}
}

/// Handler for selecting the genesis validator set.
pub trait SelectInitialValidators<ValidatorId> {
/// Returns the initial validator set. If `None` is returned
/// all accounts that have session keys set in the genesis block
/// will be validators.
fn select_initial_validators() -> Option<Vec<ValidatorId>>;
}

/// Implementation of `SelectInitialValidators` that does nothing.
impl<V> SelectInitialValidators<V> for () {
fn select_initial_validators() -> Option<Vec<V>> {
None
}
}

impl<T: Trait> ValidatorRegistration<T::ValidatorId> for Module<T> {
fn is_registered(id: &T::ValidatorId) -> bool {
Self::load_keys(id).is_some()
Expand Down Expand Up @@ -365,9 +350,6 @@ pub trait Trait: frame_system::Trait {
/// After the threshold is reached `disabled` method starts to return true,
/// which in combination with `pallet_staking` forces a new era.
type DisabledValidatorsThreshold: Get<Perbill>;

/// Select initial validators.
type SelectInitialValidators: SelectInitialValidators<Self::ValidatorId>;
}

const DEDUP_KEY_PREFIX: &[u8] = b":session:keys";
Expand Down Expand Up @@ -434,12 +416,19 @@ decl_storage! {
.expect("genesis config must not contain duplicates; qed");
}

let initial_validators = T::SelectInitialValidators::select_initial_validators()
.unwrap_or_else(|| config.keys.iter().map(|(ref v, _)| v.clone()).collect());
let initial_validators_0 = T::SessionManager::new_session(0)
// TODO TODO: should we always expect one can we fall back with config keys ?
// TODO TODO: it might be relevant for test, but if so we should just change
// implementation of SessionManager for type `()`
.expect("TODO TODO: cannot have empty validator set for session 0");
// .unwrap_or_else(|| config.keys.iter().map(|(ref v, _)| v.clone()).collect());
assert!(!initial_validators_0.is_empty(), "Empty validator set in genesis block!");

assert!(!initial_validators.is_empty(), "Empty validator set in genesis block!");
let initial_validators_1 = T::SessionManager::new_session(1)
.unwrap_or_else(|| initial_validators_0.clone());
assert!(!initial_validators_1.is_empty(), "Empty validator set in genesis block!");

let queued_keys: Vec<_> = initial_validators
let queued_keys: Vec<_> = initial_validators_1
.iter()
.cloned()
.map(|v| (
Expand All @@ -451,7 +440,7 @@ decl_storage! {
// Tell everyone about the genesis session keys
T::SessionHandler::on_genesis_session::<T::Keys>(&queued_keys);

<Validators<T>>::put(initial_validators);
<Validators<T>>::put(initial_validators_0);
<QueuedKeys<T>>::put(queued_keys);
});
}
Expand Down Expand Up @@ -551,7 +540,7 @@ impl<T: Trait> Module<T> {
CurrentIndex::put(session_index);

// Get next validator set.
let maybe_next_validators = T::SessionManager::new_session(session_index + 2);
let maybe_next_validators = T::SessionManager::new_session(session_index + 1);
let (next_validators, next_identities_changed)
= if let Some(validators) = maybe_next_validators
{
Expand Down
25 changes: 12 additions & 13 deletions frame/session/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,10 @@ impl SessionHandler<u64> for TestSessionHandler {
}
}

pub struct TestOnSessionEnding;
impl OnSessionEnding<u64> for TestOnSessionEnding {
fn on_session_ending(_: SessionIndex, _: SessionIndex) -> Option<Vec<u64>> {
pub struct TestSessionManager;
impl SessionManager<u64> for TestSessionManager {
fn end_session(_: SessionIndex) {}
fn new_session(_: SessionIndex) -> Option<Vec<u64>> {
if !TEST_SESSION_CHANGED.with(|l| *l.borrow()) {
VALIDATORS.with(|v| {
let mut v = v.borrow_mut();
Expand All @@ -108,14 +109,13 @@ impl OnSessionEnding<u64> for TestOnSessionEnding {
}

#[cfg(feature = "historical")]
impl crate::historical::OnSessionEnding<u64, u64> for TestOnSessionEnding {
fn on_session_ending(ending_index: SessionIndex, will_apply_at: SessionIndex)
-> Option<(Vec<u64>, Vec<(u64, u64)>)>
impl crate::historical::SessionManager<u64, u64> for TestSessionManager {
fn end_session(_: SessionIndex) {}
fn new_session(new_index: SessionIndex)
-> Option<Vec<(u64, u64)>>
{
let pair_with_ids = |vals: &[u64]| vals.iter().map(|&v| (v, v)).collect::<Vec<_>>();
<Self as OnSessionEnding<_>>::on_session_ending(ending_index, will_apply_at)
.map(|vals| (pair_with_ids(&vals), vals))
.map(|(ids, vals)| (vals, ids))
<Self as SessionManager<_>>::new_session(new_index)
.map(|vals| vals.into_iter().map(|val| (val, val)).collect())
}
}

Expand Down Expand Up @@ -190,15 +190,14 @@ parameter_types! {
impl Trait for Test {
type ShouldEndSession = TestShouldEndSession;
#[cfg(feature = "historical")]
type OnSessionEnding = crate::historical::NoteHistoricalRoot<Test, TestOnSessionEnding>;
type SessionManager = crate::historical::NoteHistoricalRoot<Test, TestSessionManager>;
#[cfg(not(feature = "historical"))]
type OnSessionEnding = TestOnSessionEnding;
type SessionManager = TestSessionManager;
type SessionHandler = TestSessionHandler;
type ValidatorId = u64;
type ValidatorIdOf = ConvertInto;
type Keys = MockSessionKeys;
type Event = ();
type SelectInitialValidators = ();
type DisabledValidatorsThreshold = DisabledValidatorsThreshold;
}

Expand Down
Loading

0 comments on commit 3b7db30

Please sign in to comment.