auto_id_domain_runtime/
lib.rs

1#![feature(variant_count)]
2#![cfg_attr(not(feature = "std"), no_std)]
3// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
4#![recursion_limit = "256"]
5
6// Make the WASM binary available.
7#[cfg(feature = "std")]
8include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
9
10extern crate alloc;
11
12use alloc::borrow::Cow;
13#[cfg(not(feature = "std"))]
14use alloc::format;
15use core::mem;
16use domain_runtime_primitives::opaque::Header;
17pub use domain_runtime_primitives::{
18    block_weights, maximum_block_length, opaque, Balance, BlockNumber, Hash, Nonce,
19    EXISTENTIAL_DEPOSIT, MAX_OUTGOING_MESSAGES,
20};
21use domain_runtime_primitives::{
22    AccountId, Address, CheckExtrinsicsValidityError, DecodeExtrinsicError, HoldIdentifier,
23    Signature, TargetBlockFullness, ERR_BALANCE_OVERFLOW, SLOT_DURATION,
24};
25use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo};
26use frame_support::genesis_builder_helper::{build_state, get_preset};
27use frame_support::inherent::ProvideInherent;
28use frame_support::pallet_prelude::TypeInfo;
29use frame_support::traits::fungible::Credit;
30use frame_support::traits::{
31    ConstU16, ConstU32, ConstU64, Everything, Imbalance, OnUnbalanced, VariantCount,
32};
33use frame_support::weights::constants::ParityDbWeight;
34use frame_support::weights::{ConstantMultiplier, Weight};
35use frame_support::{construct_runtime, parameter_types};
36use frame_system::limits::{BlockLength, BlockWeights};
37use pallet_block_fees::fees::OnChargeDomainTransaction;
38use pallet_transporter::EndpointHandler;
39use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen};
40use sp_api::impl_runtime_apis;
41use sp_core::crypto::KeyTypeId;
42use sp_core::{Get, OpaqueMetadata};
43use sp_domains::{ChannelId, DomainAllowlistUpdates, DomainId, Transfers};
44use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
45use sp_messenger::messages::{
46    BlockMessagesWithStorageKey, ChainId, CrossDomainMessage, FeeModel, MessageId, MessageKey,
47};
48use sp_messenger::{ChannelNonce, XdmId};
49use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest};
50use sp_mmr_primitives::EncodableOpaqueLeaf;
51use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble};
52use sp_runtime::traits::{
53    AccountIdLookup, BlakeTwo256, Block as BlockT, Checkable, DispatchTransaction, Keccak256,
54    NumberFor, One, TransactionExtension, ValidateUnsigned, Zero,
55};
56use sp_runtime::transaction_validity::{
57    InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
58};
59use sp_runtime::type_with_default::TypeWithDefault;
60use sp_runtime::{generic, impl_opaque_keys, ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode};
61pub use sp_runtime::{MultiAddress, Perbill, Permill};
62use sp_std::collections::btree_set::BTreeSet;
63use sp_std::marker::PhantomData;
64use sp_std::prelude::*;
65use sp_subspace_mmr::domain_mmr_runtime_interface::{
66    is_consensus_block_finalized, verify_mmr_proof,
67};
68use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
69use sp_version::RuntimeVersion;
70use static_assertions::const_assert;
71use subspace_runtime_primitives::utility::DefaultNonceProvider;
72use subspace_runtime_primitives::{
73    BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, Hash as ConsensusBlockHash,
74    Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler,
75    MAX_CALL_RECURSION_DEPTH, SHANNON, SSC,
76};
77
78/// Block type as expected by this runtime.
79pub type Block = generic::Block<Header, UncheckedExtrinsic>;
80
81/// A Block signed with a Justification
82pub type SignedBlock = generic::SignedBlock<Block>;
83
84/// BlockId type as expected by this runtime.
85pub type BlockId = generic::BlockId<Block>;
86
87/// The SignedExtension to the basic transaction logic.
88pub type SignedExtra = (
89    frame_system::CheckNonZeroSender<Runtime>,
90    frame_system::CheckSpecVersion<Runtime>,
91    frame_system::CheckTxVersion<Runtime>,
92    frame_system::CheckGenesis<Runtime>,
93    frame_system::CheckMortality<Runtime>,
94    frame_system::CheckNonce<Runtime>,
95    domain_check_weight::CheckWeight<Runtime>,
96    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
97    pallet_messenger::extensions::MessengerExtension<Runtime>,
98);
99
100/// The Custom SignedExtension used for pre_dispatch checks for bundle extrinsic verification
101pub type CustomSignedExtra = (
102    frame_system::CheckNonZeroSender<Runtime>,
103    frame_system::CheckSpecVersion<Runtime>,
104    frame_system::CheckTxVersion<Runtime>,
105    frame_system::CheckGenesis<Runtime>,
106    frame_system::CheckMortality<Runtime>,
107    frame_system::CheckNonce<Runtime>,
108    domain_check_weight::CheckWeight<Runtime>,
109    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
110    pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
111);
112
113/// Unchecked extrinsic type as expected by this runtime.
114pub type UncheckedExtrinsic =
115    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
116
117/// Extrinsic type that has already been checked.
118pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
119
120/// Executive: handles dispatch to the various modules.
121pub type Executive = domain_pallet_executive::Executive<
122    Runtime,
123    frame_system::ChainContext<Runtime>,
124    Runtime,
125    AllPalletsWithSystem,
126>;
127
128impl_opaque_keys! {
129    pub struct SessionKeys {
130        /// Primarily used for adding the operator signing key into the Keystore.
131        pub operator: sp_domains::OperatorKey,
132    }
133}
134
135#[sp_version::runtime_version]
136pub const VERSION: RuntimeVersion = RuntimeVersion {
137    spec_name: Cow::Borrowed("subspace-auto-id-domain"),
138    impl_name: Cow::Borrowed("subspace-auto-id-domain"),
139    authoring_version: 0,
140    // The spec version can be different on Taurus and Mainnet
141    spec_version: 0,
142    impl_version: 0,
143    apis: RUNTIME_API_VERSIONS,
144    transaction_version: 0,
145    system_version: 2,
146};
147
148parameter_types! {
149    pub const Version: RuntimeVersion = VERSION;
150    pub const BlockHashCount: BlockNumber = 2400;
151    pub RuntimeBlockLength: BlockLength = maximum_block_length();
152    pub RuntimeBlockWeights: BlockWeights = block_weights();
153}
154
155impl frame_system::Config for Runtime {
156    /// The identifier used to distinguish between accounts.
157    type AccountId = AccountId;
158    /// The aggregated dispatch type that is available for extrinsics.
159    type RuntimeCall = RuntimeCall;
160    /// The aggregated `RuntimeTask` type.
161    type RuntimeTask = RuntimeTask;
162    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
163    type Lookup = AccountIdLookup<AccountId, ()>;
164    /// The type for storing how many extrinsics an account has signed.
165    type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
166    /// The type for hashing blocks and tries.
167    type Hash = Hash;
168    /// The hashing algorithm used.
169    type Hashing = BlakeTwo256;
170    /// The block type.
171    type Block = Block;
172    /// The ubiquitous event type.
173    type RuntimeEvent = RuntimeEvent;
174    /// The ubiquitous origin type.
175    type RuntimeOrigin = RuntimeOrigin;
176    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
177    type BlockHashCount = BlockHashCount;
178    /// Runtime version.
179    type Version = Version;
180    /// Converts a module to an index of this module in the runtime.
181    type PalletInfo = PalletInfo;
182    /// The data to be stored in an account.
183    type AccountData = pallet_balances::AccountData<Balance>;
184    /// What to do if a new account is created.
185    type OnNewAccount = ();
186    /// What to do if an account is fully reaped from the system.
187    type OnKilledAccount = ();
188    /// The weight of database operations that the runtime can invoke.
189    type DbWeight = ParityDbWeight;
190    /// The basic call filter to use in dispatchable.
191    type BaseCallFilter = Everything;
192    /// Weight information for the extrinsics of this pallet.
193    type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
194    /// Block & extrinsics weights: base values and limits.
195    type BlockWeights = RuntimeBlockWeights;
196    /// The maximum length of a block (in bytes).
197    type BlockLength = RuntimeBlockLength;
198    type SS58Prefix = ConstU16<6094>;
199    /// The action to take on a Runtime Upgrade
200    type OnSetCode = ();
201    type SingleBlockMigrations = ();
202    type MultiBlockMigrator = ();
203    type PreInherents = ();
204    type PostInherents = ();
205    type PostTransactions = ();
206    type MaxConsumers = ConstU32<16>;
207    type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
208    type EventSegmentSize = DomainEventSegmentSize;
209}
210
211impl pallet_timestamp::Config for Runtime {
212    /// A timestamp: milliseconds since the unix epoch.
213    type Moment = Moment;
214    type OnTimestampSet = ();
215    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
216    type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
217}
218
219parameter_types! {
220    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
221    pub const MaxLocks: u32 = 50;
222    pub const MaxReserves: u32 = 50;
223}
224
225/// `DustRemovalHandler` used to collect all the SSC dust left when the account is reaped.
226pub struct DustRemovalHandler;
227
228impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
229    fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
230        BlockFees::note_burned_balance(dusted_amount.peek());
231    }
232}
233
234impl pallet_balances::Config for Runtime {
235    type RuntimeFreezeReason = RuntimeFreezeReason;
236    type MaxLocks = MaxLocks;
237    /// The type for recording an account's balance.
238    type Balance = Balance;
239    /// The ubiquitous event type.
240    type RuntimeEvent = RuntimeEvent;
241    type DustRemoval = DustRemovalHandler;
242    type ExistentialDeposit = ExistentialDeposit;
243    type AccountStore = System;
244    type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
245    type MaxReserves = MaxReserves;
246    type ReserveIdentifier = [u8; 8];
247    type FreezeIdentifier = ();
248    type MaxFreezes = ();
249    type RuntimeHoldReason = HoldIdentifierWrapper;
250    type DoneSlashHandler = ();
251}
252
253parameter_types! {
254    pub const OperationalFeeMultiplier: u8 = 5;
255    pub const DomainChainByteFee: Balance = 1;
256    pub TransactionWeightFee: Balance = 100_000 * SHANNON;
257}
258
259impl pallet_block_fees::Config for Runtime {
260    type Balance = Balance;
261    type DomainChainByteFee = DomainChainByteFee;
262}
263
264pub struct FinalDomainTransactionByteFee;
265
266impl Get<Balance> for FinalDomainTransactionByteFee {
267    fn get() -> Balance {
268        BlockFees::final_domain_transaction_byte_fee()
269    }
270}
271
272impl pallet_transaction_payment::Config for Runtime {
273    type RuntimeEvent = RuntimeEvent;
274    type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
275    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
276    type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
277    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
278    type OperationalFeeMultiplier = OperationalFeeMultiplier;
279    type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
280}
281
282impl pallet_auto_id::Config for Runtime {
283    type RuntimeEvent = RuntimeEvent;
284    type Time = Timestamp;
285    type Weights = pallet_auto_id::weights::SubstrateWeight<Self>;
286}
287
288pub struct ExtrinsicStorageFees;
289
290impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
291    fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
292        let dispatch_info = xt.get_dispatch_info();
293        let lookup = frame_system::ChainContext::<Runtime>::default();
294        let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
295        (maybe_signer, dispatch_info)
296    }
297
298    fn on_storage_fees_charged(
299        charged_fees: Balance,
300        tx_size: u32,
301    ) -> Result<(), TransactionValidityError> {
302        let consensus_storage_fee = BlockFees::consensus_chain_byte_fee()
303            .checked_mul(Balance::from(tx_size))
304            .ok_or(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))?;
305
306        let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
307        {
308            (charged_fees, Zero::zero())
309        } else {
310            (consensus_storage_fee, charged_fees - consensus_storage_fee)
311        };
312
313        BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
314        BlockFees::note_domain_execution_fee(paid_domain_fee);
315        Ok(())
316    }
317}
318
319impl domain_pallet_executive::Config for Runtime {
320    type RuntimeEvent = RuntimeEvent;
321    type WeightInfo = domain_pallet_executive::weights::SubstrateWeight<Runtime>;
322    type Currency = Balances;
323    type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
324    type ExtrinsicStorageFees = ExtrinsicStorageFees;
325}
326
327parameter_types! {
328    pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
329}
330
331pub struct OnXDMRewards;
332
333impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
334    fn on_xdm_rewards(rewards: Balance) {
335        BlockFees::note_domain_execution_fee(rewards)
336    }
337    fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
338        // note the chain rewards
339        BlockFees::note_chain_rewards(chain_id, fees);
340    }
341}
342
343type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
344
345pub struct MmrProofVerifier;
346
347impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
348    fn verify_proof_and_extract_leaf(
349        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
350    ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
351        let ConsensusChainMmrLeafProof {
352            consensus_block_number,
353            opaque_mmr_leaf: opaque_leaf,
354            proof,
355            ..
356        } = mmr_leaf_proof;
357
358        if !is_consensus_block_finalized(consensus_block_number) {
359            return None;
360        }
361
362        let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
363            opaque_leaf.into_opaque_leaf().try_decode()?;
364
365        verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
366            .then_some(leaf)
367    }
368}
369
370pub struct StorageKeys;
371
372impl sp_messenger::StorageKeys for StorageKeys {
373    fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
374        get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
375    }
376
377    fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
378        get_storage_key(StorageKeyRequest::OutboxStorageKey {
379            chain_id,
380            message_key,
381        })
382    }
383
384    fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
385        get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
386            chain_id,
387            message_key,
388        })
389    }
390}
391
392/// Hold identifier for balances for this runtime.
393#[derive(
394    PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
395)]
396pub struct HoldIdentifierWrapper(HoldIdentifier);
397
398impl VariantCount for HoldIdentifierWrapper {
399    const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
400}
401
402impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
403    fn messenger_channel() -> Self {
404        Self(HoldIdentifier::MessengerChannel)
405    }
406}
407
408parameter_types! {
409    pub const ChannelReserveFee: Balance = 100 * SSC;
410    pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
411    // TODO update the fee model
412    pub const ChannelFeeModel: FeeModel<Balance> = FeeModel{relay_fee: SSC};
413    pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
414    pub const MessageVersion: pallet_messenger::MessageVersion = pallet_messenger::MessageVersion::V0;
415}
416
417// ensure the max outgoing messages is not 0.
418const_assert!(MaxOutgoingMessages::get() >= 1);
419
420impl pallet_messenger::Config for Runtime {
421    type RuntimeEvent = RuntimeEvent;
422    type SelfChainId = SelfChainId;
423
424    fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
425        if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
426            Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
427        } else {
428            None
429        }
430    }
431
432    type Currency = Balances;
433    type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
434    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
435    type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
436    type FeeMultiplier = XdmFeeMultipler;
437    type OnXDMRewards = OnXDMRewards;
438    type MmrHash = MmrHash;
439    type MmrProofVerifier = MmrProofVerifier;
440    type StorageKeys = StorageKeys;
441    type DomainOwner = ();
442    type HoldIdentifier = HoldIdentifierWrapper;
443    type ChannelReserveFee = ChannelReserveFee;
444    type ChannelInitReservePortion = ChannelInitReservePortion;
445    type DomainRegistration = ();
446    type ChannelFeeModel = ChannelFeeModel;
447    type MaxOutgoingMessages = MaxOutgoingMessages;
448    type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
449    type MessageVersion = MessageVersion;
450}
451
452impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
453where
454    RuntimeCall: From<C>,
455{
456    type Extrinsic = UncheckedExtrinsic;
457    type RuntimeCall = RuntimeCall;
458}
459
460parameter_types! {
461    pub const TransporterEndpointId: EndpointId = 1;
462}
463
464impl pallet_transporter::Config for Runtime {
465    type RuntimeEvent = RuntimeEvent;
466    type SelfChainId = SelfChainId;
467    type SelfEndpointId = TransporterEndpointId;
468    type Currency = Balances;
469    type Sender = Messenger;
470    type AccountIdConverter = domain_runtime_primitives::AccountIdConverter;
471    type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
472}
473
474impl pallet_domain_id::Config for Runtime {}
475
476pub struct IntoRuntimeCall;
477
478impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
479    fn runtime_call(call: Vec<u8>) -> RuntimeCall {
480        UncheckedExtrinsic::decode(&mut call.as_slice())
481            .expect("must always be a valid extrinsic as checked by consensus chain; qed")
482            .function
483    }
484}
485
486impl pallet_domain_sudo::Config for Runtime {
487    type RuntimeEvent = RuntimeEvent;
488    type RuntimeCall = RuntimeCall;
489    type IntoRuntimeCall = IntoRuntimeCall;
490}
491
492impl pallet_utility::Config for Runtime {
493    type RuntimeEvent = RuntimeEvent;
494    type RuntimeCall = RuntimeCall;
495    type PalletsOrigin = OriginCaller;
496    type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
497}
498
499// Create the runtime by composing the FRAME pallets that were previously configured.
500//
501// NOTE: Currently domain runtime does not naturally support the pallets with inherent extrinsics.
502construct_runtime!(
503    pub struct Runtime {
504        // System support stuff.
505        System: frame_system = 0,
506        // Note: Ensure index of the timestamp matches with the index of timestamp on Consensus
507        //  so that consensus can construct encoded extrinsic that matches with Domain encoded
508        //  extrinsic.
509        Timestamp: pallet_timestamp = 1,
510        ExecutivePallet: domain_pallet_executive = 2,
511        Utility: pallet_utility = 8,
512
513        // monetary stuff
514        Balances: pallet_balances = 20,
515        TransactionPayment: pallet_transaction_payment = 21,
516
517        // AutoId
518        AutoId: pallet_auto_id = 40,
519
520        // messenger stuff
521        // Note: Indexes should match with indexes on other chains and domains
522        Messenger: pallet_messenger = 60,
523        Transporter: pallet_transporter = 61,
524
525        // domain instance stuff
526        SelfDomainId: pallet_domain_id = 90,
527        BlockFees: pallet_block_fees = 91,
528
529        // Sudo account
530        Sudo: pallet_domain_sudo = 100,
531    }
532);
533
534impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
535    fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
536        match self {
537            RuntimeCall::Messenger(call) => Some(call),
538            _ => None,
539        }
540    }
541}
542
543impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
544where
545    RuntimeCall: From<C>,
546{
547    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
548        create_unsigned_general_extrinsic(call)
549    }
550}
551
552fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
553    let extra: SignedExtra = (
554        frame_system::CheckNonZeroSender::<Runtime>::new(),
555        frame_system::CheckSpecVersion::<Runtime>::new(),
556        frame_system::CheckTxVersion::<Runtime>::new(),
557        frame_system::CheckGenesis::<Runtime>::new(),
558        frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
559        // for unsigned extrinsic, nonce check will be skipped
560        // so set a default value
561        frame_system::CheckNonce::<Runtime>::from(0u32.into()),
562        domain_check_weight::CheckWeight::<Runtime>::new(),
563        // for unsigned extrinsic, transaction fee check will be skipped
564        // so set a default value
565        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
566        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
567    );
568
569    UncheckedExtrinsic::new_transaction(call, extra)
570}
571
572fn is_xdm_mmr_proof_valid(ext: &<Block as BlockT>::Extrinsic) -> Option<bool> {
573    match &ext.function {
574        RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
575        | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
576            let ConsensusChainMmrLeafProof {
577                consensus_block_number,
578                opaque_mmr_leaf,
579                proof,
580                ..
581            } = msg.proof.consensus_mmr_proof();
582
583            if !is_consensus_block_finalized(consensus_block_number) {
584                return Some(false);
585            }
586
587            Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
588        }
589        _ => None,
590    }
591}
592
593/// Returns `true` if this is a validly encoded Sudo call.
594fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
595    UncheckedExtrinsic::decode_with_depth_limit(
596        MAX_CALL_RECURSION_DEPTH,
597        &mut encoded_ext.as_slice(),
598    )
599    .is_ok()
600}
601
602fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> <Block as BlockT>::Extrinsic {
603    let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
604        "must always be a valid extrinsic due to the check above and storage proof check; qed",
605    );
606    UncheckedExtrinsic::new_bare(
607        pallet_domain_sudo::Call::sudo {
608            call: Box::new(ext.function),
609        }
610        .into(),
611    )
612}
613
614fn extract_signer_inner<Lookup>(
615    ext: &UncheckedExtrinsic,
616    lookup: &Lookup,
617) -> Option<Result<AccountId, TransactionValidityError>>
618where
619    Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
620{
621    match &ext.preamble {
622        Preamble::Bare(_) | Preamble::General(_, _) => None,
623        Preamble::Signed(signed, _, _) => Some(lookup.lookup(signed.clone()).map_err(|e| e.into())),
624    }
625}
626
627pub fn extract_signer(
628    extrinsics: Vec<UncheckedExtrinsic>,
629) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
630    let lookup = frame_system::ChainContext::<Runtime>::default();
631
632    extrinsics
633        .into_iter()
634        .map(|extrinsic| {
635            let maybe_signer =
636                extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
637                    account_result.ok().map(|account_id| account_id.encode())
638                });
639            (maybe_signer, extrinsic)
640        })
641        .collect()
642}
643
644fn extrinsic_era(extrinsic: &<Block as BlockT>::Extrinsic) -> Option<Era> {
645    match &extrinsic.preamble {
646        Preamble::Bare(_) | Preamble::General(_, _) => None,
647        Preamble::Signed(_, _, extra) => Some(extra.4 .0),
648    }
649}
650
651#[cfg(feature = "runtime-benchmarks")]
652mod benches {
653    frame_benchmarking::define_benchmarks!(
654        [frame_benchmarking, BaselineBench::<Runtime>]
655        [frame_system, SystemBench::<Runtime>]
656        [domain_pallet_executive, ExecutivePallet]
657        [pallet_messenger, Messenger]
658        [pallet_auto_id, AutoId]
659    );
660}
661
662fn check_transaction_and_do_pre_dispatch_inner(
663    uxt: &<Block as BlockT>::Extrinsic,
664) -> Result<(), TransactionValidityError> {
665    let lookup = frame_system::ChainContext::<Runtime>::default();
666
667    let xt = uxt.clone().check(&lookup)?;
668
669    let dispatch_info = xt.get_dispatch_info();
670
671    if dispatch_info.class == DispatchClass::Mandatory {
672        return Err(InvalidTransaction::MandatoryValidation.into());
673    }
674
675    let encoded_len = uxt.encoded_size();
676
677    // We invoke `pre_dispatch` in addition to `validate_transaction`(even though the validation is almost same)
678    // as that will add the side effect of SignedExtension in the storage buffer
679    // which would help to maintain context across multiple transaction validity check against same
680    // runtime instance.
681    match xt.format {
682        ExtrinsicFormat::General(extension_version, extra) => {
683            let custom_extra: CustomSignedExtra = (
684                extra.0,
685                extra.1,
686                extra.2,
687                extra.3,
688                extra.4,
689                extra.5,
690                extra.6.clone(),
691                extra.7,
692                pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
693            );
694
695            let origin = RuntimeOrigin::none();
696            <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
697                custom_extra,
698                origin,
699                &xt.function,
700                &dispatch_info,
701                encoded_len,
702                extension_version,
703            )
704            .map(|_| ())
705        }
706        // signed transaction
707        ExtrinsicFormat::Signed(account_id, extra) => {
708            let origin = RuntimeOrigin::signed(account_id);
709            <SignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
710                extra,
711                origin,
712                &xt.function,
713                &dispatch_info,
714                encoded_len,
715                // default extension version define here -
716                // https://github.com/paritytech/polkadot-sdk/blob/master/substrate/primitives/runtime/src/generic/checked_extrinsic.rs#L37
717                0,
718            )
719            .map(|_| ())
720        }
721        // unsigned transaction
722        ExtrinsicFormat::Bare => {
723            Runtime::pre_dispatch(&xt.function).map(|_| ())?;
724            <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
725                &xt.function,
726                &dispatch_info,
727                encoded_len,
728            )
729            .map(|_| ())
730        }
731    }
732}
733
734#[cfg(feature = "runtime-benchmarks")]
735impl frame_system_benchmarking::Config for Runtime {}
736
737#[cfg(feature = "runtime-benchmarks")]
738impl frame_benchmarking::baseline::Config for Runtime {}
739
740impl_runtime_apis! {
741    impl sp_api::Core<Block> for Runtime {
742        fn version() -> RuntimeVersion {
743            VERSION
744        }
745
746        fn execute_block(block: Block) {
747            Executive::execute_block(block)
748        }
749
750        fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
751            Executive::initialize_block(header)
752        }
753    }
754
755    impl sp_api::Metadata<Block> for Runtime {
756        fn metadata() -> OpaqueMetadata {
757            OpaqueMetadata::new(Runtime::metadata().into())
758        }
759
760        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
761            Runtime::metadata_at_version(version)
762        }
763
764        fn metadata_versions() -> Vec<u32> {
765            Runtime::metadata_versions()
766        }
767    }
768
769    impl sp_block_builder::BlockBuilder<Block> for Runtime {
770        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
771            Executive::apply_extrinsic(extrinsic)
772        }
773
774        fn finalize_block() -> <Block as BlockT>::Header {
775            Executive::finalize_block()
776        }
777
778        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
779            data.create_extrinsics()
780        }
781
782        fn check_inherents(
783            block: Block,
784            data: sp_inherents::InherentData,
785        ) -> sp_inherents::CheckInherentsResult {
786            data.check_extrinsics(&block)
787        }
788    }
789
790    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
791        fn validate_transaction(
792            source: TransactionSource,
793            tx: <Block as BlockT>::Extrinsic,
794            block_hash: <Block as BlockT>::Hash,
795        ) -> TransactionValidity {
796            Executive::validate_transaction(source, tx, block_hash)
797        }
798    }
799
800    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
801        fn offchain_worker(header: &<Block as BlockT>::Header) {
802            Executive::offchain_worker(header)
803        }
804    }
805
806    impl sp_session::SessionKeys<Block> for Runtime {
807        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
808            SessionKeys::generate(seed)
809        }
810
811        fn decode_session_keys(
812            encoded: Vec<u8>,
813        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
814            SessionKeys::decode_into_raw_public_keys(&encoded)
815        }
816    }
817
818    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
819        fn account_nonce(account: AccountId) -> Nonce {
820            *System::account_nonce(account)
821        }
822    }
823
824    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
825        fn query_info(
826            uxt: <Block as BlockT>::Extrinsic,
827            len: u32,
828        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
829            TransactionPayment::query_info(uxt, len)
830        }
831        fn query_fee_details(
832            uxt: <Block as BlockT>::Extrinsic,
833            len: u32,
834        ) -> pallet_transaction_payment::FeeDetails<Balance> {
835            TransactionPayment::query_fee_details(uxt, len)
836        }
837        fn query_weight_to_fee(weight: Weight) -> Balance {
838            TransactionPayment::weight_to_fee(weight)
839        }
840        fn query_length_to_fee(length: u32) -> Balance {
841            TransactionPayment::length_to_fee(length)
842        }
843    }
844
845    impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
846        fn extract_signer(
847            extrinsics: Vec<<Block as BlockT>::Extrinsic>,
848        ) -> Vec<(Option<opaque::AccountId>, <Block as BlockT>::Extrinsic)> {
849            extract_signer(extrinsics)
850        }
851
852        fn is_within_tx_range(
853            extrinsic: &<Block as BlockT>::Extrinsic,
854            bundle_vrf_hash: &subspace_core_primitives::U256,
855            tx_range: &subspace_core_primitives::U256
856        ) -> bool {
857            use subspace_core_primitives::U256;
858            use subspace_core_primitives::hashes::blake3_hash;
859
860            let lookup = frame_system::ChainContext::<Runtime>::default();
861            if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
862                    account_result.ok().map(|account_id| account_id.encode())
863                }) {
864                // Check if the signer Id hash is within the tx range
865                let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
866                sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
867            } else {
868                // Unsigned transactions are always in the range.
869                true
870            }
871        }
872
873        fn initialize_block_with_post_state_root(header: &<Block as BlockT>::Header) -> Vec<u8> {
874            Executive::initialize_block(header);
875            Executive::storage_root()
876        }
877
878        fn apply_extrinsic_with_post_state_root(extrinsic: <Block as BlockT>::Extrinsic) -> Vec<u8> {
879            let _ = Executive::apply_extrinsic(extrinsic);
880            Executive::storage_root()
881        }
882
883        fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
884            UncheckedExtrinsic::new_bare(
885                domain_pallet_executive::Call::set_code {
886                    code
887                }.into()
888            ).encode()
889        }
890
891        fn construct_timestamp_extrinsic(moment: Moment) -> <Block as BlockT>::Extrinsic {
892            UncheckedExtrinsic::new_bare(
893                pallet_timestamp::Call::set{ now: moment }.into()
894            )
895        }
896
897        fn is_inherent_extrinsic(extrinsic: &<Block as BlockT>::Extrinsic) -> bool {
898            match &extrinsic.function {
899                RuntimeCall::Timestamp(call) => Timestamp::is_inherent(call),
900                RuntimeCall::ExecutivePallet(call) => ExecutivePallet::is_inherent(call),
901                RuntimeCall::Messenger(call) => Messenger::is_inherent(call),
902                RuntimeCall::Sudo(call) => Sudo::is_inherent(call),
903                _ => false,
904            }
905        }
906
907        fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<<Block as BlockT>::Extrinsic>, block_number: BlockNumber,
908            block_hash: <Block as BlockT>::Hash) -> Result<(), CheckExtrinsicsValidityError> {
909            // Initializing block related storage required for validation
910            System::initialize(
911                &(block_number + BlockNumber::one()),
912                &block_hash,
913                &Default::default(),
914            );
915
916            for (extrinsic_index, uxt) in uxts.iter().enumerate() {
917                check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
918                    CheckExtrinsicsValidityError {
919                        extrinsic_index: extrinsic_index as u32,
920                        transaction_validity_error: e
921                    }
922                })?;
923            }
924
925            Ok(())
926        }
927
928        fn decode_extrinsic(
929            opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
930        ) -> Result<<Block as BlockT>::Extrinsic, DecodeExtrinsicError> {
931            let encoded = opaque_extrinsic.encode();
932
933            UncheckedExtrinsic::decode_with_depth_limit(
934                MAX_CALL_RECURSION_DEPTH,
935                &mut encoded.as_slice(),
936            ).map_err(|err| DecodeExtrinsicError(format!("{}", err)))
937        }
938
939        fn extrinsic_era(
940          extrinsic: &<Block as BlockT>::Extrinsic
941        ) -> Option<Era> {
942            extrinsic_era(extrinsic)
943        }
944
945        fn extrinsic_weight(ext: &<Block as BlockT>::Extrinsic) -> Weight {
946            let len = ext.encoded_size() as u64;
947            let info = ext.get_dispatch_info();
948            info.call_weight.saturating_add(info.extension_weight)
949                .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
950                .saturating_add(Weight::from_parts(0, len))
951        }
952
953        fn block_fees() -> sp_domains::BlockFees<Balance> {
954            BlockFees::collected_block_fees()
955        }
956
957        fn block_digest() -> Digest {
958            System::digest()
959        }
960
961        fn block_weight() -> Weight {
962            System::block_weight().total()
963        }
964
965        fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> <Block as BlockT>::Extrinsic {
966            UncheckedExtrinsic::new_bare(
967                pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
968            )
969        }
970
971        fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> <Block as BlockT>::Extrinsic {
972             UncheckedExtrinsic::new_bare(
973                pallet_messenger::Call::update_domain_allowlist{ updates }.into()
974            )
975        }
976
977        fn transfers() -> Transfers<Balance> {
978            Transporter::chain_transfers()
979        }
980
981        fn transfers_storage_key() -> Vec<u8> {
982            Transporter::transfers_storage_key()
983        }
984
985        fn block_fees_storage_key() -> Vec<u8> {
986            BlockFees::block_fees_storage_key()
987        }
988    }
989
990    impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
991        fn is_xdm_mmr_proof_valid(
992            extrinsic: &<Block as BlockT>::Extrinsic,
993        ) -> Option<bool> {
994            is_xdm_mmr_proof_valid(extrinsic)
995        }
996
997        fn extract_xdm_mmr_proof(ext: &<Block as BlockT>::Extrinsic) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
998            match &ext.function {
999                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1000                | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1001                    Some(msg.proof.consensus_mmr_proof())
1002                }
1003                _ => None,
1004            }
1005        }
1006
1007        fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1008            // invalid call from Domain runtime
1009            vec![]
1010        }
1011
1012        fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1013            Messenger::outbox_storage_key(message_key)
1014        }
1015
1016        fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1017            Messenger::inbox_response_storage_key(message_key)
1018        }
1019
1020        fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1021            // not valid call on domains
1022            None
1023        }
1024
1025        fn xdm_id(ext: &<Block as BlockT>::Extrinsic) -> Option<XdmId> {
1026            match &ext.function {
1027                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1028                    Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1029                }
1030                RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1031                    Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1032                }
1033                _ => None,
1034            }
1035        }
1036
1037        fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1038            Messenger::channel_nonce(chain_id, channel_id)
1039        }
1040    }
1041
1042    impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1043        fn block_messages() -> BlockMessagesWithStorageKey {
1044            Messenger::get_block_messages()
1045        }
1046
1047        fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, <Block as BlockT>::Hash, <Block as BlockT>::Hash>) -> Option<<Block as BlockT>::Extrinsic> {
1048            Messenger::outbox_message_unsigned(msg)
1049        }
1050
1051        fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, <Block as BlockT>::Hash, <Block as BlockT>::Hash>) -> Option<<Block as BlockT>::Extrinsic> {
1052            Messenger::inbox_response_message_unsigned(msg)
1053        }
1054
1055        fn should_relay_outbox_message(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1056            Messenger::should_relay_outbox_message(dst_chain_id, msg_id)
1057        }
1058
1059        fn should_relay_inbox_message_response(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1060            Messenger::should_relay_inbox_message_response(dst_chain_id, msg_id)
1061        }
1062
1063        fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1064            Messenger::updated_channels()
1065        }
1066
1067        fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1068            Messenger::channel_storage_key(chain_id, channel_id)
1069        }
1070
1071        fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1072            Messenger::open_channels()
1073        }
1074    }
1075
1076    impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1077        fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1078            is_valid_sudo_call(extrinsic)
1079        }
1080
1081        fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> <Block as BlockT>::Extrinsic {
1082            construct_sudo_call_extrinsic(inner)
1083        }
1084    }
1085
1086    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1087        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1088            build_state::<RuntimeGenesisConfig>(config)
1089        }
1090
1091        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1092            get_preset::<RuntimeGenesisConfig>(id, |_| None)
1093        }
1094
1095        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1096            vec![]
1097        }
1098    }
1099
1100    #[cfg(feature = "runtime-benchmarks")]
1101    impl frame_benchmarking::Benchmark<Block> for Runtime {
1102        fn benchmark_metadata(extra: bool) -> (
1103            Vec<frame_benchmarking::BenchmarkList>,
1104            Vec<frame_support::traits::StorageInfo>,
1105        ) {
1106            use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1107            use frame_support::traits::StorageInfoTrait;
1108            use frame_system_benchmarking::Pallet as SystemBench;
1109            use baseline::Pallet as BaselineBench;
1110
1111            let mut list = Vec::<BenchmarkList>::new();
1112
1113            list_benchmarks!(list, extra);
1114
1115            let storage_info = AllPalletsWithSystem::storage_info();
1116
1117            (list, storage_info)
1118        }
1119
1120        fn dispatch_benchmark(
1121            config: frame_benchmarking::BenchmarkConfig
1122        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1123            use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1124            use sp_storage::TrackedStorageKey;
1125            use frame_system_benchmarking::Pallet as SystemBench;
1126            use frame_support::traits::WhitelistedStorageKeys;
1127            use baseline::Pallet as BaselineBench;
1128
1129            let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1130
1131            let mut batches = Vec::<BenchmarkBatch>::new();
1132            let params = (&config, &whitelist);
1133
1134            add_benchmarks!(params, batches);
1135
1136            if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1137            Ok(batches)
1138        }
1139    }
1140}
1141
1142#[cfg(test)]
1143mod tests {
1144    use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1145    use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1146
1147    #[test]
1148    fn multiplier_can_grow_from_zero() {
1149        FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1150    }
1151}