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