referrerpolicy=no-referrer-when-downgrade

substrate_test_runtime/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! The Substrate runtime. This can be compiled with `#[no_std]`, ready for Wasm.
19
20#![cfg_attr(not(feature = "std"), no_std)]
21
22extern crate alloc;
23
24#[cfg(feature = "std")]
25pub mod extrinsic;
26#[cfg(feature = "std")]
27pub mod genesismap;
28pub mod substrate_test_pallet;
29
30#[cfg(not(feature = "std"))]
31use alloc::{vec, vec::Vec};
32use codec::{Decode, DecodeWithMemTracking, Encode};
33use frame_support::{
34	construct_runtime, derive_impl,
35	dispatch::DispatchClass,
36	genesis_builder_helper::{build_state, get_preset},
37	parameter_types,
38	traits::{ConstU32, ConstU64},
39	weights::{
40		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_REF_TIME_PER_SECOND},
41		Weight,
42	},
43};
44use frame_system::{
45	limits::{BlockLength, BlockWeights},
46	CheckNonce, CheckWeight,
47};
48use scale_info::TypeInfo;
49use sp_application_crypto::{ecdsa, ed25519, sr25519, RuntimeAppPublic, Ss58Codec};
50use sp_keyring::Sr25519Keyring;
51
52#[cfg(feature = "bls-experimental")]
53use sp_application_crypto::{bls381, ecdsa_bls381};
54
55use sp_core::OpaqueMetadata;
56use sp_trie::{
57	trie_types::{TrieDBBuilder, TrieDBMutBuilderV1},
58	PrefixedMemoryDB, StorageProof,
59};
60use trie_db::{Trie, TrieMut};
61
62use serde_json::json;
63use sp_api::{decl_runtime_apis, impl_runtime_apis};
64pub use sp_core::hash::H256;
65use sp_genesis_builder::PresetId;
66use sp_inherents::{CheckInherentsResult, InherentData};
67use sp_runtime::{
68	impl_opaque_keys, impl_tx_ext_default,
69	traits::{BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, NumberFor, Verify},
70	transaction_validity::{
71		TransactionSource, TransactionValidity, TransactionValidityError, ValidTransaction,
72	},
73	ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill,
74};
75use sp_version::RuntimeVersion;
76
77pub use sp_consensus_babe::{AllowedSlots, BabeEpochConfiguration, Slot};
78
79pub use pallet_balances::Call as BalancesCall;
80pub use pallet_utility::Call as UtilityCall;
81
82pub type AuraId = sp_consensus_aura::sr25519::AuthorityId;
83#[cfg(feature = "std")]
84pub use extrinsic::{ExtrinsicBuilder, Transfer};
85
86const LOG_TARGET: &str = "substrate-test-runtime";
87
88// Include the WASM binary
89#[cfg(feature = "std")]
90include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
91
92#[cfg(feature = "std")]
93pub mod wasm_binary_logging_disabled {
94	include!(concat!(env!("OUT_DIR"), "/wasm_binary_logging_disabled.rs"));
95}
96
97/// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics.
98#[cfg(feature = "std")]
99pub fn wasm_binary_unwrap() -> &'static [u8] {
100	WASM_BINARY.expect(
101		"Development wasm binary is not available. Testing is only supported with the flag
102		 disabled.",
103	)
104}
105
106/// Wasm binary unwrapped. If built with `SKIP_WASM_BUILD`, the function panics.
107#[cfg(feature = "std")]
108pub fn wasm_binary_logging_disabled_unwrap() -> &'static [u8] {
109	wasm_binary_logging_disabled::WASM_BINARY.expect(
110		"Development wasm binary is not available. Testing is only supported with the flag
111		 disabled.",
112	)
113}
114
115/// Test runtime version.
116#[sp_version::runtime_version]
117pub const VERSION: RuntimeVersion = RuntimeVersion {
118	spec_name: alloc::borrow::Cow::Borrowed("test"),
119	impl_name: alloc::borrow::Cow::Borrowed("parity-test"),
120	authoring_version: 1,
121	spec_version: 2,
122	impl_version: 2,
123	apis: RUNTIME_API_VERSIONS,
124	transaction_version: 1,
125	system_version: 1,
126};
127
128fn version() -> RuntimeVersion {
129	VERSION
130}
131
132/// Transfer data extracted from Extrinsic containing `Balances::transfer_allow_death`.
133#[derive(Clone, PartialEq, Eq, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo)]
134pub struct TransferData {
135	pub from: AccountId,
136	pub to: AccountId,
137	pub amount: Balance,
138	pub nonce: Nonce,
139}
140
141/// The address format for describing accounts.
142pub type Address = sp_core::sr25519::Public;
143pub type Signature = sr25519::Signature;
144#[cfg(feature = "std")]
145pub type Pair = sp_core::sr25519::Pair;
146
147// TODO: Remove after the Checks are migrated to TxExtension.
148/// The extension to the basic transaction logic.
149pub type TxExtension = (
150	(CheckNonce<Runtime>, CheckWeight<Runtime>),
151	CheckSubstrateCall,
152	frame_metadata_hash_extension::CheckMetadataHash<Runtime>,
153	frame_system::WeightReclaim<Runtime>,
154);
155/// The payload being signed in transactions.
156pub type SignedPayload = sp_runtime::generic::SignedPayload<RuntimeCall, TxExtension>;
157/// Unchecked extrinsic type as expected by this runtime.
158pub type Extrinsic =
159	sp_runtime::generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
160
161/// An identifier for an account on this system.
162pub type AccountId = <Signature as Verify>::Signer;
163/// A simple hash type for all our hashing.
164pub type Hash = H256;
165/// The hashing algorithm used.
166pub type Hashing = BlakeTwo256;
167/// The block number type used in this runtime.
168pub type BlockNumber = u64;
169/// Index of a transaction.
170pub type Nonce = u64;
171/// The item of a block digest.
172pub type DigestItem = sp_runtime::generic::DigestItem;
173/// The digest of a block.
174pub type Digest = sp_runtime::generic::Digest;
175/// A test block.
176pub type Block = sp_runtime::generic::Block<Header, Extrinsic>;
177/// A test block's header.
178pub type Header = sp_runtime::generic::Header<BlockNumber, Hashing>;
179/// Balance of an account.
180pub type Balance = u64;
181
182#[cfg(feature = "bls-experimental")]
183mod bls {
184	use sp_application_crypto::{bls381, ecdsa_bls381};
185	pub type Bls381Public = bls381::AppPublic;
186	pub type Bls381Pop = bls381::AppProofOfPossession;
187	pub type EcdsaBls381Public = ecdsa_bls381::AppPublic;
188	pub type EcdsaBls381Pop = ecdsa_bls381::AppProofOfPossession;
189}
190#[cfg(not(feature = "bls-experimental"))]
191mod bls {
192	pub type Bls381Public = ();
193	pub type Bls381Pop = ();
194	pub type EcdsaBls381Public = ();
195	pub type EcdsaBls381Pop = ();
196}
197pub use bls::*;
198
199decl_runtime_apis! {
200	#[api_version(2)]
201	pub trait TestAPI {
202		/// Return the balance of the given account id.
203		fn balance_of(id: AccountId) -> u64;
204		/// A benchmark function that adds one to the given value and returns the result.
205		fn benchmark_add_one(val: &u64) -> u64;
206		/// A benchmark function that adds one to each value in the given vector and returns the
207		/// result.
208		fn benchmark_vector_add_one(vec: &Vec<u64>) -> Vec<u64>;
209		/// A function for that the signature changed in version `2`.
210		#[changed_in(2)]
211		fn function_signature_changed() -> Vec<u64>;
212		/// The new signature.
213		fn function_signature_changed() -> u64;
214		/// trie no_std testing
215		fn use_trie() -> u64;
216		/// Calls function in the loop using never-inlined function pointer
217		fn benchmark_indirect_call() -> u64;
218		/// Calls function in the loop
219		fn benchmark_direct_call() -> u64;
220		/// Allocates vector with given capacity.
221		fn vec_with_capacity(size: u32) -> Vec<u8>;
222		/// Returns the initialized block number.
223		fn get_block_number() -> u64;
224		/// Test that `ed25519` crypto works in the runtime.
225		///
226		/// Returns the signature generated for the message `ed25519` both the public key and proof of possession.
227		fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic, ed25519::AppProofOfPossession);
228		/// Test that `sr25519` crypto works in the runtime.
229		///
230		/// Returns the signature generated for the message `sr25519` both the public key and proof of possession.
231		fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic, sr25519::AppProofOfPossession);
232		/// Test that `ecdsa` crypto works in the runtime.
233		///
234		/// Returns the signature generated for the message `ecdsa` both the public key and proof of possession.
235		fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic, ecdsa::AppProofOfPossession);
236		/// Test that `bls381` crypto works in the runtime
237		///
238		/// Returns both the proof of possession and public key.
239		fn test_bls381_crypto() -> (Bls381Pop, Bls381Public);
240		/// Test that `ecdsa_bls381_crypto` works in the runtime
241		///
242		/// Returns both the proof of possession and public key.
243		fn test_ecdsa_bls381_crypto() -> (EcdsaBls381Pop, EcdsaBls381Public);
244		/// Run various tests against storage.
245		fn test_storage();
246		/// Check a witness.
247		fn test_witness(proof: StorageProof, root: crate::Hash);
248		/// Test that ensures that we can call a function that takes multiple
249		/// arguments.
250		fn test_multiple_arguments(data: Vec<u8>, other: Vec<u8>, num: u32);
251		/// Traces log "Hey I'm runtime."
252		fn do_trace_log();
253		/// Verify the given signature, public & message bundle.
254		fn verify_ed25519(sig: ed25519::Signature, public: ed25519::Public, message: Vec<u8>) -> bool;
255		/// Write the given `value` under the given `key` into the storage and then optional panic.
256		fn write_key_value(key: Vec<u8>, value: Vec<u8>, panic: bool);
257		/// Spin in an infinite loop (for execution-timeout tests).
258		fn spin();
259	}
260}
261
262pub type Executive = frame_executive::Executive<
263	Runtime,
264	Block,
265	frame_system::ChainContext<Runtime>,
266	Runtime,
267	AllPalletsWithSystem,
268>;
269
270#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo)]
271pub struct CheckSubstrateCall;
272
273impl sp_runtime::traits::RefundWeight for CheckSubstrateCall {
274	fn refund(&mut self, _weight: frame_support::weights::Weight) {}
275}
276impl sp_runtime::traits::ExtensionPostDispatchWeightHandler<CheckSubstrateCall>
277	for CheckSubstrateCall
278{
279	fn set_extension_weight(&mut self, _info: &CheckSubstrateCall) {}
280}
281
282impl sp_runtime::traits::Dispatchable for CheckSubstrateCall {
283	type RuntimeOrigin = RuntimeOrigin;
284	type Config = CheckSubstrateCall;
285	type Info = CheckSubstrateCall;
286	type PostInfo = CheckSubstrateCall;
287
288	fn dispatch(
289		self,
290		_origin: Self::RuntimeOrigin,
291	) -> sp_runtime::DispatchResultWithInfo<Self::PostInfo> {
292		panic!("This implementation should not be used for actual dispatch.");
293	}
294}
295
296impl sp_runtime::traits::TransactionExtension<RuntimeCall> for CheckSubstrateCall {
297	const IDENTIFIER: &'static str = "CheckSubstrateCall";
298	type Implicit = ();
299	type Pre = ();
300	type Val = ();
301	impl_tx_ext_default!(RuntimeCall; weight prepare);
302
303	fn validate(
304		&self,
305		origin: <RuntimeCall as Dispatchable>::RuntimeOrigin,
306		call: &RuntimeCall,
307		_info: &DispatchInfoOf<RuntimeCall>,
308		_len: usize,
309		_self_implicit: Self::Implicit,
310		_inherited_implication: &impl Encode,
311		_source: TransactionSource,
312	) -> Result<
313		(ValidTransaction, Self::Val, <RuntimeCall as Dispatchable>::RuntimeOrigin),
314		TransactionValidityError,
315	> {
316		log::trace!(target: LOG_TARGET, "validate");
317		let v = match call {
318			RuntimeCall::SubstrateTest(ref substrate_test_call) => {
319				substrate_test_pallet::validate_runtime_call(substrate_test_call)?
320			},
321			_ => Default::default(),
322		};
323		Ok((v, (), origin))
324	}
325}
326
327construct_runtime!(
328	pub enum Runtime
329	{
330		System: frame_system,
331		Babe: pallet_babe,
332		SubstrateTest: substrate_test_pallet::pallet,
333		Utility: pallet_utility,
334		Balances: pallet_balances,
335	}
336);
337
338/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers.
339/// This is used to limit the maximal weight of a single extrinsic.
340const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);
341/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used
342/// by  Operational  extrinsics.
343const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
344/// Max weight, actual value does not matter for test runtime.
345const MAXIMUM_BLOCK_WEIGHT: Weight =
346	Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
347
348parameter_types! {
349	pub const BlockHashCount: BlockNumber = 2400;
350	pub const Version: RuntimeVersion = VERSION;
351
352	pub RuntimeBlockLength: BlockLength = BlockLength::builder()
353		.max_length(5 * 1024 * 1024)
354		.modify_max_length_for_class(DispatchClass::Normal, |m| {
355			*m = NORMAL_DISPATCH_RATIO * *m
356		})
357		.build();
358
359	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
360		.base_block(BlockExecutionWeight::get())
361		.for_class(DispatchClass::all(), |weights| {
362			weights.base_extrinsic = ExtrinsicBaseWeight::get();
363		})
364		.for_class(DispatchClass::Normal, |weights| {
365			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
366		})
367		.for_class(DispatchClass::Operational, |weights| {
368			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
369			// Operational transactions have some extra reserved space, so that they
370			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
371			weights.reserved = Some(
372				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
373			);
374		})
375		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
376		.build_or_panic();
377}
378
379#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
380impl frame_system::pallet::Config for Runtime {
381	type BlockWeights = RuntimeBlockWeights;
382	type Nonce = Nonce;
383	type AccountId = AccountId;
384	type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
385	type Block = Block;
386	type AccountData = pallet_balances::AccountData<Balance>;
387}
388
389pub mod currency {
390	use crate::Balance;
391	const MILLICENTS: Balance = 1_000_000_000;
392	const CENTS: Balance = 1_000 * MILLICENTS; // assume this is worth about a cent.
393	pub const DOLLARS: Balance = 100 * CENTS;
394}
395
396parameter_types! {
397	pub const ExistentialDeposit: Balance = 1 * currency::DOLLARS;
398	// For weight estimation, we assume that the most locks on an individual account will be 50.
399	// This number may need to be adjusted in the future if this assumption no longer holds true.
400	pub const MaxLocks: u32 = 50;
401	pub const MaxReserves: u32 = 50;
402}
403
404impl pallet_balances::Config for Runtime {
405	type MaxLocks = MaxLocks;
406	type MaxReserves = MaxReserves;
407	type ReserveIdentifier = [u8; 8];
408	type Balance = Balance;
409	type DustRemoval = ();
410	type RuntimeEvent = RuntimeEvent;
411	type ExistentialDeposit = ExistentialDeposit;
412	type AccountStore = System;
413	type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
414	type RuntimeHoldReason = RuntimeHoldReason;
415	type RuntimeFreezeReason = RuntimeFreezeReason;
416	type DoneSlashHandler = ();
417}
418
419impl pallet_utility::Config for Runtime {
420	type RuntimeEvent = RuntimeEvent;
421	type PalletsOrigin = OriginCaller;
422	type RuntimeCall = RuntimeCall;
423	type WeightInfo = ();
424}
425
426impl substrate_test_pallet::Config for Runtime {}
427
428// Required for `pallet_babe::Config`.
429impl pallet_timestamp::Config for Runtime {
430	type Moment = u64;
431	type OnTimestampSet = Babe;
432	type MinimumPeriod = ConstU64<500>;
433	type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
434}
435
436parameter_types! {
437	pub const EpochDuration: u64 = 6;
438}
439
440impl pallet_babe::Config for Runtime {
441	type EpochDuration = EpochDuration;
442	type ExpectedBlockTime = ConstU64<10_000>;
443	type EpochChangeTrigger = pallet_babe::SameAuthoritiesForever;
444	type DisabledValidators = ();
445	type KeyOwnerProof = sp_core::Void;
446	type EquivocationReportSystem = ();
447	type WeightInfo = ();
448	type MaxAuthorities = ConstU32<10>;
449	type MaxNominators = ConstU32<100>;
450}
451
452/// Adds one to the given input and returns the final result.
453#[inline(never)]
454fn benchmark_add_one(i: u64) -> u64 {
455	i + 1
456}
457
458fn code_using_trie() -> u64 {
459	let pairs = [
460		(b"0103000000000000000464".to_vec(), b"0400000000".to_vec()),
461		(b"0103000000000000000469".to_vec(), b"0401000000".to_vec()),
462	]
463	.to_vec();
464
465	let mut mdb = PrefixedMemoryDB::default();
466	let mut root = core::default::Default::default();
467	{
468		let mut t = TrieDBMutBuilderV1::<Hashing>::new(&mut mdb, &mut root).build();
469		for (key, value) in &pairs {
470			if t.insert(key, value).is_err() {
471				return 101;
472			}
473		}
474	}
475
476	let trie = TrieDBBuilder::<Hashing>::new(&mdb, &root).build();
477	let res = if let Ok(iter) = trie.iter() { iter.flatten().count() as u64 } else { 102 };
478
479	res
480}
481
482/// The test owner to test proof of possession generation and verification for the session keys
483pub const TEST_OWNER: &[u8; 5] = b"owner";
484
485impl_opaque_keys! {
486	pub struct SessionKeys {
487		pub ed25519: ed25519::AppPublic,
488		pub sr25519: sr25519::AppPublic,
489		pub ecdsa: ecdsa::AppPublic,
490	}
491}
492
493pub const TEST_RUNTIME_BABE_EPOCH_CONFIGURATION: BabeEpochConfiguration = BabeEpochConfiguration {
494	c: (3, 10),
495	allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
496};
497
498impl_runtime_apis! {
499	impl sp_api::Core<Block> for Runtime {
500		fn version() -> RuntimeVersion {
501			version()
502		}
503
504		fn execute_block(block: <Block as BlockT>::LazyBlock) {
505			log::trace!(target: LOG_TARGET, "execute_block: {block:#?}");
506			Executive::execute_block(block);
507		}
508
509		fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
510			log::trace!(target: LOG_TARGET, "initialize_block: {header:#?}");
511			Executive::initialize_block(header)
512		}
513	}
514
515	impl sp_api::Metadata<Block> for Runtime {
516		fn metadata() -> OpaqueMetadata {
517			OpaqueMetadata::new(Runtime::metadata().into())
518		}
519
520		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
521			Runtime::metadata_at_version(version)
522		}
523		fn metadata_versions() -> alloc::vec::Vec<u32> {
524			Runtime::metadata_versions()
525		}
526	}
527
528	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
529		fn validate_transaction(
530			source: TransactionSource,
531			utx: <Block as BlockT>::Extrinsic,
532			block_hash: <Block as BlockT>::Hash,
533		) -> TransactionValidity {
534			let validity = Executive::validate_transaction(source, utx.clone(), block_hash);
535			log::trace!(target: LOG_TARGET, "validate_transaction {:?} {:?}", utx, validity);
536			validity
537		}
538	}
539
540	impl sp_block_builder::BlockBuilder<Block> for Runtime {
541		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
542			Executive::apply_extrinsic(extrinsic)
543		}
544
545		fn finalize_block() -> <Block as BlockT>::Header {
546			log::trace!(target: LOG_TARGET, "finalize_block");
547			Executive::finalize_block()
548		}
549
550		fn inherent_extrinsics(_data: InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
551			vec![]
552		}
553
554		fn check_inherents(_block: <Block as BlockT>::LazyBlock, _data: InherentData) -> CheckInherentsResult {
555			CheckInherentsResult::new()
556		}
557	}
558
559	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
560		fn account_nonce(account: AccountId) -> Nonce {
561			System::account_nonce(account)
562		}
563	}
564
565	impl self::TestAPI<Block> for Runtime {
566		fn balance_of(id: AccountId) -> u64 {
567			Balances::free_balance(id)
568		}
569
570		fn benchmark_add_one(val: &u64) -> u64 {
571			val + 1
572		}
573
574		fn benchmark_vector_add_one(vec: &Vec<u64>) -> Vec<u64> {
575			let mut vec = vec.clone();
576			vec.iter_mut().for_each(|v| *v += 1);
577			vec
578		}
579
580		fn function_signature_changed() -> u64 {
581			1
582		}
583
584		fn use_trie() -> u64 {
585			code_using_trie()
586		}
587
588		fn benchmark_indirect_call() -> u64 {
589			let function = benchmark_add_one;
590			(0..1000).fold(0, |p, i| p + function(i))
591		}
592		fn benchmark_direct_call() -> u64 {
593			(0..1000).fold(0, |p, i| p + benchmark_add_one(i))
594		}
595
596		fn vec_with_capacity(size: u32) -> Vec<u8> {
597			Vec::with_capacity(size as usize)
598		}
599
600		fn get_block_number() -> u64 {
601			System::block_number()
602		}
603
604		fn test_ed25519_crypto() -> (ed25519::AppSignature, ed25519::AppPublic, ed25519::AppProofOfPossession) {
605			test_ed25519_crypto()
606		}
607
608		fn test_sr25519_crypto() -> (sr25519::AppSignature, sr25519::AppPublic, sr25519::AppProofOfPossession) {
609			test_sr25519_crypto()
610		}
611
612		fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic, ecdsa::AppProofOfPossession) {
613			test_ecdsa_crypto()
614		}
615
616		#[cfg(feature = "bls-experimental")]
617		fn test_bls381_crypto() -> (Bls381Pop, Bls381Public) {
618			test_bls381_crypto()
619		}
620
621		#[cfg(feature = "bls-experimental")]
622		fn test_ecdsa_bls381_crypto() -> (EcdsaBls381Pop, EcdsaBls381Public) {
623			test_ecdsa_bls381_crypto()
624		}
625
626		#[cfg(not(feature = "bls-experimental"))]
627		fn test_bls381_crypto() -> (Bls381Pop, Bls381Public) {
628			((),())
629		}
630
631		#[cfg(not(feature = "bls-experimental"))]
632		fn test_ecdsa_bls381_crypto() -> (EcdsaBls381Pop, EcdsaBls381Public) {
633			((), ())
634		}
635
636		fn test_storage() {
637			test_read_storage();
638			test_read_child_storage();
639		}
640
641		fn test_witness(proof: StorageProof, root: crate::Hash) {
642			test_witness(proof, root);
643		}
644
645		fn test_multiple_arguments(data: Vec<u8>, other: Vec<u8>, num: u32) {
646			assert_eq!(&data[..], &other[..]);
647			assert_eq!(data.len(), num as usize);
648		}
649
650		fn do_trace_log() {
651			log::trace!(target: "test", "Hey I'm runtime");
652
653			let data = "THIS IS TRACING";
654
655			tracing::trace!(target: "test", %data, "Hey, I'm tracing");
656		}
657
658		fn verify_ed25519(sig: ed25519::Signature, public: ed25519::Public, message: Vec<u8>) -> bool {
659			sp_io::crypto::ed25519_verify(&sig, &message, &public)
660		}
661
662		fn write_key_value(key: Vec<u8>, value: Vec<u8>, panic: bool) {
663			sp_io::storage::set(&key, &value);
664
665			if panic {
666				panic!("I'm just following my master");
667			}
668		}
669
670		fn spin() {
671			let mut i = 0u64;
672			loop {
673				i = core::hint::black_box(i).wrapping_add(1);
674			}
675		}
676	}
677
678	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
679		fn slot_duration() -> sp_consensus_aura::SlotDuration {
680			sp_consensus_aura::SlotDuration::from_millis(1000)
681		}
682
683		fn authorities() -> Vec<AuraId> {
684			SubstrateTest::authorities().into_iter().map(|auth| AuraId::from(auth)).collect()
685		}
686	}
687
688	impl sp_consensus_babe::BabeApi<Block> for Runtime {
689		fn configuration() -> sp_consensus_babe::BabeConfiguration {
690			let epoch_config = Babe::epoch_config().unwrap_or(TEST_RUNTIME_BABE_EPOCH_CONFIGURATION);
691			sp_consensus_babe::BabeConfiguration {
692				slot_duration: Babe::slot_duration(),
693				epoch_length: EpochDuration::get(),
694				c: epoch_config.c,
695				authorities: Babe::authorities().to_vec(),
696				randomness: Babe::randomness(),
697				allowed_slots: epoch_config.allowed_slots,
698			}
699		}
700
701		fn current_epoch_start() -> Slot {
702			Babe::current_epoch_start()
703		}
704
705		fn current_epoch() -> sp_consensus_babe::Epoch {
706			Babe::current_epoch()
707		}
708
709		fn next_epoch() -> sp_consensus_babe::Epoch {
710			Babe::next_epoch()
711		}
712
713		fn submit_report_equivocation_unsigned_extrinsic(
714			_equivocation_proof: sp_consensus_babe::EquivocationProof<
715			<Block as BlockT>::Header,
716			>,
717			_key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
718		) -> Option<()> {
719			None
720		}
721
722		fn generate_key_ownership_proof(
723			_slot: sp_consensus_babe::Slot,
724			_authority_id: sp_consensus_babe::AuthorityId,
725		) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
726			None
727		}
728	}
729
730	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
731		fn offchain_worker(header: &<Block as BlockT>::Header) {
732			let ext = Extrinsic::new_bare(
733				substrate_test_pallet::pallet::Call::storage_change{
734					key:b"some_key".encode(),
735					value:Some(header.number.encode())
736				}.into(),
737			);
738			sp_io::offchain::submit_transaction(ext.encode()).unwrap();
739			Executive::offchain_worker(header);
740		}
741	}
742
743	impl sp_session::SessionKeys<Block> for Runtime {
744		fn generate_session_keys(owner: Vec<u8>, _: Option<Vec<u8>>) -> sp_session::OpaqueGeneratedSessionKeys {
745			SessionKeys::generate(&owner, None).into()
746		}
747
748		fn decode_session_keys(
749			encoded: Vec<u8>,
750		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
751			SessionKeys::decode_into_raw_public_keys(&encoded)
752		}
753	}
754
755	impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
756		fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
757			Vec::new()
758		}
759
760		fn current_set_id() -> sp_consensus_grandpa::SetId {
761			0
762		}
763
764		fn submit_report_equivocation_unsigned_extrinsic(
765			_equivocation_proof: sp_consensus_grandpa::EquivocationProof<
766			<Block as BlockT>::Hash,
767			NumberFor<Block>,
768			>,
769			_key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
770		) -> Option<()> {
771			None
772		}
773
774		fn generate_key_ownership_proof(
775			_set_id: sp_consensus_grandpa::SetId,
776			_authority_id: sp_consensus_grandpa::AuthorityId,
777		) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
778			None
779		}
780	}
781
782	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
783		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
784			build_state::<RuntimeGenesisConfig>(config)
785		}
786
787		fn get_preset(name: &Option<PresetId>) -> Option<Vec<u8>> {
788			get_preset::<RuntimeGenesisConfig>(name, |name| {
789				 let patch = match name.as_ref() {
790					"staging" => {
791						let endowed_accounts: Vec<AccountId> = vec![
792							Sr25519Keyring::Bob.public().into(),
793							Sr25519Keyring::Charlie.public().into(),
794						];
795
796						json!({
797							"balances": {
798								"balances": endowed_accounts.into_iter().map(|k| (k, 10 * currency::DOLLARS)).collect::<Vec<_>>(),
799							},
800							"substrateTest": {
801								"authorities": [
802									Sr25519Keyring::Alice.public().to_ss58check(),
803									Sr25519Keyring::Ferdie.public().to_ss58check()
804								],
805							}
806						})
807					},
808					"foobar" => json!({"foo":"bar"}),
809					_ => return None,
810				};
811				Some(serde_json::to_string(&patch)
812					.expect("serialization to json is expected to work. qed.")
813					.into_bytes())
814			})
815		}
816
817		fn preset_names() -> Vec<PresetId> {
818			vec![PresetId::from("foobar"), PresetId::from("staging")]
819		}
820	}
821}
822
823fn test_ed25519_crypto(
824) -> (ed25519::AppSignature, ed25519::AppPublic, ed25519::AppProofOfPossession) {
825	let mut public0 = ed25519::AppPublic::generate_pair(None);
826	let public1 = ed25519::AppPublic::generate_pair(None);
827	let public2 = ed25519::AppPublic::generate_pair(None);
828
829	let all = ed25519::AppPublic::all();
830	assert!(all.contains(&public0));
831	assert!(all.contains(&public1));
832	assert!(all.contains(&public2));
833
834	let proof_of_possession = public0
835		.generate_proof_of_possession(b"owner")
836		.expect("Cant generate proof_of_possession for ed25519");
837	assert!(public0.verify_proof_of_possession(b"owner", &proof_of_possession));
838
839	let signature = public0.sign(&"ed25519").expect("Generates a valid `ed25519` signature.");
840	assert!(public0.verify(&"ed25519", &signature));
841	(signature, public0, proof_of_possession)
842}
843
844fn test_sr25519_crypto(
845) -> (sr25519::AppSignature, sr25519::AppPublic, sr25519::AppProofOfPossession) {
846	let mut public0 = sr25519::AppPublic::generate_pair(None);
847	let public1 = sr25519::AppPublic::generate_pair(None);
848	let public2 = sr25519::AppPublic::generate_pair(None);
849
850	let all = sr25519::AppPublic::all();
851	assert!(all.contains(&public0));
852	assert!(all.contains(&public1));
853	assert!(all.contains(&public2));
854
855	let proof_of_possession = public0
856		.generate_proof_of_possession(b"owner")
857		.expect("Cant generate proof_of_possession for sr25519");
858	assert!(public0.verify_proof_of_possession(b"owner", &proof_of_possession));
859
860	let signature = public0.sign(&"sr25519").expect("Generates a valid `sr25519` signature.");
861	assert!(public0.verify(&"sr25519", &signature));
862	(signature, public0, proof_of_possession)
863}
864
865fn test_ecdsa_crypto() -> (ecdsa::AppSignature, ecdsa::AppPublic, ecdsa::AppProofOfPossession) {
866	let mut public0 = ecdsa::AppPublic::generate_pair(None);
867	let public1 = ecdsa::AppPublic::generate_pair(None);
868	let public2 = ecdsa::AppPublic::generate_pair(None);
869
870	let all = ecdsa::AppPublic::all();
871	assert!(all.contains(&public0));
872	assert!(all.contains(&public1));
873	assert!(all.contains(&public2));
874
875	let proof_of_possession = public0
876		.generate_proof_of_possession(b"owner")
877		.expect("Cant generate proof_of_possession for ecdsa");
878	assert!(public0.verify_proof_of_possession(b"owner", &proof_of_possession));
879
880	let signature = public0.sign(&"ecdsa").expect("Generates a valid `ecdsa` signature.");
881
882	assert!(public0.verify(&"ecdsa", &signature));
883	(signature, public0, proof_of_possession)
884}
885
886#[cfg(feature = "bls-experimental")]
887fn test_bls381_crypto() -> (Bls381Pop, Bls381Public) {
888	let mut public0 = bls381::AppPublic::generate_pair(None);
889
890	let proof_of_possession = public0
891		.generate_proof_of_possession(b"owner")
892		.expect("Cant generate proof_of_possession for bls381");
893	assert!(public0.verify_proof_of_possession(b"owner", &proof_of_possession));
894
895	(proof_of_possession, public0)
896}
897
898#[cfg(feature = "bls-experimental")]
899fn test_ecdsa_bls381_crypto() -> (EcdsaBls381Pop, EcdsaBls381Public) {
900	let mut public0 = ecdsa_bls381::AppPublic::generate_pair(None);
901
902	let proof_of_possession = public0
903		.generate_proof_of_possession(b"owner")
904		.expect("Cant Generate proof_of_possession for ecdsa_bls381");
905	assert!(public0.verify_proof_of_possession(b"owner", &proof_of_possession));
906
907	(proof_of_possession, public0)
908}
909
910fn test_read_storage() {
911	const KEY: &[u8] = b":read_storage";
912	sp_io::storage::set(KEY, b"test");
913
914	let mut v = [0u8; 4];
915	let r = sp_io::storage::read(KEY, &mut v, 0);
916	assert_eq!(r, Some(4));
917	assert_eq!(&v, b"test");
918
919	let mut v = [0u8; 4];
920	let r = sp_io::storage::read(KEY, &mut v, 4);
921	assert_eq!(r, Some(0));
922	assert_eq!(&v, &[0, 0, 0, 0]);
923}
924
925fn test_read_child_storage() {
926	const STORAGE_KEY: &[u8] = b"unique_id_1";
927	const KEY: &[u8] = b":read_child_storage";
928	sp_io::default_child_storage::set(STORAGE_KEY, KEY, b"test");
929
930	let mut v = [0u8; 4];
931	let r = sp_io::default_child_storage::read(STORAGE_KEY, KEY, &mut v, 0);
932	assert_eq!(r, Some(4));
933	assert_eq!(&v, b"test");
934
935	let mut v = [0u8; 4];
936	let r = sp_io::default_child_storage::read(STORAGE_KEY, KEY, &mut v, 8);
937	assert_eq!(r, Some(0));
938	assert_eq!(&v, &[0, 0, 0, 0]);
939}
940
941fn test_witness(proof: StorageProof, root: crate::Hash) {
942	use sp_externalities::Externalities;
943	let db: sp_trie::MemoryDB<crate::Hashing> = proof.into_memory_db();
944	let backend = sp_state_machine::TrieBackendBuilder::<_, crate::Hashing>::new(db, root).build();
945	let mut overlay = sp_state_machine::OverlayedChanges::default();
946	let mut ext = sp_state_machine::Ext::new(
947		&mut overlay,
948		&backend,
949		#[cfg(feature = "std")]
950		None,
951		crate::VERSION.state_version(),
952	);
953	assert!(ext.storage(b"value3").is_some());
954	assert!(ext.storage_root().as_slice() == &root[..]);
955	ext.place_storage(vec![0], Some(vec![1]));
956	assert!(ext.storage_root().as_slice() != &root[..]);
957}
958
959/// Some tests require the hashed keys of the storage. As the values of hashed keys are not trivial
960/// to guess, this small module provides the values of the keys, and the code which is required to
961/// generate the keys.
962#[cfg(feature = "std")]
963pub mod storage_key_generator {
964	use super::*;
965	use sp_core::Pair;
966
967	/// Generate hex string without prefix
968	pub(super) fn hex<T>(x: T) -> String
969	where
970		T: array_bytes::Hex,
971	{
972		x.hex(Default::default())
973	}
974
975	fn concat_hashes(input: &Vec<&[u8]>) -> String {
976		input.iter().map(|s| sp_crypto_hashing::twox_128(s)).map(hex).collect()
977	}
978
979	fn twox_64_concat(x: &[u8]) -> Vec<u8> {
980		sp_crypto_hashing::twox_64(x).iter().chain(x.iter()).cloned().collect()
981	}
982
983	/// Generate the hashed storage keys from the raw literals. These keys are expected to be in
984	/// storage with given substrate-test runtime.
985	pub fn generate_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec<String> {
986		let mut literals: Vec<&[u8]> = vec![b":code", b":extrinsic_index"];
987
988		if custom_heap_pages {
989			literals.push(b":heappages");
990		}
991
992		let keys: Vec<Vec<&[u8]>> = vec![
993			vec![b"Babe", b":__STORAGE_VERSION__:"],
994			vec![b"Babe", b"Authorities"],
995			vec![b"Babe", b"EpochConfig"],
996			vec![b"Babe", b"NextAuthorities"],
997			vec![b"Babe", b"SegmentIndex"],
998			vec![b"Balances", b":__STORAGE_VERSION__:"],
999			vec![b"Balances", b"TotalIssuance"],
1000			vec![b"SubstrateTest", b":__STORAGE_VERSION__:"],
1001			vec![b"SubstrateTest", b"Authorities"],
1002			vec![b"System", b":__STORAGE_VERSION__:"],
1003			vec![b"System", b"LastRuntimeUpgrade"],
1004			vec![b"System", b"ParentHash"],
1005			vec![b"System", b"UpgradedToTripleRefCount"],
1006			vec![b"System", b"UpgradedToU32RefCount"],
1007			vec![b"Utility", b":__STORAGE_VERSION__:"],
1008		];
1009
1010		let mut expected_keys = keys.iter().map(concat_hashes).collect::<Vec<String>>();
1011		expected_keys.extend(literals.into_iter().map(hex));
1012
1013		let balances_map_keys = (0..16_usize)
1014			.into_iter()
1015			.map(|i| Sr25519Keyring::numeric(i).public().to_vec())
1016			.chain(vec![
1017				Sr25519Keyring::Alice.public().to_vec(),
1018				Sr25519Keyring::Bob.public().to_vec(),
1019				Sr25519Keyring::Charlie.public().to_vec(),
1020			])
1021			.map(|pubkey| {
1022				sp_crypto_hashing::blake2_128(&pubkey)
1023					.iter()
1024					.chain(pubkey.iter())
1025					.cloned()
1026					.collect::<Vec<u8>>()
1027			})
1028			.map(|hash_pubkey| {
1029				[concat_hashes(&vec![b"System", b"Account"]), hex(hash_pubkey)].concat()
1030			});
1031
1032		expected_keys.extend(balances_map_keys);
1033
1034		expected_keys.push(
1035			[
1036				concat_hashes(&vec![b"System", b"BlockHash"]),
1037				hex(0u64.using_encoded(twox_64_concat)),
1038			]
1039			.concat(),
1040		);
1041
1042		expected_keys.sort();
1043		expected_keys
1044	}
1045
1046	/// Provides the commented list of hashed keys. This contains a hard-coded list of hashed keys
1047	/// that would be generated by `generate_expected_storage_hashed_keys`. This list is provided
1048	/// for the debugging convenience only. Value of each hex-string is documented with the literal
1049	/// origin.
1050	///
1051	/// `custom_heap_pages`: Should be set to `true` when the state contains the `:heap_pages` key
1052	/// aka when overriding the heap pages to be used by the executor.
1053	pub fn get_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec<&'static str> {
1054		let mut res = vec![
1055			//SubstrateTest|:__STORAGE_VERSION__:
1056			"00771836bebdd29870ff246d305c578c4e7b9012096b41c4eb3aaf947f6ea429",
1057			//SubstrateTest|Authorities
1058			"00771836bebdd29870ff246d305c578c5e0621c4869aa60c02be9adcc98a0d1d",
1059			//Babe|:__STORAGE_VERSION__:
1060			"1cb6f36e027abb2091cfb5110ab5087f4e7b9012096b41c4eb3aaf947f6ea429",
1061			//Babe|Authorities
1062			"1cb6f36e027abb2091cfb5110ab5087f5e0621c4869aa60c02be9adcc98a0d1d",
1063			//Babe|SegmentIndex
1064			"1cb6f36e027abb2091cfb5110ab5087f66e8f035c8adbe7f1547b43c51e6f8a4",
1065			//Babe|NextAuthorities
1066			"1cb6f36e027abb2091cfb5110ab5087faacf00b9b41fda7a9268821c2a2b3e4c",
1067			//Babe|EpochConfig
1068			"1cb6f36e027abb2091cfb5110ab5087fdc6b171b77304263c292cc3ea5ed31ef",
1069			//System|:__STORAGE_VERSION__:
1070			"26aa394eea5630e07c48ae0c9558cef74e7b9012096b41c4eb3aaf947f6ea429",
1071			//System|UpgradedToU32RefCount
1072			"26aa394eea5630e07c48ae0c9558cef75684a022a34dd8bfa2baaf44f172b710",
1073			//System|ParentHash
1074			"26aa394eea5630e07c48ae0c9558cef78a42f33323cb5ced3b44dd825fda9fcc",
1075			//System::BlockHash|0
1076			"26aa394eea5630e07c48ae0c9558cef7a44704b568d21667356a5a050c118746bb1bdbcacd6ac9340000000000000000",
1077			//System|UpgradedToTripleRefCount
1078			"26aa394eea5630e07c48ae0c9558cef7a7fd6c28836b9a28522dc924110cf439",
1079
1080			// System|Account|blake2_128Concat("//11")
1081			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da901cae4e3edfbb32c91ed3f01ab964f4eeeab50338d8e5176d3141802d7b010a55dadcd5f23cf8aaafa724627e967e90e",
1082			// System|Account|blake2_128Concat("//4")
1083			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da91b614bd4a126f2d5d294e9a8af9da25248d7e931307afb4b68d8d565d4c66e00d856c6d65f5fed6bb82dcfb60e936c67",
1084			// System|Account|blake2_128Concat("//7")
1085			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94b21aff9fe1e8b2fc4b0775b8cbeff28ba8e2c7594dd74730f3ca835e95455d199261897edc9735d602ea29615e2b10b",
1086			// System|Account|blake2_128Concat("//Bob")
1087			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48",
1088			// System|Account|blake2_128Concat("//3")
1089			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95786a2916fcb81e1bd5dcd81e0d2452884617f575372edb5a36d85c04cdf2e4699f96fe33eb5f94a28c041b88e398d0c",
1090			// System|Account|blake2_128Concat("//14")
1091			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da95b8542d9672c7b7e779cc7c1e6b605691c2115d06120ea2bee32dd601d02f36367564e7ddf84ae2717ca3f097459652e",
1092			// System|Account|blake2_128Concat("//6")
1093			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da996c30bdbfab640838e6b6d3c33ab4adb4211b79e34ee8072eab506edd4b93a7b85a14c9a05e5cdd056d98e7dbca87730",
1094			// System|Account|blake2_128Concat("//9")
1095			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da99dc65b1339ec388fbf2ca0cdef51253512c6cfd663203ea16968594f24690338befd906856c4d2f4ef32dad578dba20c",
1096			// System|Account|blake2_128Concat("//8")
1097			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da99e6eb5abd62f5fd54793da91a47e6af6125d57171ff9241f07acaa1bb6a6103517965cf2cd00e643b27e7599ebccba70",
1098			// System|Account|blake2_128Concat("//Charlie")
1099			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9b0edae20838083f2cde1c4080db8cf8090b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22",
1100			// System|Account|blake2_128Concat("//10")
1101			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9d0052993b6f3bd0544fd1f5e4125b9fbde3e789ecd53431fe5c06c12b72137153496dace35c695b5f4d7b41f7ed5763b",
1102			// System|Account|blake2_128Concat("//1")
1103			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9d6b7e9a5f12bc571053265dade10d3b4b606fc73f57f03cdb4c932d475ab426043e429cecc2ffff0d2672b0df8398c48",
1104			// System|Account|blake2_128Concat("//Alice")
1105			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d",
1106			// System|Account|blake2_128Concat("//2")
1107			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9e1a35f56ee295d39287cbffcfc60c4b346f136b564e1fad55031404dd84e5cd3fa76bfe7cc7599b39d38fd06663bbc0a",
1108			// System|Account|blake2_128Concat("//5")
1109			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9e2c1dc507e2035edbbd8776c440d870460c57f0008067cc01c5ff9eb2e2f9b3a94299a915a91198bd1021a6c55596f57",
1110			// System|Account|blake2_128Concat("//0")
1111			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9eca0e653a94f4080f6311b4e7b6934eb2afba9278e30ccf6a6ceb3a8b6e336b70068f045c666f2e7f4f9cc5f47db8972",
1112			// System|Account|blake2_128Concat("//13")
1113			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9ee8bf7ef90fc56a8aa3b90b344c599550c29b161e27ff8ba45bf6bad4711f326fc506a8803453a4d7e3158e993495f10",
1114			// System|Account|blake2_128Concat("//12")
1115			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9f5d6f1c082fe63eec7a71fcad00f4a892e3d43b7b0d04e776e69e7be35247cecdac65504c579195731eaf64b7940966e",
1116			// System|Account|blake2_128Concat("//15")
1117			"26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9fbf0818841edf110e05228a6379763c4fc3c37459d9bdc61f58a5ebc01e9e2305a19d390c0543dc733861ec3cf1de01f",
1118			// System|LastRuntimeUpgrade
1119			"26aa394eea5630e07c48ae0c9558cef7f9cce9c888469bb1a0dceaa129672ef8",
1120			// :code
1121			"3a636f6465",
1122			// :extrinsic_index
1123			"3a65787472696e7369635f696e646578",
1124			// Balances|:__STORAGE_VERSION__:
1125			"c2261276cc9d1f8598ea4b6a74b15c2f4e7b9012096b41c4eb3aaf947f6ea429",
1126			// Balances|TotalIssuance
1127			"c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80",
1128			//Utility|:__STORAGE_VERSION__:
1129			"d5e1a2fa16732ce6906189438c0a82c64e7b9012096b41c4eb3aaf947f6ea429",
1130		];
1131
1132		if custom_heap_pages {
1133			// :heappages
1134			res.push("3a686561707061676573");
1135		}
1136
1137		res
1138	}
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143	use super::*;
1144	use codec::Encode;
1145	use frame_support::dispatch::DispatchInfo;
1146	use pretty_assertions::assert_eq;
1147	use sc_block_builder::BlockBuilderBuilder;
1148	use sp_api::{ApiExt, ProvideRuntimeApi};
1149	use sp_consensus::BlockOrigin;
1150	use sp_core::{storage::well_known_keys::HEAP_PAGES, traits::CallContext};
1151	use sp_runtime::{
1152		traits::{DispatchTransaction, Hash as _},
1153		transaction_validity::{InvalidTransaction, TransactionSource::External, ValidTransaction},
1154	};
1155	use substrate_test_runtime_client::{
1156		prelude::*, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder,
1157	};
1158
1159	#[test]
1160	fn expected_keys_vec_are_matching() {
1161		assert_eq!(
1162			storage_key_generator::get_expected_storage_hashed_keys(false),
1163			storage_key_generator::generate_expected_storage_hashed_keys(false),
1164		);
1165	}
1166
1167	#[test]
1168	fn heap_pages_is_respected() {
1169		// This tests that the on-chain `HEAP_PAGES` parameter is respected.
1170
1171		// Create a client devoting only 8 pages of wasm memory. This gives us ~512k of heap memory.
1172		let client = TestClientBuilder::new().set_heap_pages(8).build();
1173		let best_hash = client.chain_info().best_hash;
1174
1175		// Try to allocate 1024k of memory on heap. This is going to fail since it is twice larger
1176		// than the heap.
1177		let mut runtime_api = client.runtime_api();
1178		// This is currently required to allocate the 1024k of memory as configured above.
1179		runtime_api.set_call_context(CallContext::Onchain { import: false });
1180		let ret = runtime_api.vec_with_capacity(best_hash, 1048576);
1181		assert!(ret.is_err());
1182
1183		// Create a block that sets the `:heap_pages` to 32 pages of memory which corresponds to
1184		// ~2048k of heap memory.
1185		let (new_at_hash, block) = {
1186			let mut builder = BlockBuilderBuilder::new(&client)
1187				.on_parent_block(best_hash)
1188				.with_parent_block_number(0)
1189				.build()
1190				.unwrap();
1191			builder.push_storage_change(HEAP_PAGES.to_vec(), Some(32u64.encode())).unwrap();
1192			let block = builder.build().unwrap().block;
1193			let hash = block.header.hash();
1194			(hash, block)
1195		};
1196
1197		futures::executor::block_on(client.import(BlockOrigin::Own, block)).unwrap();
1198
1199		// Allocation of 1024k while having ~2048k should succeed.
1200		let ret = client.runtime_api().vec_with_capacity(new_at_hash, 1048576);
1201		assert!(ret.is_ok());
1202	}
1203
1204	#[test]
1205	fn test_storage() {
1206		let client = TestClientBuilder::new().build();
1207		let runtime_api = client.runtime_api();
1208		let best_hash = client.chain_info().best_hash;
1209
1210		runtime_api.test_storage(best_hash).unwrap();
1211	}
1212
1213	fn witness_backend() -> (sp_trie::MemoryDB<crate::Hashing>, crate::Hash) {
1214		let mut root = crate::Hash::default();
1215		let mut mdb = sp_trie::MemoryDB::<crate::Hashing>::default();
1216		{
1217			let mut trie =
1218				sp_trie::trie_types::TrieDBMutBuilderV1::new(&mut mdb, &mut root).build();
1219			trie.insert(b"value3", &[142]).expect("insert failed");
1220			trie.insert(b"value4", &[124]).expect("insert failed");
1221		};
1222		(mdb, root)
1223	}
1224
1225	#[test]
1226	fn witness_backend_works() {
1227		let (db, root) = witness_backend();
1228		let backend =
1229			sp_state_machine::TrieBackendBuilder::<_, crate::Hashing>::new(db, root).build();
1230		let proof = sp_state_machine::prove_read(backend, vec![b"value3"]).unwrap();
1231		let client = TestClientBuilder::new().build();
1232		let runtime_api = client.runtime_api();
1233		let best_hash = client.chain_info().best_hash;
1234
1235		runtime_api.test_witness(best_hash, proof, root).unwrap();
1236	}
1237
1238	pub fn new_test_ext() -> sp_io::TestExternalities {
1239		genesismap::GenesisStorageBuilder::new(
1240			vec![Sr25519Keyring::One.public().into(), Sr25519Keyring::Two.public().into()],
1241			vec![Sr25519Keyring::One.into(), Sr25519Keyring::Two.into()],
1242			1000 * currency::DOLLARS,
1243		)
1244		.build()
1245		.into()
1246	}
1247
1248	#[test]
1249	fn validate_storage_keys() {
1250		assert_eq!(
1251			genesismap::GenesisStorageBuilder::default()
1252				.build()
1253				.top
1254				.keys()
1255				.cloned()
1256				.map(storage_key_generator::hex)
1257				.collect::<Vec<_>>(),
1258			storage_key_generator::get_expected_storage_hashed_keys(false)
1259		);
1260	}
1261
1262	#[test]
1263	#[allow(deprecated)]
1264	fn validate_unsigned_works() {
1265		sp_tracing::try_init_simple();
1266		new_test_ext().execute_with(|| {
1267			let failing_calls = vec![
1268				substrate_test_pallet::Call::bench_call { transfer: Default::default() },
1269				substrate_test_pallet::Call::include_data { data: vec![] },
1270				substrate_test_pallet::Call::fill_block { ratio: Perbill::from_percent(50) },
1271			];
1272			let succeeding_calls = vec![
1273				substrate_test_pallet::Call::deposit_log_digest_item {
1274					log: DigestItem::Other(vec![]),
1275				},
1276				substrate_test_pallet::Call::storage_change { key: vec![], value: None },
1277				substrate_test_pallet::Call::read { count: 0 },
1278				substrate_test_pallet::Call::read_and_panic { count: 0 },
1279			];
1280
1281			for call in failing_calls {
1282				assert_eq!(
1283					<SubstrateTest as sp_runtime::traits::ValidateUnsigned>::validate_unsigned(
1284						TransactionSource::External,
1285						&call,
1286					),
1287					InvalidTransaction::Call.into(),
1288				);
1289			}
1290
1291			for call in succeeding_calls {
1292				assert_eq!(
1293					<SubstrateTest as sp_runtime::traits::ValidateUnsigned>::validate_unsigned(
1294						TransactionSource::External,
1295						&call,
1296					),
1297					Ok(ValidTransaction {
1298						provides: vec![BlakeTwo256::hash_of(&call).encode()],
1299						..Default::default()
1300					})
1301				);
1302			}
1303		});
1304	}
1305
1306	#[test]
1307	fn check_substrate_check_signed_extension_works() {
1308		sp_tracing::try_init_simple();
1309		new_test_ext().execute_with(|| {
1310			let x = Sr25519Keyring::Alice.into();
1311			let info = DispatchInfo::default();
1312			let len = 0_usize;
1313			assert_eq!(
1314				CheckSubstrateCall {}
1315					.validate_only(
1316						Some(x).into(),
1317						&ExtrinsicBuilder::new_call_with_priority(16).build().function,
1318						&info,
1319						len,
1320						External,
1321						0,
1322					)
1323					.unwrap()
1324					.0
1325					.priority,
1326				16
1327			);
1328
1329			assert_eq!(
1330				CheckSubstrateCall {}
1331					.validate_only(
1332						Some(x).into(),
1333						&ExtrinsicBuilder::new_call_do_not_propagate().build().function,
1334						&info,
1335						len,
1336						External,
1337						0,
1338					)
1339					.unwrap()
1340					.0
1341					.propagate,
1342				false
1343			);
1344		})
1345	}
1346
1347	mod genesis_builder_tests {
1348		use super::*;
1349		use crate::genesismap::GenesisStorageBuilder;
1350		use pretty_assertions::assert_eq;
1351		use sc_executor::{error::Result, WasmExecutor};
1352		use sc_executor_common::runtime_blob::RuntimeBlob;
1353		use serde_json::json;
1354		use sp_application_crypto::Ss58Codec;
1355		use sp_core::traits::Externalities;
1356		use sp_genesis_builder::Result as BuildResult;
1357		use sp_state_machine::BasicExternalities;
1358		use std::{fs, io::Write};
1359		use storage_key_generator::hex;
1360
1361		pub fn executor_call(
1362			ext: &mut dyn Externalities,
1363			method: &str,
1364			data: &[u8],
1365		) -> Result<Vec<u8>> {
1366			let executor = WasmExecutor::<sp_io::SubstrateHostFunctions>::builder().build();
1367			executor.uncached_call(
1368				RuntimeBlob::uncompress_if_needed(wasm_binary_unwrap()).unwrap(),
1369				ext,
1370				true,
1371				method,
1372				data,
1373			)
1374		}
1375
1376		#[test]
1377		fn build_minimal_genesis_config_works() {
1378			sp_tracing::try_init_simple();
1379			let default_minimal_json = r#"{"system":{},"babe":{"authorities":[],"epochConfig":{"c": [ 3, 10 ],"allowed_slots":"PrimaryAndSecondaryPlainSlots"}},"substrateTest":{"authorities":[]},"balances":{"balances":[]}}"#;
1380			let mut t = BasicExternalities::new_empty();
1381
1382			executor_call(&mut t, "GenesisBuilder_build_state", &default_minimal_json.encode())
1383				.unwrap();
1384
1385			let mut keys = t.into_storages().top.keys().cloned().map(hex).collect::<Vec<String>>();
1386			keys.sort();
1387
1388			let mut expected = [
1389				//SubstrateTest|Authorities
1390				"00771836bebdd29870ff246d305c578c5e0621c4869aa60c02be9adcc98a0d1d",
1391				//Babe|SegmentIndex
1392				"1cb6f36e027abb2091cfb5110ab5087f66e8f035c8adbe7f1547b43c51e6f8a4",
1393				//Babe|EpochConfig
1394				"1cb6f36e027abb2091cfb5110ab5087fdc6b171b77304263c292cc3ea5ed31ef",
1395				//System|UpgradedToU32RefCount
1396				"26aa394eea5630e07c48ae0c9558cef75684a022a34dd8bfa2baaf44f172b710",
1397				//System|ParentHash
1398				"26aa394eea5630e07c48ae0c9558cef78a42f33323cb5ced3b44dd825fda9fcc",
1399				//System::BlockHash|0
1400				"26aa394eea5630e07c48ae0c9558cef7a44704b568d21667356a5a050c118746bb1bdbcacd6ac9340000000000000000",
1401				//System|UpgradedToTripleRefCount
1402				"26aa394eea5630e07c48ae0c9558cef7a7fd6c28836b9a28522dc924110cf439",
1403
1404				// System|LastRuntimeUpgrade
1405				"26aa394eea5630e07c48ae0c9558cef7f9cce9c888469bb1a0dceaa129672ef8",
1406				// :extrinsic_index
1407				"3a65787472696e7369635f696e646578",
1408				// Balances|TotalIssuance
1409				"c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80",
1410
1411				// added by on_genesis:
1412				// Balances|:__STORAGE_VERSION__:
1413				"c2261276cc9d1f8598ea4b6a74b15c2f4e7b9012096b41c4eb3aaf947f6ea429",
1414				//System|:__STORAGE_VERSION__:
1415				"26aa394eea5630e07c48ae0c9558cef74e7b9012096b41c4eb3aaf947f6ea429",
1416				//Babe|:__STORAGE_VERSION__:
1417				"1cb6f36e027abb2091cfb5110ab5087f4e7b9012096b41c4eb3aaf947f6ea429",
1418				//SubstrateTest|:__STORAGE_VERSION__:
1419				"00771836bebdd29870ff246d305c578c4e7b9012096b41c4eb3aaf947f6ea429",
1420				//Utility|:__STORAGE_VERSION__:
1421				"d5e1a2fa16732ce6906189438c0a82c64e7b9012096b41c4eb3aaf947f6ea429",
1422				].into_iter().map(String::from).collect::<Vec<_>>();
1423			expected.sort();
1424
1425			assert_eq!(expected, keys);
1426		}
1427
1428		#[test]
1429		fn default_config_as_json_works() {
1430			sp_tracing::try_init_simple();
1431			let mut t = BasicExternalities::new_empty();
1432			let r = executor_call(&mut t, "GenesisBuilder_get_preset", &None::<&PresetId>.encode())
1433				.unwrap();
1434			let r = Option::<Vec<u8>>::decode(&mut &r[..])
1435				.unwrap()
1436				.expect("default config is there");
1437			let json = String::from_utf8(r.into()).expect("returned value is json. qed.");
1438
1439			let expected = r#"{"system":{},"babe":{"authorities":[],"epochConfig":{"c":[1,4],"allowed_slots":"PrimaryAndSecondaryVRFSlots"}},"substrateTest":{"authorities":[]},"balances":{"balances":[],"devAccounts":null}}"#;
1440			assert_eq!(expected.to_string(), json);
1441		}
1442
1443		#[test]
1444		fn preset_names_listing_works() {
1445			sp_tracing::try_init_simple();
1446			let mut t = BasicExternalities::new_empty();
1447			let r = executor_call(&mut t, "GenesisBuilder_preset_names", &vec![]).unwrap();
1448			let r = Vec::<PresetId>::decode(&mut &r[..]).unwrap();
1449			assert_eq!(r, vec![PresetId::from("foobar"), PresetId::from("staging"),]);
1450			log::info!("r: {:#?}", r);
1451		}
1452
1453		#[test]
1454		fn named_config_works() {
1455			sp_tracing::try_init_simple();
1456			let f = |cfg_name: &str, expected: &str| {
1457				let mut t = BasicExternalities::new_empty();
1458				let name = cfg_name.to_string();
1459				let r = executor_call(
1460					&mut t,
1461					"GenesisBuilder_get_preset",
1462					&Some(name.as_bytes()).encode(),
1463				)
1464				.unwrap();
1465				let r = Option::<Vec<u8>>::decode(&mut &r[..]).unwrap();
1466				let json =
1467					String::from_utf8(r.unwrap().into()).expect("returned value is json. qed.");
1468				log::info!("json: {:#?}", json);
1469				assert_eq!(expected.to_string(), json);
1470			};
1471
1472			f("foobar", r#"{"foo":"bar"}"#);
1473			f(
1474				"staging",
1475				r#"{"balances":{"balances":[["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty",1000000000000000],["5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y",1000000000000000]]},"substrateTest":{"authorities":["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY","5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL"]}}"#,
1476			);
1477		}
1478
1479		#[test]
1480		fn build_config_from_json_works() {
1481			sp_tracing::try_init_simple();
1482			let j = include_str!("../res/default_genesis_config.json");
1483
1484			let mut t = BasicExternalities::new_empty();
1485			let r = executor_call(&mut t, "GenesisBuilder_build_state", &j.encode()).unwrap();
1486			let r = BuildResult::decode(&mut &r[..]);
1487			assert!(r.is_ok());
1488
1489			let mut keys = t.into_storages().top.keys().cloned().map(hex).collect::<Vec<String>>();
1490
1491			// following keys are not placed during `<RuntimeGenesisConfig as
1492			// BuildGenesisConfig>::build` process, add them `keys` to assert against known keys.
1493			keys.push(hex(b":code"));
1494			keys.sort();
1495
1496			assert_eq!(keys, storage_key_generator::get_expected_storage_hashed_keys(false));
1497		}
1498
1499		#[test]
1500		fn build_config_from_invalid_json_fails() {
1501			sp_tracing::try_init_simple();
1502			let j = include_str!("../res/default_genesis_config_invalid.json");
1503			let mut t = BasicExternalities::new_empty();
1504			let r = executor_call(&mut t, "GenesisBuilder_build_state", &j.encode()).unwrap();
1505			let r = BuildResult::decode(&mut &r[..]).unwrap();
1506			log::info!("result: {:#?}", r);
1507			assert_eq!(r, Err(
1508				"Invalid JSON blob: unknown field `renamed_authorities`, expected `authorities` or `epochConfig` at line 4 column 25".to_string(),
1509			));
1510		}
1511
1512		#[test]
1513		fn build_config_from_invalid_json_fails_2() {
1514			sp_tracing::try_init_simple();
1515			let j = include_str!("../res/default_genesis_config_invalid_2.json");
1516			let mut t = BasicExternalities::new_empty();
1517			let r = executor_call(&mut t, "GenesisBuilder_build_state", &j.encode()).unwrap();
1518			let r = BuildResult::decode(&mut &r[..]).unwrap();
1519			assert_eq!(r, Err(
1520				"Invalid JSON blob: unknown field `babex`, expected one of `system`, `babe`, `substrateTest`, `balances` at line 3 column 9".to_string(),
1521			));
1522		}
1523
1524		#[test]
1525		fn build_config_from_incomplete_json_fails() {
1526			sp_tracing::try_init_simple();
1527			let j = include_str!("../res/default_genesis_config_incomplete.json");
1528
1529			let mut t = BasicExternalities::new_empty();
1530			let r = executor_call(&mut t, "GenesisBuilder_build_state", &j.encode()).unwrap();
1531			let r = core::result::Result::<(), String>::decode(&mut &r[..]).unwrap();
1532			assert_eq!(
1533				r,
1534				Err("Invalid JSON blob: missing field `authorities` at line 11 column 3"
1535					.to_string())
1536			);
1537		}
1538
1539		#[test]
1540		fn write_default_config_to_tmp_file() {
1541			if std::env::var("WRITE_DEFAULT_JSON_FOR_STR_GC").is_ok() {
1542				sp_tracing::try_init_simple();
1543				let mut file = fs::OpenOptions::new()
1544					.create(true)
1545					.write(true)
1546					.open("/tmp/default_genesis_config.json")
1547					.unwrap();
1548
1549				let j = serde_json::to_string(&GenesisStorageBuilder::default().genesis_config())
1550					.unwrap()
1551					.into_bytes();
1552				file.write_all(&j).unwrap();
1553			}
1554		}
1555
1556		#[test]
1557		fn build_genesis_config_with_patch_json_works() {
1558			// this tests shows how to do patching on native side
1559			sp_tracing::try_init_simple();
1560
1561			let mut t = BasicExternalities::new_empty();
1562			let r = executor_call(&mut t, "GenesisBuilder_get_preset", &None::<&PresetId>.encode())
1563				.unwrap();
1564			let r = Option::<Vec<u8>>::decode(&mut &r[..])
1565				.unwrap()
1566				.expect("default config is there");
1567			let mut default_config: serde_json::Value =
1568				serde_json::from_slice(&r[..]).expect("returned value is json. qed.");
1569
1570			// Patch default json with some custom values:
1571			let patch = json!({
1572				"babe": {
1573					"epochConfig": {
1574						"c": [
1575							7,
1576							10
1577						],
1578						"allowed_slots": "PrimaryAndSecondaryPlainSlots"
1579					}
1580				},
1581				"substrateTest": {
1582					"authorities": [
1583						Sr25519Keyring::Ferdie.public().to_ss58check(),
1584						Sr25519Keyring::Alice.public().to_ss58check()
1585					],
1586				}
1587			});
1588
1589			sc_chain_spec::json_merge(&mut default_config, patch);
1590
1591			// Build genesis config using custom json:
1592			let mut t = BasicExternalities::new_empty();
1593			executor_call(
1594				&mut t,
1595				"GenesisBuilder_build_state",
1596				&default_config.to_string().encode(),
1597			)
1598			.unwrap();
1599
1600			// Ensure that custom values are in the genesis storage:
1601			let storage = t.into_storages();
1602			let get_from_storage = |key: &str| -> Vec<u8> {
1603				storage.top.get(&array_bytes::hex2bytes(key).unwrap()).unwrap().clone()
1604			};
1605
1606			// SubstrateTest|Authorities
1607			let value: Vec<u8> = get_from_storage(
1608				"00771836bebdd29870ff246d305c578c5e0621c4869aa60c02be9adcc98a0d1d",
1609			);
1610			let authority_key_vec =
1611				Vec::<sp_core::sr25519::Public>::decode(&mut &value[..]).unwrap();
1612			assert_eq!(authority_key_vec.len(), 2);
1613			assert_eq!(authority_key_vec[0], Sr25519Keyring::Ferdie.public());
1614			assert_eq!(authority_key_vec[1], Sr25519Keyring::Alice.public());
1615
1616			// Babe|Authorities
1617			let value: Vec<u8> = get_from_storage(
1618				"1cb6f36e027abb2091cfb5110ab5087fdc6b171b77304263c292cc3ea5ed31ef",
1619			);
1620			assert_eq!(
1621				BabeEpochConfiguration::decode(&mut &value[..]).unwrap(),
1622				BabeEpochConfiguration {
1623					c: (7, 10),
1624					allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots
1625				}
1626			);
1627
1628			// Ensure that some values are default ones:
1629			// Balances|TotalIssuance
1630			let value: Vec<u8> = get_from_storage(
1631				"c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80",
1632			);
1633			assert_eq!(u64::decode(&mut &value[..]).unwrap(), 0);
1634
1635			// System|ParentHash
1636			let value: Vec<u8> = get_from_storage(
1637				"26aa394eea5630e07c48ae0c9558cef78a42f33323cb5ced3b44dd825fda9fcc",
1638			);
1639			assert_eq!(H256::decode(&mut &value[..]).unwrap(), [69u8; 32].into());
1640		}
1641	}
1642}