Skip to content
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

Remove without_storage_info for the staking pallet #621

Closed
Closed
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pallets/staking/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ log = { version = "0.4.14", default-features = false }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.136", optional = true }
scale-info = { version = "2.0.1", default-features = false, features = ["derive"] }
derivative = "2.2.0"
frame-benchmarking = { git = "https://github.com/paritytech/substrate", default-features = false, optional = true , branch = "polkadot-v0.9.20" }
frame-support = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.20" }
frame-system = { git = "https://github.com/paritytech/substrate", default-features = false , branch = "polkadot-v0.9.20" }
Expand Down
141 changes: 90 additions & 51 deletions pallets/staking/src/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,15 @@ use super::{
ActiveSession, BalanceOf, BondedSessions, Config, Event, NegativeImbalanceOf, Pallet, SessionAccumulatedBalance,
SessionValidatorReward, SlashRewardProportion, Staked, Store, Total,
};
use crate::slashing;
use crate::types::{ValidatorSnapshot, ValidatorSnapshotOf};
// use crate::slashing;
use crate::{
slashing::SlashParams,
types::{ValidatorSnapshot, ValidatorSnapshotOf},
};
use frame_support::{
pallet_prelude::*,
traits::{Currency, Get, Imbalance, OnUnbalanced},
BoundedVec,
};
use frame_system::{self as system};
use pallet_session::historical;
Expand Down Expand Up @@ -77,7 +81,6 @@ where
}
}
}

/// In this implementation `new_session(session)` must be called before `end_session(session-1)`
/// i.e. the new session must be planned before the ending of the previous session.
///
Expand All @@ -89,7 +92,10 @@ impl<T: Config> pallet_session::SessionManager<T::AccountId> for Pallet<T> {
let current_block_number = system::Pallet::<T>::block_number();

// select top collator validators for next round
let (validator_count, total_staked) = Self::select_session_validators(new_index);
let (validator_count, total_staked) = match Self::select_session_validators(new_index) {
Ok((validator_count, total_staked)) => (validator_count, total_staked),
Err(_) => return None,
};

// snapshot total stake
<Staked<T>>::insert(new_index, <Total<T>>::get());
Expand All @@ -109,7 +115,7 @@ impl<T: Config> pallet_session::SessionManager<T::AccountId> for Pallet<T> {
total_staked,
);

Some(Self::selected_validators())
Some(Self::selected_validators().to_vec())
}
fn start_session(start_index: SessionIndex) {
log::trace!("start_session:[{:#?}] - Sess-idx[{:#?}]", line!(), start_index);
Expand All @@ -119,18 +125,28 @@ impl<T: Config> pallet_session::SessionManager<T::AccountId> for Pallet<T> {
let bonding_duration = T::BondedDuration::get();

<BondedSessions<T>>::mutate(|bonded| {
bonded.push(start_index);
let _ = match bonded.try_push(start_index) {
Err(_) => {
log::error!(
"start_session:[{:#?}] - Error, Could be BondedSessions Overflow",
line!()
);
return ();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this return needed here?

}
Ok(_) => (),
};

if start_index > bonding_duration {
let first_kept = start_index - bonding_duration;

// prune out everything that's from before the first-kept index.
let n_to_prune = bonded
.to_vec()
.iter()
.take_while(|&&session_idx| session_idx < first_kept)
.count();

for prune_session in bonded.drain(..n_to_prune) {
for prune_session in bonded.to_vec().drain(..n_to_prune) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can't we get an iter from an bounded vec?

// Clear the DB cached state of last session
Self::clear_session_information(prune_session);
}
Expand Down Expand Up @@ -161,8 +177,8 @@ impl<T: Config> pallet_session::SessionManager<T::AccountId> for Pallet<T> {
// pay all stakers for T::BondedDuration rounds ago
Self::pay_stakers(end_index);

// // Clear the DB cached state of last session
// Self::clear_session_information(Self::active_session());
// Clear the DB cached state of last session
Self::clear_session_information(Self::active_session());
} else {
log::error!(
"end_session:[{:#?}] - Something wrong (CSI[{}], ESI[{}])",
Expand All @@ -173,7 +189,6 @@ impl<T: Config> pallet_session::SessionManager<T::AccountId> for Pallet<T> {
}
}
}

/// Means for interacting with a specialized version of the `session` trait.
///
/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Config`
Expand All @@ -194,8 +209,8 @@ impl<T: Config> SessionInterface<<T as frame_system::Config>::AccountId> for T
where
T: pallet_session::Config<ValidatorId = <T as frame_system::Config>::AccountId>,
T: pallet_session::historical::Config<
FullIdentification = ValidatorSnapshot<<T as frame_system::Config>::AccountId, BalanceOf<T>>,
FullIdentificationOf = ValidatorSnapshotOf<T>,
FullIdentification = ValidatorSnapshot<T, T::MaxNominatorsPerValidator>,
FullIdentificationOf = ValidatorSnapshotOf<T, T::MaxNominatorsPerValidator>,
>,
T::SessionHandler: pallet_session::SessionHandler<<T as frame_system::Config>::AccountId>,
T::SessionManager: pallet_session::SessionManager<<T as frame_system::Config>::AccountId>,
Expand All @@ -217,10 +232,12 @@ where
}
}

impl<T: Config> historical::SessionManager<T::AccountId, ValidatorSnapshot<T::AccountId, BalanceOf<T>>> for Pallet<T> {
impl<T: Config> historical::SessionManager<T::AccountId, ValidatorSnapshot<T, T::MaxNominatorsPerValidator>>
for Pallet<T>
{
fn new_session(
new_index: SessionIndex,
) -> Option<Vec<(T::AccountId, ValidatorSnapshot<T::AccountId, BalanceOf<T>>)>> {
) -> Option<Vec<(T::AccountId, ValidatorSnapshot<T, T::MaxNominatorsPerValidator>)>> {
<Self as pallet_session::SessionManager<_>>::new_session(new_index).map(|validators| {
validators
.into_iter()
Expand All @@ -244,8 +261,8 @@ impl<T: Config> OnOffenceHandler<T::AccountId, pallet_session::historical::Ident
where
T: pallet_session::Config<ValidatorId = <T as frame_system::Config>::AccountId>,
T: pallet_session::historical::Config<
FullIdentification = ValidatorSnapshot<<T as frame_system::Config>::AccountId, BalanceOf<T>>,
FullIdentificationOf = ValidatorSnapshotOf<T>,
FullIdentification = ValidatorSnapshot<T, T::MaxNominatorsPerValidator>,
FullIdentificationOf = ValidatorSnapshotOf<T, T::MaxNominatorsPerValidator>,
>,
T::SessionHandler: pallet_session::SessionHandler<<T as frame_system::Config>::AccountId>,
T::SessionManager: pallet_session::SessionManager<<T as frame_system::Config>::AccountId>,
Expand Down Expand Up @@ -289,50 +306,72 @@ where
continue;
}

let unapplied = slashing::compute_slash::<T>(slashing::SlashParams {
controller,
let slash_param: SlashParams<T, T::MaxNominatorsPerValidator> = SlashParams {
controller: controller.clone(),
slash: *slash_fraction,
exposure,
exposure: exposure.clone(),
slash_session,
window_start,
now: active_session,
reward_proportion,
disable_strategy,
});
};

if let Some(mut unapplied) = unapplied {
let nominators_len = unapplied.others.len() as u64;
let reporters_len = details.reporters.len() as u64;

{
let upper_bound = 1 /* Validator/NominatorSlashInEra */ + 2 /* fetch_spans */;
let rw = upper_bound + nominators_len * upper_bound;
add_db_reads_writes(rw, rw);
match slash_param.compute_slash() {
Err(err) => {
log::error!("on_offence:[{:#?}] - compute_slash Err[{:#?}]", line!(), err,);
}
unapplied.reporters = details.reporters.clone();
if slash_defer_duration == 0 {
// apply right away.
slashing::apply_slash::<T>(unapplied);

let slash_cost = (6, 5);
let reward_cost = (2, 2);
add_db_reads_writes(
(1 + nominators_len) * slash_cost.0 + reward_cost.0 * reporters_len,
(1 + nominators_len) * slash_cost.1 + reward_cost.1 * reporters_len,
);
} else {
// defer to end of some `slash_defer_duration` from now.
let apply_at = active_session.saturating_add(slash_defer_duration);

<Self as Store>::UnappliedSlashes::mutate(apply_at, |for_later| for_later.push(unapplied.clone()));

<Pallet<T>>::deposit_event(Event::DeferredUnappliedSlash(active_session, unapplied.validator));

add_db_reads_writes(1, 1);
Ok(None) => {
log::trace!("on_offence:[{:#?}] - NOP", line!(),);
add_db_reads_writes(4 /* fetch_spans */, 5 /* kick_out_if_recent */);
}
Ok(Some(mut unapplied)) => {
let nominators_len = unapplied.others.len() as u64;
let reporters_len = details.reporters.to_vec().len() as u64;

{
let upper_bound = 1 /* Validator/NominatorSlashInEra */ + 2 /* fetch_spans */;
let rw = upper_bound + nominators_len * upper_bound;
add_db_reads_writes(rw, rw);
}

unapplied.reporters =
<BoundedVec<T::AccountId, T::MaxSlashReporters>>::try_from(details.reporters.clone())
.expect("OnOffenceHandler Reporters Overflow Error");

if slash_defer_duration == 0 {
// apply right away.
unapplied.apply_slash();

let slash_cost = (6, 5);
let reward_cost = (2, 2);
add_db_reads_writes(
(1 + nominators_len) * slash_cost.0 + reward_cost.0 * reporters_len,
(1 + nominators_len) * slash_cost.1 + reward_cost.1 * reporters_len,
);
} else {
// defer to end of some `slash_defer_duration` from now.
let apply_at = active_session.saturating_add(slash_defer_duration);

let unapplied_for_event = unapplied.clone();

<Self as Store>::UnappliedSlashes::mutate(apply_at, move |for_later| {
match for_later.try_push(unapplied) {
Err(_) => {
log::error!("on_offence:[{:#?}] - UnappliedSlashes Overflow", line!());
}
Ok(_) => {}
}
});

<Pallet<T>>::deposit_event(Event::DeferredUnappliedSlash(
active_session,
unapplied_for_event.validator,
));

add_db_reads_writes(1, 1);
}
}
} else {
log::trace!("on_offence:[{:#?}] - NOP", line!(),);
add_db_reads_writes(4 /* fetch_spans */, 5 /* kick_out_if_recent */);
}
}
consumed_weight
Expand Down
Loading