Skip to content

Pallet session wrapper draft #852

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions demo/node/src/staging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,18 +130,22 @@ pub fn staging_genesis(
},
transaction_payment: Default::default(),
session: SessionConfig {
initial_validators: initial_authorities
keys: initial_authorities
.iter()
.map(|authority_keys| {
(authority_keys.cross_chain.clone().into(), authority_keys.session.clone())
(
authority_keys.cross_chain.clone().into(),
authority_keys.cross_chain.clone().into(),
authority_keys.session.clone(),
)
})
.collect(),
non_authority_keys: Default::default(),
},
sidechain: SidechainConfig {
genesis_utxo: sp_sidechain::read_genesis_utxo_from_env_with_defaults()?,
..Default::default()
},
pallet_session: Default::default(),
session_committee_management: SessionCommitteeManagementConfig {
initial_authorities: initial_authorities
.into_iter()
Expand Down
4 changes: 2 additions & 2 deletions demo/node/src/template_chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ pub fn chain_spec() -> Result<ChainSpec, envy::Error> {
transaction_payment: Default::default(),
session: SessionConfig {
// Initial validators are meant to be updated in the chain spec file, so it is empty here.
initial_validators: vec![],
keys: vec![],
non_authority_keys: Default::default(),
},
sidechain: SidechainConfig {
genesis_utxo: sp_sidechain::read_genesis_utxo_from_env_with_defaults()?,
..Default::default()
},
pallet_session: Default::default(),
session_committee_management: SessionCommitteeManagementConfig {
// Same as SessionConfig
initial_authorities: vec![],
Expand Down
10 changes: 7 additions & 3 deletions demo/node/src/testnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,19 +181,23 @@ pub fn testnet_genesis(
},
transaction_payment: Default::default(),
session: SessionConfig {
initial_validators: initial_authorities
keys: initial_authorities
.iter()
.map(|authority_keys| {
(authority_keys.cross_chain.clone().into(), authority_keys.session.clone())
(
authority_keys.cross_chain.clone().into(),
authority_keys.cross_chain.clone().into(),
authority_keys.session.clone(),
)
})
.collect(),
non_authority_keys: Default::default(),
},
sidechain: SidechainConfig {
genesis_utxo: sp_sidechain::read_genesis_utxo_from_env_with_defaults()?,
slots_per_epoch: SlotsPerEpoch::read_from_env()?,
..Default::default()
},
pallet_session: Default::default(),
session_committee_management: SessionCommitteeManagementConfig {
initial_authorities: initial_authorities
.into_iter()
Expand Down
2 changes: 1 addition & 1 deletion demo/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pallet-grandpa = { workspace = true }
pallet-partner-chains-session = { workspace = true, features = [
"pallet-session-compat",
] }
pallet-session = { workspace = true }
pallet-session = { workspace = true, features = ["historical"] }
pallet-sudo = { workspace = true }
frame-system = { workspace = true }
frame-try-runtime = { workspace = true, optional = true }
Expand Down
1 change: 0 additions & 1 deletion demo/runtime/src/genesis_config_presets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ fn testnet_genesis(
transaction_payment: Default::default(),
sidechain: Default::default(),
session_committee_management: Default::default(),
pallet_session: Default::default(),
session: Default::default(),
native_token_management: Default::default(),
governed_map: GovernedMapConfig {
Expand Down
40 changes: 21 additions & 19 deletions demo/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ use sp_core::ByteArray;
use sp_core::{OpaqueMetadata, crypto::KeyTypeId};
use sp_governed_map::MainChainScriptsV1;
use sp_inherents::InherentIdentifier;
use sp_runtime::traits::ConvertInto;
use sp_runtime::{
ApplyExtrinsicResult, MultiSignature, Perbill, generic, impl_opaque_keys,
traits::{
Expand Down Expand Up @@ -310,7 +311,24 @@ impl pallet_aura::Config for Runtime {
type SlotDuration = ConstU64<SLOT_DURATION>;
}

pallet_partner_chains_session::impl_pallet_session_config!(Runtime);
impl pallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = AccountId;
type ValidatorIdOf = ConvertInto;
type ShouldEndSession = ValidatorManagementSessionManager<Runtime>;
type NextSessionRotation = ();
type SessionManager = ValidatorManagementSessionManager<Runtime>;
type SessionHandler = <SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = SessionKeys;
type DisablingStrategy = pallet_session::disabling::UpToLimitWithReEnablingDisablingStrategy;

type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}

// impl pallet_session::historical::Config for Runtime {
// type FullIdentification = ();
// type FullIdentificationOf = ();
// }

impl pallet_grandpa::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
Expand Down Expand Up @@ -374,16 +392,6 @@ impl pallet_sudo::Config for Runtime {
type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
}

impl pallet_partner_chains_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorId = <Self as frame_system::Config>::AccountId;
type ShouldEndSession = ValidatorManagementSessionManager<Runtime>;
type NextSessionRotation = ();
type SessionManager = ValidatorManagementSessionManager<Runtime>;
type SessionHandler = <opaque::SessionKeys as OpaqueKeys>::KeyTypeIdProviders;
type Keys = opaque::SessionKeys;
}

parameter_types! {
pub const MaxValidators: u32 = 32;
}
Expand Down Expand Up @@ -673,13 +681,8 @@ construct_runtime!(
BlockProducerMetadata: pallet_block_producer_metadata,
BlockProductionLog: pallet_block_production_log,
BlockParticipation: pallet_block_participation,
// pallet_grandpa reads pallet_session::pallet::CurrentIndex storage.
// Only stub implementation of pallet_session should be wired.
// Partner Chains session_manager ValidatorManagementSessionManager writes to pallet_session::pallet::CurrentIndex.
// ValidatorManagementSessionManager is wired in by pallet_partner_chains_session.
PalletSession: pallet_session,
// The order matters!! pallet_partner_chains_session needs to come last for correct initialization order
Session: pallet_partner_chains_session,
Session: pallet_session,
// Historical: pallet_session::historical,
NativeTokenManagement: pallet_native_token_management,
GovernedMap: pallet_governed_map,
TestHelperPallet: crate::test_helper_pallet,
Expand Down Expand Up @@ -875,7 +878,6 @@ impl_runtime_apis! {
}
}


impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
fn account_nonce(account: AccountId) -> Nonce {
System::account_nonce(account)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,15 +195,17 @@ echo "Generating chain-spec.json file for Partner chain Nodes..."
./partner-chains-node build-spec --disable-default-bootnode > chain-spec.json

echo "Configuring Initial Validators..."
jq '.genesis.runtimeGenesis.config.session.initialValidators = [
jq '.genesis.runtimeGenesis.config.session.keys = [
[
"5FnXTMg8UnfeGsMaGg24o3NY21VRFRDRdgxuLGmXuYLeZmin",
"5FnXTMg8UnfeGsMaGg24o3NY21VRFRDRdgxuLGmXuYLeZmin",
{
"aura": "5Cyx94iyji8namhRxvs4mAbURtPsvwjWCb68ZihNzfRysGLZ",
"grandpa": "5Cc5eQhbPw4CjwZpWqZkWWumMiuZywfWRK2Rh9guXUJ3U89s"
}
],
[
"5FJMH4MeZgd4fpiiAVLnr4uRop2EDFgzAFcvLmcduQ2cofCi",
"5FJMH4MeZgd4fpiiAVLnr4uRop2EDFgzAFcvLmcduQ2cofCi",
{
"aura": "5E4op92Z2Di1GoVS9KqnoGVKQXG2R9x1vdh3RW892YLFsLrc",
Expand Down
57 changes: 57 additions & 0 deletions toolkit/committee-selection/pallet/src/session_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,47 @@ impl<T: crate::Config + pallet_session::Config>
}
}

impl<T: crate::Config + pallet_session::Config> pallet_session::SessionManager<T::AccountId>
for ValidatorManagementSessionManager<T>
{
fn new_session_genesis(_new_index: SessionIndex) -> Option<Vec<T::AccountId>> {
Some(
crate::Pallet::<T>::current_committee_storage()
.committee
.into_iter()
.map(|member| member.authority_id().into())
.collect::<Vec<_>>(),
)
}

// Instead of Some((*).expect) we could just use (*). However, we rather panic in presence of
// important programming errors.
fn new_session(new_index: SessionIndex) -> Option<Vec<T::AccountId>> {
info!("New session {new_index}");
pallet_session::pallet::CurrentIndex::<T>::put(new_index);
Some(
crate::Pallet::<T>::rotate_committee_to_next_epoch()
.expect(
"Session should never end without current epoch validators defined. \
Check ShouldEndSession implementation or if it is used before starting new session",
)
.into_iter()
.map(|member| member.authority_id().into())
.collect(),
)
}

fn end_session(end_index: SessionIndex) {
info!("End session {end_index}");
}

// Session is expected to be at least 1 block behind sidechain epoch.
fn start_session(start_index: SessionIndex) {
let epoch_number = T::current_epoch_number();
info!("Start session {start_index}, epoch {epoch_number}");
}
}

/// This implementation tries to end each session in the first block of each sidechain epoch in which
/// the committee for the epoch is defined.
impl<T, ScEpochNumber> pallet_partner_chains_session::ShouldEndSession<BlockNumberFor<T>>
Expand All @@ -116,6 +157,22 @@ where
}
}

/// This implementation tries to end each session in the first block of each sidechain epoch in which
/// the committee for the epoch is defined.
impl<T, ScEpochNumber> pallet_session::ShouldEndSession<BlockNumberFor<T>>
for ValidatorManagementSessionManager<T>
where
T: crate::Config<ScEpochNumber = ScEpochNumber>,
ScEpochNumber: Clone + PartialOrd,
{
fn should_end_session(_n: BlockNumberFor<T>) -> bool {
let current_epoch_number = T::current_epoch_number();

current_epoch_number > crate::Pallet::<T>::current_committee_storage().epoch
&& crate::Pallet::<T>::next_committee().is_some()
}
}

#[cfg(test)]
mod tests {
use crate::mock::mock_pallet::CurrentEpoch;
Expand Down
Loading