referrerpolicy=no-referrer-when-downgrade

glutton_westend_runtime/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! # Glutton Westend Runtime
17//!
18//! The purpose of the Glutton parachain is to do stress testing on the Kusama
19//! network. This runtime targets the Westend runtime to allow development
20//! separate to the Kusama runtime.
21//!
22//! There may be multiple instances of the Glutton parachain deployed and
23//! connected to its parent relay chain.
24//!
25//! These parachains are not holding any real value. Their purpose is to stress
26//! test the network.
27//!
28//! ### Governance
29//!
30//! Glutton defers its governance (namely, its `Root` origin), to its Relay
31//! Chain parent, Kusama (or Westend for development purposes).
32//!
33//! ### XCM
34//!
35//! Since the main goal of Glutton is solely stress testing, the parachain will
36//! only be able receive XCM messages from the Relay Chain via DMP. This way the
37//! Glutton parachains will be able to listen for upgrades that are coming from
38//! the Relay chain.
39
40#![cfg_attr(not(feature = "std"), no_std)]
41#![recursion_limit = "256"]
42
43// Make the WASM binary available.
44#[cfg(feature = "std")]
45include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
46
47pub mod genesis_config_presets;
48pub mod weights;
49pub mod xcm_config;
50
51extern crate alloc;
52
53use alloc::{vec, vec::Vec};
54use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
55use sp_api::impl_runtime_apis;
56pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
57use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
58use sp_runtime::{
59	generic, impl_opaque_keys,
60	traits::{BlakeTwo256, Block as BlockT},
61	transaction_validity::{TransactionSource, TransactionValidity},
62	ApplyExtrinsicResult,
63};
64#[cfg(feature = "std")]
65use sp_version::NativeVersion;
66use sp_version::RuntimeVersion;
67
68use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
69pub use frame_support::{
70	construct_runtime, derive_impl,
71	dispatch::DispatchClass,
72	genesis_builder_helper::{build_state, get_preset},
73	parameter_types,
74	traits::{
75		ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything, IsInVec, Randomness,
76	},
77	weights::{
78		constants::{
79			BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND,
80		},
81		IdentityFee, Weight,
82	},
83	PalletId, StorageValue,
84};
85use frame_system::{
86	limits::{BlockLength, BlockWeights},
87	EnsureRoot,
88};
89use parachains_common::{AccountId, Signature};
90#[cfg(any(feature = "std", test))]
91pub use sp_runtime::BuildStorage;
92pub use sp_runtime::{Perbill, Permill};
93use testnet_parachains_constants::westend::consensus::*;
94
95impl_opaque_keys! {
96	pub struct SessionKeys {
97		pub aura: Aura,
98	}
99}
100
101#[sp_version::runtime_version]
102pub const VERSION: RuntimeVersion = RuntimeVersion {
103	spec_name: alloc::borrow::Cow::Borrowed("glutton-westend"),
104	impl_name: alloc::borrow::Cow::Borrowed("glutton-westend"),
105	authoring_version: 1,
106	spec_version: 1_019_003,
107	impl_version: 0,
108	apis: RUNTIME_API_VERSIONS,
109	transaction_version: 1,
110	system_version: 1,
111};
112
113/// The version information used to identify this runtime when compiled natively.
114#[cfg(feature = "std")]
115pub fn native_version() -> NativeVersion {
116	NativeVersion { runtime_version: VERSION, can_author_with: Default::default() }
117}
118
119/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
120/// This is used to limit the maximal weight of a single extrinsic.
121const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
122/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
123/// by  Operational  extrinsics.
124const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
125
126parameter_types! {
127	pub const BlockHashCount: BlockNumber = 4096;
128	pub const Version: RuntimeVersion = VERSION;
129	pub RuntimeBlockLength: BlockLength =
130		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
131	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
132		.base_block(BlockExecutionWeight::get())
133		.for_class(DispatchClass::all(), |weights| {
134			weights.base_extrinsic = ExtrinsicBaseWeight::get();
135		})
136		.for_class(DispatchClass::Normal, |weights| {
137			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
138		})
139		.for_class(DispatchClass::Operational, |weights| {
140			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
141			// Operational transactions have some extra reserved space, so that they
142			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
143			weights.reserved = Some(
144				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
145			);
146		})
147		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
148		.build_or_panic();
149	pub const SS58Prefix: u8 = 42;
150}
151
152#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)]
153impl frame_system::Config for Runtime {
154	type AccountId = AccountId;
155	type Nonce = Nonce;
156	type Hash = Hash;
157	type Block = Block;
158	type BlockHashCount = BlockHashCount;
159	type Version = Version;
160	type BlockWeights = RuntimeBlockWeights;
161	type BlockLength = RuntimeBlockLength;
162	type SS58Prefix = SS58Prefix;
163	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
164	type MaxConsumers = frame_support::traits::ConstU32<16>;
165}
166
167parameter_types! {
168	// We do anything the parent chain tells us in this runtime.
169	pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(2);
170	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
171}
172
173type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook<
174	Runtime,
175	RELAY_CHAIN_SLOT_DURATION_MILLIS,
176	3,
177	9,
178>;
179
180impl cumulus_pallet_parachain_system::Config for Runtime {
181	type RuntimeEvent = RuntimeEvent;
182	type OnSystemEvent = ();
183	type SelfParaId = parachain_info::Pallet<Runtime>;
184	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
185	type OutboundXcmpMessageSource = ();
186	type ReservedDmpWeight = ReservedDmpWeight;
187	type XcmpMessageHandler = ();
188	type ReservedXcmpWeight = ();
189	type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
190	type ConsensusHook = ConsensusHook;
191	type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo<Runtime>;
192	type RelayParentOffset = ConstU32<0>;
193}
194
195parameter_types! {
196	pub MessageQueueServiceWeight: Weight = Perbill::from_percent(80) *
197		RuntimeBlockWeights::get().max_block;
198}
199
200impl pallet_message_queue::Config for Runtime {
201	type RuntimeEvent = RuntimeEvent;
202	type WeightInfo = weights::pallet_message_queue::WeightInfo<Runtime>;
203	#[cfg(feature = "runtime-benchmarks")]
204	type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
205		cumulus_primitives_core::AggregateMessageOrigin,
206	>;
207	#[cfg(not(feature = "runtime-benchmarks"))]
208	type MessageProcessor = xcm_builder::ProcessXcmMessage<
209		AggregateMessageOrigin,
210		xcm_executor::XcmExecutor<xcm_config::XcmConfig>,
211		RuntimeCall,
212	>;
213	type Size = u32;
214	type QueueChangeHandler = ();
215	// No XCMP queue pallet deployed.
216	type QueuePausedQuery = ();
217	type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>;
218	type MaxStale = sp_core::ConstU32<8>;
219	type ServiceWeight = MessageQueueServiceWeight;
220	type IdleMaxServiceWeight = MessageQueueServiceWeight;
221}
222
223impl parachain_info::Config for Runtime {}
224
225impl cumulus_pallet_aura_ext::Config for Runtime {}
226
227impl pallet_timestamp::Config for Runtime {
228	type Moment = u64;
229	type OnTimestampSet = Aura;
230	type MinimumPeriod = ConstU64<0>;
231	type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
232}
233
234impl pallet_aura::Config for Runtime {
235	type AuthorityId = AuraId;
236	type DisabledValidators = ();
237	type MaxAuthorities = ConstU32<100_000>;
238	type AllowMultipleBlocksPerSlot = ConstBool<true>;
239	type SlotDuration = ConstU64<2000>;
240}
241
242impl pallet_glutton::Config for Runtime {
243	type RuntimeEvent = RuntimeEvent;
244	type WeightInfo = weights::pallet_glutton::WeightInfo<Runtime>;
245	type AdminOrigin = EnsureRoot<AccountId>;
246}
247
248impl pallet_sudo::Config for Runtime {
249	type RuntimeEvent = RuntimeEvent;
250	type RuntimeCall = RuntimeCall;
251	type WeightInfo = ();
252}
253
254construct_runtime! {
255	pub enum Runtime
256	{
257		System: frame_system = 0,
258		ParachainSystem: cumulus_pallet_parachain_system = 1,
259		ParachainInfo: parachain_info = 2,
260		Timestamp: pallet_timestamp = 3,
261
262		// DMP handler.
263		CumulusXcm: cumulus_pallet_xcm = 10,
264		MessageQueue: pallet_message_queue = 11,
265
266		// The main stage.
267		Glutton: pallet_glutton = 20,
268
269		// Collator support
270		Aura: pallet_aura = 30,
271		AuraExt: cumulus_pallet_aura_ext = 31,
272
273		// Sudo.
274		Sudo: pallet_sudo = 255,
275	}
276}
277
278/// Index of a transaction in the chain.
279pub type Nonce = u32;
280/// A hash of some data used by the chain.
281pub type Hash = sp_core::H256;
282/// An index to a block.
283pub type BlockNumber = u32;
284/// The address format for describing accounts.
285pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
286/// Block header type as expected by this runtime.
287pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
288/// Block type as expected by this runtime.
289pub type Block = generic::Block<Header, UncheckedExtrinsic>;
290/// A Block signed with a Justification
291pub type SignedBlock = generic::SignedBlock<Block>;
292/// BlockId type as expected by this runtime.
293pub type BlockId = generic::BlockId<Block>;
294/// The extension to the basic transaction logic.
295pub type TxExtension = (
296	frame_system::AuthorizeCall<Runtime>,
297	pallet_sudo::CheckOnlySudoAccount<Runtime>,
298	frame_system::CheckNonZeroSender<Runtime>,
299	frame_system::CheckSpecVersion<Runtime>,
300	frame_system::CheckTxVersion<Runtime>,
301	frame_system::CheckGenesis<Runtime>,
302	frame_system::CheckEra<Runtime>,
303	frame_system::CheckWeight<Runtime>,
304	frame_system::WeightReclaim<Runtime>,
305);
306/// Unchecked extrinsic type as expected by this runtime.
307pub type UncheckedExtrinsic =
308	generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
309/// Executive: handles dispatch to the various modules.
310pub type Executive = frame_executive::Executive<
311	Runtime,
312	Block,
313	frame_system::ChainContext<Runtime>,
314	Runtime,
315	AllPalletsWithSystem,
316>;
317
318#[cfg(feature = "runtime-benchmarks")]
319mod benches {
320	frame_benchmarking::define_benchmarks!(
321		[cumulus_pallet_parachain_system, ParachainSystem]
322		[frame_system, SystemBench::<Runtime>]
323		[frame_system_extensions, SystemExtensionsBench::<Runtime>]
324		[pallet_glutton, Glutton]
325		[pallet_message_queue, MessageQueue]
326		[pallet_timestamp, Timestamp]
327	);
328}
329
330impl_runtime_apis! {
331	impl sp_api::Core<Block> for Runtime {
332		fn version() -> RuntimeVersion {
333			VERSION
334		}
335
336		fn execute_block(block: Block) {
337			Executive::execute_block(block)
338		}
339
340		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
341			Executive::initialize_block(header)
342		}
343	}
344
345	impl sp_api::Metadata<Block> for Runtime {
346		fn metadata() -> OpaqueMetadata {
347			OpaqueMetadata::new(Runtime::metadata().into())
348		}
349
350		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
351			Runtime::metadata_at_version(version)
352		}
353
354		fn metadata_versions() -> alloc::vec::Vec<u32> {
355			Runtime::metadata_versions()
356		}
357	}
358
359	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
360		fn slot_duration() -> sp_consensus_aura::SlotDuration {
361			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
362		}
363
364		fn authorities() -> Vec<AuraId> {
365			pallet_aura::Authorities::<Runtime>::get().into_inner()
366		}
367	}
368
369	impl cumulus_primitives_core::RelayParentOffsetApi<Block> for Runtime {
370		fn relay_parent_offset() -> u32 {
371			0
372		}
373	}
374
375	impl cumulus_primitives_aura::AuraUnincludedSegmentApi<Block> for Runtime {
376		fn can_build_upon(
377			included_hash: <Block as BlockT>::Hash,
378			slot: cumulus_primitives_aura::Slot,
379		) -> bool {
380			ConsensusHook::can_build_upon(included_hash, slot)
381		}
382	}
383
384	impl sp_block_builder::BlockBuilder<Block> for Runtime {
385		fn apply_extrinsic(
386			extrinsic: <Block as BlockT>::Extrinsic,
387		) -> ApplyExtrinsicResult {
388			Executive::apply_extrinsic(extrinsic)
389		}
390
391		fn finalize_block() -> <Block as BlockT>::Header {
392			Executive::finalize_block()
393		}
394
395		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
396			data.create_extrinsics()
397		}
398
399		fn check_inherents(block: Block, data: sp_inherents::InherentData) -> sp_inherents::CheckInherentsResult {
400			data.check_extrinsics(&block)
401		}
402	}
403
404	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
405		fn validate_transaction(
406			source: TransactionSource,
407			tx: <Block as BlockT>::Extrinsic,
408			block_hash: <Block as BlockT>::Hash,
409		) -> TransactionValidity {
410			Executive::validate_transaction(source, tx, block_hash)
411		}
412	}
413
414	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
415		fn offchain_worker(header: &<Block as BlockT>::Header) {
416			Executive::offchain_worker(header)
417		}
418	}
419
420	impl sp_session::SessionKeys<Block> for Runtime {
421		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
422			SessionKeys::generate(seed)
423		}
424
425		fn decode_session_keys(
426			encoded: Vec<u8>,
427		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
428			SessionKeys::decode_into_raw_public_keys(&encoded)
429		}
430	}
431
432	impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
433		fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
434			ParachainSystem::collect_collation_info(header)
435		}
436	}
437
438	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
439		fn account_nonce(account: AccountId) -> Nonce {
440			System::account_nonce(account)
441		}
442	}
443
444	#[cfg(feature = "runtime-benchmarks")]
445	impl frame_benchmarking::Benchmark<Block> for Runtime {
446		fn benchmark_metadata(extra: bool) -> (
447			Vec<frame_benchmarking::BenchmarkList>,
448			Vec<frame_support::traits::StorageInfo>,
449		) {
450			use frame_benchmarking::BenchmarkList;
451			use frame_support::traits::StorageInfoTrait;
452			use frame_system_benchmarking::Pallet as SystemBench;
453			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
454
455			let mut list = Vec::<BenchmarkList>::new();
456			list_benchmarks!(list, extra);
457
458			let storage_info = AllPalletsWithSystem::storage_info();
459
460			(list, storage_info)
461		}
462
463		#[allow(non_local_definitions)]
464		fn dispatch_benchmark(
465			config: frame_benchmarking::BenchmarkConfig
466		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
467			use frame_benchmarking::{BenchmarkBatch,  BenchmarkError};
468			use sp_storage::TrackedStorageKey;
469
470			use frame_system_benchmarking::Pallet as SystemBench;
471			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
472			impl frame_system_benchmarking::Config for Runtime {
473				fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
474					ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
475					Ok(())
476				}
477
478				fn verify_set_code() {
479					System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
480				}
481			}
482
483			use frame_support::traits::WhitelistedStorageKeys;
484			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
485
486			let mut batches = Vec::<BenchmarkBatch>::new();
487			let params = (&config, &whitelist);
488			add_benchmarks!(params, batches);
489			Ok(batches)
490		}
491	}
492
493	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
494		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
495			build_state::<RuntimeGenesisConfig>(config)
496		}
497
498		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
499			get_preset::<RuntimeGenesisConfig>(id, &genesis_config_presets::get_preset)
500		}
501
502		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
503			genesis_config_presets::preset_names()
504		}
505	}
506
507	impl cumulus_primitives_core::GetParachainInfo<Block> for Runtime {
508		fn parachain_id() -> ParaId {
509			ParachainInfo::parachain_id()
510		}
511	}
512}
513
514cumulus_pallet_parachain_system::register_validate_block! {
515	Runtime = Runtime,
516	BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,
517}