1#![cfg_attr(not(feature = "std"), no_std)]
4#![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
88pub 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 fn future_slot(block_number: BlockNumberFor<T>) -> Option<sp_consensus_slots::Slot>;
108
109 fn slot_produced_after(to_check: sp_consensus_slots::Slot) -> Option<BlockNumberFor<T>>;
111
112 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#[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#[derive(
175 PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DecodeWithMemTracking,
176)]
177pub enum RawOrigin {
178 ValidatedUnsigned,
179}
180
181pub 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
198const STORAGE_VERSION: StorageVersion = StorageVersion::new(6);
200
201const MAX_BUNDLE_PER_BLOCK: u32 = 100;
206
207pub(crate) type StateRootOf<T> = <<T as frame_system::Config>::Hashing as Hash>::Output;
208
209pub 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 type DomainOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ()>;
328
329 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 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 type DomainHeader: HeaderT<Hash = Self::DomainHash>;
365
366 #[pallet::constant]
368 type ConfirmationDepthK: Get<BlockNumberFor<Self>>;
369
370 type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
372 + Mutate<Self::AccountId>
373 + InspectHold<Self::AccountId>
374 + MutateHold<Self::AccountId>;
375
376 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 type HoldIdentifier: HoldIdentifier<Self>;
391
392 #[pallet::constant]
394 type BlockTreePruningDepth: Get<DomainBlockNumberFor<Self>>;
395
396 #[pallet::constant]
398 type ConsensusSlotProbability: Get<(u64, u64)>;
399
400 #[pallet::constant]
402 type MaxDomainBlockSize: Get<u32>;
403
404 #[pallet::constant]
406 type MaxDomainBlockWeight: Get<Weight>;
407
408 #[pallet::constant]
410 type MaxDomainNameLength: Get<u32>;
411
412 #[pallet::constant]
414 type DomainInstantiationDeposit: Get<BalanceOf<Self>>;
415
416 type WeightInfo: WeightInfo;
418
419 #[pallet::constant]
421 type InitialDomainTxRange: Get<u64>;
422
423 #[pallet::constant]
425 type DomainTxRangeAdjustmentInterval: Get<u64>;
426
427 #[pallet::constant]
429 type MinOperatorStake: Get<BalanceOf<Self>>;
430
431 #[pallet::constant]
433 type MinNominatorStake: Get<BalanceOf<Self>>;
434
435 #[pallet::constant]
437 type StakeWithdrawalLockingPeriod: Get<DomainBlockNumberFor<Self>>;
438
439 #[pallet::constant]
441 type StakeEpochDuration: Get<DomainBlockNumberFor<Self>>;
442
443 #[pallet::constant]
445 type TreasuryAccount: Get<Self::AccountId>;
446
447 #[pallet::constant]
449 type MaxPendingStakingOperation: Get<u32>;
450
451 type Randomness: RandomnessT<Self::Hash, BlockNumberFor<Self>>;
453
454 #[pallet::constant]
456 type PalletId: Get<frame_support::PalletId>;
457
458 type StorageFee: StorageFee<BalanceOf<Self>>;
460
461 type BlockTimestamp: Time;
463
464 type BlockSlot: BlockSlot<Self>;
466
467 type DomainsTransfersTracker: DomainsTransfersTracker<BalanceOf<Self>>;
469
470 type MaxInitialDomainAccounts: Get<u32>;
472
473 type MinInitialDomainAccountBalance: Get<BalanceOf<Self>>;
475
476 #[pallet::constant]
478 type BundleLongevity: Get<u32>;
479
480 type DomainBundleSubmitted: DomainBundleSubmitted;
482
483 type OnDomainInstantiated: OnDomainInstantiated;
485
486 type MmrHash: Parameter + Member + Default + Clone;
488
489 type MmrProofVerifier: MmrProofVerifier<Self::MmrHash, BlockNumberFor<Self>, StateRootOf<Self>>;
491
492 type FraudProofStorageKeyProvider: FraudProofStorageKeyProvider<BlockNumberFor<Self>>;
494
495 type OnChainRewards: OnChainRewards<BalanceOf<Self>>;
497
498 #[pallet::constant]
502 type WithdrawalLimit: Get<u32>;
503
504 #[pallet::constant]
506 type CurrentBundleAndExecutionReceiptVersion: Get<BundleAndExecutionReceiptVersion>;
507
508 #[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 #[pallet::storage]
520 pub type SuccessfulBundles<T> = StorageMap<_, Identity, DomainId, Vec<H256>, ValueQuery>;
521
522 #[pallet::storage]
524 pub(super) type NextRuntimeId<T> = StorageValue<_, RuntimeId, ValueQuery>;
525
526 #[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 #[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 #[pallet::storage]
569 pub(super) type OperatorHighestSlot<T: Config> =
570 StorageMap<_, Identity, OperatorId, u64, ValueQuery>;
571
572 #[pallet::storage]
575 pub(super) type OperatorBundleSlot<T: Config> =
576 StorageMap<_, Identity, OperatorId, BTreeSet<u64>, ValueQuery>;
577
578 #[pallet::storage]
581 pub type OperatorEpochSharePrice<T: Config> =
582 StorageDoubleMap<_, Identity, OperatorId, Identity, DomainEpoch, SharePrice, OptionQuery>;
583
584 #[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 #[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 #[pallet::storage]
610 pub(super) type DepositOnHold<T: Config> =
611 StorageMap<_, Identity, (OperatorId, NominatorId<T>), BalanceOf<T>, ValueQuery>;
612
613 #[pallet::storage]
617 pub(crate) type PendingSlashes<T: Config> =
618 StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, OptionQuery>;
619
620 #[pallet::storage]
623 pub(super) type PendingStakingOperationCount<T: Config> =
624 StorageMap<_, Identity, DomainId, u32, ValueQuery>;
625
626 #[pallet::storage]
628 #[pallet::getter(fn next_domain_id)]
629 pub(super) type NextDomainId<T> = StorageValue<_, DomainId, ValueQuery>;
630
631 #[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 #[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 #[pallet::storage]
656 pub(super) type BlockTreeNodes<T: Config> =
657 StorageMap<_, Identity, ReceiptHashFor<T>, BlockTreeNodeFor<T>, OptionQuery>;
658
659 #[pallet::storage]
661 pub(super) type HeadReceiptNumber<T: Config> =
662 StorageMap<_, Identity, DomainId, DomainBlockNumberFor<T>, ValueQuery>;
663
664 #[pallet::storage]
668 pub(super) type NewAddedHeadReceipt<T: Config> =
669 StorageMap<_, Identity, DomainId, T::DomainHash, OptionQuery>;
670
671 #[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 #[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 #[pallet::storage]
702 pub(super) type InboxedBundleAuthor<T: Config> =
703 StorageMap<_, Identity, T::DomainHash, OperatorId, OptionQuery>;
704
705 #[pallet::storage]
714 pub(crate) type HeadDomainNumber<T: Config> =
715 StorageMap<_, Identity, DomainId, DomainBlockNumberFor<T>, ValueQuery>;
716
717 #[pallet::storage]
723 pub(super) type LastEpochStakingDistribution<T: Config> =
724 StorageMap<_, Identity, DomainId, ElectionVerificationParams<BalanceOf<T>>, OptionQuery>;
725
726 #[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 #[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 #[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 #[pallet::storage]
751 pub(super) type PermissionedActionAllowedBy<T: Config> =
752 StorageValue<_, sp_domains::PermissionedActionAllowedBy<T::AccountId>, OptionQuery>;
753
754 #[pallet::storage]
757 pub(super) type AccumulatedTreasuryFunds<T> = StorageValue<_, BalanceOf<T>, ValueQuery>;
758
759 #[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 #[pallet::storage]
772 pub type DomainRuntimeUpgrades<T> = StorageValue<_, Vec<RuntimeId>, ValueQuery>;
773
774 #[pallet::storage]
779 pub type DomainSudoCalls<T: Config> =
780 StorageMap<_, Identity, DomainId, DomainSudoCall, ValueQuery>;
781
782 #[pallet::storage]
786 pub type FrozenDomains<T> = StorageValue<_, BTreeSet<DomainId>, ValueQuery>;
787
788 #[pallet::storage]
793 pub type EvmDomainContractCreationAllowedByCalls<T: Config> =
794 StorageMap<_, Identity, DomainId, EvmDomainContractCreationAllowedByCall, ValueQuery>;
795
796 #[pallet::storage]
799 pub type DomainChainRewards<T: Config> =
800 StorageMap<_, Identity, DomainId, BalanceOf<T>, ValueQuery>;
801
802 #[pallet::storage]
805 pub type InvalidBundleAuthors<T: Config> =
806 StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, ValueQuery>;
807
808 #[pallet::storage]
811 pub type DeactivatedOperators<T: Config> =
812 StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, ValueQuery>;
813
814 #[pallet::storage]
817 pub type DeregisteredOperators<T: Config> =
818 StorageMap<_, Identity, DomainId, BTreeSet<OperatorId>, ValueQuery>;
819
820 #[pallet::storage]
828 pub type PreviousBundleAndExecutionReceiptVersions<T> =
829 StorageValue<_, BTreeMap<BlockNumberFor<T>, BundleAndExecutionReceiptVersion>, ValueQuery>;
830
831 #[pallet::storage]
833 pub type EpochStartSlot<T> = StorageValue<_, Slot, OptionQuery>;
834
835 #[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 InvalidOperatorId,
844 BadBundleSignature,
846 BadVrfSignature,
848 InvalidDomainId,
850 BadOperator,
852 ThresholdUnsatisfied,
854 InvalidThreshold,
856 Receipt(BlockTreeError),
858 BundleTooLarge,
860 InvalidExtrinsicRoot,
862 InvalidProofOfTime,
864 SlotInTheFuture,
866 SlotInThePast,
868 BundleTooHeavy,
870 SlotSmallerThanPreviousBlockBundle,
873 EquivocatedBundle,
875 DomainFrozen,
877 UnableToPayBundleStorageFee,
879 UnexpectedReceiptGap,
881 ExpectingReceiptGap,
883 FailedToGetMissedUpgradeCount,
885 BundleVersionMismatch,
887 ExecutionVersionMismatch,
889 ExecutionVersionMissing,
891 }
892
893 #[derive(TypeInfo, Encode, Decode, PalletError, Debug, PartialEq, DecodeWithMemTracking)]
894 pub enum FraudProofError {
895 BadReceiptNotFound,
898 ChallengingGenesisReceipt,
900 DescendantsOfFraudulentERNotPruned,
902 InvalidBlockFeesFraudProof,
904 InvalidTransfersFraudProof,
906 InvalidDomainBlockHashFraudProof,
908 InvalidExtrinsicRootFraudProof,
910 InvalidStateTransitionFraudProof,
912 ParentReceiptNotFound,
914 InvalidBundleFraudProof,
916 BadValidBundleFraudProof,
918 MissingOperator,
920 UnexpectedFraudProof,
922 BadReceiptAlreadyReported,
924 BadMmrProof,
926 UnexpectedMmrProof,
928 MissingMmrProof,
930 RuntimeNotFound,
932 DomainRuntimeCodeProofNotFound,
934 UnexpectedDomainRuntimeCodeProof,
936 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 FraudProof(FraudProofError),
1014 RuntimeRegistry(RuntimeRegistryError),
1016 Staking(StakingError),
1018 StakingEpoch(StakingEpochError),
1020 DomainRegistry(DomainRegistryError),
1022 BlockTree(BlockTreeError),
1024 BundleStorageFund(BundleStorageFundError),
1026 PermissionedActionNotAllowed,
1028 DomainSudoCallExists,
1030 InvalidDomainSudoCall,
1032 DomainNotFrozen,
1034 NotPrivateEvmDomain,
1036 NotDomainOwnerOrRoot,
1038 EvmDomainContractCreationAllowedByCallExists,
1040 }
1041
1042 #[derive(Clone, Debug, PartialEq, Encode, Decode, TypeInfo, DecodeWithMemTracking)]
1044 pub enum SlashedReason<DomainBlock, ReceiptHash> {
1045 InvalidBundle(DomainBlock),
1047 BadExecutionReceipt(ReceiptHash),
1049 }
1050
1051 #[pallet::event]
1052 #[pallet::generate_deposit(pub (super) fn deposit_event)]
1053 pub enum Event<T: Config> {
1054 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 #[derive(Debug, Default, Decode, Encode, TypeInfo, PartialEq, Eq)]
1177 pub struct TxRangeState {
1178 pub tx_range: U256,
1180
1181 pub interval_blocks: u64,
1183
1184 pub interval_bundles: u64,
1186 }
1187
1188 impl TxRangeState {
1189 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 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 ReceiptType::Accepted(accepted_receipt_type) => {
1238 #[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 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 #[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 if SuccessfulBundles::<T>::get(domain_id).is_empty() {
1324 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 #[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 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 #[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 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 ensure!(
1426 head_receipt_number >= bad_receipt_number,
1427 Error::<T>::from(FraudProofError::BadReceiptNotFound),
1428 );
1429
1430 #[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 do_unmark_invalid_bundle_authors::<T>(domain_id, &execution_receipt)
1457 .map_err(Error::<T>::Staking)?;
1458 }
1459
1460 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 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 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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 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 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 do_unmark_invalid_bundle_authors::<T>(domain_id, &execution_receipt)
1829 .map_err(Error::<T>::Staking)?;
1830
1831 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 #[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 ReceiptType::Accepted(accepted_receipt_type) => {
1885 #[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 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 #[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 #[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 Ok(Some(actual_weight.min(Self::max_submit_receipt_weight())).into())
1976 }
1977
1978 #[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 #[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 #[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 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 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 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 #[pallet::storage]
2123 pub type BlockInherentExtrinsicData<T> = StorageValue<_, InherentExtrinsicData>;
2124
2125 #[pallet::hooks]
2126 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 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 DomainRuntimeUpgrades::<T>::set(Vec::new());
2152 do_upgrade_runtimes::<T>(block_number);
2155
2156 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 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 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 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 let timestamp = Self::timestamp_value();
2200
2201 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 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 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 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 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 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 let current_block_number = frame_system::Pallet::<T>::current_block_number();
2352
2353 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 let produced_after_block_number =
2364 match T::BlockSlot::slot_produced_after(slot_number.into()) {
2365 Some(n) => n,
2366 None => {
2367 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 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 !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!(
2453 slot_number
2454 > Self::operator_highest_slot_from_previous_block(operator_id, pre_dispatch),
2455 BundleError::SlotSmallerThanPreviousBlockBundle,
2456 );
2457
2458 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 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 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!(
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 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 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 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 let tag = fraud_proof.domain_id();
2835
2836 Ok((tag, priority))
2837 }
2838
2839 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 fn initial_tx_range() -> U256 {
2863 U256::MAX / T::InitialDomainTxRange::get()
2864 }
2865
2866 pub fn head_receipt_number(domain_id: DomainId) -> DomainBlockNumberFor<T> {
2868 HeadReceiptNumber::<T>::get(domain_id)
2869 }
2870
2871 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 None
2890 }
2891 }
2892
2893 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 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 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 let mut to_check =
2932 Self::latest_confirmed_domain_block_number(domain_id).saturating_add(One::one());
2933
2934 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 pub fn extrinsics_shuffling_seed() -> T::Hash {
2958 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 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 pub fn timestamp() -> Moment {
2975 BlockInherentExtrinsicData::<T>::get()
2977 .map(|data| data.timestamp)
2978 .unwrap_or_else(|| Self::timestamp_value())
2979 }
2980
2981 fn timestamp_value() -> Moment {
2984 T::BlockTimestamp::now()
2987 .try_into()
2988 .map_err(|_| ())
2989 .expect("Moment is the same type in both pallets; qed")
2990 }
2991
2992 pub fn consensus_transaction_byte_fee() -> Balance {
2996 BlockInherentExtrinsicData::<T>::get()
2998 .map(|data| data.consensus_transaction_byte_fee)
2999 .unwrap_or_else(|| Self::consensus_transaction_byte_fee_value())
3000 }
3001
3002 fn consensus_transaction_byte_fee_value() -> Balance {
3005 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 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 match previous_versions.last_key_value() {
3031 None => {
3033 return Some(current_version);
3034 }
3035 Some((number, version)) => {
3036 if er_derived_number > *number {
3039 return Some(current_version);
3040 }
3041
3042 if er_derived_number == *number {
3045 return Some(*version);
3046 }
3047 }
3048 }
3049
3050 for (upgraded_number, version) in previous_versions.into_iter() {
3053 if er_derived_number <= upgraded_number {
3054 return Some(version);
3055 }
3056 }
3057
3058 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 if receipt_number.is_zero() {
3079 return false;
3080 }
3081
3082 let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
3083
3084 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 if latest_submitted_er.is_zero() {
3094 return false;
3095 }
3096
3097 let head_receipt_number = HeadReceiptNumber::<T>::get(domain_id);
3098
3099 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 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 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 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 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 *OperatorBundleSlot::<T>::get(operator_id)
3198 .last()
3199 .unwrap_or(&OperatorHighestSlot::<T>::get(operator_id))
3200 }
3201 }
3202
3203 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 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 (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 (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 if expected_block_number != leaf_data.block_number() {
3274 return Err(FraudProofError::UnexpectedMmrProof);
3275 }
3276
3277 Ok(leaf_data.state_root())
3278 }
3279
3280 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 let last_block_at =
3287 ExecutionInbox::<T>::iter_key_prefix((domain_id, last_domain_block_number))
3288 .next()
3289 .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 pub fn is_domain_registered(domain_id: DomainId) -> bool {
3304 DomainStakingSummary::<T>::contains_key(domain_id)
3305 }
3306
3307 pub fn domain_sudo_call(domain_id: DomainId) -> Option<Vec<u8>> {
3309 DomainSudoCalls::<T>::get(domain_id).maybe_call
3310 }
3311
3312 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 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 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 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 #[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 if previous_versions.is_empty() {
3359 previous_versions.insert(block_number, current_version);
3360 } else {
3361 let (prev_number, prev_version) = previous_versions
3365 .pop_last()
3366 .expect("at least one version is available due to check above");
3367
3368 if prev_version == current_version {
3370 previous_versions.insert(block_number, current_version);
3371 } else {
3372 previous_versions.insert(prev_number, prev_version);
3375 previous_versions.insert(block_number, current_version);
3376 }
3377 }
3378
3379 previous_versions
3380 }
3381
3382 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 None => T::CurrentBundleAndExecutionReceiptVersion::get(),
3397 Some(version) => *version,
3399 }
3400 }
3401
3402 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 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 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 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 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
3508pub 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}