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;
17use domain_runtime_primitives::{
18 AccountId, Address, CheckExtrinsicsValidityError, DecodeExtrinsicError, ERR_BALANCE_OVERFLOW,
19 HoldIdentifier, SLOT_DURATION, Signature, TargetBlockFullness,
20};
21pub use domain_runtime_primitives::{
22 Balance, BlockNumber, EXISTENTIAL_DEPOSIT, Hash, MAX_OUTGOING_MESSAGES, Nonce, block_weights,
23 maximum_block_length, opaque,
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 BlockMessagesQuery, BlockMessagesWithStorageKey, ChainId, ChannelStateWithNonce,
46 CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce,
47};
48use sp_messenger::{ChannelNonce, XdmId};
49use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key};
50use sp_mmr_primitives::EncodableOpaqueLeaf;
51use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble};
52use sp_runtime::traits::{
53 AccountIdLookup, BlakeTwo256, Checkable, DispatchTransaction, Keccak256, NumberFor, One,
54 TransactionExtension, ValidateUnsigned, Zero,
55};
56use sp_runtime::transaction_validity::{
57 InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
58};
59use sp_runtime::type_with_default::TypeWithDefault;
60use sp_runtime::{ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode, generic, impl_opaque_keys};
61pub use sp_runtime::{MultiAddress, Perbill, Permill};
62use sp_std::collections::btree_map::BTreeMap;
63use sp_std::collections::btree_set::BTreeSet;
64use sp_std::marker::PhantomData;
65use sp_std::prelude::*;
66use sp_subspace_mmr::domain_mmr_runtime_interface::{
67 is_consensus_block_finalized, verify_mmr_proof,
68};
69use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrLeaf};
70use sp_version::RuntimeVersion;
71use static_assertions::const_assert;
72use subspace_runtime_primitives::utility::DefaultNonceProvider;
73use subspace_runtime_primitives::{
74 AI3, BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor,
75 Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment, SHANNON,
76 SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler,
77};
78
79pub type Block = generic::Block<Header, UncheckedExtrinsic>;
81
82pub type SignedBlock = generic::SignedBlock<Block>;
84
85pub type BlockId = generic::BlockId<Block>;
87
88pub type SignedExtra = (
90 frame_system::CheckNonZeroSender<Runtime>,
91 frame_system::CheckSpecVersion<Runtime>,
92 frame_system::CheckTxVersion<Runtime>,
93 frame_system::CheckGenesis<Runtime>,
94 frame_system::CheckMortality<Runtime>,
95 frame_system::CheckNonce<Runtime>,
96 domain_check_weight::CheckWeight<Runtime>,
97 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
98 pallet_messenger::extensions::MessengerExtension<Runtime>,
99);
100
101pub type CustomSignedExtra = (
103 frame_system::CheckNonZeroSender<Runtime>,
104 frame_system::CheckSpecVersion<Runtime>,
105 frame_system::CheckTxVersion<Runtime>,
106 frame_system::CheckGenesis<Runtime>,
107 frame_system::CheckMortality<Runtime>,
108 frame_system::CheckNonce<Runtime>,
109 domain_check_weight::CheckWeight<Runtime>,
110 pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
111 pallet_messenger::extensions::MessengerTrustedMmrExtension<Runtime>,
112);
113
114pub type UncheckedExtrinsic =
116 generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
117
118pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
120
121pub type Executive = domain_pallet_executive::Executive<
123 Runtime,
124 frame_system::ChainContext<Runtime>,
125 Runtime,
126 AllPalletsWithSystem,
127>;
128
129impl_opaque_keys! {
130 pub struct SessionKeys {
131 pub operator: sp_domains::OperatorKey,
133 }
134}
135
136#[sp_version::runtime_version]
137pub const VERSION: RuntimeVersion = RuntimeVersion {
138 spec_name: Cow::Borrowed("subspace-auto-id-domain"),
139 impl_name: Cow::Borrowed("subspace-auto-id-domain"),
140 authoring_version: 0,
141 spec_version: 0,
143 impl_version: 0,
144 apis: RUNTIME_API_VERSIONS,
145 transaction_version: 0,
146 system_version: 2,
147};
148
149parameter_types! {
150 pub const Version: RuntimeVersion = VERSION;
151 pub const BlockHashCount: BlockNumber = 2400;
152 pub RuntimeBlockLength: BlockLength = maximum_block_length();
153 pub RuntimeBlockWeights: BlockWeights = block_weights();
154}
155
156impl frame_system::Config for Runtime {
157 type AccountId = AccountId;
159 type RuntimeCall = RuntimeCall;
161 type RuntimeTask = RuntimeTask;
163 type Lookup = AccountIdLookup<AccountId, ()>;
165 type Nonce = TypeWithDefault<Nonce, DefaultNonceProvider<System, Nonce>>;
167 type Hash = Hash;
169 type Hashing = BlakeTwo256;
171 type Block = Block;
173 type RuntimeEvent = RuntimeEvent;
175 type RuntimeOrigin = RuntimeOrigin;
177 type BlockHashCount = BlockHashCount;
179 type Version = Version;
181 type PalletInfo = PalletInfo;
183 type AccountData = pallet_balances::AccountData<Balance>;
185 type OnNewAccount = ();
187 type OnKilledAccount = ();
189 type DbWeight = ParityDbWeight;
191 type BaseCallFilter = Everything;
193 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Runtime>;
195 type BlockWeights = RuntimeBlockWeights;
197 type BlockLength = RuntimeBlockLength;
199 type SS58Prefix = ConstU16<6094>;
200 type OnSetCode = ();
202 type SingleBlockMigrations = ();
203 type MultiBlockMigrator = ();
204 type PreInherents = ();
205 type PostInherents = ();
206 type PostTransactions = ();
207 type MaxConsumers = ConstU32<16>;
208 type ExtensionsWeightInfo = frame_system::ExtensionsWeight<Runtime>;
209 type EventSegmentSize = DomainEventSegmentSize;
210}
211
212impl pallet_timestamp::Config for Runtime {
213 type Moment = Moment;
215 type OnTimestampSet = ();
216 type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>;
217 type WeightInfo = pallet_timestamp::weights::SubstrateWeight<Runtime>;
218}
219
220parameter_types! {
221 pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
222 pub const MaxLocks: u32 = 50;
223 pub const MaxReserves: u32 = 50;
224}
225
226pub struct DustRemovalHandler;
228
229impl OnUnbalanced<Credit<AccountId, Balances>> for DustRemovalHandler {
230 fn on_nonzero_unbalanced(dusted_amount: Credit<AccountId, Balances>) {
231 BlockFees::note_burned_balance(dusted_amount.peek());
232 }
233}
234
235impl pallet_balances::Config for Runtime {
236 type RuntimeFreezeReason = RuntimeFreezeReason;
237 type MaxLocks = MaxLocks;
238 type Balance = Balance;
240 type RuntimeEvent = RuntimeEvent;
242 type DustRemoval = DustRemovalHandler;
243 type ExistentialDeposit = ExistentialDeposit;
244 type AccountStore = System;
245 type WeightInfo = pallet_balances::weights::SubstrateWeight<Runtime>;
246 type MaxReserves = MaxReserves;
247 type ReserveIdentifier = [u8; 8];
248 type FreezeIdentifier = ();
249 type MaxFreezes = ();
250 type RuntimeHoldReason = HoldIdentifierWrapper;
251 type DoneSlashHandler = ();
252}
253
254parameter_types! {
255 pub const OperationalFeeMultiplier: u8 = 5;
256 pub const DomainChainByteFee: Balance = 1;
257 pub TransactionWeightFee: Balance = 100_000 * SHANNON;
258}
259
260impl pallet_block_fees::Config for Runtime {
261 type Balance = Balance;
262 type DomainChainByteFee = DomainChainByteFee;
263}
264
265pub struct FinalDomainTransactionByteFee;
266
267impl Get<Balance> for FinalDomainTransactionByteFee {
268 fn get() -> Balance {
269 BlockFees::final_domain_transaction_byte_fee()
270 }
271}
272
273impl pallet_transaction_payment::Config for Runtime {
274 type RuntimeEvent = RuntimeEvent;
275 type OnChargeTransaction = OnChargeDomainTransaction<Balances>;
276 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
277 type LengthToFee = ConstantMultiplier<Balance, FinalDomainTransactionByteFee>;
278 type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Runtime, TargetBlockFullness>;
279 type OperationalFeeMultiplier = OperationalFeeMultiplier;
280 type WeightInfo = pallet_transaction_payment::weights::SubstrateWeight<Runtime>;
281}
282
283impl pallet_auto_id::Config for Runtime {
284 type RuntimeEvent = RuntimeEvent;
285 type Time = Timestamp;
286 type Weights = pallet_auto_id::weights::SubstrateWeight<Self>;
287}
288
289pub struct ExtrinsicStorageFees;
290
291impl domain_pallet_executive::ExtrinsicStorageFees<Runtime> for ExtrinsicStorageFees {
292 fn extract_signer(xt: UncheckedExtrinsic) -> (Option<AccountId>, DispatchInfo) {
293 let dispatch_info = xt.get_dispatch_info();
294 let lookup = frame_system::ChainContext::<Runtime>::default();
295 let maybe_signer = extract_signer_inner(&xt, &lookup).and_then(|res| res.ok());
296 (maybe_signer, dispatch_info)
297 }
298
299 fn on_storage_fees_charged(
300 charged_fees: Balance,
301 tx_size: u32,
302 ) -> Result<(), TransactionValidityError> {
303 let consensus_storage_fee = BlockFees::consensus_chain_byte_fee()
304 .checked_mul(Balance::from(tx_size))
305 .ok_or(InvalidTransaction::Custom(ERR_BALANCE_OVERFLOW))?;
306
307 let (paid_consensus_storage_fee, paid_domain_fee) = if charged_fees <= consensus_storage_fee
308 {
309 (charged_fees, Zero::zero())
310 } else {
311 (consensus_storage_fee, charged_fees - consensus_storage_fee)
312 };
313
314 BlockFees::note_consensus_storage_fee(paid_consensus_storage_fee);
315 BlockFees::note_domain_execution_fee(paid_domain_fee);
316 Ok(())
317 }
318}
319
320impl domain_pallet_executive::Config for Runtime {
321 type RuntimeEvent = RuntimeEvent;
322 type WeightInfo = domain_pallet_executive::weights::SubstrateWeight<Runtime>;
323 type Currency = Balances;
324 type LengthToFee = <Runtime as pallet_transaction_payment::Config>::LengthToFee;
325 type ExtrinsicStorageFees = ExtrinsicStorageFees;
326}
327
328parameter_types! {
329 pub SelfChainId: ChainId = SelfDomainId::self_domain_id().into();
330}
331
332pub struct OnXDMRewards;
333
334impl sp_messenger::OnXDMRewards<Balance> for OnXDMRewards {
335 fn on_xdm_rewards(rewards: Balance) {
336 BlockFees::note_domain_execution_fee(rewards)
337 }
338 fn on_chain_protocol_fees(chain_id: ChainId, fees: Balance) {
339 BlockFees::note_chain_rewards(chain_id, fees);
341 }
342}
343
344type MmrHash = <Keccak256 as sp_runtime::traits::Hash>::Output;
345
346pub struct MmrProofVerifier;
347
348impl sp_subspace_mmr::MmrProofVerifier<MmrHash, NumberFor<Block>, Hash> for MmrProofVerifier {
349 fn verify_proof_and_extract_leaf(
350 mmr_leaf_proof: ConsensusChainMmrLeafProof<NumberFor<Block>, Hash, MmrHash>,
351 ) -> Option<MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash>> {
352 let ConsensusChainMmrLeafProof {
353 consensus_block_number,
354 opaque_mmr_leaf: opaque_leaf,
355 proof,
356 ..
357 } = mmr_leaf_proof;
358
359 if !is_consensus_block_finalized(consensus_block_number) {
360 return None;
361 }
362
363 let leaf: MmrLeaf<ConsensusBlockNumber, ConsensusBlockHash> =
364 opaque_leaf.into_opaque_leaf().try_decode()?;
365
366 verify_mmr_proof(vec![EncodableOpaqueLeaf::from_leaf(&leaf)], proof.encode())
367 .then_some(leaf)
368 }
369}
370
371pub struct StorageKeys;
372
373impl sp_messenger::StorageKeys for StorageKeys {
374 fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Option<Vec<u8>> {
375 get_storage_key(StorageKeyRequest::ConfirmedDomainBlockStorageKey(domain_id))
376 }
377
378 fn outbox_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
379 get_storage_key(StorageKeyRequest::OutboxStorageKey {
380 chain_id,
381 message_key,
382 })
383 }
384
385 fn inbox_responses_storage_key(chain_id: ChainId, message_key: MessageKey) -> Option<Vec<u8>> {
386 get_storage_key(StorageKeyRequest::InboxResponseStorageKey {
387 chain_id,
388 message_key,
389 })
390 }
391}
392
393#[derive(
395 PartialEq, Eq, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Ord, PartialOrd, Copy, Debug,
396)]
397pub struct HoldIdentifierWrapper(HoldIdentifier);
398
399impl VariantCount for HoldIdentifierWrapper {
400 const VARIANT_COUNT: u32 = mem::variant_count::<HoldIdentifier>() as u32;
401}
402
403impl pallet_messenger::HoldIdentifier<Runtime> for HoldIdentifierWrapper {
404 fn messenger_channel() -> Self {
405 Self(HoldIdentifier::MessengerChannel)
406 }
407}
408
409parameter_types! {
410 pub const ChannelReserveFee: Balance = 100 * AI3;
411 pub const ChannelInitReservePortion: Perbill = Perbill::from_percent(20);
412 pub const MaxOutgoingMessages: u32 = MAX_OUTGOING_MESSAGES;
413}
414
415const_assert!(MaxOutgoingMessages::get() >= 1);
417
418impl pallet_messenger::Config for Runtime {
419 type RuntimeEvent = RuntimeEvent;
420 type SelfChainId = SelfChainId;
421
422 fn get_endpoint_handler(endpoint: &Endpoint) -> Option<Box<dyn EndpointHandlerT<MessageId>>> {
423 if endpoint == &Endpoint::Id(TransporterEndpointId::get()) {
424 Some(Box::new(EndpointHandler(PhantomData::<Runtime>)))
425 } else {
426 None
427 }
428 }
429
430 type Currency = Balances;
431 type WeightInfo = pallet_messenger::weights::SubstrateWeight<Runtime>;
432 type WeightToFee = ConstantMultiplier<Balance, TransactionWeightFee>;
433 type AdjustedWeightToFee = XdmAdjustedWeightToFee<Runtime>;
434 type FeeMultiplier = XdmFeeMultipler;
435 type OnXDMRewards = OnXDMRewards;
436 type MmrHash = MmrHash;
437 type MmrProofVerifier = MmrProofVerifier;
438 type StorageKeys = StorageKeys;
439 type DomainOwner = ();
440 type HoldIdentifier = HoldIdentifierWrapper;
441 type ChannelReserveFee = ChannelReserveFee;
442 type ChannelInitReservePortion = ChannelInitReservePortion;
443 type DomainRegistration = ();
444 type MaxOutgoingMessages = MaxOutgoingMessages;
445 type MessengerOrigin = pallet_messenger::EnsureMessengerOrigin;
446 type NoteChainTransfer = Transporter;
447 type ExtensionWeightInfo = pallet_messenger::extensions::weights::SubstrateWeight<Runtime>;
448}
449
450impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
451where
452 RuntimeCall: From<C>,
453{
454 type Extrinsic = UncheckedExtrinsic;
455 type RuntimeCall = RuntimeCall;
456}
457
458parameter_types! {
459 pub const TransporterEndpointId: EndpointId = 1;
460 pub const MinimumTransfer: Balance = AI3;
461}
462
463impl pallet_transporter::Config for Runtime {
464 type RuntimeEvent = RuntimeEvent;
465 type SelfChainId = SelfChainId;
466 type SelfEndpointId = TransporterEndpointId;
467 type Currency = Balances;
468 type Sender = Messenger;
469 type AccountIdConverter = domain_runtime_primitives::AccountIdConverter;
470 type WeightInfo = pallet_transporter::weights::SubstrateWeight<Runtime>;
471 type SkipBalanceTransferChecks = ();
472 type MinimumTransfer = MinimumTransfer;
473}
474
475impl pallet_domain_id::Config for Runtime {}
476
477pub struct IntoRuntimeCall;
478
479impl sp_domain_sudo::IntoRuntimeCall<RuntimeCall> for IntoRuntimeCall {
480 fn runtime_call(call: Vec<u8>) -> RuntimeCall {
481 UncheckedExtrinsic::decode(&mut call.as_slice())
482 .expect("must always be a valid extrinsic as checked by consensus chain; qed")
483 .function
484 }
485}
486
487impl pallet_domain_sudo::Config for Runtime {
488 type RuntimeEvent = RuntimeEvent;
489 type RuntimeCall = RuntimeCall;
490 type IntoRuntimeCall = IntoRuntimeCall;
491}
492
493impl pallet_utility::Config for Runtime {
494 type RuntimeEvent = RuntimeEvent;
495 type RuntimeCall = RuntimeCall;
496 type PalletsOrigin = OriginCaller;
497 type WeightInfo = pallet_utility::weights::SubstrateWeight<Runtime>;
498}
499
500construct_runtime!(
504 pub struct Runtime {
505 System: frame_system = 0,
507 Timestamp: pallet_timestamp = 1,
511 ExecutivePallet: domain_pallet_executive = 2,
512 Utility: pallet_utility = 8,
513
514 Balances: pallet_balances = 20,
516 TransactionPayment: pallet_transaction_payment = 21,
517
518 AutoId: pallet_auto_id = 40,
520
521 Messenger: pallet_messenger = 60,
524 Transporter: pallet_transporter = 61,
525
526 SelfDomainId: pallet_domain_id = 90,
528 BlockFees: pallet_block_fees = 91,
529
530 Sudo: pallet_domain_sudo = 100,
532 }
533);
534
535impl pallet_messenger::extensions::MaybeMessengerCall<Runtime> for RuntimeCall {
536 fn maybe_messenger_call(&self) -> Option<&pallet_messenger::Call<Runtime>> {
537 match self {
538 RuntimeCall::Messenger(call) => Some(call),
539 _ => None,
540 }
541 }
542}
543
544impl<C> subspace_runtime_primitives::CreateUnsigned<C> for Runtime
545where
546 RuntimeCall: From<C>,
547{
548 fn create_unsigned(call: Self::RuntimeCall) -> Self::Extrinsic {
549 create_unsigned_general_extrinsic(call)
550 }
551}
552
553fn create_unsigned_general_extrinsic(call: RuntimeCall) -> UncheckedExtrinsic {
554 let extra: SignedExtra = (
555 frame_system::CheckNonZeroSender::<Runtime>::new(),
556 frame_system::CheckSpecVersion::<Runtime>::new(),
557 frame_system::CheckTxVersion::<Runtime>::new(),
558 frame_system::CheckGenesis::<Runtime>::new(),
559 frame_system::CheckMortality::<Runtime>::from(generic::Era::Immortal),
560 frame_system::CheckNonce::<Runtime>::from(0u32.into()),
563 domain_check_weight::CheckWeight::<Runtime>::new(),
564 pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(0u128),
567 pallet_messenger::extensions::MessengerExtension::<Runtime>::new(),
568 );
569
570 UncheckedExtrinsic::new_transaction(call, extra)
571}
572
573fn is_xdm_mmr_proof_valid(ext: &ExtrinsicFor<Block>) -> Option<bool> {
574 match &ext.function {
575 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
576 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
577 let ConsensusChainMmrLeafProof {
578 consensus_block_number,
579 opaque_mmr_leaf,
580 proof,
581 ..
582 } = msg.proof.consensus_mmr_proof();
583
584 if !is_consensus_block_finalized(consensus_block_number) {
585 return Some(false);
586 }
587
588 Some(verify_mmr_proof(vec![opaque_mmr_leaf], proof.encode()))
589 }
590 _ => None,
591 }
592}
593
594fn is_valid_sudo_call(encoded_ext: Vec<u8>) -> bool {
596 UncheckedExtrinsic::decode_with_depth_limit(
597 MAX_CALL_RECURSION_DEPTH,
598 &mut encoded_ext.as_slice(),
599 )
600 .is_ok()
601}
602
603fn construct_sudo_call_extrinsic(encoded_ext: Vec<u8>) -> ExtrinsicFor<Block> {
604 let ext = UncheckedExtrinsic::decode(&mut encoded_ext.as_slice()).expect(
605 "must always be a valid extrinsic due to the check above and storage proof check; qed",
606 );
607 UncheckedExtrinsic::new_bare(
608 pallet_domain_sudo::Call::sudo {
609 call: Box::new(ext.function),
610 }
611 .into(),
612 )
613}
614
615fn extract_signer_inner<Lookup>(
616 ext: &UncheckedExtrinsic,
617 lookup: &Lookup,
618) -> Option<Result<AccountId, TransactionValidityError>>
619where
620 Lookup: sp_runtime::traits::Lookup<Source = Address, Target = AccountId>,
621{
622 match &ext.preamble {
623 Preamble::Bare(_) | Preamble::General(_, _) => None,
624 Preamble::Signed(signed, _, _) => Some(lookup.lookup(signed.clone()).map_err(|e| e.into())),
625 }
626}
627
628pub fn extract_signer(
629 extrinsics: Vec<UncheckedExtrinsic>,
630) -> Vec<(Option<opaque::AccountId>, UncheckedExtrinsic)> {
631 let lookup = frame_system::ChainContext::<Runtime>::default();
632
633 extrinsics
634 .into_iter()
635 .map(|extrinsic| {
636 let maybe_signer =
637 extract_signer_inner(&extrinsic, &lookup).and_then(|account_result| {
638 account_result.ok().map(|account_id| account_id.encode())
639 });
640 (maybe_signer, extrinsic)
641 })
642 .collect()
643}
644
645fn extrinsic_era(extrinsic: &ExtrinsicFor<Block>) -> Option<Era> {
646 match &extrinsic.preamble {
647 Preamble::Bare(_) | Preamble::General(_, _) => None,
648 Preamble::Signed(_, _, extra) => Some(extra.4.0),
649 }
650}
651
652#[cfg(feature = "runtime-benchmarks")]
653mod benches {
654 frame_benchmarking::define_benchmarks!(
655 [frame_benchmarking, BaselineBench::<Runtime>]
656 [frame_system, SystemBench::<Runtime>]
657 [domain_pallet_executive, ExecutivePallet]
658 [pallet_messenger, Messenger]
659 [pallet_auto_id, AutoId]
660 );
661}
662
663fn check_transaction_and_do_pre_dispatch_inner(
664 uxt: &ExtrinsicFor<Block>,
665) -> Result<(), TransactionValidityError> {
666 let lookup = frame_system::ChainContext::<Runtime>::default();
667
668 let xt = uxt.clone().check(&lookup)?;
669
670 let dispatch_info = xt.get_dispatch_info();
671
672 if dispatch_info.class == DispatchClass::Mandatory {
673 return Err(InvalidTransaction::MandatoryValidation.into());
674 }
675
676 let encoded_len = uxt.encoded_size();
677
678 match xt.format {
683 ExtrinsicFormat::General(extension_version, extra) => {
684 let custom_extra: CustomSignedExtra = (
685 extra.0,
686 extra.1,
687 extra.2,
688 extra.3,
689 extra.4,
690 extra.5,
691 extra.6.clone(),
692 extra.7,
693 pallet_messenger::extensions::MessengerTrustedMmrExtension::<Runtime>::new(),
694 );
695
696 let origin = RuntimeOrigin::none();
697 <CustomSignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
698 custom_extra,
699 origin,
700 &xt.function,
701 &dispatch_info,
702 encoded_len,
703 extension_version,
704 )
705 .map(|_| ())
706 }
707 ExtrinsicFormat::Signed(account_id, extra) => {
709 let origin = RuntimeOrigin::signed(account_id);
710 <SignedExtra as DispatchTransaction<RuntimeCall>>::validate_and_prepare(
711 extra,
712 origin,
713 &xt.function,
714 &dispatch_info,
715 encoded_len,
716 0,
719 )
720 .map(|_| ())
721 }
722 ExtrinsicFormat::Bare => {
724 Runtime::pre_dispatch(&xt.function).map(|_| ())?;
725 <SignedExtra as TransactionExtension<RuntimeCall>>::bare_validate_and_prepare(
726 &xt.function,
727 &dispatch_info,
728 encoded_len,
729 )
730 .map(|_| ())
731 }
732 }
733}
734
735#[cfg(feature = "runtime-benchmarks")]
736impl frame_system_benchmarking::Config for Runtime {}
737
738#[cfg(feature = "runtime-benchmarks")]
739impl frame_benchmarking::baseline::Config for Runtime {}
740
741impl_runtime_apis! {
742 impl sp_api::Core<Block> for Runtime {
743 fn version() -> RuntimeVersion {
744 VERSION
745 }
746
747 fn execute_block(block: Block) {
748 Executive::execute_block(block)
749 }
750
751 fn initialize_block(header: &HeaderFor<Block>) -> ExtrinsicInclusionMode {
752 Executive::initialize_block(header)
753 }
754 }
755
756 impl sp_api::Metadata<Block> for Runtime {
757 fn metadata() -> OpaqueMetadata {
758 OpaqueMetadata::new(Runtime::metadata().into())
759 }
760
761 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
762 Runtime::metadata_at_version(version)
763 }
764
765 fn metadata_versions() -> Vec<u32> {
766 Runtime::metadata_versions()
767 }
768 }
769
770 impl sp_block_builder::BlockBuilder<Block> for Runtime {
771 fn apply_extrinsic(extrinsic: ExtrinsicFor<Block>) -> ApplyExtrinsicResult {
772 Executive::apply_extrinsic(extrinsic)
773 }
774
775 fn finalize_block() -> HeaderFor<Block> {
776 Executive::finalize_block()
777 }
778
779 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<ExtrinsicFor<Block>> {
780 data.create_extrinsics()
781 }
782
783 fn check_inherents(
784 block: Block,
785 data: sp_inherents::InherentData,
786 ) -> sp_inherents::CheckInherentsResult {
787 data.check_extrinsics(&block)
788 }
789 }
790
791 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
792 fn validate_transaction(
793 source: TransactionSource,
794 tx: ExtrinsicFor<Block>,
795 block_hash: BlockHashFor<Block>,
796 ) -> TransactionValidity {
797 Executive::validate_transaction(source, tx, block_hash)
798 }
799 }
800
801 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
802 fn offchain_worker(header: &HeaderFor<Block>) {
803 Executive::offchain_worker(header)
804 }
805 }
806
807 impl sp_session::SessionKeys<Block> for Runtime {
808 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
809 SessionKeys::generate(seed)
810 }
811
812 fn decode_session_keys(
813 encoded: Vec<u8>,
814 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
815 SessionKeys::decode_into_raw_public_keys(&encoded)
816 }
817 }
818
819 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
820 fn account_nonce(account: AccountId) -> Nonce {
821 *System::account_nonce(account)
822 }
823 }
824
825 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
826 fn query_info(
827 uxt: ExtrinsicFor<Block>,
828 len: u32,
829 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
830 TransactionPayment::query_info(uxt, len)
831 }
832 fn query_fee_details(
833 uxt: ExtrinsicFor<Block>,
834 len: u32,
835 ) -> pallet_transaction_payment::FeeDetails<Balance> {
836 TransactionPayment::query_fee_details(uxt, len)
837 }
838 fn query_weight_to_fee(weight: Weight) -> Balance {
839 TransactionPayment::weight_to_fee(weight)
840 }
841 fn query_length_to_fee(length: u32) -> Balance {
842 TransactionPayment::length_to_fee(length)
843 }
844 }
845
846 impl sp_domains::core_api::DomainCoreApi<Block> for Runtime {
847 fn extract_signer(
848 extrinsics: Vec<ExtrinsicFor<Block>>,
849 ) -> Vec<(Option<opaque::AccountId>, ExtrinsicFor<Block>)> {
850 extract_signer(extrinsics)
851 }
852
853 fn is_within_tx_range(
854 extrinsic: &ExtrinsicFor<Block>,
855 bundle_vrf_hash: &subspace_core_primitives::U256,
856 tx_range: &subspace_core_primitives::U256
857 ) -> bool {
858 use subspace_core_primitives::U256;
859 use subspace_core_primitives::hashes::blake3_hash;
860
861 let lookup = frame_system::ChainContext::<Runtime>::default();
862 if let Some(signer) = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
863 account_result.ok().map(|account_id| account_id.encode())
864 }) {
865 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
867 sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range)
868 } else {
869 true
871 }
872 }
873
874 fn extract_signer_if_all_within_tx_range(
875 extrinsics: &Vec<ExtrinsicFor<Block>>,
876 bundle_vrf_hash: &subspace_core_primitives::U256,
877 tx_range: &subspace_core_primitives::U256
878 ) -> Result<Vec<Option<opaque::AccountId>> , u32> {
879 use subspace_core_primitives::U256;
880 use subspace_core_primitives::hashes::blake3_hash;
881
882 let mut signers = Vec::with_capacity(extrinsics.len());
883 let lookup = frame_system::ChainContext::<Runtime>::default();
884 for (index, extrinsic) in extrinsics.iter().enumerate() {
885 let maybe_signer = extract_signer_inner(extrinsic, &lookup).and_then(|account_result| {
886 account_result.ok().map(|account_id| account_id.encode())
887 });
888 if let Some(signer) = &maybe_signer {
889 let signer_id_hash = U256::from_be_bytes(*blake3_hash(&signer.encode()));
891 if !sp_domains::signer_in_tx_range(bundle_vrf_hash, &signer_id_hash, tx_range) {
892 return Err(index as u32)
893 }
894 }
895 signers.push(maybe_signer);
896 }
897
898 Ok(signers)
899 }
900
901 fn initialize_block_with_post_state_root(header: &HeaderFor<Block>) -> Vec<u8> {
902 Executive::initialize_block(header);
903 Executive::storage_root()
904 }
905
906 fn apply_extrinsic_with_post_state_root(extrinsic: ExtrinsicFor<Block>) -> Vec<u8> {
907 let _ = Executive::apply_extrinsic(extrinsic);
908 Executive::storage_root()
909 }
910
911 fn construct_set_code_extrinsic(code: Vec<u8>) -> Vec<u8> {
912 UncheckedExtrinsic::new_bare(
913 domain_pallet_executive::Call::set_code {
914 code
915 }.into()
916 ).encode()
917 }
918
919 fn construct_timestamp_extrinsic(moment: Moment) -> ExtrinsicFor<Block> {
920 UncheckedExtrinsic::new_bare(
921 pallet_timestamp::Call::set{ now: moment }.into()
922 )
923 }
924
925 fn is_inherent_extrinsic(extrinsic: &ExtrinsicFor<Block>) -> bool {
926 <Self as IsInherent<_>>::is_inherent(extrinsic)
927 }
928
929 fn find_first_inherent_extrinsic(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Option<u32> {
930 for (index, extrinsic) in extrinsics.iter().enumerate() {
931 if <Self as IsInherent<_>>::is_inherent(extrinsic) {
932 return Some(index as u32)
933 }
934 }
935 None
936 }
937
938 fn check_extrinsics_and_do_pre_dispatch(uxts: Vec<ExtrinsicFor<Block>>, block_number: BlockNumber,
939 block_hash: BlockHashFor<Block>) -> Result<(), CheckExtrinsicsValidityError> {
940 System::initialize(
942 &(block_number + BlockNumber::one()),
943 &block_hash,
944 &Default::default(),
945 );
946
947 for (extrinsic_index, uxt) in uxts.iter().enumerate() {
948 check_transaction_and_do_pre_dispatch_inner(uxt).map_err(|e| {
949 CheckExtrinsicsValidityError {
950 extrinsic_index: extrinsic_index as u32,
951 transaction_validity_error: e
952 }
953 })?;
954 }
955
956 Ok(())
957 }
958
959 fn decode_extrinsic(
960 opaque_extrinsic: sp_runtime::OpaqueExtrinsic,
961 ) -> Result<ExtrinsicFor<Block>, DecodeExtrinsicError> {
962 let encoded = opaque_extrinsic.encode();
963
964 UncheckedExtrinsic::decode_with_depth_limit(
965 MAX_CALL_RECURSION_DEPTH,
966 &mut encoded.as_slice(),
967 ).map_err(|err| DecodeExtrinsicError(format!("{err}")))
968 }
969
970 fn decode_extrinsics_prefix(
971 opaque_extrinsics: Vec<sp_runtime::OpaqueExtrinsic>,
972 ) -> Vec<ExtrinsicFor<Block>> {
973 let mut extrinsics = Vec::with_capacity(opaque_extrinsics.len());
974 for opaque_ext in opaque_extrinsics {
975 match UncheckedExtrinsic::decode_with_depth_limit(
976 MAX_CALL_RECURSION_DEPTH,
977 &mut opaque_ext.encode().as_slice(),
978 ) {
979 Ok(tx) => extrinsics.push(tx),
980 Err(_) => return extrinsics,
981 }
982 }
983 extrinsics
984 }
985
986 fn extrinsic_era(
987 extrinsic: &ExtrinsicFor<Block>
988 ) -> Option<Era> {
989 extrinsic_era(extrinsic)
990 }
991
992 fn extrinsic_weight(ext: &ExtrinsicFor<Block>) -> Weight {
993 let len = ext.encoded_size() as u64;
994 let info = ext.get_dispatch_info();
995 info.call_weight.saturating_add(info.extension_weight)
996 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
997 .saturating_add(Weight::from_parts(0, len))
998 }
999
1000 fn extrinsics_weight(extrinsics: &Vec<ExtrinsicFor<Block>>) -> Weight {
1001 let mut total_weight = Weight::zero();
1002 for ext in extrinsics {
1003 let ext_weight = {
1004 let len = ext.encoded_size() as u64;
1005 let info = ext.get_dispatch_info();
1006 info.call_weight.saturating_add(info.extension_weight)
1007 .saturating_add(<Runtime as frame_system::Config>::BlockWeights::get().get(info.class).base_extrinsic)
1008 .saturating_add(Weight::from_parts(0, len))
1009 };
1010 total_weight = total_weight.saturating_add(ext_weight);
1011 }
1012 total_weight
1013 }
1014
1015 fn block_fees() -> sp_domains::BlockFees<Balance> {
1016 BlockFees::collected_block_fees()
1017 }
1018
1019 fn block_digest() -> Digest {
1020 System::digest()
1021 }
1022
1023 fn block_weight() -> Weight {
1024 System::block_weight().total()
1025 }
1026
1027 fn construct_consensus_chain_byte_fee_extrinsic(transaction_byte_fee: Balance) -> ExtrinsicFor<Block> {
1028 UncheckedExtrinsic::new_bare(
1029 pallet_block_fees::Call::set_next_consensus_chain_byte_fee{ transaction_byte_fee }.into()
1030 )
1031 }
1032
1033 fn construct_domain_update_chain_allowlist_extrinsic(updates: DomainAllowlistUpdates) -> ExtrinsicFor<Block> {
1034 UncheckedExtrinsic::new_bare(
1035 pallet_messenger::Call::update_domain_allowlist{ updates }.into()
1036 )
1037 }
1038
1039 fn transfers() -> Transfers<Balance> {
1040 Transporter::chain_transfers()
1041 }
1042
1043 fn transfers_storage_key() -> Vec<u8> {
1044 Transporter::transfers_storage_key()
1045 }
1046
1047 fn block_fees_storage_key() -> Vec<u8> {
1048 BlockFees::block_fees_storage_key()
1049 }
1050 }
1051
1052 impl sp_messenger::MessengerApi<Block, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1053 fn is_xdm_mmr_proof_valid(
1054 extrinsic: &ExtrinsicFor<Block>,
1055 ) -> Option<bool> {
1056 is_xdm_mmr_proof_valid(extrinsic)
1057 }
1058
1059 fn extract_xdm_mmr_proof(ext: &ExtrinsicFor<Block>) -> Option<ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1060 match &ext.function {
1061 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1062 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1063 Some(msg.proof.consensus_mmr_proof())
1064 }
1065 _ => None,
1066 }
1067 }
1068
1069 fn batch_extract_xdm_mmr_proof(extrinsics: &Vec<ExtrinsicFor<Block>>) -> BTreeMap<u32, ConsensusChainMmrLeafProof<ConsensusBlockNumber, ConsensusBlockHash, sp_core::H256>> {
1070 let mut mmr_proofs = BTreeMap::new();
1071 for (index, ext) in extrinsics.iter().enumerate() {
1072 match &ext.function {
1073 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })
1074 | RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1075 mmr_proofs.insert(index as u32, msg.proof.consensus_mmr_proof());
1076 }
1077 _ => {},
1078 }
1079 }
1080 mmr_proofs
1081 }
1082
1083 fn confirmed_domain_block_storage_key(_domain_id: DomainId) -> Vec<u8> {
1084 vec![]
1086 }
1087
1088 fn outbox_storage_key(message_key: MessageKey) -> Vec<u8> {
1089 Messenger::outbox_storage_key(message_key)
1090 }
1091
1092 fn inbox_response_storage_key(message_key: MessageKey) -> Vec<u8> {
1093 Messenger::inbox_response_storage_key(message_key)
1094 }
1095
1096 fn domain_chains_allowlist_update(_domain_id: DomainId) -> Option<DomainAllowlistUpdates>{
1097 None
1099 }
1100
1101 fn xdm_id(ext: &ExtrinsicFor<Block>) -> Option<XdmId> {
1102 match &ext.function {
1103 RuntimeCall::Messenger(pallet_messenger::Call::relay_message { msg })=> {
1104 Some(XdmId::RelayMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1105 }
1106 RuntimeCall::Messenger(pallet_messenger::Call::relay_message_response { msg }) => {
1107 Some(XdmId::RelayResponseMessage((msg.src_chain_id, msg.channel_id, msg.nonce)))
1108 }
1109 _ => None,
1110 }
1111 }
1112
1113 fn channel_nonce(chain_id: ChainId, channel_id: ChannelId) -> Option<ChannelNonce> {
1114 Messenger::channel_nonce(chain_id, channel_id)
1115 }
1116 }
1117
1118 impl sp_messenger::RelayerApi<Block, BlockNumber, ConsensusBlockNumber, ConsensusBlockHash> for Runtime {
1119 fn block_messages() -> BlockMessagesWithStorageKey {
1120 BlockMessagesWithStorageKey::default()
1121 }
1122
1123 fn outbox_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1124 Messenger::outbox_message_unsigned(msg)
1125 }
1126
1127 fn inbox_response_message_unsigned(msg: CrossDomainMessage<NumberFor<Block>, BlockHashFor<Block>, BlockHashFor<Block>>) -> Option<ExtrinsicFor<Block>> {
1128 Messenger::inbox_response_message_unsigned(msg)
1129 }
1130
1131 fn should_relay_outbox_message(_: ChainId, _: MessageId) -> bool {
1132 false
1133 }
1134
1135 fn should_relay_inbox_message_response(_: ChainId, _: MessageId) -> bool {
1136 false
1137 }
1138
1139 fn updated_channels() -> BTreeSet<(ChainId, ChannelId)> {
1140 Messenger::updated_channels()
1141 }
1142
1143 fn channel_storage_key(chain_id: ChainId, channel_id: ChannelId) -> Vec<u8> {
1144 Messenger::channel_storage_key(chain_id, channel_id)
1145 }
1146
1147 fn open_channels() -> BTreeSet<(ChainId, ChannelId)> {
1148 Messenger::open_channels()
1149 }
1150
1151 fn block_messages_with_query(query: BlockMessagesQuery) -> MessagesWithStorageKey {
1152 Messenger::get_block_messages(query)
1153 }
1154
1155 fn channels_and_state() -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> {
1156 Messenger::channels_and_states()
1157 }
1158
1159 fn first_outbox_message_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1160 Messenger::first_outbox_message_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1161 }
1162
1163 fn first_inbox_message_response_nonce_to_relay(dst_chain_id: ChainId, channel_id: ChannelId, from_nonce: XdmNonce) -> Option<XdmNonce> {
1164 Messenger::first_inbox_message_response_nonce_to_relay(dst_chain_id, channel_id, from_nonce)
1165 }
1166 }
1167
1168 impl sp_domain_sudo::DomainSudoApi<Block> for Runtime {
1169 fn is_valid_sudo_call(extrinsic: Vec<u8>) -> bool {
1170 is_valid_sudo_call(extrinsic)
1171 }
1172
1173 fn construct_domain_sudo_extrinsic(inner: Vec<u8>) -> ExtrinsicFor<Block> {
1174 construct_sudo_call_extrinsic(inner)
1175 }
1176 }
1177
1178 impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
1179 fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
1180 build_state::<RuntimeGenesisConfig>(config)
1181 }
1182
1183 fn get_preset(_id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
1184 get_preset::<RuntimeGenesisConfig>(&None, |_| None)
1186 }
1187
1188 fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
1189 vec![]
1190 }
1191 }
1192
1193 #[cfg(feature = "runtime-benchmarks")]
1194 impl frame_benchmarking::Benchmark<Block> for Runtime {
1195 fn benchmark_metadata(extra: bool) -> (
1196 Vec<frame_benchmarking::BenchmarkList>,
1197 Vec<frame_support::traits::StorageInfo>,
1198 ) {
1199 use frame_benchmarking::{baseline, Benchmarking, BenchmarkList};
1200 use frame_support::traits::StorageInfoTrait;
1201 use frame_system_benchmarking::Pallet as SystemBench;
1202 use baseline::Pallet as BaselineBench;
1203
1204 let mut list = Vec::<BenchmarkList>::new();
1205
1206 list_benchmarks!(list, extra);
1207
1208 let storage_info = AllPalletsWithSystem::storage_info();
1209
1210 (list, storage_info)
1211 }
1212
1213 fn dispatch_benchmark(
1214 config: frame_benchmarking::BenchmarkConfig
1215 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
1216 use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch};
1217 use sp_storage::TrackedStorageKey;
1218 use frame_system_benchmarking::Pallet as SystemBench;
1219 use frame_support::traits::WhitelistedStorageKeys;
1220 use baseline::Pallet as BaselineBench;
1221
1222 let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
1223
1224 let mut batches = Vec::<BenchmarkBatch>::new();
1225 let params = (&config, &whitelist);
1226
1227 add_benchmarks!(params, batches);
1228
1229 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }
1230 Ok(batches)
1231 }
1232 }
1233}
1234
1235#[cfg(test)]
1236mod tests {
1237 use crate::{Runtime, RuntimeBlockWeights as BlockWeights};
1238 use subspace_runtime_primitives::tests_utils::FeeMultiplierUtils;
1239
1240 #[test]
1241 fn multiplier_can_grow_from_zero() {
1242 FeeMultiplierUtils::<Runtime, BlockWeights>::multiplier_can_grow_from_zero()
1243 }
1244}