Skip to main content

pallet_domains/
lib.rs

1//! Pallet Domains
2
3#![cfg_attr(not(feature = "std"), no_std)]
4// TODO: Remove once FRAME macros stop generating `.clone()` calls on `Copy` types with user spans
5#![expect(clippy::clone_on_copy, reason = "Comes from Substrate")]
6#![cfg_attr(any(feature = "fuzz", test), feature(variant_count))]
7
8#[cfg(feature = "runtime-benchmarks")]
9mod benchmarking;
10
11pub mod block_tree;
12pub mod bundle_storage_fund;
13pub mod domain_registry;
14pub mod extensions;
15#[cfg(feature = "fuzz")]
16pub mod fuzz;
17pub mod migrations;
18#[cfg(any(feature = "fuzz", test,))]
19pub(crate) mod mock;
20mod nominator_position;
21pub mod runtime_registry;
22pub mod staking;
23mod staking_epoch;
24#[cfg(test)]
25mod tests;
26pub mod weights;
27
28extern crate alloc;
29
30use crate::block_tree::{Error as BlockTreeError, verify_execution_receipt};
31use crate::bundle_storage_fund::{charge_bundle_storage_fee, storage_fund_account};
32use crate::domain_registry::{DomainConfig, Error as DomainRegistryError};
33use crate::runtime_registry::into_complete_raw_genesis;
34#[cfg(feature = "runtime-benchmarks")]
35pub use crate::staking::do_register_operator;
36use crate::staking_epoch::EpochTransitionResult;
37#[cfg(not(feature = "std"))]
38use alloc::boxed::Box;
39use alloc::collections::btree_map::BTreeMap;
40#[cfg(not(feature = "std"))]
41use alloc::vec::Vec;
42use domain_runtime_primitives::EthereumAccountId;
43use frame_support::dispatch::DispatchResult;
44use frame_support::ensure;
45use frame_support::pallet_prelude::StorageVersion;
46use frame_support::traits::fungible::{Inspect, InspectHold};
47use frame_support::traits::tokens::{Fortitude, Preservation};
48use frame_support::traits::{EnsureOrigin, Get, Randomness as RandomnessT, Time};
49use frame_support::weights::Weight;
50use frame_system::offchain::SubmitTransaction;
51use frame_system::pallet_prelude::*;
52pub use pallet::*;
53use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
54use scale_info::TypeInfo;
55use sp_consensus_subspace::WrappedPotOutput;
56use sp_consensus_subspace::consensus::is_proof_of_time_valid;
57use sp_core::H256;
58use sp_domains::bundle::{Bundle, BundleVersion, OpaqueBundle};
59use sp_domains::bundle_producer_election::BundleProducerElectionParams;
60use sp_domains::execution_receipt::{
61    ExecutionReceipt, ExecutionReceiptRef, ExecutionReceiptVersion, SealedSingletonReceipt,
62};
63use sp_domains::{
64    BundleAndExecutionReceiptVersion, DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT, DomainBundleLimit,
65    DomainId, DomainInstanceData, EMPTY_EXTRINSIC_ROOT, OperatorId, OperatorPublicKey,
66    OperatorSignature, ProofOfElection, RuntimeId,
67};
68use sp_domains_fraud_proof::fraud_proof::{
69    DomainRuntimeCodeAt, FraudProof, FraudProofVariant, InvalidBlockFeesProof,
70    InvalidDomainBlockHashProof, InvalidTransfersProof,
71};
72use sp_domains_fraud_proof::storage_proof::{self, BasicStorageProof, DomainRuntimeCodeProof};
73use sp_domains_fraud_proof::verification::{
74    verify_invalid_block_fees_fraud_proof, verify_invalid_bundles_fraud_proof,
75    verify_invalid_domain_block_hash_fraud_proof,
76    verify_invalid_domain_extrinsics_root_fraud_proof, verify_invalid_state_transition_fraud_proof,
77    verify_invalid_transfers_fraud_proof, verify_valid_bundle_fraud_proof,
78};
79use sp_runtime::traits::{BlockNumberProvider, CheckedSub, Hash, Header, One, Zero};
80use sp_runtime::transaction_validity::TransactionPriority;
81use sp_runtime::{RuntimeAppPublic, SaturatedConversion, Saturating};
82use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrProofVerifier};
83pub use staking::OperatorConfig;
84use subspace_core_primitives::pot::PotOutput;
85use subspace_core_primitives::{BlockHash, SlotNumber, U256};
86use subspace_runtime_primitives::{Balance, CreateUnsigned, Moment, StorageFee};
87
88/// Maximum number of nominators to slash within a give operator at a time.
89pub const MAX_NOMINATORS_TO_SLASH: u32 = 10;
90
91pub(crate) type BalanceOf<T> = <T as Config>::Balance;
92
93pub(crate) type FungibleHoldId<T> =
94    <<T as Config>::Currency as InspectHold<<T as frame_system::Config>::AccountId>>::Reason;
95
96pub(crate) type NominatorId<T> = <T as frame_system::Config>::AccountId;
97
98pub trait HoldIdentifier<T: Config> {
99    fn staking_staked() -> FungibleHoldId<T>;
100    fn domain_instantiation_id() -> FungibleHoldId<T>;
101    fn storage_fund_withdrawal() -> FungibleHoldId<T>;
102}
103
104pub trait BlockSlot<T: frame_system::Config> {
105    /// Returns the highest valid slot for the given `block_number`.
106    /// Returns `None` if that block number is too far in the past, or too far in the future.
107    fn future_slot(block_number: BlockNumberFor<T>) -> Option<sp_consensus_slots::Slot>;
108
109    /// Returns the latest block number whose slot is less than the given `to_check` slot
110    fn slot_produced_after(to_check: sp_consensus_slots::Slot) -> Option<BlockNumberFor<T>>;
111
112    /// Returns the slot at the current block height
113    fn current_slot() -> sp_consensus_slots::Slot;
114}
115
116pub type ExecutionReceiptOf<T> = ExecutionReceipt<
117    BlockNumberFor<T>,
118    <T as frame_system::Config>::Hash,
119    DomainBlockNumberFor<T>,
120    <T as Config>::DomainHash,
121    BalanceOf<T>,
122>;
123
124pub type ExecutionReceiptRefOf<'a, T> = ExecutionReceiptRef<
125    'a,
126    BlockNumberFor<T>,
127    <T as frame_system::Config>::Hash,
128    DomainBlockNumberFor<T>,
129    <T as Config>::DomainHash,
130    BalanceOf<T>,
131>;
132
133pub type OpaqueBundleOf<T> = OpaqueBundle<
134    BlockNumberFor<T>,
135    <T as frame_system::Config>::Hash,
136    <T as Config>::DomainHeader,
137    BalanceOf<T>,
138>;
139
140pub type SingletonReceiptOf<T> = SealedSingletonReceipt<
141    BlockNumberFor<T>,
142    <T as frame_system::Config>::Hash,
143    <T as Config>::DomainHeader,
144    BalanceOf<T>,
145>;
146
147pub type FraudProofFor<T> = FraudProof<
148    BlockNumberFor<T>,
149    <T as frame_system::Config>::Hash,
150    <T as Config>::DomainHeader,
151    <T as Config>::MmrHash,
152>;
153
154/// Parameters used to verify proof of election.
155#[derive(TypeInfo, Debug, Encode, Decode, Clone, PartialEq, Eq)]
156pub(crate) struct ElectionVerificationParams<Balance> {
157    operators: BTreeMap<OperatorId, Balance>,
158    total_domain_stake: Balance,
159}
160
161pub type DomainBlockNumberFor<T> = <<T as Config>::DomainHeader as Header>::Number;
162pub type DomainHashingFor<T> = <<T as Config>::DomainHeader as Header>::Hashing;
163pub type ReceiptHashFor<T> = <<T as Config>::DomainHeader as Header>::Hash;
164
165pub type BlockTreeNodeFor<T> = crate::block_tree::BlockTreeNode<
166    BlockNumberFor<T>,
167    <T as frame_system::Config>::Hash,
168    DomainBlockNumberFor<T>,
169    <T as Config>::DomainHash,
170    BalanceOf<T>,
171>;
172
173/// Custom origin for validated unsigned extrinsics.
174#[derive(
175    PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DecodeWithMemTracking,
176)]
177pub enum RawOrigin {
178    ValidatedUnsigned,
179}
180
181/// Ensure the domain origin.
182pub struct EnsureDomainOrigin;
183impl<O: Into<Result<RawOrigin, O>> + From<RawOrigin>> EnsureOrigin<O> for EnsureDomainOrigin {
184    type Success = ();
185
186    fn try_origin(o: O) -> Result<Self::Success, O> {
187        o.into().map(|o| match o {
188            RawOrigin::ValidatedUnsigned => (),
189        })
190    }
191
192    #[cfg(feature = "runtime-benchmarks")]
193    fn try_successful_origin() -> Result<O, ()> {
194        Ok(O::from(RawOrigin::ValidatedUnsigned))
195    }
196}
197
198/// The current storage version.
199const STORAGE_VERSION: StorageVersion = StorageVersion::new(6);
200
201/// The number of bundle of a particular domain to be included in the block is probabilistic
202/// and based on the consensus chain slot probability and domain bundle slot probability, usually
203/// the value is 6 on average, smaller/bigger value with less probability, we hypocritically use
204/// 100 as the maximum number of bundle per block for benchmarking.
205const MAX_BUNDLE_PER_BLOCK: u32 = 100;
206
207pub(crate) type StateRootOf<T> = <<T as frame_system::Config>::Hashing as Hash>::Output;
208
209/// Weight functions needed for pallet_domains.
210pub trait WeightInfo {
211    fn submit_bundle() -> Weight;
212    fn submit_fraud_proof() -> Weight;
213    fn handle_bad_receipt(n: u32) -> Weight;
214    fn confirm_domain_block(n: u32, s: u32) -> Weight;
215    fn operator_reward_tax_and_restake(n: u32) -> Weight;
216    fn slash_operator(n: u32) -> Weight;
217    fn finalize_domain_epoch_staking(p: u32) -> Weight;
218    fn register_domain_runtime() -> Weight;
219    fn upgrade_domain_runtime() -> Weight;
220    fn instantiate_domain() -> Weight;
221    fn register_operator() -> Weight;
222    fn nominate_operator() -> Weight;
223    fn deregister_operator() -> Weight;
224    fn withdraw_stake() -> Weight;
225    fn unlock_funds(w: u32) -> Weight;
226    fn unlock_nominator() -> Weight;
227    fn update_domain_operator_allow_list() -> Weight;
228    fn transfer_treasury_funds() -> Weight;
229    fn submit_receipt() -> Weight;
230    fn validate_submit_bundle() -> Weight;
231    fn validate_singleton_receipt() -> Weight;
232    fn fraud_proof_pre_check() -> Weight;
233    fn deactivate_operator() -> Weight;
234    fn reactivate_operator() -> Weight;
235    fn deregister_deactivated_operator() -> Weight;
236    fn withdraw_stake_from_deactivated_operator() -> Weight;
237}
238
239#[frame_support::pallet]
240mod pallet {
241    #[cfg(not(feature = "runtime-benchmarks"))]
242    use crate::DomainHashingFor;
243    #[cfg(not(feature = "runtime-benchmarks"))]
244    use crate::MAX_NOMINATORS_TO_SLASH;
245    use crate::block_tree::{
246        AcceptedReceiptType, BlockTreeNode, Error as BlockTreeError, ReceiptType,
247        execution_receipt_type, process_execution_receipt, prune_receipt,
248    };
249    use crate::bundle_storage_fund::Error as BundleStorageFundError;
250    #[cfg(not(feature = "runtime-benchmarks"))]
251    use crate::bundle_storage_fund::refund_storage_fee;
252    use crate::domain_registry::{
253        DomainConfigParams, DomainObject, Error as DomainRegistryError, do_instantiate_domain,
254        do_update_domain_allow_list,
255    };
256    use crate::runtime_registry::{
257        DomainRuntimeUpgradeEntry, Error as RuntimeRegistryError, ScheduledRuntimeUpgrade,
258        do_register_runtime, do_schedule_runtime_upgrade, do_upgrade_runtimes,
259        register_runtime_at_genesis,
260    };
261    #[cfg(not(feature = "runtime-benchmarks"))]
262    use crate::staking::do_reward_operators;
263    use crate::staking::{
264        Deposit, DomainEpoch, Error as StakingError, Operator, OperatorConfig, SharePrice,
265        StakingSummary, Withdrawal, do_deregister_operator, do_mark_invalid_bundle_authors,
266        do_mark_operators_as_slashed, do_nominate_operator, do_register_operator, do_unlock_funds,
267        do_unlock_nominator, do_unmark_invalid_bundle_authors, do_withdraw_stake,
268    };
269    #[cfg(not(feature = "runtime-benchmarks"))]
270    use crate::staking_epoch::do_slash_operator;
271    use crate::staking_epoch::{Error as StakingEpochError, do_finalize_domain_current_epoch};
272    use crate::storage_proof::InherentExtrinsicData;
273    use crate::{
274        BalanceOf, BlockSlot, BlockTreeNodeFor, DomainBlockNumberFor, ElectionVerificationParams,
275        ExecutionReceiptOf, FraudProofFor, HoldIdentifier, MAX_BUNDLE_PER_BLOCK, NominatorId,
276        OpaqueBundleOf, RawOrigin, ReceiptHashFor, STORAGE_VERSION, SingletonReceiptOf,
277        StateRootOf, WeightInfo,
278    };
279    #[cfg(not(feature = "std"))]
280    use alloc::string::String;
281    #[cfg(not(feature = "std"))]
282    use alloc::vec;
283    #[cfg(not(feature = "std"))]
284    use alloc::vec::Vec;
285    use domain_runtime_primitives::{EVMChainId, EthereumAccountId};
286    use frame_support::pallet_prelude::*;
287    use frame_support::traits::fungible::{Inspect, InspectHold, Mutate, MutateHold};
288    use frame_support::traits::tokens::Preservation;
289    use frame_support::traits::{Randomness as RandomnessT, Time};
290    use frame_support::weights::Weight;
291    use frame_support::{Identity, PalletError};
292    use frame_system::pallet_prelude::*;
293    use parity_scale_codec::FullCodec;
294    use sp_consensus_slots::Slot;
295    use sp_core::H256;
296    use sp_domains::bundle::BundleDigest;
297    use sp_domains::bundle_producer_election::ProofOfElectionError;
298    use sp_domains::offline_operators::OperatorEpochExpectations;
299    use sp_domains::{
300        BundleAndExecutionReceiptVersion, DomainBundleSubmitted, DomainId, DomainOwner,
301        DomainSudoCall, DomainsTransfersTracker, EpochIndex,
302        EvmDomainContractCreationAllowedByCall, GenesisDomain, OnChainRewards,
303        OnDomainInstantiated, OperatorAllowList, OperatorId, OperatorRewardSource, RuntimeId,
304        RuntimeObject, RuntimeType,
305    };
306    use sp_domains_fraud_proof::fraud_proof_runtime_interface::domain_runtime_call;
307    use sp_domains_fraud_proof::storage_proof::{self, FraudProofStorageKeyProvider};
308    use sp_domains_fraud_proof::{InvalidTransactionCode, StatelessDomainRuntimeCall};
309    use sp_runtime::Saturating;
310    use sp_runtime::traits::{
311        AtLeast32BitUnsigned, BlockNumberProvider, CheckEqual, CheckedAdd, Header as HeaderT,
312        MaybeDisplay, One, SimpleBitOps, Zero,
313    };
314    use sp_std::boxed::Box;
315    use sp_std::collections::btree_map::BTreeMap;
316    use sp_std::collections::btree_set::BTreeSet;
317    use sp_std::fmt::Debug;
318    use sp_subspace_mmr::MmrProofVerifier;
319    use subspace_core_primitives::{Randomness, U256};
320    use subspace_runtime_primitives::StorageFee;
321
322    #[pallet::config]
323    pub trait Config:
324        frame_system::Config<Hash: Into<H256> + From<H256>, RuntimeEvent: From<Event<Self>>>
325    {
326        /// Origin for domain call.
327        type DomainOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ()>;
328
329        // TODO: `DomainHash` can be derived from `DomainHeader`, it is still needed just for
330        // converting `DomainHash` to/from `H256` without encode/decode, remove it once we found
331        // other ways to do this.
332        /// Domain block hash type.
333        type DomainHash: Parameter
334            + Member
335            + MaybeSerializeDeserialize
336            + Debug
337            + MaybeDisplay
338            + SimpleBitOps
339            + Ord
340            + Default
341            + Copy
342            + CheckEqual
343            + sp_std::hash::Hash
344            + AsRef<[u8]>
345            + AsMut<[u8]>
346            + MaxEncodedLen
347            + Into<H256>
348            + From<H256>;
349
350        // We need this explicit type since Currency::Balance does not provide From<u64>
351        type Balance: Parameter
352            + Member
353            + MaybeSerializeDeserialize
354            + AtLeast32BitUnsigned
355            + FullCodec
356            + Debug
357            + MaybeDisplay
358            + Default
359            + Copy
360            + MaxEncodedLen
361            + From<u64>;
362
363        /// The domain header type.
364        type DomainHeader: HeaderT<Hash = Self::DomainHash>;
365
366        /// Same with `pallet_subspace::Config::ConfirmationDepthK`.
367        #[pallet::constant]
368        type ConfirmationDepthK: Get<BlockNumberFor<Self>>;
369
370        /// Currency type used by the domains for staking and other currency related stuff.
371        type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
372            + Mutate<Self::AccountId>
373            + InspectHold<Self::AccountId>
374            + MutateHold<Self::AccountId>;
375
376        /// Type representing the shares in the staking protocol.
377        type Share: Parameter
378            + Member
379            + MaybeSerializeDeserialize
380            + Debug
381            + AtLeast32BitUnsigned
382            + FullCodec
383            + Copy
384            + Default
385            + TypeInfo
386            + MaxEncodedLen
387            + IsType<BalanceOf<Self>>;
388
389        /// A variation of the Identifier used for holding the funds used for staking and domains.
390        type HoldIdentifier: HoldIdentifier<Self>;
391
392        /// The block tree pruning depth.
393        #[pallet::constant]
394        type BlockTreePruningDepth: Get<DomainBlockNumberFor<Self>>;
395
396        /// Consensus chain slot probability.
397        #[pallet::constant]
398        type ConsensusSlotProbability: Get<(u64, u64)>;
399
400        /// The maximum block size limit for all domain.
401        #[pallet::constant]
402        type MaxDomainBlockSize: Get<u32>;
403
404        /// The maximum block weight limit for all domain.
405        #[pallet::constant]
406        type MaxDomainBlockWeight: Get<Weight>;
407
408        /// The maximum domain name length limit for all domain.
409        #[pallet::constant]
410        type MaxDomainNameLength: Get<u32>;
411
412        /// The amount of fund to be locked up for the domain instance creator.
413        #[pallet::constant]
414        type DomainInstantiationDeposit: Get<BalanceOf<Self>>;
415
416        /// Weight information for extrinsics in this pallet.
417        type WeightInfo: WeightInfo;
418
419        /// Initial domain tx range value.
420        #[pallet::constant]
421        type InitialDomainTxRange: Get<u64>;
422
423        /// Domain tx range is adjusted after every DomainTxRangeAdjustmentInterval blocks.
424        #[pallet::constant]
425        type DomainTxRangeAdjustmentInterval: Get<u64>;
426
427        /// Minimum operator stake required to become operator of a domain.
428        #[pallet::constant]
429        type MinOperatorStake: Get<BalanceOf<Self>>;
430
431        /// Minimum nominator stake required to nominate and operator.
432        #[pallet::constant]
433        type MinNominatorStake: Get<BalanceOf<Self>>;
434
435        /// Minimum number of blocks after which any finalized withdrawals are released to nominators.
436        #[pallet::constant]
437        type StakeWithdrawalLockingPeriod: Get<DomainBlockNumberFor<Self>>;
438
439        /// Domain epoch transition interval
440        #[pallet::constant]
441        type StakeEpochDuration: Get<DomainBlockNumberFor<Self>>;
442
443        /// Treasury account.
444        #[pallet::constant]
445        type TreasuryAccount: Get<Self::AccountId>;
446
447        /// The maximum number of pending staking operation that can perform upon epoch transition.
448        #[pallet::constant]
449        type MaxPendingStakingOperation: Get<u32>;
450
451        /// Randomness source.
452        type Randomness: RandomnessT<Self::Hash, BlockNumberFor<Self>>;
453
454        /// The pallet-domains's pallet id.
455        #[pallet::constant]
456        type PalletId: Get<frame_support::PalletId>;
457
458        /// Storage fee interface used to deal with bundle storage fee
459        type StorageFee: StorageFee<BalanceOf<Self>>;
460
461        /// The block timestamp
462        type BlockTimestamp: Time;
463
464        /// The block slot
465        type BlockSlot: BlockSlot<Self>;
466
467        /// Transfers tracker.
468        type DomainsTransfersTracker: DomainsTransfersTracker<BalanceOf<Self>>;
469
470        /// Upper limit for total initial accounts domains
471        type MaxInitialDomainAccounts: Get<u32>;
472
473        /// Minimum balance for each initial domain account
474        type MinInitialDomainAccountBalance: Get<BalanceOf<Self>>;
475
476        /// How many block a bundle should still consider as valid after produced
477        #[pallet::constant]
478        type BundleLongevity: Get<u32>;
479
480        /// Post hook to notify accepted domain bundles in previous block.
481        type DomainBundleSubmitted: DomainBundleSubmitted;
482
483        /// A hook to call after a domain is instantiated
484        type OnDomainInstantiated: OnDomainInstantiated;
485
486        /// Hash type of MMR
487        type MmrHash: Parameter + Member + Default + Clone;
488
489        /// MMR proof verifier
490        type MmrProofVerifier: MmrProofVerifier<Self::MmrHash, BlockNumberFor<Self>, StateRootOf<Self>>;
491
492        /// Fraud proof storage key provider
493        type FraudProofStorageKeyProvider: FraudProofStorageKeyProvider<BlockNumberFor<Self>>;
494
495        /// Hook to handle chain rewards.
496        type OnChainRewards: OnChainRewards<BalanceOf<Self>>;
497
498        /// The max number of withdrawals per nominator that may exist at any time,
499        /// once this limit is reached, the nominator need to unlock the withdrawal
500        /// before requesting new withdrawal.
501        #[pallet::constant]
502        type WithdrawalLimit: Get<u32>;
503
504        /// Current bundle version accepted by the runtime.
505        #[pallet::constant]
506        type CurrentBundleAndExecutionReceiptVersion: Get<BundleAndExecutionReceiptVersion>;
507
508        /// Operator activation delay after deactivation in Epochs.
509        #[pallet::constant]
510        type OperatorActivationDelayInEpochs: Get<EpochIndex>;
511    }
512
513    #[pallet::pallet]
514    #[pallet::without_storage_info]
515    #[pallet::storage_version(STORAGE_VERSION)]
516    pub struct Pallet<T>(_);
517
518    /// Bundles submitted successfully in current block.
519    #[pallet::storage]
520    pub type SuccessfulBundles<T> = StorageMap<_, Identity, DomainId, Vec<H256>, ValueQuery>;
521
522    /// Stores the next runtime id.
523    #[pallet::storage]
524    pub(super) type NextRuntimeId<T> = StorageValue<_, RuntimeId, ValueQuery>;
525
526    /// Stored the occupied evm chain id against a domain_id.
527    #[pallet::storage]
528    pub type EvmChainIds<T: Config> = StorageMap<_, Identity, EVMChainId, DomainId, OptionQuery>;
529
530    #[pallet::storage]
531    pub type RuntimeRegistry<T: Config> =
532        StorageMap<_, Identity, RuntimeId, RuntimeObject<BlockNumberFor<T>, T::Hash>, OptionQuery>;
533
534    #[pallet::storage]
535    pub(super) type ScheduledRuntimeUpgrades<T: Config> = StorageDoubleMap<
536        _,
537        Identity,
538        BlockNumberFor<T>,
539        Identity,
540        RuntimeId,
541        ScheduledRuntimeUpgrade<T::Hash>,
542        OptionQuery,
543    >;
544
545    #[pallet::storage]
546    pub(super) type NextOperatorId<T> = StorageValue<_, OperatorId, ValueQuery>;
547
548    #[pallet::storage]
549    pub(super) type OperatorIdOwner<T: Config> =
550        StorageMap<_, Identity, OperatorId, T::AccountId, OptionQuery>;
551
552    #[pallet::storage]
553    #[pallet::getter(fn domain_staking_summary)]
554    pub(crate) type DomainStakingSummary<T: Config> =
555        StorageMap<_, Identity, DomainId, StakingSummary<OperatorId, BalanceOf<T>>, OptionQuery>;
556
557    /// List of all registered operators and their configuration.
558    #[pallet::storage]
559    pub(super) type Operators<T: Config> = StorageMap<
560        _,
561        Identity,
562        OperatorId,
563        Operator<BalanceOf<T>, T::Share, DomainBlockNumberFor<T>, ReceiptHashFor<T>>,
564        OptionQuery,
565    >;
566
567    /// The highest slot of the bundle submitted by an operator
568    #[pallet::storage]
569    pub(super) type OperatorHighestSlot<T: Config> =
570        StorageMap<_, Identity, OperatorId, u64, ValueQuery>;
571
572    /// The set of slot of the bundle submitted by an operator in the current block, cleared at the
573    /// next block initialization
574    #[pallet::storage]
575    pub(super) type OperatorBundleSlot<T: Config> =
576        StorageMap<_, Identity, OperatorId, BTreeSet<u64>, ValueQuery>;
577
578    /// Share price for the operator pool at the end of Domain epoch.
579    // TODO: currently unbounded storage.
580    #[pallet::storage]
581    pub type OperatorEpochSharePrice<T: Config> =
582        StorageDoubleMap<_, Identity, OperatorId, Identity, DomainEpoch, SharePrice, OptionQuery>;
583
584    /// List of all deposits for given Operator.
585    #[pallet::storage]
586    pub(crate) type Deposits<T: Config> = StorageDoubleMap<
587        _,
588        Identity,
589        OperatorId,
590        Identity,
591        NominatorId<T>,
592        Deposit<T::Share, BalanceOf<T>>,
593        OptionQuery,
594    >;
595
596    /// List of all withdrawals for a given operator.
597    #[pallet::storage]
598    pub(crate) type Withdrawals<T: Config> = StorageDoubleMap<
599        _,
600        Identity,
601        OperatorId,
602        Identity,
603        NominatorId<T>,
604        Withdrawal<BalanceOf<T>, T::Share, DomainBlockNumberFor<T>>,
605        OptionQuery,
606    >;
607
608    /// The amount of balance the nominator hold for a given operator
609    #[pallet::storage]
610    pub(super) type DepositOnHold<T: Config> =
611        StorageMap<_, Identity, (OperatorId, NominatorId<T>), BalanceOf<T>, ValueQuery>;
612
613    /// A list operators who were slashed during the current epoch associated with the domain.
614    /// When the epoch for a given domain is complete, operator total stake is moved to treasury and
615    /// then deleted.
616    #[pallet::storage]
617    pub(crate) type PendingSlashes<T: Config> =
618        StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, OptionQuery>;
619
620    /// The pending staking operation count of the current epoch, it should not larger than
621    /// `MaxPendingStakingOperation` and will be resetted to 0 upon epoch transition.
622    #[pallet::storage]
623    pub(super) type PendingStakingOperationCount<T: Config> =
624        StorageMap<_, Identity, DomainId, u32, ValueQuery>;
625
626    /// Stores the next domain id.
627    #[pallet::storage]
628    #[pallet::getter(fn next_domain_id)]
629    pub(super) type NextDomainId<T> = StorageValue<_, DomainId, ValueQuery>;
630
631    /// The domain registry
632    #[pallet::storage]
633    pub(super) type DomainRegistry<T: Config> = StorageMap<
634        _,
635        Identity,
636        DomainId,
637        DomainObject<BlockNumberFor<T>, ReceiptHashFor<T>, T::AccountId, BalanceOf<T>>,
638        OptionQuery,
639    >;
640
641    /// The domain block tree, map (`domain_id`, `domain_block_number`) to the hash of ER,
642    /// which can be used get the block tree node in `BlockTreeNodes`
643    #[pallet::storage]
644    pub(super) type BlockTree<T: Config> = StorageDoubleMap<
645        _,
646        Identity,
647        DomainId,
648        Identity,
649        DomainBlockNumberFor<T>,
650        ReceiptHashFor<T>,
651        OptionQuery,
652    >;
653
654    /// Mapping of block tree node hash to the node, each node represent a domain block
655    #[pallet::storage]
656    pub(super) type BlockTreeNodes<T: Config> =
657        StorageMap<_, Identity, ReceiptHashFor<T>, BlockTreeNodeFor<T>, OptionQuery>;
658
659    /// The head receipt number of each domain
660    #[pallet::storage]
661    pub(super) type HeadReceiptNumber<T: Config> =
662        StorageMap<_, Identity, DomainId, DomainBlockNumberFor<T>, ValueQuery>;
663
664    /// The hash of the new head receipt added in the current consensus block
665    ///
666    /// Temporary storage only exist during block execution
667    #[pallet::storage]
668    pub(super) type NewAddedHeadReceipt<T: Config> =
669        StorageMap<_, Identity, DomainId, T::DomainHash, OptionQuery>;
670
671    /// Map of consensus block hashes.
672    ///
673    /// The consensus block hash used to verify ER, only store the consensus block hash for a domain
674    /// if that consensus block contains bundle of the domain, the hash will be pruned when the ER
675    /// that point to the consensus block is pruned.
676    #[pallet::storage]
677    #[pallet::getter(fn consensus_block_info)]
678    pub type ConsensusBlockHash<T: Config> =
679        StorageDoubleMap<_, Identity, DomainId, Identity, BlockNumberFor<T>, T::Hash, OptionQuery>;
680
681    /// A set of `BundleDigest` from all bundles that successfully submitted to the consensus block,
682    /// these bundles will be used to construct the domain block and `ExecutionInbox` is used to:
683    ///
684    /// 1. Ensure subsequent ERs of that domain block include all pre-validated extrinsic bundles
685    /// 2. Index the `InboxedBundleAuthor` and pruned its value when the corresponding `ExecutionInbox` is pruned
686    #[pallet::storage]
687    pub type ExecutionInbox<T: Config> = StorageNMap<
688        _,
689        (
690            NMapKey<Identity, DomainId>,
691            NMapKey<Identity, DomainBlockNumberFor<T>>,
692            NMapKey<Identity, BlockNumberFor<T>>,
693        ),
694        Vec<BundleDigest<T::DomainHash>>,
695        ValueQuery,
696    >;
697
698    /// A mapping of `bundle_header_hash` -> `bundle_author` for all the successfully submitted bundles of
699    /// the last `BlockTreePruningDepth` domain blocks. Used to verify the invalid bundle fraud proof and
700    /// slash malicious operator who have submitted invalid bundle.
701    #[pallet::storage]
702    pub(super) type InboxedBundleAuthor<T: Config> =
703        StorageMap<_, Identity, T::DomainHash, OperatorId, OptionQuery>;
704
705    /// The block number of the best domain block, increase by one when the first bundle of the domain is
706    /// successfully submitted to current consensus block, which mean a new domain block with this block
707    /// number will be produce. Used as a pointer in `ExecutionInbox` to identify the current under building
708    /// domain block, also used as a mapping of consensus block number to domain block number.
709    //
710    // NOTE: the `HeadDomainNumber` is lazily updated for the domain runtime upgrade block (which only include
711    // the runtime upgrade tx from the consensus chain and no any user submitted tx from the bundle), use
712    // `domain_best_number` for the actual best domain block
713    #[pallet::storage]
714    pub(crate) type HeadDomainNumber<T: Config> =
715        StorageMap<_, Identity, DomainId, DomainBlockNumberFor<T>, ValueQuery>;
716
717    /// A temporary storage to hold any previous epoch details for a given domain
718    /// if the epoch transitioned in this block so that all the submitted bundles
719    /// within this block are verified.
720    /// TODO: The storage is cleared on block finalization that means this storage is already cleared when
721    /// verifying the `submit_bundle` extrinsic and not used at all
722    #[pallet::storage]
723    pub(super) type LastEpochStakingDistribution<T: Config> =
724        StorageMap<_, Identity, DomainId, ElectionVerificationParams<BalanceOf<T>>, OptionQuery>;
725
726    /// Storage to hold all the domain's latest confirmed block.
727    #[pallet::storage]
728    #[pallet::getter(fn latest_confirmed_domain_execution_receipt)]
729    pub type LatestConfirmedDomainExecutionReceipt<T: Config> =
730        StorageMap<_, Identity, DomainId, ExecutionReceiptOf<T>, OptionQuery>;
731
732    /// Storage to hold all the domain's genesis execution receipt.
733    #[pallet::storage]
734    #[pallet::getter(fn domain_genesis_block_execution_receipt)]
735    pub type DomainGenesisBlockExecutionReceipt<T: Config> =
736        StorageMap<_, Identity, DomainId, ExecutionReceiptOf<T>, OptionQuery>;
737
738    /// The latest ER submitted by the operator for a given domain. It is used to determine if the operator
739    /// has submitted bad ER and is pending to slash.
740    ///
741    /// The storage item of a given `(domain_id, operator_id)` will be pruned after either:
742    /// - All the ERs submitted by the operator for this domain are confirmed and pruned
743    /// - All the bad ERs submitted by the operator for this domain are pruned and the operator is slashed
744    #[pallet::storage]
745    #[pallet::getter(fn latest_submitted_er)]
746    pub(super) type LatestSubmittedER<T: Config> =
747        StorageMap<_, Identity, (DomainId, OperatorId), DomainBlockNumberFor<T>, ValueQuery>;
748
749    /// Storage for PermissionedActions for domain instantiation and other permissioned calls.
750    #[pallet::storage]
751    pub(super) type PermissionedActionAllowedBy<T: Config> =
752        StorageValue<_, sp_domains::PermissionedActionAllowedBy<T::AccountId>, OptionQuery>;
753
754    /// Accumulate treasury funds temporarily until the funds are above Existential deposit.
755    /// We do this to ensure minting small amounts into treasury would not fail.
756    #[pallet::storage]
757    pub(super) type AccumulatedTreasuryFunds<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;
758
759    /// Storage used to keep track of which consensus block each domain runtime upgrade happens in.
760    #[pallet::storage]
761    pub(super) type DomainRuntimeUpgradeRecords<T: Config> = StorageMap<
762        _,
763        Identity,
764        RuntimeId,
765        BTreeMap<BlockNumberFor<T>, DomainRuntimeUpgradeEntry<T::Hash>>,
766        ValueQuery,
767    >;
768
769    /// Temporary storage to keep track of domain runtime upgrades which happened in the parent
770    /// block. Cleared in the current block's initialization.
771    #[pallet::storage]
772    pub type DomainRuntimeUpgrades<T> = StorageValue<_, Vec<RuntimeId>, ValueQuery>;
773
774    /// Temporary storage to hold the sudo calls meant for domains.
775    ///
776    /// Storage is cleared when there are any successful bundles in the next block.
777    /// Only one sudo call is allowed per domain per consensus block.
778    #[pallet::storage]
779    pub type DomainSudoCalls<T: Config> =
780        StorageMap<_, Identity, DomainId, DomainSudoCall, ValueQuery>;
781
782    /// Storage that hold a list of all frozen domains.
783    ///
784    /// A frozen domain does not accept the bundles but does accept a fraud proof.
785    #[pallet::storage]
786    pub type FrozenDomains<T> = StorageValue<_, BTreeSet<DomainId>, ValueQuery>;
787
788    /// Temporary storage to hold the "set contract creation allowed by" calls meant for EVM Domains.
789    ///
790    /// Storage is cleared when there are any successful bundles in the next block.
791    /// Only one of these calls is allowed per domain per consensus block.
792    #[pallet::storage]
793    pub type EvmDomainContractCreationAllowedByCalls<T: Config> =
794        StorageMap<_, Identity, DomainId, EvmDomainContractCreationAllowedByCall, ValueQuery>;
795
796    /// Storage for chain rewards specific to each domain.
797    /// These rewards to equally distributed to active operators during epoch migration.
798    #[pallet::storage]
799    pub type DomainChainRewards<T: Config> =
800        StorageMap<_, Identity, DomainId, BalanceOf<T>, ValueQuery>;
801
802    /// Storage for operators who are marked as invalid bundle authors in the current epoch.
803    /// Will be cleared once epoch is transitioned.
804    #[pallet::storage]
805    pub type InvalidBundleAuthors<T: Config> =
806        StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, ValueQuery>;
807
808    /// Storage for operators who were de-activated during this epoch.
809    /// Will be cleared once epoch is transitioned.
810    #[pallet::storage]
811    pub type DeactivatedOperators<T: Config> =
812        StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, ValueQuery>;
813
814    /// Storage for operators who de-registered in the current epoch.
815    /// Will be cleared once epoch is transitioned.
816    #[pallet::storage]
817    pub type DeregisteredOperators<T: Config> =
818        StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, ValueQuery>;
819
820    /// Storage that hold a previous versions of Bundle and Execution Receipt.
821    /// Unfortunately, it adds a new item for every runtime upgrade if the versions change between
822    /// runtime upgrades. If the versions does not change, then same version is set with higher block
823    /// number.
824    /// Pruning this storage is not quiet straight forward since each domain
825    /// may submit an ER with a gap as well and also introduces the loop to find the
826    /// correct block number.
827    #[pallet::storage]
828    pub type PreviousBundleAndExecutionReceiptVersions<T> =
829        StorageValue<_, BTreeMap<BlockNumberFor<T>, BundleAndExecutionReceiptVersion>, ValueQuery>;
830
831    /// Stores the slot at which a new epoch has started.
832    #[pallet::storage]
833    pub type EpochStartSlot<T> = StorageValue<_, Slot, OptionQuery>;
834
835    /// Stores the number of bundles each operator submitted in a given epoch.
836    /// Storage is cleared at the end of epoch.
837    #[pallet::storage]
838    pub type OperatorBundleCountInEpoch<T> = StorageMap<_, Identity, OperatorId, u64, ValueQuery>;
839
840    #[derive(TypeInfo, Encode, Decode, PalletError, Debug, PartialEq)]
841    pub enum BundleError {
842        /// Can not find the operator for given operator id.
843        InvalidOperatorId,
844        /// Invalid signature on the bundle header.
845        BadBundleSignature,
846        /// Invalid vrf signature in the proof of election.
847        BadVrfSignature,
848        /// Can not find the domain for given domain id.
849        InvalidDomainId,
850        /// Operator is not allowed to produce bundles in current epoch.
851        BadOperator,
852        /// Failed to pass the threshold check.
853        ThresholdUnsatisfied,
854        /// Invalid Threshold.
855        InvalidThreshold,
856        /// An invalid execution receipt found in the bundle.
857        Receipt(BlockTreeError),
858        /// Bundle size exceed the max bundle size limit in the domain config
859        BundleTooLarge,
860        /// Bundle with an invalid extrinsic root
861        InvalidExtrinsicRoot,
862        /// Invalid proof of time in the proof of election
863        InvalidProofOfTime,
864        /// The bundle is built on a slot in the future
865        SlotInTheFuture,
866        /// The bundle is built on a slot in the past
867        SlotInThePast,
868        /// Bundle weight exceeds the max bundle weight limit
869        BundleTooHeavy,
870        /// The bundle slot is smaller then the highest slot from previous slot
871        /// thus potential equivocated bundle
872        SlotSmallerThanPreviousBlockBundle,
873        /// Equivocated bundle in current block
874        EquivocatedBundle,
875        /// Domain is frozen and cannot accept new bundles
876        DomainFrozen,
877        /// The operator's bundle storage fund unable to pay the storage fee
878        UnableToPayBundleStorageFee,
879        /// Unexpected receipt gap when validating `submit_bundle`
880        UnexpectedReceiptGap,
881        /// Expecting receipt gap when validating `submit_receipt`
882        ExpectingReceiptGap,
883        /// Failed to get missed domain runtime upgrade count
884        FailedToGetMissedUpgradeCount,
885        /// Bundle version mismatch
886        BundleVersionMismatch,
887        /// Execution receipt version mismatch
888        ExecutionVersionMismatch,
889        /// Execution receipt version missing
890        ExecutionVersionMissing,
891    }
892
893    #[derive(TypeInfo, Encode, Decode, PalletError, Debug, PartialEq, DecodeWithMemTracking)]
894    pub enum FraudProofError {
895        /// The targeted bad receipt not found which may already pruned by other
896        /// fraud proof or the fraud proof is submitted to the wrong fork.
897        BadReceiptNotFound,
898        /// The genesis receipt is unchallengeable.
899        ChallengingGenesisReceipt,
900        /// The descendants of the fraudulent ER is not pruned
901        DescendantsOfFraudulentERNotPruned,
902        /// Invalid fraud proof since block fees are not mismatched.
903        InvalidBlockFeesFraudProof,
904        /// Invalid fraud proof since transfers are not mismatched.
905        InvalidTransfersFraudProof,
906        /// Invalid domain block hash fraud proof.
907        InvalidDomainBlockHashFraudProof,
908        /// Invalid domain extrinsic fraud proof
909        InvalidExtrinsicRootFraudProof,
910        /// Invalid state transition fraud proof
911        InvalidStateTransitionFraudProof,
912        /// Parent receipt not found.
913        ParentReceiptNotFound,
914        /// Invalid bundles fraud proof
915        InvalidBundleFraudProof,
916        /// Bad/Invalid valid bundle fraud proof
917        BadValidBundleFraudProof,
918        /// Missing operator.
919        MissingOperator,
920        /// Unexpected fraud proof.
921        UnexpectedFraudProof,
922        /// The bad receipt already reported by a previous fraud proof
923        BadReceiptAlreadyReported,
924        /// Bad MMR proof, it may due to the proof is expired or it is generated against a different fork.
925        BadMmrProof,
926        /// Unexpected MMR proof
927        UnexpectedMmrProof,
928        /// Missing MMR proof
929        MissingMmrProof,
930        /// Domain runtime not found
931        RuntimeNotFound,
932        /// The domain runtime code proof is not provided
933        DomainRuntimeCodeProofNotFound,
934        /// The domain runtime code proof is unexpected
935        UnexpectedDomainRuntimeCodeProof,
936        /// The storage proof is invalid
937        StorageProof(storage_proof::VerificationError),
938    }
939
940    impl From<BundleError> for TransactionValidity {
941        fn from(e: BundleError) -> Self {
942            if BundleError::UnableToPayBundleStorageFee == e {
943                InvalidTransactionCode::BundleStorageFeePayment.into()
944            } else if let BundleError::Receipt(_) = e {
945                InvalidTransactionCode::ExecutionReceipt.into()
946            } else {
947                InvalidTransactionCode::Bundle.into()
948            }
949        }
950    }
951
952    impl From<storage_proof::VerificationError> for FraudProofError {
953        fn from(err: storage_proof::VerificationError) -> Self {
954            FraudProofError::StorageProof(err)
955        }
956    }
957
958    impl<T> From<FraudProofError> for Error<T> {
959        fn from(err: FraudProofError) -> Self {
960            Error::FraudProof(err)
961        }
962    }
963
964    impl<T> From<RuntimeRegistryError> for Error<T> {
965        fn from(err: RuntimeRegistryError) -> Self {
966            Error::RuntimeRegistry(err)
967        }
968    }
969
970    impl<T> From<StakingError> for Error<T> {
971        fn from(err: StakingError) -> Self {
972            Error::Staking(err)
973        }
974    }
975
976    impl<T> From<StakingEpochError> for Error<T> {
977        fn from(err: StakingEpochError) -> Self {
978            Error::StakingEpoch(err)
979        }
980    }
981
982    impl<T> From<DomainRegistryError> for Error<T> {
983        fn from(err: DomainRegistryError) -> Self {
984            Error::DomainRegistry(err)
985        }
986    }
987
988    impl<T> From<BlockTreeError> for Error<T> {
989        fn from(err: BlockTreeError) -> Self {
990            Error::BlockTree(err)
991        }
992    }
993
994    impl From<ProofOfElectionError> for BundleError {
995        fn from(err: ProofOfElectionError) -> Self {
996            match err {
997                ProofOfElectionError::BadVrfProof => Self::BadVrfSignature,
998                ProofOfElectionError::ThresholdUnsatisfied => Self::ThresholdUnsatisfied,
999                ProofOfElectionError::InvalidThreshold => Self::InvalidThreshold,
1000            }
1001        }
1002    }
1003
1004    impl<T> From<BundleStorageFundError> for Error<T> {
1005        fn from(err: BundleStorageFundError) -> Self {
1006            Error::BundleStorageFund(err)
1007        }
1008    }
1009
1010    #[pallet::error]
1011    pub enum Error<T> {
1012        /// Invalid fraud proof.
1013        FraudProof(FraudProofError),
1014        /// Runtime registry specific errors
1015        RuntimeRegistry(RuntimeRegistryError),
1016        /// Staking related errors.
1017        Staking(StakingError),
1018        /// Staking epoch specific errors.
1019        StakingEpoch(StakingEpochError),
1020        /// Domain registry specific errors
1021        DomainRegistry(DomainRegistryError),
1022        /// Block tree specific errors
1023        BlockTree(BlockTreeError),
1024        /// Bundle storage fund specific errors
1025        BundleStorageFund(BundleStorageFundError),
1026        /// Permissioned action is not allowed by the caller.
1027        PermissionedActionNotAllowed,
1028        /// Domain Sudo call already exists.
1029        DomainSudoCallExists,
1030        /// Invalid Domain sudo call.
1031        InvalidDomainSudoCall,
1032        /// Domain must be frozen before execution receipt can be pruned.
1033        DomainNotFrozen,
1034        /// Domain is not a private EVM domain.
1035        NotPrivateEvmDomain,
1036        /// Account is not a Domain owner or root.
1037        NotDomainOwnerOrRoot,
1038        /// EVM Domain "set contract creation allowed by" call already exists.
1039        EvmDomainContractCreationAllowedByCallExists,
1040    }
1041
1042    /// Reason for slashing an operator
1043    #[derive(Clone, Debug, PartialEq, Encode, Decode, TypeInfo, DecodeWithMemTracking)]
1044    pub enum SlashedReason<DomainBlock, ReceiptHash> {
1045        /// Operator produced bad bundle.
1046        InvalidBundle(DomainBlock),
1047        /// Operator submitted bad Execution receipt.
1048        BadExecutionReceipt(ReceiptHash),
1049    }
1050
1051    #[pallet::event]
1052    #[pallet::generate_deposit(pub (super) fn deposit_event)]
1053    pub enum Event<T: Config> {
1054        /// A domain bundle was included.
1055        BundleStored {
1056            domain_id: DomainId,
1057            bundle_hash: H256,
1058            bundle_author: OperatorId,
1059        },
1060        DomainRuntimeCreated {
1061            runtime_id: RuntimeId,
1062            runtime_type: RuntimeType,
1063        },
1064        DomainRuntimeUpgradeScheduled {
1065            runtime_id: RuntimeId,
1066            scheduled_at: BlockNumberFor<T>,
1067        },
1068        DomainRuntimeUpgraded {
1069            runtime_id: RuntimeId,
1070        },
1071        OperatorRegistered {
1072            operator_id: OperatorId,
1073            domain_id: DomainId,
1074        },
1075        NominatedStakedUnlocked {
1076            operator_id: OperatorId,
1077            nominator_id: NominatorId<T>,
1078            unlocked_amount: BalanceOf<T>,
1079        },
1080        StorageFeeUnlocked {
1081            operator_id: OperatorId,
1082            nominator_id: NominatorId<T>,
1083            storage_fee: BalanceOf<T>,
1084        },
1085        OperatorNominated {
1086            operator_id: OperatorId,
1087            nominator_id: NominatorId<T>,
1088            amount: BalanceOf<T>,
1089        },
1090        DomainInstantiated {
1091            domain_id: DomainId,
1092        },
1093        OperatorSwitchedDomain {
1094            old_domain_id: DomainId,
1095            new_domain_id: DomainId,
1096        },
1097        OperatorDeregistered {
1098            operator_id: OperatorId,
1099        },
1100        NominatorUnlocked {
1101            operator_id: OperatorId,
1102            nominator_id: NominatorId<T>,
1103        },
1104        WithdrewStake {
1105            operator_id: OperatorId,
1106            nominator_id: NominatorId<T>,
1107        },
1108        PreferredOperator {
1109            operator_id: OperatorId,
1110            nominator_id: NominatorId<T>,
1111        },
1112        OperatorRewarded {
1113            source: OperatorRewardSource<BlockNumberFor<T>>,
1114            operator_id: OperatorId,
1115            reward: BalanceOf<T>,
1116        },
1117        OperatorTaxCollected {
1118            operator_id: OperatorId,
1119            tax: BalanceOf<T>,
1120        },
1121        DomainEpochCompleted {
1122            domain_id: DomainId,
1123            completed_epoch_index: EpochIndex,
1124        },
1125        ForceDomainEpochTransition {
1126            domain_id: DomainId,
1127            completed_epoch_index: EpochIndex,
1128        },
1129        FraudProofProcessed {
1130            domain_id: DomainId,
1131            new_head_receipt_number: Option<DomainBlockNumberFor<T>>,
1132        },
1133        DomainOperatorAllowListUpdated {
1134            domain_id: DomainId,
1135        },
1136        OperatorSlashed {
1137            operator_id: OperatorId,
1138            reason: SlashedReason<DomainBlockNumberFor<T>, ReceiptHashFor<T>>,
1139        },
1140        StorageFeeDeposited {
1141            operator_id: OperatorId,
1142            nominator_id: NominatorId<T>,
1143            amount: BalanceOf<T>,
1144        },
1145        DomainFrozen {
1146            domain_id: DomainId,
1147        },
1148        DomainUnfrozen {
1149            domain_id: DomainId,
1150        },
1151        PrunedExecutionReceipt {
1152            domain_id: DomainId,
1153            new_head_receipt_number: Option<DomainBlockNumberFor<T>>,
1154        },
1155        OperatorDeactivated {
1156            domain_id: DomainId,
1157            operator_id: OperatorId,
1158            reactivation_delay: EpochIndex,
1159        },
1160        OperatorReactivated {
1161            operator_id: OperatorId,
1162            domain_id: DomainId,
1163        },
1164        OperatorOffline {
1165            operator_id: OperatorId,
1166            domain_id: DomainId,
1167            submitted_bundles: u64,
1168            expectations: OperatorEpochExpectations,
1169        },
1170    }
1171
1172    #[pallet::origin]
1173    pub type Origin = RawOrigin;
1174
1175    /// Per-domain state for tx range calculation.
1176    #[derive(Debug, Default, Decode, Encode, TypeInfo, PartialEq, Eq)]
1177    pub struct TxRangeState {
1178        /// Current tx range.
1179        pub tx_range: U256,
1180
1181        /// Blocks in the current adjustment interval.
1182        pub interval_blocks: u64,
1183
1184        /// Bundles in the current adjustment interval.
1185        pub interval_bundles: u64,
1186    }
1187
1188    impl TxRangeState {
1189        /// Called when a bundle is added to the current block.
1190        pub fn on_bundle(&mut self) {
1191            self.interval_bundles += 1;
1192        }
1193    }
1194
1195    #[pallet::storage]
1196    pub(super) type DomainTxRangeState<T: Config> =
1197        StorageMap<_, Identity, DomainId, TxRangeState, OptionQuery>;
1198
1199    #[pallet::call]
1200    impl<T: Config> Pallet<T> {
1201        #[pallet::call_index(0)]
1202        #[pallet::weight(Pallet::<T>::max_submit_bundle_weight())]
1203        pub fn submit_bundle(
1204            origin: OriginFor<T>,
1205            opaque_bundle: OpaqueBundleOf<T>,
1206        ) -> DispatchResultWithPostInfo {
1207            T::DomainOrigin::ensure_origin(origin)?;
1208
1209            log::trace!("Processing bundle: {opaque_bundle:?}");
1210
1211            let domain_id = opaque_bundle.domain_id();
1212            let bundle_hash = opaque_bundle.hash();
1213            let bundle_header_hash = opaque_bundle.sealed_header().pre_hash();
1214            let extrinsics_root = opaque_bundle.extrinsics_root();
1215            let operator_id = opaque_bundle.operator_id();
1216            let bundle_size = opaque_bundle.size();
1217            let slot_number = opaque_bundle.slot_number();
1218            let receipt = opaque_bundle.into_receipt();
1219            #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))]
1220            let receipt_block_number = *receipt.domain_block_number();
1221
1222            // increment the operator bundle count in the epoch.
1223            OperatorBundleCountInEpoch::<T>::mutate(operator_id, |c| {
1224                *c = c.saturating_add(1);
1225            });
1226
1227            #[cfg(not(feature = "runtime-benchmarks"))]
1228            let mut actual_weight = T::WeightInfo::submit_bundle();
1229            #[cfg(feature = "runtime-benchmarks")]
1230            let actual_weight = T::WeightInfo::submit_bundle();
1231
1232            match execution_receipt_type::<T>(domain_id, &receipt.as_execution_receipt_ref()) {
1233                ReceiptType::Rejected(rejected_receipt_type) => {
1234                    return Err(Error::<T>::BlockTree(rejected_receipt_type.into()).into());
1235                }
1236                // Add the execution receipt to the block tree
1237                ReceiptType::Accepted(accepted_receipt_type) => {
1238                    // Before adding the new head receipt to the block tree, try to prune any previous
1239                    // bad ER at the same domain block and slash the submitter.
1240                    //
1241                    // NOTE: Skip the following staking related operations when benchmarking the
1242                    // `submit_bundle` call, these operations will be benchmarked separately.
1243                    #[cfg(not(feature = "runtime-benchmarks"))]
1244                    if accepted_receipt_type == AcceptedReceiptType::NewHead
1245                        && let Some(BlockTreeNode {
1246                            execution_receipt,
1247                            operator_ids,
1248                        }) = prune_receipt::<T>(domain_id, receipt_block_number)
1249                            .map_err(Error::<T>::from)?
1250                    {
1251                        actual_weight = actual_weight.saturating_add(
1252                            T::WeightInfo::handle_bad_receipt(operator_ids.len() as u32),
1253                        );
1254
1255                        let bad_receipt_hash = execution_receipt.hash::<DomainHashingFor<T>>();
1256                        do_mark_operators_as_slashed::<T>(
1257                            operator_ids.into_iter(),
1258                            SlashedReason::BadExecutionReceipt(bad_receipt_hash),
1259                        )
1260                        .map_err(Error::<T>::from)?;
1261
1262                        do_unmark_invalid_bundle_authors::<T>(domain_id, &execution_receipt)
1263                            .map_err(Error::<T>::from)?;
1264                    }
1265
1266                    if accepted_receipt_type == AcceptedReceiptType::NewHead {
1267                        // when a new receipt is accepted and extending the chain,
1268                        // also mark the invalid bundle authors from this er
1269                        do_mark_invalid_bundle_authors::<T>(domain_id, &receipt)
1270                            .map_err(Error::<T>::Staking)?;
1271                    }
1272
1273                    #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))]
1274                    let maybe_confirmed_domain_block_info = process_execution_receipt::<T>(
1275                        domain_id,
1276                        operator_id,
1277                        receipt,
1278                        accepted_receipt_type,
1279                    )
1280                    .map_err(Error::<T>::from)?;
1281
1282                    // If any domain block is confirmed, then we have a new head added
1283                    // so distribute the operator rewards and, if required, do epoch transition as well.
1284                    //
1285                    // NOTE: Skip the following staking related operations when benchmarking the
1286                    // `submit_bundle` call, these operations will be benchmarked separately.
1287                    #[cfg(not(feature = "runtime-benchmarks"))]
1288                    if let Some(confirmed_block_info) = maybe_confirmed_domain_block_info {
1289                        actual_weight =
1290                            actual_weight.saturating_add(T::WeightInfo::confirm_domain_block(
1291                                confirmed_block_info.operator_ids.len() as u32,
1292                                confirmed_block_info.invalid_bundle_authors.len() as u32,
1293                            ));
1294
1295                        refund_storage_fee::<T>(
1296                            confirmed_block_info.total_storage_fee,
1297                            confirmed_block_info.paid_bundle_storage_fees,
1298                        )
1299                        .map_err(Error::<T>::from)?;
1300
1301                        do_reward_operators::<T>(
1302                            domain_id,
1303                            OperatorRewardSource::Bundle {
1304                                at_block_number: confirmed_block_info.consensus_block_number,
1305                            },
1306                            confirmed_block_info.operator_ids.into_iter(),
1307                            confirmed_block_info.rewards,
1308                        )
1309                        .map_err(Error::<T>::from)?;
1310
1311                        do_mark_operators_as_slashed::<T>(
1312                            confirmed_block_info.invalid_bundle_authors.into_iter(),
1313                            SlashedReason::InvalidBundle(confirmed_block_info.domain_block_number),
1314                        )
1315                        .map_err(Error::<T>::from)?;
1316                    }
1317                }
1318            }
1319
1320            // `SuccessfulBundles` is empty means this is the first accepted bundle for this domain in this
1321            // consensus block, which also mean a domain block will be produced thus update `HeadDomainNumber`
1322            // to this domain block's block number.
1323            if SuccessfulBundles::<T>::get(domain_id).is_empty() {
1324                // Domain runtime upgrade is forced to happen, even if there is no bundle submitted for a given domain
1325                // it will still derive a domain block for the upgrade, so we need to increase the `HeadDomainNumber`
1326                // by the number of runtime upgrades that happened since the last block, to account for these blocks.
1327                //
1328                // NOTE: if a domain runtime upgrade happened in the current block it won't be accounted for in
1329                // `missed_upgrade` because `DomainRuntimeUpgradeRecords` is updated in the next block's initialization.
1330                let missed_upgrade =
1331                    Self::missed_domain_runtime_upgrade(domain_id).map_err(Error::<T>::from)?;
1332
1333                let next_number = HeadDomainNumber::<T>::get(domain_id)
1334                    .checked_add(&One::one())
1335                    .ok_or::<Error<T>>(BlockTreeError::MaxHeadDomainNumber.into())?
1336                    .checked_add(&missed_upgrade.into())
1337                    .ok_or::<Error<T>>(BlockTreeError::MaxHeadDomainNumber.into())?;
1338
1339                // Trigger an epoch transition, if needed, at the first bundle in the block
1340                #[cfg(not(feature = "runtime-benchmarks"))]
1341                if next_number % T::StakeEpochDuration::get() == Zero::zero() {
1342                    let epoch_transition_res = do_finalize_domain_current_epoch::<T>(domain_id)
1343                        .map_err(Error::<T>::from)?;
1344
1345                    Self::deposit_event(Event::DomainEpochCompleted {
1346                        domain_id,
1347                        completed_epoch_index: epoch_transition_res.completed_epoch_index,
1348                    });
1349
1350                    actual_weight = actual_weight
1351                        .saturating_add(Self::actual_epoch_transition_weight(epoch_transition_res));
1352                }
1353
1354                HeadDomainNumber::<T>::set(domain_id, next_number);
1355            }
1356
1357            // Put the `extrinsics_root` into the inbox of the current domain block being built
1358            let head_domain_number = HeadDomainNumber::<T>::get(domain_id);
1359            let consensus_block_number = frame_system::Pallet::<T>::current_block_number();
1360            ExecutionInbox::<T>::append(
1361                (domain_id, head_domain_number, consensus_block_number),
1362                BundleDigest {
1363                    header_hash: bundle_header_hash,
1364                    extrinsics_root,
1365                    size: bundle_size,
1366                },
1367            );
1368
1369            InboxedBundleAuthor::<T>::insert(bundle_header_hash, operator_id);
1370
1371            SuccessfulBundles::<T>::append(domain_id, bundle_hash);
1372
1373            OperatorBundleSlot::<T>::mutate(operator_id, |slot_set| slot_set.insert(slot_number));
1374
1375            // slash operators who are in pending slash
1376            #[cfg(not(feature = "runtime-benchmarks"))]
1377            {
1378                let slashed_nominator_count =
1379                    do_slash_operator::<T>(domain_id, MAX_NOMINATORS_TO_SLASH)
1380                        .map_err(Error::<T>::from)?;
1381                actual_weight = actual_weight
1382                    .saturating_add(T::WeightInfo::slash_operator(slashed_nominator_count));
1383            }
1384
1385            Self::deposit_event(Event::BundleStored {
1386                domain_id,
1387                bundle_hash,
1388                bundle_author: operator_id,
1389            });
1390
1391            // Ensure the returned weight not exceed the maximum weight in the `pallet::weight`
1392            Ok(Some(actual_weight.min(Self::max_submit_bundle_weight())).into())
1393        }
1394
1395        #[pallet::call_index(15)]
1396        #[pallet::weight((
1397            T::WeightInfo::submit_fraud_proof().saturating_add(
1398                T::WeightInfo::handle_bad_receipt(MAX_BUNDLE_PER_BLOCK)
1399            ),
1400            DispatchClass::Operational
1401        ))]
1402        pub fn submit_fraud_proof(
1403            origin: OriginFor<T>,
1404            fraud_proof: Box<FraudProofFor<T>>,
1405        ) -> DispatchResultWithPostInfo {
1406            T::DomainOrigin::ensure_origin(origin)?;
1407
1408            log::trace!("Processing fraud proof: {fraud_proof:?}");
1409
1410            #[cfg(not(feature = "runtime-benchmarks"))]
1411            let mut actual_weight = T::WeightInfo::submit_fraud_proof();
1412            #[cfg(feature = "runtime-benchmarks")]
1413            let actual_weight = T::WeightInfo::submit_fraud_proof();
1414
1415            let domain_id = fraud_proof.domain_id();
1416            let bad_receipt_hash = fraud_proof.targeted_bad_receipt_hash();
1417            let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
1418            let bad_receipt_number = *BlockTreeNodes::<T>::get(bad_receipt_hash)
1419                .ok_or::<Error<T>>(FraudProofError::BadReceiptNotFound.into())?
1420                .execution_receipt
1421                .domain_block_number();
1422            // The `head_receipt_number` must greater than or equal to any existing receipt, including
1423            // the bad receipt, otherwise the fraud proof should be rejected due to `BadReceiptNotFound`,
1424            // double check here to make it more robust.
1425            ensure!(
1426                head_receipt_number >= bad_receipt_number,
1427                Error::<T>::from(FraudProofError::BadReceiptNotFound),
1428            );
1429
1430            // Prune the bad ER and slash the submitter, the descendants of the bad ER (i.e. all ERs in
1431            // `[bad_receipt_number + 1..head_receipt_number]` ) and the corresponding submitter will be
1432            // pruned/slashed lazily as the domain progressed.
1433            //
1434            // NOTE: Skip the following staking related operations when benchmarking the
1435            // `submit_fraud_proof` call, these operations will be benchmarked separately.
1436            #[cfg(not(feature = "runtime-benchmarks"))]
1437            {
1438                let BlockTreeNode {
1439                    execution_receipt,
1440                    operator_ids,
1441                } = prune_receipt::<T>(domain_id, bad_receipt_number)
1442                    .map_err(Error::<T>::from)?
1443                    .ok_or::<Error<T>>(FraudProofError::BadReceiptNotFound.into())?;
1444
1445                actual_weight = actual_weight.saturating_add(T::WeightInfo::handle_bad_receipt(
1446                    (operator_ids.len() as u32).min(MAX_BUNDLE_PER_BLOCK),
1447                ));
1448
1449                do_mark_operators_as_slashed::<T>(
1450                    operator_ids.into_iter(),
1451                    SlashedReason::BadExecutionReceipt(bad_receipt_hash),
1452                )
1453                .map_err(Error::<T>::from)?;
1454
1455                // unmark any operators who are incorrectly marked as invalid bundle authors.
1456                do_unmark_invalid_bundle_authors::<T>(domain_id, &execution_receipt)
1457                    .map_err(Error::<T>::Staking)?;
1458            }
1459
1460            // Update the head receipt number to `bad_receipt_number - 1`
1461            let new_head_receipt_number = bad_receipt_number.saturating_sub(One::one());
1462            HeadReceiptNumber::<T>::insert(domain_id, new_head_receipt_number);
1463
1464            Self::deposit_event(Event::FraudProofProcessed {
1465                domain_id,
1466                new_head_receipt_number: Some(new_head_receipt_number),
1467            });
1468
1469            Ok(Some(actual_weight).into())
1470        }
1471
1472        #[pallet::call_index(2)]
1473        #[pallet::weight(T::WeightInfo::register_domain_runtime())]
1474        pub fn register_domain_runtime(
1475            origin: OriginFor<T>,
1476            runtime_name: String,
1477            runtime_type: RuntimeType,
1478            // TODO: we can use `RawGenesis` as argument directly to avoid decoding but the in tool like
1479            // `polkadot.js` it will require the user to provide each field of the struct type and not
1480            // support uploading file, which is bad UX.
1481            raw_genesis_storage: Vec<u8>,
1482        ) -> DispatchResult {
1483            ensure_root(origin)?;
1484
1485            let block_number = frame_system::Pallet::<T>::current_block_number();
1486            let runtime_id = do_register_runtime::<T>(
1487                runtime_name,
1488                runtime_type,
1489                raw_genesis_storage,
1490                block_number,
1491            )
1492            .map_err(Error::<T>::from)?;
1493
1494            Self::deposit_event(Event::DomainRuntimeCreated {
1495                runtime_id,
1496                runtime_type,
1497            });
1498
1499            Ok(())
1500        }
1501
1502        #[pallet::call_index(3)]
1503        #[pallet::weight(T::WeightInfo::upgrade_domain_runtime())]
1504        pub fn upgrade_domain_runtime(
1505            origin: OriginFor<T>,
1506            runtime_id: RuntimeId,
1507            raw_genesis_storage: Vec<u8>,
1508        ) -> DispatchResult {
1509            ensure_root(origin)?;
1510
1511            let block_number = frame_system::Pallet::<T>::current_block_number();
1512            let scheduled_at =
1513                do_schedule_runtime_upgrade::<T>(runtime_id, raw_genesis_storage, block_number)
1514                    .map_err(Error::<T>::from)?;
1515
1516            Self::deposit_event(Event::DomainRuntimeUpgradeScheduled {
1517                runtime_id,
1518                scheduled_at,
1519            });
1520
1521            Ok(())
1522        }
1523
1524        #[pallet::call_index(4)]
1525        #[pallet::weight(T::WeightInfo::register_operator())]
1526        pub fn register_operator(
1527            origin: OriginFor<T>,
1528            domain_id: DomainId,
1529            amount: BalanceOf<T>,
1530            config: OperatorConfig<BalanceOf<T>>,
1531        ) -> DispatchResult {
1532            let owner = ensure_signed(origin)?;
1533
1534            let (operator_id, current_epoch_index) =
1535                do_register_operator::<T>(owner, domain_id, amount, config)
1536                    .map_err(Error::<T>::from)?;
1537
1538            Self::deposit_event(Event::OperatorRegistered {
1539                operator_id,
1540                domain_id,
1541            });
1542
1543            // if the domain's current epoch is 0,
1544            // then do an epoch transition so that operator can start producing bundles
1545            if current_epoch_index.is_zero() {
1546                do_finalize_domain_current_epoch::<T>(domain_id).map_err(Error::<T>::from)?;
1547            }
1548
1549            Ok(())
1550        }
1551
1552        #[pallet::call_index(5)]
1553        #[pallet::weight(T::WeightInfo::nominate_operator())]
1554        pub fn nominate_operator(
1555            origin: OriginFor<T>,
1556            operator_id: OperatorId,
1557            amount: BalanceOf<T>,
1558        ) -> DispatchResult {
1559            let nominator_id = ensure_signed(origin)?;
1560
1561            do_nominate_operator::<T>(operator_id, nominator_id.clone(), amount)
1562                .map_err(Error::<T>::from)?;
1563
1564            Ok(())
1565        }
1566
1567        #[pallet::call_index(6)]
1568        #[pallet::weight(T::WeightInfo::instantiate_domain())]
1569        pub fn instantiate_domain(
1570            origin: OriginFor<T>,
1571            domain_config_params: DomainConfigParams<T::AccountId, BalanceOf<T>>,
1572        ) -> DispatchResult {
1573            let who = ensure_signed(origin)?;
1574            ensure!(
1575                PermissionedActionAllowedBy::<T>::get()
1576                    .map(|allowed_by| allowed_by.is_allowed(&who))
1577                    .unwrap_or_default(),
1578                Error::<T>::PermissionedActionNotAllowed
1579            );
1580
1581            let created_at = frame_system::Pallet::<T>::current_block_number();
1582
1583            let domain_id = do_instantiate_domain::<T>(domain_config_params, who, created_at)
1584                .map_err(Error::<T>::from)?;
1585
1586            Self::deposit_event(Event::DomainInstantiated { domain_id });
1587
1588            Ok(())
1589        }
1590
1591        #[pallet::call_index(8)]
1592        #[pallet::weight(Pallet::<T>::max_deregister_operator())]
1593        pub fn deregister_operator(
1594            origin: OriginFor<T>,
1595            operator_id: OperatorId,
1596        ) -> DispatchResultWithPostInfo {
1597            let who = ensure_signed(origin)?;
1598
1599            let executed_weight =
1600                do_deregister_operator::<T>(who, operator_id).map_err(Error::<T>::from)?;
1601
1602            Self::deposit_event(Event::OperatorDeregistered { operator_id });
1603
1604            let actual_weight = executed_weight.min(Pallet::<T>::max_deregister_operator());
1605            Ok(Some(actual_weight).into())
1606        }
1607
1608        #[pallet::call_index(9)]
1609        #[pallet::weight(Pallet::<T>::max_withdraw_stake())]
1610        pub fn withdraw_stake(
1611            origin: OriginFor<T>,
1612            operator_id: OperatorId,
1613            to_withdraw: T::Share,
1614        ) -> DispatchResultWithPostInfo {
1615            let who = ensure_signed(origin)?;
1616
1617            let executed_weight = do_withdraw_stake::<T>(operator_id, who.clone(), to_withdraw)
1618                .map_err(Error::<T>::from)?;
1619
1620            Self::deposit_event(Event::WithdrewStake {
1621                operator_id,
1622                nominator_id: who,
1623            });
1624
1625            let actual_weight = executed_weight.min(Pallet::<T>::max_withdraw_stake());
1626            Ok(Some(actual_weight).into())
1627        }
1628
1629        /// Unlocks the first withdrawal given the unlocking period is complete.
1630        /// Even if the rest of the withdrawals are out of the unlocking period, the nominator
1631        /// should call this extrinsic to unlock each withdrawal
1632        #[pallet::call_index(10)]
1633        #[pallet::weight(T::WeightInfo::unlock_funds(T::WithdrawalLimit::get()))]
1634        pub fn unlock_funds(
1635            origin: OriginFor<T>,
1636            operator_id: OperatorId,
1637        ) -> DispatchResultWithPostInfo {
1638            let nominator_id = ensure_signed(origin)?;
1639            let withdrawal_count = do_unlock_funds::<T>(operator_id, nominator_id.clone())
1640                .map_err(crate::pallet::Error::<T>::from)?;
1641
1642            Ok(Some(T::WeightInfo::unlock_funds(
1643                withdrawal_count.min(T::WithdrawalLimit::get()),
1644            ))
1645            .into())
1646        }
1647
1648        /// Unlocks the nominator under given operator given the unlocking period is complete.
1649        /// A nominator can initiate their unlock given operator is already deregistered.
1650        #[pallet::call_index(11)]
1651        #[pallet::weight(T::WeightInfo::unlock_nominator())]
1652        pub fn unlock_nominator(origin: OriginFor<T>, operator_id: OperatorId) -> DispatchResult {
1653            let nominator = ensure_signed(origin)?;
1654
1655            do_unlock_nominator::<T>(operator_id, nominator.clone())
1656                .map_err(crate::pallet::Error::<T>::from)?;
1657
1658            Self::deposit_event(Event::NominatorUnlocked {
1659                operator_id,
1660                nominator_id: nominator,
1661            });
1662
1663            Ok(())
1664        }
1665
1666        /// Extrinsic to update domain's operator allow list.
1667        /// Note:
1668        /// - If the previous allowed list is set to specific operators and new allow list is set
1669        ///   to `Anyone`, then domain will become permissioned to open for all operators.
1670        /// - If the previous allowed list is set to `Anyone` or specific operators and the new
1671        ///   allow list is set to specific operators, then all the registered not allowed operators
1672        ///   will continue to operate until they de-register themselves.
1673        #[pallet::call_index(12)]
1674        #[pallet::weight(T::WeightInfo::update_domain_operator_allow_list())]
1675        pub fn update_domain_operator_allow_list(
1676            origin: OriginFor<T>,
1677            domain_id: DomainId,
1678            operator_allow_list: OperatorAllowList<T::AccountId>,
1679        ) -> DispatchResult {
1680            let who = ensure_signed(origin)?;
1681            do_update_domain_allow_list::<T>(who, domain_id, operator_allow_list)
1682                .map_err(Error::<T>::from)?;
1683            Self::deposit_event(crate::pallet::Event::DomainOperatorAllowListUpdated { domain_id });
1684            Ok(())
1685        }
1686
1687        /// Force staking epoch transition for a given domain
1688        #[pallet::call_index(13)]
1689        #[pallet::weight(Pallet::<T>::max_staking_epoch_transition())]
1690        pub fn force_staking_epoch_transition(
1691            origin: OriginFor<T>,
1692            domain_id: DomainId,
1693        ) -> DispatchResultWithPostInfo {
1694            ensure_root(origin)?;
1695
1696            let epoch_transition_res =
1697                do_finalize_domain_current_epoch::<T>(domain_id).map_err(Error::<T>::from)?;
1698
1699            Self::deposit_event(Event::ForceDomainEpochTransition {
1700                domain_id,
1701                completed_epoch_index: epoch_transition_res.completed_epoch_index,
1702            });
1703
1704            // Ensure the returned weight not exceed the maximum weight in the `pallet::weight`
1705            let actual_weight = Self::actual_epoch_transition_weight(epoch_transition_res)
1706                .min(Self::max_staking_epoch_transition());
1707
1708            Ok(Some(actual_weight).into())
1709        }
1710
1711        /// Update permissioned action allowed by storage by Sudo.
1712        #[pallet::call_index(14)]
1713        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(0, 1))]
1714        pub fn set_permissioned_action_allowed_by(
1715            origin: OriginFor<T>,
1716            permissioned_action_allowed_by: sp_domains::PermissionedActionAllowedBy<T::AccountId>,
1717        ) -> DispatchResult {
1718            ensure_root(origin)?;
1719            PermissionedActionAllowedBy::<T>::put(permissioned_action_allowed_by);
1720            Ok(())
1721        }
1722
1723        /// Submit a domain sudo call.
1724        #[pallet::call_index(16)]
1725        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(3, 1))]
1726        pub fn send_domain_sudo_call(
1727            origin: OriginFor<T>,
1728            domain_id: DomainId,
1729            call: Vec<u8>,
1730        ) -> DispatchResult {
1731            ensure_root(origin)?;
1732            ensure!(
1733                DomainSudoCalls::<T>::get(domain_id).maybe_call.is_none(),
1734                Error::<T>::DomainSudoCallExists
1735            );
1736
1737            let domain_runtime = Self::domain_runtime_code(domain_id).ok_or(
1738                Error::<T>::DomainRegistry(DomainRegistryError::DomainNotFound),
1739            )?;
1740            ensure!(
1741                domain_runtime_call(
1742                    domain_runtime,
1743                    StatelessDomainRuntimeCall::IsValidDomainSudoCall(call.clone()),
1744                )
1745                .unwrap_or(false),
1746                Error::<T>::InvalidDomainSudoCall
1747            );
1748
1749            DomainSudoCalls::<T>::set(
1750                domain_id,
1751                DomainSudoCall {
1752                    maybe_call: Some(call),
1753                },
1754            );
1755            Ok(())
1756        }
1757
1758        /// Freezes a given domain.
1759        /// A frozen domain does not accept new bundles but accepts fraud proofs.
1760        #[pallet::call_index(17)]
1761        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(0, 1))]
1762        pub fn freeze_domain(origin: OriginFor<T>, domain_id: DomainId) -> DispatchResult {
1763            ensure_root(origin)?;
1764            FrozenDomains::<T>::mutate(|frozen_domains| frozen_domains.insert(domain_id));
1765            Self::deposit_event(Event::DomainFrozen { domain_id });
1766            Ok(())
1767        }
1768
1769        /// Unfreezes a frozen domain.
1770        #[pallet::call_index(18)]
1771        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(0, 1))]
1772        pub fn unfreeze_domain(origin: OriginFor<T>, domain_id: DomainId) -> DispatchResult {
1773            ensure_root(origin)?;
1774            FrozenDomains::<T>::mutate(|frozen_domains| frozen_domains.remove(&domain_id));
1775            Self::deposit_event(Event::DomainUnfrozen { domain_id });
1776            Ok(())
1777        }
1778
1779        /// Prunes a given execution receipt for given frozen domain.
1780        /// This call assumes the execution receipt to be bad and implicitly trusts Sudo
1781        /// to do the necessary validation of the ER before dispatching this call.
1782        #[pallet::call_index(19)]
1783        #[pallet::weight(Pallet::<T>::max_prune_domain_execution_receipt())]
1784        pub fn prune_domain_execution_receipt(
1785            origin: OriginFor<T>,
1786            domain_id: DomainId,
1787            bad_receipt_hash: ReceiptHashFor<T>,
1788        ) -> DispatchResultWithPostInfo {
1789            ensure_root(origin)?;
1790            ensure!(
1791                FrozenDomains::<T>::get().contains(&domain_id),
1792                Error::<T>::DomainNotFrozen
1793            );
1794
1795            let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
1796            let bad_receipt_number = *BlockTreeNodes::<T>::get(bad_receipt_hash)
1797                .ok_or::<Error<T>>(FraudProofError::BadReceiptNotFound.into())?
1798                .execution_receipt
1799                .domain_block_number();
1800            // The `head_receipt_number` must greater than or equal to any existing receipt, including
1801            // the bad receipt.
1802            ensure!(
1803                head_receipt_number >= bad_receipt_number,
1804                Error::<T>::from(FraudProofError::BadReceiptNotFound),
1805            );
1806
1807            let mut actual_weight = T::DbWeight::get().reads(3);
1808
1809            // prune the bad ER
1810            let BlockTreeNode {
1811                execution_receipt,
1812                operator_ids,
1813            } = prune_receipt::<T>(domain_id, bad_receipt_number)
1814                .map_err(Error::<T>::from)?
1815                .ok_or::<Error<T>>(FraudProofError::BadReceiptNotFound.into())?;
1816
1817            actual_weight = actual_weight.saturating_add(T::WeightInfo::handle_bad_receipt(
1818                (operator_ids.len() as u32).min(MAX_BUNDLE_PER_BLOCK),
1819            ));
1820
1821            do_mark_operators_as_slashed::<T>(
1822                operator_ids.into_iter(),
1823                SlashedReason::BadExecutionReceipt(bad_receipt_hash),
1824            )
1825            .map_err(Error::<T>::from)?;
1826
1827            // unmark any operators who are incorrectly marked as invalid bundle authors.
1828            do_unmark_invalid_bundle_authors::<T>(domain_id, &execution_receipt)
1829                .map_err(Error::<T>::Staking)?;
1830
1831            // Update the head receipt number to `bad_receipt_number - 1`
1832            let new_head_receipt_number = bad_receipt_number.saturating_sub(One::one());
1833            HeadReceiptNumber::<T>::insert(domain_id, new_head_receipt_number);
1834            actual_weight = actual_weight.saturating_add(T::DbWeight::get().reads_writes(0, 1));
1835
1836            Self::deposit_event(Event::PrunedExecutionReceipt {
1837                domain_id,
1838                new_head_receipt_number: Some(new_head_receipt_number),
1839            });
1840
1841            Ok(Some(actual_weight).into())
1842        }
1843
1844        /// Transfer funds from treasury to given account
1845        #[pallet::call_index(20)]
1846        #[pallet::weight(T::WeightInfo::transfer_treasury_funds())]
1847        pub fn transfer_treasury_funds(
1848            origin: OriginFor<T>,
1849            account_id: T::AccountId,
1850            balance: BalanceOf<T>,
1851        ) -> DispatchResult {
1852            ensure_root(origin)?;
1853            T::Currency::transfer(
1854                &T::TreasuryAccount::get(),
1855                &account_id,
1856                balance,
1857                Preservation::Preserve,
1858            )?;
1859            Ok(())
1860        }
1861
1862        #[pallet::call_index(21)]
1863        #[pallet::weight(Pallet::<T>::max_submit_receipt_weight())]
1864        pub fn submit_receipt(
1865            origin: OriginFor<T>,
1866            singleton_receipt: SingletonReceiptOf<T>,
1867        ) -> DispatchResultWithPostInfo {
1868            T::DomainOrigin::ensure_origin(origin)?;
1869
1870            let domain_id = singleton_receipt.domain_id();
1871            let operator_id = singleton_receipt.operator_id();
1872            let receipt = singleton_receipt.into_receipt();
1873
1874            #[cfg(not(feature = "runtime-benchmarks"))]
1875            let mut actual_weight = T::WeightInfo::submit_receipt();
1876            #[cfg(feature = "runtime-benchmarks")]
1877            let actual_weight = T::WeightInfo::submit_receipt();
1878
1879            match execution_receipt_type::<T>(domain_id, &receipt.as_execution_receipt_ref()) {
1880                ReceiptType::Rejected(rejected_receipt_type) => {
1881                    return Err(Error::<T>::BlockTree(rejected_receipt_type.into()).into());
1882                }
1883                // Add the execution receipt to the block tree
1884                ReceiptType::Accepted(accepted_receipt_type) => {
1885                    // Before adding the new head receipt to the block tree, try to prune any previous
1886                    // bad ER at the same domain block and slash the submitter.
1887                    //
1888                    // NOTE: Skip the following staking related operations when benchmarking the
1889                    // `submit_receipt` call, these operations will be benchmarked separately.
1890                    #[cfg(not(feature = "runtime-benchmarks"))]
1891                    if accepted_receipt_type == AcceptedReceiptType::NewHead
1892                        && let Some(BlockTreeNode {
1893                            execution_receipt,
1894                            operator_ids,
1895                        }) = prune_receipt::<T>(domain_id, *receipt.domain_block_number())
1896                            .map_err(Error::<T>::from)?
1897                    {
1898                        actual_weight = actual_weight.saturating_add(
1899                            T::WeightInfo::handle_bad_receipt(operator_ids.len() as u32),
1900                        );
1901
1902                        let bad_receipt_hash = execution_receipt.hash::<DomainHashingFor<T>>();
1903                        do_mark_operators_as_slashed::<T>(
1904                            operator_ids.into_iter(),
1905                            SlashedReason::BadExecutionReceipt(bad_receipt_hash),
1906                        )
1907                        .map_err(Error::<T>::from)?;
1908
1909                        do_unmark_invalid_bundle_authors::<T>(domain_id, &execution_receipt)
1910                            .map_err(Error::<T>::from)?;
1911                    }
1912
1913                    if accepted_receipt_type == AcceptedReceiptType::NewHead {
1914                        // when a new receipt is accepted and extending the chain,
1915                        // also mark the invalid bundle authors from this er
1916                        do_mark_invalid_bundle_authors::<T>(domain_id, &receipt)
1917                            .map_err(Error::<T>::Staking)?;
1918                    }
1919
1920                    #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))]
1921                    let maybe_confirmed_domain_block_info = process_execution_receipt::<T>(
1922                        domain_id,
1923                        operator_id,
1924                        receipt,
1925                        accepted_receipt_type,
1926                    )
1927                    .map_err(Error::<T>::from)?;
1928
1929                    // NOTE: Skip the following staking related operations when benchmarking the
1930                    // `submit_receipt` call, these operations will be benchmarked separately.
1931                    #[cfg(not(feature = "runtime-benchmarks"))]
1932                    if let Some(confirmed_block_info) = maybe_confirmed_domain_block_info {
1933                        actual_weight =
1934                            actual_weight.saturating_add(T::WeightInfo::confirm_domain_block(
1935                                confirmed_block_info.operator_ids.len() as u32,
1936                                confirmed_block_info.invalid_bundle_authors.len() as u32,
1937                            ));
1938
1939                        refund_storage_fee::<T>(
1940                            confirmed_block_info.total_storage_fee,
1941                            confirmed_block_info.paid_bundle_storage_fees,
1942                        )
1943                        .map_err(Error::<T>::from)?;
1944
1945                        do_reward_operators::<T>(
1946                            domain_id,
1947                            OperatorRewardSource::Bundle {
1948                                at_block_number: confirmed_block_info.consensus_block_number,
1949                            },
1950                            confirmed_block_info.operator_ids.into_iter(),
1951                            confirmed_block_info.rewards,
1952                        )
1953                        .map_err(Error::<T>::from)?;
1954
1955                        do_mark_operators_as_slashed::<T>(
1956                            confirmed_block_info.invalid_bundle_authors.into_iter(),
1957                            SlashedReason::InvalidBundle(confirmed_block_info.domain_block_number),
1958                        )
1959                        .map_err(Error::<T>::from)?;
1960                    }
1961                }
1962            }
1963
1964            // slash operator who are in pending slash
1965            #[cfg(not(feature = "runtime-benchmarks"))]
1966            {
1967                let slashed_nominator_count =
1968                    do_slash_operator::<T>(domain_id, MAX_NOMINATORS_TO_SLASH)
1969                        .map_err(Error::<T>::from)?;
1970                actual_weight = actual_weight
1971                    .saturating_add(T::WeightInfo::slash_operator(slashed_nominator_count));
1972            }
1973
1974            // Ensure the returned weight not exceed the maximum weight in the `pallet::weight`
1975            Ok(Some(actual_weight.min(Self::max_submit_receipt_weight())).into())
1976        }
1977
1978        /// Submit an EVM domain "set contract creation allowed by" call as domain owner or root.
1979        #[pallet::call_index(22)]
1980        #[pallet::weight(<T as frame_system::Config>::DbWeight::get().reads_writes(3, 1))]
1981        pub fn send_evm_domain_set_contract_creation_allowed_by_call(
1982            origin: OriginFor<T>,
1983            domain_id: DomainId,
1984            contract_creation_allowed_by: sp_domains::PermissionedActionAllowedBy<
1985                EthereumAccountId,
1986            >,
1987        ) -> DispatchResult {
1988            let signer = ensure_signed_or_root(origin)?;
1989
1990            ensure!(
1991                Pallet::<T>::is_private_evm_domain(domain_id),
1992                Error::<T>::NotPrivateEvmDomain,
1993            );
1994            if let Some(non_root_signer) = signer {
1995                ensure!(
1996                    Pallet::<T>::is_domain_owner(domain_id, non_root_signer),
1997                    Error::<T>::NotDomainOwnerOrRoot,
1998                );
1999            }
2000            ensure!(
2001                EvmDomainContractCreationAllowedByCalls::<T>::get(domain_id)
2002                    .maybe_call
2003                    .is_none(),
2004                Error::<T>::EvmDomainContractCreationAllowedByCallExists,
2005            );
2006
2007            EvmDomainContractCreationAllowedByCalls::<T>::set(
2008                domain_id,
2009                EvmDomainContractCreationAllowedByCall {
2010                    maybe_call: Some(contract_creation_allowed_by),
2011                },
2012            );
2013
2014            Ok(())
2015        }
2016
2017        /// Deactivate an offline operator through Sudo or Governance.
2018        #[pallet::call_index(23)]
2019        #[pallet::weight(T::WeightInfo::deactivate_operator())]
2020        pub fn deactivate_operator(
2021            origin: OriginFor<T>,
2022            operator_id: OperatorId,
2023        ) -> DispatchResult {
2024            ensure_root(origin)?;
2025            crate::staking::do_deactivate_operator::<T>(operator_id).map_err(Error::<T>::from)?;
2026            Ok(())
2027        }
2028
2029        /// Reactivate a deactivated operator through Sudo or Governance given
2030        /// activation delay has passed.
2031        #[pallet::call_index(24)]
2032        #[pallet::weight(T::WeightInfo::reactivate_operator())]
2033        pub fn reactivate_operator(
2034            origin: OriginFor<T>,
2035            operator_id: OperatorId,
2036        ) -> DispatchResult {
2037            ensure_root(origin)?;
2038            crate::staking::do_reactivate_operator::<T>(operator_id).map_err(Error::<T>::from)?;
2039            Ok(())
2040        }
2041    }
2042
2043    #[pallet::genesis_config]
2044    pub struct GenesisConfig<T: Config> {
2045        pub permissioned_action_allowed_by:
2046            Option<sp_domains::PermissionedActionAllowedBy<T::AccountId>>,
2047        pub genesis_domains: Vec<GenesisDomain<T::AccountId, BalanceOf<T>>>,
2048    }
2049
2050    impl<T: Config> Default for GenesisConfig<T> {
2051        fn default() -> Self {
2052            GenesisConfig {
2053                permissioned_action_allowed_by: None,
2054                genesis_domains: vec![],
2055            }
2056        }
2057    }
2058
2059    #[pallet::genesis_build]
2060    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
2061        fn build(&self) {
2062            if let Some(permissioned_action_allowed_by) =
2063                self.permissioned_action_allowed_by.as_ref().cloned()
2064            {
2065                PermissionedActionAllowedBy::<T>::put(permissioned_action_allowed_by)
2066            }
2067
2068            self.genesis_domains
2069                .clone()
2070                .into_iter()
2071                .for_each(|genesis_domain| {
2072                    // Register the genesis domain runtime
2073                    let runtime_id = register_runtime_at_genesis::<T>(
2074                        genesis_domain.runtime_name,
2075                        genesis_domain.runtime_type,
2076                        genesis_domain.runtime_version,
2077                        genesis_domain.raw_genesis_storage,
2078                        Zero::zero(),
2079                    )
2080                    .expect("Genesis runtime registration must always succeed");
2081
2082                    // Instantiate the genesis domain
2083                    let domain_config_params = DomainConfigParams {
2084                        domain_name: genesis_domain.domain_name,
2085                        runtime_id,
2086                        maybe_bundle_limit: None,
2087                        bundle_slot_probability: genesis_domain.bundle_slot_probability,
2088                        operator_allow_list: genesis_domain.operator_allow_list,
2089                        initial_balances: genesis_domain.initial_balances,
2090                        domain_runtime_info: genesis_domain.domain_runtime_info,
2091                    };
2092                    let domain_owner = genesis_domain.owner_account_id;
2093                    let domain_id = do_instantiate_domain::<T>(
2094                        domain_config_params,
2095                        domain_owner.clone(),
2096                        Zero::zero(),
2097                    )
2098                    .expect("Genesis domain instantiation must always succeed");
2099
2100                    // Register domain_owner as the genesis operator.
2101                    let operator_config = OperatorConfig {
2102                        signing_key: genesis_domain.signing_key.clone(),
2103                        minimum_nominator_stake: genesis_domain.minimum_nominator_stake,
2104                        nomination_tax: genesis_domain.nomination_tax,
2105                    };
2106                    let operator_stake = T::MinOperatorStake::get();
2107                    do_register_operator::<T>(
2108                        domain_owner,
2109                        domain_id,
2110                        operator_stake,
2111                        operator_config,
2112                    )
2113                    .expect("Genesis operator registration must succeed");
2114
2115                    do_finalize_domain_current_epoch::<T>(domain_id)
2116                        .expect("Genesis epoch must succeed");
2117                });
2118        }
2119    }
2120
2121    /// Combined fraud proof data for the InvalidInherentExtrinsic fraud proof
2122    #[pallet::storage]
2123    pub type BlockInherentExtrinsicData<T> = StorageValue<_, InherentExtrinsicData>;
2124
2125    #[pallet::hooks]
2126    // TODO: proper benchmark
2127    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
2128        fn on_initialize(block_number: BlockNumberFor<T>) -> Weight {
2129            let parent_number = block_number - One::one();
2130            let parent_hash = frame_system::Pallet::<T>::block_hash(parent_number);
2131
2132            // Record any previous domain runtime upgrades in `DomainRuntimeUpgradeRecords`
2133            for runtime_id in DomainRuntimeUpgrades::<T>::take() {
2134                let reference_count = RuntimeRegistry::<T>::get(runtime_id)
2135                    .expect("Runtime object must be present since domain is insantiated; qed")
2136                    .instance_count;
2137                if !reference_count.is_zero() {
2138                    DomainRuntimeUpgradeRecords::<T>::mutate(runtime_id, |upgrade_record| {
2139                        upgrade_record.insert(
2140                            parent_number,
2141                            DomainRuntimeUpgradeEntry {
2142                                at_hash: parent_hash,
2143                                reference_count,
2144                            },
2145                        )
2146                    });
2147                }
2148            }
2149            // Set DomainRuntimeUpgrades to an empty list. (If there are no runtime upgrades
2150            // scheduled in the current block, we can generate a proof the list is empty.)
2151            DomainRuntimeUpgrades::<T>::set(Vec::new());
2152            // Do the domain runtime upgrades scheduled in the current block, and record them in
2153            // DomainRuntimeUpgrades
2154            do_upgrade_runtimes::<T>(block_number);
2155
2156            // Store the hash of the parent consensus block for domains that have bundles submitted
2157            // in that consensus block
2158            for (domain_id, _) in SuccessfulBundles::<T>::drain() {
2159                ConsensusBlockHash::<T>::insert(domain_id, parent_number, parent_hash);
2160                T::DomainBundleSubmitted::domain_bundle_submitted(domain_id);
2161
2162                // And clear the domain inherents which have been submitted.
2163                DomainSudoCalls::<T>::mutate(domain_id, |sudo_call| {
2164                    sudo_call.clear();
2165                });
2166                EvmDomainContractCreationAllowedByCalls::<T>::mutate(
2167                    domain_id,
2168                    |evm_contract_call| {
2169                        evm_contract_call.clear();
2170                    },
2171                );
2172            }
2173
2174            for (operator_id, slot_set) in OperatorBundleSlot::<T>::drain() {
2175                // NOTE: `OperatorBundleSlot` uses `BTreeSet` so `last` will return the maximum
2176                // value in the set
2177                if let Some(highest_slot) = slot_set.last() {
2178                    OperatorHighestSlot::<T>::insert(operator_id, highest_slot);
2179                }
2180            }
2181
2182            BlockInherentExtrinsicData::<T>::kill();
2183
2184            Weight::zero()
2185        }
2186
2187        fn on_finalize(_: BlockNumberFor<T>) {
2188            // If this consensus block will derive any domain block, gather the necessary storage
2189            // for potential fraud proof usage
2190            if SuccessfulBundles::<T>::iter_keys().count() > 0
2191                || !DomainRuntimeUpgrades::<T>::get().is_empty()
2192            {
2193                let extrinsics_shuffling_seed = Randomness::from(
2194                    Into::<H256>::into(Self::extrinsics_shuffling_seed_value()).to_fixed_bytes(),
2195                );
2196
2197                // There are no actual conversions here, but the trait bounds required to prove that
2198                // (and debug-print the error in expect()) are very verbose.
2199                let timestamp = Self::timestamp_value();
2200
2201                // The value returned by the consensus_chain_byte_fee() runtime API
2202                let consensus_transaction_byte_fee = Self::consensus_transaction_byte_fee_value();
2203
2204                let inherent_extrinsic_data = InherentExtrinsicData {
2205                    extrinsics_shuffling_seed,
2206                    timestamp,
2207                    consensus_transaction_byte_fee,
2208                };
2209
2210                BlockInherentExtrinsicData::<T>::set(Some(inherent_extrinsic_data));
2211            }
2212
2213            let _ = LastEpochStakingDistribution::<T>::clear(u32::MAX, None);
2214            let _ = NewAddedHeadReceipt::<T>::clear(u32::MAX, None);
2215        }
2216    }
2217}
2218
2219impl<T: Config> Pallet<T> {
2220    fn log_bundle_error(err: &BundleError, domain_id: DomainId, operator_id: OperatorId) {
2221        match err {
2222            // These errors are common due to networking delay or chain re-org,
2223            // using a lower log level to avoid the noise.
2224            BundleError::Receipt(BlockTreeError::InFutureReceipt)
2225            | BundleError::Receipt(BlockTreeError::StaleReceipt)
2226            | BundleError::Receipt(BlockTreeError::NewBranchReceipt)
2227            | BundleError::Receipt(BlockTreeError::UnavailableConsensusBlockHash)
2228            | BundleError::Receipt(BlockTreeError::BuiltOnUnknownConsensusBlock)
2229            | BundleError::SlotInThePast
2230            | BundleError::SlotInTheFuture
2231            | BundleError::InvalidProofOfTime
2232            | BundleError::SlotSmallerThanPreviousBlockBundle
2233            | BundleError::ExpectingReceiptGap
2234            | BundleError::UnexpectedReceiptGap => {
2235                log::debug!(
2236                    "Bad bundle/receipt, domain {domain_id:?}, operator {operator_id:?}, error: {err:?}",
2237                );
2238            }
2239            _ => {
2240                log::warn!(
2241                    "Bad bundle/receipt, domain {domain_id:?}, operator {operator_id:?}, error: {err:?}",
2242                );
2243            }
2244        }
2245    }
2246
2247    pub fn successful_bundles(domain_id: DomainId) -> Vec<H256> {
2248        SuccessfulBundles::<T>::get(domain_id)
2249    }
2250
2251    pub fn domain_runtime_code(domain_id: DomainId) -> Option<Vec<u8>> {
2252        RuntimeRegistry::<T>::get(Self::runtime_id(domain_id)?)
2253            .and_then(|mut runtime_object| runtime_object.raw_genesis.take_runtime_code())
2254    }
2255
2256    pub fn domain_best_number(domain_id: DomainId) -> Result<DomainBlockNumberFor<T>, BundleError> {
2257        // The missed domain runtime upgrades will derive domain blocks thus should be accounted
2258        // into the domain best number
2259        let missed_upgrade = Self::missed_domain_runtime_upgrade(domain_id)
2260            .map_err(|_| BundleError::FailedToGetMissedUpgradeCount)?;
2261
2262        Ok(HeadDomainNumber::<T>::get(domain_id) + missed_upgrade.into())
2263    }
2264
2265    /// Returns the runtime ID for the supplied `domain_id`, if that domain exists.
2266    pub fn runtime_id(domain_id: DomainId) -> Option<RuntimeId> {
2267        DomainRegistry::<T>::get(domain_id)
2268            .map(|domain_object| domain_object.domain_config.runtime_id)
2269    }
2270
2271    /// Returns the list of runtime upgrades in the current block.
2272    pub fn runtime_upgrades() -> Vec<RuntimeId> {
2273        DomainRuntimeUpgrades::<T>::get()
2274    }
2275
2276    pub fn domain_instance_data(
2277        domain_id: DomainId,
2278    ) -> Option<(DomainInstanceData, BlockNumberFor<T>)> {
2279        let domain_obj = DomainRegistry::<T>::get(domain_id)?;
2280        let runtime_object = RuntimeRegistry::<T>::get(domain_obj.domain_config.runtime_id)?;
2281        let runtime_type = runtime_object.runtime_type;
2282        let total_issuance = domain_obj.domain_config.total_issuance()?;
2283        let raw_genesis = into_complete_raw_genesis::<T>(
2284            runtime_object,
2285            domain_id,
2286            &domain_obj.domain_runtime_info,
2287            total_issuance,
2288            domain_obj.domain_config.initial_balances,
2289        )
2290        .ok()?;
2291        Some((
2292            DomainInstanceData {
2293                runtime_type,
2294                raw_genesis,
2295            },
2296            domain_obj.created_at,
2297        ))
2298    }
2299
2300    /// Returns the tx range for the domain.
2301    pub fn domain_tx_range(domain_id: DomainId) -> U256 {
2302        DomainTxRangeState::<T>::try_get(domain_id)
2303            .map(|state| state.tx_range)
2304            .ok()
2305            .unwrap_or_else(Self::initial_tx_range)
2306    }
2307
2308    pub fn bundle_producer_election_params(
2309        domain_id: DomainId,
2310    ) -> Option<BundleProducerElectionParams<BalanceOf<T>>> {
2311        match (
2312            DomainRegistry::<T>::get(domain_id),
2313            DomainStakingSummary::<T>::get(domain_id),
2314        ) {
2315            (Some(domain_object), Some(stake_summary)) => Some(BundleProducerElectionParams {
2316                total_domain_stake: stake_summary.current_total_stake,
2317                bundle_slot_probability: domain_object.domain_config.bundle_slot_probability,
2318            }),
2319            _ => None,
2320        }
2321    }
2322
2323    pub fn operator(operator_id: OperatorId) -> Option<(OperatorPublicKey, BalanceOf<T>)> {
2324        Operators::<T>::get(operator_id)
2325            .map(|operator| (operator.signing_key, operator.current_total_stake))
2326    }
2327
2328    fn check_extrinsics_root(opaque_bundle: &OpaqueBundleOf<T>) -> Result<(), BundleError> {
2329        let expected_extrinsics_root = <T::DomainHeader as Header>::Hashing::ordered_trie_root(
2330            opaque_bundle
2331                .extrinsics()
2332                .iter()
2333                .map(|xt| xt.encode())
2334                .collect(),
2335            sp_core::storage::StateVersion::V1,
2336        );
2337        ensure!(
2338            expected_extrinsics_root == opaque_bundle.extrinsics_root(),
2339            BundleError::InvalidExtrinsicRoot
2340        );
2341        Ok(())
2342    }
2343
2344    fn check_slot_and_proof_of_time(
2345        slot_number: u64,
2346        proof_of_time: PotOutput,
2347        pre_dispatch: bool,
2348    ) -> Result<(), BundleError> {
2349        // NOTE: the `current_block_number` from `frame_system` is initialized during `validate_unsigned` thus
2350        // it is the same value in both `validate_unsigned` and `pre_dispatch`
2351        let current_block_number = frame_system::Pallet::<T>::current_block_number();
2352
2353        // Check if the slot is in future
2354        //
2355        // NOTE: during `validate_unsigned` this is implicitly checked within `is_proof_of_time_valid` since we
2356        // are using quick verification which will return `false` if the `proof-of-time` is not seem by the node
2357        // before.
2358        if pre_dispatch && let Some(future_slot) = T::BlockSlot::future_slot(current_block_number) {
2359            ensure!(slot_number <= *future_slot, BundleError::SlotInTheFuture)
2360        }
2361
2362        // Check if the bundle is built too long time ago and beyond `T::BundleLongevity` number of consensus blocks.
2363        let produced_after_block_number =
2364            match T::BlockSlot::slot_produced_after(slot_number.into()) {
2365                Some(n) => n,
2366                None => {
2367                    // There is no slot for the genesis block, if the current block is less than `BundleLongevity`
2368                    // than we assume the slot is produced after the genesis block.
2369                    if current_block_number > T::BundleLongevity::get().into() {
2370                        return Err(BundleError::SlotInThePast);
2371                    } else {
2372                        Zero::zero()
2373                    }
2374                }
2375            };
2376        let produced_after_block_hash = if produced_after_block_number == current_block_number {
2377            // The hash of the current block is only available in the next block thus use the parent hash here
2378            frame_system::Pallet::<T>::parent_hash()
2379        } else {
2380            frame_system::Pallet::<T>::block_hash(produced_after_block_number)
2381        };
2382        if let Some(last_eligible_block) =
2383            current_block_number.checked_sub(&T::BundleLongevity::get().into())
2384        {
2385            ensure!(
2386                produced_after_block_number >= last_eligible_block,
2387                BundleError::SlotInThePast
2388            );
2389        }
2390
2391        if !is_proof_of_time_valid(
2392            BlockHash::try_from(produced_after_block_hash.as_ref())
2393                .expect("Must be able to convert to block hash type"),
2394            SlotNumber::from(slot_number),
2395            WrappedPotOutput::from(proof_of_time),
2396            // Quick verification when entering transaction pool, but not when constructing the block
2397            !pre_dispatch,
2398        ) {
2399            return Err(BundleError::InvalidProofOfTime);
2400        }
2401
2402        Ok(())
2403    }
2404
2405    fn validate_bundle(
2406        opaque_bundle: &OpaqueBundleOf<T>,
2407        domain_config: &DomainConfig<T::AccountId, BalanceOf<T>>,
2408    ) -> Result<(), BundleError> {
2409        ensure!(
2410            opaque_bundle.body_size() <= domain_config.max_bundle_size,
2411            BundleError::BundleTooLarge
2412        );
2413
2414        ensure!(
2415            opaque_bundle
2416                .estimated_weight()
2417                .all_lte(domain_config.max_bundle_weight),
2418            BundleError::BundleTooHeavy
2419        );
2420
2421        Self::check_extrinsics_root(opaque_bundle)?;
2422
2423        Ok(())
2424    }
2425
2426    fn validate_eligibility(
2427        to_sign: &[u8],
2428        signature: &OperatorSignature,
2429        proof_of_election: &ProofOfElection,
2430        domain_config: &DomainConfig<T::AccountId, BalanceOf<T>>,
2431        pre_dispatch: bool,
2432    ) -> Result<(), BundleError> {
2433        let domain_id = proof_of_election.domain_id;
2434        let operator_id = proof_of_election.operator_id;
2435        let slot_number = proof_of_election.slot_number;
2436
2437        ensure!(
2438            !FrozenDomains::<T>::get().contains(&domain_id),
2439            BundleError::DomainFrozen
2440        );
2441
2442        let operator = Operators::<T>::get(operator_id).ok_or(BundleError::InvalidOperatorId)?;
2443
2444        let can_submit_bundle = operator.can_operator_submit_bundle::<T>(operator_id);
2445        ensure!(can_submit_bundle, BundleError::BadOperator);
2446
2447        if !operator.signing_key.verify(&to_sign, signature) {
2448            return Err(BundleError::BadBundleSignature);
2449        }
2450
2451        // Ensure this is no equivocated bundle that reuse `ProofOfElection` from the previous block
2452        ensure!(
2453            slot_number
2454                > Self::operator_highest_slot_from_previous_block(operator_id, pre_dispatch),
2455            BundleError::SlotSmallerThanPreviousBlockBundle,
2456        );
2457
2458        // Ensure there is no equivocated/duplicated bundle in the same block
2459        ensure!(
2460            !OperatorBundleSlot::<T>::get(operator_id).contains(&slot_number),
2461            BundleError::EquivocatedBundle,
2462        );
2463
2464        let (operator_stake, total_domain_stake) =
2465            Self::fetch_operator_stake_info(domain_id, &operator_id)?;
2466
2467        Self::check_slot_and_proof_of_time(
2468            slot_number,
2469            proof_of_election.proof_of_time,
2470            pre_dispatch,
2471        )?;
2472
2473        sp_domains::bundle_producer_election::check_proof_of_election(
2474            &operator.signing_key,
2475            domain_config.bundle_slot_probability,
2476            proof_of_election,
2477            operator_stake.saturated_into(),
2478            total_domain_stake.saturated_into(),
2479        )?;
2480
2481        Ok(())
2482    }
2483
2484    /// Verifies if the submitted ER version matches with the version
2485    /// defined at the block number ER is derived from.
2486    fn check_execution_receipt_version(
2487        er_derived_consensus_number: BlockNumberFor<T>,
2488        receipt_version: ExecutionReceiptVersion,
2489    ) -> Result<(), BundleError> {
2490        let expected_execution_receipt_version =
2491            Self::bundle_and_execution_receipt_version_for_consensus_number(
2492                er_derived_consensus_number,
2493                PreviousBundleAndExecutionReceiptVersions::<T>::get(),
2494                T::CurrentBundleAndExecutionReceiptVersion::get(),
2495            )
2496            .ok_or(BundleError::ExecutionVersionMissing)?
2497            .execution_receipt_version;
2498        match (receipt_version, expected_execution_receipt_version) {
2499            (ExecutionReceiptVersion::V0, ExecutionReceiptVersion::V0) => Ok(()),
2500        }
2501    }
2502
2503    fn validate_submit_bundle(
2504        opaque_bundle: &OpaqueBundleOf<T>,
2505        pre_dispatch: bool,
2506    ) -> Result<(), BundleError> {
2507        let current_bundle_version =
2508            T::CurrentBundleAndExecutionReceiptVersion::get().bundle_version;
2509
2510        // bundle version check
2511        match (current_bundle_version, opaque_bundle) {
2512            (BundleVersion::V0, Bundle::V0(_)) => Ok::<(), BundleError>(()),
2513        }?;
2514
2515        let domain_id = opaque_bundle.domain_id();
2516        let operator_id = opaque_bundle.operator_id();
2517        let sealed_header = opaque_bundle.sealed_header();
2518
2519        let receipt = sealed_header.receipt();
2520        Self::check_execution_receipt_version(
2521            *receipt.consensus_block_number(),
2522            receipt.version(),
2523        )?;
2524
2525        // Ensure the receipt gap is <= 1 so that the bundle will only be accepted if its receipt is
2526        // derived from the latest domain block, and the stale bundle (that verified against an old
2527        // domain block) produced by a lagging honest operator will be rejected.
2528        ensure!(
2529            Self::receipt_gap(domain_id)? <= One::one(),
2530            BundleError::UnexpectedReceiptGap,
2531        );
2532
2533        charge_bundle_storage_fee::<T>(operator_id, opaque_bundle.size())
2534            .map_err(|_| BundleError::UnableToPayBundleStorageFee)?;
2535
2536        let domain_config = &DomainRegistry::<T>::get(domain_id)
2537            .ok_or(BundleError::InvalidDomainId)?
2538            .domain_config;
2539
2540        Self::validate_bundle(opaque_bundle, domain_config)?;
2541
2542        Self::validate_eligibility(
2543            sealed_header.pre_hash().as_ref(),
2544            sealed_header.signature(),
2545            sealed_header.proof_of_election(),
2546            domain_config,
2547            pre_dispatch,
2548        )?;
2549
2550        verify_execution_receipt::<T>(domain_id, &receipt).map_err(BundleError::Receipt)?;
2551
2552        Ok(())
2553    }
2554
2555    fn validate_singleton_receipt(
2556        sealed_singleton_receipt: &SingletonReceiptOf<T>,
2557        pre_dispatch: bool,
2558    ) -> Result<(), BundleError> {
2559        let domain_id = sealed_singleton_receipt.domain_id();
2560        let operator_id = sealed_singleton_receipt.operator_id();
2561
2562        // Singleton receipt is only allowed when there is a receipt gap
2563        ensure!(
2564            Self::receipt_gap(domain_id)? > One::one(),
2565            BundleError::ExpectingReceiptGap,
2566        );
2567
2568        charge_bundle_storage_fee::<T>(operator_id, sealed_singleton_receipt.size())
2569            .map_err(|_| BundleError::UnableToPayBundleStorageFee)?;
2570
2571        Self::check_execution_receipt_version(
2572            *sealed_singleton_receipt
2573                .singleton_receipt
2574                .receipt
2575                .consensus_block_number(),
2576            sealed_singleton_receipt.singleton_receipt.receipt.version(),
2577        )?;
2578
2579        let domain_config = DomainRegistry::<T>::get(domain_id)
2580            .ok_or(BundleError::InvalidDomainId)?
2581            .domain_config;
2582        Self::validate_eligibility(
2583            sealed_singleton_receipt.pre_hash().as_ref(),
2584            &sealed_singleton_receipt.signature,
2585            &sealed_singleton_receipt.singleton_receipt.proof_of_election,
2586            &domain_config,
2587            pre_dispatch,
2588        )?;
2589
2590        verify_execution_receipt::<T>(
2591            domain_id,
2592            &sealed_singleton_receipt
2593                .singleton_receipt
2594                .receipt
2595                .as_execution_receipt_ref(),
2596        )
2597        .map_err(BundleError::Receipt)?;
2598
2599        Ok(())
2600    }
2601
2602    fn validate_fraud_proof(
2603        fraud_proof: &FraudProofFor<T>,
2604    ) -> Result<(DomainId, TransactionPriority), FraudProofError> {
2605        let domain_id = fraud_proof.domain_id();
2606        let bad_receipt_hash = fraud_proof.targeted_bad_receipt_hash();
2607        let bad_receipt = BlockTreeNodes::<T>::get(bad_receipt_hash)
2608            .ok_or(FraudProofError::BadReceiptNotFound)?
2609            .execution_receipt;
2610        let bad_receipt_domain_block_number = *bad_receipt.domain_block_number();
2611
2612        ensure!(
2613            !bad_receipt_domain_block_number.is_zero(),
2614            FraudProofError::ChallengingGenesisReceipt
2615        );
2616
2617        ensure!(
2618            !Self::is_bad_er_pending_to_prune(domain_id, bad_receipt_domain_block_number),
2619            FraudProofError::BadReceiptAlreadyReported,
2620        );
2621
2622        ensure!(
2623            !fraud_proof.is_unexpected_domain_runtime_code_proof(),
2624            FraudProofError::UnexpectedDomainRuntimeCodeProof,
2625        );
2626
2627        ensure!(
2628            !fraud_proof.is_unexpected_mmr_proof(),
2629            FraudProofError::UnexpectedMmrProof,
2630        );
2631
2632        let maybe_state_root = match &fraud_proof.maybe_mmr_proof {
2633            Some(mmr_proof) => Some(Self::verify_mmr_proof_and_extract_state_root(
2634                mmr_proof.clone(),
2635                *bad_receipt.consensus_block_number(),
2636            )?),
2637            None => None,
2638        };
2639
2640        match &fraud_proof.proof {
2641            FraudProofVariant::InvalidBlockFees(InvalidBlockFeesProof { storage_proof }) => {
2642                let domain_runtime_code = Self::get_domain_runtime_code_for_receipt(
2643                    domain_id,
2644                    &bad_receipt,
2645                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2646                )?;
2647
2648                verify_invalid_block_fees_fraud_proof::<
2649                    T::Block,
2650                    DomainBlockNumberFor<T>,
2651                    T::DomainHash,
2652                    BalanceOf<T>,
2653                    DomainHashingFor<T>,
2654                >(bad_receipt, storage_proof, domain_runtime_code)
2655                .map_err(|err| {
2656                    log::error!("Block fees proof verification failed: {err:?}");
2657                    FraudProofError::InvalidBlockFeesFraudProof
2658                })?;
2659            }
2660            FraudProofVariant::InvalidTransfers(InvalidTransfersProof { storage_proof }) => {
2661                let domain_runtime_code = Self::get_domain_runtime_code_for_receipt(
2662                    domain_id,
2663                    &bad_receipt,
2664                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2665                )?;
2666
2667                verify_invalid_transfers_fraud_proof::<
2668                    T::Block,
2669                    DomainBlockNumberFor<T>,
2670                    T::DomainHash,
2671                    BalanceOf<T>,
2672                    DomainHashingFor<T>,
2673                >(bad_receipt, storage_proof, domain_runtime_code)
2674                .map_err(|err| {
2675                    log::error!("Domain transfers proof verification failed: {err:?}");
2676                    FraudProofError::InvalidTransfersFraudProof
2677                })?;
2678            }
2679            FraudProofVariant::InvalidDomainBlockHash(InvalidDomainBlockHashProof {
2680                digest_storage_proof,
2681            }) => {
2682                let parent_receipt =
2683                    BlockTreeNodes::<T>::get(*bad_receipt.parent_domain_block_receipt_hash())
2684                        .ok_or(FraudProofError::ParentReceiptNotFound)?
2685                        .execution_receipt;
2686                verify_invalid_domain_block_hash_fraud_proof::<
2687                    T::Block,
2688                    BalanceOf<T>,
2689                    T::DomainHeader,
2690                >(
2691                    bad_receipt,
2692                    digest_storage_proof.clone(),
2693                    *parent_receipt.domain_block_hash(),
2694                )
2695                .map_err(|err| {
2696                    log::error!("Invalid Domain block hash proof verification failed: {err:?}");
2697                    FraudProofError::InvalidDomainBlockHashFraudProof
2698                })?;
2699            }
2700            FraudProofVariant::InvalidExtrinsicsRoot(proof) => {
2701                let domain_runtime_code = Self::get_domain_runtime_code_for_receipt(
2702                    domain_id,
2703                    &bad_receipt,
2704                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2705                )?;
2706                let runtime_id =
2707                    Self::runtime_id(domain_id).ok_or(FraudProofError::RuntimeNotFound)?;
2708                let state_root = maybe_state_root.ok_or(FraudProofError::MissingMmrProof)?;
2709
2710                verify_invalid_domain_extrinsics_root_fraud_proof::<
2711                    T::Block,
2712                    BalanceOf<T>,
2713                    T::DomainHeader,
2714                    T::Hashing,
2715                    T::FraudProofStorageKeyProvider,
2716                >(
2717                    bad_receipt,
2718                    proof,
2719                    domain_id,
2720                    runtime_id,
2721                    state_root,
2722                    domain_runtime_code,
2723                )
2724                .map_err(|err| {
2725                    log::error!("Invalid Domain extrinsic root proof verification failed: {err:?}");
2726                    FraudProofError::InvalidExtrinsicRootFraudProof
2727                })?;
2728            }
2729            FraudProofVariant::InvalidStateTransition(proof) => {
2730                let domain_runtime_code = Self::get_domain_runtime_code_for_receipt(
2731                    domain_id,
2732                    &bad_receipt,
2733                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2734                )?;
2735                let bad_receipt_parent =
2736                    BlockTreeNodes::<T>::get(*bad_receipt.parent_domain_block_receipt_hash())
2737                        .ok_or(FraudProofError::ParentReceiptNotFound)?
2738                        .execution_receipt;
2739
2740                verify_invalid_state_transition_fraud_proof::<
2741                    T::Block,
2742                    T::DomainHeader,
2743                    BalanceOf<T>,
2744                >(bad_receipt, bad_receipt_parent, proof, domain_runtime_code)
2745                .map_err(|err| {
2746                    log::error!("Invalid State transition proof verification failed: {err:?}");
2747                    FraudProofError::InvalidStateTransitionFraudProof
2748                })?;
2749            }
2750            FraudProofVariant::InvalidBundles(proof) => {
2751                let state_root = maybe_state_root.ok_or(FraudProofError::MissingMmrProof)?;
2752                let domain_runtime_code = Self::get_domain_runtime_code_for_receipt(
2753                    domain_id,
2754                    &bad_receipt,
2755                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2756                )?;
2757
2758                let bad_receipt_parent =
2759                    BlockTreeNodes::<T>::get(*bad_receipt.parent_domain_block_receipt_hash())
2760                        .ok_or(FraudProofError::ParentReceiptNotFound)?
2761                        .execution_receipt;
2762
2763                verify_invalid_bundles_fraud_proof::<
2764                    T::Block,
2765                    T::DomainHeader,
2766                    T::MmrHash,
2767                    BalanceOf<T>,
2768                    T::FraudProofStorageKeyProvider,
2769                    T::MmrProofVerifier,
2770                >(
2771                    bad_receipt,
2772                    bad_receipt_parent,
2773                    proof,
2774                    domain_id,
2775                    state_root,
2776                    domain_runtime_code,
2777                )
2778                .map_err(|err| {
2779                    log::error!("Invalid Bundle proof verification failed: {err:?}");
2780                    FraudProofError::InvalidBundleFraudProof
2781                })?;
2782            }
2783            FraudProofVariant::ValidBundle(proof) => {
2784                let state_root = maybe_state_root.ok_or(FraudProofError::MissingMmrProof)?;
2785                let domain_runtime_code = Self::get_domain_runtime_code_for_receipt(
2786                    domain_id,
2787                    &bad_receipt,
2788                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2789                )?;
2790
2791                verify_valid_bundle_fraud_proof::<
2792                    T::Block,
2793                    T::DomainHeader,
2794                    BalanceOf<T>,
2795                    T::FraudProofStorageKeyProvider,
2796                >(
2797                    bad_receipt,
2798                    proof,
2799                    domain_id,
2800                    state_root,
2801                    domain_runtime_code,
2802                )
2803                .map_err(|err| {
2804                    log::error!("Valid bundle proof verification failed: {err:?}");
2805                    FraudProofError::BadValidBundleFraudProof
2806                })?
2807            }
2808            #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
2809            FraudProofVariant::Dummy => {
2810                // Almost every fraud proof (except `InvalidDomainBlockHash` fraud proof) need to call
2811                // `get_domain_runtime_code_for_receipt` thus we include this part in the benchmark of
2812                // the dummy fraud proof.
2813                //
2814                // NOTE: the dummy fraud proof's `maybe_domain_runtime_code_proof` is `None` thus
2815                // this proof's verification is not included in the benchmark here.
2816                let _ = Self::get_domain_runtime_code_for_receipt(
2817                    domain_id,
2818                    &bad_receipt,
2819                    fraud_proof.maybe_domain_runtime_code_proof.clone(),
2820                )?;
2821            }
2822        }
2823
2824        // The priority of fraud proof is determined by how many blocks left before the bad ER
2825        // is confirmed, the less the more emergency it is, thus give a higher priority.
2826        let block_before_bad_er_confirm = bad_receipt_domain_block_number.saturating_sub(
2827            Self::latest_confirmed_domain_block_number(fraud_proof.domain_id()),
2828        );
2829        let priority =
2830            TransactionPriority::MAX - block_before_bad_er_confirm.saturated_into::<u64>();
2831
2832        // Use the domain id as tag thus the consensus node only accept one fraud proof for a
2833        // specific domain at a time
2834        let tag = fraud_proof.domain_id();
2835
2836        Ok((tag, priority))
2837    }
2838
2839    /// Return operators specific election verification params for Proof of Election verification.
2840    /// If there was an epoch transition in this block for this domain,
2841    ///     then return the parameters from previous epoch stored in LastEpochStakingDistribution
2842    /// Else, return those details from the Domain's stake summary for this epoch.
2843    fn fetch_operator_stake_info(
2844        domain_id: DomainId,
2845        operator_id: &OperatorId,
2846    ) -> Result<(BalanceOf<T>, BalanceOf<T>), BundleError> {
2847        if let Some(pending_election_params) = LastEpochStakingDistribution::<T>::get(domain_id)
2848            && let Some(operator_stake) = pending_election_params.operators.get(operator_id)
2849        {
2850            return Ok((*operator_stake, pending_election_params.total_domain_stake));
2851        }
2852        let domain_stake_summary =
2853            DomainStakingSummary::<T>::get(domain_id).ok_or(BundleError::InvalidDomainId)?;
2854        let operator_stake = domain_stake_summary
2855            .current_operators
2856            .get(operator_id)
2857            .ok_or(BundleError::BadOperator)?;
2858        Ok((*operator_stake, domain_stake_summary.current_total_stake))
2859    }
2860
2861    /// Calculates the initial tx range.
2862    fn initial_tx_range() -> U256 {
2863        U256::MAX / T::InitialDomainTxRange::get()
2864    }
2865
2866    /// Returns the best execution chain number.
2867    pub fn head_receipt_number(domain_id: DomainId) -> DomainBlockNumberFor<T> {
2868        HeadReceiptNumber::<T>::get(domain_id)
2869    }
2870
2871    /// Returns the block number of the oldest existing unconfirmed execution receipt, return `None`
2872    /// means there is no unconfirmed ER exist or submitted yet.
2873    pub fn oldest_unconfirmed_receipt_number(
2874        domain_id: DomainId,
2875    ) -> Option<DomainBlockNumberFor<T>> {
2876        let oldest_nonconfirmed_er_number =
2877            Self::latest_confirmed_domain_block_number(domain_id).saturating_add(One::one());
2878        let is_er_exist = BlockTree::<T>::get(domain_id, oldest_nonconfirmed_er_number).is_some();
2879        let is_pending_to_prune =
2880            Self::is_bad_er_pending_to_prune(domain_id, oldest_nonconfirmed_er_number);
2881
2882        if is_er_exist && !is_pending_to_prune {
2883            Some(oldest_nonconfirmed_er_number)
2884        } else {
2885            // The `oldest_nonconfirmed_er_number` ER may not exist if
2886            // - The domain just started and no ER submitted yet
2887            // - The oldest ER just pruned by fraud proof and no new ER submitted yet
2888            // - When using consensus block to derive the challenge period forward (unimplemented yet)
2889            None
2890        }
2891    }
2892
2893    /// Returns the latest confirmed domain block number for a given domain
2894    /// Zero block is always a default confirmed block.
2895    pub fn latest_confirmed_domain_block_number(domain_id: DomainId) -> DomainBlockNumberFor<T> {
2896        LatestConfirmedDomainExecutionReceipt::<T>::get(domain_id)
2897            .map(|er| *er.domain_block_number())
2898            .unwrap_or_default()
2899    }
2900
2901    pub fn latest_confirmed_domain_block(
2902        domain_id: DomainId,
2903    ) -> Option<(DomainBlockNumberFor<T>, T::DomainHash)> {
2904        LatestConfirmedDomainExecutionReceipt::<T>::get(domain_id)
2905            .map(|er| (*er.domain_block_number(), *er.domain_block_hash()))
2906    }
2907
2908    /// Returns the domain bundle limit of the given domain
2909    pub fn domain_bundle_limit(
2910        domain_id: DomainId,
2911    ) -> Result<Option<DomainBundleLimit>, DomainRegistryError> {
2912        let domain_config = match DomainRegistry::<T>::get(domain_id) {
2913            None => return Ok(None),
2914            Some(domain_obj) => domain_obj.domain_config,
2915        };
2916
2917        Ok(Some(DomainBundleLimit {
2918            max_bundle_size: domain_config.max_bundle_size,
2919            max_bundle_weight: domain_config.max_bundle_weight,
2920        }))
2921    }
2922
2923    /// Returns if there are any ERs in the challenge period that have non empty extrinsics.
2924    /// Note that Genesis ER is also considered special and hence non empty
2925    pub fn non_empty_er_exists(domain_id: DomainId) -> bool {
2926        if BlockTree::<T>::contains_key(domain_id, DomainBlockNumberFor::<T>::zero()) {
2927            return true;
2928        }
2929
2930        // Start from the oldest non-confirmed ER to the head domain number
2931        let mut to_check =
2932            Self::latest_confirmed_domain_block_number(domain_id).saturating_add(One::one());
2933
2934        // NOTE: we use the `HeadDomainNumber` here instead of the `domain_best_number`, which include the
2935        // missed domain runtime upgrade block, because we don't want to trigger empty bundle production
2936        // for confirming these blocks since they only include runtime upgrade extrinsic and no any user
2937        // submitted extrinsic.
2938        let head_number = HeadDomainNumber::<T>::get(domain_id);
2939
2940        while to_check <= head_number {
2941            if !ExecutionInbox::<T>::iter_prefix_values((domain_id, to_check)).all(|digests| {
2942                digests
2943                    .iter()
2944                    .all(|digest| digest.extrinsics_root == EMPTY_EXTRINSIC_ROOT.into())
2945            }) {
2946                return true;
2947            }
2948
2949            to_check = to_check.saturating_add(One::one())
2950        }
2951
2952        false
2953    }
2954
2955    /// The external function used to access the extrinsics shuffling seed stored in
2956    /// `BlockInherentExtrinsicData`.
2957    pub fn extrinsics_shuffling_seed() -> T::Hash {
2958        // Fall back to recalculating if it hasn't been stored yet.
2959        BlockInherentExtrinsicData::<T>::get()
2960            .map(|data| H256::from(*data.extrinsics_shuffling_seed).into())
2961            .unwrap_or_else(|| Self::extrinsics_shuffling_seed_value())
2962    }
2963
2964    /// The internal function used to calculate the extrinsics shuffling seed for storage into
2965    /// `BlockInherentExtrinsicData`.
2966    fn extrinsics_shuffling_seed_value() -> T::Hash {
2967        let subject = DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT;
2968        let (randomness, _) = T::Randomness::random(subject);
2969        randomness
2970    }
2971
2972    /// The external function used to access the timestamp stored in
2973    /// `BlockInherentExtrinsicData`.
2974    pub fn timestamp() -> Moment {
2975        // Fall back to recalculating if it hasn't been stored yet.
2976        BlockInherentExtrinsicData::<T>::get()
2977            .map(|data| data.timestamp)
2978            .unwrap_or_else(|| Self::timestamp_value())
2979    }
2980
2981    /// The internal function used to access the timestamp for storage into
2982    /// `BlockInherentExtrinsicData`.
2983    fn timestamp_value() -> Moment {
2984        // There are no actual conversions here, but the trait bounds required to prove that
2985        // (and debug-print the error in expect()) are very verbose.
2986        T::BlockTimestamp::now()
2987            .try_into()
2988            .map_err(|_| ())
2989            .expect("Moment is the same type in both pallets; qed")
2990    }
2991
2992    /// The external function used to access the consensus transaction byte fee stored in
2993    /// `BlockInherentExtrinsicData`.
2994    /// This value is returned by the consensus_chain_byte_fee() runtime API
2995    pub fn consensus_transaction_byte_fee() -> Balance {
2996        // Fall back to recalculating if it hasn't been stored yet.
2997        BlockInherentExtrinsicData::<T>::get()
2998            .map(|data| data.consensus_transaction_byte_fee)
2999            .unwrap_or_else(|| Self::consensus_transaction_byte_fee_value())
3000    }
3001
3002    /// The internal function used to calculate the consensus transaction byte fee for storage into
3003    /// `BlockInherentExtrinsicData`.
3004    fn consensus_transaction_byte_fee_value() -> Balance {
3005        // There are no actual conversions here, but the trait bounds required to prove that
3006        // (and debug-print the error in expect()) are very verbose.
3007        let transaction_byte_fee: Balance = T::StorageFee::transaction_byte_fee()
3008            .try_into()
3009            .map_err(|_| ())
3010            .expect("Balance is the same type in both pallets; qed");
3011
3012        sp_domains::DOMAIN_STORAGE_FEE_MULTIPLIER * transaction_byte_fee
3013    }
3014
3015    pub fn execution_receipt(receipt_hash: ReceiptHashFor<T>) -> Option<ExecutionReceiptOf<T>> {
3016        BlockTreeNodes::<T>::get(receipt_hash).map(|db| db.execution_receipt)
3017    }
3018
3019    /// Returns the correct bundle and er version based on
3020    /// the consensus block number at which execution receipt was derived.
3021    pub(crate) fn bundle_and_execution_receipt_version_for_consensus_number<BEV>(
3022        er_derived_number: BlockNumberFor<T>,
3023        previous_versions: BTreeMap<BlockNumberFor<T>, BEV>,
3024        current_version: BEV,
3025    ) -> Option<BEV>
3026    where
3027        BEV: Copy + Clone,
3028    {
3029        // short circuit if the er version should be the latest version
3030        match previous_versions.last_key_value() {
3031            // if there are no versions, all ERs should be the latest version.
3032            None => {
3033                return Some(current_version);
3034            }
3035            Some((number, version)) => {
3036                // if er derived number is greater than the last stored version,
3037                // then er version should be the latest version.
3038                if er_derived_number > *number {
3039                    return Some(current_version);
3040                }
3041
3042                // if the er derived number is equal to the last stored version,
3043                // then the er version should be the previous er version
3044                if er_derived_number == *number {
3045                    return Some(*version);
3046                }
3047            }
3048        }
3049
3050        // if we are here, it means the er version should be the version before a previous upgrade.
3051        // loop through to find the correct version.
3052        for (upgraded_number, version) in previous_versions.into_iter() {
3053            if er_derived_number <= upgraded_number {
3054                return Some(version);
3055            }
3056        }
3057
3058        // should not reach here since above loop always finds the oldest version
3059        None
3060    }
3061
3062    pub fn receipt_hash(
3063        domain_id: DomainId,
3064        domain_number: DomainBlockNumberFor<T>,
3065    ) -> Option<ReceiptHashFor<T>> {
3066        BlockTree::<T>::get(domain_id, domain_number)
3067    }
3068
3069    pub fn confirmed_domain_block_storage_key(domain_id: DomainId) -> Vec<u8> {
3070        LatestConfirmedDomainExecutionReceipt::<T>::hashed_key_for(domain_id)
3071    }
3072
3073    pub fn is_bad_er_pending_to_prune(
3074        domain_id: DomainId,
3075        receipt_number: DomainBlockNumberFor<T>,
3076    ) -> bool {
3077        // The genesis receipt is always valid
3078        if receipt_number.is_zero() {
3079            return false;
3080        }
3081
3082        let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
3083
3084        // If `receipt_number` is greater than the current `head_receipt_number` meaning it is a
3085        // bad ER and the `head_receipt_number` is previously reverted by a fraud proof
3086        head_receipt_number < receipt_number
3087    }
3088
3089    pub fn is_operator_pending_to_slash(domain_id: DomainId, operator_id: OperatorId) -> bool {
3090        let latest_submitted_er = LatestSubmittedER::<T>::get((domain_id, operator_id));
3091
3092        // The genesis receipt is always valid
3093        if latest_submitted_er.is_zero() {
3094            return false;
3095        }
3096
3097        let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
3098
3099        // If the operator have submitted an ER greater than the current `head_receipt_number`
3100        // meaning the ER is a bad ER and the `head_receipt_number` is previously reverted by
3101        // a fraud proof
3102        head_receipt_number < latest_submitted_er
3103    }
3104
3105    pub fn max_submit_bundle_weight() -> Weight {
3106        T::WeightInfo::submit_bundle()
3107            .saturating_add(
3108                // NOTE: within `submit_bundle`, only one of (or none) `handle_bad_receipt` and
3109                // `confirm_domain_block` can happen, thus we use the `max` of them
3110                //
3111                // We use `MAX_BUNDLE_PER_BLOCK` number to assume the number of slashed operators.
3112                // We do not expect so many operators to be slashed but nonetheless, if it did happen
3113                // we will limit the weight to 100 operators.
3114                T::WeightInfo::handle_bad_receipt(MAX_BUNDLE_PER_BLOCK).max(
3115                    T::WeightInfo::confirm_domain_block(MAX_BUNDLE_PER_BLOCK, MAX_BUNDLE_PER_BLOCK),
3116                ),
3117            )
3118            .saturating_add(Self::max_staking_epoch_transition())
3119            .saturating_add(T::WeightInfo::slash_operator(MAX_NOMINATORS_TO_SLASH))
3120    }
3121
3122    pub fn max_submit_receipt_weight() -> Weight {
3123        T::WeightInfo::submit_bundle()
3124            .saturating_add(
3125                // NOTE: within `submit_bundle`, only one of (or none) `handle_bad_receipt` and
3126                // `confirm_domain_block` can happen, thus we use the `max` of them
3127                //
3128                // We use `MAX_BUNDLE_PER_BLOCK` number to assume the number of slashed operators.
3129                // We do not expect so many operators to be slashed but nonetheless, if it did happen
3130                // we will limit the weight to 100 operators.
3131                T::WeightInfo::handle_bad_receipt(MAX_BUNDLE_PER_BLOCK).max(
3132                    T::WeightInfo::confirm_domain_block(MAX_BUNDLE_PER_BLOCK, MAX_BUNDLE_PER_BLOCK),
3133                ),
3134            )
3135            .saturating_add(T::WeightInfo::slash_operator(MAX_NOMINATORS_TO_SLASH))
3136    }
3137
3138    pub fn max_staking_epoch_transition() -> Weight {
3139        T::WeightInfo::operator_reward_tax_and_restake(MAX_BUNDLE_PER_BLOCK).saturating_add(
3140            T::WeightInfo::finalize_domain_epoch_staking(T::MaxPendingStakingOperation::get()),
3141        )
3142    }
3143
3144    pub fn max_deregister_operator() -> Weight {
3145        T::WeightInfo::deregister_operator().max(T::WeightInfo::deregister_deactivated_operator())
3146    }
3147
3148    pub fn max_withdraw_stake() -> Weight {
3149        T::WeightInfo::withdraw_stake()
3150            .max(T::WeightInfo::withdraw_stake_from_deactivated_operator())
3151    }
3152
3153    pub fn max_prune_domain_execution_receipt() -> Weight {
3154        T::WeightInfo::handle_bad_receipt(MAX_BUNDLE_PER_BLOCK)
3155            .saturating_add(T::DbWeight::get().reads_writes(3, 1))
3156    }
3157
3158    fn actual_epoch_transition_weight(epoch_transition_res: EpochTransitionResult) -> Weight {
3159        let EpochTransitionResult {
3160            rewarded_operator_count,
3161            finalized_operator_count,
3162            completed_epoch_index: _,
3163        } = epoch_transition_res;
3164
3165        T::WeightInfo::operator_reward_tax_and_restake(rewarded_operator_count).saturating_add(
3166            T::WeightInfo::finalize_domain_epoch_staking(finalized_operator_count),
3167        )
3168    }
3169
3170    /// Reward the active operators of this domain epoch.
3171    pub fn reward_domain_operators(domain_id: DomainId, rewards: BalanceOf<T>) {
3172        DomainChainRewards::<T>::mutate(domain_id, |current_rewards| {
3173            current_rewards.saturating_add(rewards)
3174        });
3175    }
3176
3177    pub fn storage_fund_account_balance(operator_id: OperatorId) -> BalanceOf<T> {
3178        let storage_fund_acc = storage_fund_account::<T>(operator_id);
3179        T::Currency::reducible_balance(&storage_fund_acc, Preservation::Preserve, Fortitude::Polite)
3180    }
3181
3182    // Get the highest slot of the bundle submitted by a given operator from the previous block
3183    //
3184    // Return 0 if the operator not submit any bundle before
3185    pub fn operator_highest_slot_from_previous_block(
3186        operator_id: OperatorId,
3187        pre_dispatch: bool,
3188    ) -> u64 {
3189        if pre_dispatch {
3190            OperatorHighestSlot::<T>::get(operator_id)
3191        } else {
3192            // The `OperatorBundleSlot` is lazily move to `OperatorHighestSlot` in the `on_initialize` hook
3193            // so when validating tx in the pool we should check `OperatorBundleSlot` first (which is from the
3194            // parent block) then `OperatorHighestSlot`
3195            //
3196            // NOTE: `OperatorBundleSlot` use `BTreeSet` so `last` will return the maximum value in the set
3197            *OperatorBundleSlot::<T>::get(operator_id)
3198                .last()
3199                .unwrap_or(&OperatorHighestSlot::<T>::get(operator_id))
3200        }
3201    }
3202
3203    // Get the domain runtime code that used to derive `receipt`, if the runtime code still present in
3204    // the state then get it from the state otherwise from the `maybe_domain_runtime_code_at` proof.
3205    pub fn get_domain_runtime_code_for_receipt(
3206        domain_id: DomainId,
3207        receipt: &ExecutionReceiptOf<T>,
3208        maybe_domain_runtime_code_at: Option<
3209            DomainRuntimeCodeAt<BlockNumberFor<T>, T::Hash, T::MmrHash>,
3210        >,
3211    ) -> Result<Vec<u8>, FraudProofError> {
3212        let runtime_id = Self::runtime_id(domain_id).ok_or(FraudProofError::RuntimeNotFound)?;
3213        let current_runtime_obj =
3214            RuntimeRegistry::<T>::get(runtime_id).ok_or(FraudProofError::RuntimeNotFound)?;
3215
3216        // NOTE: domain runtime code is taking affect in the next block, so to get the domain runtime code
3217        // that used to derive `receipt` we need to use runtime code at `parent_receipt.consensus_block_number`
3218        let at = {
3219            let parent_receipt =
3220                BlockTreeNodes::<T>::get(*receipt.parent_domain_block_receipt_hash())
3221                    .ok_or(FraudProofError::ParentReceiptNotFound)?
3222                    .execution_receipt;
3223            *parent_receipt.consensus_block_number()
3224        };
3225
3226        let is_domain_runtime_upgraded = current_runtime_obj.updated_at >= at;
3227
3228        let mut runtime_obj = match (is_domain_runtime_upgraded, maybe_domain_runtime_code_at) {
3229            //  The domain runtime is upgraded since `at`, the domain runtime code in `at` is not available
3230            // so `domain_runtime_code_proof` must be provided
3231            (true, None) => return Err(FraudProofError::DomainRuntimeCodeProofNotFound),
3232            (true, Some(domain_runtime_code_at)) => {
3233                let DomainRuntimeCodeAt {
3234                    mmr_proof,
3235                    domain_runtime_code_proof,
3236                } = domain_runtime_code_at;
3237
3238                let state_root = Self::verify_mmr_proof_and_extract_state_root(mmr_proof, at)?;
3239
3240                <DomainRuntimeCodeProof as BasicStorageProof<T::Block>>::verify::<
3241                    T::FraudProofStorageKeyProvider,
3242                >(domain_runtime_code_proof, runtime_id, &state_root)?
3243            }
3244            // Domain runtime code in `at` is available in the state so `domain_runtime_code_proof`
3245            // is unexpected
3246            (false, Some(_)) => return Err(FraudProofError::UnexpectedDomainRuntimeCodeProof),
3247            (false, None) => current_runtime_obj,
3248        };
3249        let code = runtime_obj
3250            .raw_genesis
3251            .take_runtime_code()
3252            .ok_or(storage_proof::VerificationError::RuntimeCodeNotFound)?;
3253        Ok(code)
3254    }
3255
3256    pub fn is_domain_runtime_upgraded_since(
3257        domain_id: DomainId,
3258        at: BlockNumberFor<T>,
3259    ) -> Option<bool> {
3260        Self::runtime_id(domain_id)
3261            .and_then(RuntimeRegistry::<T>::get)
3262            .map(|runtime_obj| runtime_obj.updated_at >= at)
3263    }
3264
3265    pub fn verify_mmr_proof_and_extract_state_root(
3266        mmr_leaf_proof: ConsensusChainMmrLeafProof<BlockNumberFor<T>, T::Hash, T::MmrHash>,
3267        expected_block_number: BlockNumberFor<T>,
3268    ) -> Result<T::Hash, FraudProofError> {
3269        let leaf_data = T::MmrProofVerifier::verify_proof_and_extract_leaf(mmr_leaf_proof)
3270            .ok_or(FraudProofError::BadMmrProof)?;
3271
3272        // Ensure it is a proof of the exact block that we expected
3273        if expected_block_number != leaf_data.block_number() {
3274            return Err(FraudProofError::UnexpectedMmrProof);
3275        }
3276
3277        Ok(leaf_data.state_root())
3278    }
3279
3280    // Return the number of domain runtime upgrade happened since `last_domain_block_number`
3281    fn missed_domain_runtime_upgrade(domain_id: DomainId) -> Result<u32, BlockTreeError> {
3282        let runtime_id = Self::runtime_id(domain_id).ok_or(BlockTreeError::RuntimeNotFound)?;
3283        let last_domain_block_number = HeadDomainNumber::<T>::get(domain_id);
3284
3285        // The consensus block number that derive the last domain block
3286        let last_block_at =
3287            ExecutionInbox::<T>::iter_key_prefix((domain_id, last_domain_block_number))
3288                .next()
3289                // If there is no `ExecutionInbox` exist for the `last_domain_block_number` it means
3290                // there is no bundle submitted for the domain since it is instantiated, in this case,
3291                // we use the `domain_obj.created_at` (which derive the genesis block).
3292                .or(DomainRegistry::<T>::get(domain_id).map(|domain_obj| domain_obj.created_at))
3293                .ok_or(BlockTreeError::LastBlockNotFound)?;
3294
3295        Ok(DomainRuntimeUpgradeRecords::<T>::get(runtime_id)
3296            .into_keys()
3297            .rev()
3298            .take_while(|upgraded_at| *upgraded_at > last_block_at)
3299            .count() as u32)
3300    }
3301
3302    /// Returns true if the Domain is registered.
3303    pub fn is_domain_registered(domain_id: DomainId) -> bool {
3304        DomainStakingSummary::<T>::contains_key(domain_id)
3305    }
3306
3307    /// Returns domain's sudo call, if any.
3308    pub fn domain_sudo_call(domain_id: DomainId) -> Option<Vec<u8>> {
3309        DomainSudoCalls::<T>::get(domain_id).maybe_call
3310    }
3311
3312    // The gap between `domain_best_number` and `HeadReceiptNumber` represent the number
3313    // of receipt to be submitted
3314    pub fn receipt_gap(domain_id: DomainId) -> Result<DomainBlockNumberFor<T>, BundleError> {
3315        let domain_best_number = Self::domain_best_number(domain_id)?;
3316        let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
3317
3318        Ok(domain_best_number.saturating_sub(head_receipt_number))
3319    }
3320
3321    /// Returns true if this is an EVM domain.
3322    pub fn is_evm_domain(domain_id: DomainId) -> bool {
3323        if let Some(domain_obj) = DomainRegistry::<T>::get(domain_id) {
3324            domain_obj.domain_runtime_info.is_evm_domain()
3325        } else {
3326            false
3327        }
3328    }
3329
3330    /// Returns true if this is a private EVM domain.
3331    pub fn is_private_evm_domain(domain_id: DomainId) -> bool {
3332        if let Some(domain_obj) = DomainRegistry::<T>::get(domain_id) {
3333            domain_obj.domain_runtime_info.is_private_evm_domain()
3334        } else {
3335            false
3336        }
3337    }
3338
3339    /// Returns EVM domain's "set contract creation allowed by" call, if any.
3340    pub fn evm_domain_contract_creation_allowed_by_call(
3341        domain_id: DomainId,
3342    ) -> Option<sp_domains::PermissionedActionAllowedBy<EthereumAccountId>> {
3343        EvmDomainContractCreationAllowedByCalls::<T>::get(domain_id).maybe_call
3344    }
3345
3346    /// Updates `previous_versions` with the latest bundle and execution receipt version, and
3347    /// returns the updated map.
3348    #[must_use = "set PreviousBundleAndExecutionReceiptVersions to the value returned by this function"]
3349    pub(crate) fn calculate_previous_bundle_and_execution_receipt_versions<BEV>(
3350        block_number: BlockNumberFor<T>,
3351        mut previous_versions: BTreeMap<BlockNumberFor<T>, BEV>,
3352        current_version: BEV,
3353    ) -> BTreeMap<BlockNumberFor<T>, BEV>
3354    where
3355        BEV: PartialEq,
3356    {
3357        // First version change, just add it to the map (no replacements possible)
3358        if previous_versions.is_empty() {
3359            previous_versions.insert(block_number, current_version);
3360        } else {
3361            // if there is a previous version stored, and
3362            // the last previous version matches the current version,
3363            // then we can mark that version with the latest upgraded block number.
3364            let (prev_number, prev_version) = previous_versions
3365                .pop_last()
3366                .expect("at least one version is available due to check above");
3367
3368            // versions matched, so insert the version with latest block number.
3369            if prev_version == current_version {
3370                previous_versions.insert(block_number, current_version);
3371            } else {
3372                // versions did not match, so keep the last previous version at its original block
3373                // number, and add the current version at the latest block number.
3374                previous_versions.insert(prev_number, prev_version);
3375                previous_versions.insert(block_number, current_version);
3376            }
3377        }
3378
3379        previous_versions
3380    }
3381
3382    /// Returns the current bundle and execution receipt versions.
3383    ///
3384    /// When there is a substrate upgrade at block #x, and if the client
3385    /// uses any runtime apis at that particular block, the new runtime is used
3386    /// instead of previous runtime even though previous runtime was used for execution.
3387    /// This is an unfortunate side-effect of substrate pulling the runtime from :code: key
3388    /// which was replaced with new one in that block #x.
3389    /// Since we store the version before runtime upgrade, if there exists a key in the stored version
3390    /// for that specific block, we return the that version instead of currently defined version on new runtime.
3391    pub fn current_bundle_and_execution_receipt_version() -> BundleAndExecutionReceiptVersion {
3392        let block_number = frame_system::Pallet::<T>::block_number();
3393        let versions = PreviousBundleAndExecutionReceiptVersions::<T>::get();
3394        match versions.get(&block_number) {
3395            // no upgrade happened at this number, so safe to return the current version
3396            None => T::CurrentBundleAndExecutionReceiptVersion::get(),
3397            // upgrade did happen at this block, so return the version stored at this number.
3398            Some(version) => *version,
3399        }
3400    }
3401
3402    /// Returns the complete nominator position for a given operator and account at the current block.
3403    ///
3404    /// This calculates the total position including:
3405    /// - Current stake value (converted from shares using instant share price including rewards)
3406    /// - Total storage fee deposits (known + pending)
3407    /// - Pending deposits (not yet converted to shares)
3408    /// - Pending withdrawals (with unlock timing)
3409    ///
3410    /// Note: Operator accounts are also nominator accounts, so this call will return the position
3411    /// for the operator account.
3412    ///
3413    /// Returns None if no position exists for the given operator and account at the current block.
3414    pub fn nominator_position(
3415        operator_id: OperatorId,
3416        nominator_account: T::AccountId,
3417    ) -> Option<sp_domains::NominatorPosition<BalanceOf<T>, DomainBlockNumberFor<T>, T::Share>>
3418    {
3419        nominator_position::nominator_position::<T>(operator_id, nominator_account)
3420    }
3421}
3422
3423impl<T: Config> subspace_runtime_primitives::OnSetCode<BlockNumberFor<T>> for Pallet<T> {
3424    /// Store the Bundle and Er versions before runtime is upgraded along with the
3425    /// Consensus number at which runtime is upgraded.
3426    fn set_code(block_number: BlockNumberFor<T>) -> DispatchResult {
3427        PreviousBundleAndExecutionReceiptVersions::<T>::set(
3428            Self::calculate_previous_bundle_and_execution_receipt_versions(
3429                block_number,
3430                PreviousBundleAndExecutionReceiptVersions::<T>::get(),
3431                T::CurrentBundleAndExecutionReceiptVersion::get(),
3432            ),
3433        );
3434
3435        Ok(())
3436    }
3437}
3438
3439impl<T: Config> sp_domains::DomainOwner<T::AccountId> for Pallet<T> {
3440    fn is_domain_owner(domain_id: DomainId, acc: T::AccountId) -> bool {
3441        if let Some(domain_obj) = DomainRegistry::<T>::get(domain_id) {
3442            domain_obj.owner_account_id == acc
3443        } else {
3444            false
3445        }
3446    }
3447}
3448
3449impl<T> Pallet<T>
3450where
3451    T: Config + CreateUnsigned<Call<T>>,
3452{
3453    /// Submits an unsigned extrinsic [`Call::submit_bundle`].
3454    pub fn submit_bundle_unsigned(opaque_bundle: OpaqueBundleOf<T>) {
3455        let slot = opaque_bundle.slot_number();
3456        let extrinsics_count = opaque_bundle.body_length();
3457
3458        let call = Call::submit_bundle { opaque_bundle };
3459        let ext = T::create_unsigned(call.into());
3460
3461        match SubmitTransaction::<T, Call<T>>::submit_transaction(ext) {
3462            Ok(()) => {
3463                log::info!("Submitted bundle from slot {slot}, extrinsics: {extrinsics_count}",);
3464            }
3465            Err(()) => {
3466                log::error!("Error submitting bundle");
3467            }
3468        }
3469    }
3470
3471    /// Submits an unsigned extrinsic [`Call::submit_receipt`].
3472    pub fn submit_receipt_unsigned(singleton_receipt: SingletonReceiptOf<T>) {
3473        let slot = singleton_receipt.slot_number();
3474        let domain_block_number = *singleton_receipt.receipt().domain_block_number();
3475
3476        let call = Call::submit_receipt { singleton_receipt };
3477        let ext = T::create_unsigned(call.into());
3478        match SubmitTransaction::<T, Call<T>>::submit_transaction(ext) {
3479            Ok(()) => {
3480                log::info!(
3481                    "Submitted singleton receipt from slot {slot}, domain_block_number: {domain_block_number:?}",
3482                );
3483            }
3484            Err(()) => {
3485                log::error!("Error submitting singleton receipt");
3486            }
3487        }
3488    }
3489
3490    /// Submits an unsigned extrinsic [`Call::submit_fraud_proof`].
3491    pub fn submit_fraud_proof_unsigned(fraud_proof: FraudProofFor<T>) {
3492        let call = Call::submit_fraud_proof {
3493            fraud_proof: Box::new(fraud_proof),
3494        };
3495
3496        let ext = T::create_unsigned(call.into());
3497        match SubmitTransaction::<T, Call<T>>::submit_transaction(ext) {
3498            Ok(()) => {
3499                log::info!("Submitted fraud proof");
3500            }
3501            Err(()) => {
3502                log::error!("Error submitting fraud proof");
3503            }
3504        }
3505    }
3506}
3507
3508/// Calculates the new tx range based on the bundles produced during the interval.
3509pub fn calculate_tx_range(
3510    cur_tx_range: U256,
3511    actual_bundle_count: u64,
3512    expected_bundle_count: u64,
3513) -> U256 {
3514    if actual_bundle_count == 0 || expected_bundle_count == 0 {
3515        return cur_tx_range;
3516    }
3517
3518    let Some(new_tx_range) = U256::from(actual_bundle_count)
3519        .saturating_mul(&cur_tx_range)
3520        .checked_div(&U256::from(expected_bundle_count))
3521    else {
3522        return cur_tx_range;
3523    };
3524
3525    let upper_bound = cur_tx_range.saturating_mul(&U256::from(4_u64));
3526    let Some(lower_bound) = cur_tx_range.checked_div(&U256::from(4_u64)) else {
3527        return cur_tx_range;
3528    };
3529    new_tx_range.clamp(lower_bound, upper_bound)
3530}