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

difftreelog

source

runtime/common/mod.rs10.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/>.1617pub mod config;18pub mod construct_runtime;19pub mod dispatch;20pub mod ethereum;21pub mod identity;22pub mod instance;23pub mod maintenance;24pub mod runtime_apis;2526#[cfg(feature = "unique-scheduler")]27pub mod scheduler;2829pub mod sponsoring;30#[allow(missing_docs)]31pub mod weights;3233#[cfg(test)]34pub mod tests;3536use sp_core::H160;37use frame_support::{38	traits::{Currency, OnUnbalanced, Imbalance},39	weights::Weight,40};41use sp_runtime::{42	generic,43	traits::{BlakeTwo256, BlockNumberProvider},44	impl_opaque_keys,45};46use sp_std::vec::Vec;4748#[cfg(feature = "std")]49use sp_version::NativeVersion;5051use crate::{52	Runtime, RuntimeCall, Balances, Treasury, Aura, Signature, AllPalletsWithSystem,53	InherentDataExt,54};55use up_common::types::{AccountId, BlockNumber};5657#[macro_export]58macro_rules! unsupported {59	() => {60		pallet_common::unsupported!($crate::Runtime)61	};62}6364/// The address format for describing accounts.65pub type Address = sp_runtime::MultiAddress<AccountId, ()>;66/// Block header type as expected by this runtime.67pub type Header = generic::Header<BlockNumber, BlakeTwo256>;68/// Block type as expected by this runtime.69pub type Block = generic::Block<Header, UncheckedExtrinsic>;70/// A Block signed with a Justification71pub type SignedBlock = generic::SignedBlock<Block>;72/// BlockId type as expected by this runtime.73pub type BlockId = generic::BlockId<Block>;7475impl_opaque_keys! {76	pub struct SessionKeys {77		pub aura: Aura,78	}79}8081/// The version information used to identify this runtime when compiled natively.82#[cfg(feature = "std")]83pub fn native_version() -> NativeVersion {84	NativeVersion {85		runtime_version: crate::VERSION,86		can_author_with: Default::default(),87	}88}8990pub type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;9192pub type SignedExtra = (93	frame_system::CheckSpecVersion<Runtime>,94	frame_system::CheckTxVersion<Runtime>,95	frame_system::CheckGenesis<Runtime>,96	frame_system::CheckEra<Runtime>,97	frame_system::CheckNonce<Runtime>,98	frame_system::CheckWeight<Runtime>,99	maintenance::CheckMaintenance,100	identity::DisableIdentityCalls,101	ChargeTransactionPayment,102	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,103	pallet_ethereum::FakeTransactionFinalizer<Runtime>,104);105106/// Unchecked extrinsic type as expected by this runtime.107pub type UncheckedExtrinsic =108	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;109110/// Extrinsic type that has already been checked.111pub type CheckedExtrinsic =112	fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;113114/// Executive: handles dispatch to the various modules.115pub type Executive = frame_executive::Executive<116	Runtime,117	Block,118	frame_system::ChainContext<Runtime>,119	Runtime,120	AllPalletsWithSystem,121	AuraToCollatorSelection,122>;123124type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;125126pub struct DealWithFees;127impl OnUnbalanced<NegativeImbalance> for DealWithFees {128	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {129		if let Some(fees) = fees_then_tips.next() {130			// for fees, 100% to treasury131			let mut split = fees.ration(100, 0);132			if let Some(tips) = fees_then_tips.next() {133				// for tips, if any, 100% to treasury134				tips.ration_merge_into(100, 0, &mut split);135			}136			Treasury::on_unbalanced(split.0);137			// Author::on_unbalanced(split.1);138		}139	}140}141142pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);143144impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider145	for RelayChainBlockNumberProvider<T>146{147	type BlockNumber = BlockNumber;148149	fn current_block_number() -> Self::BlockNumber {150		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()151			.map(|d| d.relay_parent_number)152			.unwrap_or_default()153	}154	#[cfg(feature = "runtime-benchmarks")]155	fn set_block_number(block: Self::BlockNumber) {156		cumulus_pallet_parachain_system::RelaychainDataProvider::<T>::set_block_number(block)157	}158}159160pub(crate) struct CheckInherents;161162impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {163	fn check_inherents(164		block: &Block,165		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,166	) -> sp_inherents::CheckInherentsResult {167		let relay_chain_slot = relay_state_proof168			.read_slot()169			.expect("Could not read the relay chain slot from the proof");170171		let inherent_data =172			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(173				relay_chain_slot,174				sp_std::time::Duration::from_secs(6),175			)176			.create_inherent_data()177			.expect("Could not create the timestamp inherent data");178179		inherent_data.check_extrinsics(block)180	}181}182183#[derive(codec::Encode, codec::Decode)]184pub enum XCMPMessage<XAccountId, XBalance> {185	/// Transfer tokens to the given account from the Parachain account.186	TransferToken(XAccountId, XBalance),187}188189pub struct AuraToCollatorSelection;190impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {191	fn on_runtime_upgrade() -> Weight {192		#[cfg(feature = "collator-selection")]193		{194			use frame_support::{BoundedVec, storage::migration};195			use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};196			use pallet_session::SessionManager;197			use crate::config::pallets::MaxCollators;198199			let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);200201			let version = migration::get_storage_value::<()>(202				b"AuraToCollatorSelection",203				b"StorageVersion",204				&[],205			);206207			let should_upgrade = version.is_none();208209			if should_upgrade {210				log::info!(211					target: "runtime::aura_to_collator_selection",212					"Running migration of Aura authorities to Collator Selection invulnerables"213				);214215				let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()216					.iter()217					.cloned()218					.filter_map(|authority_id| {219						weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));220						let vec = authority_id.to_raw_vec();221						let slice = vec.as_slice();222						let array: Option<[u8; 32]> = match slice.try_into() {223							Ok(a) => Some(a),224							Err(_) => {225								log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);226								None227							},228						};229						array.map(|a| (AccountId::from(a), authority_id))230					})231					.collect::<Vec<_>>();232233				let bounded_invulnerables = BoundedVec::<_, MaxCollators>::try_from(234					invulnerables235						.iter()236						.cloned()237						.map(|(acc, _)| acc)238						.collect::<Vec<_>>(),239				)240				.expect("Existing collators/invulnerables are more than MaxCollators");241242				<pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);243244				let keys = invulnerables245					.into_iter()246					.map(|(acc, aura)| {247						(248							acc.clone(),          // account id249							acc,                  // validator id250							SessionKeys { aura }, // session keys251						)252					})253					.collect::<Vec<_>>();254255				for (account, val, keys) in keys.iter() {256					for id in <Runtime as pallet_session::Config>::Keys::key_ids() {257						<pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)258					}259					<pallet_session::NextKeys<Runtime>>::insert(val, keys);260					// todo exercise caution, the following is taken from genesis261					if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)262						.is_err()263					{264						log::warn!(265							"We have entered an error with incrementing consumers without limit during the migration"266						);267						// This will leak a provider reference, however it only happens once (at268						// genesis) so it's really not a big deal and we assume that the user wants to269						// do this since it's the only way a non-endowed account can contain a session270						// key.271						frame_system::Pallet::<Runtime>::inc_providers(account);272					}273				}274275				let initial_validators_0 =276					<Runtime as pallet_session::Config>::SessionManager::new_session(0)277						.unwrap_or_else(|| {278							frame_support::print(279								"No initial validator provided by `SessionManager`, use \280							session config keys to generate initial validator set.",281							);282							keys.iter().map(|x| x.1.clone()).collect()283						});284				/*assert!(285					!initial_validators_0.is_empty(),286					"Empty validator set for session 0 in (pseudo) genesis block!"287				);*/288289				let initial_validators_1 =290					<Runtime as pallet_session::Config>::SessionManager::new_session(1)291						.unwrap_or_else(|| initial_validators_0.clone());292				/*assert!(293					!initial_validators_1.is_empty(),294					"Empty validator set for session 1 in (pseudo) genesis block!"295				);*/296297				let queued_keys: Vec<_> = initial_validators_1298					.iter()299					.cloned()300					.map(|v| {301						(302							v.clone(),303							<pallet_session::NextKeys<Runtime>>::get(&v)304								.expect("Validator in session 1 missing keys!"),305						)306					})307					.collect();308309				// Tell everyone about the genesis session keys -- Aura must've already initialized it310				//<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);311312				<pallet_session::Validators<Runtime>>::put(initial_validators_0);313				<pallet_session::QueuedKeys<Runtime>>::put(queued_keys);314315				<Runtime as pallet_session::Config>::SessionManager::start_session(0);316317				log::info!(318					target: "runtime::aura_to_collator_selection",319					"Migration of Aura authorities to Collator Selection invulnerables is complete."320				);321322				migration::put_storage_value::<()>(323					b"AuraToCollatorSelection",324					b"StorageVersion",325					&[],326					(),327				);328329				weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)330			} else {331				log::info!(332					target: "runtime::aura_to_collator_selection",333					"The storage migration has already been flagged as complete. No migration needs to be done.",334				);335			}336337			weight338		}339340		#[cfg(not(feature = "collator-selection"))]341		{342			Weight::zero()343		}344	}345}