1#![cfg_attr(not(feature = "std"), no_std)]
18#![feature(variant_count)]
19#![recursion_limit = "256"]
21#![allow(
23 non_camel_case_types,
24 reason = "https://github.com/rust-lang/rust-analyzer/issues/16514"
25)]
26
27extern crate alloc;
28
29#[cfg(feature = "std")]
31include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
32
33use alloc::borrow::Cow;
34use core::mem;
35use core::num::NonZeroU64;
36use domain_runtime_primitives::opaque::Header as DomainHeader;
37use domain_runtime_primitives::{
38 AccountIdConverter, BlockNumber as DomainNumber, EthereumAccountId, Hash as DomainHash,
39 MAX_OUTGOING_MESSAGES,
40};
41use frame_support::dispatch::DispatchClass;
42use frame_support::genesis_builder_helper::{build_state, get_preset};
43use frame_support::inherent::ProvideInherent;
44use frame_support::traits::fungible::Inspect;
45#[cfg(feature = "runtime-benchmarks")]
46use frame_support::traits::fungible::Mutate;
47use frame_support::traits::tokens::WithdrawConsequence;
48use frame_support::traits::{
49 ConstU8, ConstU16, ConstU32, ConstU64, ConstU128, Currency, Everything, ExistenceRequirement,
50 Get, Imbalance, VariantCount, WithdrawReasons,
51};
52use frame_support::weights::constants::{ParityDbWeight, WEIGHT_REF_TIME_PER_SECOND};
53use frame_support::weights::{ConstantMultiplier, Weight};
54use frame_support::{PalletId, construct_runtime, parameter_types};
55use frame_system::limits::{BlockLength, BlockWeights};
56use frame_system::pallet_prelude::RuntimeCallFor;
57use pallet_balances::NegativeImbalance;
58use pallet_domains::staking::StakingSummary;
59pub use pallet_rewards::RewardPoint;
60pub use pallet_subspace::{AllowAuthoringBy, EnableRewardsAt};
61use pallet_transporter::EndpointHandler;
62use parity_scale_codec::{
63 Compact, CompactLen, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen,
64};
65use scale_info::TypeInfo;
66use sp_api::impl_runtime_apis;
67use sp_consensus_slots::{Slot, SlotDuration};
68use sp_consensus_subspace::{ChainConstants, PotParameters, SignedVote, SolutionRanges, Vote};
69use sp_core::crypto::KeyTypeId;
70use sp_core::{H256, OpaqueMetadata};
71use sp_domains::bundle::{BundleVersion, OpaqueBundle, OpaqueBundles};
72use sp_domains::bundle_producer_election::BundleProducerElectionParams;
73use sp_domains::execution_receipt::{
74 ExecutionReceiptFor, ExecutionReceiptVersion, SealedSingletonReceipt,
75};
76use sp_domains::{
77 BundleAndExecutionReceiptVersion, DomainAllowlistUpdates, DomainId, DomainInstanceData,
78 EpochIndex, INITIAL_DOMAIN_TX_RANGE, OperatorId, OperatorPublicKey,
79 PermissionedActionAllowedBy,
80};
81use sp_domains_fraud_proof::fraud_proof::FraudProof;
82use sp_domains_fraud_proof::storage_proof::{
83 FraudProofStorageKeyProvider, FraudProofStorageKeyRequest,
84};
85use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
86use sp_messenger::messages::{
87 BlockMessagesQuery, ChainId, ChannelId, ChannelStateWithNonce, CrossDomainMessage, MessageId,
88 MessageKey, MessagesWithStorageKey, Nonce as XdmNonce,
89};
90use sp_messenger::{ChannelNonce, XdmId};
91use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key};
92use sp_mmr_primitives::EncodableOpaqueLeaf;
93use sp_runtime::traits::{
94 AccountIdConversion, AccountIdLookup, BlakeTwo256, DispatchInfoOf, Keccak256, NumberFor,
95 PostDispatchInfoOf, Zero,
96};
97use sp_runtime::transaction_validity::{
98 InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
99};
100use sp_runtime::type_with_default::TypeWithDefault;
101use sp_runtime::{AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill, generic};
102use sp_std::collections::btree_map::BTreeMap;
103use sp_std::collections::btree_set::BTreeSet;
104use sp_std::marker::PhantomData;
105use sp_std::prelude::*;
106use sp_subspace_mmr::ConsensusChainMmrLeafProof;
107use sp_version::RuntimeVersion;
108use static_assertions::const_assert;
109use subspace_core_primitives::objects::{BlockObject, BlockObjectMapping};
110use subspace_core_primitives::pieces::Piece;
111use subspace_core_primitives::segments::{
112 HistorySize, SegmentCommitment, SegmentHeader, SegmentIndex,
113};
114use subspace_core_primitives::solutions::SolutionRange;
115use subspace_core_primitives::{PublicKey, Randomness, SlotNumber, U256, hashes};
116pub use subspace_runtime_primitives::extension::BalanceTransferCheckExtension;
117use subspace_runtime_primitives::extension::{
118 BalanceTransferChecks, MaybeBalancesCall, SmallOrderEd25519CheckExtension,
119};
120use subspace_runtime_primitives::utility::{
121 DefaultNonceProvider, MaybeMultisigCall, MaybeNestedCall, MaybeUtilityCall,
122};
123use subspace_runtime_primitives::{
124 AI3, AccountId, Balance, BlockHashFor, BlockNumber, ConsensusEventSegmentSize, ExtrinsicFor,
125 FindBlockRewardAddress, Hash, HeaderFor, HoldIdentifier, MAX_BLOCK_LENGTH,
126 MAX_CALL_RECURSION_DEPTH, MIN_REPLICATION_FACTOR, Moment, Nonce, SHANNON, Signature,
127 SlowAdjustingFeeUpdate, TargetBlockFullness, XdmAdjustedWeightToFee, XdmFeeMultipler,
128};
129
130sp_runtime::impl_opaque_keys! {
131 pub struct SessionKeys {
132 }
133}
134
135const MAX_PIECES_IN_SECTOR: u16 = 32;
137
138#[sp_version::runtime_version]
141pub const VERSION: RuntimeVersion = RuntimeVersion {
142 spec_name: Cow::Borrowed("subspace"),
143 impl_name: Cow::Borrowed("subspace"),
144 authoring_version: 1,
145 spec_version: 100,
151 impl_version: 1,
152 apis: RUNTIME_API_VERSIONS,
153 transaction_version: 1,
154 system_version: 2,
155};
156
157pub const MILLISECS_PER_BLOCK: u64 = 2000;
176
177pub const SLOT_DURATION: u64 = 2000;
180
181const SLOT_PROBABILITY: (u64, u64) = (1, 1);
184const BLOCK_AUTHORING_DELAY: SlotNumber = 2;
186
187const POT_ENTROPY_INJECTION_INTERVAL: BlockNumber = 5;
189
190const POT_ENTROPY_INJECTION_LOOKBACK_DEPTH: u8 = 2;
192
193const POT_ENTROPY_INJECTION_DELAY: SlotNumber = 4;
195
196const_assert!(POT_ENTROPY_INJECTION_INTERVAL as u64 > POT_ENTROPY_INJECTION_DELAY);
199const_assert!(POT_ENTROPY_INJECTION_DELAY > BLOCK_AUTHORING_DELAY + 1);
203
204const ERA_DURATION_IN_BLOCKS: BlockNumber = 2016;
206
207const INITIAL_SOLUTION_RANGE: SolutionRange = SolutionRange::MAX;
209
210const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
212
213const BLOCK_WEIGHT_FOR_2_SEC: Weight =
215 Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), u64::MAX);
216
217parameter_types! {
218 pub const Version: RuntimeVersion = VERSION;
219 pub const BlockHashCount: BlockNumber = 250;
220 pub SubspaceBlockWeights: BlockWeights = BlockWeights::with_sensible_defaults(BLOCK_WEIGHT_FOR_2_SEC, NORMAL_DISPATCH_RATIO);
222 pub SubspaceBlockLength: BlockLength = BlockLength::builder()
224 .max_length(MAX_BLOCK_LENGTH)
225 .modify_max_length_for_class(DispatchClass::Normal, |max| {
226 *max = NORMAL_DISPATCH_RATIO * MAX_BLOCK_LENGTH
227 })
228 .build();
229}
230
231pub type SS58Prefix = ConstU16<6094>;
232
233impl frame_system::Config for Runtime {
236 type RuntimeEvent = RuntimeEvent;
237 type BaseCallFilter = Everything;
242 type BlockWeights = SubspaceBlockWeights;
244 type BlockLength = SubspaceBlockLength;
246 type AccountId = AccountId;
248 type RuntimeCall = RuntimeCall;
250 type RuntimeTask = RuntimeTask;
252 type Lookup = AccountIdLookup<AccountId, ()>;
254 type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
256 type Hash = Hash;
258 type Hashing = BlakeTwo256;
260 type Block = Block;
262 type RuntimeOrigin = RuntimeOrigin;
265 type BlockHashCount = BlockHashCount;
267 type DbWeight = ParityDbWeight;
269 type Version = Version;
271 type PalletInfo = PalletInfo;
275 type OnNewAccount = ();
277 type OnKilledAccount = ();
279 type AccountData = pallet_balances::AccountData<Balance>;
281 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
283 type SS58Prefix = SS58Prefix;
285 type OnSetCode = subspace_runtime_primitives::SetCode<Runtime, Domains>;
287 type SingleBlockMigrations = ();
288 type MultiBlockMigrator = ();
289 type PreInherents = ();
290 type PostInherents = ();
291 type PostTransactions = ();
292 type MaxConsumers = ConstU32<16>;
293 type ExtensionsWeightInfo = frame_system::SubstrateExtensionsWeight<Runtime>;
294 type EventSegmentSize = ConsensusEventSegmentSize;
295}
296
297parameter_types! {
298 pub const BlockAuthoringDelay: SlotNumber = BLOCK_AUTHORING_DELAY;
299 pub const PotEntropyInjectionInterval: BlockNumber = POT_ENTROPY_INJECTION_INTERVAL;
300 pub const PotEntropyInjectionLookbackDepth: u8 = POT_ENTROPY_INJECTION_LOOKBACK_DEPTH;
301 pub const PotEntropyInjectionDelay: SlotNumber = POT_ENTROPY_INJECTION_DELAY;
302 pub const EraDuration: BlockNumber = ERA_DURATION_IN_BLOCKS;
303 pub const SlotProbability: (u64, u64) = SLOT_PROBABILITY;
304 pub const ShouldAdjustSolutionRange: bool = false;
305 pub const ExpectedVotesPerBlock: u32 = 9;
306 pub const ConfirmationDepthK: u32 = 5;
307 pub const RecentSegments: HistorySize = HistorySize::new(NonZeroU64::new(5).unwrap());
308 pub const RecentHistoryFraction: (HistorySize, HistorySize) = (
309 HistorySize::new(NonZeroU64::new(1).unwrap()),
310 HistorySize::new(NonZeroU64::new(10).unwrap()),
311 );
312 pub const MinSectorLifetime: HistorySize = HistorySize::new(NonZeroU64::new(4).unwrap());
313 pub const BlockSlotCount: u32 = 6;
314 pub TransactionWeightFee: Balance = 100_000 * SHANNON;
315}
316
317impl pallet_subspace::Config for Runtime {
318 type SubspaceOrigin = pallet_subspace::EnsureSubspaceOrigin;
319 type BlockAuthoringDelay = BlockAuthoringDelay;
320 type PotEntropyInjectionInterval = PotEntropyInjectionInterval;
321 type PotEntropyInjectionLookbackDepth = PotEntropyInjectionLookbackDepth;
322 type PotEntropyInjectionDelay = PotEntropyInjectionDelay;
323 type EraDuration = EraDuration;
324 type InitialSolutionRange = ConstU64<INITIAL_SOLUTION_RANGE>;
325 type SlotProbability = SlotProbability;
326 type ConfirmationDepthK = ConfirmationDepthK;
327 type RecentSegments = RecentSegments;
328 type RecentHistoryFraction = RecentHistoryFraction;
329 type MinSectorLifetime = MinSectorLifetime;
330 type ExpectedVotesPerBlock = ExpectedVotesPerBlock;
331 type MaxPiecesInSector = ConstU16<{ MAX_PIECES_IN_SECTOR }>;
332 type ShouldAdjustSolutionRange = ShouldAdjustSolutionRange;
333 type EraChangeTrigger = pallet_subspace::NormalEraChange;
334 type WeightInfo = pallet_subspace::weights::SubstrateWeight<Runtime>;
335 type BlockSlotCount = BlockSlotCount;
336 type ExtensionWeightInfo = pallet_subspace::extensions::weights::SubstrateWeight<Runtime>;
337}
338
339impl pallet_timestamp::Config for Runtime {
340 type Moment = Moment;
342 type OnTimestampSet = ();
343 type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
344 type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
345}
346
347#[derive(
348 PartialEq,
349 Eq,
350 Clone,
351 Encode,
352 Decode,
353 TypeInfo,
354 MaxEncodedLen,
355 Ord,
356 PartialOrd,
357 Copy,
358 Debug,
359 DecodeWithMemTracking,
360)]
361pub struct HoldIdentifierWrapper(HoldIdentifier);
362
363impl pallet_domains::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
364 fn staking_staked() -> Self {
365 Self(HoldIdentifier::DomainStaking)
366 }
367
368 fn domain_instantiation_id() -> Self {
369 Self(HoldIdentifier::DomainInstantiation)
370 }
371
372 fn storage_fund_withdrawal() -> Self {
373 Self(HoldIdentifier::DomainStorageFund)
374 }
375}
376
377impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
378 fn messenger_channel() -> Self {
379 Self(HoldIdentifier::MessengerChannel)
380 }
381}
382
383impl VariantCount for HoldIdentifierWrapper {
384 const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
385}
386
387impl pallet_balances::Config for Runtime {
388 type RuntimeEvent = RuntimeEvent;
389 type RuntimeFreezeReason = RuntimeFreezeReason;
390 type MaxLocks = ConstU32<50>;
391 type MaxReserves = ();
392 type ReserveIdentifier = [u8; 8];
393 type Balance = Balance;
395 type DustRemoval = ();
397 type ExistentialDeposit = ConstU128<{ 10_000_000_000_000 * SHANNON }>;
398 type AccountStore = System;
399 type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
400 type FreezeIdentifier = ();
401 type MaxFreezes = ();
402 type RuntimeHoldReason = HoldIdentifierWrapper;
403 type DoneSlashHandler = ();
404}
405
406pub struct CreditSupply;
407
408impl Get<Balance> for CreditSupply {
409 fn get() -> Balance {
410 Balances::total_issuance().saturating_add(Transporter::all_domains_supply())
411 }
412}
413
414pub struct TotalSpacePledged;
415
416impl Get<u128> for TotalSpacePledged {
417 fn get() -> u128 {
418 u128::from(u64::MAX)
421 .saturating_mul(Piece::SIZE as u128)
422 .saturating_mul(u128::from(SlotProbability::get().0))
423 / u128::from(Subspace::solution_ranges().current)
424 / u128::from(SlotProbability::get().1)
425 }
426}
427
428pub struct BlockchainHistorySize;
429
430impl Get<u128> for BlockchainHistorySize {
431 fn get() -> u128 {
432 u128::from(Subspace::archived_history_size())
433 }
434}
435
436pub struct DynamicCostOfStorage;
437
438impl Get<bool> for DynamicCostOfStorage {
439 fn get() -> bool {
440 RuntimeConfigs::enable_dynamic_cost_of_storage()
441 }
442}
443
444impl pallet_transaction_fees::Config for Runtime {
445 type MinReplicationFactor = ConstU16<MIN_REPLICATION_FACTOR>;
446 type CreditSupply = CreditSupply;
447 type TotalSpacePledged = TotalSpacePledged;
448 type BlockchainHistorySize = BlockchainHistorySize;
449 type Currency = Balances;
450 type FindBlockRewardAddress = Subspace;
451 type DynamicCostOfStorage = DynamicCostOfStorage;
452 type WeightInfo = pallet_transaction_fees::weights::SubstrateWeight<Runtime>;
453}
454
455pub struct TransactionByteFee;
456
457impl Get<Balance> for TransactionByteFee {
458 fn get() -> Balance {
459 TransactionFees::transaction_byte_fee()
460 }
461}
462
463pub struct LiquidityInfo {
464 storage_fee: Balance,
465 imbalance: NegativeImbalance<Runtime>,
466}
467
468pub struct OnChargeTransaction;
471
472impl pallet_transaction_payment::TxCreditHold<Runtime> for OnChargeTransaction {
473 type Credit = ();
474}
475
476impl pallet_transaction_payment::OnChargeTransaction<Runtime> for OnChargeTransaction {
477 type LiquidityInfo = Option<LiquidityInfo>;
478 type Balance = Balance;
479
480 fn withdraw_fee(
481 who: &AccountId,
482 call: &RuntimeCall,
483 _info: &DispatchInfoOf<RuntimeCall>,
484 fee: Self::Balance,
485 tip: Self::Balance,
486 ) -> Result<Self::LiquidityInfo, TransactionValidityError> {
487 if fee.is_zero() {
488 return Ok(None);
489 }
490
491 let withdraw_reason = if tip.is_zero() {
492 WithdrawReasons::TRANSACTION_PAYMENT
493 } else {
494 WithdrawReasons::TRANSACTION_PAYMENT | WithdrawReasons::TIP
495 };
496
497 let withdraw_result =
498 Balances::withdraw(who, fee, withdraw_reason, ExistenceRequirement::KeepAlive);
499 let imbalance = withdraw_result.map_err(|_error| InvalidTransaction::Payment)?;
500
501 let storage_fee = TransactionByteFee::get()
503 * Balance::try_from(call.encoded_size())
504 .expect("Size of the call never exceeds balance units; qed");
505
506 Ok(Some(LiquidityInfo {
507 storage_fee,
508 imbalance,
509 }))
510 }
511
512 fn correct_and_deposit_fee(
513 who: &AccountId,
514 _dispatch_info: &DispatchInfoOf<RuntimeCall>,
515 _post_info: &PostDispatchInfoOf<RuntimeCall>,
516 corrected_fee: Self::Balance,
517 tip: Self::Balance,
518 liquidity_info: Self::LiquidityInfo,
519 ) -> Result<(), TransactionValidityError> {
520 if let Some(LiquidityInfo {
521 storage_fee,
522 imbalance,
523 }) = liquidity_info
524 {
525 let refund_amount = imbalance.peek().saturating_sub(corrected_fee);
527 let refund_imbalance = Balances::deposit_into_existing(who, refund_amount)
530 .unwrap_or_else(|_| <Balances as Currency<AccountId>>::PositiveImbalance::zero());
531 let adjusted_paid = imbalance
533 .offset(refund_imbalance)
534 .same()
535 .map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::Payment))?;
536
537 let (tip, fee) = adjusted_paid.split(tip);
539 let (paid_storage_fee, paid_compute_fee) = fee.split(storage_fee);
541
542 TransactionFees::note_transaction_fees(
543 paid_storage_fee.peek(),
544 paid_compute_fee.peek(),
545 tip.peek(),
546 );
547 }
548 Ok(())
549 }
550
551 fn can_withdraw_fee(
552 who: &AccountId,
553 _call: &RuntimeCall,
554 _dispatch_info: &DispatchInfoOf<RuntimeCall>,
555 fee: Self::Balance,
556 _tip: Self::Balance,
557 ) -> Result<(), TransactionValidityError> {
558 if fee.is_zero() {
559 return Ok(());
560 }
561
562 match Balances::can_withdraw(who, fee) {
563 WithdrawConsequence::Success => Ok(()),
564 _ => Err(InvalidTransaction::Payment.into()),
565 }
566 }
567
568 #[cfg(feature = "runtime-benchmarks")]
569 fn endow_account(who: &AccountId, amount: Self::Balance) {
570 Balances::set_balance(who, amount);
571 }
572
573 #[cfg(feature = "runtime-benchmarks")]
574 fn minimum_balance() -> Self::Balance {
575 <Balances as Currency<AccountId>>::minimum_balance()
576 }
577}
578
579impl pallet_transaction_payment::Config for Runtime {
580 type RuntimeEvent = RuntimeEvent;
581 type OnChargeTransaction = OnChargeTransaction;
582 type OperationalFeeMultiplier = ConstU8<5>;
583 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
584 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
585 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
586 type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
587}
588
589impl pallet_utility::Config for Runtime {
590 type RuntimeEvent = RuntimeEvent;
591 type RuntimeCall = RuntimeCall;
592 type PalletsOrigin = OriginCaller;
593 type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
594}
595
596impl MaybeBalancesCall<Runtime> for RuntimeCall {
597 fn maybe_balance_call(&self) -> Option<&pallet_balances::Call<Runtime>> {
598 match self {
599 RuntimeCall::Balances(call) => Some(call),
600 _ => None,
601 }
602 }
603}
604
605impl BalanceTransferChecks for Runtime {
606 fn is_balance_transferable() -> bool {
607 RuntimeConfigs::enable_balance_transfers()
608 }
609}
610
611impl MaybeMultisigCall<Runtime> for RuntimeCall {
612 fn maybe_multisig_call(&self) -> Option<&pallet_multisig::Call<Runtime>> {
614 match self {
615 RuntimeCall::Multisig(call) => Some(call),
616 _ => None,
617 }
618 }
619}
620
621impl MaybeUtilityCall<Runtime> for RuntimeCall {
622 fn maybe_utility_call(&self) -> Option<&pallet_utility::Call<Runtime>> {
624 match self {
625 RuntimeCall::Utility(call) => Some(call),
626 _ => None,
627 }
628 }
629}
630
631impl MaybeNestedCall<Runtime> for RuntimeCall {
632 fn maybe_nested_call(&self) -> Option<Vec<&RuntimeCallFor<Runtime>>> {
637 let calls = self.maybe_nested_utility_calls();
643 if calls.is_some() {
644 return calls;
645 }
646
647 let calls = self.maybe_nested_multisig_calls();
648 if calls.is_some() {
649 return calls;
650 }
651
652 None
653 }
654}
655
656impl pallet_sudo::Config for Runtime {
657 type RuntimeEvent = RuntimeEvent;
658 type RuntimeCall = RuntimeCall;
659 type WeightInfo = pallet_sudo::weights::SubstrateWeight<Runtime>;
660}
661
662parameter_types! {
663 pub SelfChainId: ChainId = ChainId::Consensus;
664}
665
666pub struct MmrProofVerifier;
667
668impl sp_subspace_mmr::MmrProofVerifier<mmr::Hash, NumberFor<Block>, Hash> for MmrProofVerifier {
669 fn verify_proof_and_extract_leaf(
670 mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, mmr::Hash>,
671 ) -> Option<mmr::Leaf> {
672 let mmr_root = SubspaceMmr::mmr_root_hash(mmr_leaf_proof.consensus_block_number)?;
673 Self::verify_proof_stateless(mmr_root, mmr_leaf_proof)
674 }
675
676 fn verify_proof_stateless(
677 mmr_root: mmr::Hash,
678 mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, mmr::Hash>,
679 ) -> Option<mmr::Leaf> {
680 let ConsensusChainMmrLeafProof {
681 opaque_mmr_leaf,
682 proof,
683 ..
684 } = mmr_leaf_proof;
685
686 pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(
687 mmr_root,
688 vec![mmr::DataOrHash::Data(
689 EncodableOpaqueLeaf(opaque_mmr_leaf.0.clone()).into_opaque_leaf(),
690 )],
691 proof,
692 )
693 .ok()?;
694
695 let leaf: mmr::Leaf = opaque_mmr_leaf.into_opaque_leaf().try_decode()?;
696
697 Some(leaf)
698 }
699}
700
701pub struct StorageKeys;
702
703impl sp_messenger::StorageKeys for StorageKeys {
704 fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
705 Some(Domains::confirmed_domain_block_storage_key(domain_id))
706 }
707
708 fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
709 get_storage_key(StorageKeyRequest::OutboxStorageKey {
710 chain_id,
711 message_key,
712 })
713 }
714
715 fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
716 get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
717 chain_id,
718 message_key,
719 })
720 }
721}
722
723pub struct DomainRegistration;
724impl sp_messenger::DomainRegistration for DomainRegistration {
725 fn is_domain_registered(domain_id: DomainId) -> bool {
726 Domains::is_domain_registered(domain_id)
727 }
728}
729
730parameter_types! {
731 pub const ChannelReserveFee: Balance = AI3;
732 pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
733 pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
734}
735
736const_assert!(MaxOutgoingMessages::get() >= 1);
738
739pub struct OnXDMRewards;
740
741impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
742 fn on_xdm_rewards(reward: Balance) {
743 if let Some(block_author) = Subspace::find_block_reward_address() {
744 let _ = Balances::deposit_creating(&block_author, reward);
745 }
746 }
747
748 fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
749 if let ChainId::Domain(domain_id) = chain_id {
752 Domains::reward_domain_operators(domain_id, fees)
753 }
754 }
755}
756
757impl pallet_messenger::Config for Runtime {
758 type SelfChainId = SelfChainId;
759
760 fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
761 if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
762 Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
763 } else {
764 None
765 }
766 }
767
768 type Currency = Balances;
769 type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
770 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
771 type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
772 type FeeMultiplier = XdmFeeMultipler;
773 type OnXDMRewards = OnXDMRewards;
774 type MmrHash = mmr::Hash;
775 type MmrProofVerifier = MmrProofVerifier;
776 type StorageKeys = StorageKeys;
777 type DomainOwner = Domains;
778 type HoldIdentifier = HoldIdentifierWrapper;
779 type ChannelReserveFee = ChannelReserveFee;
780 type ChannelInitReservePortion = ChannelInitReservePortion;
781 type DomainRegistration = DomainRegistration;
782 type MaxOutgoingMessages = MaxOutgoingMessages;
783 type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
784 type NoteChainTransfer = Transporter;
785 type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<
786 Runtime,
787 pallet_messenger::extensions::WeightsFromConsensus<Runtime>,
788 pallet_messenger::extensions::WeightsFromDomains<Runtime>,
789 >;
790}
791
792impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
793where
794 RuntimeCall: From<C>,
795{
796 type Extrinsic = UncheckedExtrinsic;
797 type RuntimeCall = RuntimeCall;
798}
799
800impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
801where
802 RuntimeCall: From<C>,
803{
804 fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
805 create_unsigned_general_extrinsic(call)
806 }
807}
808
809parameter_types! {
810 pub const TransporterEndpointId: EndpointId = 1;
811 pub const MinimumTransfer: Balance = 1;
812}
813
814impl pallet_transporter::Config for Runtime {
815 type SelfChainId = SelfChainId;
816 type SelfEndpointId = TransporterEndpointId;
817 type Currency = Balances;
818 type Sender = Messenger;
819 type AccountIdConverter = AccountIdConverter;
820 type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
821 type MinimumTransfer = MinimumTransfer;
822}
823
824pub struct BlockTreePruningDepth;
825impl Get<BlockNumber> for BlockTreePruningDepth {
826 fn get() -> BlockNumber {
827 pallet_runtime_configs::DomainBlockPruningDepth::<Runtime>::get()
828 }
829}
830
831pub struct StakeWithdrawalLockingPeriod;
832impl Get<BlockNumber> for StakeWithdrawalLockingPeriod {
833 fn get() -> BlockNumber {
834 pallet_runtime_configs::StakingWithdrawalPeriod::<Runtime>::get()
835 }
836}
837
838parameter_types! {
839 pub const MaximumReceiptDrift: BlockNumber = 2;
840 pub const InitialDomainTxRange: u64 = INITIAL_DOMAIN_TX_RANGE;
841 pub const DomainTxRangeAdjustmentInterval: u64 = 100;
842 pub const MinOperatorStake: Balance = 100 * AI3;
843 pub const MinNominatorStake: Balance = AI3;
844 pub MaxDomainBlockSize: u32 = NORMAL_DISPATCH_RATIO * MAX_BLOCK_LENGTH;
846 pub MaxDomainBlockWeight: Weight = NORMAL_DISPATCH_RATIO * BLOCK_WEIGHT_FOR_2_SEC;
848 pub const DomainInstantiationDeposit: Balance = 100 * AI3;
849 pub const MaxDomainNameLength: u32 = 32;
850 pub const StakeEpochDuration: DomainNumber = 5;
851 pub TreasuryAccount: AccountId = PalletId(*b"treasury").into_account_truncating();
852 pub const MaxPendingStakingOperation: u32 = 512;
853 pub const DomainsPalletId: PalletId = PalletId(*b"domains_");
854 pub const MaxInitialDomainAccounts: u32 = 20;
855 pub const MinInitialDomainAccountBalance: Balance = AI3;
856 pub const BundleLongevity: u32 = 5;
857 pub const WithdrawalLimit: u32 = 32;
858 pub const CurrentBundleAndExecutionReceiptVersion: BundleAndExecutionReceiptVersion = BundleAndExecutionReceiptVersion {
859 bundle_version: BundleVersion::V0,
860 execution_receipt_version: ExecutionReceiptVersion::V0,
861 };
862 pub const OperatorActivationDelayInEpochs: EpochIndex = 5;
863}
864
865const_assert!(BlockSlotCount::get() >= 2 && BlockSlotCount::get() > BundleLongevity::get());
868
869const_assert!(BlockHashCount::get() > BlockSlotCount::get());
872
873const_assert!(MinOperatorStake::get() >= MinNominatorStake::get());
875
876pub struct BlockSlot;
877
878impl pallet_domains::BlockSlot<Runtime> for BlockSlot {
879 fn future_slot(block_number: BlockNumber) -> Option<Slot> {
880 let block_slots = Subspace::block_slots();
881 block_slots
882 .get(&block_number)
883 .map(|slot| *slot + Slot::from(BlockAuthoringDelay::get()))
884 }
885
886 fn slot_produced_after(to_check: Slot) -> Option<BlockNumber> {
887 let block_slots = Subspace::block_slots();
888 for (block_number, slot) in block_slots.into_iter().rev() {
889 if to_check > slot {
890 return Some(block_number);
891 }
892 }
893 None
894 }
895
896 fn current_slot() -> Slot {
897 Subspace::current_slot()
898 }
899}
900
901pub struct OnChainRewards;
902
903impl sp_domains::OnChainRewards<Balance> for OnChainRewards {
904 fn on_chain_rewards(chain_id: ChainId, reward: Balance) {
905 match chain_id {
906 ChainId::Consensus => {
907 if let Some(block_author) = Subspace::find_block_reward_address() {
908 let _ = Balances::deposit_creating(&block_author, reward);
909 }
910 }
911 ChainId::Domain(domain_id) => Domains::reward_domain_operators(domain_id, reward),
912 }
913 }
914}
915
916impl pallet_domains::Config for Runtime {
917 type DomainOrigin = pallet_domains::EnsureDomainOrigin;
918 type DomainHash = DomainHash;
919 type Balance = Balance;
920 type DomainHeader = DomainHeader;
921 type ConfirmationDepthK = ConfirmationDepthK;
922 type Currency = Balances;
923 type Share = Balance;
924 type HoldIdentifier = HoldIdentifierWrapper;
925 type BlockTreePruningDepth = BlockTreePruningDepth;
926 type ConsensusSlotProbability = SlotProbability;
927 type MaxDomainBlockSize = MaxDomainBlockSize;
928 type MaxDomainBlockWeight = MaxDomainBlockWeight;
929 type MaxDomainNameLength = MaxDomainNameLength;
930 type DomainInstantiationDeposit = DomainInstantiationDeposit;
931 type WeightInfo = pallet_domains::weights::SubstrateWeight<Runtime>;
932 type InitialDomainTxRange = InitialDomainTxRange;
933 type DomainTxRangeAdjustmentInterval = DomainTxRangeAdjustmentInterval;
934 type MinOperatorStake = MinOperatorStake;
935 type MinNominatorStake = MinNominatorStake;
936 type StakeWithdrawalLockingPeriod = StakeWithdrawalLockingPeriod;
937 type StakeEpochDuration = StakeEpochDuration;
938 type TreasuryAccount = TreasuryAccount;
939 type MaxPendingStakingOperation = MaxPendingStakingOperation;
940 type Randomness = Subspace;
941 type PalletId = DomainsPalletId;
942 type StorageFee = TransactionFees;
943 type BlockTimestamp = pallet_timestamp::Pallet<Runtime>;
944 type BlockSlot = BlockSlot;
945 type DomainsTransfersTracker = Transporter;
946 type MaxInitialDomainAccounts = MaxInitialDomainAccounts;
947 type MinInitialDomainAccountBalance = MinInitialDomainAccountBalance;
948 type BundleLongevity = BundleLongevity;
949 type DomainBundleSubmitted = Messenger;
950 type OnDomainInstantiated = Messenger;
951 type MmrHash = mmr::Hash;
952 type MmrProofVerifier = MmrProofVerifier;
953 type FraudProofStorageKeyProvider = StorageKeyProvider;
954 type OnChainRewards = OnChainRewards;
955 type WithdrawalLimit = WithdrawalLimit;
956 type CurrentBundleAndExecutionReceiptVersion = CurrentBundleAndExecutionReceiptVersion;
957 type OperatorActivationDelayInEpochs = OperatorActivationDelayInEpochs;
958}
959
960parameter_types! {
961 pub const AvgBlockspaceUsageNumBlocks: BlockNumber = 100;
962 pub const ProposerTaxOnVotes: (u32, u32) = (1, 10);
963}
964
965impl pallet_rewards::Config for Runtime {
966 type Currency = Balances;
967 type AvgBlockspaceUsageNumBlocks = AvgBlockspaceUsageNumBlocks;
968 type TransactionByteFee = TransactionByteFee;
969 type MaxRewardPoints = ConstU32<20>;
970 type ProposerTaxOnVotes = ProposerTaxOnVotes;
971 type RewardsEnabled = Subspace;
972 type FindBlockRewardAddress = Subspace;
973 type FindVotingRewardAddresses = Subspace;
974 type WeightInfo = pallet_rewards::weights::SubstrateWeight<Runtime>;
975 type OnReward = ();
976}
977
978pub mod mmr {
979 use super::Runtime;
980 pub use pallet_mmr::primitives::*;
981
982 pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
983 pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
984 pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
985}
986
987pub struct BlockHashProvider;
988
989impl pallet_mmr::BlockHashProvider<BlockNumber, Hash> for BlockHashProvider {
990 fn block_hash(block_number: BlockNumber) -> Hash {
991 sp_subspace_mmr::subspace_mmr_runtime_interface::consensus_block_hash(block_number)
992 .expect("Hash must exist for a given block number.")
993 }
994}
995
996impl pallet_mmr::Config for Runtime {
997 const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
998 type Hashing = Keccak256;
999 type LeafData = SubspaceMmr;
1000 type OnNewRoot = SubspaceMmr;
1001 type BlockHashProvider = BlockHashProvider;
1002 type WeightInfo = ();
1003 #[cfg(feature = "runtime-benchmarks")]
1004 type BenchmarkHelper = ();
1005}
1006
1007parameter_types! {
1008 pub const MmrRootHashCount: u32 = 15;
1009}
1010
1011impl pallet_subspace_mmr::Config for Runtime {
1012 type MmrRootHash = mmr::Hash;
1013 type MmrRootHashCount = MmrRootHashCount;
1014}
1015
1016impl pallet_runtime_configs::Config for Runtime {
1017 type WeightInfo = pallet_runtime_configs::weights::SubstrateWeight<Runtime>;
1018}
1019
1020impl pallet_domains::extensions::DomainsCheck for Runtime {
1021 fn is_domains_enabled() -> bool {
1022 RuntimeConfigs::enable_domains()
1023 }
1024}
1025
1026parameter_types! {
1027 pub const MaxSignatories: u32 = 100;
1028}
1029
1030macro_rules! deposit {
1031 ($name:ident, $item_fee:expr, $items:expr, $bytes:expr) => {
1032 pub struct $name;
1033
1034 impl Get<Balance> for $name {
1035 fn get() -> Balance {
1036 $item_fee.saturating_mul($items.into()).saturating_add(
1037 TransactionFees::transaction_byte_fee().saturating_mul($bytes.into()),
1038 )
1039 }
1040 }
1041 };
1042}
1043
1044deposit!(DepositBaseFee, 20 * AI3, 1u32, 88u32);
1047
1048deposit!(DepositFactor, 0u128, 0u32, 32u32);
1050
1051impl pallet_multisig::Config for Runtime {
1052 type RuntimeEvent = RuntimeEvent;
1053 type RuntimeCall = RuntimeCall;
1054 type Currency = Balances;
1055 type DepositBase = DepositBaseFee;
1056 type DepositFactor = DepositFactor;
1057 type MaxSignatories = MaxSignatories;
1058 type WeightInfo = pallet_multisig::weights::SubstrateWeight<Runtime>;
1059 type BlockNumberProvider = System;
1060}
1061
1062construct_runtime!(
1063 pub struct Runtime {
1064 System: frame_system = 0,
1065 Timestamp: pallet_timestamp = 1,
1066
1067 Subspace: pallet_subspace = 2,
1068 Rewards: pallet_rewards = 9,
1069
1070 Balances: pallet_balances = 4,
1071 TransactionFees: pallet_transaction_fees = 12,
1072 TransactionPayment: pallet_transaction_payment = 5,
1073 Utility: pallet_utility = 8,
1074
1075 Domains: pallet_domains = 11,
1076 RuntimeConfigs: pallet_runtime_configs = 14,
1077
1078 Mmr: pallet_mmr = 30,
1079 SubspaceMmr: pallet_subspace_mmr = 31,
1080
1081 Messenger: pallet_messenger exclude_parts { Inherent } = 60,
1084 Transporter: pallet_transporter = 61,
1085
1086 Multisig: pallet_multisig = 90,
1088
1089 Sudo: pallet_sudo = 100,
1091 }
1092);
1093
1094pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
1096pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
1098pub type Block = generic::Block<Header, UncheckedExtrinsic>;
1100pub type SignedExtra = (
1102 (
1103 frame_system::CheckNonZeroSender<Runtime>,
1104 SmallOrderEd25519CheckExtension<Runtime>,
1105 ),
1106 frame_system::CheckSpecVersion<Runtime>,
1107 frame_system::CheckTxVersion<Runtime>,
1108 frame_system::CheckGenesis<Runtime>,
1109 frame_system::CheckMortality<Runtime>,
1110 frame_system::CheckNonce<Runtime>,
1111 frame_system::CheckWeight<Runtime>,
1112 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
1113 BalanceTransferCheckExtension<Runtime>,
1114 pallet_subspace::extensions::SubspaceExtension<Runtime>,
1115 pallet_domains::extensions::DomainsExtension<Runtime>,
1116 pallet_messenger::extensions::MessengerExtension<Runtime>,
1117);
1118pub type UncheckedExtrinsic =
1120 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
1121pub type Executive = frame_executive::Executive<
1123 Runtime,
1124 Block,
1125 frame_system::ChainContext<Runtime>,
1126 Runtime,
1127 AllPalletsWithSystem,
1128 pallet_transporter::migrations::VersionCheckedMigrateTransporterV0ToV1<Runtime>,
1129>;
1130pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
1132
1133impl pallet_subspace::extensions::MaybeSubspaceCall<Runtime> for RuntimeCall {
1134 fn maybe_subspace_call(&self) -> Option<&pallet_subspace::Call<Runtime>> {
1135 match self {
1136 RuntimeCall::Subspace(call) => Some(call),
1137 _ => None,
1138 }
1139 }
1140}
1141
1142impl pallet_domains::extensions::MaybeDomainsCall<Runtime> for RuntimeCall {
1143 fn maybe_domains_call(&self) -> Option<&pallet_domains::Call<Runtime>> {
1144 match self {
1145 RuntimeCall::Domains(call) => Some(call),
1146 _ => None,
1147 }
1148 }
1149}
1150
1151impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
1152 fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
1153 match self {
1154 RuntimeCall::Messenger(call) => Some(call),
1155 _ => None,
1156 }
1157 }
1158}
1159
1160fn extract_segment_headers(ext: &UncheckedExtrinsic) -> Option<Vec<SegmentHeader>> {
1161 match &ext.function {
1162 RuntimeCall::Subspace(pallet_subspace::Call::store_segment_headers { segment_headers }) => {
1163 Some(segment_headers.clone())
1164 }
1165 _ => None,
1166 }
1167}
1168
1169fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
1170 match &ext.function {
1171 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1172 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1173 let ConsensusChainMmrLeafProof {
1174 consensus_block_number,
1175 opaque_mmr_leaf,
1176 proof,
1177 ..
1178 } = msg.proof.consensus_mmr_proof();
1179
1180 let mmr_root = SubspaceMmr::mmr_root_hash(consensus_block_number)?;
1181
1182 Some(
1183 pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(
1184 mmr_root,
1185 vec![mmr::DataOrHash::Data(
1186 EncodableOpaqueLeaf(opaque_mmr_leaf.0.clone()).into_opaque_leaf(),
1187 )],
1188 proof,
1189 )
1190 .is_ok(),
1191 )
1192 }
1193 _ => None,
1194 }
1195}
1196
1197fn extract_utility_block_object_mapping(
1199 mut base_offset: u32,
1200 objects: &mut Vec<BlockObject>,
1201 call: &pallet_utility::Call<Runtime>,
1202 mut recursion_depth_left: u16,
1203) {
1204 if recursion_depth_left == 0 {
1205 return;
1206 }
1207
1208 recursion_depth_left -= 1;
1209
1210 base_offset += 1;
1212
1213 match call {
1214 pallet_utility::Call::batch { calls }
1215 | pallet_utility::Call::batch_all { calls }
1216 | pallet_utility::Call::force_batch { calls } => {
1217 base_offset += Compact::compact_len(&(calls.len() as u32)) as u32;
1218
1219 for call in calls {
1220 extract_call_block_object_mapping(base_offset, objects, call, recursion_depth_left);
1221
1222 base_offset += call.encoded_size() as u32;
1223 }
1224 }
1225 pallet_utility::Call::as_derivative { index, call } => {
1226 base_offset += index.encoded_size() as u32;
1227
1228 extract_call_block_object_mapping(
1229 base_offset,
1230 objects,
1231 call.as_ref(),
1232 recursion_depth_left,
1233 );
1234 }
1235 pallet_utility::Call::dispatch_as { as_origin, call }
1236 | pallet_utility::Call::dispatch_as_fallible { as_origin, call } => {
1237 base_offset += as_origin.encoded_size() as u32;
1238
1239 extract_call_block_object_mapping(
1240 base_offset,
1241 objects,
1242 call.as_ref(),
1243 recursion_depth_left,
1244 );
1245 }
1246 pallet_utility::Call::with_weight { call, .. } => {
1247 extract_call_block_object_mapping(
1248 base_offset,
1249 objects,
1250 call.as_ref(),
1251 recursion_depth_left,
1252 );
1253 }
1254 pallet_utility::Call::if_else { .. } => {}
1261 pallet_utility::Call::__Ignore(_, _) => {
1262 }
1264 }
1265}
1266
1267fn extract_call_block_object_mapping(
1268 mut base_offset: u32,
1269 objects: &mut Vec<BlockObject>,
1270 call: &RuntimeCall,
1271 recursion_depth_left: u16,
1272) {
1273 base_offset += 1;
1275
1276 match call {
1277 RuntimeCall::System(frame_system::Call::remark { remark }) => {
1279 objects.push(BlockObject {
1280 hash: hashes::blake3_hash(remark),
1281 offset: base_offset + 1,
1283 });
1284 }
1285 RuntimeCall::System(frame_system::Call::remark_with_event { remark }) => {
1286 objects.push(BlockObject {
1287 hash: hashes::blake3_hash(remark),
1288 offset: base_offset + 1,
1290 });
1291 }
1292
1293 RuntimeCall::Utility(call) => {
1295 extract_utility_block_object_mapping(base_offset, objects, call, recursion_depth_left)
1296 }
1297 _ => {}
1299 }
1300}
1301
1302fn extract_block_object_mapping(block: Block) -> BlockObjectMapping {
1303 let mut block_object_mapping = BlockObjectMapping::default();
1304 let mut base_offset =
1305 block.header.encoded_size() + Compact::compact_len(&(block.extrinsics.len() as u32));
1306 for extrinsic in block.extrinsics {
1307 let preamble_size = extrinsic.preamble.encoded_size();
1308 let base_extrinsic_offset = base_offset
1311 + Compact::compact_len(&((preamble_size + extrinsic.function.encoded_size()) as u32))
1312 + preamble_size;
1313
1314 extract_call_block_object_mapping(
1315 base_extrinsic_offset as u32,
1316 block_object_mapping.objects_mut(),
1317 &extrinsic.function,
1318 MAX_CALL_RECURSION_DEPTH as u16,
1319 );
1320
1321 base_offset += extrinsic.encoded_size();
1322 }
1323
1324 block_object_mapping
1325}
1326
1327fn extract_successful_bundles(
1328 domain_id: DomainId,
1329 extrinsics: Vec<UncheckedExtrinsic>,
1330) -> OpaqueBundles<Block, DomainHeader, Balance> {
1331 let successful_bundles = Domains::successful_bundles(domain_id);
1332 extrinsics
1333 .into_iter()
1334 .filter_map(|uxt| match uxt.function {
1335 RuntimeCall::Domains(pallet_domains::Call::submit_bundle { opaque_bundle })
1336 if opaque_bundle.domain_id() == domain_id
1337 && successful_bundles.contains(&opaque_bundle.hash()) =>
1338 {
1339 Some(opaque_bundle)
1340 }
1341 _ => None,
1342 })
1343 .collect()
1344}
1345
1346fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
1347 let extra: SignedExtra = (
1348 (
1349 frame_system::CheckNonZeroSender::<Runtime>::new(),
1350 SmallOrderEd25519CheckExtension::<Runtime>::new(),
1351 ),
1352 frame_system::CheckSpecVersion::<Runtime>::new(),
1353 frame_system::CheckTxVersion::<Runtime>::new(),
1354 frame_system::CheckGenesis::<Runtime>::new(),
1355 frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1356 frame_system::CheckNonce::<Runtime>::from(0u32.into()),
1359 frame_system::CheckWeight::<Runtime>::new(),
1360 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1363 BalanceTransferCheckExtension::<Runtime>::default(),
1364 pallet_subspace::extensions::SubspaceExtension::<Runtime>::new(),
1365 pallet_domains::extensions::DomainsExtension::<Runtime>::new(),
1366 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1367 );
1368
1369 UncheckedExtrinsic::new_transaction(call, extra)
1370}
1371
1372struct RewardAddress([u8; 32]);
1373
1374impl From<PublicKey> for RewardAddress {
1375 #[inline]
1376 fn from(public_key: PublicKey) -> Self {
1377 Self(*public_key)
1378 }
1379}
1380
1381impl From<RewardAddress> for AccountId32 {
1382 #[inline]
1383 fn from(reward_address: RewardAddress) -> Self {
1384 reward_address.0.into()
1385 }
1386}
1387
1388pub struct StorageKeyProvider;
1389impl FraudProofStorageKeyProvider<NumberFor<Block>> for StorageKeyProvider {
1390 fn storage_key(req: FraudProofStorageKeyRequest<NumberFor<Block>>) -> Vec<u8> {
1391 match req {
1392 FraudProofStorageKeyRequest::InvalidInherentExtrinsicData => {
1393 pallet_domains::BlockInherentExtrinsicData::<Runtime>::hashed_key().to_vec()
1394 }
1395 FraudProofStorageKeyRequest::SuccessfulBundles(domain_id) => {
1396 pallet_domains::SuccessfulBundles::<Runtime>::hashed_key_for(domain_id)
1397 }
1398 FraudProofStorageKeyRequest::DomainAllowlistUpdates(domain_id) => {
1399 Messenger::domain_allow_list_update_storage_key(domain_id)
1400 }
1401 FraudProofStorageKeyRequest::DomainRuntimeUpgrades => {
1402 pallet_domains::DomainRuntimeUpgrades::<Runtime>::hashed_key().to_vec()
1403 }
1404 FraudProofStorageKeyRequest::RuntimeRegistry(runtime_id) => {
1405 pallet_domains::RuntimeRegistry::<Runtime>::hashed_key_for(runtime_id)
1406 }
1407 FraudProofStorageKeyRequest::DomainSudoCall(domain_id) => {
1408 pallet_domains::DomainSudoCalls::<Runtime>::hashed_key_for(domain_id)
1409 }
1410 FraudProofStorageKeyRequest::EvmDomainContractCreationAllowedByCall(domain_id) => {
1411 pallet_domains::EvmDomainContractCreationAllowedByCalls::<Runtime>::hashed_key_for(
1412 domain_id,
1413 )
1414 }
1415 FraudProofStorageKeyRequest::MmrRoot(block_number) => {
1416 pallet_subspace_mmr::MmrRootHashes::<Runtime>::hashed_key_for(block_number)
1417 }
1418 }
1419 }
1420}
1421
1422impl_runtime_apis! {
1423 impl sp_api::Core<Block> for Runtime {
1424 fn version() -> RuntimeVersion {
1425 VERSION
1426 }
1427
1428 fn execute_block(block: <Block as sp_runtime::traits::Block>::LazyBlock) {
1429 Executive::execute_block(block);
1430 }
1431
1432 fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
1433 Executive::initialize_block(header)
1434 }
1435 }
1436
1437 impl sp_api::Metadata<Block> for Runtime {
1438 fn metadata() -> OpaqueMetadata {
1439 OpaqueMetadata::new(Runtime::metadata().into())
1440 }
1441
1442 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1443 Runtime::metadata_at_version(version)
1444 }
1445
1446 fn metadata_versions() -> Vec<u32> {
1447 Runtime::metadata_versions()
1448 }
1449 }
1450
1451 impl sp_block_builder::BlockBuilder<Block> for Runtime {
1452 fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
1453 Executive::apply_extrinsic(extrinsic)
1454 }
1455
1456 fn finalize_block() -> HeaderFor<Block> {
1457 Executive::finalize_block()
1458 }
1459
1460 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
1461 data.create_extrinsics()
1462 }
1463
1464 fn check_inherents(
1465 block: <Block as sp_runtime::traits::Block>::LazyBlock,
1466 data: sp_inherents::InherentData,
1467 ) -> sp_inherents::CheckInherentsResult {
1468 data.check_extrinsics(&block)
1469 }
1470 }
1471
1472 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1473 fn validate_transaction(
1474 source: TransactionSource,
1475 tx: ExtrinsicFor<Block>,
1476 block_hash: BlockHashFor<Block>,
1477 ) -> TransactionValidity {
1478 Executive::validate_transaction(source, tx, block_hash)
1479 }
1480 }
1481
1482 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1483 fn offchain_worker(header: &HeaderFor<Block>) {
1484 Executive::offchain_worker(header)
1485 }
1486 }
1487
1488 impl sp_objects::ObjectsApi<Block> for Runtime {
1489 fn extract_block_object_mapping(block: Block) -> BlockObjectMapping {
1490 extract_block_object_mapping(block)
1491 }
1492 }
1493
1494 impl sp_consensus_subspace::SubspaceApi<Block, PublicKey> for Runtime {
1495 fn pot_parameters() -> PotParameters {
1496 Subspace::pot_parameters()
1497 }
1498
1499 fn solution_ranges() -> SolutionRanges {
1500 Subspace::solution_ranges()
1501 }
1502
1503 fn submit_vote_extrinsic(
1504 signed_vote: SignedVote<NumberFor<Block>, BlockHashFor<Block>, PublicKey>,
1505 ) {
1506 let SignedVote { vote, signature } = signed_vote;
1507 let Vote::V0 {
1508 height,
1509 parent_hash,
1510 slot,
1511 solution,
1512 proof_of_time,
1513 future_proof_of_time,
1514 } = vote;
1515
1516 Subspace::submit_vote(SignedVote {
1517 vote: Vote::V0 {
1518 height,
1519 parent_hash,
1520 slot,
1521 solution: solution.into_reward_address_format::<RewardAddress, AccountId32>(),
1522 proof_of_time,
1523 future_proof_of_time,
1524 },
1525 signature,
1526 })
1527 }
1528
1529 fn history_size() -> HistorySize {
1530 <pallet_subspace::Pallet<Runtime>>::history_size()
1531 }
1532
1533 fn max_pieces_in_sector() -> u16 {
1534 MAX_PIECES_IN_SECTOR
1535 }
1536
1537 fn segment_commitment(segment_index: SegmentIndex) -> Option<SegmentCommitment> {
1538 Subspace::segment_commitment(segment_index)
1539 }
1540
1541 fn extract_segment_headers(ext: &ExtrinsicFor<Block>) -> Option<Vec<SegmentHeader >> {
1542 extract_segment_headers(ext)
1543 }
1544
1545 fn is_inherent(ext: &ExtrinsicFor<Block>) -> bool {
1546 match &ext.function {
1547 RuntimeCall::Subspace(call) => Subspace::is_inherent(call),
1548 RuntimeCall::Timestamp(call) => Timestamp::is_inherent(call),
1549 _ => false,
1550 }
1551 }
1552
1553 fn root_plot_public_key() -> Option<PublicKey> {
1554 Subspace::root_plot_public_key()
1555 }
1556
1557 fn should_adjust_solution_range() -> bool {
1558 Subspace::should_adjust_solution_range()
1559 }
1560
1561 fn chain_constants() -> ChainConstants {
1562 ChainConstants::V0 {
1563 confirmation_depth_k: ConfirmationDepthK::get(),
1564 block_authoring_delay: Slot::from(BlockAuthoringDelay::get()),
1565 era_duration: EraDuration::get(),
1566 slot_probability: SlotProbability::get(),
1567 slot_duration: SlotDuration::from_millis(SLOT_DURATION),
1568 recent_segments: RecentSegments::get(),
1569 recent_history_fraction: RecentHistoryFraction::get(),
1570 min_sector_lifetime: MinSectorLifetime::get(),
1571 }
1572 }
1573
1574 fn block_weight() -> Weight {
1575 System::block_weight().total()
1576 }
1577 }
1578
1579 impl sp_domains::DomainsApi<Block, DomainHeader> for Runtime {
1580 fn submit_bundle_unsigned(
1581 opaque_bundle: OpaqueBundle<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, Balance>,
1582 ) {
1583 Domains::submit_bundle_unsigned(opaque_bundle)
1584 }
1585
1586 fn submit_receipt_unsigned(
1587 singleton_receipt: SealedSingletonReceipt<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, Balance>,
1588 ) {
1589 Domains::submit_receipt_unsigned(singleton_receipt)
1590 }
1591
1592 fn extract_successful_bundles(
1593 domain_id: DomainId,
1594 extrinsics: Vec<ExtrinsicFor<Block>>,
1595 ) -> OpaqueBundles<Block, DomainHeader, Balance> {
1596 extract_successful_bundles(domain_id, extrinsics)
1597 }
1598
1599 fn extrinsics_shuffling_seed() -> Randomness {
1600 Randomness::from(Domains::extrinsics_shuffling_seed().to_fixed_bytes())
1601 }
1602
1603 fn domain_runtime_code(domain_id: DomainId) -> Option<Vec<u8>> {
1604 Domains::domain_runtime_code(domain_id)
1605 }
1606
1607 fn runtime_id(domain_id: DomainId) -> Option<sp_domains::RuntimeId> {
1608 Domains::runtime_id(domain_id)
1609 }
1610
1611 fn runtime_upgrades() -> Vec<sp_domains::RuntimeId> {
1612 Domains::runtime_upgrades()
1613 }
1614
1615 fn domain_instance_data(domain_id: DomainId) -> Option<(DomainInstanceData, NumberFor<Block>)> {
1616 Domains::domain_instance_data(domain_id)
1617 }
1618
1619 fn domain_timestamp() -> Moment {
1620 Domains::timestamp()
1621 }
1622
1623 fn consensus_transaction_byte_fee() -> Balance {
1624 Domains::consensus_transaction_byte_fee()
1625 }
1626
1627 fn domain_tx_range(_: DomainId) -> U256 {
1628 U256::MAX
1629 }
1630
1631 fn genesis_state_root(domain_id: DomainId) -> Option<H256> {
1632 Domains::domain_genesis_block_execution_receipt(domain_id)
1633 .map(|er| *er.final_state_root())
1634 }
1635
1636 fn head_receipt_number(domain_id: DomainId) -> DomainNumber {
1637 Domains::head_receipt_number(domain_id)
1638 }
1639
1640 fn oldest_unconfirmed_receipt_number(domain_id: DomainId) -> Option<DomainNumber> {
1641 Domains::oldest_unconfirmed_receipt_number(domain_id)
1642 }
1643
1644 fn domain_bundle_limit(domain_id: DomainId) -> Option<sp_domains::DomainBundleLimit> {
1645 Domains::domain_bundle_limit(domain_id).ok().flatten()
1646 }
1647
1648 fn non_empty_er_exists(domain_id: DomainId) -> bool {
1649 Domains::non_empty_er_exists(domain_id)
1650 }
1651
1652 fn domain_best_number(domain_id: DomainId) -> Option<DomainNumber> {
1653 Domains::domain_best_number(domain_id).ok()
1654 }
1655
1656 fn execution_receipt(receipt_hash: DomainHash) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>> {
1657 Domains::execution_receipt(receipt_hash)
1658 }
1659
1660 fn domain_operators(domain_id: DomainId) -> Option<(BTreeMap<OperatorId, Balance>, Vec<OperatorId>)> {
1661 Domains::domain_staking_summary(domain_id).map(|summary| {
1662 let next_operators = summary.next_operators.into_iter().collect();
1663 (summary.current_operators, next_operators)
1664 })
1665 }
1666
1667 fn receipt_hash(domain_id: DomainId, domain_number: DomainNumber) -> Option<DomainHash> {
1668 Domains::receipt_hash(domain_id, domain_number)
1669 }
1670
1671 fn latest_confirmed_domain_block(domain_id: DomainId) -> Option<(DomainNumber, DomainHash)>{
1672 Domains::latest_confirmed_domain_block(domain_id)
1673 }
1674
1675 fn is_bad_er_pending_to_prune(domain_id: DomainId, receipt_hash: DomainHash) -> bool {
1676 Domains::execution_receipt(receipt_hash).map(
1677 |er| Domains::is_bad_er_pending_to_prune(domain_id, *er.domain_block_number())
1678 )
1679 .unwrap_or(false)
1680 }
1681
1682 fn storage_fund_account_balance(operator_id: OperatorId) -> Balance {
1683 Domains::storage_fund_account_balance(operator_id)
1684 }
1685
1686 fn is_domain_runtime_upgraded_since(domain_id: DomainId, at: NumberFor<Block>) -> Option<bool> {
1687 Domains::is_domain_runtime_upgraded_since(domain_id, at)
1688 }
1689
1690 fn domain_sudo_call(domain_id: DomainId) -> Option<Vec<u8>> {
1691 Domains::domain_sudo_call(domain_id)
1692 }
1693
1694 fn evm_domain_contract_creation_allowed_by_call(domain_id: DomainId) -> Option<PermissionedActionAllowedBy<EthereumAccountId>> {
1695 Domains::evm_domain_contract_creation_allowed_by_call(domain_id)
1696 }
1697
1698 fn last_confirmed_domain_block_receipt(domain_id: DomainId) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>>{
1699 Domains::latest_confirmed_domain_execution_receipt(domain_id)
1700 }
1701
1702 fn current_bundle_and_execution_receipt_version() -> BundleAndExecutionReceiptVersion {
1703 Domains::current_bundle_and_execution_receipt_version()
1704 }
1705
1706 fn genesis_execution_receipt(domain_id: DomainId) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>> {
1707 Domains::domain_genesis_block_execution_receipt(domain_id)
1708 }
1709
1710 fn nominator_position(
1711 operator_id: OperatorId,
1712 nominator_account: sp_runtime::AccountId32,
1713 ) -> Option<sp_domains::NominatorPosition<Balance, DomainNumber, Balance>> {
1714 Domains::nominator_position(operator_id, nominator_account)
1715 }
1716
1717 fn block_pruning_depth() -> NumberFor<Block> {
1718 BlockTreePruningDepth::get()
1719 }
1720 }
1721
1722 impl sp_domains::BundleProducerElectionApi<Block, Balance> for Runtime {
1723 fn bundle_producer_election_params(domain_id: DomainId) -> Option<BundleProducerElectionParams<Balance>> {
1724 Domains::bundle_producer_election_params(domain_id)
1725 }
1726
1727 fn operator(operator_id: OperatorId) -> Option<(OperatorPublicKey, Balance)> {
1728 Domains::operator(operator_id)
1729 }
1730 }
1731
1732 impl sp_session::SessionKeys<Block> for Runtime {
1733 fn generate_session_keys(
1734 owner: Vec<u8>,
1735 seed: Option<Vec<u8>>,
1736 ) -> sp_session::OpaqueGeneratedSessionKeys {
1737 SessionKeys::generate(&owner, seed).into()
1738 }
1739
1740 fn decode_session_keys(
1741 encoded: Vec<u8>,
1742 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1743 SessionKeys::decode_into_raw_public_keys(&encoded)
1744 }
1745 }
1746
1747 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1748 fn account_nonce(account: AccountId) -> Nonce {
1749 *System::account_nonce(account)
1750 }
1751 }
1752
1753 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1754 fn query_info(
1755 uxt: ExtrinsicFor<Block>,
1756 len: u32,
1757 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1758 TransactionPayment::query_info(uxt, len)
1759 }
1760 fn query_fee_details(
1761 uxt: ExtrinsicFor<Block>,
1762 len: u32,
1763 ) -> pallet_transaction_payment::FeeDetails<Balance> {
1764 TransactionPayment::query_fee_details(uxt, len)
1765 }
1766 fn query_weight_to_fee(weight: Weight) -> Balance {
1767 TransactionPayment::weight_to_fee(weight)
1768 }
1769 fn query_length_to_fee(length: u32) -> Balance {
1770 TransactionPayment::length_to_fee(length)
1771 }
1772 }
1773
1774 impl sp_messenger::MessengerApi<Block, BlockNumber, BlockHashFor<Block>> for Runtime {
1775 fn is_xdm_mmr_proof_valid(
1776 extrinsic: &ExtrinsicFor<Block>
1777 ) -> Option<bool> {
1778 is_xdm_mmr_proof_valid(extrinsic)
1779 }
1780
1781 fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<BlockNumber, BlockHashFor<Block>, sp_core::H256>> {
1782 match &ext.function {
1783 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1784 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1785 Some(msg.proof.consensus_mmr_proof())
1786 }
1787 _ => None,
1788 }
1789 }
1790
1791 fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<BlockNumber, BlockHashFor<Block>, sp_core::H256>> {
1792 let mut mmr_proofs = BTreeMap::new();
1793 for (index, ext) in extrinsics.iter().enumerate() {
1794 match &ext.function {
1795 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1796 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1797 mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1798 }
1799 _ => {},
1800 }
1801 }
1802 mmr_proofs
1803 }
1804
1805 fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Vec<u8> {
1806 Domains::confirmed_domain_block_storage_key(domain_id)
1807 }
1808
1809 fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1810 Messenger::outbox_storage_key(message_key)
1811 }
1812
1813 fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1814 Messenger::inbox_response_storage_key(message_key)
1815 }
1816
1817 fn domain_chains_allowlist_update(domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1818 Messenger::domain_chains_allowlist_update(domain_id)
1819 }
1820
1821 fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1822 match &ext.function {
1823 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1824 Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1825 }
1826 RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1827 Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1828 }
1829 _ => None,
1830 }
1831 }
1832
1833 fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1834 Messenger::channel_nonce(chain_id, channel_id)
1835 }
1836 }
1837
1838 impl sp_messenger::RelayerApi<Block, BlockNumber, BlockNumber, BlockHashFor<Block>> for Runtime {
1839 fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1840 Messenger::outbox_message_unsigned(msg)
1841 }
1842
1843 fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1844 Messenger::inbox_response_message_unsigned(msg)
1845 }
1846
1847 fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1848 Messenger::updated_channels()
1849 }
1850
1851 fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1852 Messenger::channel_storage_key(chain_id, channel_id)
1853 }
1854
1855 fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1856 Messenger::open_channels()
1857 }
1858
1859 fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1860 Messenger::get_block_messages(query)
1861 }
1862
1863 fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1864 Messenger::channels_and_states()
1865 }
1866
1867 fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1868 Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1869 }
1870
1871 fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1872 Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1873 }
1874 }
1875
1876 impl sp_domains_fraud_proof::FraudProofApi<Block, DomainHeader> for Runtime {
1877 fn submit_fraud_proof_unsigned(fraud_proof: FraudProof<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, H256>) {
1878 Domains::submit_fraud_proof_unsigned(fraud_proof)
1879 }
1880
1881 fn fraud_proof_storage_key(req: FraudProofStorageKeyRequest<NumberFor<Block>>) -> Vec<u8> {
1882 <StorageKeyProvider as FraudProofStorageKeyProvider<NumberFor<Block>>>::storage_key(req)
1883 }
1884 }
1885
1886 impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
1887 fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
1888 Ok(Mmr::mmr_root())
1889 }
1890
1891 fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
1892 Ok(Mmr::mmr_leaves())
1893 }
1894
1895 fn generate_proof(
1896 block_numbers: Vec<BlockNumber>,
1897 best_known_block_number: Option<BlockNumber>,
1898 ) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
1899 Mmr::generate_proof(block_numbers, best_known_block_number).map(
1900 |(leaves, proof)| {
1901 (
1902 leaves
1903 .into_iter()
1904 .map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
1905 .collect(),
1906 proof,
1907 )
1908 },
1909 )
1910 }
1911
1912 fn generate_ancestry_proof(
1913 prev_block_number: BlockNumber,
1914 best_known_block_number: Option<BlockNumber>,
1915 ) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
1916 Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
1917 }
1918
1919 fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
1920 -> Result<(), mmr::Error>
1921 {
1922 let leaves = leaves.into_iter().map(|leaf|
1923 leaf.into_opaque_leaf()
1924 .try_decode()
1925 .ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
1926 Mmr::verify_leaves(leaves, proof)
1927 }
1928
1929 fn verify_proof_stateless(
1930 root: mmr::Hash,
1931 leaves: Vec<mmr::EncodableOpaqueLeaf>,
1932 proof: mmr::LeafProof<mmr::Hash>
1933 ) -> Result<(), mmr::Error> {
1934 let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
1935 pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
1936 }
1937 }
1938
1939 impl subspace_test_primitives::OnchainStateApi<Block, AccountId, Balance> for Runtime {
1940 fn free_balance(account_id: AccountId) -> Balance {
1941 Balances::free_balance(account_id)
1942 }
1943
1944 fn get_open_channel_for_chain(dst_chain_id: ChainId) -> Option<ChannelId> {
1945 Messenger::get_open_channel_for_chain(dst_chain_id)
1946 }
1947
1948 fn verify_proof_and_extract_leaf(mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, BlockHashFor<Block>, H256>) -> Option<mmr::Leaf> {
1949 <MmrProofVerifier as sp_subspace_mmr::MmrProofVerifier<_, _, _,>>::verify_proof_and_extract_leaf(mmr_leaf_proof)
1950 }
1951
1952 fn domain_balance(domain_id: DomainId) -> Balance {
1953 Transporter::domain_balances(domain_id)
1954 }
1955
1956 fn consensus_total_issuance() -> Balance {
1957 Balances::total_issuance()
1958 }
1959
1960 fn consensus_credit_supply() -> Balance {
1961 CreditSupply::get()
1962 }
1963
1964 fn domain_stake_summary(domain_id: DomainId) -> Option<StakingSummary<OperatorId, Balance>>{
1965 Domains::domain_staking_summary(domain_id)
1966 }
1967 }
1968
1969 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1970 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1971 build_state::<RuntimeGenesisConfig>(config)
1972 }
1973
1974 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1975 get_preset::<RuntimeGenesisConfig>(id, |_| None)
1976 }
1977
1978 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1979 vec![]
1980 }
1981 }
1982}
1983
1984#[cfg(test)]
1985mod tests {
1986 use crate::{
1987 AccountId, Balance, Balances, BlockchainHistorySize, Executive, MIN_REPLICATION_FACTOR,
1988 Runtime, RuntimeCall, RuntimeConfigs, Signature, SignedExtra, System, TotalSpacePledged,
1989 TransactionFees, Transporter, UncheckedExtrinsic,
1990 };
1991 use frame_support::traits::{
1992 Currency, ExistenceRequirement, Get, OnFinalize, OnInitialize, WithdrawReasons,
1993 };
1994 use pallet_domains::bundle_storage_fund::AccountType;
1995 use pallet_runtime_configs::EnableDynamicCostOfStorage;
1996 use parity_scale_codec::Encode;
1997 use sp_core::{Pair as _, sr25519};
1998 use sp_domains::{DomainId, DomainsTransfersTracker, OperatorId};
1999 use sp_messenger::messages::ChainId;
2000 use sp_runtime::generic::{Era, SignedPayload};
2001 use sp_runtime::traits::{AccountIdConversion, TransactionExtension};
2002 use sp_runtime::transaction_validity::{InvalidTransaction, TransactionSource};
2003 use sp_runtime::{BuildStorage, MultiAddress};
2004 use subspace_runtime_primitives::extension::{
2005 BalanceTransferCheckExtension, SmallOrderEd25519CheckExtension,
2006 };
2007
2008 #[test]
2009 fn test_bundle_storage_fund_account_uniqueness() {
2010 let _: <Runtime as frame_system::Config>::AccountId = <Runtime as pallet_domains::Config>::PalletId::get()
2011 .try_into_sub_account((AccountType::StorageFund, OperatorId::MAX))
2012 .expect(
2013 "The `AccountId` type must be large enough to fit the seed of the bundle storage fund account",
2014 );
2015 }
2016
2017 const TEST_ACCOUNT: [u8; 32] = [1u8; 32];
2018 const INITIAL_BALANCE: Balance = 1_000_000_000_000_000_000;
2020
2021 fn new_test_ext() -> sp_io::TestExternalities {
2022 let mut t = frame_system::GenesisConfig::<Runtime>::default()
2023 .build_storage()
2024 .unwrap();
2025 pallet_balances::GenesisConfig::<Runtime> {
2026 balances: vec![(AccountId::from(TEST_ACCOUNT), INITIAL_BALANCE)],
2027 dev_accounts: None,
2028 }
2029 .assimilate_storage(&mut t)
2030 .unwrap();
2031 let mut ext: sp_io::TestExternalities = t.into();
2032 ext.execute_with(|| System::set_block_number(1));
2033 ext
2034 }
2035
2036 #[test]
2037 fn dynamic_byte_fee_tracks_all_domains_supply() {
2038 new_test_ext().execute_with(|| {
2039 EnableDynamicCostOfStorage::<Runtime>::put(true);
2040
2041 let free_space = TotalSpacePledged::get() / u128::from(MIN_REPLICATION_FACTOR)
2044 - BlockchainHistorySize::get();
2045 assert!(
2046 free_space > 0,
2047 "must exercise the credit_supply / free_space branch"
2048 );
2049
2050 let fee_before = TransactionFees::calculate_transaction_byte_fee();
2051
2052 Transporter::initialize_domain_balance(DomainId::new(0), free_space).unwrap();
2054
2055 let fee_after = TransactionFees::calculate_transaction_byte_fee();
2056 assert_eq!(
2057 fee_after,
2058 fee_before + 1,
2059 "raising the aggregate by one free_space raises the per-byte fee by exactly one"
2060 );
2061
2062 TransactionFees::on_initialize(System::block_number());
2064 TransactionFees::on_finalize(System::block_number());
2065 let getter_fee = TransactionFees::transaction_byte_fee();
2066 assert_eq!(getter_fee, fee_after);
2067 assert!(getter_fee > 1);
2068 });
2069 }
2070
2071 #[test]
2072 fn credit_supply_conservation_keeps_byte_fee_stable() {
2073 new_test_ext().execute_with(|| {
2074 EnableDynamicCostOfStorage::<Runtime>::put(true);
2075 let account = AccountId::from(TEST_ACCOUNT);
2076 let amount: Balance = 500_000_000;
2077
2078 let fee_before = TransactionFees::calculate_transaction_byte_fee();
2079
2080 let _ = <Balances as Currency<AccountId>>::withdraw(
2083 &account,
2084 amount,
2085 WithdrawReasons::TRANSFER,
2086 ExistenceRequirement::AllowDeath,
2087 )
2088 .expect("account funded in genesis");
2089 let domain = ChainId::Domain(DomainId::new(0));
2090 Transporter::note_transfer(ChainId::Consensus, domain, amount).unwrap();
2091 Transporter::confirm_transfer(ChainId::Consensus, domain, amount).unwrap();
2092
2093 let fee_after = TransactionFees::calculate_transaction_byte_fee();
2094 assert_eq!(
2095 fee_after, fee_before,
2096 "a conserved consensus->domain transfer must not move the byte fee"
2097 );
2098 });
2099 }
2100
2101 #[test]
2102 fn byte_fee_is_constant_when_dynamic_cost_disabled() {
2103 new_test_ext().execute_with(|| {
2104 assert!(!RuntimeConfigs::enable_dynamic_cost_of_storage());
2106 assert_eq!(TransactionFees::transaction_byte_fee(), 1);
2107
2108 Transporter::initialize_domain_balance(DomainId::new(0), 1_000_000).unwrap();
2110 assert_eq!(TransactionFees::transaction_byte_fee(), 1);
2111 });
2112 }
2113
2114 fn signed_extra(nonce: u32) -> SignedExtra {
2115 (
2116 (
2117 frame_system::CheckNonZeroSender::<Runtime>::new(),
2118 SmallOrderEd25519CheckExtension::<Runtime>::new(),
2119 ),
2120 frame_system::CheckSpecVersion::<Runtime>::new(),
2121 frame_system::CheckTxVersion::<Runtime>::new(),
2122 frame_system::CheckGenesis::<Runtime>::new(),
2123 frame_system::CheckMortality::<Runtime>::from(Era::Immortal),
2124 frame_system::CheckNonce::<Runtime>::from(nonce.into()),
2125 frame_system::CheckWeight::<Runtime>::new(),
2126 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
2127 BalanceTransferCheckExtension::<Runtime>::default(),
2128 pallet_subspace::extensions::SubspaceExtension::<Runtime>::new(),
2129 pallet_domains::extensions::DomainsExtension::<Runtime>::new(),
2130 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
2131 )
2132 }
2133
2134 fn remark_call() -> RuntimeCall {
2135 RuntimeCall::System(frame_system::Call::remark { remark: vec![] })
2136 }
2137
2138 fn signing_payload(call: &RuntimeCall, extra: &SignedExtra) -> Vec<u8> {
2139 let implicit = <SignedExtra as TransactionExtension<RuntimeCall>>::implicit(extra)
2140 .expect("implicit data must be available in the test environment");
2141 SignedPayload::<RuntimeCall, SignedExtra>::from_raw(call.clone(), extra.clone(), implicit)
2142 .using_encoded(|encoded| encoded.to_vec())
2143 }
2144
2145 #[test]
2146 fn small_order_ed25519_signed_extrinsic_is_rejected() {
2147 let ordinary_pair = sr25519::Pair::from_seed(&[3u8; 32]);
2148 let mut storage = frame_system::GenesisConfig::<Runtime>::default()
2149 .build_storage()
2150 .unwrap();
2151 pallet_balances::GenesisConfig::<Runtime> {
2152 balances: vec![(
2153 AccountId::new(ordinary_pair.public().to_raw()),
2154 INITIAL_BALANCE,
2155 )],
2156 dev_accounts: None,
2157 }
2158 .assimilate_storage(&mut storage)
2159 .unwrap();
2160 let mut ext: sp_io::TestExternalities = storage.into();
2161 ext.execute_with(|| {
2162 System::set_block_number(1);
2163 frame_system::BlockHash::<Runtime>::insert(0u32, sp_core::H256::default());
2164 });
2165
2166 ext.execute_with(|| {
2167 let call = remark_call();
2168
2169 let ordinary_extra = signed_extra(0);
2171 let ordinary_payload = signing_payload(&call, &ordinary_extra);
2172 let ordinary_signature = Signature::Sr25519(ordinary_pair.sign(&ordinary_payload));
2173 let ordinary_extrinsic = UncheckedExtrinsic::new_signed(
2174 call.clone(),
2175 MultiAddress::Id(AccountId::new(ordinary_pair.public().to_raw())),
2176 ordinary_signature,
2177 ordinary_extra,
2178 );
2179 let result = Executive::validate_transaction(
2180 TransactionSource::External,
2181 ordinary_extrinsic,
2182 Default::default(),
2183 );
2184 assert!(
2185 result.is_ok(),
2186 "ordinary signed extrinsic rejected: {result:?}"
2187 );
2188
2189 let mut sender = [0u8; 32];
2193 sender[0] = 0x01;
2194 let mut forged = [0u8; 64];
2195 forged[0] = 0x01;
2196 let forged_signature =
2197 Signature::Ed25519(sp_core::ed25519::Signature::from_raw(forged));
2198 let forged_extrinsic = UncheckedExtrinsic::new_signed(
2199 call,
2200 MultiAddress::Id(AccountId::new(sender)),
2201 forged_signature,
2202 signed_extra(0),
2203 );
2204 let result = Executive::validate_transaction(
2205 TransactionSource::External,
2206 forged_extrinsic,
2207 Default::default(),
2208 );
2209 assert_eq!(result, Err(InvalidTransaction::BadSigner.into()));
2210 });
2211 }
2212}