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

difftreelog

source

runtime/common/mod.rs10.3 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/// A Block signed with a Justification67pub type SignedBlock = generic::SignedBlock<Block>;68/// Frontier wrapped extrinsic69pub type UncheckedExtrinsic =70	fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;71/// Header type.72pub type Header = generic::Header<BlockNumber, BlakeTwo256>;73/// Block type.74pub type Block = generic::Block<Header, UncheckedExtrinsic>;75/// BlockId type as expected by this runtime.76pub type BlockId = generic::BlockId<Block>;7778impl_opaque_keys! {79	pub struct SessionKeys {80		pub aura: Aura,81	}82}8384/// The version information used to identify this runtime when compiled natively.85#[cfg(feature = "std")]86pub fn native_version() -> NativeVersion {87	NativeVersion {88		runtime_version: crate::VERSION,89		can_author_with: Default::default(),90	}91}9293pub type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;9495pub type SignedExtra = (96	frame_system::CheckSpecVersion<Runtime>,97	frame_system::CheckTxVersion<Runtime>,98	frame_system::CheckGenesis<Runtime>,99	frame_system::CheckEra<Runtime>,100	frame_system::CheckNonce<Runtime>,101	frame_system::CheckWeight<Runtime>,102	maintenance::CheckMaintenance,103	identity::DisableIdentityCalls,104	ChargeTransactionPayment,105	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,106	pallet_ethereum::FakeTransactionFinalizer<Runtime>,107);108109/// Executive: handles dispatch to the various modules.110pub type Executive = frame_executive::Executive<111	Runtime,112	Block,113	frame_system::ChainContext<Runtime>,114	Runtime,115	AllPalletsWithSystem,116	AuraToCollatorSelection,117>;118119type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;120121pub struct DealWithFees;122impl OnUnbalanced<NegativeImbalance> for DealWithFees {123	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {124		if let Some(fees) = fees_then_tips.next() {125			// for fees, 100% to treasury126			let mut split = fees.ration(100, 0);127			if let Some(tips) = fees_then_tips.next() {128				// for tips, if any, 100% to treasury129				tips.ration_merge_into(100, 0, &mut split);130			}131			Treasury::on_unbalanced(split.0);132			// Author::on_unbalanced(split.1);133		}134	}135}136137pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);138139impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider140	for RelayChainBlockNumberProvider<T>141{142	type BlockNumber = BlockNumber;143144	fn current_block_number() -> Self::BlockNumber {145		cumulus_pallet_parachain_system::Pallet::<T>::validation_data()146			.map(|d| d.relay_parent_number)147			.unwrap_or_default()148	}149	#[cfg(feature = "runtime-benchmarks")]150	fn set_block_number(block: Self::BlockNumber) {151		cumulus_pallet_parachain_system::RelaychainDataProvider::<T>::set_block_number(block)152	}153}154155pub(crate) struct CheckInherents;156157impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {158	fn check_inherents(159		block: &Block,160		relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,161	) -> sp_inherents::CheckInherentsResult {162		let relay_chain_slot = relay_state_proof163			.read_slot()164			.expect("Could not read the relay chain slot from the proof");165166		let inherent_data =167			cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(168				relay_chain_slot,169				sp_std::time::Duration::from_secs(6),170			)171			.create_inherent_data()172			.expect("Could not create the timestamp inherent data");173174		inherent_data.check_extrinsics(block)175	}176}177178#[derive(codec::Encode, codec::Decode)]179pub enum XCMPMessage<XAccountId, XBalance> {180	/// Transfer tokens to the given account from the Parachain account.181	TransferToken(XAccountId, XBalance),182}183184pub struct AuraToCollatorSelection;185impl frame_support::traits::OnRuntimeUpgrade for AuraToCollatorSelection {186	fn on_runtime_upgrade() -> Weight {187		#[cfg(feature = "collator-selection")]188		{189			use frame_support::{BoundedVec, storage::migration};190			use sp_runtime::{traits::OpaqueKeys, RuntimeAppPublic};191			use pallet_session::SessionManager;192			use crate::config::pallets::MaxCollators;193194			let mut weight = <Runtime as frame_system::Config>::DbWeight::get().reads(1);195196			let version = migration::get_storage_value::<()>(197				b"AuraToCollatorSelection",198				b"StorageVersion",199				&[],200			);201202			let should_upgrade = version.is_none();203204			if should_upgrade {205				log::info!(206					target: "runtime::aura_to_collator_selection",207					"Running migration of Aura authorities to Collator Selection invulnerables"208				);209210				let invulnerables = pallet_aura::Pallet::<Runtime>::authorities()211					.iter()212					.cloned()213					.filter_map(|authority_id| {214						weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));215						let vec = authority_id.to_raw_vec();216						let slice = vec.as_slice();217						let array: Option<[u8; 32]> = match slice.try_into() {218							Ok(a) => Some(a),219							Err(_) => {220								log::error!("Failed to convert an Aura authority to a Collator Selection invulnerable: {:?}", authority_id);221								None222							},223						};224						array.map(|a| (AccountId::from(a), authority_id))225					})226					.collect::<Vec<_>>();227228				let bounded_invulnerables = BoundedVec::<_, MaxCollators>::try_from(229					invulnerables230						.iter()231						.cloned()232						.map(|(acc, _)| acc)233						.collect::<Vec<_>>(),234				)235				.expect("Existing collators/invulnerables are more than MaxCollators");236237				<pallet_collator_selection::Invulnerables<Runtime>>::put(bounded_invulnerables);238239				let keys = invulnerables240					.into_iter()241					.map(|(acc, aura)| {242						(243							acc.clone(),          // account id244							acc,                  // validator id245							SessionKeys { aura }, // session keys246						)247					})248					.collect::<Vec<_>>();249250				for (account, val, keys) in keys.iter() {251					for id in <Runtime as pallet_session::Config>::Keys::key_ids() {252						<pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)253					}254					<pallet_session::NextKeys<Runtime>>::insert(val, keys);255					// todo exercise caution, the following is taken from genesis256					if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)257						.is_err()258					{259						log::warn!(260							"We have entered an error with incrementing consumers without limit during the migration"261						);262						// This will leak a provider reference, however it only happens once (at263						// genesis) so it's really not a big deal and we assume that the user wants to264						// do this since it's the only way a non-endowed account can contain a session265						// key.266						frame_system::Pallet::<Runtime>::inc_providers(account);267					}268				}269270				let initial_validators_0 =271					<Runtime as pallet_session::Config>::SessionManager::new_session(0)272						.unwrap_or_else(|| {273							frame_support::print(274								"No initial validator provided by `SessionManager`, use \275							session config keys to generate initial validator set.",276							);277							keys.iter().map(|x| x.1.clone()).collect()278						});279				/*assert!(280					!initial_validators_0.is_empty(),281					"Empty validator set for session 0 in (pseudo) genesis block!"282				);*/283284				let initial_validators_1 =285					<Runtime as pallet_session::Config>::SessionManager::new_session(1)286						.unwrap_or_else(|| initial_validators_0.clone());287				/*assert!(288					!initial_validators_1.is_empty(),289					"Empty validator set for session 1 in (pseudo) genesis block!"290				);*/291292				let queued_keys: Vec<_> = initial_validators_1293					.iter()294					.cloned()295					.map(|v| {296						(297							v.clone(),298							<pallet_session::NextKeys<Runtime>>::get(&v)299								.expect("Validator in session 1 missing keys!"),300						)301					})302					.collect();303304				// Tell everyone about the genesis session keys -- Aura must've already initialized it305				//<Runtime as pallet_session::Config>::SessionHandler::on_genesis_session::<<Runtime as pallet_session::Config>::Keys>(&queued_keys);306307				<pallet_session::Validators<Runtime>>::put(initial_validators_0);308				<pallet_session::QueuedKeys<Runtime>>::put(queued_keys);309310				<Runtime as pallet_session::Config>::SessionManager::start_session(0);311312				log::info!(313					target: "runtime::aura_to_collator_selection",314					"Migration of Aura authorities to Collator Selection invulnerables is complete."315				);316317				migration::put_storage_value::<()>(318					b"AuraToCollatorSelection",319					b"StorageVersion",320					&[],321					(),322				);323324				weight += <Runtime as frame_system::Config>::DbWeight::get().writes(1)325			} else {326				log::info!(327					target: "runtime::aura_to_collator_selection",328					"The storage migration has already been flagged as complete. No migration needs to be done.",329				);330			}331332			weight333		}334335		#[cfg(not(feature = "collator-selection"))]336		{337			Weight::zero()338		}339	}340}