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

difftreelog

source

pallets/collator-selection/src/mock.rs9.2 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, Call, Storage, Inherent},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 UncleGenerations = ();132	type FilterUncle = ();133	type EventHandler = CollatorSelection;134}135136parameter_types! {137	pub const MinimumPeriod: u64 = 1;138}139140impl pallet_timestamp::Config for Test {141	type Moment = u64;142	type OnTimestampSet = Aura;143	type MinimumPeriod = MinimumPeriod;144	type WeightInfo = ();145}146147impl pallet_aura::Config for Test {148	type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;149	type MaxAuthorities = MaxAuthorities;150	type DisabledValidators = ();151}152153sp_runtime::impl_opaque_keys! {154	pub struct MockSessionKeys {155		// a key for aura authoring156		pub aura: UintAuthorityId,157	}158}159160impl From<UintAuthorityId> for MockSessionKeys {161	fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self {162		Self { aura }163	}164}165166parameter_types! {167	pub static SessionHandlerCollators: Vec<u64> = Vec::new();168	pub static SessionChangeBlock: u64 = 0;169}170171pub struct TestSessionHandler;172impl pallet_session::SessionHandler<u64> for TestSessionHandler {173	const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID];174	fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) {175		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())176	}177	fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {178		SessionChangeBlock::set(System::block_number());179		dbg!(keys.len());180		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())181	}182	fn on_before_session_ending() {}183	fn on_disabled(_: u32) {}184}185186parameter_types! {187	pub const Offset: u64 = 0;188	pub const Period: u64 = 10;189}190191impl pallet_session::Config for Test {192	type RuntimeEvent = RuntimeEvent;193	type ValidatorId = <Self as frame_system::Config>::AccountId;194	// we don't have stash and controller, thus we don't need the convert as well.195	type ValidatorIdOf = IdentityCollator;196	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;197	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;198	type SessionManager = CollatorSelection;199	type SessionHandler = TestSessionHandler;200	type Keys = MockSessionKeys;201	type WeightInfo = ();202}203204parameter_types! {205	pub const MaxCollators: u32 = 5;206	pub const LicenseBond: u64 = 10;207	pub const KickThreshold: u64 = 10;208	// the following values do not matter and are meaningless, etc.209	pub const DefaultWeightToFeeCoefficient: u64 = 100_000;210	pub const DefaultMinGasPrice: u64 = 100_000;211	pub const MaxXcmAllowedLocations: u32 = 16;212	pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);213	pub const DayRelayBlocks: u32 = 1;214}215216impl pallet_configuration::Config for Test {217	type RuntimeEvent = RuntimeEvent;218	type Currency = Balances;219	type DefaultCollatorSelectionMaxCollators = MaxCollators;220	type DefaultCollatorSelectionKickThreshold = KickThreshold;221	type DefaultCollatorSelectionLicenseBond = LicenseBond;222	// the following constants we don't care about223	type DefaultWeightToFeeCoefficient = DefaultWeightToFeeCoefficient;224	type DefaultMinGasPrice = DefaultMinGasPrice;225	type MaxXcmAllowedLocations = MaxXcmAllowedLocations;226	type AppPromotionDailyRate = AppPromotionDailyRate;227	type DayRelayBlocks = DayRelayBlocks;228	type WeightInfo = pallet_configuration::weights::SubstrateWeight<Self>;229}230231ord_parameter_types! {232	pub const RootAccount: u64 = 777;233}234235parameter_types! {236	pub const PotId: PalletId = PalletId(*b"PotStake");237	pub const MaxAuthorities: u32 = 100_000;238	pub const SlashRatio: Perbill = Perbill::one();239}240241pub struct IsRegistered;242impl ValidatorRegistration<u64> for IsRegistered {243	fn is_registered(id: &u64) -> bool {244		if *id == 7u64 {245			false246		} else {247			true248		}249	}250}251252impl Config for Test {253	type RuntimeEvent = RuntimeEvent;254	type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;255	type PotId = PotId;256	type MaxCollators = MaxCollators;257	type SlashRatio = SlashRatio;258	type TreasuryAccountId = ();259	type ValidatorId = <Self as frame_system::Config>::AccountId;260	type ValidatorIdOf = IdentityCollator;261	type ValidatorRegistration = IsRegistered;262	type WeightInfo = ();263}264265pub fn new_test_ext() -> sp_io::TestExternalities {266	sp_tracing::try_init_simple();267	let mut t = frame_system::GenesisConfig::default()268		.build_storage::<Test>()269		.unwrap();270	let invulnerables = vec![1, 2];271272	let balances = vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)];273	let keys = balances274		.iter()275		.map(|&(i, _)| {276			(277				i,278				i,279				MockSessionKeys {280					aura: UintAuthorityId(i),281				},282			)283		})284		.collect::<Vec<_>>();285	let collator_selection = collator_selection::GenesisConfig::<Test> { invulnerables };286	let session = pallet_session::GenesisConfig::<Test> { keys };287	pallet_balances::GenesisConfig::<Test> { balances }288		.assimilate_storage(&mut t)289		.unwrap();290	// collator selection must be initialized before session.291	collator_selection.assimilate_storage(&mut t).unwrap();292	session.assimilate_storage(&mut t).unwrap();293294	t.into()295}296297pub fn initialize_to_block(n: u64) {298	for i in System::block_number() + 1..=n {299		System::set_block_number(i);300		<AllPalletsWithSystem as frame_support::traits::OnInitialize<u64>>::on_initialize(i);301	}302}