git.delta.rocks / unique-network / refs/commits / 0d52e2cbc000

difftreelog

source

pallets/collator-selection/src/mock.rs8.6 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}9596parameter_types! {97	pub const ExistentialDeposit: u64 = 5;98	pub const MaxReserves: u32 = 50;99	pub const MaxHolds: u32 = 2;100	pub const MaxFreezes: u32 = 2;101}102103impl pallet_balances::Config for Test {104	type Balance = u64;105	type RuntimeEvent = RuntimeEvent;106	type DustRemoval = ();107	type ExistentialDeposit = ExistentialDeposit;108	type AccountStore = System;109	type WeightInfo = ();110	type MaxLocks = ();111	type MaxReserves = MaxReserves;112	type ReserveIdentifier = [u8; 8];113	type FreezeIdentifier = [u8; 16];114	type MaxHolds = MaxHolds;115	type MaxFreezes = MaxFreezes;116	type RuntimeHoldReason = RuntimeHoldReason;117	type RuntimeFreezeReason = RuntimeFreezeReason;118}119120pub struct Author4;121impl FindAuthor<u64> for Author4 {122	fn find_author<'a, I>(_digests: I) -> Option<u64>123	where124		I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,125	{126		Some(4)127	}128}129130impl pallet_authorship::Config for Test {131	type FindAuthor = Author4;132	type EventHandler = CollatorSelection;133}134135parameter_types! {136	pub const MinimumPeriod: u64 = 1;137}138139impl pallet_timestamp::Config for Test {140	type Moment = u64;141	type OnTimestampSet = Aura;142	type MinimumPeriod = MinimumPeriod;143	type WeightInfo = ();144}145146impl pallet_aura::Config for Test {147	type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;148	type MaxAuthorities = MaxAuthorities;149	type DisabledValidators = ();150	type AllowMultipleBlocksPerSlot = ConstBool<true>;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: u32 = 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.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.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: u32 = 0;188	pub const Period: u32 = 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: u32 = 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_parts(453_256);213	pub const DayRelayBlocks: u32 = 1;214	pub const LicenceBondIdentifier: [u8; 16] = *b"licenceidentifie";215}216217ord_parameter_types! {218	pub const RootAccount: u64 = 777;219}220221parameter_types! {222	pub const PotId: PalletId = PalletId(*b"PotStake");223	pub const MaxAuthorities: u32 = 100_000;224	pub const SlashRatio: Perbill = Perbill::one();225}226227pub struct IsRegistered;228impl ValidatorRegistration<u64> for IsRegistered {229	fn is_registered(id: &u64) -> bool {230		*id != 7u64231	}232}233234impl Config for Test {235	type RuntimeEvent = RuntimeEvent;236	type RuntimeHoldReason = RuntimeHoldReason;237	type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;238	type PotId = PotId;239	type MaxCollators = MaxCollators;240	type SlashRatio = SlashRatio;241	type TreasuryAccountId = ();242	type ValidatorId = <Self as frame_system::Config>::AccountId;243	type ValidatorIdOf = IdentityCollator;244	type ValidatorRegistration = IsRegistered;245	type Currency = Balances;246	type DesiredCollators = MaxCollators;247	type LicenseBond = LicenseBond;248	type KickThreshold = KickThreshold;249	type WeightInfo = ();250}251252pub fn new_test_ext() -> sp_io::TestExternalities {253	sp_tracing::try_init_simple();254	let mut t = <frame_system::GenesisConfig<Test>>::default()255		.build_storage()256		.unwrap();257	let invulnerables = vec![1, 2];258259	let ed = <Test as pallet_balances::Config>::ExistentialDeposit::get();260261	let balances: Vec<(u64, u64)> = (1..=<Test as Config>::DesiredCollators::get() as u64 + 1)262		.map(|i| (i, 100))263		.chain(core::iter::once((33, ed)))264		.collect();265266	let keys = balances267		.iter()268		.map(|&(i, _)| {269			(270				i,271				i,272				MockSessionKeys {273					aura: UintAuthorityId(i),274				},275			)276		})277		.collect::<Vec<_>>();278	let collator_selection = collator_selection::GenesisConfig::<Test> { invulnerables };279	let session = pallet_session::GenesisConfig::<Test> { keys };280	pallet_balances::GenesisConfig::<Test> { balances }281		.assimilate_storage(&mut t)282		.unwrap();283	// collator selection must be initialized before session.284	collator_selection.assimilate_storage(&mut t).unwrap();285	session.assimilate_storage(&mut t).unwrap();286287	t.into()288}289290pub fn initialize_to_block(n: u32) {291	for i in System::block_number() + 1..=n {292		System::set_block_number(i);293		<AllPalletsWithSystem as frame_support::traits::OnInitialize<u32>>::on_initialize(i);294	}295}