Skip to main content

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