git.delta.rocks / unique-network / refs/commits / bce2cc1e9ab8

difftreelog

source

pallets/collator-selection/src/mock.rs8.9 KiBsourcehistory
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// Copyright (C) 2021 Parity Technologies (UK) Ltd.19// SPDX-License-Identifier: Apache-2.02021// Licensed under the Apache License, Version 2.0 (the "License");22// you may not use this file except in compliance with the License.23// You may obtain a copy of the License at24//25// 	http://www.apache.org/licenses/LICENSE-2.026//27// Unless required by applicable law or agreed to in writing, software28// distributed under the License is distributed on an "AS IS" BASIS,29// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.30// See the License for the specific language governing permissions and31// limitations under the License.3233use super::*;34use crate as collator_selection;35use frame_support::{36	ord_parameter_types, parameter_types,37	traits::{FindAuthor, GenesisBuild, ValidatorRegistration},38	PalletId,39};40use frame_system as system;41use frame_system::EnsureSignedBy;42use sp_core::H256;43use sp_runtime::{44	testing::{Header, UintAuthorityId},45	traits::{BlakeTwo256, IdentityLookup, OpaqueKeys},46	Perbill, RuntimeAppPublic,47};4849type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;50type Block = frame_system::mocking::MockBlock<Test>;5152// Configure a mock runtime to test the pallet.53frame_support::construct_runtime!(54	pub enum Test where55		Block = Block,56		NodeBlock = Block,57		UncheckedExtrinsic = UncheckedExtrinsic,58	{59		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},60		Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent},61		Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>},62		Aura: pallet_aura::{Pallet, Storage, Config<T>},63		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},64		CollatorSelection: collator_selection::{Pallet, Call, Storage, Event<T>},65		Authorship: pallet_authorship::{Pallet, Storage},66	}67);6869parameter_types! {70	pub const BlockHashCount: u64 = 250;71	pub const SS58Prefix: u8 = 42;72}7374impl system::Config for Test {75	type BaseCallFilter = frame_support::traits::Everything;76	type BlockWeights = ();77	type BlockLength = ();78	type DbWeight = ();79	type RuntimeOrigin = RuntimeOrigin;80	type RuntimeCall = RuntimeCall;81	type Index = u64;82	type BlockNumber = u64;83	type Hash = H256;84	type Hashing = BlakeTwo256;85	type AccountId = u64;86	type Lookup = IdentityLookup<Self::AccountId>;87	type Header = Header;88	type RuntimeEvent = RuntimeEvent;89	type BlockHashCount = BlockHashCount;90	type Version = ();91	type PalletInfo = PalletInfo;92	type AccountData = pallet_balances::AccountData<u64>;93	type OnNewAccount = ();94	type OnKilledAccount = ();95	type SystemWeightInfo = ();96	type SS58Prefix = SS58Prefix;97	type OnSetCode = ();98	type MaxConsumers = frame_support::traits::ConstU32<16>;99}100101parameter_types! {102	pub const ExistentialDeposit: u64 = 5;103	pub const MaxReserves: u32 = 50;104	pub const MaxHolds: u32 = 2;105	pub const MaxFreezes: u32 = 2;106}107108impl pallet_balances::Config for Test {109	type Balance = u64;110	type RuntimeEvent = RuntimeEvent;111	type DustRemoval = ();112	type ExistentialDeposit = ExistentialDeposit;113	type AccountStore = System;114	type WeightInfo = ();115	type MaxLocks = ();116	type MaxReserves = MaxReserves;117	type ReserveIdentifier = [u8; 8];118	type HoldIdentifier = [u8; 16];119	type FreezeIdentifier = [u8; 16];120	type MaxHolds = MaxHolds;121	type MaxFreezes = MaxFreezes;122}123124pub struct Author4;125impl FindAuthor<u64> for Author4 {126	fn find_author<'a, I>(_digests: I) -> Option<u64>127	where128		I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,129	{130		Some(4)131	}132}133134impl pallet_authorship::Config for Test {135	type FindAuthor = Author4;136	type EventHandler = CollatorSelection;137}138139parameter_types! {140	pub const MinimumPeriod: u64 = 1;141}142143impl pallet_timestamp::Config for Test {144	type Moment = u64;145	type OnTimestampSet = Aura;146	type MinimumPeriod = MinimumPeriod;147	type WeightInfo = ();148}149150impl pallet_aura::Config for Test {151	type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;152	type MaxAuthorities = MaxAuthorities;153	type DisabledValidators = ();154}155156sp_runtime::impl_opaque_keys! {157	pub struct MockSessionKeys {158		// a key for aura authoring159		pub aura: UintAuthorityId,160	}161}162163impl From<UintAuthorityId> for MockSessionKeys {164	fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self {165		Self { aura }166	}167}168169parameter_types! {170	pub static SessionHandlerCollators: Vec<u64> = Vec::new();171	pub static SessionChangeBlock: u64 = 0;172}173174pub struct TestSessionHandler;175impl pallet_session::SessionHandler<u64> for TestSessionHandler {176	const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID];177	fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) {178		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())179	}180	fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {181		SessionChangeBlock::set(System::block_number());182		dbg!(keys.len());183		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())184	}185	fn on_before_session_ending() {}186	fn on_disabled(_: u32) {}187}188189parameter_types! {190	pub const Offset: u64 = 0;191	pub const Period: u64 = 10;192}193194impl pallet_session::Config for Test {195	type RuntimeEvent = RuntimeEvent;196	type ValidatorId = <Self as frame_system::Config>::AccountId;197	// we don't have stash and controller, thus we don't need the convert as well.198	type ValidatorIdOf = IdentityCollator;199	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;200	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;201	type SessionManager = CollatorSelection;202	type SessionHandler = TestSessionHandler;203	type Keys = MockSessionKeys;204	type WeightInfo = ();205}206207parameter_types! {208	pub const MaxCollators: u32 = 5;209	pub const LicenseBond: u64 = 10;210	pub const KickThreshold: u64 = 10;211	// the following values do not matter and are meaningless, etc.212	pub const DefaultWeightToFeeCoefficient: u64 = 100_000;213	pub const DefaultMinGasPrice: u64 = 100_000;214	pub const MaxXcmAllowedLocations: u32 = 16;215	pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);216	pub const DayRelayBlocks: u32 = 1;217	pub const LicenceBondIdentifier: [u8; 16] = *b"licenceidentifie";218}219220ord_parameter_types! {221	pub const RootAccount: u64 = 777;222}223224parameter_types! {225	pub const PotId: PalletId = PalletId(*b"PotStake");226	pub const MaxAuthorities: u32 = 100_000;227	pub const SlashRatio: Perbill = Perbill::one();228}229230pub struct IsRegistered;231impl ValidatorRegistration<u64> for IsRegistered {232	fn is_registered(id: &u64) -> bool {233		*id != 7u64234	}235}236237impl Config for Test {238	type RuntimeEvent = RuntimeEvent;239	type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;240	type PotId = PotId;241	type MaxCollators = MaxCollators;242	type SlashRatio = SlashRatio;243	type TreasuryAccountId = ();244	type ValidatorId = <Self as frame_system::Config>::AccountId;245	type ValidatorIdOf = IdentityCollator;246	type ValidatorRegistration = IsRegistered;247	type LicenceBondIdentifier = LicenceBondIdentifier;248	type Currency = Balances;249	type DesiredCollators = MaxCollators;250	type LicenseBond = LicenseBond;251	type KickThreshold = KickThreshold;252	type WeightInfo = ();253}254255pub fn new_test_ext() -> sp_io::TestExternalities {256	sp_tracing::try_init_simple();257	let mut t = frame_system::GenesisConfig::default()258		.build_storage::<Test>()259		.unwrap();260	let invulnerables = vec![1, 2];261262	let ed = <Test as pallet_balances::Config>::ExistentialDeposit::get();263264	let balances: Vec<(u64, u64)> = (1..=<Test as Config>::DesiredCollators::get() as u64 + 1)265		.map(|i| (i, 100))266		.chain(core::iter::once((33, ed)))267		.collect();268269	let keys = balances270		.iter()271		.map(|&(i, _)| {272			(273				i,274				i,275				MockSessionKeys {276					aura: UintAuthorityId(i),277				},278			)279		})280		.collect::<Vec<_>>();281	let collator_selection = collator_selection::GenesisConfig::<Test> { invulnerables };282	let session = pallet_session::GenesisConfig::<Test> { keys };283	pallet_balances::GenesisConfig::<Test> { balances }284		.assimilate_storage(&mut t)285		.unwrap();286	// collator selection must be initialized before session.287	collator_selection.assimilate_storage(&mut t).unwrap();288	session.assimilate_storage(&mut t).unwrap();289290	t.into()291}292293pub fn initialize_to_block(n: u64) {294	for i in System::block_number() + 1..=n {295		System::set_block_number(i);296		<AllPalletsWithSystem as frame_support::traits::OnInitialize<u64>>::on_initialize(i);297	}298}