feat: Rebrand Polkadot/Substrate references to PezkuwiChain

This commit systematically rebrands various references from Parity Technologies'
Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk.

Key changes include:
- Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks.
- Modified internal documentation and code comments to reflect PezkuwiChain naming and structure.
- Replaced direct references to  with  or specific paths within the  for XCM, Pezkuwi, and other modules.
- Cleaned up deprecated  issue and PR references in various  and  files, particularly in  and  modules.
- Adjusted image and logo URLs in documentation to point to PezkuwiChain assets.
- Removed or rephrased comments related to external Polkadot/Substrate PRs and issues.

This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
2025-12-14 00:04:10 +03:00
parent 286de54384
commit 1c0e57d984
9084 changed files with 997839 additions and 997557 deletions
@@ -0,0 +1,88 @@
[package]
name = "pezpallet-ahm-test"
version = "1.0.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "e2e unit tests for staking in AHM"
publish = false
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dev-dependencies]
codec = { features = ["derive"], workspace = true, default-features = true }
frame = { workspace = true, default-features = true }
pezframe-support = { workspace = true, default-features = true }
log = { workspace = true }
scale-info = { features = [
"derive",
], workspace = true, default-features = true }
pezsp-core = { workspace = true, default-features = true }
pezsp-session = { workspace = true, default-features = true }
pezsp-staking = { workspace = true, default-features = true }
pezsp-tracing = { workspace = true, default-features = true }
# pallets we need in both
pezpallet-balances = { workspace = true, default-features = true }
# pallets that we need in AH
pezframe-election-provider-support = { workspace = true, default-features = true }
pezpallet-election-provider-multi-block = { workspace = true, default-features = true }
pezpallet-staking-async = { workspace = true, default-features = true }
pezpallet-staking-async-rc-client = { workspace = true, default-features = true }
# pallets we need in the RC
pezpallet-authorship = { workspace = true, default-features = true }
pezpallet-session = { workspace = true, default-features = true }
pezpallet-staking-async-ah-client = { workspace = true, default-features = true }
pezpallet-timestamp = { workspace = true, default-features = true }
# staking classic which will be replaced by ah-client
pezpallet-offences = { workspace = true, default-features = true }
pezpallet-root-offences = { workspace = true, default-features = true }
pezpallet-staking = { workspace = true, default-features = true }
[features]
std = ["log/std"]
try-runtime = [
"pezpallet-balances/try-runtime",
"pezpallet-staking/try-runtime",
"pezpallet-staking-async-rc-client/try-runtime",
"pezpallet-staking-async/try-runtime",
"pezframe-election-provider-support/try-runtime",
"pezframe-support/try-runtime",
"frame/try-runtime",
"pezpallet-authorship/try-runtime",
"pezpallet-election-provider-multi-block/try-runtime",
"pezpallet-offences/try-runtime",
"pezpallet-root-offences/try-runtime",
"pezpallet-session/try-runtime",
"pezpallet-staking-async-ah-client/try-runtime",
"pezpallet-timestamp/try-runtime",
]
runtime-benchmarks = [
"pezframe-election-provider-support/runtime-benchmarks",
"pezframe-support/runtime-benchmarks",
"frame/runtime-benchmarks",
"pezpallet-authorship/runtime-benchmarks",
"pezpallet-balances/runtime-benchmarks",
"pezpallet-election-provider-multi-block/runtime-benchmarks",
"pezpallet-offences/runtime-benchmarks",
"pezpallet-root-offences/runtime-benchmarks",
"pezpallet-session/runtime-benchmarks",
"pezpallet-staking-async-ah-client/runtime-benchmarks",
"pezpallet-staking-async-rc-client/runtime-benchmarks",
"pezpallet-staking-async/runtime-benchmarks",
"pezpallet-staking/runtime-benchmarks",
"pezpallet-timestamp/runtime-benchmarks",
"pezsp-session/runtime-benchmarks",
"pezsp-staking/runtime-benchmarks",
]
@@ -0,0 +1,574 @@
// This file is part of Bizinikiwi.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::shared;
use frame::testing_prelude::*;
use pezframe_election_provider_support::{
bounds::{ElectionBounds, ElectionBoundsBuilder},
SequentialPhragmen,
};
use pezframe_support::pezsp_runtime::testing::TestXt;
use pezpallet_election_provider_multi_block as multi_block;
use pezpallet_staking_async::Forcing;
use pezpallet_staking_async_rc_client::{SessionReport, ValidatorSetReport};
use pezsp_staking::SessionIndex;
construct_runtime! {
pub enum Runtime {
System: pezframe_system,
Balances: pezpallet_balances,
// NOTE: the validator set is given by pezpallet-staking to rc-client on-init, and rc-client
// will not send it immediately, but rather store it and sends it over on its own next
// on-init call. Yet, because staking comes first here, its on-init is called before
// rc-client, so under normal conditions, the message is sent immediately.
Staking: pezpallet_staking_async,
RcClient: pezpallet_staking_async_rc_client,
MultiBlock: multi_block,
MultiBlockVerifier: multi_block::verifier,
MultiBlockSigned: multi_block::signed,
MultiBlockUnsigned: multi_block::unsigned,
}
}
// alias Runtime with T.
pub type T = Runtime;
pub fn roll_next() {
let now = System::block_number();
let next = now + 1;
System::set_block_number(next);
Staking::on_initialize(next);
RcClient::on_initialize(next);
MultiBlock::on_initialize(next);
MultiBlockVerifier::on_initialize(next);
MultiBlockSigned::on_initialize(next);
MultiBlockUnsigned::on_initialize(next);
}
pub fn roll_many(blocks: BlockNumber) {
let current = System::block_number();
while System::block_number() < current + blocks {
roll_next();
}
}
pub fn roll_until_matches(criteria: impl Fn() -> bool, with_rc: bool) {
while !criteria() {
roll_next();
if with_rc {
if LocalQueue::get().is_some() {
panic!("when local queue is set, you cannot roll ah forward as well!")
}
shared::in_rc(|| {
crate::rc::roll_next();
});
}
}
}
/// Use the given `end_index` as the first session report, and increment as per needed.
pub(crate) fn roll_until_next_active(mut end_index: SessionIndex) -> Vec<AccountId> {
// receive enough session reports, such that we plan a new era
let planned_era = pezpallet_staking_async::session_rotation::Rotator::<Runtime>::planned_era();
let active_era = pezpallet_staking_async::session_rotation::Rotator::<Runtime>::active_era();
while pezpallet_staking_async::session_rotation::Rotator::<Runtime>::planned_era() == planned_era {
let report = SessionReport {
end_index,
activation_timestamp: None,
leftover: false,
validator_points: Default::default(),
};
assert_ok!(pezpallet_staking_async_rc_client::Pallet::<Runtime>::relay_session_report(
RuntimeOrigin::root(),
report
));
roll_next();
end_index += 1;
}
// now we have planned a new session. Roll until we have an outgoing message ready, meaning the
// election is done
LocalQueue::flush();
loop {
let messages = LocalQueue::get_since_last_call();
match messages.len() {
0 => {
roll_next();
continue;
},
1 => {
assert_eq!(
messages[0],
(
System::block_number(),
OutgoingMessages::ValidatorSet(ValidatorSetReport {
id: planned_era + 1,
leftover: false,
// arbitrary, feel free to change if test setup updates
new_validator_set: vec![3, 5, 6, 8],
prune_up_to: active_era.checked_sub(BondingDuration::get()),
})
)
);
break;
},
_ => panic!("Expected only one message in local queue, but got: {:?}", messages),
}
}
// active era is still 0
assert_eq!(
pezpallet_staking_async::session_rotation::Rotator::<Runtime>::active_era(),
active_era
);
// rc will not tell us that it has instantly activated a validator set.
let report = SessionReport {
end_index,
activation_timestamp: Some((1000, planned_era + 1)),
leftover: false,
validator_points: Default::default(),
};
assert_ok!(pezpallet_staking_async_rc_client::Pallet::<Runtime>::relay_session_report(
RuntimeOrigin::root(),
report
));
// active era is now 1.
assert_eq!(
pezpallet_staking_async::session_rotation::Rotator::<Runtime>::active_era(),
active_era + 1
);
// arbitrary, feel free to change if test setup updates
vec![3, 5, 6, 8]
}
pub type AccountId = <Runtime as pezframe_system::Config>::AccountId;
pub type Balance = <Runtime as pezpallet_balances::Config>::Balance;
pub type Hash = <Runtime as pezframe_system::Config>::Hash;
pub type BlockNumber = BlockNumberFor<Runtime>;
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
impl pezframe_system::Config for Runtime {
type Block = MockBlock<Self>;
type AccountData = pezpallet_balances::AccountData<Balance>;
}
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
impl pezpallet_balances::Config for Runtime {
type Balance = u128;
type AccountStore = System;
}
pezframe_election_provider_support::generate_solution_type!(
pub struct TestNposSolution::<
VoterIndex = u16,
TargetIndex = u16,
Accuracy = PerU16,
MaxVoters = ConstU32::<1000>
>(16)
);
type Extrinsic = TestXt<RuntimeCall, ()>;
impl<LocalCall> pezframe_system::offchain::CreateTransactionBase<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
type RuntimeCall = RuntimeCall;
type Extrinsic = Extrinsic;
}
impl<LocalCall> pezframe_system::offchain::CreateBare<LocalCall> for Runtime
where
RuntimeCall: From<LocalCall>,
{
fn create_bare(call: Self::RuntimeCall) -> Self::Extrinsic {
Extrinsic::new_bare(call)
}
}
type MaxVotesPerVoter = pezpallet_staking_async::MaxNominationsOf<Runtime>;
parameter_types! {
pub static MaxValidators: u32 = 32;
pub static MaxBackersPerWinner: u32 = 16;
pub static MaxExposurePageSize: u32 = 8;
pub static MaxBackersPerWinnerFinal: u32 = 16;
pub static MaxWinnersPerPage: u32 = 16;
pub static MaxLength: u32 = 4 * 1024 * 1024;
pub static Pages: u32 = 3;
pub static TargetSnapshotPerBlock: u32 = 4;
pub static VoterSnapshotPerBlock: u32 = 4;
pub static SignedPhase: BlockNumber = 4;
pub static UnsignedPhase: BlockNumber = 4;
pub static SignedValidationPhase: BlockNumber = (2 * Pages::get() as BlockNumber);
}
impl multi_block::unsigned::miner::MinerConfig for Runtime {
type AccountId = AccountId;
type Hash = Hash;
type MaxBackersPerWinner = MaxBackersPerWinner;
type MaxWinnersPerPage = MaxWinnersPerPage;
type MaxBackersPerWinnerFinal = MaxBackersPerWinnerFinal;
type MaxVotesPerVoter = MaxVotesPerVoter;
type Solution = TestNposSolution;
type MaxLength = MaxLength;
type Pages = Pages;
type Solver = SequentialPhragmen<AccountId, Perbill>;
type TargetSnapshotPerBlock = TargetSnapshotPerBlock;
type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
}
parameter_types! {
pub Bounds: ElectionBounds = ElectionBoundsBuilder::default().build();
}
pub struct OnChainConfig;
impl pezframe_election_provider_support::onchain::Config for OnChainConfig {
// unbounded
type Bounds = Bounds;
// We should not need sorting, as our bounds are large enough for the number of
// nominators/validators in this test setup.
type Sort = ConstBool<false>;
type DataProvider = Staking;
type MaxBackersPerWinner = MaxBackersPerWinner;
type MaxWinnersPerPage = MaxWinnersPerPage;
type Solver = SequentialPhragmen<AccountId, Perbill>;
type System = Runtime;
type WeightInfo = ();
}
impl multi_block::Config for Runtime {
type AdminOrigin = EnsureRoot<AccountId>;
type ManagerOrigin = EnsureRoot<AccountId>;
type DataProvider = Staking;
type Fallback = pezframe_election_provider_support::onchain::OnChainExecution<OnChainConfig>;
type MinerConfig = Self;
type Pages = Pages;
type SignedPhase = SignedPhase;
type UnsignedPhase = UnsignedPhase;
type SignedValidationPhase = SignedValidationPhase;
type TargetSnapshotPerBlock = TargetSnapshotPerBlock;
type VoterSnapshotPerBlock = VoterSnapshotPerBlock;
type Verifier = MultiBlockVerifier;
type AreWeDone = multi_block::ProceedRegardlessOf<Self>;
type OnRoundRotation = multi_block::CleanRound<Self>;
type WeightInfo = ();
}
impl multi_block::verifier::Config for Runtime {
type MaxBackersPerWinner = MaxBackersPerWinner;
type MaxBackersPerWinnerFinal = MaxBackersPerWinnerFinal;
type MaxWinnersPerPage = MaxWinnersPerPage;
type SolutionDataProvider = MultiBlockSigned;
type WeightInfo = ();
}
impl multi_block::unsigned::Config for Runtime {
type MinerPages = ConstU32<1>;
type WeightInfo = ();
type OffchainStorage = ConstBool<true>;
type MinerTxPriority = ConstU64<{ u64::MAX }>;
type OffchainRepeat = ();
type OffchainSolver = SequentialPhragmen<AccountId, Perbill>;
}
parameter_types! {
pub static DepositBase: Balance = 1;
pub static DepositPerPage: Balance = 1;
pub static MaxSubmissions: u32 = 2;
pub static RewardBase: Balance = 5;
}
impl multi_block::signed::Config for Runtime {
type Currency = Balances;
type EjectGraceRatio = ();
type BailoutGraceRatio = ();
type InvulnerableDeposit = ();
type DepositBase = DepositBase;
type DepositPerPage = DepositPerPage;
type EstimateCallFee = ConstU32<1>;
type MaxSubmissions = MaxSubmissions;
type RewardBase = RewardBase;
type WeightInfo = ();
}
parameter_types! {
pub static BondingDuration: u32 = 3;
pub static SlashDeferredDuration: u32 = 2;
pub static SessionsPerEra: u32 = 6;
pub static PlanningEraOffset: u32 = 2;
pub MaxPruningItems: u32 = 100;
}
impl pezpallet_staking_async::Config for Runtime {
type Filter = ();
type RuntimeHoldReason = RuntimeHoldReason;
type AdminOrigin = EnsureRoot<AccountId>;
type BondingDuration = BondingDuration;
type SessionsPerEra = SessionsPerEra;
type PlanningEraOffset = PlanningEraOffset;
type Currency = Balances;
type OldCurrency = Balances;
type CurrencyBalance = Balance;
type CurrencyToVote = ();
type ElectionProvider = MultiBlock;
type EraPayout = ();
type EventListeners = ();
type Reward = ();
type RewardRemainder = ();
type Slash = ();
type SlashDeferDuration = SlashDeferredDuration;
type MaxEraDuration = ();
type MaxPruningItems = MaxPruningItems;
type HistoryDepth = ConstU32<7>;
type MaxControllersInDeprecationBatch = ();
type MaxValidatorSet = MaxValidators;
type MaxExposurePageSize = MaxExposurePageSize;
type MaxInvulnerables = MaxValidators;
type MaxUnlockingChunks = ConstU32<16>;
type NominationsQuota = pezpallet_staking_async::FixedNominationsQuota<16>;
type VoterList = pezpallet_staking_async::UseNominatorsAndValidatorsMap<Self>;
type TargetList = pezpallet_staking_async::UseValidatorsMap<Self>;
type RcClientInterface = RcClient;
type WeightInfo = ();
}
impl pezpallet_staking_async_rc_client::Config for Runtime {
type AHStakingInterface = Staking;
type SendToRelayChain = DeliverToRelay;
type RelayChainOrigin = EnsureRoot<AccountId>;
type MaxValidatorSetRetries = ConstU32<3>;
}
parameter_types! {
pub static NextRelayDeliveryFails: bool = false;
}
pub struct DeliverToRelay;
impl DeliverToRelay {
fn ensure_delivery_guard() -> Result<(), ()> {
// `::take` will set it back to the default value, `false`.
if NextRelayDeliveryFails::take() {
Err(())
} else {
Ok(())
}
}
}
impl pezpallet_staking_async_rc_client::SendToRelayChain for DeliverToRelay {
type AccountId = AccountId;
fn validator_set(
report: pezpallet_staking_async_rc_client::ValidatorSetReport<Self::AccountId>,
) -> Result<(), ()> {
Self::ensure_delivery_guard()?;
if let Some(mut local_queue) = LocalQueue::get() {
local_queue.push((System::block_number(), OutgoingMessages::ValidatorSet(report)));
LocalQueue::set(Some(local_queue));
} else {
shared::CounterAHRCValidatorSet::mutate(|x| *x += 1);
shared::in_rc(|| {
let origin = crate::rc::RuntimeOrigin::root();
pezpallet_staking_async_ah_client::Pallet::<crate::rc::Runtime>::validator_set(
origin,
report.clone(),
)
.unwrap();
});
}
Ok(())
}
}
const INITIAL_BALANCE: Balance = 1000;
const INITIAL_STAKE: Balance = 100;
#[derive(Clone, Debug, PartialEq)]
pub enum OutgoingMessages {
ValidatorSet(pezpallet_staking_async_rc_client::ValidatorSetReport<AccountId>),
}
parameter_types! {
pub static LocalQueue: Option<Vec<(BlockNumber, OutgoingMessages)>> = None;
pub static LocalQueueLastIndex: usize = 0;
}
impl LocalQueue {
pub fn get_since_last_call() -> Vec<(BlockNumber, OutgoingMessages)> {
if let Some(all) = Self::get() {
let last = LocalQueueLastIndex::get();
LocalQueueLastIndex::set(all.len());
all.into_iter().skip(last).collect()
} else {
panic!("Must set local_queue()!")
}
}
pub fn flush() {
let _ = Self::get_since_last_call();
}
}
pub struct ExtBuilder {
// if true, emulate pre-ahm-migration state
pre_migration: bool,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self { pre_migration: false }
}
}
impl ExtBuilder {
/// Set this if you want to emulate pre-migration state of staking-async.
pub fn pre_migration(self) -> Self {
Self { pre_migration: true }
}
/// Set this if you want to test the ah-runtime locally. This will push outgoing messages to
/// `LocalQueue` instead of enacting them on RC.
pub fn local_queue(self) -> Self {
LocalQueue::set(Some(Default::default()));
self
}
pub fn slash_defer_duration(self, duration: u32) -> Self {
SlashDeferredDuration::set(duration);
self
}
pub fn build(self) -> TestState {
let _ = pezsp_tracing::try_init_simple();
let mut t = pezframe_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
// Note: The state in pezpallet-staking-async is retained even when pre-migration is set.
// This does not impact the tests, but for strict accuracy, be aware that the state isn't
// fully representative.
let validators = vec![1, 2, 3, 4, 5, 6, 7, 8]
.into_iter()
.map(|x| (x, INITIAL_STAKE, pezpallet_staking_async::StakerStatus::Validator));
let nominators = vec![
(100, vec![1, 2]),
(101, vec![2, 5]),
(102, vec![1, 1]),
(103, vec![3, 3]),
(104, vec![1, 5]),
(105, vec![5, 4]),
(106, vec![6, 2]),
(107, vec![1, 6]),
(108, vec![2, 7]),
(109, vec![4, 8]),
(110, vec![5, 2]),
(111, vec![6, 6]),
(112, vec![8, 1]),
]
.into_iter()
.map(|(x, y)| (x, INITIAL_STAKE, pezpallet_staking_async::StakerStatus::Nominator(y)));
let stakers = validators.chain(nominators).collect::<Vec<_>>();
let balances = stakers
.clone()
.into_iter()
.map(|(x, _, _)| (x, INITIAL_BALANCE))
.collect::<Vec<_>>();
pezpallet_balances::GenesisConfig::<Runtime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
pezpallet_staking_async::GenesisConfig::<Runtime> {
stakers,
validator_count: 4,
active_era: (0, 0, 0),
force_era: if self.pre_migration { Forcing::ForceNone } else { Forcing::default() },
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
let mut state: TestState = t.into();
state.execute_with(|| {
// initialises events
roll_next();
});
state
}
}
parameter_types! {
static StakingEventsIndex: usize = 0;
static ElectionEventsIndex: usize = 0;
static RcClientEventsIndex: usize = 0;
}
pub(crate) fn rc_client_events_since_last_call() -> Vec<pezpallet_staking_async_rc_client::Event<T>> {
let all: Vec<_> = System::events()
.into_iter()
.filter_map(
|r| if let RuntimeEvent::RcClient(inner) = r.event { Some(inner) } else { None },
)
.collect();
let seen = RcClientEventsIndex::get();
RcClientEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
pub(crate) fn staking_events_since_last_call() -> Vec<pezpallet_staking_async::Event<T>> {
let all: Vec<_> = System::events()
.into_iter()
.filter_map(|r| if let RuntimeEvent::Staking(inner) = r.event { Some(inner) } else { None })
.collect();
let seen = StakingEventsIndex::get();
StakingEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
pub(crate) fn election_events_since_last_call() -> Vec<multi_block::Event<T>> {
let all: Vec<_> = System::events()
.into_iter()
.filter_map(
|r| if let RuntimeEvent::MultiBlock(inner) = r.event { Some(inner) } else { None },
)
.collect();
let seen = ElectionEventsIndex::get();
ElectionEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
@@ -0,0 +1,22 @@
// This file is part of Bizinikiwi.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod mock;
pub mod test;
// re-export for easier use in dual runtime tests.
pub use mock::*;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,967 @@
// This file is part of Bizinikiwi.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[cfg(test)]
pub mod ah;
#[cfg(test)]
pub mod rc;
#[cfg(test)]
pub mod shared;
// shared tests.
#[cfg(test)]
mod tests {
use super::*;
use crate::{
ah::{rc_client_events_since_last_call, staking_events_since_last_call},
rc::RootOffences,
};
use ah_client::OperatingMode;
use frame::testing_prelude::*;
use pezframe_support::traits::Get;
use pezpallet_election_provider_multi_block as multi_block;
use pezpallet_staking as staking_classic;
use pezpallet_staking_async::{ActiveEra, ActiveEraInfo, Forcing};
use pezpallet_staking_async_ah_client::{self as ah_client, OffenceSendQueue};
use pezpallet_staking_async_rc_client as rc_client;
#[test]
fn rc_session_change_reported_to_ah() {
// sets up AH chain with current and active era.
shared::put_ah_state(ah::ExtBuilder::default().build());
shared::put_rc_state(rc::ExtBuilder::default().build());
// shared::RC_STATE.with(|state| *state.get_mut() = rc::ExtBuilder::default().build());
// initial state of ah
shared::in_ah(|| {
assert_eq!(pezframe_system::Pallet::<ah::Runtime>::block_number(), 1);
assert_eq!(pezpallet_staking_async::CurrentEra::<ah::Runtime>::get(), Some(0));
assert_eq!(
ActiveEra::<ah::Runtime>::get(),
Some(ActiveEraInfo { index: 0, start: Some(0) })
);
});
shared::in_rc(|| {
// initial state of rc
assert_eq!(ah_client::Mode::<rc::Runtime>::get(), OperatingMode::Active);
// go to session 1 in RC and test.
// when
assert!(pezframe_system::Pallet::<rc::Runtime>::block_number() == 1);
// given end session 0, start session 1, plan 2
rc::roll_until_matches(
|| pezpallet_session::CurrentIndex::<rc::Runtime>::get() == 1,
true,
);
// then
assert_eq!(pezframe_system::Pallet::<rc::Runtime>::block_number(), rc::Period::get());
});
shared::in_rc(|| {
// roll a few more sessions
rc::roll_until_matches(
|| pezpallet_session::CurrentIndex::<rc::Runtime>::get() == 4,
true,
);
});
shared::in_ah(|| {
// ah's rc-client has also progressed some blocks, equal to 4 sessions
assert_eq!(pezframe_system::Pallet::<ah::Runtime>::block_number(), 120);
// election is ongoing, and has just started
assert!(matches!(
multi_block::CurrentPhase::<ah::Runtime>::get(),
multi_block::Phase::Snapshot(_)
));
});
// go to session 5 in rc, and forward AH too.
shared::in_rc(|| {
rc::roll_until_matches(
|| pezpallet_session::CurrentIndex::<rc::Runtime>::get() == 5,
true,
);
});
// ah has bumped the current era, but not the active era
shared::in_ah(|| {
assert_eq!(pezpallet_staking_async::CurrentEra::<ah::Runtime>::get(), Some(1));
assert_eq!(
ActiveEra::<ah::Runtime>::get(),
Some(ActiveEraInfo { index: 0, start: Some(0) })
);
});
// go to session 6 in rc, and forward AH too.
shared::in_rc(|| {
rc::roll_until_matches(
|| pezpallet_session::CurrentIndex::<rc::Runtime>::get() == 6,
true,
);
});
}
#[test]
fn ah_takes_over_staking_post_migration() {
// SCENE (1): Pre AHM Migration
shared::put_rc_state(
rc::ExtBuilder::default()
.pre_migration()
// set session keys for all "potential" validators
.session_keys(vec![1, 2, 3, 4, 5, 6, 7, 8])
// set a very low `MaxOffenceBatchSize` to test batching behavior
.max_offence_batch_size(2)
.build(),
);
shared::put_ah_state(ah::ExtBuilder::default().build());
shared::in_rc(|| {
assert!(staking_classic::ActiveEra::<rc::Runtime>::get().is_none());
// - staking-classic is active on RC.
rc::roll_until_matches(
|| {
staking_classic::ActiveEra::<rc::Runtime>::get().map(|a| a.index).unwrap_or(0) ==
1
},
true,
);
// No offence exist so far
assert!(staking_classic::UnappliedSlashes::<rc::Runtime>::get(4).is_empty());
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(100))],
None,
None
));
// offence is expected to be deferred to era 1 + 3 = 4
assert_eq!(staking_classic::UnappliedSlashes::<rc::Runtime>::get(4).len(), 1);
});
// nothing happened in ah-staking so far
shared::in_ah(|| {
// Ensure AH does not receive any
// - offences
// - session change reports.
assert_eq!(shared::CounterRCAHNewOffence::get(), 0);
assert_eq!(shared::CounterRCAHSessionReport::get(), 0);
assert_eq!(ah::mock::staking_events_since_last_call(), vec![]);
});
// SCENE (2): AHM migration begins
let mut pre_migration_block_number = 0;
shared::in_rc(|| {
rc::roll_next();
let pre_migration_era_points =
staking_classic::ErasRewardPoints::<rc::Runtime>::get(1).total;
ah_client::Pallet::<rc::Runtime>::on_migration_start();
assert_eq!(ah_client::Mode::<rc::Runtime>::get(), OperatingMode::Buffered);
// get current session
let current_session = pezpallet_session::CurrentIndex::<rc::Runtime>::get();
pre_migration_block_number = pezframe_system::Pallet::<rc::Runtime>::block_number();
// assume migration takes at least one era
// go forward by more than `SessionsPerEra` sessions -- staking will not rotate a new
// era.
rc::roll_until_matches(
|| {
pezpallet_session::CurrentIndex::<rc::Runtime>::get() ==
current_session + ah::SessionsPerEra::get() + 1
},
true,
);
let migration_start_block_number = pezframe_system::Pallet::<rc::Runtime>::block_number();
// ensure era is still 1 on RC.
// (Session events are received by AHClient and never passed on to staking-classic once
// migration starts)
assert_eq!(staking_classic::ActiveEra::<rc::Runtime>::get().unwrap().index, 1);
// no new era is planned
assert_eq!(staking_classic::CurrentEra::<rc::Runtime>::get().unwrap(), 1);
// no new block author points accumulated
assert_eq!(
staking_classic::ErasRewardPoints::<rc::Runtime>::get(1).total,
pre_migration_era_points
);
// some validator points have been recorded in ah-client
assert_eq!(
ah_client::ValidatorPoints::<rc::Runtime>::iter().count(),
1,
"only 11 has authored blocks in rc"
);
assert_eq!(
ah_client::ValidatorPoints::<rc::Runtime>::get(&11),
(migration_start_block_number - pre_migration_block_number) as u32 *
<<rc::Runtime as ah_client::Config>::PointsPerBlock as Get<u32>>::get()
);
// Verify buffered mode doesn't send anything to AH
let offence_counter_before = shared::CounterRCAHNewOffence::get();
// ---------- Offences in session 12 (6 total) ----------
assert_eq!(pezpallet_session::CurrentIndex::<rc::Runtime>::get(), 12);
// 3 for validator 2
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(50))],
None,
None,
));
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(100))],
None,
None,
));
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(25))],
None,
None,
));
// 2 for validator 1
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(1, Perbill::from_percent(75))],
None,
None,
));
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(1, Perbill::from_percent(60))],
None,
None,
));
// one for validator 4
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(5, Perbill::from_percent(55))],
None,
None,
));
// Move to the next session to create offences in different sessions for batching test
rc::roll_to_next_session(false);
// ---------- Offences in session 13 (4 total) ----------
assert_eq!(pezpallet_session::CurrentIndex::<rc::Runtime>::get(), 13);
// 2 for validator 2
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(90))],
None,
None,
));
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(80))],
None,
None,
));
// 1 for validator 1
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(1, Perbill::from_percent(85))],
None,
None,
));
// 1 for validator 5
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(5, Perbill::from_percent(45))],
None,
None,
));
// Move to another session and create more offences
rc::roll_to_next_session(false);
// ---------- Offences in session 14 (3 total) ----------
assert_eq!(pezpallet_session::CurrentIndex::<rc::Runtime>::get(), 14);
// 1 for validator 2
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(2, Perbill::from_percent(70))],
None,
None,
));
// 1 for validator 1
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(1, Perbill::from_percent(65))],
None,
None,
));
// 1 for validator 5
assert_ok!(RootOffences::create_offence(
rc::RuntimeOrigin::root(),
vec![(5, Perbill::from_percent(40))],
None,
None,
));
// ---------- End of offences created so far (13 total) ----------
// Verify nothing was sent to AH in buffered mode
assert_eq!(
shared::CounterRCAHNewOffence::get(),
offence_counter_before,
"No offences should be sent to AH in buffered mode"
);
// no new unapplied slashes are created in staking-classic (other than the previously
// created).
assert_eq!(staking_classic::UnappliedSlashes::<rc::Runtime>::get(4).len(), 1);
// we have stored a total of 13 offences, in 7 pages
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 13);
assert_eq!(OffenceSendQueue::<rc::Runtime>::pages(), 7);
});
// Ensure AH still does not receive any offence while migration is ongoing.
shared::in_ah(|| {
assert_eq!(shared::CounterRCAHNewOffence::get(), 0);
assert_eq!(shared::CounterRCAHSessionReport::get(), 0);
assert_eq!(ah::mock::staking_events_since_last_call(), vec![]);
});
// let's migrate state from RC::staking-classic to AH::staking-async
shared::migrate_state();
// SCENE (3): AHM migration ends.
shared::in_rc(|| {
// Before migration ends, verify we have 9 buffered offences across multiple sessions
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 13);
ah_client::Pallet::<rc::Runtime>::on_migration_end();
assert_eq!(ah_client::Mode::<rc::Runtime>::get(), OperatingMode::Active);
// `MaxOffenceBatchSize` is set to 2 in this test, so we will send over the 13 offences
// in 7 next blocks.
assert_eq!(crate::rc::MaxOffenceBatchSize::get(), 2);
// in the first block we process the half finished page.
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 12);
assert_eq!(shared::CounterRCAHNewOffence::get(), 1);
// the rest are full pages of 2 offences each.
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 10);
assert_eq!(shared::CounterRCAHNewOffence::get(), 3);
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 8);
assert_eq!(shared::CounterRCAHNewOffence::get(), 5);
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 6);
assert_eq!(shared::CounterRCAHNewOffence::get(), 7);
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 4);
assert_eq!(shared::CounterRCAHNewOffence::get(), 9);
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 2);
assert_eq!(shared::CounterRCAHNewOffence::get(), 11);
rc::roll_next();
assert_eq!(OffenceSendQueue::<rc::Runtime>::count(), 0);
assert_eq!(shared::CounterRCAHNewOffence::get(), 13);
});
let mut post_migration_era_reward_points = 0;
shared::in_ah(|| {
// all offences are received by rc-client. The count of these events are not 13, because
// in each batch we group offenders by session. Note that the sum of offenders count is
// indeed 13.
assert_eq!(
rc_client_events_since_last_call(),
vec![
rc_client::Event::OffenceReceived { slash_session: 14, offences_count: 1 },
rc_client::Event::OffenceReceived { slash_session: 14, offences_count: 2 },
rc_client::Event::OffenceReceived { slash_session: 13, offences_count: 2 },
rc_client::Event::OffenceReceived { slash_session: 13, offences_count: 2 },
rc_client::Event::OffenceReceived { slash_session: 12, offences_count: 2 },
rc_client::Event::OffenceReceived { slash_session: 12, offences_count: 2 },
rc_client::Event::OffenceReceived { slash_session: 12, offences_count: 2 }
]
);
post_migration_era_reward_points =
pezpallet_staking_async::ErasRewardPoints::<ah::Runtime>::get(1).total;
// staking async has always been in NotForcing, not doing anything since no session
// reports come in
assert_eq!(pezpallet_staking_async::ForceEra::<ah::Runtime>::get(), Forcing::NotForcing);
// Verify all offences were properly queued in staking-async.
// Should have offences for validators 1, 2, and 5 from different sessions (all map to
// era 1)
assert!(pezpallet_staking_async::OffenceQueue::<ah::Runtime>::get(1, 1).is_some());
assert!(pezpallet_staking_async::OffenceQueue::<ah::Runtime>::get(1, 2).is_some());
assert!(pezpallet_staking_async::OffenceQueue::<ah::Runtime>::get(1, 5).is_some());
// Verify specific OffenceRecord structure for all three validators
let offence_record_v1 =
pezpallet_staking_async::OffenceQueue::<ah::Runtime>::get(1, 1).unwrap();
assert_eq!(
offence_record_v1,
pezpallet_staking_async::slashing::OffenceRecord {
reporter: None,
reported_era: 1,
exposure_page: 0,
slash_fraction: Perbill::from_percent(85), /* Should be the highest slash
* fraction for validator 1 */
prior_slash_fraction: Perbill::from_percent(0),
}
);
let offence_record_v2 =
pezpallet_staking_async::OffenceQueue::<ah::Runtime>::get(1, 2).unwrap();
assert_eq!(
offence_record_v2,
pezpallet_staking_async::slashing::OffenceRecord {
reporter: None,
reported_era: 1,
exposure_page: 0,
slash_fraction: Perbill::from_percent(100), /* Should be the highest slash
* fraction for validator 2 */
prior_slash_fraction: Perbill::from_percent(0),
}
);
let offence_record_v5 =
pezpallet_staking_async::OffenceQueue::<ah::Runtime>::get(1, 5).unwrap();
assert_eq!(
offence_record_v5,
pezpallet_staking_async::slashing::OffenceRecord {
reporter: None,
reported_era: 1,
exposure_page: 0,
slash_fraction: Perbill::from_percent(55), /* Should be the highest slash
* fraction for validator 5 */
prior_slash_fraction: Perbill::from_percent(0),
}
);
// NOTE:
// - We sent 13 total offences across 3 sessions and 7 messages (3 offences per session)
// - Each session's offences trigger OffenceReported events when received
// - But only the highest slash fraction per validator per era gets queued for
// processing
// - So we see 13 OffenceReported events but only 3 offences in the processing queue
// - The queue processing happens one offence per block in staking-async pallet.
// Process all queued offences (one offence per block)
// We have 3 offences queued (one per validator), so we need to roll 3 times
for _ in 0..3 {
ah::roll_next();
}
// Check that offences were processed for multiple validators
let staking_events = ah::mock::staking_events_since_last_call();
// Verify that OffenceReported events were emitted for all validators
let offence_reported_events: Vec<_> = staking_events
.iter()
.filter_map(|event| {
if let pezpallet_staking_async::Event::OffenceReported {
offence_era,
validator,
fraction,
} = event
{
Some((offence_era, validator, fraction))
} else {
None
}
})
.collect();
// Verify all OffenceReported events
assert_eq!(
offence_reported_events,
vec![
// 13 offences total, no deduplication here.
(&1, &5, &Perbill::from_percent(40)),
(&1, &2, &Perbill::from_percent(70)),
(&1, &1, &Perbill::from_percent(65)),
(&1, &1, &Perbill::from_percent(85)),
(&1, &5, &Perbill::from_percent(45)),
(&1, &2, &Perbill::from_percent(90)),
(&1, &2, &Perbill::from_percent(80)),
(&1, &1, &Perbill::from_percent(60)),
(&1, &5, &Perbill::from_percent(55)),
(&1, &2, &Perbill::from_percent(25)),
(&1, &1, &Perbill::from_percent(75)),
(&1, &2, &Perbill::from_percent(50)),
(&1, &2, &Perbill::from_percent(100))
]
);
// Verify that SlashComputed events were emitted for all three validators
let slash_computed_events: Vec<_> = staking_events
.iter()
.filter_map(|event| {
if let pezpallet_staking_async::Event::SlashComputed {
offence_era,
slash_era,
offender,
page,
} = event
{
Some((offence_era, slash_era, offender, page))
} else {
None
}
})
.collect();
// Should have SlashComputed events for all three validators. Here we deduplicate for
// maximum per session. Note: OffenceQueue uses StorageDoubleMap with Twox64Concat
// hasher, so iteration order depends on hash(validator_id).
assert_eq!(
slash_computed_events,
vec![
(&1, &3, &5, &0), /* validator 5: offence_era=1, slash_era=3, offender=5,
* page=0 */
(&1, &3, &1, &0), /* validator 1: offence_era=1, slash_era=3, offender=1,
* page=0 */
(&1, &3, &2, &0), /* validator 2: offence_era=1, slash_era=3, offender=2,
* page=0 */
]
);
// Verify that all offences have been processed (no longer in queue)
assert!(
!pezpallet_staking_async::OffenceQueue::<ah::Runtime>::contains_key(1, 1),
"Expected no remaining offences for validator 1"
);
assert!(
!pezpallet_staking_async::OffenceQueue::<ah::Runtime>::contains_key(1, 2),
"Expected no remaining offences for validator 2"
);
assert!(
!pezpallet_staking_async::OffenceQueue::<ah::Runtime>::contains_key(1, 5),
"Expected no remaining offences for validator 5"
);
// offence is deferred by two eras, ie 1 + 2 = 3. Note that this is one era less than
// staking-classic since slashing happens in multi-block, and we want to apply all
// slashes before the era 4 starts.
// Check if at least one of the validators has an unapplied slash
// Check for unapplied slashes for all validators with any of the slash fractions
// Check validator 2 slashes
let slash_v2_100_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(2, Perbill::from_percent(100), 0),
)
.is_some();
let slash_v2_90_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(2, Perbill::from_percent(90), 0),
)
.is_some();
let slash_v2_70_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(2, Perbill::from_percent(70), 0),
)
.is_some();
let total_slashes_v2 =
slash_v2_100_present as u8 + slash_v2_90_present as u8 + slash_v2_70_present as u8;
assert_eq!(
total_slashes_v2, 1,
"Expected exactly 1 unapplied slash for validator 2, got {} (100%:{}, 90%:{}, 70%:{})",
total_slashes_v2, slash_v2_100_present, slash_v2_90_present, slash_v2_70_present
);
// Check validator 1 slashes
let slash_v1_75_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(1, Perbill::from_percent(75), 0),
)
.is_some();
let slash_v1_85_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(1, Perbill::from_percent(85), 0),
)
.is_some();
let slash_v1_65_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(1, Perbill::from_percent(65), 0),
)
.is_some();
let total_slashes_v1 =
slash_v1_75_present as u8 + slash_v1_85_present as u8 + slash_v1_65_present as u8;
assert_eq!(
total_slashes_v1, 1,
"Expected exactly 1 unapplied slash for validator 1, got {} (75%:{}, 85%:{}, 65%:{})",
total_slashes_v1, slash_v1_75_present, slash_v1_85_present, slash_v1_65_present
);
// Check validator 5 slashes
let slash_v5_55_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(5, Perbill::from_percent(55), 0),
)
.is_some();
let slash_v5_45_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(5, Perbill::from_percent(45), 0),
)
.is_some();
let slash_v5_40_present = pezpallet_staking_async::UnappliedSlashes::<ah::Runtime>::get(
3,
(5, Perbill::from_percent(40), 0),
)
.is_some();
let total_slashes_v5 =
slash_v5_55_present as u8 + slash_v5_45_present as u8 + slash_v5_40_present as u8;
assert_eq!(
total_slashes_v5, 1,
"Expected exactly 1 unapplied slash for validator 5, got {} (55%:{}, 45%:{}, 40%:{})",
total_slashes_v5, slash_v5_55_present, slash_v5_45_present, slash_v5_40_present
);
});
// NOW: lets verify we kick off the election at the appropriate time
shared::in_ah(|| {
// roll another block just to strongly prove election is not kicked off at the end of
// migration.
ah::roll_next();
// ensure no election is kicked off yet
// (when election is kicked off, current_era = active_era + 1)
assert_eq!(pezpallet_staking_async::CurrentEra::<ah::Runtime>::get(), Some(1));
assert_eq!(pezpallet_staking_async::ActiveEra::<ah::Runtime>::get().unwrap().index, 1);
// also no session report is sent to AH yet.
assert_eq!(shared::CounterRCAHSessionReport::get(), 0);
});
// It was more than 6 sessions since the last election, on RC, so an election is already
// overdue. The next session change should trigger an election.
let mut post_migration_session_block_number = 0;
shared::in_rc(|| {
rc::roll_to_next_session(true);
post_migration_session_block_number =
pezframe_system::Pallet::<rc::Runtime>::block_number();
// all the buffered validators points are flushed
assert_eq!(ah_client::ValidatorPoints::<rc::Runtime>::iter().count(), 0,);
});
// AH receives the session report.
assert_eq!(shared::CounterRCAHSessionReport::get(), 1);
shared::in_ah(|| {
assert_eq!(pezpallet_staking_async::ActiveEra::<ah::Runtime>::get().unwrap().index, 1);
assert_eq!(pezpallet_staking_async::CurrentEra::<ah::Runtime>::get(), Some(1 + 1));
// by now one session report should have been received in staking
assert_eq!(
ah::rc_client_events_since_last_call(),
vec![rc_client::Event::SessionReportReceived {
end_index: 14,
activation_timestamp: None,
validator_points_counts: 1,
leftover: false
}]
);
assert_eq!(
staking_events_since_last_call(),
vec![pezpallet_staking_async::Event::SessionRotated {
starting_session: 15,
active_era: 1,
planned_era: 2
}]
);
// all expected era reward points are here
assert_eq!(
pezpallet_staking_async::ErasRewardPoints::<ah::Runtime>::get(1).total,
((post_migration_session_block_number - pre_migration_block_number) * 20) as u32 +
// --- ^^ these were buffered in ah-client
post_migration_era_reward_points // --- ^^ these were migrated as part of AHM
);
// ensure new validator is sent once election is complete.
ah::roll_until_matches(|| shared::CounterAHRCValidatorSet::get() == 1, true);
assert_eq!(
ah::staking_events_since_last_call(),
vec![
pezpallet_staking_async::Event::PagedElectionProceeded { page: 2, result: Ok(4) },
pezpallet_staking_async::Event::PagedElectionProceeded { page: 1, result: Ok(0) },
pezpallet_staking_async::Event::PagedElectionProceeded { page: 0, result: Ok(0) }
]
);
});
shared::in_rc(|| {
assert_eq!(
rc::ah_client_events_since_last_call(),
vec![ah_client::Event::ValidatorSetReceived {
id: 2,
new_validator_set_count: 4,
prune_up_to: None,
leftover: false
}]
);
let (planned_era, next_validator_set) =
ah_client::ValidatorSet::<rc::Runtime>::get().unwrap();
assert_eq!(planned_era, 2);
assert!(next_validator_set.len() >= rc::MinimumValidatorSetSize::get() as usize);
});
shared::in_ah(|| {
assert_eq!(pezpallet_staking_async::ActiveEra::<ah::Runtime>::get().unwrap().index, 1);
// at next session, the validator set is queued but not applied yet.
ah::roll_until_matches(|| shared::CounterRCAHSessionReport::get() == 2, true);
// active era is still 1.
assert_eq!(pezpallet_staking_async::ActiveEra::<ah::Runtime>::get().unwrap().index, 1);
// the following session, the validator set is applied.
ah::roll_until_matches(|| shared::CounterRCAHSessionReport::get() == 3, true);
assert_eq!(pezpallet_staking_async::ActiveEra::<ah::Runtime>::get().unwrap().index, 2);
});
}
#[test]
fn election_result_on_ah_reported_to_rc() {
// when election result is complete
// staking stores all exposures
// validators reported to rc
// validators enacted for next session
}
#[test]
fn rc_continues_with_same_validators_if_ah_is_late() {
// A test where ah is late to give us election result.
}
#[test]
fn authoring_points_reported_to_ah_per_session() {}
#[test]
fn rc_is_late_to_report_session_change() {}
#[test]
fn pruning_is_at_least_bonding_duration() {}
#[test]
fn ah_eras_are_delayed() {
// rc will trigger new sessions,
// ah cannot start a new era (election fail)
// we don't prune anything, because era should not be increased.
}
#[test]
fn ah_knows_good_era_duration() {
// era duration and rewards work.
}
#[test]
fn election_provider_fails_to_start() {
// call to ElectionProvider::start fails because it is already ongoing. What do we do?
}
#[test]
fn overlapping_election_wont_happen() {
// while one election is ongoing, enough sessions pass that we think we should plan yet
// another era.
}
#[test]
fn session_report_burst() {
// AH is offline for a while, and it suddenly receives 3 eras worth of session reports. What
// do we do?
}
mod message_queue_sizes {
use super::*;
use pezsp_core::crypto::AccountId32;
#[test]
fn normal_session_report() {
assert_eq!(
rc_client::SessionReport::<AccountId32> {
end_index: 0,
activation_timestamp: Some((0, 0)),
leftover: false,
validator_points: (0..1000)
.map(|i| (AccountId32::from([i as u8; 32]), 1000))
.collect(),
}
.encoded_size(),
36_020
);
}
#[test]
fn normal_validator_set() {
assert_eq!(
rc_client::ValidatorSetReport::<AccountId32> {
id: 42,
leftover: false,
new_validator_set: (0..1000)
.map(|i| AccountId32::from([i as u8; 32]))
.collect(),
prune_up_to: Some(69),
}
.encoded_size(),
32_012
);
}
#[test]
fn offence() {
// when one validator had an offence
let offences = (0..1)
.map(|i| rc_client::Offence::<AccountId32> {
offender: AccountId32::from([i as u8; 32]),
reporters: vec![AccountId32::from([42; 32])],
slash_fraction: Perbill::from_percent(50),
})
.collect::<Vec<_>>();
// offence + session-index
let encoded_size = offences.encoded_size() + 42u32.encoded_size();
assert_eq!(encoded_size, 74);
}
// Kusama has the same configurations as of now.
const PEZKUWI_MAX_DOWNWARD_MESSAGE_SIZE: u32 = 51200; // 50 Kib
const PEZKUWI_MAX_UPWARD_MESSAGE_SIZE: u32 = 65531; // 64 Kib
#[test]
fn maximum_session_report() {
let mut num_validator_points = 1;
loop {
let session_report = rc_client::SessionReport::<AccountId32> {
end_index: 0,
activation_timestamp: Some((0, 0)),
leftover: false,
validator_points: (0..num_validator_points)
.map(|i| (AccountId32::from([i as u8; 32]), 1000))
.collect(),
};
// Note: the real encoded size of the message will be a few bytes more, due to call
// indices and XCM instructions, but not significant.
let encoded_size = session_report.encoded_size() as u32;
if encoded_size > PEZKUWI_MAX_DOWNWARD_MESSAGE_SIZE {
println!(
"SessionReport: num_validator_points: {}, encoded len: {}, max: {:?}, largest session report: {}",
num_validator_points, encoded_size, PEZKUWI_MAX_DOWNWARD_MESSAGE_SIZE, num_validator_points - 1
);
break;
}
num_validator_points += 1;
}
// We can send up to 1422 32-octet validators + u32 points in a single message. This
// should inform the configuration `MaximumValidatorsWithPoints`.
assert_eq!(num_validator_points, 1422);
}
#[test]
fn maximum_validator_set() {
let mut num_validators = 1;
loop {
let validator_set_report = rc_client::ValidatorSetReport::<AccountId32> {
id: 42,
leftover: false,
new_validator_set: (0..num_validators)
.map(|i| AccountId32::from([i as u8; 32]))
.collect(),
prune_up_to: Some(69),
};
// Note: the real encoded size of the message will be a few bytes more, due to call
// indices and XCM instructions, but not significant.
let encoded_size = validator_set_report.encoded_size() as u32;
if encoded_size > PEZKUWI_MAX_DOWNWARD_MESSAGE_SIZE {
println!(
"ValidatorSetReport: num_validators: {}, encoded len: {}, max: {:?}, largest validator set: {}",
num_validators, encoded_size, PEZKUWI_MAX_DOWNWARD_MESSAGE_SIZE, num_validators - 1
);
break;
}
num_validators += 1;
}
// We can send up to 1599 32-octet validator keys (+ other small metadata) in a single
// validator set report.
assert_eq!(num_validators, 1600);
}
#[test]
fn maximum_offence_batched() {
let mut num_offences = 1;
let session_index: u32 = 42;
loop {
let offences = (0..num_offences)
.map(|i| {
(
session_index,
rc_client::Offence::<AccountId32> {
offender: AccountId32::from([i as u8; 32]),
reporters: vec![AccountId32::from([42; 32])],
slash_fraction: Perbill::from_percent(50),
},
)
})
.collect::<Vec<_>>();
let encoded_size = offences.encoded_size();
if encoded_size as u32 > PEZKUWI_MAX_UPWARD_MESSAGE_SIZE {
println!(
"Offence (batched): num_offences: {}, encoded len: {}, max: {:?}, largest offence batch: {}",
num_offences, encoded_size, PEZKUWI_MAX_UPWARD_MESSAGE_SIZE, num_offences - 1
);
break;
}
num_offences += 1;
}
// expectedly, this is a bit less than `offence_legacy` since we encode the session
// index over and over again.
assert_eq!(num_offences, 898);
}
}
}
@@ -0,0 +1,591 @@
// This file is part of Bizinikiwi.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::shared;
use ah_client::OperatingMode;
use frame::{
deps::pezsp_runtime::testing::UintAuthorityId, testing_prelude::*, traits::fungible::Mutate,
};
use pezframe_election_provider_support::{
bounds::{ElectionBounds, ElectionBoundsBuilder},
onchain, SequentialPhragmen,
};
use pezframe_support::traits::FindAuthor;
use pezpallet_staking_async_ah_client as ah_client;
use pezpallet_staking_async_rc_client::{self as rc_client, ValidatorSetReport};
use pezsp_staking::SessionIndex;
pub type T = Runtime;
construct_runtime! {
pub enum Runtime {
System: pezframe_system,
Authorship: pezpallet_authorship,
Balances: pezpallet_balances,
Timestamp: pezpallet_timestamp,
Session: pezpallet_session,
SessionHistorical: pezpallet_session::historical,
Staking: pezpallet_staking,
// NOTE: the session report is given by pezpallet-session to ah-client on-init, and ah-client
// will not send it immediately, but rather store it and sends it over on its own next
// on-init call. Yet, because session comes first here, its on-init is called before
// ah-client, so under normal conditions, the message is sent immediately.
StakingAhClient: pezpallet_staking_async_ah_client,
RootOffences: pezpallet_root_offences,
Offences: pezpallet_offences,
}
}
pub fn roll_next() {
let now = System::block_number();
let next = now + 1;
System::set_block_number(next);
// Timestamp is always the RC block number * 1000
Timestamp::set_timestamp(next * 1000);
Authorship::on_initialize(next);
Session::on_initialize(next);
StakingAhClient::on_initialize(next);
Staking::on_initialize(next);
Staking::on_finalize(next);
}
parameter_types! {
/// The maximum number of blocks to roll before we stop rolling.
///
/// Avoids infinite loops in tests.
pub static MaxRollsUntilCriteria: u16 = 1000;
}
pub fn roll_until_matches(criteria: impl Fn() -> bool, with_ah: bool) {
let mut rolls = 0;
while !criteria() {
roll_next();
rolls += 1;
if with_ah {
if LocalQueue::get().is_some() {
panic!("when local queue is set, you cannot roll ah forward as well!")
}
shared::in_ah(|| {
crate::ah::roll_next();
});
}
if rolls > MaxRollsUntilCriteria::get() {
panic!("rolled too many times");
}
}
}
pub fn roll_to_next_session(with_ah: bool) {
let current_session = pezpallet_session::CurrentIndex::<Runtime>::get();
roll_until_matches(
|| pezpallet_session::CurrentIndex::<Runtime>::get() == current_session + 1,
with_ah,
);
}
pub type AccountId = <Runtime as pezframe_system::Config>::AccountId;
pub type Balance = <Runtime as pezpallet_balances::Config>::Balance;
pub type Hash = <Runtime as pezframe_system::Config>::Hash;
pub type BlockNumber = BlockNumberFor<Runtime>;
#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
impl pezframe_system::Config for Runtime {
type Block = MockBlock<Self>;
type AccountData = pezpallet_balances::AccountData<u128>;
}
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
impl pezpallet_balances::Config for Runtime {
type Balance = u128;
type AccountStore = System;
}
impl pezpallet_timestamp::Config for Runtime {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = ConstU64<3>;
type WeightInfo = ();
}
pub struct ValidatorIdOf;
impl Convert<AccountId, Option<AccountId>> for ValidatorIdOf {
fn convert(a: AccountId) -> Option<AccountId> {
Some(a)
}
}
pub struct OtherSessionHandler;
impl OneSessionHandler<AccountId> for OtherSessionHandler {
type Key = UintAuthorityId;
fn on_genesis_session<'a, I: 'a>(_: I)
where
I: Iterator<Item = (&'a AccountId, Self::Key)>,
AccountId: 'a,
{
}
fn on_new_session<'a, I: 'a>(_: bool, _: I, _: I)
where
I: Iterator<Item = (&'a AccountId, Self::Key)>,
AccountId: 'a,
{
}
fn on_disabled(_validator_index: u32) {}
}
impl BoundToRuntimeAppPublic for OtherSessionHandler {
type Public = UintAuthorityId;
}
frame::deps::pezsp_runtime::impl_opaque_keys! {
pub struct SessionKeys {
pub other: OtherSessionHandler,
}
}
parameter_types! {
pub static Period: BlockNumber = 30;
pub static Offset: BlockNumber = 0;
}
impl pezpallet_session::historical::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type FullIdentification = pezsp_staking::Exposure<AccountId, Balance>;
type FullIdentificationOf = ah_client::DefaultExposureOf<Self>;
}
impl pezpallet_session::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type ValidatorIdOf = ValidatorIdOf;
type ValidatorId = AccountId;
type DisablingStrategy = pezpallet_session::disabling::UpToLimitDisablingStrategy<1>;
type Keys = SessionKeys;
type SessionHandler = <SessionKeys as frame::traits::OpaqueKeys>::KeyTypeIdProviders;
type NextSessionRotation = Self::ShouldEndSession;
type ShouldEndSession = pezpallet_session::PeriodicSessions<Period, Offset>;
// Should be AH-client
type SessionManager = pezpallet_session::historical::NoteHistoricalRoot<Self, StakingAhClient>;
type WeightInfo = ();
type Currency = Balances;
type KeyDeposit = ();
}
parameter_types! {
pub static DefaultAuthor: Option<AccountId> = Some(11);
}
pub struct GetAuthor;
impl FindAuthor<AccountId> for GetAuthor {
fn find_author<'a, I>(_digests: I) -> Option<AccountId>
where
I: 'a + IntoIterator<Item = (pezframe_support::ConsensusEngineId, &'a [u8])>,
{
DefaultAuthor::get()
}
}
impl pezpallet_authorship::Config for Runtime {
type FindAuthor = GetAuthor;
type EventHandler = StakingAhClient;
}
parameter_types! {
pub static MaxBackersPerWinner: u32 = 256;
pub static MaxWinnersPerPage: u32 = 100;
pub static ElectionsBounds: ElectionBounds = ElectionBoundsBuilder::default().build();
}
pub struct OnChainSeqPhragmen;
impl onchain::Config for OnChainSeqPhragmen {
type System = Runtime;
type Solver = SequentialPhragmen<AccountId, Perbill>;
type DataProvider = Staking;
type WeightInfo = ();
type MaxBackersPerWinner = MaxBackersPerWinner;
type MaxWinnersPerPage = MaxWinnersPerPage;
type Bounds = ElectionsBounds;
type Sort = ConstBool<true>;
}
#[derive_impl(pezpallet_staking::config_preludes::TestDefaultConfig)]
impl pezpallet_staking::Config for Runtime {
type OldCurrency = Balances;
type Currency = Balances;
type UnixTime = pezpallet_timestamp::Pallet<Self>;
type AdminOrigin = pezframe_system::EnsureRoot<Self::AccountId>;
type EraPayout = ();
type ElectionProvider = onchain::OnChainExecution<OnChainSeqPhragmen>;
type GenesisElectionProvider = Self::ElectionProvider;
type VoterList = pezpallet_staking::UseNominatorsAndValidatorsMap<Self>;
type TargetList = pezpallet_staking::UseValidatorsMap<Self>;
type BenchmarkingConfig = pezpallet_staking::TestBenchmarkingConfig;
type SlashDeferDuration = ConstU32<2>;
type SessionInterface = Self;
type BondingDuration = ConstU32<3>;
}
impl pezpallet_offences::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type IdentificationTuple = pezpallet_session::historical::IdentificationTuple<Self>;
type OnOffenceHandler = StakingAhClient;
}
impl pezpallet_root_offences::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type OffenceHandler = StakingAhClient;
type ReportOffence = Offences;
}
#[derive(Clone, Debug, PartialEq)]
pub enum OutgoingMessages {
SessionReport(rc_client::SessionReport<AccountId>),
OffenceReportPaged(Vec<(SessionIndex, rc_client::Offence<AccountId>)>),
}
parameter_types! {
pub static MinimumValidatorSetSize: u32 = 4;
pub static MaximumValidatorsWithPoints: u32 = 32;
pub static MaxOffenceBatchSize: u32 = 50;
pub static LocalQueue: Option<Vec<(BlockNumber, OutgoingMessages)>> = None;
pub static LocalQueueLastIndex: usize = 0;
}
impl LocalQueue {
pub fn get_since_last_call() -> Vec<(BlockNumber, OutgoingMessages)> {
if let Some(all) = Self::get() {
let last = LocalQueueLastIndex::get();
LocalQueueLastIndex::set(all.len());
all.into_iter().skip(last).collect()
} else {
panic!("Must set local_queue()!")
}
}
pub fn flush() {
let _ = Self::get_since_last_call();
}
}
impl ah_client::Config for Runtime {
type CurrencyBalance = Balance;
type AdminOrigin = EnsureRoot<AccountId>;
type SendToAssetHub = DeliverToAH;
type AssetHubOrigin = EnsureSigned<AccountId>;
type UnixTime = Timestamp;
type MinimumValidatorSetSize = MinimumValidatorSetSize;
type MaximumValidatorsWithPoints = MaximumValidatorsWithPoints;
type PointsPerBlock = ConstU32<20>;
type MaxOffenceBatchSize = MaxOffenceBatchSize;
type SessionInterface = Self;
type Fallback = Staking;
type MaxSessionReportRetries = ConstU32<3>;
}
parameter_types! {
pub static NextAhDeliveryFails: bool = false;
}
pub struct DeliverToAH;
impl DeliverToAH {
fn ensure_delivery_guard() -> Result<(), ()> {
// `::take` will set it back to the default value, `false`.
if NextAhDeliveryFails::take() {
Err(())
} else {
Ok(())
}
}
}
impl ah_client::SendToAssetHub for DeliverToAH {
type AccountId = AccountId;
fn relay_session_report(
session_report: rc_client::SessionReport<Self::AccountId>,
) -> Result<(), ()> {
Self::ensure_delivery_guard()?;
if let Some(mut local_queue) = LocalQueue::get() {
local_queue
.push((System::block_number(), OutgoingMessages::SessionReport(session_report)));
LocalQueue::set(Some(local_queue));
} else {
shared::CounterRCAHSessionReport::mutate(|x| *x += 1);
shared::in_ah(|| {
let origin = crate::ah::RuntimeOrigin::root();
rc_client::Pallet::<crate::ah::Runtime>::relay_session_report(
origin,
session_report.clone(),
)
.unwrap();
});
}
Ok(())
}
fn relay_new_offence_paged(
offences: Vec<(SessionIndex, pezpallet_staking_async_rc_client::Offence<Self::AccountId>)>,
) -> Result<(), ()> {
Self::ensure_delivery_guard()?;
if let Some(mut local_queue) = LocalQueue::get() {
local_queue
.push((System::block_number(), OutgoingMessages::OffenceReportPaged(offences)));
LocalQueue::set(Some(local_queue));
} else {
shared::in_ah(|| {
crate::shared::CounterRCAHNewOffence::mutate(|x| *x += offences.len() as u32);
let origin = crate::ah::RuntimeOrigin::root();
rc_client::Pallet::<crate::ah::Runtime>::relay_new_offence_paged(
origin,
offences.clone(),
)
.unwrap();
});
}
Ok(())
}
}
parameter_types! {
pub static SessionEventsIndex: usize = 0;
pub static HistoricalEventsIndex: usize = 0;
pub static AhClientEventsIndex: usize = 0;
pub static OffenceEventsIndex: usize = 0;
}
pub fn historical_events_since_last_call() -> Vec<pezpallet_session::historical::Event<Runtime>> {
let all = pezframe_system::Pallet::<Runtime>::read_events_for_pallet::<
pezpallet_session::historical::Event<Runtime>,
>();
let seen = HistoricalEventsIndex::get();
HistoricalEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
pub fn offence_events_since_last_call() -> Vec<pezpallet_offences::Event> {
let all = pezframe_system::Pallet::<Runtime>::read_events_for_pallet::<pezpallet_offences::Event>();
let seen = OffenceEventsIndex::get();
OffenceEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
pub fn session_events_since_last_call() -> Vec<pezpallet_session::Event<Runtime>> {
let all =
pezframe_system::Pallet::<Runtime>::read_events_for_pallet::<pezpallet_session::Event<Runtime>>();
let seen = SessionEventsIndex::get();
SessionEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
pub fn ah_client_events_since_last_call() -> Vec<ah_client::Event<Runtime>> {
let all =
pezframe_system::Pallet::<Runtime>::read_events_for_pallet::<ah_client::Event<Runtime>>();
let seen = AhClientEventsIndex::get();
AhClientEventsIndex::set(all.len());
all.into_iter().skip(seen).collect()
}
const INITIAL_STAKE: Balance = 100;
const INITIAL_BALANCE: Balance = 1000;
pub struct ExtBuilder {
session_keys: Vec<AccountId>,
pre_migration: bool,
}
impl Default for ExtBuilder {
fn default() -> Self {
Self { session_keys: vec![], pre_migration: false }
}
}
impl ExtBuilder {
/// Set this if you want to test the rc-runtime locally. This will push outgoing messages to
/// `LocalQueue` instead of enacting them on AH.
pub fn local_queue(self) -> Self {
LocalQueue::set(Some(Default::default()));
self
}
/// Set the session keys for the given accounts.
pub fn session_keys(mut self, session_keys: Vec<AccountId>) -> Self {
self.session_keys = session_keys;
self
}
/// Don't set 11 as the automatic block author of every block
pub fn no_default_author(self) -> Self {
DefaultAuthor::set(None);
self
}
/// Set the staking-classic state to be pre-AHM-migration state.
pub fn pre_migration(mut self) -> Self {
self.pre_migration = true;
self
}
/// Set the smallest number of validators to be received by ah-client
pub fn minimum_validator_set_size(self, size: u32) -> Self {
MinimumValidatorSetSize::set(size);
self
}
/// Set the maximum offence batch size for testing batching behavior
pub fn max_offence_batch_size(self, size: u32) -> Self {
MaxOffenceBatchSize::set(size);
self
}
pub fn build(self) -> TestState {
let _ = pezsp_tracing::try_init_simple();
let mut t = pezframe_system::GenesisConfig::<T>::default().build_storage().unwrap();
// add pre-migration state to staking-classic.
let operating_mode = if self.pre_migration {
let validators = vec![1, 2, 3, 4, 5, 6, 7, 8]
.into_iter()
.map(|x| (x, x, INITIAL_STAKE, pezpallet_staking::StakerStatus::Validator));
let nominators = vec![
(100, vec![1, 2]),
(101, vec![2, 5]),
(102, vec![1, 1]),
(103, vec![3, 3]),
(104, vec![1, 5]),
(105, vec![5, 4]),
(106, vec![6, 2]),
(107, vec![1, 6]),
(108, vec![2, 7]),
(109, vec![4, 8]),
(110, vec![5, 2]),
(111, vec![6, 6]),
(112, vec![8, 1]),
]
.into_iter()
.map(|(x, y)| (x, x, INITIAL_STAKE, pezpallet_staking_async::StakerStatus::Nominator(y)));
let stakers = validators.chain(nominators).collect::<Vec<_>>();
let balances = stakers
.clone()
.into_iter()
.map(|(x, _, _, _)| (x, INITIAL_BALANCE))
.collect::<Vec<_>>();
pezpallet_balances::GenesisConfig::<Runtime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
pezpallet_staking::GenesisConfig::<Runtime> {
stakers,
validator_count: 4,
minimum_validator_count: 2,
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
// Set ah client in passive mode -> implies it is inactive and staking-classic is
// active.
OperatingMode::Passive
} else {
OperatingMode::Active
};
let mut state: TestState = t.into();
state.execute_with(|| {
// so events can be deposited.
roll_next();
for v in self.session_keys {
// min some funds, create account and ref counts
pezpallet_balances::Pallet::<T>::mint_into(&v, INITIAL_BALANCE).unwrap();
pezpallet_session::Pallet::<T>::set_keys(
RuntimeOrigin::signed(v),
SessionKeys { other: UintAuthorityId(v) },
vec![],
)
.unwrap();
}
ah_client::Mode::<T>::put(operating_mode);
});
state
}
}
/// Progress until `sessions`, receive a `new_validator_set` with `id`, and go forward to `sessions
/// + 1` such that it is queued in pezpallet-session. If `active`, then progress until `sessions + 2`
/// such that it is in the active session validators.
pub(crate) fn receive_validator_set_at(
sessions: SessionIndex,
id: u32,
new_validator_set: Vec<AccountId>,
activate: bool,
) {
roll_until_matches(|| pezpallet_session::CurrentIndex::<Runtime>::get() == sessions, false);
assert_eq!(pezpallet_session::CurrentIndex::<Runtime>::get(), sessions);
let report = ValidatorSetReport {
id,
prune_up_to: None,
leftover: false,
new_validator_set: new_validator_set.clone(),
};
assert_ok!(ah_client::Pallet::<Runtime>::validator_set(RuntimeOrigin::root(), report));
// go forward till one more session such that these validators are in the session queue now
roll_until_matches(|| pezpallet_session::CurrentIndex::<Runtime>::get() == sessions + 1, false);
assert_eq!(pezpallet_session::CurrentIndex::<Runtime>::get(), sessions + 1);
assert_eq!(
pezpallet_session::QueuedKeys::<Runtime>::get()
.into_iter()
.map(|(x, _)| x)
.collect::<Vec<_>>(),
new_validator_set.clone(),
);
if activate {
// if need be go one more session to activate them
roll_until_matches(
|| pezpallet_session::CurrentIndex::<Runtime>::get() == sessions + 2,
false,
);
assert_eq!(pezpallet_session::Validators::<Runtime>::get(), new_validator_set);
}
}
/// The queued validator points in the ah-client sorted by account id.
pub(crate) fn validator_points() -> Vec<(AccountId, u32)> {
let mut points = ah_client::ValidatorPoints::<Runtime>::iter().collect::<Vec<_>>();
points.sort_by(|a, b| a.0.cmp(&b.0));
points
}
@@ -0,0 +1,22 @@
// This file is part of Bizinikiwi.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod mock;
pub mod test;
// re-export for easier use in dual runtime tests.
pub use mock::*;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,124 @@
// This file is part of Bizinikiwi.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::*;
use frame::testing_prelude::*;
use std::cell::UnsafeCell;
thread_local! {
pub static RC_STATE: UnsafeCell<TestState> = UnsafeCell::new(Default::default());
pub static AH_STATE: UnsafeCell<TestState> = UnsafeCell::new(Default::default());
}
parameter_types! {
// counts how many times a new offence message is sent from RC -> AH.
pub static CounterRCAHNewOffence: u32 = 0;
// counts how many times a new session report is sent from RC -> AH.
pub static CounterRCAHSessionReport: u32 = 0;
// counts how many times a validator set is sent to RC.
pub static CounterAHRCValidatorSet: u32 = 0;
}
pub fn put_ah_state(ah: TestState) {
AH_STATE.with(|state| unsafe {
let ptr = state.get();
*ptr = ah;
})
}
pub fn in_ah(f: impl FnMut() -> ()) {
AH_STATE.with(|state| unsafe {
let ptr = state.get();
(*ptr).execute_with(f)
})
}
pub fn put_rc_state(rc: TestState) {
RC_STATE.with(|state| unsafe {
let ptr = state.get();
*ptr = rc;
})
}
pub fn in_rc(f: impl FnMut() -> ()) {
RC_STATE.with(|state| unsafe {
let ptr = state.get();
(*ptr).execute_with(f)
})
}
pub fn migrate_state() {
// NOTE: this is not exhaustive, only migrates the state that is needed for the tests.
shared::in_rc(|| {
let current_era = pezpallet_staking::CurrentEra::<rc::Runtime>::take();
let active_era = pezpallet_staking::ActiveEra::<rc::Runtime>::take().unwrap();
shared::in_ah(|| {
pezpallet_staking_async::CurrentEra::<ah::Runtime>::set(current_era);
pezpallet_staking_async::ActiveEra::<ah::Runtime>::set(Some(
pezpallet_staking_async::ActiveEraInfo {
index: active_era.index,
start: active_era.start,
},
));
});
for (era, reward_points) in pezpallet_staking::ErasRewardPoints::<rc::Runtime>::drain() {
shared::in_ah(|| {
pezpallet_staking_async::ErasRewardPoints::<ah::Runtime>::insert(
era,
pezpallet_staking_async::EraRewardPoints {
total: reward_points.total,
individual: reward_points.individual.clone().try_into().unwrap(),
},
)
});
}
// exposure
for (era, account, overview) in pezpallet_staking::ErasStakersOverview::<rc::Runtime>::drain()
{
shared::in_ah(|| {
pezpallet_staking_async::ErasStakersOverview::<ah::Runtime>::insert(
era, account, overview,
)
});
}
for ((era, account, page), exposure_page) in
pezpallet_staking::ErasStakersPaged::<rc::Runtime>::drain()
{
shared::in_ah(|| {
pezpallet_staking_async::ErasStakersPaged::<ah::Runtime>::insert(
(era, account, page),
exposure_page.clone(),
)
});
}
shared::in_ah(|| {
pezpallet_staking_async::BondedEras::<ah::Runtime>::kill();
});
for (era, session) in pezpallet_staking::BondedEras::<rc::Runtime>::get() {
shared::in_ah(|| {
pezpallet_staking_async::BondedEras::<ah::Runtime>::mutate(|bonded| {
bonded.try_push((era, session)).unwrap()
})
});
}
})
}