1#![feature(variant_count)]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![recursion_limit = "256"]
5
6#[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::pallet_prelude::TypeInfo;
28use frame_support::traits::fungible::Credit;
29use frame_support::traits::{
30 ConstU16, ConstU32, ConstU64, Everything, Imbalance, IsInherent, OnUnbalanced, VariantCount,
31};
32use frame_support::weights::constants::ParityDbWeight;
33use frame_support::weights::{ConstantMultiplier, Weight};
34use frame_support::{construct_runtime, parameter_types};
35use frame_system::limits::{BlockLength, BlockWeights};
36use pallet_block_fees::fees::OnChargeDomainTransaction;
37use pallet_transporter::EndpointHandler;
38use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen};
39use sp_api::impl_runtime_apis;
40use sp_core::crypto::KeyTypeId;
41use sp_core::{Get, OpaqueMetadata};
42use sp_domains::{ChannelId, DomainAllowlistUpdates, DomainId, Transfers};
43use sp_messenger::endpoint::{Endpoint, EndpointHandler as EndpointHandlerT, EndpointId};
44use sp_messenger::messages::{
45 BlockMessagesWithStorageKey, ChainId, CrossDomainMessage, MessageId, MessageKey,
46};
47use sp_messenger::{ChannelNonce, XdmId};
48use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest};
49use sp_mmr_primitives::EncodableOpaqueLeaf;
50use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble};
51use sp_runtime::traits::{
52 AccountIdLookup, BlakeTwo256, Checkable, DispatchTransaction, Keccak256, NumberFor, One,
53 TransactionExtension, ValidateUnsigned, Zero,
54};
55use sp_runtime::transaction_validity::{
56 InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
57};
58use sp_runtime::type_with_default::TypeWithDefault;
59use sp_runtime::{generic, impl_opaque_keys, ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode};
60pub use sp_runtime::{MultiAddress, Perbill, Permill};
61use sp_std::collections::btree_map::BTreeMap;
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 BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor,
74 Hash as ConsensusBlockHash, HeaderFor, Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee,
75 XdmFeeMultipler, MAX_CALL_RECURSION_DEPTH, SHANNON, SSC,
76};
77
78pub type Block = generic::Block<Header, UncheckedExtrinsic>;
80
81pub type SignedBlock = generic::SignedBlock<Block>;
83
84pub type BlockId = generic::BlockId<Block>;
86
87pub 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
100pub 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
113pub type UncheckedExtrinsic =
115 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
116
117pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
119
120pub 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 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 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 type AccountId = AccountId;
158 type RuntimeCall = RuntimeCall;
160 type RuntimeTask = RuntimeTask;
162 type Lookup = AccountIdLookup<AccountId, ()>;
164 type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
166 type Hash = Hash;
168 type Hashing = BlakeTwo256;
170 type Block = Block;
172 type RuntimeEvent = RuntimeEvent;
174 type RuntimeOrigin = RuntimeOrigin;
176 type BlockHashCount = BlockHashCount;
178 type Version = Version;
180 type PalletInfo = PalletInfo;
182 type AccountData = pallet_balances::AccountData<Balance>;
184 type OnNewAccount = ();
186 type OnKilledAccount = ();
188 type DbWeight = ParityDbWeight;
190 type BaseCallFilter = Everything;
192 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
194 type BlockWeights = RuntimeBlockWeights;
196 type BlockLength = RuntimeBlockLength;
198 type SS58Prefix = ConstU16<6094>;
199 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 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
225pub 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 type Balance = Balance;
239 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 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#[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 pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
412}
413
414const_assert!(MaxOutgoingMessages::get() >= 1);
416
417impl pallet_messenger::Config for Runtime {
418 type RuntimeEvent = RuntimeEvent;
419 type SelfChainId = SelfChainId;
420
421 fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
422 if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
423 Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
424 } else {
425 None
426 }
427 }
428
429 type Currency = Balances;
430 type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
431 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
432 type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
433 type FeeMultiplier = XdmFeeMultipler;
434 type OnXDMRewards = OnXDMRewards;
435 type MmrHash = MmrHash;
436 type MmrProofVerifier = MmrProofVerifier;
437 type StorageKeys = StorageKeys;
438 type DomainOwner = ();
439 type HoldIdentifier = HoldIdentifierWrapper;
440 type ChannelReserveFee = ChannelReserveFee;
441 type ChannelInitReservePortion = ChannelInitReservePortion;
442 type DomainRegistration = ();
443 type MaxOutgoingMessages = MaxOutgoingMessages;
444 type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
445 type NoteChainTransfer = Transporter;
446}
447
448impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
449where
450 RuntimeCall: From<C>,
451{
452 type Extrinsic = UncheckedExtrinsic;
453 type RuntimeCall = RuntimeCall;
454}
455
456parameter_types! {
457 pub const TransporterEndpointId: EndpointId = 1;
458}
459
460impl pallet_transporter::Config for Runtime {
461 type RuntimeEvent = RuntimeEvent;
462 type SelfChainId = SelfChainId;
463 type SelfEndpointId = TransporterEndpointId;
464 type Currency = Balances;
465 type Sender = Messenger;
466 type AccountIdConverter = domain_runtime_primitives::AccountIdConverter;
467 type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
468 type SkipBalanceTransferChecks = ();
469}
470
471impl pallet_domain_id::Config for Runtime {}
472
473pub struct IntoRuntimeCall;
474
475impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
476 fn runtime_call(call: Vec<u8>) -> RuntimeCall {
477 UncheckedExtrinsic::decode(&mut call.as_slice())
478 .expect("must always be a valid extrinsic as checked by consensus chain; qed")
479 .function
480 }
481}
482
483impl pallet_domain_sudo::Config for Runtime {
484 type RuntimeEvent = RuntimeEvent;
485 type RuntimeCall = RuntimeCall;
486 type IntoRuntimeCall = IntoRuntimeCall;
487}
488
489impl pallet_utility::Config for Runtime {
490 type RuntimeEvent = RuntimeEvent;
491 type RuntimeCall = RuntimeCall;
492 type PalletsOrigin = OriginCaller;
493 type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
494}
495
496construct_runtime!(
500 pub struct Runtime {
501 System: frame_system = 0,
503 Timestamp: pallet_timestamp = 1,
507 ExecutivePallet: domain_pallet_executive = 2,
508 Utility: pallet_utility = 8,
509
510 Balances: pallet_balances = 20,
512 TransactionPayment: pallet_transaction_payment = 21,
513
514 AutoId: pallet_auto_id = 40,
516
517 Messenger: pallet_messenger = 60,
520 Transporter: pallet_transporter = 61,
521
522 SelfDomainId: pallet_domain_id = 90,
524 BlockFees: pallet_block_fees = 91,
525
526 Sudo: pallet_domain_sudo = 100,
528 }
529);
530
531impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
532 fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
533 match self {
534 RuntimeCall::Messenger(call) => Some(call),
535 _ => None,
536 }
537 }
538}
539
540impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
541where
542 RuntimeCall: From<C>,
543{
544 fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
545 create_unsigned_general_extrinsic(call)
546 }
547}
548
549fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
550 let extra: SignedExtra = (
551 frame_system::CheckNonZeroSender::<Runtime>::new(),
552 frame_system::CheckSpecVersion::<Runtime>::new(),
553 frame_system::CheckTxVersion::<Runtime>::new(),
554 frame_system::CheckGenesis::<Runtime>::new(),
555 frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
556 frame_system::CheckNonce::<Runtime>::from(0u32.into()),
559 domain_check_weight::CheckWeight::<Runtime>::new(),
560 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
563 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
564 );
565
566 UncheckedExtrinsic::new_transaction(call, extra)
567}
568
569fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
570 match &ext.function {
571 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
572 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
573 let ConsensusChainMmrLeafProof {
574 consensus_block_number,
575 opaque_mmr_leaf,
576 proof,
577 ..
578 } = msg.proof.consensus_mmr_proof();
579
580 if !is_consensus_block_finalized(consensus_block_number) {
581 return Some(false);
582 }
583
584 Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
585 }
586 _ => None,
587 }
588}
589
590fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
592 UncheckedExtrinsic::decode_with_depth_limit(
593 MAX_CALL_RECURSION_DEPTH,
594 &mut encoded_ext.as_slice(),
595 )
596 .is_ok()
597}
598
599fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> ExtrinsicFor<Block> {
600 let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
601 "must always be a valid extrinsic due to the check above and storage proof check; qed",
602 );
603 UncheckedExtrinsic::new_bare(
604 pallet_domain_sudo::Call::sudo {
605 call: Box::new(ext.function),
606 }
607 .into(),
608 )
609}
610
611fn extract_signer_inner<Lookup>(
612 ext: &UncheckedExtrinsic,
613 lookup: &Lookup,
614) -> Option<Result<AccountId, TransactionValidityError>>
615where
616 Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
617{
618 match &ext.preamble {
619 Preamble::Bare(_) | Preamble::General(_, _) => None,
620 Preamble::Signed(signed, _, _) => Some(lookup.lookup(signed.clone()).map_err(|e| e.into())),
621 }
622}
623
624pub fn extract_signer(
625 extrinsics: Vec<UncheckedExtrinsic>,
626) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
627 let lookup = frame_system::ChainContext::<Runtime>::default();
628
629 extrinsics
630 .into_iter()
631 .map(|extrinsic| {
632 let maybe_signer =
633 extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
634 account_result.ok().map(|account_id| account_id.encode())
635 });
636 (maybe_signer, extrinsic)
637 })
638 .collect()
639}
640
641fn extrinsic_era(extrinsic: &ExtrinsicFor<Block>) -> Option<Era> {
642 match &extrinsic.preamble {
643 Preamble::Bare(_) | Preamble::General(_, _) => None,
644 Preamble::Signed(_, _, extra) => Some(extra.4 .0),
645 }
646}
647
648#[cfg(feature = "runtime-benchmarks")]
649mod benches {
650 frame_benchmarking::define_benchmarks!(
651 [frame_benchmarking, BaselineBench::<Runtime>]
652 [frame_system, SystemBench::<Runtime>]
653 [domain_pallet_executive, ExecutivePallet]
654 [pallet_messenger, Messenger]
655 [pallet_auto_id, AutoId]
656 );
657}
658
659fn check_transaction_and_do_pre_dispatch_inner(
660 uxt: &ExtrinsicFor<Block>,
661) -> Result<(), TransactionValidityError> {
662 let lookup = frame_system::ChainContext::<Runtime>::default();
663
664 let xt = uxt.clone().check(&lookup)?;
665
666 let dispatch_info = xt.get_dispatch_info();
667
668 if dispatch_info.class == DispatchClass::Mandatory {
669 return Err(InvalidTransaction::MandatoryValidation.into());
670 }
671
672 let encoded_len = uxt.encoded_size();
673
674 match xt.format {
679 ExtrinsicFormat::General(extension_version, extra) => {
680 let custom_extra: CustomSignedExtra = (
681 extra.0,
682 extra.1,
683 extra.2,
684 extra.3,
685 extra.4,
686 extra.5,
687 extra.6.clone(),
688 extra.7,
689 pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
690 );
691
692 let origin = RuntimeOrigin::none();
693 <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
694 custom_extra,
695 origin,
696 &xt.function,
697 &dispatch_info,
698 encoded_len,
699 extension_version,
700 )
701 .map(|_| ())
702 }
703 ExtrinsicFormat::Signed(account_id, extra) => {
705 let origin = RuntimeOrigin::signed(account_id);
706 <SignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
707 extra,
708 origin,
709 &xt.function,
710 &dispatch_info,
711 encoded_len,
712 0,
715 )
716 .map(|_| ())
717 }
718 ExtrinsicFormat::Bare => {
720 Runtime::pre_dispatch(&xt.function).map(|_| ())?;
721 <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
722 &xt.function,
723 &dispatch_info,
724 encoded_len,
725 )
726 .map(|_| ())
727 }
728 }
729}
730
731#[cfg(feature = "runtime-benchmarks")]
732impl frame_system_benchmarking::Config for Runtime {}
733
734#[cfg(feature = "runtime-benchmarks")]
735impl frame_benchmarking::baseline::Config for Runtime {}
736
737impl_runtime_apis! {
738 impl sp_api::Core<Block> for Runtime {
739 fn version() -> RuntimeVersion {
740 VERSION
741 }
742
743 fn execute_block(block: Block) {
744 Executive::execute_block(block)
745 }
746
747 fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
748 Executive::initialize_block(header)
749 }
750 }
751
752 impl sp_api::Metadata<Block> for Runtime {
753 fn metadata() -> OpaqueMetadata {
754 OpaqueMetadata::new(Runtime::metadata().into())
755 }
756
757 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
758 Runtime::metadata_at_version(version)
759 }
760
761 fn metadata_versions() -> Vec<u32> {
762 Runtime::metadata_versions()
763 }
764 }
765
766 impl sp_block_builder::BlockBuilder<Block> for Runtime {
767 fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
768 Executive::apply_extrinsic(extrinsic)
769 }
770
771 fn finalize_block() -> HeaderFor<Block> {
772 Executive::finalize_block()
773 }
774
775 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
776 data.create_extrinsics()
777 }
778
779 fn check_inherents(
780 block: Block,
781 data: sp_inherents::InherentData,
782 ) -> sp_inherents::CheckInherentsResult {
783 data.check_extrinsics(&block)
784 }
785 }
786
787 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
788 fn validate_transaction(
789 source: TransactionSource,
790 tx: ExtrinsicFor<Block>,
791 block_hash: BlockHashFor<Block>,
792 ) -> TransactionValidity {
793 Executive::validate_transaction(source, tx, block_hash)
794 }
795 }
796
797 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
798 fn offchain_worker(header: &HeaderFor<Block>) {
799 Executive::offchain_worker(header)
800 }
801 }
802
803 impl sp_session::SessionKeys<Block> for Runtime {
804 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
805 SessionKeys::generate(seed)
806 }
807
808 fn decode_session_keys(
809 encoded: Vec<u8>,
810 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
811 SessionKeys::decode_into_raw_public_keys(&encoded)
812 }
813 }
814
815 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
816 fn account_nonce(account: AccountId) -> Nonce {
817 *System::account_nonce(account)
818 }
819 }
820
821 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
822 fn query_info(
823 uxt: ExtrinsicFor<Block>,
824 len: u32,
825 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
826 TransactionPayment::query_info(uxt, len)
827 }
828 fn query_fee_details(
829 uxt: ExtrinsicFor<Block>,
830 len: u32,
831 ) -> pallet_transaction_payment::FeeDetails<Balance> {
832 TransactionPayment::query_fee_details(uxt, len)
833 }
834 fn query_weight_to_fee(weight: Weight) -> Balance {
835 TransactionPayment::weight_to_fee(weight)
836 }
837 fn query_length_to_fee(length: u32) -> Balance {
838 TransactionPayment::length_to_fee(length)
839 }
840 }
841
842 impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
843 fn extract_signer(
844 extrinsics: Vec<ExtrinsicFor<Block>>,
845 ) -> Vec<(Option<opaque::AccountId>, ExtrinsicFor<Block>)> {
846 extract_signer(extrinsics)
847 }
848
849 fn is_within_tx_range(
850 extrinsic: &ExtrinsicFor<Block>,
851 bundle_vrf_hash: &subspace_core_primitives::U256,
852 tx_range: &subspace_core_primitives::U256
853 ) -> bool {
854 use subspace_core_primitives::U256;
855 use subspace_core_primitives::hashes::blake3_hash;
856
857 let lookup = frame_system::ChainContext::<Runtime>::default();
858 if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
859 account_result.ok().map(|account_id| account_id.encode())
860 }) {
861 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
863 sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
864 } else {
865 true
867 }
868 }
869
870 fn extract_signer_if_all_within_tx_range(
871 extrinsics: &Vec<ExtrinsicFor<Block>>,
872 bundle_vrf_hash: &subspace_core_primitives::U256,
873 tx_range: &subspace_core_primitives::U256
874 ) -> Result<Vec<Option<opaque::AccountId>> , u32> {
875 use subspace_core_primitives::U256;
876 use subspace_core_primitives::hashes::blake3_hash;
877
878 let mut signers = Vec::with_capacity(extrinsics.len());
879 let lookup = frame_system::ChainContext::<Runtime>::default();
880 for (index, extrinsic) in extrinsics.iter().enumerate() {
881 let maybe_signer = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
882 account_result.ok().map(|account_id| account_id.encode())
883 });
884 if let Some(signer) = &maybe_signer {
885 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
887 if !sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) {
888 return Err(index as u32)
889 }
890 }
891 signers.push(maybe_signer);
892 }
893
894 Ok(signers)
895 }
896
897 fn initialize_block_with_post_state_root(header: &HeaderFor<Block>) -> Vec<u8> {
898 Executive::initialize_block(header);
899 Executive::storage_root()
900 }
901
902 fn apply_extrinsic_with_post_state_root(extrinsic: ExtrinsicFor<Block>) -> Vec<u8> {
903 let _ = Executive::apply_extrinsic(extrinsic);
904 Executive::storage_root()
905 }
906
907 fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
908 UncheckedExtrinsic::new_bare(
909 domain_pallet_executive::Call::set_code {
910 code
911 }.into()
912 ).encode()
913 }
914
915 fn construct_timestamp_extrinsic(moment: Moment) -> ExtrinsicFor<Block> {
916 UncheckedExtrinsic::new_bare(
917 pallet_timestamp::Call::set{ now: moment }.into()
918 )
919 }
920
921 fn is_inherent_extrinsic(extrinsic: &ExtrinsicFor<Block>) -> bool {
922 <Self as IsInherent<_>>::is_inherent(extrinsic)
923 }
924
925 fn find_first_inherent_extrinsic(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Option<u32> {
926 for (index, extrinsic) in extrinsics.iter().enumerate() {
927 if <Self as IsInherent<_>>::is_inherent(extrinsic) {
928 return Some(index as u32)
929 }
930 }
931 None
932 }
933
934 fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<ExtrinsicFor<Block>>, block_number: BlockNumber,
935 block_hash: BlockHashFor<Block>) -> Result<(), CheckExtrinsicsValidityError> {
936 System::initialize(
938 &(block_number + BlockNumber::one()),
939 &block_hash,
940 &Default::default(),
941 );
942
943 for (extrinsic_index, uxt) in uxts.iter().enumerate() {
944 check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
945 CheckExtrinsicsValidityError {
946 extrinsic_index: extrinsic_index as u32,
947 transaction_validity_error: e
948 }
949 })?;
950 }
951
952 Ok(())
953 }
954
955 fn decode_extrinsic(
956 opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
957 ) -> Result<ExtrinsicFor<Block>, DecodeExtrinsicError> {
958 let encoded = opaque_extrinsic.encode();
959
960 UncheckedExtrinsic::decode_with_depth_limit(
961 MAX_CALL_RECURSION_DEPTH,
962 &mut encoded.as_slice(),
963 ).map_err(|err| DecodeExtrinsicError(format!("{}", err)))
964 }
965
966 fn decode_extrinsics_prefix(
967 opaque_extrinsics: Vec<sp_runtime::OpaqueExtrinsic>,
968 ) -> Vec<ExtrinsicFor<Block>> {
969 let mut extrinsics = Vec::with_capacity(opaque_extrinsics.len());
970 for opaque_ext in opaque_extrinsics {
971 match UncheckedExtrinsic::decode_with_depth_limit(
972 MAX_CALL_RECURSION_DEPTH,
973 &mut opaque_ext.encode().as_slice(),
974 ) {
975 Ok(tx) => extrinsics.push(tx),
976 Err(_) => return extrinsics,
977 }
978 }
979 extrinsics
980 }
981
982 fn extrinsic_era(
983 extrinsic: &ExtrinsicFor<Block>
984 ) -> Option<Era> {
985 extrinsic_era(extrinsic)
986 }
987
988 fn extrinsic_weight(ext: &ExtrinsicFor<Block>) -> Weight {
989 let len = ext.encoded_size() as u64;
990 let info = ext.get_dispatch_info();
991 info.call_weight.saturating_add(info.extension_weight)
992 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
993 .saturating_add(Weight::from_parts(0, len))
994 }
995
996 fn extrinsics_weight(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Weight {
997 let mut total_weight = Weight::zero();
998 for ext in extrinsics {
999 let ext_weight = {
1000 let len = ext.encoded_size() as u64;
1001 let info = ext.get_dispatch_info();
1002 info.call_weight.saturating_add(info.extension_weight)
1003 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1004 .saturating_add(Weight::from_parts(0, len))
1005 };
1006 total_weight = total_weight.saturating_add(ext_weight);
1007 }
1008 total_weight
1009 }
1010
1011 fn block_fees() -> sp_domains::BlockFees<Balance> {
1012 BlockFees::collected_block_fees()
1013 }
1014
1015 fn block_digest() -> Digest {
1016 System::digest()
1017 }
1018
1019 fn block_weight() -> Weight {
1020 System::block_weight().total()
1021 }
1022
1023 fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> ExtrinsicFor<Block> {
1024 UncheckedExtrinsic::new_bare(
1025 pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
1026 )
1027 }
1028
1029 fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> ExtrinsicFor<Block> {
1030 UncheckedExtrinsic::new_bare(
1031 pallet_messenger::Call::update_domain_allowlist{ updates }.into()
1032 )
1033 }
1034
1035 fn transfers() -> Transfers<Balance> {
1036 Transporter::chain_transfers()
1037 }
1038
1039 fn transfers_storage_key() -> Vec<u8> {
1040 Transporter::transfers_storage_key()
1041 }
1042
1043 fn block_fees_storage_key() -> Vec<u8> {
1044 BlockFees::block_fees_storage_key()
1045 }
1046 }
1047
1048 impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1049 fn is_xdm_mmr_proof_valid(
1050 extrinsic: &ExtrinsicFor<Block>,
1051 ) -> Option<bool> {
1052 is_xdm_mmr_proof_valid(extrinsic)
1053 }
1054
1055 fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1056 match &ext.function {
1057 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1058 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1059 Some(msg.proof.consensus_mmr_proof())
1060 }
1061 _ => None,
1062 }
1063 }
1064
1065 fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1066 let mut mmr_proofs = BTreeMap::new();
1067 for (index, ext) in extrinsics.iter().enumerate() {
1068 match &ext.function {
1069 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1070 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1071 mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1072 }
1073 _ => {},
1074 }
1075 }
1076 mmr_proofs
1077 }
1078
1079 fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1080 vec![]
1082 }
1083
1084 fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1085 Messenger::outbox_storage_key(message_key)
1086 }
1087
1088 fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1089 Messenger::inbox_response_storage_key(message_key)
1090 }
1091
1092 fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1093 None
1095 }
1096
1097 fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1098 match &ext.function {
1099 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1100 Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1101 }
1102 RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1103 Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1104 }
1105 _ => None,
1106 }
1107 }
1108
1109 fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1110 Messenger::channel_nonce(chain_id, channel_id)
1111 }
1112 }
1113
1114 impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1115 fn block_messages() -> BlockMessagesWithStorageKey {
1116 Messenger::get_block_messages()
1117 }
1118
1119 fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1120 Messenger::outbox_message_unsigned(msg)
1121 }
1122
1123 fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1124 Messenger::inbox_response_message_unsigned(msg)
1125 }
1126
1127 fn should_relay_outbox_message(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1128 Messenger::should_relay_outbox_message(dst_chain_id, msg_id)
1129 }
1130
1131 fn should_relay_inbox_message_response(dst_chain_id: ChainId, msg_id: MessageId) -> bool {
1132 Messenger::should_relay_inbox_message_response(dst_chain_id, msg_id)
1133 }
1134
1135 fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1136 Messenger::updated_channels()
1137 }
1138
1139 fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1140 Messenger::channel_storage_key(chain_id, channel_id)
1141 }
1142
1143 fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1144 Messenger::open_channels()
1145 }
1146 }
1147
1148 impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1149 fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1150 is_valid_sudo_call(extrinsic)
1151 }
1152
1153 fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> ExtrinsicFor<Block> {
1154 construct_sudo_call_extrinsic(inner)
1155 }
1156 }
1157
1158 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1159 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1160 build_state::<RuntimeGenesisConfig>(config)
1161 }
1162
1163 fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1164 get_preset::<RuntimeGenesisConfig>(id, |_| None)
1165 }
1166
1167 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1168 vec![]
1169 }
1170 }
1171
1172 #[cfg(feature = "runtime-benchmarks")]
1173 impl frame_benchmarking::Benchmark<Block> for Runtime {
1174 fn benchmark_metadata(extra: bool) -> (
1175 Vec<frame_benchmarking::BenchmarkList>,
1176 Vec<frame_support::traits::StorageInfo>,
1177 ) {
1178 use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1179 use frame_support::traits::StorageInfoTrait;
1180 use frame_system_benchmarking::Pallet as SystemBench;
1181 use baseline::Pallet as BaselineBench;
1182
1183 let mut list = Vec::<BenchmarkList>::new();
1184
1185 list_benchmarks!(list, extra);
1186
1187 let storage_info = AllPalletsWithSystem::storage_info();
1188
1189 (list, storage_info)
1190 }
1191
1192 fn dispatch_benchmark(
1193 config: frame_benchmarking::BenchmarkConfig
1194 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1195 use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1196 use sp_storage::TrackedStorageKey;
1197 use frame_system_benchmarking::Pallet as SystemBench;
1198 use frame_support::traits::WhitelistedStorageKeys;
1199 use baseline::Pallet as BaselineBench;
1200
1201 let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1202
1203 let mut batches = Vec::<BenchmarkBatch>::new();
1204 let params = (&config, &whitelist);
1205
1206 add_benchmarks!(params, batches);
1207
1208 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1209 Ok(batches)
1210 }
1211 }
1212}
1213
1214#[cfg(test)]
1215mod tests {
1216 use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1217 use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1218
1219 #[test]
1220 fn multiplier_can_grow_from_zero() {
1221 FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1222 }
1223}