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

difftreelog

source

pallets/collator-selection/src/mock.rs8.7 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 frame_support::{34	ord_parameter_types, parameter_types,35	traits::{ConstU32, FindAuthor, ValidatorRegistration},36	PalletId,37};38use frame_system as system;39use frame_system::EnsureSignedBy;40use sp_core::{ConstBool, H256};41use sp_runtime::{42	testing::UintAuthorityId,43	traits::{BlakeTwo256, IdentityLookup, OpaqueKeys},44	BuildStorage, Perbill, RuntimeAppPublic,45};4647use super::*;48use crate as collator_selection;4950type Block = frame_system::mocking::MockBlockU32<Test>;5152// Configure a mock runtime to test the pallet.53frame_support::construct_runtime!(54	pub enum Test {55		System: frame_system,56		Timestamp: pallet_timestamp,57		Session: pallet_session,58		Aura: pallet_aura,59		Balances: pallet_balances,60		CollatorSelection: collator_selection,61		Authorship: pallet_authorship,62	}63);6465parameter_types! {66	pub const BlockHashCount: u32 = 250;67	pub const SS58Prefix: u8 = 42;68}6970impl system::Config for Test {71	type BaseCallFilter = frame_support::traits::Everything;72	type Block = Block;73	type BlockWeights = ();74	type BlockLength = ();75	type DbWeight = ();76	type RuntimeOrigin = RuntimeOrigin;77	type RuntimeCall = RuntimeCall;78	type Nonce = u64;79	type Hash = H256;80	type Hashing = BlakeTwo256;81	type AccountId = u64;82	type Lookup = IdentityLookup<Self::AccountId>;83	type RuntimeEvent = RuntimeEvent;84	type BlockHashCount = BlockHashCount;85	type Version = ();86	type PalletInfo = PalletInfo;87	type AccountData = pallet_balances::AccountData<u64>;88	type OnNewAccount = ();89	type OnKilledAccount = ();90	type SystemWeightInfo = ();91	type SS58Prefix = SS58Prefix;92	type OnSetCode = ();93	type MaxConsumers = ConstU32<16>;94	type RuntimeTask = ();95	type PreInherents = ();96	type PostInherents = ();97	type PostTransactions = ();98	type SingleBlockMigrations = ();99	type MultiBlockMigrator = ();100}101102parameter_types! {103	pub const ExistentialDeposit: u64 = 5;104	pub const MaxReserves: u32 = 50;105	pub const MaxHolds: u32 = 2;106	pub const MaxFreezes: u32 = 2;107}108109impl pallet_balances::Config for Test {110	type Balance = u64;111	type RuntimeEvent = RuntimeEvent;112	type DustRemoval = ();113	type ExistentialDeposit = ExistentialDeposit;114	type AccountStore = System;115	type WeightInfo = ();116	type MaxLocks = ();117	type MaxReserves = MaxReserves;118	type ReserveIdentifier = [u8; 8];119	type FreezeIdentifier = [u8; 16];120	type MaxFreezes = MaxFreezes;121	type RuntimeHoldReason = RuntimeHoldReason;122	type RuntimeFreezeReason = RuntimeFreezeReason;123}124125pub struct Author4;126impl FindAuthor<u64> for Author4 {127	fn find_author<'a, I>(_digests: I) -> Option<u64>128	where129		I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,130	{131		Some(4)132	}133}134135impl pallet_authorship::Config for Test {136	type FindAuthor = Author4;137	type EventHandler = CollatorSelection;138}139140parameter_types! {141	pub const MinimumPeriod: u64 = 1;142}143144impl pallet_timestamp::Config for Test {145	type Moment = u64;146	type OnTimestampSet = Aura;147	type MinimumPeriod = MinimumPeriod;148	type WeightInfo = ();149}150151impl pallet_aura::Config for Test {152	type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;153	type MaxAuthorities = MaxAuthorities;154	type DisabledValidators = ();155	type AllowMultipleBlocksPerSlot = ConstBool<true>;156}157158sp_runtime::impl_opaque_keys! {159	pub struct MockSessionKeys {160		// a key for aura authoring161		pub aura: UintAuthorityId,162	}163}164165impl From<UintAuthorityId> for MockSessionKeys {166	fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self {167		Self { aura }168	}169}170171parameter_types! {172	pub static SessionHandlerCollators: Vec<u64> = Vec::new();173	pub static SessionChangeBlock: u32 = 0;174}175176pub struct TestSessionHandler;177impl pallet_session::SessionHandler<u64> for TestSessionHandler {178	const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID];179	fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) {180		SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>())181	}182	fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {183		SessionChangeBlock::set(System::block_number());184		dbg!(keys.len());185		SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>())186	}187	fn on_before_session_ending() {}188	fn on_disabled(_: u32) {}189}190191parameter_types! {192	pub const Offset: u32 = 0;193	pub const Period: u32 = 10;194}195196impl pallet_session::Config for Test {197	type RuntimeEvent = RuntimeEvent;198	type ValidatorId = <Self as frame_system::Config>::AccountId;199	// we don't have stash and controller, thus we don't need the convert as well.200	type ValidatorIdOf = IdentityCollator;201	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;202	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;203	type SessionManager = CollatorSelection;204	type SessionHandler = TestSessionHandler;205	type Keys = MockSessionKeys;206	type WeightInfo = ();207}208209parameter_types! {210	pub const MaxCollators: u32 = 5;211	pub const LicenseBond: u64 = 10;212	pub const KickThreshold: u32 = 10;213	// the following values do not matter and are meaningless, etc.214	pub const DefaultWeightToFeeCoefficient: u64 = 100_000;215	pub const DefaultMinGasPrice: u64 = 100_000;216	pub const MaxXcmAllowedLocations: u32 = 16;217	pub AppPromotionDailyRate: Perbill = Perbill::from_parts(453_256);218	pub const DayRelayBlocks: u32 = 1;219	pub const LicenceBondIdentifier: [u8; 16] = *b"licenceidentifie";220}221222ord_parameter_types! {223	pub const RootAccount: u64 = 777;224}225226parameter_types! {227	pub const PotId: PalletId = PalletId(*b"PotStake");228	pub const MaxAuthorities: u32 = 100_000;229	pub const SlashRatio: Perbill = Perbill::one();230}231232pub struct IsRegistered;233impl ValidatorRegistration<u64> for IsRegistered {234	fn is_registered(id: &u64) -> bool {235		*id != 7u64236	}237}238239impl Config for Test {240	type RuntimeEvent = RuntimeEvent;241	type RuntimeHoldReason = RuntimeHoldReason;242	type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;243	type PotId = PotId;244	type MaxCollators = MaxCollators;245	type SlashRatio = SlashRatio;246	type TreasuryAccountId = ();247	type ValidatorId = <Self as frame_system::Config>::AccountId;248	type ValidatorIdOf = IdentityCollator;249	type ValidatorRegistration = IsRegistered;250	type Currency = Balances;251	type DesiredCollators = MaxCollators;252	type LicenseBond = LicenseBond;253	type KickThreshold = KickThreshold;254	type WeightInfo = ();255}256257pub fn new_test_ext() -> sp_io::TestExternalities {258	sp_tracing::try_init_simple();259	let mut t = <frame_system::GenesisConfig<Test>>::default()260		.build_storage()261		.unwrap();262	let invulnerables = vec![1, 2];263264	let ed = <Test as pallet_balances::Config>::ExistentialDeposit::get();265266	let balances: Vec<(u64, u64)> = (1..=<Test as Config>::DesiredCollators::get() as u64 + 1)267		.map(|i| (i, 100))268		.chain(core::iter::once((33, ed)))269		.collect();270271	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: u32) {296	for i in System::block_number() + 1..=n {297		System::set_block_number(i);298		<AllPalletsWithSystem as frame_support::traits::OnInitialize<u32>>::on_initialize(i);299	}300}