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

difftreelog

source

pallets/collator-selection/src/mock.rs9.1 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		Configuration: pallet_configuration::{Pallet, Call, Storage, Event<T>},67	}68);6970parameter_types! {71	pub const BlockHashCount: u64 = 250;72	pub const SS58Prefix: u8 = 42;73}7475impl system::Config for Test {76	type BaseCallFilter = frame_support::traits::Everything;77	type BlockWeights = ();78	type BlockLength = ();79	type DbWeight = ();80	type RuntimeOrigin = RuntimeOrigin;81	type RuntimeCall = RuntimeCall;82	type Index = u64;83	type BlockNumber = u64;84	type Hash = H256;85	type Hashing = BlakeTwo256;86	type AccountId = u64;87	type Lookup = IdentityLookup<Self::AccountId>;88	type Header = Header;89	type RuntimeEvent = RuntimeEvent;90	type BlockHashCount = BlockHashCount;91	type Version = ();92	type PalletInfo = PalletInfo;93	type AccountData = pallet_balances::AccountData<u64>;94	type OnNewAccount = ();95	type OnKilledAccount = ();96	type SystemWeightInfo = ();97	type SS58Prefix = SS58Prefix;98	type OnSetCode = ();99	type MaxConsumers = frame_support::traits::ConstU32<16>;100}101102parameter_types! {103	pub const ExistentialDeposit: u64 = 5;104	pub const MaxReserves: u32 = 50;105}106107impl pallet_balances::Config for Test {108	type Balance = u64;109	type RuntimeEvent = RuntimeEvent;110	type DustRemoval = ();111	type ExistentialDeposit = ExistentialDeposit;112	type AccountStore = System;113	type WeightInfo = ();114	type MaxLocks = ();115	type MaxReserves = MaxReserves;116	type ReserveIdentifier = [u8; 8];117}118119pub struct Author4;120impl FindAuthor<u64> for Author4 {121	fn find_author<'a, I>(_digests: I) -> Option<u64>122	where123		I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,124	{125		Some(4)126	}127}128129impl pallet_authorship::Config for Test {130	type FindAuthor = Author4;131	type EventHandler = CollatorSelection;132}133134parameter_types! {135	pub const MinimumPeriod: u64 = 1;136}137138impl pallet_timestamp::Config for Test {139	type Moment = u64;140	type OnTimestampSet = Aura;141	type MinimumPeriod = MinimumPeriod;142	type WeightInfo = ();143}144145impl pallet_aura::Config for Test {146	type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;147	type MaxAuthorities = MaxAuthorities;148	type DisabledValidators = ();149}150151sp_runtime::impl_opaque_keys! {152	pub struct MockSessionKeys {153		// a key for aura authoring154		pub aura: UintAuthorityId,155	}156}157158impl From<UintAuthorityId> for MockSessionKeys {159	fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self {160		Self { aura }161	}162}163164parameter_types! {165	pub static SessionHandlerCollators: Vec<u64> = Vec::new();166	pub static SessionChangeBlock: u64 = 0;167}168169pub struct TestSessionHandler;170impl pallet_session::SessionHandler<u64> for TestSessionHandler {171	const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID];172	fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) {173		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())174	}175	fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {176		SessionChangeBlock::set(System::block_number());177		dbg!(keys.len());178		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())179	}180	fn on_before_session_ending() {}181	fn on_disabled(_: u32) {}182}183184parameter_types! {185	pub const Offset: u64 = 0;186	pub const Period: u64 = 10;187}188189impl pallet_session::Config for Test {190	type RuntimeEvent = RuntimeEvent;191	type ValidatorId = <Self as frame_system::Config>::AccountId;192	// we don't have stash and controller, thus we don't need the convert as well.193	type ValidatorIdOf = IdentityCollator;194	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;195	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;196	type SessionManager = CollatorSelection;197	type SessionHandler = TestSessionHandler;198	type Keys = MockSessionKeys;199	type WeightInfo = ();200}201202parameter_types! {203	pub const MaxCollators: u32 = 5;204	pub const LicenseBond: u64 = 10;205	pub const KickThreshold: u64 = 10;206	// the following values do not matter and are meaningless, etc.207	pub const DefaultWeightToFeeCoefficient: u64 = 100_000;208	pub const DefaultMinGasPrice: u64 = 100_000;209	pub const MaxXcmAllowedLocations: u32 = 16;210	pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);211	pub const DayRelayBlocks: u32 = 1;212}213214impl pallet_configuration::Config for Test {215	type RuntimeEvent = RuntimeEvent;216	type Currency = Balances;217	type DefaultCollatorSelectionMaxCollators = MaxCollators;218	type DefaultCollatorSelectionKickThreshold = KickThreshold;219	type DefaultCollatorSelectionLicenseBond = LicenseBond;220	// the following constants we don't care about221	type DefaultWeightToFeeCoefficient = DefaultWeightToFeeCoefficient;222	type DefaultMinGasPrice = DefaultMinGasPrice;223	type MaxXcmAllowedLocations = MaxXcmAllowedLocations;224	type AppPromotionDailyRate = AppPromotionDailyRate;225	type DayRelayBlocks = DayRelayBlocks;226	type WeightInfo = pallet_configuration::weights::SubstrateWeight<Self>;227}228229ord_parameter_types! {230	pub const RootAccount: u64 = 777;231}232233parameter_types! {234	pub const PotId: PalletId = PalletId(*b"PotStake");235	pub const MaxAuthorities: u32 = 100_000;236	pub const SlashRatio: Perbill = Perbill::one();237}238239pub struct IsRegistered;240impl ValidatorRegistration<u64> for IsRegistered {241	fn is_registered(id: &u64) -> bool {242		if *id == 7u64 {243			false244		} else {245			true246		}247	}248}249250impl Config for Test {251	type RuntimeEvent = RuntimeEvent;252	type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;253	type PotId = PotId;254	type MaxCollators = MaxCollators;255	type SlashRatio = SlashRatio;256	type TreasuryAccountId = ();257	type ValidatorId = <Self as frame_system::Config>::AccountId;258	type ValidatorIdOf = IdentityCollator;259	type ValidatorRegistration = IsRegistered;260	type WeightInfo = ();261}262263pub fn new_test_ext() -> sp_io::TestExternalities {264	sp_tracing::try_init_simple();265	let mut t = frame_system::GenesisConfig::default()266		.build_storage::<Test>()267		.unwrap();268	let invulnerables = vec![1, 2];269270	let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)];271	let keys = balances272		.iter()273		.map(|&(i, _)| {274			(275				i,276				i,277				MockSessionKeys {278					aura: UintAuthorityId(i),279				},280			)281		})282		.collect::<Vec<_>>();283	let collator_selection = collator_selection::GenesisConfig::<Test> { invulnerables };284	let session = pallet_session::GenesisConfig::<Test> { keys };285	pallet_balances::GenesisConfig::<Test> { balances }286		.assimilate_storage(&mut t)287		.unwrap();288	// collator selection must be initialized before session.289	collator_selection.assimilate_storage(&mut t).unwrap();290	session.assimilate_storage(&mut t).unwrap();291292	t.into()293}294295pub fn initialize_to_block(n: u64) {296	for i in System::block_number() + 1..=n {297		System::set_block_number(i);298		<AllPalletsWithSystem as frame_support::traits::OnInitialize<u64>>::on_initialize(i);299	}300}