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