1#![doc = include_str!("../README.md")]
2#![cfg_attr(not(feature = "std"), no_std)]
3#![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
67pub trait EraChangeTrigger {
69 fn trigger<T: Config>(block_number: BlockNumberFor<T>);
72}
73
74pub 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#[derive(
87 PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DecodeWithMemTracking,
88)]
89pub enum RawOrigin {
90 ValidatedUnsigned,
91}
92
93pub 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 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 #[derive(Debug, Encode, Decode, TypeInfo)]
165 pub(super) struct SolutionRangeOverride {
166 pub(super) solution_range: SolutionRange,
168 pub(super) voting_solution_range: SolutionRange,
170 }
171
172 #[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 type SubspaceOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = ()>;
182
183 #[pallet::constant]
188 type BlockAuthoringDelay: Get<Slot>;
189
190 #[pallet::constant]
192 type PotEntropyInjectionInterval: Get<BlockNumberFor<Self>>;
193
194 #[pallet::constant]
196 type PotEntropyInjectionLookbackDepth: Get<u8>;
197
198 #[pallet::constant]
200 type PotEntropyInjectionDelay: Get<Slot>;
201
202 #[pallet::constant]
206 type EraDuration: Get<BlockNumberFor<Self>>;
207
208 #[pallet::constant]
210 type InitialSolutionRange: Get<SolutionRange>;
211
212 #[pallet::constant]
218 type SlotProbability: Get<(u64, u64)>;
219
220 #[pallet::constant]
223 type ConfirmationDepthK: Get<BlockNumberFor<Self>>;
224
225 #[pallet::constant]
227 type RecentSegments: Get<HistorySize>;
228
229 #[pallet::constant]
231 type RecentHistoryFraction: Get<(HistorySize, HistorySize)>;
232
233 #[pallet::constant]
235 type MinSectorLifetime: Get<HistorySize>;
236
237 #[pallet::constant]
241 type ExpectedVotesPerBlock: Get<u32>;
242
243 #[pallet::constant]
245 type MaxPiecesInSector: Get<u16>;
246
247 type ShouldAdjustSolutionRange: Get<bool>;
248 type EraChangeTrigger: EraChangeTrigger;
253
254 type WeightInfo: WeightInfo;
256
257 #[pallet::constant]
259 type BlockSlotCount: Get<u32>;
260
261 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 #[default]
270 Anyone,
271 FirstFarmer,
274 RootFarmer(PublicKey),
276 }
277
278 #[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo)]
279 pub(super) struct PotEntropyValue {
280 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 pub(super) update: Option<PotSlotIterationsUpdate>,
290 }
291
292 #[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo, PartialEq)]
293 pub(super) struct PotSlotIterationsUpdate {
294 pub(super) target_slot: Option<Slot>,
296 pub(super) slot_iterations: NonZeroU32,
297 }
298
299 #[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 Height(BlockNumber),
307 SolutionRange(u64),
309 Manually,
311 }
312
313 #[pallet::genesis_config]
314 pub struct GenesisConfig<T>
315 where
316 T: Config,
317 {
318 pub enable_rewards_at: EnableRewardsAt<BlockNumberFor<T>>,
320 pub allow_authoring_by: AllowAuthoringBy,
322 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 }
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 #[pallet::event]
381 #[pallet::generate_deposit(pub (super) fn deposit_event)]
382 pub enum Event<T: Config> {
383 SegmentHeaderStored { segment_header: SegmentHeader },
385 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 SolutionRangeAdjustmentAlreadyEnabled,
401 NotMultipleOfCheckpoints,
403 PotSlotIterationsMustIncrease,
405 PotSlotIterationsUpdateAlreadyScheduled,
407 }
408
409 #[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 #[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 #[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 #[pallet::storage]
433 pub(super) type NextSolutionRangeOverride<T> = StorageValue<_, SolutionRangeOverride>;
434
435 #[pallet::storage]
437 pub(super) type EraStartSlot<T> = StorageValue<_, Slot>;
438
439 #[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 #[pallet::storage]
454 pub(super) type DidProcessSegmentHeaders<T: Config> = StorageValue<_, bool, ValueQuery>;
455
456 #[pallet::storage]
458 pub(super) type ParentVoteVerificationData<T> = StorageValue<_, VoteVerificationData>;
459
460 #[pallet::storage]
462 pub(super) type ParentBlockAuthorInfo<T> =
463 StorageValue<_, (PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot)>;
464
465 #[pallet::storage]
467 pub(super) type EnableRewards<T: Config> = StorageValue<_, BlockNumberFor<T>>;
468
469 #[pallet::storage]
471 pub(super) type EnableRewardsBelowSolutionRange<T: Config> = StorageValue<_, u64>;
472
473 #[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 #[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 #[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 #[pallet::storage]
510 pub(super) type PotSlotIterations<T> = StorageValue<_, PotSlotIterationsValue>;
511
512 #[pallet::storage]
515 pub(super) type PotEntropy<T: Config> =
516 StorageValue<_, BTreeMap<BlockNumberFor<T>, PotEntropyValue>, ValueQuery>;
517
518 #[pallet::storage]
521 pub type BlockRandomness<T> = StorageValue<_, Randomness>;
522
523 #[pallet::storage]
525 pub(super) type AllowAuthoringByAnyone<T> = StorageValue<_, bool, ValueQuery>;
526
527 #[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 #[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 #[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 #[pallet::call_index(2)]
585 #[pallet::weight((< T as Config >::WeightInfo::vote(), DispatchClass::Operational))]
586 #[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 #[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 #[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 frame_system::Pallet::<T>::deposit_log(DigestItem::root_plot_public_key_update(None));
620
621 Ok(())
622 }
623
624 #[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 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 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 #[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 pub fn history_size() -> HistorySize {
750 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 fn should_era_change(block_number: BlockNumberFor<T>) -> bool {
758 block_number % T::EraDuration::get() == Zero::zero()
759 }
760
761 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 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 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 CurrentBlockAuthorInfo::<T>::take();
834 let farmer_public_key = pre_digest.solution().public_key;
835
836 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 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 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 BlockRandomness::<T>::put(block_randomness);
901
902 frame_system::Pallet::<T>::deposit_log(DigestItem::solution_range(
904 SolutionRanges::<T>::get().current,
905 ));
906
907 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 frame_system::Pallet::<T>::deposit_log(DigestItem::pot_slot_iterations(
915 pot_slot_iterations.slot_iterations,
916 ));
917
918 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 entropy.insert(
952 block_number,
953 PotEntropyValue {
954 target_slot: None,
955 entropy: current_block_entropy,
956 },
957 );
958
959 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 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 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 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 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 if let Some(next_solution_range) = SolutionRanges::<T>::get().next {
1029 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 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_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 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 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 }
1149 }
1150
1151 Ok(())
1152 }
1153
1154 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 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 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 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 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
1244impl<T: Config> Pallet<T> {
1249 fn validate_segment_header(
1250 source: TransactionSource,
1251 segment_headers: &[SegmentHeader],
1252 ) -> TransactionValidity {
1253 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 .priority(TransactionPriority::MAX)
1268 .longevity(0)
1271 .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 .priority(TransactionPriority::MAX)
1290 .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 Ok(T::ExtensionWeightInfo::vote_with_equivocation())
1305 }
1306 Err(error) => Err(error.into()),
1307 }
1308 }
1309}
1310
1311fn 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 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 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 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 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 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 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 !pre_dispatch,
1565 ) {
1566 debug!("Invalid proof of time");
1567
1568 return Err(CheckVoteError::InvalidProofOfTime);
1569 }
1570
1571 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 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 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 return Err(CheckVoteError::DuplicateVote);
1629 }
1630 }
1631
1632 if pre_dispatch {
1633 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 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 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 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 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 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 if segment_index != last_segment_index + SegmentIndex::ONE {
1720 return Err(InvalidTransaction::BadMandatory.into());
1721 }
1722
1723 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 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 if let Some(height) = EnableRewards::<T>::get()
1765 && frame_system::Pallet::<T>::current_block_number() >= height
1766 {
1767 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}