Skip to main content

subspace_runtime/
lib.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2#![feature(const_trait_impl, variant_count)]
3// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
4#![recursion_limit = "256"]
5// TODO: remove when upstream issue is fixed
6#![allow(
7    non_camel_case_types,
8    reason = "https://github.com/rust-lang/rust-analyzer/issues/16514"
9)]
10
11mod domains;
12mod fees;
13mod object_mapping;
14mod weights;
15
16extern crate alloc;
17
18// Make the WASM binary available.
19#[cfg(feature = "std")]
20include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
21
22use crate::fees::{OnChargeTransaction, TransactionByteFee};
23use crate::object_mapping::extract_block_object_mapping;
24use alloc::borrow::Cow;
25use core::mem;
26use core::num::NonZeroU64;
27use domain_runtime_primitives::opaque::Header as DomainHeader;
28use domain_runtime_primitives::{
29    AccountIdConverter, BlockNumber as DomainNumber, EthereumAccountId, Hash as DomainHash,
30    MAX_OUTGOING_MESSAGES, maximum_domain_block_weight,
31};
32use frame_support::genesis_builder_helper::{build_state, get_preset};
33use frame_support::inherent::ProvideInherent;
34use frame_support::traits::fungible::HoldConsideration;
35use frame_support::traits::{
36    ConstU8, ConstU16, ConstU32, ConstU64, Currency, EitherOfDiverse, EqualPrivilegeOnly,
37    Everything, Get, LinearStoragePrice, OnUnbalanced, VariantCount,
38};
39use frame_support::weights::constants::ParityDbWeight;
40use frame_support::weights::{ConstantMultiplier, Weight};
41use frame_support::{PalletId, construct_runtime, parameter_types};
42use frame_system::EnsureRoot;
43use frame_system::limits::{BlockLength, BlockWeights};
44use frame_system::pallet_prelude::RuntimeCallFor;
45use pallet_collective::{EnsureMember, EnsureProportionAtLeast};
46pub use pallet_rewards::RewardPoint;
47pub use pallet_subspace::{AllowAuthoringBy, EnableRewardsAt};
48use pallet_transporter::EndpointHandler;
49use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
50use scale_info::TypeInfo;
51use sp_api::impl_runtime_apis;
52use sp_consensus_slots::{Slot, SlotDuration};
53use sp_consensus_subspace::{ChainConstants, PotParameters, SignedVote, SolutionRanges, Vote};
54use sp_core::crypto::KeyTypeId;
55use sp_core::{ConstBool, H256, OpaqueMetadata};
56use sp_domains::bundle::BundleVersion;
57use sp_domains::bundle_producer_election::BundleProducerElectionParams;
58use sp_domains::execution_receipt::{
59    ExecutionReceiptFor, ExecutionReceiptVersion, SealedSingletonReceipt,
60};
61use sp_domains::{
62    BundleAndExecutionReceiptVersion, ChannelId, DomainAllowlistUpdates, DomainId,
63    DomainInstanceData, EpochIndex, INITIAL_DOMAIN_TX_RANGE, OperatorId, OperatorPublicKey,
64    PermissionedActionAllowedBy,
65};
66use sp_domains_fraud_proof::fraud_proof::FraudProof;
67use sp_domains_fraud_proof::storage_proof::{
68    FraudProofStorageKeyProvider, FraudProofStorageKeyRequest,
69};
70use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
71use sp_messenger::messages::{
72    BlockMessagesQuery, ChainId, ChannelStateWithNonce, CrossDomainMessage, MessageId, MessageKey,
73    MessagesWithStorageKey, Nonce as XdmNonce,
74};
75use sp_messenger::{ChannelNonce, XdmId};
76use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key};
77use sp_mmr_primitives::EncodableOpaqueLeaf;
78use sp_runtime::traits::{
79    AccountIdConversion, AccountIdLookup, BlakeTwo256, ConstU128, Keccak256, NumberFor,
80};
81use sp_runtime::transaction_validity::{TransactionSource, TransactionValidity};
82use sp_runtime::type_with_default::TypeWithDefault;
83use sp_runtime::{AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill, generic};
84use sp_std::collections::btree_map::BTreeMap;
85use sp_std::collections::btree_set::BTreeSet;
86use sp_std::marker::PhantomData;
87use sp_std::prelude::*;
88use sp_subspace_mmr::ConsensusChainMmrLeafProof;
89use sp_subspace_mmr::subspace_mmr_runtime_interface::consensus_block_hash;
90use sp_version::RuntimeVersion;
91use static_assertions::const_assert;
92use subspace_core_primitives::objects::BlockObjectMapping;
93use subspace_core_primitives::pieces::Piece;
94use subspace_core_primitives::segments::{
95    HistorySize, SegmentCommitment, SegmentHeader, SegmentIndex,
96};
97use subspace_core_primitives::solutions::{
98    SolutionRange, pieces_to_solution_range, solution_range_to_pieces,
99};
100use subspace_core_primitives::{PublicKey, Randomness, SlotNumber, U256};
101pub use subspace_runtime_primitives::extension::{
102    BalanceTransferCheckExtension, SmallOrderEd25519CheckExtension,
103};
104use subspace_runtime_primitives::extension::{BalanceTransferChecks, MaybeBalancesCall};
105use subspace_runtime_primitives::utility::{
106    DefaultNonceProvider, MaybeMultisigCall, MaybeNestedCall, MaybeUtilityCall,
107};
108use subspace_runtime_primitives::{
109    AI3, AccountId, BLOCK_WEIGHT_FOR_2_SEC, Balance, BlockHashFor, BlockNumber,
110    ConsensusEventSegmentSize, ExtrinsicFor, FindBlockRewardAddress, Hash, HeaderFor,
111    HoldIdentifier, MAX_BLOCK_LENGTH, MIN_REPLICATION_FACTOR, Moment, NORMAL_DISPATCH_RATIO, Nonce,
112    SHANNON, SLOT_PROBABILITY, Signature, SlowAdjustingFeeUpdate, TargetBlockFullness,
113    XdmAdjustedWeightToFee, XdmFeeMultipler, maximum_normal_block_length,
114};
115
116sp_runtime::impl_opaque_keys! {
117    pub struct SessionKeys {
118    }
119}
120
121/// How many pieces one sector is supposed to contain (max)
122const MAX_PIECES_IN_SECTOR: u16 = 1000;
123
124// To learn more about runtime versioning and what each of the following value means:
125//   https://paritytech.github.io/polkadot-sdk/master/sp_version/struct.RuntimeVersion.html
126#[sp_version::runtime_version]
127pub const VERSION: RuntimeVersion = RuntimeVersion {
128    spec_name: Cow::Borrowed("subspace"),
129    impl_name: Cow::Borrowed("subspace"),
130    authoring_version: 0,
131    spec_version: 11,
132    impl_version: 0,
133    apis: RUNTIME_API_VERSIONS,
134    transaction_version: 1,
135    system_version: 2,
136};
137
138// TODO: Many of below constants should probably be updatable but currently they are not
139
140// NOTE: Currently it is not possible to change the slot duration after the chain has started.
141//       Attempting to do so will brick block production.
142const SLOT_DURATION: u64 = 1000;
143
144/// Number of slots between slot arrival and when corresponding block can be produced.
145const BLOCK_AUTHORING_DELAY: SlotNumber = 4;
146
147/// Interval, in blocks, between blockchain entropy injection into proof of time chain.
148const POT_ENTROPY_INJECTION_INTERVAL: BlockNumber = 50;
149
150/// Interval, in entropy injection intervals, where to take entropy for injection from.
151const POT_ENTROPY_INJECTION_LOOKBACK_DEPTH: u8 = 2;
152
153/// Delay after block, in slots, when entropy injection takes effect.
154const POT_ENTROPY_INJECTION_DELAY: SlotNumber = 15;
155
156// Entropy injection interval must be bigger than injection delay or else we may end up in a
157// situation where we'll need to do more than one injection at the same slot
158const_assert!(POT_ENTROPY_INJECTION_INTERVAL as u64 > POT_ENTROPY_INJECTION_DELAY);
159// Entropy injection delay must be bigger than block authoring delay or else we may include
160// invalid future proofs in parent block, +1 ensures we do not have unnecessary reorgs that will
161// inevitably happen otherwise
162const_assert!(POT_ENTROPY_INJECTION_DELAY > BLOCK_AUTHORING_DELAY + 1);
163
164/// Era duration in blocks.
165const ERA_DURATION_IN_BLOCKS: BlockNumber = 2016;
166
167/// Tx range is adjusted every DOMAIN_TX_RANGE_ADJUSTMENT_INTERVAL blocks.
168const TX_RANGE_ADJUSTMENT_INTERVAL_BLOCKS: u64 = 100;
169
170// We assume initial plot size starts with a single sector.
171const INITIAL_SOLUTION_RANGE: SolutionRange =
172    pieces_to_solution_range(MAX_PIECES_IN_SECTOR as u64, SLOT_PROBABILITY);
173
174/// Number of votes expected per block.
175///
176/// This impacts solution range for votes in consensus.
177const EXPECTED_VOTES_PER_BLOCK: u32 = 9;
178
179/// Number of latest archived segments that are considered "recent history".
180const RECENT_SEGMENTS: HistorySize = HistorySize::new(NonZeroU64::new(5).expect("Not zero; qed"));
181/// Fraction of pieces from the "recent history" (`recent_segments`) in each sector.
182const RECENT_HISTORY_FRACTION: (HistorySize, HistorySize) = (
183    HistorySize::new(NonZeroU64::new(1).expect("Not zero; qed")),
184    HistorySize::new(NonZeroU64::new(10).expect("Not zero; qed")),
185);
186/// Minimum lifetime of a plotted sector, measured in archived segment.
187const MIN_SECTOR_LIFETIME: HistorySize =
188    HistorySize::new(NonZeroU64::new(4).expect("Not zero; qed"));
189
190parameter_types! {
191    pub const Version: RuntimeVersion = VERSION;
192    pub const BlockHashCount: BlockNumber = 250;
193    /// We allow for 2 seconds of compute with a 6 second average block time.
194    pub SubspaceBlockWeights: BlockWeights = BlockWeights::with_sensible_defaults(BLOCK_WEIGHT_FOR_2_SEC, NORMAL_DISPATCH_RATIO);
195    /// We allow for 3.75 MiB for `Normal` extrinsic with 5 MiB maximum block length.
196    pub SubspaceBlockLength: BlockLength = maximum_normal_block_length();
197}
198
199pub type SS58Prefix = ConstU16<6094>;
200
201// Configure FRAME pallets to include in runtime.
202
203impl frame_system::Config for Runtime {
204    type RuntimeEvent = RuntimeEvent;
205    /// The basic call filter to use in dispatchable.
206    ///
207    /// `Everything` is used here as we use the signed extension
208    /// `DisablePallets` as the actual call filter.
209    type BaseCallFilter = Everything;
210    /// Block & extrinsics weights: base values and limits.
211    type BlockWeights = SubspaceBlockWeights;
212    /// The maximum length of a block (in bytes).
213    type BlockLength = SubspaceBlockLength;
214    /// The identifier used to distinguish between accounts.
215    type AccountId = AccountId;
216    /// The aggregated dispatch type that is available for extrinsics.
217    type RuntimeCall = RuntimeCall;
218    /// The aggregated `RuntimeTask` type.
219    type RuntimeTask = RuntimeTask;
220    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
221    type Lookup = AccountIdLookup<AccountId, ()>;
222    /// The type for storing how many extrinsics an account has signed.
223    type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
224    /// The type for hashing blocks and tries.
225    type Hash = Hash;
226    /// The hashing algorithm used.
227    type Hashing = BlakeTwo256;
228    /// The block type.
229    type Block = Block;
230    /// The ubiquitous event type.
231    /// The ubiquitous origin type.
232    type RuntimeOrigin = RuntimeOrigin;
233    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
234    type BlockHashCount = BlockHashCount;
235    /// The weight of database operations that the runtime can invoke.
236    type DbWeight = ParityDbWeight;
237    /// Version of the runtime.
238    type Version = Version;
239    /// Converts a module to the index of the module in `construct_runtime!`.
240    ///
241    /// This type is being generated by `construct_runtime!`.
242    type PalletInfo = PalletInfo;
243    /// What to do if a new account is created.
244    type OnNewAccount = ();
245    /// What to do if an account is fully reaped from the system.
246    type OnKilledAccount = ();
247    /// The data to be stored in an account.
248    type AccountData = pallet_balances::AccountData<Balance>;
249    /// Weight information for the extrinsics of this pallet.
250    type SystemWeightInfo = weights::frame_system::WeightInfo<Runtime>;
251    /// This is used as an identifier of the chain.
252    type SS58Prefix = SS58Prefix;
253    /// The set code logic.
254    type OnSetCode = subspace_runtime_primitives::SetCode<Runtime, Domains>;
255    type SingleBlockMigrations = ();
256    type MultiBlockMigrator = ();
257    type PreInherents = ();
258    type PostInherents = ();
259    type PostTransactions = ();
260    type MaxConsumers = ConstU32<16>;
261    type ExtensionsWeightInfo = frame_system::SubstrateExtensionsWeight<Runtime>;
262    type EventSegmentSize = ConsensusEventSegmentSize;
263}
264
265parameter_types! {
266    pub const BlockAuthoringDelay: SlotNumber = BLOCK_AUTHORING_DELAY;
267    pub const PotEntropyInjectionInterval: BlockNumber = POT_ENTROPY_INJECTION_INTERVAL;
268    pub const PotEntropyInjectionLookbackDepth: u8 = POT_ENTROPY_INJECTION_LOOKBACK_DEPTH;
269    pub const PotEntropyInjectionDelay: SlotNumber = POT_ENTROPY_INJECTION_DELAY;
270    pub const EraDuration: u32 = ERA_DURATION_IN_BLOCKS;
271    pub const SlotProbability: (u64, u64) = SLOT_PROBABILITY;
272    pub const ExpectedVotesPerBlock: u32 = EXPECTED_VOTES_PER_BLOCK;
273    pub const RecentSegments: HistorySize = RECENT_SEGMENTS;
274    pub const RecentHistoryFraction: (HistorySize, HistorySize) = RECENT_HISTORY_FRACTION;
275    pub const MinSectorLifetime: HistorySize = MIN_SECTOR_LIFETIME;
276    // Disable solution range adjustment at the start of chain.
277    // Root origin must enable later
278    pub const ShouldAdjustSolutionRange: bool = false;
279    pub const BlockSlotCount: u32 = 6;
280}
281
282pub struct ConfirmationDepthK;
283
284impl Get<BlockNumber> for ConfirmationDepthK {
285    fn get() -> BlockNumber {
286        pallet_runtime_configs::ConfirmationDepthK::<Runtime>::get()
287    }
288}
289
290impl pallet_subspace::Config for Runtime {
291    type SubspaceOrigin = pallet_subspace::EnsureSubspaceOrigin;
292    type BlockAuthoringDelay = BlockAuthoringDelay;
293    type PotEntropyInjectionInterval = PotEntropyInjectionInterval;
294    type PotEntropyInjectionLookbackDepth = PotEntropyInjectionLookbackDepth;
295    type PotEntropyInjectionDelay = PotEntropyInjectionDelay;
296    type EraDuration = EraDuration;
297    type InitialSolutionRange = ConstU64<INITIAL_SOLUTION_RANGE>;
298    type SlotProbability = SlotProbability;
299    type ConfirmationDepthK = ConfirmationDepthK;
300    type RecentSegments = RecentSegments;
301    type RecentHistoryFraction = RecentHistoryFraction;
302    type MinSectorLifetime = MinSectorLifetime;
303    type ExpectedVotesPerBlock = ExpectedVotesPerBlock;
304    type MaxPiecesInSector = ConstU16<{ MAX_PIECES_IN_SECTOR }>;
305    type ShouldAdjustSolutionRange = ShouldAdjustSolutionRange;
306    type EraChangeTrigger = pallet_subspace::NormalEraChange;
307    type WeightInfo = weights::pallet_subspace::WeightInfo<Runtime>;
308    type BlockSlotCount = BlockSlotCount;
309    type ExtensionWeightInfo = weights::pallet_subspace_extension::WeightInfo<Runtime>;
310}
311
312impl pallet_timestamp::Config for Runtime {
313    /// A timestamp: milliseconds since the unix epoch.
314    type Moment = Moment;
315    type OnTimestampSet = ();
316    type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
317    type WeightInfo = weights::pallet_timestamp::WeightInfo<Runtime>;
318}
319
320parameter_types! {
321    // Computed as ED = Account data size * Price per byte, where
322    // Price per byte = Min Number of validators * Storage duration (years) * Storage cost per year
323    // Account data size (80 bytes)
324    // Min Number of redundant validators (100) - For a stable and redundant blockchain we need at least a certain number of full nodes/collators.
325    // Storage duration (1 year) - It is theoretically unlimited, accounts will stay around while the chain is alive.
326    // Storage cost per year of (12 * 1e-9 * 0.1 ) - SSD storage on cloud hosting costs about 0.1 USD per Gb per month
327    pub const ExistentialDeposit: Balance = 10_000_000_000_000 * SHANNON;
328}
329
330#[derive(
331    PartialEq,
332    Eq,
333    Clone,
334    Encode,
335    Decode,
336    TypeInfo,
337    MaxEncodedLen,
338    Ord,
339    PartialOrd,
340    Copy,
341    Debug,
342    DecodeWithMemTracking,
343)]
344pub struct HoldIdentifierWrapper(HoldIdentifier);
345
346impl pallet_domains::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
347    fn staking_staked() -> Self {
348        Self(HoldIdentifier::DomainStaking)
349    }
350
351    fn domain_instantiation_id() -> Self {
352        Self(HoldIdentifier::DomainInstantiation)
353    }
354
355    fn storage_fund_withdrawal() -> Self {
356        Self(HoldIdentifier::DomainStorageFund)
357    }
358}
359
360impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
361    fn messenger_channel() -> Self {
362        Self(HoldIdentifier::MessengerChannel)
363    }
364}
365
366impl VariantCount for HoldIdentifierWrapper {
367    const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
368}
369
370impl pallet_balances::Config for Runtime {
371    type RuntimeEvent = RuntimeEvent;
372    type RuntimeFreezeReason = RuntimeFreezeReason;
373    type MaxLocks = ConstU32<50>;
374    type MaxReserves = ();
375    type ReserveIdentifier = [u8; 8];
376    /// The type for recording an account's balance.
377    type Balance = Balance;
378    /// The ubiquitous event type.
379    type DustRemoval = ();
380    type ExistentialDeposit = ExistentialDeposit;
381    type AccountStore = System;
382    type WeightInfo = weights::pallet_balances::WeightInfo<Runtime>;
383    type FreezeIdentifier = ();
384    type MaxFreezes = ();
385    type RuntimeHoldReason = HoldIdentifierWrapper;
386    type DoneSlashHandler = ();
387}
388
389parameter_types! {
390    pub CreditSupply: Balance =
391        Balances::total_issuance().saturating_add(Transporter::all_domains_supply());
392    pub TotalSpacePledged: u128 = {
393        let pieces = solution_range_to_pieces(Subspace::solution_ranges().current, SLOT_PROBABILITY);
394        pieces as u128 * Piece::SIZE as u128
395    };
396    pub BlockchainHistorySize: u128 = u128::from(Subspace::archived_history_size());
397    pub DynamicCostOfStorage: bool = RuntimeConfigs::enable_dynamic_cost_of_storage();
398    pub TransactionWeightFee: Balance = 100_000 * SHANNON;
399}
400
401impl pallet_transaction_fees::Config for Runtime {
402    type MinReplicationFactor = ConstU16<MIN_REPLICATION_FACTOR>;
403    type CreditSupply = CreditSupply;
404    type TotalSpacePledged = TotalSpacePledged;
405    type BlockchainHistorySize = BlockchainHistorySize;
406    type Currency = Balances;
407    type FindBlockRewardAddress = Subspace;
408    type DynamicCostOfStorage = DynamicCostOfStorage;
409    type WeightInfo = pallet_transaction_fees::weights::SubstrateWeight<Runtime>;
410}
411
412impl pallet_transaction_payment::Config for Runtime {
413    type RuntimeEvent = RuntimeEvent;
414    type OnChargeTransaction = OnChargeTransaction;
415    type OperationalFeeMultiplier = ConstU8<5>;
416    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
417    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
418    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
419    type WeightInfo = weights::pallet_transaction_payment::WeightInfo<Runtime>;
420}
421
422impl pallet_utility::Config for Runtime {
423    type RuntimeEvent = RuntimeEvent;
424    type RuntimeCall = RuntimeCall;
425    type PalletsOrigin = OriginCaller;
426    type WeightInfo = weights::pallet_utility::WeightInfo<Runtime>;
427}
428
429impl MaybeBalancesCall<Runtime> for RuntimeCall {
430    fn maybe_balance_call(&self) -> Option<&pallet_balances::Call<Runtime>> {
431        match self {
432            RuntimeCall::Balances(call) => Some(call),
433            _ => None,
434        }
435    }
436}
437
438impl BalanceTransferChecks for Runtime {
439    fn is_balance_transferable() -> bool {
440        let enabled = RuntimeConfigs::enable_balance_transfers();
441        // For benchmarks, always return disabled, so the extension runs its checks.
442        // But in the extension, we always return success, so benchmarks run transfers as well.
443        if cfg!(feature = "runtime-benchmarks") {
444            false
445        } else {
446            enabled
447        }
448    }
449}
450
451impl MaybeMultisigCall<Runtime> for RuntimeCall {
452    /// If this call is a `pallet_multisig::Call<Runtime>` call, returns the inner call.
453    fn maybe_multisig_call(&self) -> Option<&pallet_multisig::Call<Runtime>> {
454        match self {
455            RuntimeCall::Multisig(call) => Some(call),
456            _ => None,
457        }
458    }
459}
460
461impl MaybeUtilityCall<Runtime> for RuntimeCall {
462    /// If this call is a `pallet_utility::Call<Runtime>` call, returns the inner call.
463    fn maybe_utility_call(&self) -> Option<&pallet_utility::Call<Runtime>> {
464        match self {
465            RuntimeCall::Utility(call) => Some(call),
466            _ => None,
467        }
468    }
469}
470
471impl MaybeNestedCall<Runtime> for RuntimeCall {
472    /// If this call is a nested runtime call, returns the inner call(s).
473    ///
474    /// Ignored calls (such as `pallet_utility::Call::__Ignore`) should be yielded themsevles, but
475    /// their contents should not be yielded.
476    fn maybe_nested_call(&self) -> Option<Vec<&RuntimeCallFor<Runtime>>> {
477        // We currently ignore privileged calls, because privileged users can already change
478        // runtime code. This includes sudo, collective, and scheduler nested `RuntimeCall`s,
479        // and democracy nested `BoundedCall`s.
480
481        // It is ok to return early, because each call can only belong to one pallet.
482        let calls = self.maybe_nested_utility_calls();
483        if calls.is_some() {
484            return calls;
485        }
486
487        let calls = self.maybe_nested_multisig_calls();
488        if calls.is_some() {
489            return calls;
490        }
491
492        None
493    }
494}
495
496impl pallet_sudo::Config for Runtime {
497    type RuntimeEvent = RuntimeEvent;
498    type RuntimeCall = RuntimeCall;
499    type WeightInfo = weights::pallet_sudo::WeightInfo<Runtime>;
500}
501
502pub type CouncilCollective = pallet_collective::Instance1;
503
504// Macro to implement 'Get' trait for each field of 'CouncilDemocracyConfigParams'
505macro_rules! impl_get_council_democracy_field_block_number {
506    ($field_type_name:ident, $field:ident) => {
507        pub struct $field_type_name;
508
509        impl Get<BlockNumber> for $field_type_name {
510            fn get() -> BlockNumber {
511                pallet_runtime_configs::CouncilDemocracyConfig::<Runtime>::get().$field
512            }
513        }
514    };
515}
516
517impl_get_council_democracy_field_block_number! {CouncilMotionDuration, council_motion_duration}
518
519parameter_types! {
520    // maximum dispatch weight of a given council motion
521    // currently set to 50% of maximum block weight
522    pub MaxProposalWeight: Weight = Perbill::from_percent(50) * SubspaceBlockWeights::get().max_block;
523}
524
525pub type EnsureRootOr<O> = EitherOfDiverse<EnsureRoot<AccountId>, O>;
526pub type AllCouncil = EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 1>;
527pub type TwoThirdsCouncil = EnsureProportionAtLeast<AccountId, CouncilCollective, 2, 3>;
528pub type HalfCouncil = EnsureProportionAtLeast<AccountId, CouncilCollective, 1, 2>;
529
530// TODO: update params for mainnnet
531impl pallet_collective::Config<CouncilCollective> for Runtime {
532    type RuntimeEvent = RuntimeEvent;
533    type DefaultVote = pallet_collective::PrimeDefaultVote;
534    type MaxMembers = ConstU32<100>;
535    type MaxProposalWeight = MaxProposalWeight;
536    type MaxProposals = ConstU32<100>;
537    /// Duration of voting for a given council motion.
538    type MotionDuration = CouncilMotionDuration;
539    type Proposal = RuntimeCall;
540    type RuntimeOrigin = RuntimeOrigin;
541    type SetMembersOrigin = EnsureRootOr<AllCouncil>;
542    type WeightInfo = weights::pallet_collective::WeightInfo<Runtime>;
543    type DisapproveOrigin = TwoThirdsCouncil;
544    type KillOrigin = TwoThirdsCouncil;
545    /// Kind of consideration(amount to hold/freeze) on Collective account who initiated the proposal.
546    /// Currently set to zero.
547    type Consideration = ();
548}
549
550// TODO: update params for mainnnet
551parameter_types! {
552    pub PreimageBaseDeposit: Balance = 100 * AI3;
553    pub PreimageByteDeposit: Balance = AI3;
554    pub const PreImageHoldReason: HoldIdentifierWrapper = HoldIdentifierWrapper(HoldIdentifier::Preimage);
555}
556
557impl pallet_preimage::Config for Runtime {
558    type RuntimeEvent = RuntimeEvent;
559    type Consideration = HoldConsideration<
560        AccountId,
561        Balances,
562        PreImageHoldReason,
563        LinearStoragePrice<PreimageBaseDeposit, PreimageByteDeposit, Balance>,
564    >;
565    type Currency = Balances;
566    type ManagerOrigin = EnsureRoot<AccountId>;
567    type WeightInfo = weights::pallet_preimage::WeightInfo<Runtime>;
568}
569
570parameter_types! {
571    pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * SubspaceBlockWeights::get().max_block;
572    // Retry a scheduled item every 10 blocks (2 minutes) until the preimage exists.
573    pub const NoPreimagePostponement: Option<u32> = Some(10);
574}
575
576// Call preimages for the democracy and scheduler pallets can be stored as a binary blob. These
577// blobs are only fetched and decoded in the future block when the call is actually run. This
578// means any member of the council (or sudo) can schedule an invalid subspace runtime call. These
579// calls can cause a stack limit exceeded error in a future block. (Or other kinds of errors.)
580//
581// This risk is acceptable because those accounts are privileged, and those pallets already have
582// to deal with invalid stored calls (for example, stored before an upgrade, but run after).
583//
584// Invalid domain runtime calls will be rejected by the domain runtime extrinsic format checks,
585// even if they are scheduled/democratized in the subspace runtime.
586impl pallet_scheduler::Config for Runtime {
587    type RuntimeEvent = RuntimeEvent;
588    type MaxScheduledPerBlock = ConstU32<50>;
589    type MaximumWeight = MaximumSchedulerWeight;
590    type OriginPrivilegeCmp = EqualPrivilegeOnly;
591    type PalletsOrigin = OriginCaller;
592    type Preimages = Preimage;
593    type RuntimeCall = RuntimeCall;
594    type RuntimeOrigin = RuntimeOrigin;
595    type ScheduleOrigin = EnsureRoot<AccountId>;
596    type WeightInfo = weights::pallet_scheduler::WeightInfo<Runtime>;
597    type BlockNumberProvider = System;
598}
599
600type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
601
602pub struct DemocracySlash;
603impl OnUnbalanced<NegativeImbalance> for DemocracySlash {
604    fn on_nonzero_unbalanced(slashed: NegativeImbalance) {
605        Balances::resolve_creating(&TreasuryAccount::get(), slashed);
606    }
607}
608
609impl_get_council_democracy_field_block_number! {CooloffPeriod, democracy_cooloff_period}
610impl_get_council_democracy_field_block_number! {EnactmentPeriod, democracy_enactment_period}
611impl_get_council_democracy_field_block_number! {FastTrackVotingPeriod, democracy_fast_track_voting_period}
612impl_get_council_democracy_field_block_number! {LaunchPeriod, democracy_launch_period}
613impl_get_council_democracy_field_block_number! {VoteLockingPeriod, democracy_vote_locking_period}
614impl_get_council_democracy_field_block_number! {VotingPeriod, democracy_voting_period}
615
616// TODO: update params for mainnnet
617impl pallet_democracy::Config for Runtime {
618    type RuntimeEvent = RuntimeEvent;
619    type BlacklistOrigin = EnsureRoot<AccountId>;
620    /// To cancel a proposal before it has been passed and slash its backers, must be root.
621    type CancelProposalOrigin = EnsureRoot<AccountId>;
622    /// Origin to cancel a proposal.
623    type CancellationOrigin = EnsureRootOr<TwoThirdsCouncil>;
624    /// Period in blocks where an external proposal may not be re-submitted
625    /// after being vetoed.
626    type CooloffPeriod = CooloffPeriod;
627    type Currency = Balances;
628    /// The minimum period of locking and the period between a proposal being
629    /// approved and enacted.
630    type EnactmentPeriod = EnactmentPeriod;
631    /// A unanimous council can have the next scheduled referendum be a straight
632    /// default-carries (negative turnout biased) vote.
633    /// 100% council vote.
634    type ExternalDefaultOrigin = AllCouncil;
635    /// A simple majority can have the next scheduled referendum be a straight
636    /// majority-carries vote.
637    /// 50% of council votes.
638    type ExternalMajorityOrigin = HalfCouncil;
639    /// A simple majority of the council can decide what their next motion is.
640    /// 50% council votes.
641    type ExternalOrigin = HalfCouncil;
642    /// Half of the council can have an ExternalMajority/ExternalDefault vote
643    /// be tabled immediately and with a shorter voting/enactment period.
644    type FastTrackOrigin = EnsureRootOr<HalfCouncil>;
645    /// Voting period for Fast track voting.
646    type FastTrackVotingPeriod = FastTrackVotingPeriod;
647    type InstantAllowed = ConstBool<true>;
648    type InstantOrigin = EnsureRootOr<AllCouncil>;
649    /// How often (in blocks) new public referenda are launched.
650    type LaunchPeriod = LaunchPeriod;
651    type MaxBlacklisted = ConstU32<100>;
652    type MaxDeposits = ConstU32<100>;
653    type MaxProposals = ConstU32<100>;
654    type MaxVotes = ConstU32<100>;
655    /// The minimum amount to be used as a deposit for a public referendum
656    /// proposal.
657    type MinimumDeposit = ConstU128<{ 1000 * AI3 }>;
658    type PalletsOrigin = OriginCaller;
659    type Preimages = Preimage;
660    type Scheduler = Scheduler;
661    /// Handler for the unbalanced reduction when slashing a preimage deposit.
662    type Slash = DemocracySlash;
663    /// Origin used to submit proposals.
664    /// Currently set to Council member so that no one can submit new proposals except council through democracy
665    type SubmitOrigin = EnsureMember<AccountId, CouncilCollective>;
666    /// Any single council member may veto a coming council proposal, however they
667    /// can only do it once and it lasts only for the cooloff period.
668    type VetoOrigin = EnsureMember<AccountId, CouncilCollective>;
669    type VoteLockingPeriod = VoteLockingPeriod;
670    /// How often (in blocks) to check for new votes.
671    type VotingPeriod = VotingPeriod;
672    type WeightInfo = pallet_democracy::weights::SubstrateWeight<Runtime>;
673}
674
675parameter_types! {
676    pub const SelfChainId: ChainId = ChainId::Consensus;
677}
678
679pub struct OnXDMRewards;
680
681impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
682    fn on_xdm_rewards(reward: Balance) {
683        if let Some(block_author) = Subspace::find_block_reward_address() {
684            let _ = Balances::deposit_creating(&block_author, reward);
685        }
686    }
687
688    fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
689        // on consensus chain, reward the domain operators
690        // balance is already on this consensus runtime
691        if let ChainId::Domain(domain_id) = chain_id {
692            Domains::reward_domain_operators(domain_id, fees)
693        }
694    }
695}
696
697pub struct MmrProofVerifier;
698
699impl sp_subspace_mmr::MmrProofVerifier<mmr::Hash, NumberFor<Block>, Hash> for MmrProofVerifier {
700    fn verify_proof_and_extract_leaf(
701        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, mmr::Hash>,
702    ) -> Option<mmr::Leaf> {
703        let mmr_root = SubspaceMmr::mmr_root_hash(mmr_leaf_proof.consensus_block_number)?;
704        Self::verify_proof_stateless(mmr_root, mmr_leaf_proof)
705    }
706
707    fn verify_proof_stateless(
708        mmr_root: mmr::Hash,
709        mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, mmr::Hash>,
710    ) -> Option<mmr::Leaf> {
711        let ConsensusChainMmrLeafProof {
712            opaque_mmr_leaf,
713            proof,
714            ..
715        } = mmr_leaf_proof;
716
717        pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(
718            mmr_root,
719            vec![mmr::DataOrHash::Data(
720                EncodableOpaqueLeaf(opaque_mmr_leaf.0.clone()).into_opaque_leaf(),
721            )],
722            proof,
723        )
724        .ok()?;
725
726        let leaf: mmr::Leaf = opaque_mmr_leaf.into_opaque_leaf().try_decode()?;
727
728        Some(leaf)
729    }
730}
731
732pub struct StorageKeys;
733
734impl sp_messenger::StorageKeys for StorageKeys {
735    fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
736        Some(Domains::confirmed_domain_block_storage_key(domain_id))
737    }
738
739    fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
740        get_storage_key(StorageKeyRequest::OutboxStorageKey {
741            chain_id,
742            message_key,
743        })
744    }
745
746    fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
747        get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
748            chain_id,
749            message_key,
750        })
751    }
752}
753
754parameter_types! {
755    // TODO: update value
756    pub const ChannelReserveFee: Balance = 100 * AI3;
757    pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
758    pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
759}
760
761// ensure the max outgoing messages is not 0.
762const_assert!(MaxOutgoingMessages::get() >= 1);
763
764pub struct DomainRegistration;
765impl sp_messenger::DomainRegistration for DomainRegistration {
766    fn is_domain_registered(domain_id: DomainId) -> bool {
767        Domains::is_domain_registered(domain_id)
768    }
769}
770
771impl pallet_messenger::Config for Runtime {
772    type SelfChainId = SelfChainId;
773
774    fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
775        if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
776            Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
777        } else {
778            None
779        }
780    }
781
782    type Currency = Balances;
783    type WeightInfo = weights::pallet_messenger::WeightInfo<Runtime>;
784    type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
785    type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
786    type FeeMultiplier = XdmFeeMultipler;
787    type OnXDMRewards = OnXDMRewards;
788    type MmrHash = mmr::Hash;
789    type MmrProofVerifier = MmrProofVerifier;
790    #[cfg(feature = "runtime-benchmarks")]
791    type StorageKeys = sp_messenger::BenchmarkStorageKeys;
792    #[cfg(not(feature = "runtime-benchmarks"))]
793    type StorageKeys = StorageKeys;
794    type DomainOwner = Domains;
795    type HoldIdentifier = HoldIdentifierWrapper;
796    type ChannelReserveFee = ChannelReserveFee;
797    type ChannelInitReservePortion = ChannelInitReservePortion;
798    type DomainRegistration = DomainRegistration;
799    type MaxOutgoingMessages = MaxOutgoingMessages;
800    type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
801    type NoteChainTransfer = Transporter;
802    type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<
803        Runtime,
804        // NOTE: use `()` as `FromConsensusWeightInfo` since the consensus chain should
805        // never process XDM that come from the consensus chain itself.
806        (),
807        weights::pallet_messenger_from_domains_extension::WeightInfo<Runtime>,
808    >;
809}
810
811impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
812where
813    RuntimeCall: From<C>,
814{
815    type Extrinsic = UncheckedExtrinsic;
816    type RuntimeCall = RuntimeCall;
817}
818
819impl<C> frame_system::offchain::CreateInherent<C> for Runtime
820where
821    RuntimeCall: From<C>,
822{
823    fn create_bare(call: Self::RuntimeCall) -> Self::Extrinsic {
824        UncheckedExtrinsic::new_bare(call)
825    }
826}
827
828impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
829where
830    RuntimeCall: From<C>,
831{
832    fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
833        create_unsigned_general_extrinsic(call)
834    }
835}
836
837parameter_types! {
838    pub const TransporterEndpointId: EndpointId = 1;
839    pub const MinimumTransfer: Balance = AI3;
840}
841
842impl pallet_transporter::Config for Runtime {
843    type SelfChainId = SelfChainId;
844    type SelfEndpointId = TransporterEndpointId;
845    type Currency = Balances;
846    type Sender = Messenger;
847    type AccountIdConverter = AccountIdConverter;
848    type WeightInfo = weights::pallet_transporter::WeightInfo<Runtime>;
849    type MinimumTransfer = MinimumTransfer;
850}
851
852pub struct BlockTreePruningDepth;
853impl Get<BlockNumber> for BlockTreePruningDepth {
854    fn get() -> BlockNumber {
855        pallet_runtime_configs::DomainBlockPruningDepth::<Runtime>::get()
856    }
857}
858
859pub struct StakeWithdrawalLockingPeriod;
860impl Get<BlockNumber> for StakeWithdrawalLockingPeriod {
861    fn get() -> BlockNumber {
862        pallet_runtime_configs::StakingWithdrawalPeriod::<Runtime>::get()
863    }
864}
865
866parameter_types! {
867    pub const MaximumReceiptDrift: BlockNumber = 128;
868    pub const InitialDomainTxRange: u64 = INITIAL_DOMAIN_TX_RANGE;
869    pub const DomainTxRangeAdjustmentInterval: u64 = TX_RANGE_ADJUSTMENT_INTERVAL_BLOCKS;
870    /// Minimum operator stake to become an operator.
871    // TODO: this value should be properly updated before permissionless operators are allowed
872    pub const MinOperatorStake: Balance = 100 * AI3;
873    /// Minimum nominator stake to nominate and operator.
874    // TODO: this value should be properly updated before permissionless operators are allowed
875    pub const MinNominatorStake: Balance = AI3;
876    /// Use the consensus chain's `Normal` extrinsics block size limit as the domain block size limit
877    pub MaxDomainBlockSize: u32 = NORMAL_DISPATCH_RATIO * MAX_BLOCK_LENGTH;
878    /// Use the consensus chain's `Normal` extrinsics block weight limit as the domain block weight limit
879    pub MaxDomainBlockWeight: Weight = maximum_domain_block_weight();
880    pub const DomainInstantiationDeposit: Balance = 100 * AI3;
881    pub const MaxDomainNameLength: u32 = 32;
882    // TODO: revisit these. For now epoch every 10 mins for a 6 second block and only 100 number of staking
883    // operations allowed within each epoch.
884    pub const StakeEpochDuration: DomainNumber = 100;
885    pub TreasuryAccount: AccountId = PalletId(*b"treasury").into_account_truncating();
886    pub const MaxPendingStakingOperation: u32 = 512;
887    pub const DomainsPalletId: PalletId = PalletId(*b"domains_");
888    pub const MaxInitialDomainAccounts: u32 = 10;
889    pub const MinInitialDomainAccountBalance: Balance = AI3;
890    pub const BundleLongevity: u32 = 5;
891    pub const WithdrawalLimit: u32 = 32;
892    pub const CurrentBundleAndExecutionReceiptVersion: BundleAndExecutionReceiptVersion = BundleAndExecutionReceiptVersion{
893        bundle_version: BundleVersion::V0,
894        execution_receipt_version: ExecutionReceiptVersion::V0,
895    };
896    /// Operator activation delay after deactivation in Epochs
897    pub const OperatorActivationDelayInEpochs: EpochIndex = 5;
898}
899
900// `BlockSlotCount` must at least keep the slot for the current and the parent block, it also need to
901// keep enough block slot for bundle validation
902const_assert!(BlockSlotCount::get() >= 2 && BlockSlotCount::get() > BundleLongevity::get());
903
904// `BlockHashCount` must greater than `BlockSlotCount` because we need to use the block number found
905// with `BlockSlotCount` to get the block hash.
906const_assert!(BlockHashCount::get() > BlockSlotCount::get());
907
908// Minimum operator stake must be >= minimum nominator stake since operator is also a nominator.
909const_assert!(MinOperatorStake::get() >= MinNominatorStake::get());
910
911pub struct BlockSlot;
912
913impl pallet_domains::BlockSlot<Runtime> for BlockSlot {
914    fn future_slot(block_number: BlockNumber) -> Option<sp_consensus_slots::Slot> {
915        let block_slots = Subspace::block_slots();
916        block_slots
917            .get(&block_number)
918            .map(|slot| *slot + Slot::from(BlockAuthoringDelay::get()))
919    }
920
921    fn slot_produced_after(to_check: sp_consensus_slots::Slot) -> Option<BlockNumber> {
922        let block_slots = Subspace::block_slots();
923        for (block_number, slot) in block_slots.into_iter().rev() {
924            if to_check > slot {
925                return Some(block_number);
926            }
927        }
928        None
929    }
930
931    fn current_slot() -> Slot {
932        Subspace::current_slot()
933    }
934}
935
936pub struct OnChainRewards;
937
938impl sp_domains::OnChainRewards<Balance> for OnChainRewards {
939    fn on_chain_rewards(chain_id: ChainId, reward: Balance) {
940        match chain_id {
941            ChainId::Consensus => {
942                if let Some(block_author) = Subspace::find_block_reward_address() {
943                    let _ = Balances::deposit_creating(&block_author, reward);
944                }
945            }
946            ChainId::Domain(domain_id) => Domains::reward_domain_operators(domain_id, reward),
947        }
948    }
949}
950
951impl pallet_domains::Config for Runtime {
952    type DomainOrigin = pallet_domains::EnsureDomainOrigin;
953    type DomainHash = DomainHash;
954    type Balance = Balance;
955    type DomainHeader = sp_runtime::generic::Header<DomainNumber, BlakeTwo256>;
956    type ConfirmationDepthK = ConfirmationDepthK;
957    type Currency = Balances;
958    type Share = Balance;
959    type HoldIdentifier = HoldIdentifierWrapper;
960    type BlockTreePruningDepth = BlockTreePruningDepth;
961    type ConsensusSlotProbability = SlotProbability;
962    type MaxDomainBlockSize = MaxDomainBlockSize;
963    type MaxDomainBlockWeight = MaxDomainBlockWeight;
964    type MaxDomainNameLength = MaxDomainNameLength;
965    type DomainInstantiationDeposit = DomainInstantiationDeposit;
966    type WeightInfo = weights::pallet_domains::WeightInfo<Runtime>;
967    type InitialDomainTxRange = InitialDomainTxRange;
968    type DomainTxRangeAdjustmentInterval = DomainTxRangeAdjustmentInterval;
969    type MinOperatorStake = MinOperatorStake;
970    type MinNominatorStake = MinNominatorStake;
971    type StakeWithdrawalLockingPeriod = StakeWithdrawalLockingPeriod;
972    type StakeEpochDuration = StakeEpochDuration;
973    type TreasuryAccount = TreasuryAccount;
974    type MaxPendingStakingOperation = MaxPendingStakingOperation;
975    type Randomness = Subspace;
976    type PalletId = DomainsPalletId;
977    type StorageFee = TransactionFees;
978    type BlockTimestamp = pallet_timestamp::Pallet<Runtime>;
979    type BlockSlot = BlockSlot;
980    type DomainsTransfersTracker = Transporter;
981    type MaxInitialDomainAccounts = MaxInitialDomainAccounts;
982    type MinInitialDomainAccountBalance = MinInitialDomainAccountBalance;
983    type BundleLongevity = BundleLongevity;
984    type DomainBundleSubmitted = Messenger;
985    type OnDomainInstantiated = Messenger;
986    type MmrHash = mmr::Hash;
987    type MmrProofVerifier = MmrProofVerifier;
988    type FraudProofStorageKeyProvider = StorageKeyProvider;
989    type OnChainRewards = OnChainRewards;
990    type WithdrawalLimit = WithdrawalLimit;
991    type CurrentBundleAndExecutionReceiptVersion = CurrentBundleAndExecutionReceiptVersion;
992    type OperatorActivationDelayInEpochs = OperatorActivationDelayInEpochs;
993}
994
995parameter_types! {
996    pub const AvgBlockspaceUsageNumBlocks: BlockNumber = 100;
997    pub const ProposerTaxOnVotes: (u32, u32) = (1, 10);
998}
999
1000impl pallet_rewards::Config for Runtime {
1001    type Currency = Balances;
1002    type AvgBlockspaceUsageNumBlocks = AvgBlockspaceUsageNumBlocks;
1003    type TransactionByteFee = TransactionByteFee;
1004    type MaxRewardPoints = ConstU32<20>;
1005    type ProposerTaxOnVotes = ProposerTaxOnVotes;
1006    type RewardsEnabled = Subspace;
1007    type FindBlockRewardAddress = Subspace;
1008    type FindVotingRewardAddresses = Subspace;
1009    type WeightInfo = weights::pallet_rewards::WeightInfo<Runtime>;
1010    type OnReward = ();
1011}
1012
1013impl pallet_runtime_configs::Config for Runtime {
1014    type WeightInfo = weights::pallet_runtime_configs::WeightInfo<Runtime>;
1015}
1016
1017impl pallet_domains::extensions::DomainsCheck for Runtime {
1018    fn is_domains_enabled() -> bool {
1019        RuntimeConfigs::enable_domains()
1020    }
1021}
1022
1023mod mmr {
1024    use super::Runtime;
1025    pub use pallet_mmr::primitives::*;
1026
1027    pub type Leaf = <<Runtime as pallet_mmr::Config>::LeafData as LeafDataProvider>::LeafData;
1028    pub type Hashing = <Runtime as pallet_mmr::Config>::Hashing;
1029    pub type Hash = <Hashing as sp_runtime::traits::Hash>::Output;
1030}
1031
1032pub struct BlockHashProvider;
1033
1034impl pallet_mmr::BlockHashProvider<BlockNumber, Hash> for BlockHashProvider {
1035    fn block_hash(block_number: BlockNumber) -> Hash {
1036        consensus_block_hash(block_number).expect("Hash must exist for a given block number.")
1037    }
1038}
1039
1040impl pallet_mmr::Config for Runtime {
1041    const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX;
1042    type Hashing = Keccak256;
1043    type LeafData = SubspaceMmr;
1044    type OnNewRoot = SubspaceMmr;
1045    type BlockHashProvider = BlockHashProvider;
1046    type WeightInfo = weights::pallet_mmr::WeightInfo<Runtime>;
1047    #[cfg(feature = "runtime-benchmarks")]
1048    type BenchmarkHelper = ();
1049}
1050
1051parameter_types! {
1052    pub const MmrRootHashCount: u32 = 1024;
1053}
1054
1055impl pallet_subspace_mmr::Config for Runtime {
1056    type MmrRootHash = mmr::Hash;
1057    type MmrRootHashCount = MmrRootHashCount;
1058}
1059
1060parameter_types! {
1061    pub const MaxSignatories: u32 = 100;
1062}
1063
1064macro_rules! deposit {
1065    ($name:ident, $item_fee:expr, $items:expr, $bytes:expr) => {
1066        pub struct $name;
1067
1068        impl Get<Balance> for $name {
1069            fn get() -> Balance {
1070                $item_fee.saturating_mul($items.into()).saturating_add(
1071                    TransactionFees::transaction_byte_fee().saturating_mul($bytes.into()),
1072                )
1073            }
1074        }
1075    };
1076}
1077
1078// One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes.
1079// Each multisig costs 20 AI3 + bytes_of_storge * TransactionByteFee
1080deposit!(DepositBaseFee, 20 * AI3, 1u32, 88u32);
1081
1082// Additional storage item size of 32 bytes.
1083deposit!(DepositFactor, 0u128, 0u32, 32u32);
1084
1085impl pallet_multisig::Config for Runtime {
1086    type RuntimeEvent = RuntimeEvent;
1087    type RuntimeCall = RuntimeCall;
1088    type Currency = Balances;
1089    type DepositBase = DepositBaseFee;
1090    type DepositFactor = DepositFactor;
1091    type MaxSignatories = MaxSignatories;
1092    type WeightInfo = weights::pallet_multisig::WeightInfo<Runtime>;
1093    type BlockNumberProvider = System;
1094}
1095
1096construct_runtime!(
1097    pub struct Runtime {
1098        System: frame_system = 0,
1099        Timestamp: pallet_timestamp = 1,
1100
1101        Subspace: pallet_subspace = 2,
1102        Rewards: pallet_rewards = 4,
1103
1104        Balances: pallet_balances = 5,
1105        TransactionFees: pallet_transaction_fees = 6,
1106        TransactionPayment: pallet_transaction_payment = 7,
1107        Utility: pallet_utility = 8,
1108
1109        Domains: pallet_domains = 12,
1110        RuntimeConfigs: pallet_runtime_configs = 14,
1111
1112        Mmr: pallet_mmr = 30,
1113        SubspaceMmr: pallet_subspace_mmr = 31,
1114
1115        // messenger stuff
1116        // Note: Indexes should match with indexes on other chains and domains
1117        Messenger: pallet_messenger exclude_parts { Inherent } = 60,
1118        Transporter: pallet_transporter = 61,
1119
1120        // council and democracy
1121        Scheduler: pallet_scheduler = 81,
1122        Council: pallet_collective::<Instance1> = 82,
1123        Democracy: pallet_democracy = 83,
1124        Preimage: pallet_preimage = 84,
1125
1126        // Multisig
1127        Multisig: pallet_multisig = 90,
1128
1129        // Reserve some room for other pallets as we'll remove sudo pallet eventually.
1130        Sudo: pallet_sudo = 100,
1131    }
1132);
1133
1134/// The address format for describing accounts.
1135pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
1136/// Block header type as expected by this runtime.
1137pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
1138/// Block type as expected by this runtime.
1139pub type Block = generic::Block<Header, UncheckedExtrinsic>;
1140
1141/// The SignedExtension to the basic transaction logic.
1142pub type SignedExtra = (
1143    (
1144        frame_system::CheckNonZeroSender<Runtime>,
1145        SmallOrderEd25519CheckExtension<Runtime>,
1146    ),
1147    frame_system::CheckSpecVersion<Runtime>,
1148    frame_system::CheckTxVersion<Runtime>,
1149    frame_system::CheckGenesis<Runtime>,
1150    frame_system::CheckMortality<Runtime>,
1151    frame_system::CheckNonce<Runtime>,
1152    frame_system::CheckWeight<Runtime>,
1153    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
1154    BalanceTransferCheckExtension<Runtime>,
1155    pallet_subspace::extensions::SubspaceExtension<Runtime>,
1156    pallet_domains::extensions::DomainsExtension<Runtime>,
1157    pallet_messenger::extensions::MessengerExtension<Runtime>,
1158);
1159/// Unchecked extrinsic type as expected by this runtime.
1160pub type UncheckedExtrinsic =
1161    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
1162
1163/// Executive: handles dispatch to the various modules.
1164pub type Executive = frame_executive::Executive<
1165    Runtime,
1166    Block,
1167    frame_system::ChainContext<Runtime>,
1168    Runtime,
1169    AllPalletsWithSystem,
1170    (
1171        pallet_domains::migrations::VersionCheckedMigrateDomainsV5ToV6<Runtime>,
1172        pallet_transporter::migrations::VersionCheckedMigrateTransporterV0ToV1<Runtime>,
1173    ),
1174>;
1175
1176impl pallet_subspace::extensions::MaybeSubspaceCall<Runtime> for RuntimeCall {
1177    fn maybe_subspace_call(&self) -> Option<&pallet_subspace::Call<Runtime>> {
1178        match self {
1179            RuntimeCall::Subspace(call) => Some(call),
1180            _ => None,
1181        }
1182    }
1183}
1184
1185impl pallet_domains::extensions::MaybeDomainsCall<Runtime> for RuntimeCall {
1186    fn maybe_domains_call(&self) -> Option<&pallet_domains::Call<Runtime>> {
1187        match self {
1188            RuntimeCall::Domains(call) => Some(call),
1189            _ => None,
1190        }
1191    }
1192}
1193
1194impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
1195    fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
1196        match self {
1197            RuntimeCall::Messenger(call) => Some(call),
1198            _ => None,
1199        }
1200    }
1201}
1202
1203fn extract_segment_headers(ext: &UncheckedExtrinsic) -> Option<Vec<SegmentHeader>> {
1204    match &ext.function {
1205        RuntimeCall::Subspace(pallet_subspace::Call::store_segment_headers { segment_headers }) => {
1206            Some(segment_headers.clone())
1207        }
1208        _ => None,
1209    }
1210}
1211
1212fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
1213    match &ext.function {
1214        RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1215        | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1216            let ConsensusChainMmrLeafProof {
1217                consensus_block_number,
1218                opaque_mmr_leaf,
1219                proof,
1220                ..
1221            } = msg.proof.consensus_mmr_proof();
1222
1223            let mmr_root = SubspaceMmr::mmr_root_hash(consensus_block_number)?;
1224
1225            Some(
1226                pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(
1227                    mmr_root,
1228                    vec![mmr::DataOrHash::Data(
1229                        EncodableOpaqueLeaf(opaque_mmr_leaf.0.clone()).into_opaque_leaf(),
1230                    )],
1231                    proof,
1232                )
1233                .is_ok(),
1234            )
1235        }
1236        _ => None,
1237    }
1238}
1239
1240fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
1241    let extra: SignedExtra = (
1242        (
1243            frame_system::CheckNonZeroSender::<Runtime>::new(),
1244            SmallOrderEd25519CheckExtension::<Runtime>::new(),
1245        ),
1246        frame_system::CheckSpecVersion::<Runtime>::new(),
1247        frame_system::CheckTxVersion::<Runtime>::new(),
1248        frame_system::CheckGenesis::<Runtime>::new(),
1249        frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
1250        // for unsigned extrinsic, nonce check will be skipped
1251        // so set a default value
1252        frame_system::CheckNonce::<Runtime>::from(0u32.into()),
1253        frame_system::CheckWeight::<Runtime>::new(),
1254        // for unsigned extrinsic, transaction fee check will be skipped
1255        // so set a default value
1256        pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1257        BalanceTransferCheckExtension::<Runtime>::default(),
1258        pallet_subspace::extensions::SubspaceExtension::<Runtime>::new(),
1259        pallet_domains::extensions::DomainsExtension::<Runtime>::new(),
1260        pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1261    );
1262
1263    UncheckedExtrinsic::new_transaction(call, extra)
1264}
1265
1266struct RewardAddress([u8; 32]);
1267
1268impl From<PublicKey> for RewardAddress {
1269    #[inline]
1270    fn from(public_key: PublicKey) -> Self {
1271        Self(*public_key)
1272    }
1273}
1274
1275impl From<RewardAddress> for AccountId32 {
1276    #[inline]
1277    fn from(reward_address: RewardAddress) -> Self {
1278        reward_address.0.into()
1279    }
1280}
1281
1282pub struct StorageKeyProvider;
1283impl FraudProofStorageKeyProvider<NumberFor<Block>> for StorageKeyProvider {
1284    fn storage_key(req: FraudProofStorageKeyRequest<NumberFor<Block>>) -> Vec<u8> {
1285        match req {
1286            FraudProofStorageKeyRequest::InvalidInherentExtrinsicData => {
1287                pallet_domains::BlockInherentExtrinsicData::<Runtime>::hashed_key().to_vec()
1288            }
1289            FraudProofStorageKeyRequest::SuccessfulBundles(domain_id) => {
1290                pallet_domains::SuccessfulBundles::<Runtime>::hashed_key_for(domain_id)
1291            }
1292            FraudProofStorageKeyRequest::DomainAllowlistUpdates(domain_id) => {
1293                Messenger::domain_allow_list_update_storage_key(domain_id)
1294            }
1295            FraudProofStorageKeyRequest::DomainRuntimeUpgrades => {
1296                pallet_domains::DomainRuntimeUpgrades::<Runtime>::hashed_key().to_vec()
1297            }
1298            FraudProofStorageKeyRequest::RuntimeRegistry(runtime_id) => {
1299                pallet_domains::RuntimeRegistry::<Runtime>::hashed_key_for(runtime_id)
1300            }
1301            FraudProofStorageKeyRequest::DomainSudoCall(domain_id) => {
1302                pallet_domains::DomainSudoCalls::<Runtime>::hashed_key_for(domain_id)
1303            }
1304            FraudProofStorageKeyRequest::EvmDomainContractCreationAllowedByCall(domain_id) => {
1305                pallet_domains::EvmDomainContractCreationAllowedByCalls::<Runtime>::hashed_key_for(
1306                    domain_id,
1307                )
1308            }
1309            FraudProofStorageKeyRequest::MmrRoot(block_number) => {
1310                pallet_subspace_mmr::MmrRootHashes::<Runtime>::hashed_key_for(block_number)
1311            }
1312        }
1313    }
1314}
1315
1316#[cfg(feature = "runtime-benchmarks")]
1317mod benches {
1318    frame_benchmarking::define_benchmarks!(
1319        [frame_benchmarking, BaselineBench::<Runtime>]
1320        [frame_system, SystemBench::<Runtime>]
1321        [pallet_timestamp, Timestamp]
1322        [pallet_subspace, Subspace]
1323        [pallet_subspace_extension, SubspaceExtensionBench::<Runtime>]
1324        [pallet_rewards, Rewards]
1325        [pallet_balances, Balances]
1326        [balance_transfer_check_extension, BalanceTransferCheckBench::<Runtime>]
1327        // pallet_transaction_fees uses a default over-estimated weight
1328        [pallet_transaction_payment, TransactionPayment]
1329        [pallet_utility, Utility]
1330        [pallet_domains, Domains]
1331        [pallet_runtime_configs, RuntimeConfigs]
1332        [pallet_mmr, Mmr]
1333        // pallet_subspace_mmr has no calls to benchmark
1334        [pallet_messenger, Messenger]
1335        [pallet_messenger_from_domains_extension, MessengerFromDomainsExtensionBench::<Runtime>]
1336        [pallet_transporter, Transporter]
1337        [pallet_scheduler, Scheduler]
1338        [pallet_collective, Council]
1339        [pallet_democracy, Democracy]
1340        [pallet_preimage, Preimage]
1341        [pallet_multisig, Multisig]
1342        [pallet_sudo, Sudo]
1343    );
1344}
1345
1346#[cfg(feature = "runtime-benchmarks")]
1347impl frame_system_benchmarking::Config for Runtime {}
1348
1349#[cfg(feature = "runtime-benchmarks")]
1350impl pallet_transaction_payment::BenchmarkConfig for Runtime {}
1351
1352#[cfg(feature = "runtime-benchmarks")]
1353impl frame_benchmarking::baseline::Config for Runtime {}
1354
1355impl_runtime_apis! {
1356    impl sp_api::Core<Block> for Runtime {
1357        fn version() -> RuntimeVersion {
1358            VERSION
1359        }
1360
1361        fn execute_block(block: <Block as sp_runtime::traits::Block>::LazyBlock) {
1362            Executive::execute_block(block);
1363        }
1364
1365        fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
1366            Executive::initialize_block(header)
1367        }
1368    }
1369
1370    impl sp_api::Metadata<Block> for Runtime {
1371        fn metadata() -> OpaqueMetadata {
1372            OpaqueMetadata::new(Runtime::metadata().into())
1373        }
1374
1375        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
1376            Runtime::metadata_at_version(version)
1377        }
1378
1379        fn metadata_versions() -> Vec<u32> {
1380            Runtime::metadata_versions()
1381        }
1382    }
1383
1384    impl sp_block_builder::BlockBuilder<Block> for Runtime {
1385        fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
1386            Executive::apply_extrinsic(extrinsic)
1387        }
1388
1389        fn finalize_block() -> HeaderFor<Block> {
1390            Executive::finalize_block()
1391        }
1392
1393        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
1394            data.create_extrinsics()
1395        }
1396
1397        fn check_inherents(
1398            block: <Block as sp_runtime::traits::Block>::LazyBlock,
1399            data: sp_inherents::InherentData,
1400        ) -> sp_inherents::CheckInherentsResult {
1401            data.check_extrinsics(&block)
1402        }
1403    }
1404
1405    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
1406        fn validate_transaction(
1407            source: TransactionSource,
1408            tx: ExtrinsicFor<Block>,
1409            block_hash: BlockHashFor<Block>,
1410        ) -> TransactionValidity {
1411            Executive::validate_transaction(source, tx, block_hash)
1412        }
1413    }
1414
1415    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
1416        fn offchain_worker(header: &HeaderFor<Block>) {
1417            Executive::offchain_worker(header)
1418        }
1419    }
1420
1421    impl sp_objects::ObjectsApi<Block> for Runtime {
1422        fn extract_block_object_mapping(block: Block) -> BlockObjectMapping {
1423            extract_block_object_mapping(block)
1424        }
1425    }
1426
1427    impl sp_consensus_subspace::SubspaceApi<Block, PublicKey> for Runtime {
1428        fn pot_parameters() -> PotParameters {
1429            Subspace::pot_parameters()
1430        }
1431
1432        fn solution_ranges() -> SolutionRanges {
1433            Subspace::solution_ranges()
1434        }
1435
1436        fn submit_vote_extrinsic(
1437            signed_vote: SignedVote<NumberFor<Block>, BlockHashFor<Block>, PublicKey>,
1438        ) {
1439            let SignedVote { vote, signature } = signed_vote;
1440            let Vote::V0 {
1441                height,
1442                parent_hash,
1443                slot,
1444                solution,
1445                proof_of_time,
1446                future_proof_of_time,
1447            } = vote;
1448
1449            Subspace::submit_vote(SignedVote {
1450                vote: Vote::V0 {
1451                    height,
1452                    parent_hash,
1453                    slot,
1454                    solution: solution.into_reward_address_format::<RewardAddress, AccountId32>(),
1455                    proof_of_time,
1456                    future_proof_of_time,
1457                },
1458                signature,
1459            })
1460        }
1461
1462        fn history_size() -> HistorySize {
1463            <pallet_subspace::Pallet<Runtime>>::history_size()
1464        }
1465
1466        fn max_pieces_in_sector() -> u16 {
1467            MAX_PIECES_IN_SECTOR
1468        }
1469
1470        fn segment_commitment(segment_index: SegmentIndex) -> Option<SegmentCommitment> {
1471            Subspace::segment_commitment(segment_index)
1472        }
1473
1474        fn extract_segment_headers(ext: &ExtrinsicFor<Block>) -> Option<Vec<SegmentHeader >> {
1475            extract_segment_headers(ext)
1476        }
1477
1478        fn is_inherent(ext: &ExtrinsicFor<Block>) -> bool {
1479            match &ext.function {
1480                RuntimeCall::Subspace(call) => Subspace::is_inherent(call),
1481                RuntimeCall::Timestamp(call) => Timestamp::is_inherent(call),
1482                _ => false,
1483            }
1484        }
1485
1486        fn root_plot_public_key() -> Option<PublicKey> {
1487            Subspace::root_plot_public_key()
1488        }
1489
1490        fn should_adjust_solution_range() -> bool {
1491            Subspace::should_adjust_solution_range()
1492        }
1493
1494        fn chain_constants() -> ChainConstants {
1495            ChainConstants::V0 {
1496                confirmation_depth_k: ConfirmationDepthK::get(),
1497                block_authoring_delay: Slot::from(BlockAuthoringDelay::get()),
1498                era_duration: EraDuration::get(),
1499                slot_probability: SlotProbability::get(),
1500                slot_duration: SlotDuration::from_millis(SLOT_DURATION),
1501                recent_segments: RecentSegments::get(),
1502                recent_history_fraction: RecentHistoryFraction::get(),
1503                min_sector_lifetime: MinSectorLifetime::get(),
1504            }
1505        }
1506
1507        fn block_weight() -> Weight {
1508            System::block_weight().total()
1509        }
1510    }
1511
1512    impl sp_domains::DomainsApi<Block, DomainHeader> for Runtime {
1513        fn submit_bundle_unsigned(
1514            opaque_bundle: sp_domains::bundle::OpaqueBundle<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, Balance>,
1515        ) {
1516            Domains::submit_bundle_unsigned(opaque_bundle)
1517        }
1518
1519        fn submit_receipt_unsigned(
1520            singleton_receipt: SealedSingletonReceipt<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, Balance>,
1521        ) {
1522            Domains::submit_receipt_unsigned(singleton_receipt)
1523        }
1524
1525        fn extract_successful_bundles(
1526            domain_id: DomainId,
1527            extrinsics: Vec<ExtrinsicFor<Block>>,
1528        ) -> sp_domains::bundle::OpaqueBundles<Block, DomainHeader, Balance> {
1529            crate::domains::extract_successful_bundles(domain_id, extrinsics)
1530        }
1531
1532        fn extrinsics_shuffling_seed() -> Randomness {
1533            Randomness::from(Domains::extrinsics_shuffling_seed().to_fixed_bytes())
1534        }
1535
1536        fn domain_runtime_code(domain_id: DomainId) -> Option<Vec<u8>> {
1537            Domains::domain_runtime_code(domain_id)
1538        }
1539
1540        fn runtime_id(domain_id: DomainId) -> Option<sp_domains::RuntimeId> {
1541            Domains::runtime_id(domain_id)
1542        }
1543
1544        fn runtime_upgrades() -> Vec<sp_domains::RuntimeId> {
1545            Domains::runtime_upgrades()
1546        }
1547
1548        fn domain_instance_data(domain_id: DomainId) -> Option<(DomainInstanceData, NumberFor<Block>)> {
1549            Domains::domain_instance_data(domain_id)
1550        }
1551
1552        fn domain_timestamp() -> Moment {
1553            Domains::timestamp()
1554        }
1555
1556        fn consensus_transaction_byte_fee() -> Balance {
1557            Domains::consensus_transaction_byte_fee()
1558        }
1559
1560        fn domain_tx_range(domain_id: DomainId) -> U256 {
1561            Domains::domain_tx_range(domain_id)
1562        }
1563
1564        fn genesis_state_root(domain_id: DomainId) -> Option<H256> {
1565            Domains::domain_genesis_block_execution_receipt(domain_id)
1566                .map(|er| *er.final_state_root())
1567        }
1568
1569        fn head_receipt_number(domain_id: DomainId) -> DomainNumber {
1570            Domains::head_receipt_number(domain_id)
1571        }
1572
1573        fn oldest_unconfirmed_receipt_number(domain_id: DomainId) -> Option<DomainNumber> {
1574            Domains::oldest_unconfirmed_receipt_number(domain_id)
1575        }
1576
1577        fn domain_bundle_limit(domain_id: DomainId) -> Option<sp_domains::DomainBundleLimit> {
1578            Domains::domain_bundle_limit(domain_id).ok().flatten()
1579        }
1580
1581        fn non_empty_er_exists(domain_id: DomainId) -> bool {
1582            Domains::non_empty_er_exists(domain_id)
1583        }
1584
1585        fn domain_best_number(domain_id: DomainId) -> Option<DomainNumber> {
1586            Domains::domain_best_number(domain_id).ok()
1587        }
1588
1589        fn execution_receipt(receipt_hash: DomainHash) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>> {
1590            Domains::execution_receipt(receipt_hash)
1591        }
1592
1593        fn domain_operators(domain_id: DomainId) -> Option<(BTreeMap<OperatorId, Balance>, Vec<OperatorId>)> {
1594            Domains::domain_staking_summary(domain_id).map(|summary| {
1595                let next_operators = summary.next_operators.into_iter().collect();
1596                (summary.current_operators, next_operators)
1597            })
1598        }
1599
1600        fn receipt_hash(domain_id: DomainId, domain_number: DomainNumber) -> Option<DomainHash> {
1601            Domains::receipt_hash(domain_id, domain_number)
1602        }
1603
1604        fn latest_confirmed_domain_block(domain_id: DomainId) -> Option<(DomainNumber, DomainHash)>{
1605            Domains::latest_confirmed_domain_block(domain_id)
1606        }
1607
1608        fn is_bad_er_pending_to_prune(domain_id: DomainId, receipt_hash: DomainHash) -> bool {
1609            Domains::execution_receipt(receipt_hash).map(
1610                |er| Domains::is_bad_er_pending_to_prune(domain_id, *er.domain_block_number())
1611            )
1612            .unwrap_or(false)
1613        }
1614
1615        fn storage_fund_account_balance(operator_id: OperatorId) -> Balance {
1616            Domains::storage_fund_account_balance(operator_id)
1617        }
1618
1619        fn is_domain_runtime_upgraded_since(domain_id: DomainId, at: NumberFor<Block>) -> Option<bool> {
1620            Domains::is_domain_runtime_upgraded_since(domain_id, at)
1621        }
1622
1623        fn domain_sudo_call(domain_id: DomainId) -> Option<Vec<u8>> {
1624            Domains::domain_sudo_call(domain_id)
1625        }
1626
1627        fn evm_domain_contract_creation_allowed_by_call(domain_id: DomainId) -> Option<PermissionedActionAllowedBy<EthereumAccountId>> {
1628            Domains::evm_domain_contract_creation_allowed_by_call(domain_id)
1629        }
1630
1631        fn last_confirmed_domain_block_receipt(domain_id: DomainId) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>>{
1632            Domains::latest_confirmed_domain_execution_receipt(domain_id)
1633        }
1634
1635        fn current_bundle_and_execution_receipt_version() -> BundleAndExecutionReceiptVersion {
1636            Domains::current_bundle_and_execution_receipt_version()
1637        }
1638
1639        fn genesis_execution_receipt(domain_id: DomainId) -> Option<ExecutionReceiptFor<DomainHeader, Block, Balance>> {
1640            Domains::domain_genesis_block_execution_receipt(domain_id)
1641        }
1642
1643        fn nominator_position(
1644            operator_id: OperatorId,
1645            nominator_account: sp_runtime::AccountId32,
1646        ) -> Option<sp_domains::NominatorPosition<Balance, DomainNumber, Balance>> {
1647            Domains::nominator_position(operator_id, nominator_account)
1648        }
1649
1650        fn block_pruning_depth() -> NumberFor<Block> {
1651            BlockTreePruningDepth::get()
1652        }
1653    }
1654
1655    impl sp_domains::BundleProducerElectionApi<Block, Balance> for Runtime {
1656        fn bundle_producer_election_params(domain_id: DomainId) -> Option<BundleProducerElectionParams<Balance>> {
1657            Domains::bundle_producer_election_params(domain_id)
1658        }
1659
1660        fn operator(operator_id: OperatorId) -> Option<(OperatorPublicKey, Balance)> {
1661            Domains::operator(operator_id)
1662        }
1663    }
1664
1665    impl sp_session::SessionKeys<Block> for Runtime {
1666        fn generate_session_keys(
1667            owner: Vec<u8>,
1668            seed: Option<Vec<u8>>,
1669        ) -> sp_session::OpaqueGeneratedSessionKeys {
1670            SessionKeys::generate(&owner, seed).into()
1671        }
1672
1673        fn decode_session_keys(
1674            encoded: Vec<u8>,
1675        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
1676            SessionKeys::decode_into_raw_public_keys(&encoded)
1677        }
1678    }
1679
1680    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
1681        fn account_nonce(account: AccountId) -> Nonce {
1682            *System::account_nonce(account)
1683        }
1684    }
1685
1686    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
1687        fn query_info(
1688            uxt: ExtrinsicFor<Block>,
1689            len: u32,
1690        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
1691            TransactionPayment::query_info(uxt, len)
1692        }
1693        fn query_fee_details(
1694            uxt: ExtrinsicFor<Block>,
1695            len: u32,
1696        ) -> pallet_transaction_payment::FeeDetails<Balance> {
1697            TransactionPayment::query_fee_details(uxt, len)
1698        }
1699        fn query_weight_to_fee(weight: Weight) -> Balance {
1700            TransactionPayment::weight_to_fee(weight)
1701        }
1702        fn query_length_to_fee(length: u32) -> Balance {
1703            TransactionPayment::length_to_fee(length)
1704        }
1705    }
1706
1707    impl sp_messenger::MessengerApi<Block, BlockNumber, BlockHashFor<Block>> for Runtime {
1708        fn is_xdm_mmr_proof_valid(
1709            ext: &ExtrinsicFor<Block>
1710        ) -> Option<bool> {
1711            is_xdm_mmr_proof_valid(ext)
1712        }
1713
1714        fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<BlockNumber, BlockHashFor<Block>, sp_core::H256>> {
1715            match &ext.function {
1716                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1717                | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1718                    Some(msg.proof.consensus_mmr_proof())
1719                }
1720                _ => None,
1721            }
1722        }
1723
1724        fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<BlockNumber, BlockHashFor<Block>, sp_core::H256>> {
1725            let mut mmr_proofs = BTreeMap::new();
1726            for (index, ext) in extrinsics.iter().enumerate() {
1727                match &ext.function {
1728                    RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1729                    | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1730                        mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1731                    }
1732                    _ => {},
1733                }
1734            }
1735            mmr_proofs
1736        }
1737
1738        fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Vec<u8> {
1739            Domains::confirmed_domain_block_storage_key(domain_id)
1740        }
1741
1742        fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1743            Messenger::outbox_storage_key(message_key)
1744        }
1745
1746        fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1747            Messenger::inbox_response_storage_key(message_key)
1748        }
1749
1750        fn domain_chains_allowlist_update(domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1751            Messenger::domain_chains_allowlist_update(domain_id)
1752        }
1753
1754        fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1755            match &ext.function {
1756                RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1757                    Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1758                }
1759                RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1760                    Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1761                }
1762                _ => None,
1763            }
1764        }
1765
1766        fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1767            Messenger::channel_nonce(chain_id, channel_id)
1768        }
1769    }
1770
1771    impl sp_messenger::RelayerApi<Block, BlockNumber, BlockNumber, BlockHashFor<Block>> for Runtime {
1772        fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1773            Messenger::outbox_message_unsigned(msg)
1774        }
1775
1776        fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1777            Messenger::inbox_response_message_unsigned(msg)
1778        }
1779
1780        fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1781            Messenger::updated_channels()
1782        }
1783
1784        fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1785            Messenger::channel_storage_key(chain_id, channel_id)
1786        }
1787
1788        fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1789            Messenger::open_channels()
1790        }
1791
1792        fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1793            Messenger::get_block_messages(query)
1794        }
1795
1796        fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1797            Messenger::channels_and_states()
1798        }
1799
1800        fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1801            Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1802        }
1803
1804        fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1805            Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1806        }
1807    }
1808
1809    impl sp_domains_fraud_proof::FraudProofApi<Block, DomainHeader> for Runtime {
1810        fn submit_fraud_proof_unsigned(fraud_proof: FraudProof<NumberFor<Block>, BlockHashFor<Block>, DomainHeader, H256>) {
1811            Domains::submit_fraud_proof_unsigned(fraud_proof)
1812        }
1813
1814        fn fraud_proof_storage_key(req: FraudProofStorageKeyRequest<NumberFor<Block>>) -> Vec<u8> {
1815            <StorageKeyProvider as FraudProofStorageKeyProvider<NumberFor<Block>>>::storage_key(req)
1816        }
1817    }
1818
1819    impl mmr::MmrApi<Block, mmr::Hash, BlockNumber> for Runtime {
1820        fn mmr_root() -> Result<mmr::Hash, mmr::Error> {
1821            Ok(Mmr::mmr_root())
1822        }
1823
1824        fn mmr_leaf_count() -> Result<mmr::LeafIndex, mmr::Error> {
1825            Ok(Mmr::mmr_leaves())
1826        }
1827
1828        fn generate_proof(
1829            block_numbers: Vec<BlockNumber>,
1830            best_known_block_number: Option<BlockNumber>,
1831        ) -> Result<(Vec<mmr::EncodableOpaqueLeaf>, mmr::LeafProof<mmr::Hash>), mmr::Error> {
1832            Mmr::generate_proof(block_numbers, best_known_block_number).map(
1833                |(leaves, proof)| {
1834                    (
1835                        leaves
1836                            .into_iter()
1837                            .map(|leaf| mmr::EncodableOpaqueLeaf::from_leaf(&leaf))
1838                            .collect(),
1839                        proof,
1840                    )
1841                },
1842            )
1843        }
1844
1845        fn generate_ancestry_proof(
1846            prev_block_number: BlockNumber,
1847            best_known_block_number: Option<BlockNumber>,
1848        ) -> Result<mmr::AncestryProof<mmr::Hash>, mmr::Error> {
1849            Mmr::generate_ancestry_proof(prev_block_number, best_known_block_number)
1850        }
1851
1852        fn verify_proof(leaves: Vec<mmr::EncodableOpaqueLeaf>, proof: mmr::LeafProof<mmr::Hash>)
1853            -> Result<(), mmr::Error>
1854        {
1855            let leaves = leaves.into_iter().map(|leaf|
1856                leaf.into_opaque_leaf()
1857                .try_decode()
1858                .ok_or(mmr::Error::Verify)).collect::<Result<Vec<mmr::Leaf>, mmr::Error>>()?;
1859            Mmr::verify_leaves(leaves, proof)
1860        }
1861
1862        fn verify_proof_stateless(
1863            root: mmr::Hash,
1864            leaves: Vec<mmr::EncodableOpaqueLeaf>,
1865            proof: mmr::LeafProof<mmr::Hash>
1866        ) -> Result<(), mmr::Error> {
1867            let nodes = leaves.into_iter().map(|leaf|mmr::DataOrHash::Data(leaf.into_opaque_leaf())).collect();
1868            pallet_mmr::verify_leaves_proof::<mmr::Hashing, _>(root, nodes, proof)
1869        }
1870    }
1871
1872    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1873        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1874            build_state::<RuntimeGenesisConfig>(config)
1875        }
1876
1877        fn get_preset(_id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1878            // By passing `None` the upstream `get_preset` will return the default value of `RuntimeGenesisConfig`
1879            get_preset::<RuntimeGenesisConfig>(&None, |_| None)
1880        }
1881
1882        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1883            vec![]
1884        }
1885    }
1886
1887    #[cfg(feature = "runtime-benchmarks")]
1888    impl frame_benchmarking::Benchmark<Block> for Runtime {
1889        fn benchmark_metadata(extra: bool) -> (
1890            Vec<frame_benchmarking::BenchmarkList>,
1891            Vec<frame_support::traits::StorageInfo>,
1892        ) {
1893            use frame_benchmarking::{baseline, BenchmarkList};
1894            use frame_support::traits::StorageInfoTrait;
1895            use frame_system_benchmarking::Pallet as SystemBench;
1896            use baseline::Pallet as BaselineBench;
1897            use pallet_subspace::extensions::benchmarking::Pallet as SubspaceExtensionBench;
1898            use pallet_messenger::extensions::benchmarking_from_domains::Pallet as MessengerFromDomainsExtensionBench;
1899            use subspace_runtime_primitives::extension::benchmarking::Pallet as BalanceTransferCheckBench;
1900
1901            let mut list = Vec::<BenchmarkList>::new();
1902            list_benchmarks!(list, extra);
1903
1904            let storage_info = AllPalletsWithSystem::storage_info();
1905
1906            (list, storage_info)
1907        }
1908
1909        fn dispatch_benchmark(
1910            config: frame_benchmarking::BenchmarkConfig
1911        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1912            use frame_benchmarking::{baseline, BenchmarkBatch};
1913            use sp_core::storage::TrackedStorageKey;
1914
1915            use frame_system_benchmarking::Pallet as SystemBench;
1916            use baseline::Pallet as BaselineBench;
1917            use pallet_subspace::extensions::benchmarking::Pallet as SubspaceExtensionBench;
1918            use pallet_messenger::extensions::benchmarking_from_domains::Pallet as MessengerFromDomainsExtensionBench;
1919            use subspace_runtime_primitives::extension::benchmarking::Pallet as BalanceTransferCheckBench;
1920
1921            use frame_support::traits::WhitelistedStorageKeys;
1922            let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1923
1924            let mut batches = Vec::<BenchmarkBatch>::new();
1925            let params = (&config, &whitelist);
1926            add_benchmarks!(params, batches);
1927
1928            Ok(batches)
1929        }
1930    }
1931}
1932
1933#[cfg(test)]
1934mod tests {
1935    use crate::{
1936        AccountId, Balance, Executive, Runtime, RuntimeCall, SignedExtra,
1937        SubspaceBlockWeights as BlockWeights, System, UncheckedExtrinsic,
1938    };
1939    use pallet_domains::bundle_storage_fund::AccountType;
1940    use parity_scale_codec::Encode;
1941    use sp_core::{H256, Pair as _};
1942    use sp_domains::OperatorId;
1943    use sp_runtime::generic::{Era, SignedPayload};
1944    use sp_runtime::traits::{AccountIdConversion, TransactionExtension};
1945    use sp_runtime::transaction_validity::{InvalidTransaction, TransactionSource};
1946    use sp_runtime::{BuildStorage, MultiAddress, MultiSignature};
1947    use sp_std::prelude::*;
1948    use subspace_runtime_primitives::extension::SmallOrderEd25519CheckExtension;
1949    use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1950
1951    const INITIAL_BALANCE: Balance = 1_000_000_000_000_000_000;
1952
1953    fn ordinary_sr25519_pair() -> sp_core::sr25519::Pair {
1954        sp_core::sr25519::Pair::from_seed(&[3u8; 32])
1955    }
1956
1957    fn signed_extra(nonce: u32) -> SignedExtra {
1958        (
1959            (
1960                frame_system::CheckNonZeroSender::<Runtime>::new(),
1961                SmallOrderEd25519CheckExtension::<Runtime>::new(),
1962            ),
1963            frame_system::CheckSpecVersion::<Runtime>::new(),
1964            frame_system::CheckTxVersion::<Runtime>::new(),
1965            frame_system::CheckGenesis::<Runtime>::new(),
1966            frame_system::CheckMortality::<Runtime>::from(Era::Immortal),
1967            frame_system::CheckNonce::<Runtime>::from(nonce.into()),
1968            frame_system::CheckWeight::<Runtime>::new(),
1969            pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
1970            crate::BalanceTransferCheckExtension::<Runtime>::default(),
1971            pallet_subspace::extensions::SubspaceExtension::<Runtime>::new(),
1972            pallet_domains::extensions::DomainsExtension::<Runtime>::new(),
1973            pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
1974        )
1975    }
1976
1977    fn remark_call() -> RuntimeCall {
1978        RuntimeCall::System(frame_system::Call::remark { remark: vec![] })
1979    }
1980
1981    fn signing_payload(call: &RuntimeCall, extra: &SignedExtra) -> Vec<u8> {
1982        let implicit = <SignedExtra as TransactionExtension<RuntimeCall>>::implicit(extra)
1983            .expect("implicit data must be available in the test environment");
1984        SignedPayload::<RuntimeCall, SignedExtra>::from_raw(call.clone(), extra.clone(), implicit)
1985            .using_encoded(|encoded| encoded.to_vec())
1986    }
1987
1988    fn new_test_ext() -> sp_io::TestExternalities {
1989        let mut storage = frame_system::GenesisConfig::<Runtime>::default()
1990            .build_storage()
1991            .expect("default genesis builds");
1992        pallet_balances::GenesisConfig::<Runtime> {
1993            balances: vec![(
1994                AccountId::new(ordinary_sr25519_pair().public().to_raw()),
1995                INITIAL_BALANCE,
1996            )],
1997            dev_accounts: None,
1998        }
1999        .assimilate_storage(&mut storage)
2000        .expect("balances genesis assimilates");
2001
2002        let mut ext: sp_io::TestExternalities = storage.into();
2003        ext.execute_with(|| {
2004            System::set_block_number(1);
2005            // `CheckMortality` reads the birth block hash while signing.
2006            frame_system::BlockHash::<Runtime>::insert(0u32, H256::default());
2007        });
2008        ext
2009    }
2010
2011    #[test]
2012    fn multiplier_can_grow_from_zero() {
2013        FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
2014    }
2015
2016    #[test]
2017    fn test_bundle_storage_fund_account_uniqueness() {
2018        let _: <Runtime as frame_system::Config>::AccountId = <Runtime as pallet_domains::Config>::PalletId::get()
2019            .try_into_sub_account((AccountType::StorageFund, OperatorId::MAX))
2020            .expect(
2021                "The `AccountId` type must be large enough to fit the seed of the bundle storage fund account",
2022            );
2023    }
2024
2025    #[test]
2026    fn ordinary_sr25519_signed_extrinsic_validates() {
2027        new_test_ext().execute_with(|| {
2028            let pair = ordinary_sr25519_pair();
2029            let call = remark_call();
2030            let extra = signed_extra(0);
2031            let signature = MultiSignature::Sr25519(pair.sign(&signing_payload(&call, &extra)));
2032            let extrinsic = UncheckedExtrinsic::new_signed(
2033                call,
2034                MultiAddress::Id(AccountId::new(pair.public().to_raw())),
2035                signature,
2036                extra,
2037            );
2038
2039            let result = Executive::validate_transaction(
2040                TransactionSource::External,
2041                extrinsic,
2042                Default::default(),
2043            );
2044            assert!(
2045                result.is_ok(),
2046                "ordinary signed extrinsic rejected: {result:?}"
2047            );
2048        });
2049    }
2050
2051    #[test]
2052    fn small_order_ed25519_signed_extrinsic_is_rejected() {
2053        new_test_ext().execute_with(|| {
2054            // p - 1, an order-2 torsion point. Non-zero, so `CheckNonZeroSender` lets it
2055            // through and only the small-order check can reject it.
2056            let mut sender = [0xff; 32];
2057            sender[0] = 0xec;
2058            sender[31] = 0x7f;
2059
2060            // ZIP-215 cofactored verification accepts R = identity, S = 0 under any
2061            // small-order public key.
2062            let mut forged = [0u8; 64];
2063            forged[0] = 0x01;
2064            let signature = MultiSignature::Ed25519(sp_core::ed25519::Signature::from_raw(forged));
2065
2066            let extrinsic = UncheckedExtrinsic::new_signed(
2067                remark_call(),
2068                MultiAddress::Id(AccountId::new(sender)),
2069                signature,
2070                signed_extra(0),
2071            );
2072
2073            let result = Executive::validate_transaction(
2074                TransactionSource::External,
2075                extrinsic,
2076                Default::default(),
2077            );
2078            assert_eq!(result, Err(InvalidTransaction::BadSigner.into()));
2079        });
2080    }
2081}