Skip to main content

pallet_subspace/
lib.rs

1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3// TODO: Remove once FRAME macros stop generating `.clone()` calls on `Copy` types with user spans
4#![expect(clippy::clone_on_copy, reason = "Comes from Substrate")]
5#![cfg_attr(test, feature(portable_simd))]
6#![warn(unused_must_use, unsafe_code, unused_variables)]
7
8#[cfg(not(feature = "std"))]
9extern crate alloc;
10
11#[cfg(test)]
12mod mock;
13#[cfg(test)]
14mod tests;
15
16#[cfg(feature = "runtime-benchmarks")]
17mod benchmarking;
18
19pub mod extensions;
20pub mod weights;
21
22use crate::extensions::weights::WeightInfo as ExtensionWeightInfo;
23#[cfg(not(feature = "std"))]
24use alloc::string::String;
25use core::num::NonZeroU64;
26use frame_support::dispatch::DispatchResult;
27use frame_support::pallet_prelude::EnsureOrigin;
28use frame_support::traits::Get;
29use frame_system::offchain::SubmitTransaction;
30use frame_system::pallet_prelude::*;
31use log::{debug, error, warn};
32pub use pallet::*;
33use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
34use scale_info::TypeInfo;
35use schnorrkel::SignatureError;
36use sp_consensus_slots::Slot;
37use sp_consensus_subspace::consensus::{is_proof_of_time_valid, verify_solution};
38use sp_consensus_subspace::digests::CompatibleDigestItem;
39use sp_consensus_subspace::{
40    PotParameters, PotParametersChange, SignedVote, Vote, WrappedPotOutput,
41};
42use sp_runtime::Weight;
43use sp_runtime::generic::DigestItem;
44use sp_runtime::traits::{BlockNumberProvider, CheckedSub, Hash, One, Zero};
45use sp_runtime::transaction_validity::{
46    InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
47    TransactionValidityError, ValidTransaction,
48};
49use sp_std::collections::btree_map::BTreeMap;
50use sp_std::prelude::*;
51use subspace_core_primitives::pieces::PieceOffset;
52use subspace_core_primitives::sectors::{SectorId, SectorIndex};
53use subspace_core_primitives::segments::{
54    ArchivedHistorySegment, HistorySize, SegmentHeader, SegmentIndex,
55};
56use subspace_core_primitives::solutions::{RewardSignature, SolutionRange};
57use subspace_core_primitives::{
58    BlockHash, PublicKey, REWARD_SIGNING_CONTEXT, ScalarBytes, SlotNumber,
59};
60use subspace_runtime_primitives::CreateUnsigned;
61use subspace_verification::{
62    PieceCheckParams, VerifySolutionParams, check_reward_signature, derive_next_solution_range,
63    derive_pot_entropy,
64};
65pub use weights::WeightInfo;
66
67/// Trigger an era change, if any should take place.
68pub trait EraChangeTrigger {
69    /// Trigger an era change, if any should take place. This should be called
70    /// during every block, after initialization is done.
71    fn trigger<T: Config>(block_number: BlockNumberFor<T>);
72}
73
74/// A type signifying to Subspace that it should perform era changes with an internal trigger.
75pub struct NormalEraChange;
76
77impl EraChangeTrigger for NormalEraChange {
78    fn trigger<T: Config>(block_number: BlockNumberFor<T>) {
79        if <Pallet<T>>::should_era_change(block_number) {
80            <Pallet<T>>::enact_era_change();
81        }
82    }
83}
84
85/// Custom origin for validated unsigned extrinsics.
86#[derive(
87    PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DecodeWithMemTracking,
88)]
89pub enum RawOrigin {
90    ValidatedUnsigned,
91}
92
93/// Ensure the subspace origin.
94pub struct EnsureSubspaceOrigin;
95impl<O: Into<Result<RawOrigin, O>> + From<RawOrigin>> EnsureOrigin<O> for EnsureSubspaceOrigin {
96    type Success = ();
97
98    fn try_origin(o: O) -> Result<Self::Success, O> {
99        o.into().map(|o| match o {
100            RawOrigin::ValidatedUnsigned => (),
101        })
102    }
103
104    #[cfg(feature = "runtime-benchmarks")]
105    fn try_successful_origin() -> Result<O, ()> {
106        Ok(O::from(RawOrigin::ValidatedUnsigned))
107    }
108}
109
110#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, TypeInfo)]
111struct VoteVerificationData {
112    /// Block solution range, vote must not reach it
113    solution_range: SolutionRange,
114    vote_solution_range: SolutionRange,
115    current_slot: Slot,
116    parent_slot: Slot,
117}
118
119#[frame_support::pallet]
120pub mod pallet {
121    use super::{EraChangeTrigger, ExtensionWeightInfo, VoteVerificationData};
122    use crate::RawOrigin;
123    use crate::weights::WeightInfo;
124    use frame_support::pallet_prelude::*;
125    use frame_system::pallet_prelude::*;
126    use sp_consensus_slots::Slot;
127    use sp_consensus_subspace::SignedVote;
128    use sp_consensus_subspace::digests::CompatibleDigestItem;
129    use sp_consensus_subspace::inherents::{INHERENT_IDENTIFIER, InherentError, InherentType};
130    use sp_runtime::DigestItem;
131    use sp_runtime::traits::One;
132    use sp_std::collections::btree_map::BTreeMap;
133    use sp_std::num::NonZeroU32;
134    use sp_std::prelude::*;
135    use subspace_core_primitives::hashes::Blake3Hash;
136    use subspace_core_primitives::pieces::PieceOffset;
137    use subspace_core_primitives::pot::PotCheckpoints;
138    use subspace_core_primitives::sectors::SectorIndex;
139    use subspace_core_primitives::segments::{HistorySize, SegmentHeader, SegmentIndex};
140    use subspace_core_primitives::solutions::{RewardSignature, SolutionRange};
141    use subspace_core_primitives::{PublicKey, Randomness, ScalarBytes};
142
143    pub(super) struct InitialSolutionRanges<T: Config> {
144        _config: T,
145    }
146
147    impl<T: Config> Get<sp_consensus_subspace::SolutionRanges> for InitialSolutionRanges<T> {
148        fn get() -> sp_consensus_subspace::SolutionRanges {
149            sp_consensus_subspace::SolutionRanges {
150                current: T::InitialSolutionRange::get(),
151                next: None,
152                voting_current: if T::ShouldAdjustSolutionRange::get() {
153                    T::InitialSolutionRange::get()
154                        .saturating_mul(u64::from(T::ExpectedVotesPerBlock::get()) + 1)
155                } else {
156                    T::InitialSolutionRange::get()
157                },
158                voting_next: None,
159            }
160        }
161    }
162
163    /// Override for next solution range adjustment
164    #[derive(Debug, Encode, Decode, TypeInfo)]
165    pub(super) struct SolutionRangeOverride {
166        /// Value that should be set as solution range
167        pub(super) solution_range: SolutionRange,
168        /// Value that should be set as voting solution range
169        pub(super) voting_solution_range: SolutionRange,
170    }
171
172    /// The Subspace Pallet
173    #[pallet::pallet]
174    #[pallet::without_storage_info]
175    pub struct Pallet<T>(_);
176
177    #[pallet::config]
178    #[pallet::disable_frame_system_supertrait_check]
179    pub trait Config: frame_system::Config<RuntimeEvent: From<Event<Self>>> {
180        /// Origin for subspace call.
181        type SubspaceOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ()>;
182
183        /// Number of slots between slot arrival and when corresponding block can be produced.
184        ///
185        /// Practically this means future proof of time proof needs to be revealed this many slots
186        /// ahead before block can be authored even though solution is available before that.
187        #[pallet::constant]
188        type BlockAuthoringDelay: Get<Slot>;
189
190        /// Interval, in blocks, between blockchain entropy injection into proof of time chain.
191        #[pallet::constant]
192        type PotEntropyInjectionInterval: Get<BlockNumberFor<Self>>;
193
194        /// Interval, in entropy injection intervals, where to take entropy for injection from.
195        #[pallet::constant]
196        type PotEntropyInjectionLookbackDepth: Get<u8>;
197
198        /// Delay after block, in slots, when entropy injection takes effect.
199        #[pallet::constant]
200        type PotEntropyInjectionDelay: Get<Slot>;
201
202        /// The amount of time, in blocks, that each era should last.
203        /// NOTE: Currently it is not possible to change the era duration after
204        /// the chain has started. Attempting to do so will brick block production.
205        #[pallet::constant]
206        type EraDuration: Get<BlockNumberFor<Self>>;
207
208        /// Initial solution range used for challenges during the very first era.
209        #[pallet::constant]
210        type InitialSolutionRange: Get<SolutionRange>;
211
212        /// How often in slots slots (on average, not counting collisions) will have a block.
213        ///
214        /// Expressed as a rational where the first member of the tuple is the
215        /// numerator and the second is the denominator. The rational should
216        /// represent a value between 0 and 1.
217        #[pallet::constant]
218        type SlotProbability: Get<(u64, u64)>;
219
220        /// Depth `K` after which a block enters the recorded history (a global constant, as opposed
221        /// to the client-dependent transaction confirmation depth `k`).
222        #[pallet::constant]
223        type ConfirmationDepthK: Get<BlockNumberFor<Self>>;
224
225        /// Number of latest archived segments that are considered "recent history".
226        #[pallet::constant]
227        type RecentSegments: Get<HistorySize>;
228
229        /// Fraction of pieces from the "recent history" (`recent_segments`) in each sector.
230        #[pallet::constant]
231        type RecentHistoryFraction: Get<(HistorySize, HistorySize)>;
232
233        /// Minimum lifetime of a plotted sector, measured in archived segment.
234        #[pallet::constant]
235        type MinSectorLifetime: Get<HistorySize>;
236
237        /// Number of votes expected per block.
238        ///
239        /// This impacts solution range for votes in consensus.
240        #[pallet::constant]
241        type ExpectedVotesPerBlock: Get<u32>;
242
243        /// How many pieces one sector is supposed to contain (max)
244        #[pallet::constant]
245        type MaxPiecesInSector: Get<u16>;
246
247        type ShouldAdjustSolutionRange: Get<bool>;
248        /// Subspace requires some logic to be triggered on every block to query for whether an era
249        /// has ended and to perform the transition to the next era.
250        ///
251        /// Era is normally used to update solution range used for challenges.
252        type EraChangeTrigger: EraChangeTrigger;
253
254        /// Weight information for extrinsics in this pallet.
255        type WeightInfo: WeightInfo;
256
257        /// Maximum number of block number to block slot mappings to keep (oldest pruned first).
258        #[pallet::constant]
259        type BlockSlotCount: Get<u32>;
260
261        /// Extension weight information for the pallet's extensions.
262        type ExtensionWeightInfo: ExtensionWeightInfo;
263    }
264
265    #[derive(Debug, Default, Encode, Decode, TypeInfo)]
266    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
267    pub enum AllowAuthoringBy {
268        /// Anyone can author new blocks at genesis.
269        #[default]
270        Anyone,
271        /// Author of the first block will be able to author blocks going forward unless unlocked
272        /// for everyone.
273        FirstFarmer,
274        /// Specified root farmer is allowed to author blocks unless unlocked for everyone.
275        RootFarmer(PublicKey),
276    }
277
278    #[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo)]
279    pub(super) struct PotEntropyValue {
280        /// Target slot at which entropy should be injected (when known)
281        pub(super) target_slot: Option<Slot>,
282        pub(super) entropy: Blake3Hash,
283    }
284
285    #[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo, PartialEq)]
286    pub(super) struct PotSlotIterationsValue {
287        pub(super) slot_iterations: NonZeroU32,
288        /// Scheduled proof of time slot iterations update
289        pub(super) update: Option<PotSlotIterationsUpdate>,
290    }
291
292    #[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo, PartialEq)]
293    pub(super) struct PotSlotIterationsUpdate {
294        /// Target slot at which entropy should be injected (when known)
295        pub(super) target_slot: Option<Slot>,
296        pub(super) slot_iterations: NonZeroU32,
297    }
298
299    /// When to enable block/vote rewards
300    #[derive(
301        Debug, Copy, Clone, Eq, PartialEq, Encode, Decode, TypeInfo, DecodeWithMemTracking,
302    )]
303    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
304    pub enum EnableRewardsAt<BlockNumber> {
305        /// At specified height or next block if `None`
306        Height(BlockNumber),
307        /// When solution range is below specified threshold
308        SolutionRange(u64),
309        /// Manually with an explicit extrinsic
310        Manually,
311    }
312
313    #[pallet::genesis_config]
314    pub struct GenesisConfig<T>
315    where
316        T: Config,
317    {
318        /// When rewards should be enabled.
319        pub enable_rewards_at: EnableRewardsAt<BlockNumberFor<T>>,
320        /// Who can author blocks at genesis.
321        pub allow_authoring_by: AllowAuthoringBy,
322        /// Number of iterations for proof of time per slot
323        pub pot_slot_iterations: NonZeroU32,
324        #[serde(skip)]
325        pub phantom: PhantomData<T>,
326    }
327
328    impl<T> Default for GenesisConfig<T>
329    where
330        T: Config,
331    {
332        #[inline]
333        fn default() -> Self {
334            Self {
335                enable_rewards_at: EnableRewardsAt::Height(BlockNumberFor::<T>::one()),
336                allow_authoring_by: AllowAuthoringBy::Anyone,
337                pot_slot_iterations: NonZeroU32::MIN,
338                phantom: PhantomData,
339            }
340        }
341    }
342
343    #[pallet::genesis_build]
344    impl<T> BuildGenesisConfig for GenesisConfig<T>
345    where
346        T: Config,
347    {
348        fn build(&self) {
349            match self.enable_rewards_at {
350                EnableRewardsAt::Height(block_number) => {
351                    EnableRewards::<T>::put(block_number);
352                }
353                EnableRewardsAt::SolutionRange(solution_range) => {
354                    EnableRewardsBelowSolutionRange::<T>::put(solution_range);
355                }
356                EnableRewardsAt::Manually => {
357                    // Nothing to do in this case
358                }
359            }
360            match &self.allow_authoring_by {
361                AllowAuthoringBy::Anyone => {
362                    AllowAuthoringByAnyone::<T>::put(true);
363                }
364                AllowAuthoringBy::FirstFarmer => {
365                    AllowAuthoringByAnyone::<T>::put(false);
366                }
367                AllowAuthoringBy::RootFarmer(root_farmer) => {
368                    AllowAuthoringByAnyone::<T>::put(false);
369                    RootPlotPublicKey::<T>::put(root_farmer);
370                }
371            }
372            PotSlotIterations::<T>::put(PotSlotIterationsValue {
373                slot_iterations: self.pot_slot_iterations,
374                update: None,
375            });
376        }
377    }
378
379    /// Events type.
380    #[pallet::event]
381    #[pallet::generate_deposit(pub (super) fn deposit_event)]
382    pub enum Event<T: Config> {
383        /// Segment header was stored in blockchain history.
384        SegmentHeaderStored { segment_header: SegmentHeader },
385        /// Farmer vote.
386        FarmerVote {
387            public_key: PublicKey,
388            reward_address: T::AccountId,
389            height: BlockNumberFor<T>,
390            parent_hash: T::Hash,
391        },
392    }
393
394    #[pallet::origin]
395    pub type Origin = RawOrigin;
396
397    #[pallet::error]
398    pub enum Error<T> {
399        /// Solution range adjustment already enabled.
400        SolutionRangeAdjustmentAlreadyEnabled,
401        /// Iterations are not multiple of number of checkpoints times two
402        NotMultipleOfCheckpoints,
403        /// Proof of time slot iterations must increase as hardware improves
404        PotSlotIterationsMustIncrease,
405        /// Proof of time slot iterations update already scheduled
406        PotSlotIterationsUpdateAlreadyScheduled,
407    }
408
409    /// Bounded mapping from block number to slot
410    #[pallet::storage]
411    #[pallet::getter(fn block_slots)]
412    pub(super) type BlockSlots<T: Config> =
413        StorageValue<_, BoundedBTreeMap<BlockNumberFor<T>, Slot, T::BlockSlotCount>, ValueQuery>;
414
415    /// Solution ranges used for challenges.
416    #[pallet::storage]
417    #[pallet::getter(fn solution_ranges)]
418    pub(super) type SolutionRanges<T: Config> = StorageValue<
419        _,
420        sp_consensus_subspace::SolutionRanges,
421        ValueQuery,
422        InitialSolutionRanges<T>,
423    >;
424
425    /// Storage to check if the solution range is to be adjusted for next era
426    #[pallet::storage]
427    #[pallet::getter(fn should_adjust_solution_range)]
428    pub(super) type ShouldAdjustSolutionRange<T: Config> =
429        StorageValue<_, bool, ValueQuery, T::ShouldAdjustSolutionRange>;
430
431    /// Override solution range during next update
432    #[pallet::storage]
433    pub(super) type NextSolutionRangeOverride<T> = StorageValue<_, SolutionRangeOverride>;
434
435    /// Slot at which current era started.
436    #[pallet::storage]
437    pub(super) type EraStartSlot<T> = StorageValue<_, Slot>;
438
439    /// Mapping from segment index to corresponding segment commitment of contained records.
440    #[pallet::storage]
441    #[pallet::getter(fn segment_commitment)]
442    pub(super) type SegmentCommitment<T> = CountedStorageMap<
443        _,
444        Twox64Concat,
445        SegmentIndex,
446        subspace_core_primitives::segments::SegmentCommitment,
447    >;
448
449    /// Whether the segment headers inherent has been processed in this block (temporary value).
450    ///
451    /// This value is updated to `true` when processing `store_segment_headers` by a node.
452    /// It is then cleared at the end of each block execution in the `on_finalize` hook.
453    #[pallet::storage]
454    pub(super) type DidProcessSegmentHeaders<T: Config> = StorageValue<_, bool, ValueQuery>;
455
456    /// Storage of previous vote verification data, updated on each block during finalization.
457    #[pallet::storage]
458    pub(super) type ParentVoteVerificationData<T> = StorageValue<_, VoteVerificationData>;
459
460    /// Parent block author information.
461    #[pallet::storage]
462    pub(super) type ParentBlockAuthorInfo<T> =
463        StorageValue<_, (PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot)>;
464
465    /// Enable rewards since specified block number.
466    #[pallet::storage]
467    pub(super) type EnableRewards<T: Config> = StorageValue<_, BlockNumberFor<T>>;
468
469    /// Enable rewards when solution range is below this threshold.
470    #[pallet::storage]
471    pub(super) type EnableRewardsBelowSolutionRange<T: Config> = StorageValue<_, u64>;
472
473    /// Block author information
474    #[pallet::storage]
475    pub(super) type CurrentBlockAuthorInfo<T: Config> = StorageValue<
476        _,
477        (
478            PublicKey,
479            SectorIndex,
480            PieceOffset,
481            ScalarBytes,
482            Slot,
483            Option<T::AccountId>,
484        ),
485    >;
486
487    /// Voters in the parent block (set at the end of the block with current values).
488    #[pallet::storage]
489    pub(super) type ParentBlockVoters<T: Config> = StorageValue<
490        _,
491        BTreeMap<
492            (PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot),
493            (Option<T::AccountId>, RewardSignature),
494        >,
495        ValueQuery,
496    >;
497
498    /// Voters in the current block thus far
499    #[pallet::storage]
500    pub(super) type CurrentBlockVoters<T: Config> = StorageValue<
501        _,
502        BTreeMap<
503            (PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot),
504            (Option<T::AccountId>, RewardSignature),
505        >,
506    >;
507
508    /// Number of iterations for proof of time per slot with optional scheduled update
509    #[pallet::storage]
510    pub(super) type PotSlotIterations<T> = StorageValue<_, PotSlotIterationsValue>;
511
512    /// Entropy that needs to be injected into proof of time chain at specific slot associated with
513    /// block number it came from.
514    #[pallet::storage]
515    pub(super) type PotEntropy<T: Config> =
516        StorageValue<_, BTreeMap<BlockNumberFor<T>, PotEntropyValue>, ValueQuery>;
517
518    /// The current block randomness, updated at block initialization. When the proof of time feature
519    /// is enabled it derived from PoT otherwise PoR.
520    #[pallet::storage]
521    pub type BlockRandomness<T> = StorageValue<_, Randomness>;
522
523    /// Allow block authoring by anyone or just root.
524    #[pallet::storage]
525    pub(super) type AllowAuthoringByAnyone<T> = StorageValue<_, bool, ValueQuery>;
526
527    /// Root plot public key.
528    ///
529    /// Set just once to make sure no one else can author blocks until allowed for anyone.
530    #[pallet::storage]
531    #[pallet::getter(fn root_plot_public_key)]
532    pub(super) type RootPlotPublicKey<T> = StorageValue<_, PublicKey>;
533
534    #[pallet::hooks]
535    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
536        fn on_initialize(block_number: BlockNumberFor<T>) -> Weight {
537            Self::do_initialize(block_number);
538            Weight::zero()
539        }
540
541        fn on_finalize(block_number: BlockNumberFor<T>) {
542            Self::do_finalize(block_number)
543        }
544    }
545
546    #[pallet::call]
547    impl<T: Config> Pallet<T> {
548        /// Submit new segment header to the blockchain. This is an inherent extrinsic and part of
549        /// the Subspace consensus logic.
550        #[pallet::call_index(0)]
551        #[pallet::weight((< T as Config >::WeightInfo::store_segment_headers(segment_headers.len() as u32), DispatchClass::Mandatory))]
552        pub fn store_segment_headers(
553            origin: OriginFor<T>,
554            segment_headers: Vec<SegmentHeader>,
555        ) -> DispatchResult {
556            ensure_none(origin)?;
557            Self::do_store_segment_headers(segment_headers)
558        }
559
560        /// Enable solution range adjustment after every era.
561        /// Note: No effect on the solution range for the current era
562        #[pallet::call_index(1)]
563        #[pallet::weight(< T as Config >::WeightInfo::enable_solution_range_adjustment())]
564        pub fn enable_solution_range_adjustment(
565            origin: OriginFor<T>,
566            solution_range_override: Option<u64>,
567            voting_solution_range_override: Option<u64>,
568        ) -> DispatchResult {
569            ensure_root(origin)?;
570
571            Self::do_enable_solution_range_adjustment(
572                solution_range_override,
573                voting_solution_range_override,
574            )?;
575
576            frame_system::Pallet::<T>::deposit_log(
577                DigestItem::enable_solution_range_adjustment_and_override(solution_range_override),
578            );
579
580            Ok(())
581        }
582
583        /// Farmer vote, currently only used for extra rewards to farmers.
584        #[pallet::call_index(2)]
585        #[pallet::weight((< T as Config >::WeightInfo::vote(), DispatchClass::Operational))]
586        // Suppression because the custom syntax will also generate an enum and we need enum to have
587        // boxed value.
588        #[allow(clippy::boxed_local)]
589        pub fn vote(
590            origin: OriginFor<T>,
591            signed_vote: Box<SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>>,
592        ) -> DispatchResult {
593            T::SubspaceOrigin::ensure_origin(origin)?;
594
595            Self::do_vote(*signed_vote)
596        }
597
598        /// Enable rewards for blocks and votes at specified block height.
599        #[pallet::call_index(3)]
600        #[pallet::weight(< T as Config >::WeightInfo::enable_rewards_at())]
601        pub fn enable_rewards_at(
602            origin: OriginFor<T>,
603            enable_rewards_at: EnableRewardsAt<BlockNumberFor<T>>,
604        ) -> DispatchResult {
605            ensure_root(origin)?;
606
607            Self::do_enable_rewards_at(enable_rewards_at)
608        }
609
610        /// Enable storage access for all users.
611        #[pallet::call_index(4)]
612        #[pallet::weight(< T as Config >::WeightInfo::enable_authoring_by_anyone())]
613        pub fn enable_authoring_by_anyone(origin: OriginFor<T>) -> DispatchResult {
614            ensure_root(origin)?;
615
616            AllowAuthoringByAnyone::<T>::put(true);
617            RootPlotPublicKey::<T>::take();
618            // Deposit root plot public key update such that light client can validate blocks later.
619            frame_system::Pallet::<T>::deposit_log(DigestItem::root_plot_public_key_update(None));
620
621            Ok(())
622        }
623
624        /// Update proof of time slot iterations
625        #[pallet::call_index(5)]
626        #[pallet::weight(< T as Config >::WeightInfo::set_pot_slot_iterations())]
627        pub fn set_pot_slot_iterations(
628            origin: OriginFor<T>,
629            slot_iterations: NonZeroU32,
630        ) -> DispatchResult {
631            ensure_root(origin)?;
632
633            if !slot_iterations
634                .get()
635                .is_multiple_of(u32::from(PotCheckpoints::NUM_CHECKPOINTS.get() * 2))
636            {
637                return Err(Error::<T>::NotMultipleOfCheckpoints.into());
638            }
639
640            let mut pot_slot_iterations =
641                PotSlotIterations::<T>::get().expect("Always initialized during genesis; qed");
642
643            if pot_slot_iterations.slot_iterations >= slot_iterations {
644                return Err(Error::<T>::PotSlotIterationsMustIncrease.into());
645            }
646
647            // Can't update if already scheduled since it will cause verification issues
648            if let Some(pot_slot_iterations_update_value) = pot_slot_iterations.update
649                && pot_slot_iterations_update_value.target_slot.is_some()
650            {
651                return Err(Error::<T>::PotSlotIterationsUpdateAlreadyScheduled.into());
652            }
653
654            pot_slot_iterations.update.replace(PotSlotIterationsUpdate {
655                // Slot will be known later when next entropy injection takes place
656                target_slot: None,
657                slot_iterations,
658            });
659
660            PotSlotIterations::<T>::put(pot_slot_iterations);
661
662            Ok(())
663        }
664    }
665
666    #[pallet::inherent]
667    impl<T: Config> ProvideInherent for Pallet<T> {
668        type Call = Call<T>;
669        type Error = InherentError;
670        const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
671
672        fn create_inherent(data: &InherentData) -> Option<Self::Call> {
673            let inherent_data = data
674                .get_data::<InherentType>(&INHERENT_IDENTIFIER)
675                .expect("Subspace inherent data not correctly encoded")
676                .expect("Subspace inherent data must be provided");
677
678            let segment_headers = inherent_data.segment_headers;
679            if segment_headers.is_empty() {
680                None
681            } else {
682                Some(Call::store_segment_headers { segment_headers })
683            }
684        }
685
686        fn is_inherent_required(data: &InherentData) -> Result<Option<Self::Error>, Self::Error> {
687            let inherent_data = data
688                .get_data::<InherentType>(&INHERENT_IDENTIFIER)
689                .expect("Subspace inherent data not correctly encoded")
690                .expect("Subspace inherent data must be provided");
691
692            Ok(if inherent_data.segment_headers.is_empty() {
693                None
694            } else {
695                Some(InherentError::MissingSegmentHeadersList)
696            })
697        }
698
699        fn check_inherent(call: &Self::Call, data: &InherentData) -> Result<(), Self::Error> {
700            if let Call::store_segment_headers { segment_headers } = call {
701                let inherent_data = data
702                    .get_data::<InherentType>(&INHERENT_IDENTIFIER)
703                    .expect("Subspace inherent data not correctly encoded")
704                    .expect("Subspace inherent data must be provided");
705
706                if segment_headers != &inherent_data.segment_headers {
707                    return Err(InherentError::IncorrectSegmentHeadersList {
708                        expected: inherent_data.segment_headers,
709                        actual: segment_headers.clone(),
710                    });
711                }
712            }
713
714            Ok(())
715        }
716
717        fn is_inherent(call: &Self::Call) -> bool {
718            matches!(call, Call::store_segment_headers { .. })
719        }
720    }
721
722    // Must stay exactly this form: frame-support-procedural keys on it to suppress its deprecation shim.
723    #[allow(deprecated)]
724    #[pallet::validate_unsigned]
725    impl<T: Config> ValidateUnsigned for Pallet<T> {
726        type Call = Call<T>;
727        fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
728            match call {
729                Call::store_segment_headers { segment_headers } => {
730                    Self::validate_segment_header(source, segment_headers)
731                }
732                _ => InvalidTransaction::Call.into(),
733            }
734        }
735
736        fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
737            match call {
738                Call::store_segment_headers { segment_headers } => {
739                    Self::pre_dispatch_segment_header(segment_headers)
740                }
741                _ => Err(InvalidTransaction::Call.into()),
742            }
743        }
744    }
745}
746
747impl<T: Config> Pallet<T> {
748    /// Total number of pieces in the blockchain
749    pub fn history_size() -> HistorySize {
750        // Chain starts with one segment plotted, even if it is not recorded in the runtime yet
751        let number_of_segments = u64::from(SegmentCommitment::<T>::count()).max(1);
752        HistorySize::from(NonZeroU64::new(number_of_segments).expect("Not zero; qed"))
753    }
754
755    /// Determine whether an era change should take place at this block.
756    /// Assumes that initialization has already taken place.
757    fn should_era_change(block_number: BlockNumberFor<T>) -> bool {
758        block_number % T::EraDuration::get() == Zero::zero()
759    }
760
761    /// DANGEROUS: Enact era change. Should be done on every block where `should_era_change` has
762    /// returned `true`, and the caller is the only caller of this function.
763    ///
764    /// This will update solution range used in consensus.
765    fn enact_era_change() {
766        let slot_probability = T::SlotProbability::get();
767
768        let current_slot = Self::current_slot();
769
770        SolutionRanges::<T>::mutate(|solution_ranges| {
771            let next_solution_range;
772            let next_voting_solution_range;
773            // Check if the solution range should be adjusted for next era.
774            if !ShouldAdjustSolutionRange::<T>::get() {
775                next_solution_range = solution_ranges.current;
776                next_voting_solution_range = solution_ranges.current;
777            } else if let Some(solution_range_override) = NextSolutionRangeOverride::<T>::take() {
778                next_solution_range = solution_range_override.solution_range;
779                next_voting_solution_range = solution_range_override.voting_solution_range;
780            } else {
781                next_solution_range = derive_next_solution_range(
782                    // If Era start slot is not found it means we have just finished the first era
783                    u64::from(EraStartSlot::<T>::get().unwrap_or_default()),
784                    u64::from(current_slot),
785                    slot_probability,
786                    solution_ranges.current,
787                    T::EraDuration::get()
788                        .try_into()
789                        .unwrap_or_else(|_| panic!("Era duration is always within u64; qed")),
790                );
791
792                next_voting_solution_range = next_solution_range
793                    .saturating_mul(u64::from(T::ExpectedVotesPerBlock::get()) + 1);
794            };
795            solution_ranges.next.replace(next_solution_range);
796            solution_ranges
797                .voting_next
798                .replace(next_voting_solution_range);
799
800            if let Some(solution_range_for_rewards) = EnableRewardsBelowSolutionRange::<T>::get()
801                && next_solution_range <= solution_range_for_rewards
802            {
803                EnableRewardsBelowSolutionRange::<T>::take();
804
805                let next_block_number =
806                    frame_system::Pallet::<T>::current_block_number() + One::one();
807                EnableRewards::<T>::put(next_block_number);
808            }
809        });
810
811        EraStartSlot::<T>::put(current_slot);
812    }
813
814    fn do_initialize(block_number: BlockNumberFor<T>) {
815        let pre_digest = frame_system::Pallet::<T>::digest()
816            .logs
817            .iter()
818            .find_map(|s| s.as_subspace_pre_digest::<T::AccountId>())
819            .expect("Block must always have pre-digest");
820        let current_slot = pre_digest.slot();
821
822        BlockSlots::<T>::mutate(|block_slots| {
823            if let Some(to_remove) = block_number.checked_sub(&T::BlockSlotCount::get().into()) {
824                block_slots.remove(&to_remove);
825            }
826            block_slots
827                .try_insert(block_number, current_slot)
828                .expect("one entry just removed before inserting; qed");
829        });
830
831        {
832            // Remove old value
833            CurrentBlockAuthorInfo::<T>::take();
834            let farmer_public_key = pre_digest.solution().public_key;
835
836            // Optional restriction for block authoring to the root user
837            if !AllowAuthoringByAnyone::<T>::get() {
838                RootPlotPublicKey::<T>::mutate(|maybe_root_plot_public_key| {
839                    if let Some(root_plot_public_key) = maybe_root_plot_public_key {
840                        if root_plot_public_key != &farmer_public_key {
841                            panic!("Client bug, authoring must be only done by the root user");
842                        }
843                    } else {
844                        maybe_root_plot_public_key.replace(farmer_public_key);
845                        // Deposit root plot public key update such that light client can validate
846                        // blocks later.
847                        frame_system::Pallet::<T>::deposit_log(
848                            DigestItem::root_plot_public_key_update(Some(farmer_public_key)),
849                        );
850                    }
851                });
852            }
853
854            let key = (
855                farmer_public_key,
856                pre_digest.solution().sector_index,
857                pre_digest.solution().piece_offset,
858                pre_digest.solution().chunk,
859                current_slot,
860            );
861            if !ParentBlockVoters::<T>::get().contains_key(&key) {
862                let (public_key, sector_index, piece_offset, chunk, slot) = key;
863
864                CurrentBlockAuthorInfo::<T>::put((
865                    public_key,
866                    sector_index,
867                    piece_offset,
868                    chunk,
869                    slot,
870                    Some(pre_digest.solution().reward_address.clone()),
871                ));
872            }
873        }
874        CurrentBlockVoters::<T>::put(BTreeMap::<
875            (PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot),
876            (Option<T::AccountId>, RewardSignature),
877        >::default());
878
879        // If solution range was updated in previous block, set it as current.
880        if let sp_consensus_subspace::SolutionRanges {
881            next: Some(next),
882            voting_next: Some(voting_next),
883            ..
884        } = SolutionRanges::<T>::get()
885        {
886            SolutionRanges::<T>::put(sp_consensus_subspace::SolutionRanges {
887                current: next,
888                next: None,
889                voting_current: voting_next,
890                voting_next: None,
891            });
892        }
893
894        let block_randomness = pre_digest
895            .pot_info()
896            .proof_of_time()
897            .derive_global_randomness();
898
899        // Update the block randomness.
900        BlockRandomness::<T>::put(block_randomness);
901
902        // Deposit solution range data such that light client can validate blocks later.
903        frame_system::Pallet::<T>::deposit_log(DigestItem::solution_range(
904            SolutionRanges::<T>::get().current,
905        ));
906
907        // Enact era change, if necessary.
908        T::EraChangeTrigger::trigger::<T>(block_number);
909
910        {
911            let mut pot_slot_iterations =
912                PotSlotIterations::<T>::get().expect("Always initialized during genesis; qed");
913            // This is what we had after previous block
914            frame_system::Pallet::<T>::deposit_log(DigestItem::pot_slot_iterations(
915                pot_slot_iterations.slot_iterations,
916            ));
917
918            // Check PoT slot iterations update and apply it if it is time to do so, while also
919            // removing corresponding storage item
920            if let Some(update) = pot_slot_iterations.update
921                && let Some(target_slot) = update.target_slot
922                && target_slot <= current_slot
923            {
924                debug!(
925                    "Applying PoT slots update, changing to {} at block #{:?}",
926                    update.slot_iterations, block_number
927                );
928                pot_slot_iterations = PotSlotIterationsValue {
929                    slot_iterations: update.slot_iterations,
930                    update: None,
931                };
932                PotSlotIterations::<T>::put(pot_slot_iterations);
933            }
934            let pot_entropy_injection_interval = T::PotEntropyInjectionInterval::get();
935            let pot_entropy_injection_delay = T::PotEntropyInjectionDelay::get();
936
937            let mut entropy = PotEntropy::<T>::get();
938            let lookback_in_blocks = pot_entropy_injection_interval
939                * BlockNumberFor::<T>::from(T::PotEntropyInjectionLookbackDepth::get());
940            let last_entropy_injection_block =
941                block_number / pot_entropy_injection_interval * pot_entropy_injection_interval;
942            let maybe_entropy_source_block_number =
943                last_entropy_injection_block.checked_sub(&lookback_in_blocks);
944
945            if (block_number % pot_entropy_injection_interval).is_zero() {
946                let current_block_entropy = derive_pot_entropy(
947                    &pre_digest.solution().chunk,
948                    pre_digest.pot_info().proof_of_time(),
949                );
950                // Collect entropy every `T::PotEntropyInjectionInterval` blocks
951                entropy.insert(
952                    block_number,
953                    PotEntropyValue {
954                        target_slot: None,
955                        entropy: current_block_entropy,
956                    },
957                );
958
959                // Update target slot for entropy injection once we know it
960                if let Some(entropy_source_block_number) = maybe_entropy_source_block_number
961                    && let Some(entropy_value) = entropy.get_mut(&entropy_source_block_number)
962                {
963                    let target_slot = pre_digest
964                        .slot()
965                        .saturating_add(pot_entropy_injection_delay);
966                    debug!("Pot entropy injection will happen at slot {target_slot:?}",);
967                    entropy_value.target_slot.replace(target_slot);
968
969                    // Schedule PoT slot iterations update at the same slot as entropy
970                    if let Some(update) = &mut pot_slot_iterations.update
971                        && update.target_slot.is_none()
972                    {
973                        debug!("Scheduling PoT slots update to happen at slot {target_slot:?}");
974                        update.target_slot.replace(target_slot);
975                        PotSlotIterations::<T>::put(pot_slot_iterations);
976                    }
977                }
978
979                PotEntropy::<T>::put(entropy.clone());
980            }
981
982            // Deposit consensus log item with parameters change in case corresponding entropy is
983            // available
984            if let Some(entropy_source_block_number) = maybe_entropy_source_block_number {
985                let maybe_entropy_value = entropy.get(&entropy_source_block_number).copied();
986                if let Some(PotEntropyValue {
987                    target_slot,
988                    entropy,
989                }) = maybe_entropy_value
990                {
991                    let target_slot = target_slot
992                        .expect("Target slot is guaranteed to be present due to logic above; qed");
993                    // Check if there was a PoT slot iterations update at the same exact slot
994                    let slot_iterations = if let Some(update) = pot_slot_iterations.update
995                        && let Some(update_target_slot) = update.target_slot
996                        && update_target_slot == target_slot
997                    {
998                        debug!("Applying PoT slots update to the next PoT parameters change");
999                        update.slot_iterations
1000                    } else {
1001                        pot_slot_iterations.slot_iterations
1002                    };
1003
1004                    frame_system::Pallet::<T>::deposit_log(DigestItem::pot_parameters_change(
1005                        PotParametersChange {
1006                            slot: target_slot,
1007                            slot_iterations,
1008                            entropy,
1009                        },
1010                    ));
1011                }
1012            }
1013
1014            // Clean up old values we'll no longer need
1015            if let Some(entry) = entropy.first_entry()
1016                && let Some(target_slot) = entry.get().target_slot
1017                && target_slot < current_slot
1018            {
1019                entry.remove();
1020                PotEntropy::<T>::put(entropy);
1021            }
1022        }
1023    }
1024
1025    fn do_finalize(_block_number: BlockNumberFor<T>) {
1026        // Deposit the next solution range in the block finalization to account for solution range override extrinsic and
1027        // era change happens in the same block.
1028        if let Some(next_solution_range) = SolutionRanges::<T>::get().next {
1029            // Deposit next solution range data such that light client can validate blocks later.
1030            frame_system::Pallet::<T>::deposit_log(DigestItem::next_solution_range(
1031                next_solution_range,
1032            ));
1033        }
1034
1035        if let Some((public_key, sector_index, piece_offset, scalar, slot, _reward_address)) =
1036            CurrentBlockAuthorInfo::<T>::get()
1037        {
1038            ParentBlockAuthorInfo::<T>::put((public_key, sector_index, piece_offset, scalar, slot));
1039        } else {
1040            ParentBlockAuthorInfo::<T>::take();
1041        }
1042
1043        ParentVoteVerificationData::<T>::put(current_vote_verification_data::<T>(true));
1044
1045        ParentBlockVoters::<T>::put(CurrentBlockVoters::<T>::get().unwrap_or_default());
1046
1047        DidProcessSegmentHeaders::<T>::take();
1048    }
1049
1050    fn do_store_segment_headers(segment_headers: Vec<SegmentHeader>) -> DispatchResult {
1051        assert!(
1052            !DidProcessSegmentHeaders::<T>::exists(),
1053            "Segment headers must be updated only once in the block"
1054        );
1055
1056        for segment_header in segment_headers {
1057            SegmentCommitment::<T>::insert(
1058                segment_header.segment_index(),
1059                segment_header.segment_commitment(),
1060            );
1061            // Deposit global randomness data such that light client can validate blocks later.
1062            frame_system::Pallet::<T>::deposit_log(DigestItem::segment_commitment(
1063                segment_header.segment_index(),
1064                segment_header.segment_commitment(),
1065            ));
1066            Self::deposit_event(Event::SegmentHeaderStored { segment_header });
1067        }
1068
1069        DidProcessSegmentHeaders::<T>::put(true);
1070        Ok(())
1071    }
1072
1073    fn do_enable_solution_range_adjustment(
1074        solution_range_override: Option<u64>,
1075        voting_solution_range_override: Option<u64>,
1076    ) -> DispatchResult {
1077        if ShouldAdjustSolutionRange::<T>::get() {
1078            return Err(Error::<T>::SolutionRangeAdjustmentAlreadyEnabled.into());
1079        }
1080
1081        ShouldAdjustSolutionRange::<T>::put(true);
1082
1083        if let Some(solution_range) = solution_range_override {
1084            let voting_solution_range = voting_solution_range_override.unwrap_or_else(|| {
1085                solution_range.saturating_mul(u64::from(T::ExpectedVotesPerBlock::get()) + 1)
1086            });
1087            SolutionRanges::<T>::mutate(|solution_ranges| {
1088                // If solution range update is already scheduled, just update values
1089                if solution_ranges.next.is_some() {
1090                    solution_ranges.next.replace(solution_range);
1091                    solution_ranges.voting_next.replace(voting_solution_range);
1092                } else {
1093                    solution_ranges.current = solution_range;
1094                    solution_ranges.voting_current = voting_solution_range;
1095
1096                    // Solution range can re-adjust very soon, make sure next re-adjustment is
1097                    // also overridden
1098                    NextSolutionRangeOverride::<T>::put(SolutionRangeOverride {
1099                        solution_range,
1100                        voting_solution_range,
1101                    });
1102                    frame_system::Pallet::<T>::deposit_log(DigestItem::next_solution_range(
1103                        solution_range,
1104                    ));
1105                }
1106            });
1107        }
1108
1109        Ok(())
1110    }
1111
1112    fn do_vote(
1113        signed_vote: SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>,
1114    ) -> DispatchResult {
1115        let Vote::V0 {
1116            height,
1117            parent_hash,
1118            solution,
1119            ..
1120        } = signed_vote.vote;
1121
1122        Self::deposit_event(Event::FarmerVote {
1123            public_key: solution.public_key,
1124            reward_address: solution.reward_address,
1125            height,
1126            parent_hash,
1127        });
1128
1129        Ok(())
1130    }
1131
1132    fn do_enable_rewards_at(
1133        enable_rewards_at: EnableRewardsAt<BlockNumberFor<T>>,
1134    ) -> DispatchResult {
1135        match enable_rewards_at {
1136            EnableRewardsAt::Height(block_number) => {
1137                // Enable rewards at a particular block height (default to the next block after
1138                // this)
1139                let next_block_number =
1140                    frame_system::Pallet::<T>::current_block_number() + One::one();
1141                EnableRewards::<T>::put(block_number.max(next_block_number));
1142            }
1143            EnableRewardsAt::SolutionRange(solution_range) => {
1144                EnableRewardsBelowSolutionRange::<T>::put(solution_range);
1145            }
1146            EnableRewardsAt::Manually => {
1147                // Nothing to do in this case
1148            }
1149        }
1150
1151        Ok(())
1152    }
1153
1154    /// Proof of time parameters
1155    pub fn pot_parameters() -> PotParameters {
1156        let block_number = frame_system::Pallet::<T>::block_number();
1157        let pot_slot_iterations =
1158            PotSlotIterations::<T>::get().expect("Always initialized during genesis; qed");
1159        let pot_entropy_injection_interval = T::PotEntropyInjectionInterval::get();
1160
1161        let entropy = PotEntropy::<T>::get();
1162        let lookback_in_blocks = pot_entropy_injection_interval
1163            * BlockNumberFor::<T>::from(T::PotEntropyInjectionLookbackDepth::get());
1164        let last_entropy_injection_block =
1165            block_number / pot_entropy_injection_interval * pot_entropy_injection_interval;
1166        let maybe_entropy_source_block_number =
1167            last_entropy_injection_block.checked_sub(&lookback_in_blocks);
1168
1169        let mut next_change = None;
1170
1171        if let Some(entropy_source_block_number) = maybe_entropy_source_block_number {
1172            let maybe_entropy_value = entropy.get(&entropy_source_block_number).copied();
1173            if let Some(PotEntropyValue {
1174                target_slot,
1175                entropy,
1176            }) = maybe_entropy_value
1177            {
1178                let target_slot = target_slot.expect(
1179                    "Always present due to identical check present in block initialization; qed",
1180                );
1181                // Check if there was a PoT slot iterations update at the same exact slot
1182                let slot_iterations = if let Some(update) = pot_slot_iterations.update
1183                    && let Some(update_target_slot) = update.target_slot
1184                    && update_target_slot == target_slot
1185                {
1186                    update.slot_iterations
1187                } else {
1188                    pot_slot_iterations.slot_iterations
1189                };
1190
1191                next_change.replace(PotParametersChange {
1192                    slot: target_slot,
1193                    slot_iterations,
1194                    entropy,
1195                });
1196            }
1197        }
1198
1199        PotParameters::V0 {
1200            slot_iterations: pot_slot_iterations.slot_iterations,
1201            next_change,
1202        }
1203    }
1204
1205    /// Current slot number
1206    pub fn current_slot() -> Slot {
1207        BlockSlots::<T>::get()
1208            .last_key_value()
1209            .map(|(_block, slot)| *slot)
1210            .unwrap_or_default()
1211    }
1212
1213    /// Size of the archived history of the blockchain in bytes
1214    pub fn archived_history_size() -> u64 {
1215        let archived_segments = SegmentCommitment::<T>::count();
1216
1217        u64::from(archived_segments) * ArchivedHistorySegment::SIZE as u64
1218    }
1219}
1220
1221impl<T> Pallet<T>
1222where
1223    T: Config + CreateUnsigned<Call<T>>,
1224{
1225    /// Submit farmer vote that is essentially a header with bigger solution range than
1226    /// acceptable for block authoring.
1227    pub fn submit_vote(signed_vote: SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>) {
1228        let call = Call::vote {
1229            signed_vote: Box::new(signed_vote),
1230        };
1231
1232        let ext = T::create_unsigned(call.into());
1233        match SubmitTransaction::<T, Call<T>>::submit_transaction(ext) {
1234            Ok(()) => {
1235                debug!("Submitted Subspace vote");
1236            }
1237            Err(()) => {
1238                error!("Error submitting Subspace vote");
1239            }
1240        }
1241    }
1242}
1243
1244/// Methods for the `ValidateUnsigned` implementation:
1245/// It restricts calls to `store_segment_header` to local calls (i.e. extrinsics generated on this
1246/// node) or that already in a block. This guarantees that only block authors can include root
1247/// blocks.
1248impl<T: Config> Pallet<T> {
1249    fn validate_segment_header(
1250        source: TransactionSource,
1251        segment_headers: &[SegmentHeader],
1252    ) -> TransactionValidity {
1253        // Discard segment header not coming from the local node
1254        if !matches!(
1255            source,
1256            TransactionSource::Local | TransactionSource::InBlock,
1257        ) {
1258            warn!("Rejecting segment header extrinsic because it is not local/in-block.",);
1259
1260            return InvalidTransaction::Call.into();
1261        }
1262
1263        check_segment_headers::<T>(segment_headers)?;
1264
1265        ValidTransaction::with_tag_prefix("SubspaceSegmentHeader")
1266            // We assign the maximum priority for any segment header.
1267            .priority(TransactionPriority::MAX)
1268            // Should be included immediately into the current block (this is an inherent
1269            // extrinsic) with no exceptions.
1270            .longevity(0)
1271            // We don't propagate this. This can never be included on a remote node.
1272            .propagate(false)
1273            .build()
1274    }
1275
1276    fn pre_dispatch_segment_header(
1277        segment_headers: &[SegmentHeader],
1278    ) -> Result<(), TransactionValidityError> {
1279        check_segment_headers::<T>(segment_headers)
1280    }
1281
1282    fn validate_vote(
1283        signed_vote: &SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>,
1284    ) -> Result<(ValidTransaction, Weight), TransactionValidityError> {
1285        check_vote::<T>(signed_vote, false)?;
1286
1287        ValidTransaction::with_tag_prefix("SubspaceVote")
1288            // We assign the maximum priority for any vote.
1289            .priority(TransactionPriority::MAX)
1290            // Should be included in the next block or block after that, but not later
1291            .longevity(2)
1292            .and_provides(signed_vote.signature)
1293            .build()
1294            .map(|validity| (validity, T::ExtensionWeightInfo::vote()))
1295    }
1296
1297    fn pre_dispatch_vote(
1298        signed_vote: &SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>,
1299    ) -> Result<Weight, TransactionValidityError> {
1300        match check_vote::<T>(signed_vote, true) {
1301            Ok(()) => Ok(T::ExtensionWeightInfo::vote()),
1302            Err(CheckVoteError::Equivocated { .. }) => {
1303                // Return Ok such that changes from this pre-dispatch are persisted
1304                Ok(T::ExtensionWeightInfo::vote_with_equivocation())
1305            }
1306            Err(error) => Err(error.into()),
1307        }
1308    }
1309}
1310
1311/// Verification data retrieval depends on whether it is called from pre_dispatch (meaning block
1312/// initialization has already happened) or from `validate_unsigned` by transaction pool (meaning
1313/// block initialization didn't happen yet).
1314fn current_vote_verification_data<T: Config>(is_block_initialized: bool) -> VoteVerificationData {
1315    let solution_ranges = SolutionRanges::<T>::get();
1316
1317    VoteVerificationData {
1318        solution_range: if is_block_initialized {
1319            solution_ranges.current
1320        } else {
1321            solution_ranges.next.unwrap_or(solution_ranges.current)
1322        },
1323        vote_solution_range: if is_block_initialized {
1324            solution_ranges.voting_current
1325        } else {
1326            solution_ranges
1327                .voting_next
1328                .unwrap_or(solution_ranges.voting_current)
1329        },
1330        current_slot: Pallet::<T>::current_slot(),
1331        parent_slot: ParentVoteVerificationData::<T>::get()
1332            .map(|parent_vote_verification_data| {
1333                if is_block_initialized {
1334                    parent_vote_verification_data.current_slot
1335                } else {
1336                    parent_vote_verification_data.parent_slot
1337                }
1338            })
1339            .unwrap_or_else(Pallet::<T>::current_slot),
1340    }
1341}
1342
1343#[derive(Debug, Eq, PartialEq)]
1344enum CheckVoteError {
1345    UnexpectedBeforeHeightTwo,
1346    HeightInTheFuture,
1347    HeightInThePast,
1348    IncorrectParentHash,
1349    SlotInTheFuture,
1350    SlotInThePast,
1351    BadRewardSignature(SignatureError),
1352    UnknownSegmentCommitment,
1353    InvalidHistorySize,
1354    InvalidSolution(String),
1355    QualityTooHigh,
1356    InvalidProofOfTime,
1357    InvalidFutureProofOfTime,
1358    DuplicateVote,
1359    Equivocated { slot: Slot, offender: PublicKey },
1360}
1361
1362impl From<CheckVoteError> for TransactionValidityError {
1363    #[inline]
1364    fn from(error: CheckVoteError) -> Self {
1365        TransactionValidityError::Invalid(match error {
1366            CheckVoteError::UnexpectedBeforeHeightTwo => InvalidTransaction::Call,
1367            CheckVoteError::HeightInTheFuture => InvalidTransaction::Future,
1368            CheckVoteError::HeightInThePast => InvalidTransaction::Stale,
1369            CheckVoteError::IncorrectParentHash => InvalidTransaction::Call,
1370            CheckVoteError::SlotInTheFuture => InvalidTransaction::Future,
1371            CheckVoteError::SlotInThePast => InvalidTransaction::Stale,
1372            CheckVoteError::BadRewardSignature(_) => InvalidTransaction::BadProof,
1373            CheckVoteError::UnknownSegmentCommitment => InvalidTransaction::Call,
1374            CheckVoteError::InvalidHistorySize => InvalidTransaction::Call,
1375            CheckVoteError::InvalidSolution(_) => InvalidTransaction::Call,
1376            CheckVoteError::QualityTooHigh => InvalidTransaction::Call,
1377            CheckVoteError::InvalidProofOfTime => InvalidTransaction::Future,
1378            CheckVoteError::InvalidFutureProofOfTime => InvalidTransaction::Call,
1379            CheckVoteError::DuplicateVote => InvalidTransaction::Call,
1380            CheckVoteError::Equivocated { .. } => InvalidTransaction::BadSigner,
1381        })
1382    }
1383}
1384
1385fn check_vote<T: Config>(
1386    signed_vote: &SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>,
1387    pre_dispatch: bool,
1388) -> Result<(), CheckVoteError> {
1389    let Vote::V0 {
1390        height,
1391        parent_hash,
1392        slot,
1393        solution,
1394        proof_of_time,
1395        future_proof_of_time,
1396    } = &signed_vote.vote;
1397    let height = *height;
1398    let slot = *slot;
1399
1400    let current_block_number = frame_system::Pallet::<T>::current_block_number();
1401
1402    if current_block_number <= One::one() || height <= One::one() {
1403        debug!("Votes are not expected at height below 2");
1404
1405        return Err(CheckVoteError::UnexpectedBeforeHeightTwo);
1406    }
1407
1408    // Height must be either the same as in current block or smaller by one.
1409    //
1410    // Subtraction will not panic due to check above.
1411    if !(height == current_block_number || height == current_block_number - One::one()) {
1412        debug!(
1413            "Vote verification error: bad height {height:?}, current block number is \
1414            {current_block_number:?}"
1415        );
1416        return Err(if height > current_block_number {
1417            CheckVoteError::HeightInTheFuture
1418        } else {
1419            CheckVoteError::HeightInThePast
1420        });
1421    }
1422
1423    // Should have parent hash from -1 (parent hash of current block) or -2 (block before that)
1424    //
1425    // Subtraction will not panic due to check above.
1426    if *parent_hash != frame_system::Pallet::<T>::block_hash(height - One::one()) {
1427        debug!("Vote verification error: parent hash {parent_hash:?}",);
1428        return Err(CheckVoteError::IncorrectParentHash);
1429    }
1430
1431    let current_vote_verification_data = current_vote_verification_data::<T>(pre_dispatch);
1432    let parent_vote_verification_data = ParentVoteVerificationData::<T>::get()
1433        .expect("Above check for block number ensures that this value is always present; qed");
1434
1435    if pre_dispatch {
1436        // New time slot is already set, whatever time slot is in the vote it must be smaller or the
1437        // same (for votes produced locally)
1438        let current_slot = current_vote_verification_data.current_slot;
1439        if slot > current_slot || (slot == current_slot && height != current_block_number) {
1440            debug!("Vote slot {slot:?} must be before current slot {current_slot:?}",);
1441            return Err(CheckVoteError::SlotInTheFuture);
1442        }
1443    }
1444
1445    let parent_slot = if pre_dispatch {
1446        // For pre-dispatch parent slot is `current_slot` in the parent vote verification data (it
1447        // was updated in current block because initialization hook was already called) if vote is
1448        // at the same height as the current block, otherwise it is one level older and
1449        // `parent_slot` from parent vote verification data needs to be taken instead
1450        if height == current_block_number {
1451            parent_vote_verification_data.current_slot
1452        } else {
1453            parent_vote_verification_data.parent_slot
1454        }
1455    } else {
1456        // Otherwise parent slot is `current_slot` in the current vote verification data (that
1457        // wasn't updated from parent block because initialization hook wasn't called yet) if vote
1458        // is at the same height as the current block, otherwise it is one level older and
1459        // `parent_slot` from current vote verification data needs to be taken instead
1460        if height == current_block_number {
1461            current_vote_verification_data.current_slot
1462        } else {
1463            current_vote_verification_data.parent_slot
1464        }
1465    };
1466
1467    if slot <= parent_slot {
1468        debug!("Vote slot {slot:?} must be after parent slot {parent_slot:?}",);
1469        return Err(CheckVoteError::SlotInThePast);
1470    }
1471
1472    if let Err(error) = check_reward_signature(
1473        signed_vote.vote.hash().as_bytes(),
1474        &signed_vote.signature,
1475        &solution.public_key,
1476        &schnorrkel::signing_context(REWARD_SIGNING_CONTEXT),
1477    ) {
1478        debug!("Vote verification error: {error:?}");
1479        return Err(CheckVoteError::BadRewardSignature(error));
1480    }
1481
1482    let vote_verification_data = if height == current_block_number {
1483        current_vote_verification_data
1484    } else {
1485        parent_vote_verification_data
1486    };
1487
1488    let sector_id = SectorId::new(
1489        solution.public_key.hash(),
1490        solution.sector_index,
1491        solution.history_size,
1492    );
1493
1494    let recent_segments = T::RecentSegments::get();
1495    let recent_history_fraction = (
1496        T::RecentHistoryFraction::get().0,
1497        T::RecentHistoryFraction::get().1,
1498    );
1499    let segment_index = sector_id
1500        .derive_piece_index(
1501            solution.piece_offset,
1502            solution.history_size,
1503            T::MaxPiecesInSector::get(),
1504            recent_segments,
1505            recent_history_fraction,
1506        )
1507        .segment_index();
1508
1509    let segment_commitment = if let Some(segment_commitment) =
1510        Pallet::<T>::segment_commitment(segment_index)
1511    {
1512        segment_commitment
1513    } else {
1514        debug!("Vote verification error: no segment commitment for segment index {segment_index}");
1515        return Err(CheckVoteError::UnknownSegmentCommitment);
1516    };
1517
1518    let sector_expiration_check_segment_commitment = Pallet::<T>::segment_commitment(
1519        solution
1520            .history_size
1521            .sector_expiration_check(T::MinSectorLifetime::get())
1522            .ok_or(CheckVoteError::InvalidHistorySize)?
1523            .segment_index(),
1524    );
1525
1526    match verify_solution(
1527        solution.into(),
1528        slot.into(),
1529        (&VerifySolutionParams {
1530            proof_of_time: *proof_of_time,
1531            solution_range: vote_verification_data.vote_solution_range,
1532            piece_check_params: Some(PieceCheckParams {
1533                max_pieces_in_sector: T::MaxPiecesInSector::get(),
1534                segment_commitment,
1535                recent_segments,
1536                recent_history_fraction,
1537                min_sector_lifetime: T::MinSectorLifetime::get(),
1538                current_history_size: Pallet::<T>::history_size(),
1539                sector_expiration_check_segment_commitment,
1540            }),
1541        })
1542            .into(),
1543    ) {
1544        Ok(solution_distance) => {
1545            if solution_distance <= vote_verification_data.solution_range / 2 {
1546                debug!("Vote quality is too high");
1547                return Err(CheckVoteError::QualityTooHigh);
1548            }
1549        }
1550        Err(error) => {
1551            debug!("Vote verification error: {error:?}");
1552            return Err(CheckVoteError::InvalidSolution(error));
1553        }
1554    }
1555
1556    // Cheap proof of time verification is possible here because proof of time must have already
1557    // been seen by this node due to votes requiring the same authoring delay as blocks
1558    if !is_proof_of_time_valid(
1559        BlockHash::try_from(parent_hash.as_ref())
1560            .expect("Must be able to convert to block hash type"),
1561        SlotNumber::from(slot),
1562        WrappedPotOutput::from(*proof_of_time),
1563        // Quick verification when entering transaction pool, but not when constructing the block
1564        !pre_dispatch,
1565    ) {
1566        debug!("Invalid proof of time");
1567
1568        return Err(CheckVoteError::InvalidProofOfTime);
1569    }
1570
1571    // During pre-dispatch we have already verified proofs of time up to future proof of time of
1572    // current block, which vote can't exceed, this must be possible to verify cheaply
1573    if pre_dispatch
1574        && !is_proof_of_time_valid(
1575            BlockHash::try_from(parent_hash.as_ref())
1576                .expect("Must be able to convert to block hash type"),
1577            SlotNumber::from(slot + T::BlockAuthoringDelay::get()),
1578            WrappedPotOutput::from(*future_proof_of_time),
1579            false,
1580        )
1581    {
1582        debug!("Invalid future proof of time");
1583
1584        return Err(CheckVoteError::InvalidFutureProofOfTime);
1585    }
1586
1587    let key = (
1588        solution.public_key,
1589        solution.sector_index,
1590        solution.piece_offset,
1591        solution.chunk,
1592        slot,
1593    );
1594    // Check that farmer didn't use solution from this vote yet in:
1595    // * parent block
1596    // * current block
1597    // * parent block vote
1598    // * current block vote
1599    let mut is_equivocating = ParentBlockAuthorInfo::<T>::get().as_ref() == Some(&key)
1600        || CurrentBlockAuthorInfo::<T>::get()
1601            .map(
1602                |(public_key, sector_index, piece_offset, chunk, slot, _reward_address)| {
1603                    (public_key, sector_index, piece_offset, chunk, slot)
1604                },
1605            )
1606            .as_ref()
1607            == Some(&key);
1608
1609    if !is_equivocating
1610        && let Some((_reward_address, signature)) = ParentBlockVoters::<T>::get().get(&key)
1611    {
1612        if signature != &signed_vote.signature {
1613            is_equivocating = true;
1614        } else {
1615            // The same vote should never be included more than once
1616            return Err(CheckVoteError::DuplicateVote);
1617        }
1618    }
1619
1620    if !is_equivocating
1621        && let Some((_reward_address, signature)) =
1622            CurrentBlockVoters::<T>::get().unwrap_or_default().get(&key)
1623    {
1624        if signature != &signed_vote.signature {
1625            is_equivocating = true;
1626        } else {
1627            // The same vote should never be included more than once
1628            return Err(CheckVoteError::DuplicateVote);
1629        }
1630    }
1631
1632    if pre_dispatch {
1633        // During `pre_dispatch` call put farmer into the list of reward receivers.
1634        CurrentBlockVoters::<T>::mutate(|current_reward_receivers| {
1635            current_reward_receivers
1636                .as_mut()
1637                .expect("Always set during block initialization")
1638                .insert(
1639                    key,
1640                    (
1641                        if is_equivocating {
1642                            None
1643                        } else {
1644                            Some(solution.reward_address.clone())
1645                        },
1646                        signed_vote.signature,
1647                    ),
1648                );
1649        });
1650    }
1651
1652    if is_equivocating {
1653        let offender = solution.public_key;
1654
1655        CurrentBlockAuthorInfo::<T>::mutate(|maybe_info| {
1656            if let Some((public_key, _sector_index, _piece_offset, _chunk, _slot, reward_address)) =
1657                maybe_info
1658                && public_key == &offender
1659            {
1660                // Revoke reward for block author
1661                reward_address.take();
1662            }
1663        });
1664
1665        CurrentBlockVoters::<T>::mutate(|current_reward_receivers| {
1666            if let Some(current_reward_receivers) = current_reward_receivers {
1667                for (
1668                    (public_key, _sector_index, _piece_offset, _chunk, _slot),
1669                    (reward_address, _signature),
1670                ) in current_reward_receivers.iter_mut()
1671                {
1672                    if public_key == &offender {
1673                        // Revoke reward if assigned in current block.
1674                        reward_address.take();
1675                    }
1676                }
1677            }
1678        });
1679
1680        return Err(CheckVoteError::Equivocated { slot, offender });
1681    }
1682
1683    Ok(())
1684}
1685
1686fn check_segment_headers<T: Config>(
1687    segment_headers: &[SegmentHeader],
1688) -> Result<(), TransactionValidityError> {
1689    let mut segment_headers_iter = segment_headers.iter();
1690
1691    // There should be some segment headers
1692    let first_segment_header = match segment_headers_iter.next() {
1693        Some(first_segment_header) => first_segment_header,
1694        None => {
1695            return Err(InvalidTransaction::BadMandatory.into());
1696        }
1697    };
1698
1699    // Segment in segment headers should monotonically increase
1700    if first_segment_header.segment_index() > SegmentIndex::ZERO
1701        && !SegmentCommitment::<T>::contains_key(
1702            first_segment_header.segment_index() - SegmentIndex::ONE,
1703        )
1704    {
1705        return Err(InvalidTransaction::BadMandatory.into());
1706    }
1707
1708    // Segment headers should never repeat
1709    if SegmentCommitment::<T>::contains_key(first_segment_header.segment_index()) {
1710        return Err(InvalidTransaction::BadMandatory.into());
1711    }
1712
1713    let mut last_segment_index = first_segment_header.segment_index();
1714
1715    for segment_header in segment_headers_iter {
1716        let segment_index = segment_header.segment_index();
1717
1718        // Segment in segment headers should monotonically increase
1719        if segment_index != last_segment_index + SegmentIndex::ONE {
1720            return Err(InvalidTransaction::BadMandatory.into());
1721        }
1722
1723        // Segment headers should never repeat
1724        if SegmentCommitment::<T>::contains_key(segment_index) {
1725            return Err(InvalidTransaction::BadMandatory.into());
1726        }
1727
1728        last_segment_index = segment_index;
1729    }
1730
1731    Ok(())
1732}
1733
1734impl<T: Config> subspace_runtime_primitives::RewardsEnabled for Pallet<T> {
1735    fn rewards_enabled() -> bool {
1736        if let Some(height) = EnableRewards::<T>::get() {
1737            frame_system::Pallet::<T>::current_block_number() >= height
1738        } else {
1739            false
1740        }
1741    }
1742}
1743
1744impl<T: Config> subspace_runtime_primitives::FindBlockRewardAddress<T::AccountId> for Pallet<T> {
1745    fn find_block_reward_address() -> Option<T::AccountId> {
1746        CurrentBlockAuthorInfo::<T>::get().and_then(
1747            |(_public_key, _sector_index, _piece_offset, _chunk, _slot, reward_address)| {
1748                // Rewards might be disabled, in which case no block reward
1749                if let Some(height) = EnableRewards::<T>::get()
1750                    && frame_system::Pallet::<T>::current_block_number() >= height
1751                {
1752                    return reward_address;
1753                }
1754
1755                None
1756            },
1757        )
1758    }
1759}
1760
1761impl<T: Config> subspace_runtime_primitives::FindVotingRewardAddresses<T::AccountId> for Pallet<T> {
1762    fn find_voting_reward_addresses() -> Vec<T::AccountId> {
1763        // Rewards might be disabled, in which case no voting reward
1764        if let Some(height) = EnableRewards::<T>::get()
1765            && frame_system::Pallet::<T>::current_block_number() >= height
1766        {
1767            // It is possible that this is called during initialization when current block
1768            // voters are already moved into parent block voters, handle it accordingly
1769            return CurrentBlockVoters::<T>::get()
1770                .unwrap_or_else(ParentBlockVoters::<T>::get)
1771                .into_values()
1772                .filter_map(|(reward_address, _signature)| reward_address)
1773                .collect();
1774        }
1775
1776        Vec::new()
1777    }
1778}
1779
1780impl<T: Config> frame_support::traits::Randomness<T::Hash, BlockNumberFor<T>> for Pallet<T> {
1781    fn random(subject: &[u8]) -> (T::Hash, BlockNumberFor<T>) {
1782        let mut subject = subject.to_vec();
1783        subject.extend_from_slice(
1784            BlockRandomness::<T>::get()
1785                .expect("Block randomness is always set in block initialization; qed")
1786                .as_ref(),
1787        );
1788
1789        (
1790            T::Hashing::hash(&subject),
1791            frame_system::Pallet::<T>::current_block_number(),
1792        )
1793    }
1794
1795    fn random_seed() -> (T::Hash, BlockNumberFor<T>) {
1796        (
1797            T::Hashing::hash(
1798                BlockRandomness::<T>::get()
1799                    .expect("Block randomness is always set in block initialization; qed")
1800                    .as_ref(),
1801            ),
1802            frame_system::Pallet::<T>::current_block_number(),
1803        )
1804    }
1805}