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

difftreelog

source

pallets/collator-selection/src/mock.rs8.5 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 {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: u64 = 250;67	pub const SS58Prefix: u8 = 42;68}6970impl system::Config for Test {71	type BaseCallFilter = frame_support::traits::Everything;72	type BlockWeights = ();73	type BlockLength = ();74	type DbWeight = ();75	type RuntimeOrigin = RuntimeOrigin;76	type RuntimeCall = RuntimeCall;77	type Nonce = u64;78	type Hash = H256;79	type Hashing = BlakeTwo256;80	type AccountId = u64;81	type Lookup = IdentityLookup<Self::AccountId>;82	type RuntimeEvent = RuntimeEvent;83	type BlockHashCount = BlockHashCount;84	type Version = ();85	type PalletInfo = PalletInfo;86	type AccountData = pallet_balances::AccountData<u64>;87	type OnNewAccount = ();88	type OnKilledAccount = ();89	type SystemWeightInfo = ();90	type SS58Prefix = SS58Prefix;91	type OnSetCode = ();92	type MaxConsumers = frame_support::traits::ConstU32<16>;93}9495parameter_types! {96	pub const ExistentialDeposit: u64 = 5;97	pub const MaxReserves: u32 = 50;98	pub const MaxHolds: u32 = 2;99	pub const MaxFreezes: u32 = 2;100}101102impl pallet_balances::Config for Test {103	type Balance = u64;104	type RuntimeEvent = RuntimeEvent;105	type DustRemoval = ();106	type ExistentialDeposit = ExistentialDeposit;107	type AccountStore = System;108	type WeightInfo = ();109	type MaxLocks = ();110	type MaxReserves = MaxReserves;111	type ReserveIdentifier = [u8; 8];112	type FreezeIdentifier = [u8; 16];113	type MaxHolds = MaxHolds;114	type MaxFreezes = MaxFreezes;115}116117pub struct Author4;118impl FindAuthor<u64> for Author4 {119	fn find_author<'a, I>(_digests: I) -> Option<u64>120	where121		I: 'a + IntoIterator<Item = (frame_support::ConsensusEngineId, &'a [u8])>,122	{123		Some(4)124	}125}126127impl pallet_authorship::Config for Test {128	type FindAuthor = Author4;129	type EventHandler = CollatorSelection;130}131132parameter_types! {133	pub const MinimumPeriod: u64 = 1;134}135136impl pallet_timestamp::Config for Test {137	type Moment = u64;138	type OnTimestampSet = Aura;139	type MinimumPeriod = MinimumPeriod;140	type WeightInfo = ();141}142143impl pallet_aura::Config for Test {144	type AuthorityId = sp_consensus_aura::sr25519::AuthorityId;145	type MaxAuthorities = MaxAuthorities;146	type DisabledValidators = ();147}148149sp_runtime::impl_opaque_keys! {150	pub struct MockSessionKeys {151		// a key for aura authoring152		pub aura: UintAuthorityId,153	}154}155156impl From<UintAuthorityId> for MockSessionKeys {157	fn from(aura: sp_runtime::testing::UintAuthorityId) -> Self {158		Self { aura }159	}160}161162parameter_types! {163	pub static SessionHandlerCollators: Vec<u64> = Vec::new();164	pub static SessionChangeBlock: u64 = 0;165}166167pub struct TestSessionHandler;168impl pallet_session::SessionHandler<u64> for TestSessionHandler {169	const KEY_TYPE_IDS: &'static [sp_runtime::KeyTypeId] = &[UintAuthorityId::ID];170	fn on_genesis_session<Ks: OpaqueKeys>(keys: &[(u64, Ks)]) {171		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())172	}173	fn on_new_session<Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {174		SessionChangeBlock::set(System::block_number());175		dbg!(keys.len());176		SessionHandlerCollators::set(keys.into_iter().map(|(a, _)| *a).collect::<Vec<_>>())177	}178	fn on_before_session_ending() {}179	fn on_disabled(_: u32) {}180}181182parameter_types! {183	pub const Offset: u64 = 0;184	pub const Period: u64 = 10;185}186187impl pallet_session::Config for Test {188	type RuntimeEvent = RuntimeEvent;189	type ValidatorId = <Self as frame_system::Config>::AccountId;190	// we don't have stash and controller, thus we don't need the convert as well.191	type ValidatorIdOf = IdentityCollator;192	type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>;193	type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>;194	type SessionManager = CollatorSelection;195	type SessionHandler = TestSessionHandler;196	type Keys = MockSessionKeys;197	type WeightInfo = ();198}199200parameter_types! {201	pub const MaxCollators: u32 = 5;202	pub const LicenseBond: u64 = 10;203	pub const KickThreshold: u64 = 10;204	// the following values do not matter and are meaningless, etc.205	pub const DefaultWeightToFeeCoefficient: u64 = 100_000;206	pub const DefaultMinGasPrice: u64 = 100_000;207	pub const MaxXcmAllowedLocations: u32 = 16;208	pub AppPromotionDailyRate: Perbill = Perbill::from_rational(5u32, 10_000);209	pub const DayRelayBlocks: u32 = 1;210	pub const LicenceBondIdentifier: [u8; 16] = *b"licenceidentifie";211}212213ord_parameter_types! {214	pub const RootAccount: u64 = 777;215}216217parameter_types! {218	pub const PotId: PalletId = PalletId(*b"PotStake");219	pub const MaxAuthorities: u32 = 100_000;220	pub const SlashRatio: Perbill = Perbill::one();221}222223pub struct IsRegistered;224impl ValidatorRegistration<u64> for IsRegistered {225	fn is_registered(id: &u64) -> bool {226		*id != 7u64227	}228}229230impl Config for Test {231	type RuntimeEvent = RuntimeEvent;232	type UpdateOrigin = EnsureSignedBy<RootAccount, u64>;233	type PotId = PotId;234	type MaxCollators = MaxCollators;235	type SlashRatio = SlashRatio;236	type TreasuryAccountId = ();237	type ValidatorId = <Self as frame_system::Config>::AccountId;238	type ValidatorIdOf = IdentityCollator;239	type ValidatorRegistration = IsRegistered;240	type LicenceBondIdentifier = LicenceBondIdentifier;241	type Currency = Balances;242	type DesiredCollators = MaxCollators;243	type LicenseBond = LicenseBond;244	type KickThreshold = KickThreshold;245	type WeightInfo = ();246}247248pub fn new_test_ext() -> sp_io::TestExternalities {249	sp_tracing::try_init_simple();250	let mut t = frame_system::GenesisConfig::default()251		.build_storage::<Test>()252		.unwrap();253	let invulnerables = vec![1, 2];254255	let ed = <Test as pallet_balances::Config>::ExistentialDeposit::get();256257	let balances: Vec<(u64, u64)> = (1..=<Test as Config>::DesiredCollators::get() as u64 + 1)258		.map(|i| (i, 100))259		.chain(core::iter::once((33, ed)))260		.collect();261262	let keys = balances263		.iter()264		.map(|&(i, _)| {265			(266				i,267				i,268				MockSessionKeys {269					aura: UintAuthorityId(i),270				},271			)272		})273		.collect::<Vec<_>>();274	let collator_selection = collator_selection::GenesisConfig::<Test> { invulnerables };275	let session = pallet_session::GenesisConfig::<Test> { keys };276	pallet_balances::GenesisConfig::<Test> { balances }277		.assimilate_storage(&mut t)278		.unwrap();279	// collator selection must be initialized before session.280	collator_selection.assimilate_storage(&mut t).unwrap();281	session.assimilate_storage(&mut t).unwrap();282283	t.into()284}285286pub fn initialize_to_block(n: u64) {287	for i in System::block_number() + 1..=n {288		System::set_block_number(i);289		<AllPalletsWithSystem as frame_support::traits::OnInitialize<u64>>::on_initialize(i);290	}291}