-
Notifications
You must be signed in to change notification settings - Fork 246
/
lib.rs
1814 lines (1601 loc) · 69.5 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd.
// Copyright (C) 2021 Subspace Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(array_chunks, assert_matches, let_chains, portable_simd)]
#![warn(unused_must_use, unsafe_code, unused_variables)]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod weights;
#[cfg(not(feature = "std"))]
use alloc::string::String;
use codec::{Decode, Encode, MaxEncodedLen};
use core::num::NonZeroU64;
use frame_support::dispatch::DispatchResult;
use frame_support::traits::Get;
use frame_system::offchain::{SendTransactionTypes, SubmitTransaction};
use frame_system::pallet_prelude::*;
use log::{debug, error, warn};
pub use pallet::*;
use scale_info::TypeInfo;
use schnorrkel::SignatureError;
use sp_consensus_slots::Slot;
use sp_consensus_subspace::consensus::{is_proof_of_time_valid, verify_solution};
use sp_consensus_subspace::digests::CompatibleDigestItem;
use sp_consensus_subspace::{
PotParameters, PotParametersChange, SignedVote, Vote, WrappedPotOutput,
};
use sp_runtime::generic::DigestItem;
use sp_runtime::traits::{BlockNumberProvider, CheckedSub, Hash, One, Zero};
use sp_runtime::transaction_validity::{
InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity,
TransactionValidityError, ValidTransaction,
};
use sp_std::collections::btree_map::BTreeMap;
use sp_std::prelude::*;
use subspace_core_primitives::pieces::PieceOffset;
use subspace_core_primitives::sectors::{SectorId, SectorIndex};
use subspace_core_primitives::segments::{
ArchivedHistorySegment, HistorySize, SegmentHeader, SegmentIndex,
};
use subspace_core_primitives::solutions::{RewardSignature, SolutionRange};
use subspace_core_primitives::{
BlockHash, PublicKey, ScalarBytes, SlotNumber, REWARD_SIGNING_CONTEXT,
};
use subspace_verification::{
check_reward_signature, derive_next_solution_range, derive_pot_entropy, PieceCheckParams,
VerifySolutionParams,
};
/// Trigger an era change, if any should take place.
pub trait EraChangeTrigger {
/// Trigger an era change, if any should take place. This should be called
/// during every block, after initialization is done.
fn trigger<T: Config>(block_number: BlockNumberFor<T>);
}
/// A type signifying to Subspace that it should perform era changes with an internal trigger.
pub struct NormalEraChange;
impl EraChangeTrigger for NormalEraChange {
fn trigger<T: Config>(block_number: BlockNumberFor<T>) {
if <Pallet<T>>::should_era_change(block_number) {
<Pallet<T>>::enact_era_change();
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, MaxEncodedLen, TypeInfo)]
struct VoteVerificationData {
/// Block solution range, vote must not reach it
solution_range: SolutionRange,
vote_solution_range: SolutionRange,
current_slot: Slot,
parent_slot: Slot,
}
#[frame_support::pallet]
pub mod pallet {
use super::{EraChangeTrigger, VoteVerificationData};
use crate::weights::WeightInfo;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use sp_consensus_slots::Slot;
use sp_consensus_subspace::digests::CompatibleDigestItem;
use sp_consensus_subspace::inherents::{InherentError, InherentType, INHERENT_IDENTIFIER};
use sp_consensus_subspace::SignedVote;
use sp_runtime::traits::One;
use sp_runtime::DigestItem;
use sp_std::collections::btree_map::BTreeMap;
use sp_std::num::NonZeroU32;
use sp_std::prelude::*;
use subspace_core_primitives::hashes::Blake3Hash;
use subspace_core_primitives::pieces::PieceOffset;
use subspace_core_primitives::pot::PotCheckpoints;
use subspace_core_primitives::sectors::SectorIndex;
use subspace_core_primitives::segments::{HistorySize, SegmentHeader, SegmentIndex};
use subspace_core_primitives::solutions::{RewardSignature, SolutionRange};
use subspace_core_primitives::{PublicKey, Randomness, ScalarBytes};
pub(super) struct InitialSolutionRanges<T: Config> {
_config: T,
}
impl<T: Config> Get<sp_consensus_subspace::SolutionRanges> for InitialSolutionRanges<T> {
fn get() -> sp_consensus_subspace::SolutionRanges {
sp_consensus_subspace::SolutionRanges {
current: T::InitialSolutionRange::get(),
next: None,
voting_current: if T::ShouldAdjustSolutionRange::get() {
T::InitialSolutionRange::get()
.saturating_mul(u64::from(T::ExpectedVotesPerBlock::get()) + 1)
} else {
T::InitialSolutionRange::get()
},
voting_next: None,
}
}
}
/// Override for next solution range adjustment
#[derive(Debug, Encode, Decode, TypeInfo)]
pub(super) struct SolutionRangeOverride {
/// Value that should be set as solution range
pub(super) solution_range: SolutionRange,
/// Value that should be set as voting solution range
pub(super) voting_solution_range: SolutionRange,
}
/// The Subspace Pallet
#[pallet::pallet]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::config]
#[pallet::disable_frame_system_supertrait_check]
pub trait Config: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Number of slots between slot arrival and when corresponding block can be produced.
///
/// Practically this means future proof of time proof needs to be revealed this many slots
/// ahead before block can be authored even though solution is available before that.
#[pallet::constant]
type BlockAuthoringDelay: Get<Slot>;
/// Interval, in blocks, between blockchain entropy injection into proof of time chain.
#[pallet::constant]
type PotEntropyInjectionInterval: Get<BlockNumberFor<Self>>;
/// Interval, in entropy injection intervals, where to take entropy for injection from.
#[pallet::constant]
type PotEntropyInjectionLookbackDepth: Get<u8>;
/// Delay after block, in slots, when entropy injection takes effect.
#[pallet::constant]
type PotEntropyInjectionDelay: Get<Slot>;
/// The amount of time, in blocks, that each era should last.
/// NOTE: Currently it is not possible to change the era duration after
/// the chain has started. Attempting to do so will brick block production.
#[pallet::constant]
type EraDuration: Get<BlockNumberFor<Self>>;
/// Initial solution range used for challenges during the very first era.
#[pallet::constant]
type InitialSolutionRange: Get<SolutionRange>;
/// How often in slots slots (on average, not counting collisions) will have a block.
///
/// Expressed as a rational where the first member of the tuple is the
/// numerator and the second is the denominator. The rational should
/// represent a value between 0 and 1.
#[pallet::constant]
type SlotProbability: Get<(u64, u64)>;
/// Depth `K` after which a block enters the recorded history (a global constant, as opposed
/// to the client-dependent transaction confirmation depth `k`).
#[pallet::constant]
type ConfirmationDepthK: Get<BlockNumberFor<Self>>;
/// Number of latest archived segments that are considered "recent history".
#[pallet::constant]
type RecentSegments: Get<HistorySize>;
/// Fraction of pieces from the "recent history" (`recent_segments`) in each sector.
#[pallet::constant]
type RecentHistoryFraction: Get<(HistorySize, HistorySize)>;
/// Minimum lifetime of a plotted sector, measured in archived segment.
#[pallet::constant]
type MinSectorLifetime: Get<HistorySize>;
/// Number of votes expected per block.
///
/// This impacts solution range for votes in consensus.
#[pallet::constant]
type ExpectedVotesPerBlock: Get<u32>;
/// How many pieces one sector is supposed to contain (max)
#[pallet::constant]
type MaxPiecesInSector: Get<u16>;
type ShouldAdjustSolutionRange: Get<bool>;
/// Subspace requires some logic to be triggered on every block to query for whether an era
/// has ended and to perform the transition to the next era.
///
/// Era is normally used to update solution range used for challenges.
type EraChangeTrigger: EraChangeTrigger;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// Maximum number of block number to block slot mappings to keep (oldest pruned first).
#[pallet::constant]
type BlockSlotCount: Get<u32>;
}
#[derive(Debug, Default, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AllowAuthoringBy {
/// Anyone can author new blocks at genesis.
#[default]
Anyone,
/// Author of the first block will be able to author blocks going forward unless unlocked
/// for everyone.
FirstFarmer,
/// Specified root farmer is allowed to author blocks unless unlocked for everyone.
RootFarmer(PublicKey),
}
#[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo)]
pub(super) struct PotEntropyValue {
/// Target slot at which entropy should be injected (when known)
pub(super) target_slot: Option<Slot>,
pub(super) entropy: Blake3Hash,
}
#[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo, PartialEq)]
pub(super) struct PotSlotIterationsValue {
pub(super) slot_iterations: NonZeroU32,
/// Scheduled proof of time slot iterations update
pub(super) update: Option<PotSlotIterationsUpdate>,
}
#[derive(Debug, Copy, Clone, Encode, Decode, TypeInfo, PartialEq)]
pub(super) struct PotSlotIterationsUpdate {
/// Target slot at which entropy should be injected (when known)
pub(super) target_slot: Option<Slot>,
pub(super) slot_iterations: NonZeroU32,
}
/// When to enable block/vote rewards
#[derive(Debug, Copy, Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum EnableRewardsAt<BlockNumber> {
/// At specified height or next block if `None`
Height(BlockNumber),
/// When solution range is below specified threshold
SolutionRange(u64),
/// Manually with an explicit extrinsic
Manually,
}
#[pallet::genesis_config]
pub struct GenesisConfig<T>
where
T: Config,
{
/// When rewards should be enabled.
pub enable_rewards_at: EnableRewardsAt<BlockNumberFor<T>>,
/// Who can author blocks at genesis.
pub allow_authoring_by: AllowAuthoringBy,
/// Number of iterations for proof of time per slot
pub pot_slot_iterations: NonZeroU32,
#[serde(skip)]
pub phantom: PhantomData<T>,
}
impl<T> Default for GenesisConfig<T>
where
T: Config,
{
#[inline]
fn default() -> Self {
Self {
enable_rewards_at: EnableRewardsAt::Height(BlockNumberFor::<T>::one()),
allow_authoring_by: AllowAuthoringBy::Anyone,
pot_slot_iterations: NonZeroU32::MIN,
phantom: PhantomData,
}
}
}
#[pallet::genesis_build]
impl<T> BuildGenesisConfig for GenesisConfig<T>
where
T: Config,
{
fn build(&self) {
match self.enable_rewards_at {
EnableRewardsAt::Height(block_number) => {
EnableRewards::<T>::put(block_number);
}
EnableRewardsAt::SolutionRange(solution_range) => {
EnableRewardsBelowSolutionRange::<T>::put(solution_range);
}
EnableRewardsAt::Manually => {
// Nothing to do in this case
}
}
match &self.allow_authoring_by {
AllowAuthoringBy::Anyone => {
AllowAuthoringByAnyone::<T>::put(true);
}
AllowAuthoringBy::FirstFarmer => {
AllowAuthoringByAnyone::<T>::put(false);
}
AllowAuthoringBy::RootFarmer(root_farmer) => {
AllowAuthoringByAnyone::<T>::put(false);
RootPlotPublicKey::<T>::put(root_farmer);
}
}
PotSlotIterations::<T>::put(PotSlotIterationsValue {
slot_iterations: self.pot_slot_iterations,
update: None,
});
}
}
/// Events type.
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
/// Segment header was stored in blockchain history.
SegmentHeaderStored { segment_header: SegmentHeader },
/// Farmer vote.
FarmerVote {
public_key: PublicKey,
reward_address: T::AccountId,
height: BlockNumberFor<T>,
parent_hash: T::Hash,
},
}
#[pallet::error]
pub enum Error<T> {
/// Solution range adjustment already enabled.
SolutionRangeAdjustmentAlreadyEnabled,
/// Iterations are not multiple of number of checkpoints times two
NotMultipleOfCheckpoints,
/// Proof of time slot iterations must increase as hardware improves
PotSlotIterationsMustIncrease,
/// Proof of time slot iterations update already scheduled
PotSlotIterationsUpdateAlreadyScheduled,
}
/// Bounded mapping from block number to slot
#[pallet::storage]
#[pallet::getter(fn block_slots)]
pub(super) type BlockSlots<T: Config> =
StorageValue<_, BoundedBTreeMap<BlockNumberFor<T>, Slot, T::BlockSlotCount>, ValueQuery>;
/// Solution ranges used for challenges.
#[pallet::storage]
#[pallet::getter(fn solution_ranges)]
pub(super) type SolutionRanges<T: Config> = StorageValue<
_,
sp_consensus_subspace::SolutionRanges,
ValueQuery,
InitialSolutionRanges<T>,
>;
/// Storage to check if the solution range is to be adjusted for next era
#[pallet::storage]
#[pallet::getter(fn should_adjust_solution_range)]
pub(super) type ShouldAdjustSolutionRange<T: Config> =
StorageValue<_, bool, ValueQuery, T::ShouldAdjustSolutionRange>;
/// Override solution range during next update
#[pallet::storage]
pub(super) type NextSolutionRangeOverride<T> = StorageValue<_, SolutionRangeOverride>;
/// Slot at which current era started.
#[pallet::storage]
pub(super) type EraStartSlot<T> = StorageValue<_, Slot>;
/// Mapping from segment index to corresponding segment commitment of contained records.
#[pallet::storage]
#[pallet::getter(fn segment_commitment)]
pub(super) type SegmentCommitment<T> = CountedStorageMap<
_,
Twox64Concat,
SegmentIndex,
subspace_core_primitives::segments::SegmentCommitment,
>;
/// Whether the segment headers inherent has been processed in this block (temporary value).
///
/// This value is updated to `true` when processing `store_segment_headers` by a node.
/// It is then cleared at the end of each block execution in the `on_finalize` hook.
#[pallet::storage]
pub(super) type DidProcessSegmentHeaders<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Storage of previous vote verification data, updated on each block during finalization.
#[pallet::storage]
pub(super) type ParentVoteVerificationData<T> = StorageValue<_, VoteVerificationData>;
/// Parent block author information.
#[pallet::storage]
pub(super) type ParentBlockAuthorInfo<T> =
StorageValue<_, (PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot)>;
/// Enable rewards since specified block number.
#[pallet::storage]
pub(super) type EnableRewards<T: Config> = StorageValue<_, BlockNumberFor<T>>;
/// Enable rewards when solution range is below this threshold.
#[pallet::storage]
pub(super) type EnableRewardsBelowSolutionRange<T: Config> = StorageValue<_, u64>;
/// Block author information
#[pallet::storage]
pub(super) type CurrentBlockAuthorInfo<T: Config> = StorageValue<
_,
(
PublicKey,
SectorIndex,
PieceOffset,
ScalarBytes,
Slot,
Option<T::AccountId>,
),
>;
/// Voters in the parent block (set at the end of the block with current values).
#[pallet::storage]
pub(super) type ParentBlockVoters<T: Config> = StorageValue<
_,
BTreeMap<
(PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot),
(Option<T::AccountId>, RewardSignature),
>,
ValueQuery,
>;
/// Voters in the current block thus far
#[pallet::storage]
pub(super) type CurrentBlockVoters<T: Config> = StorageValue<
_,
BTreeMap<
(PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot),
(Option<T::AccountId>, RewardSignature),
>,
>;
/// Number of iterations for proof of time per slot with optional scheduled update
#[pallet::storage]
pub(super) type PotSlotIterations<T> = StorageValue<_, PotSlotIterationsValue>;
/// Entropy that needs to be injected into proof of time chain at specific slot associated with
/// block number it came from.
#[pallet::storage]
pub(super) type PotEntropy<T: Config> =
StorageValue<_, BTreeMap<BlockNumberFor<T>, PotEntropyValue>, ValueQuery>;
/// The current block randomness, updated at block initialization. When the proof of time feature
/// is enabled it derived from PoT otherwise PoR.
#[pallet::storage]
pub type BlockRandomness<T> = StorageValue<_, Randomness>;
/// Allow block authoring by anyone or just root.
#[pallet::storage]
pub(super) type AllowAuthoringByAnyone<T> = StorageValue<_, bool, ValueQuery>;
/// Root plot public key.
///
/// Set just once to make sure no one else can author blocks until allowed for anyone.
#[pallet::storage]
#[pallet::getter(fn root_plot_public_key)]
pub(super) type RootPlotPublicKey<T> = StorageValue<_, PublicKey>;
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(block_number: BlockNumberFor<T>) -> Weight {
Self::do_initialize(block_number);
Weight::zero()
}
fn on_finalize(block_number: BlockNumberFor<T>) {
Self::do_finalize(block_number)
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Submit new segment header to the blockchain. This is an inherent extrinsic and part of
/// the Subspace consensus logic.
#[pallet::call_index(0)]
#[pallet::weight((< T as Config >::WeightInfo::store_segment_headers(segment_headers.len() as u32), DispatchClass::Mandatory))]
pub fn store_segment_headers(
origin: OriginFor<T>,
segment_headers: Vec<SegmentHeader>,
) -> DispatchResult {
ensure_none(origin)?;
Self::do_store_segment_headers(segment_headers)
}
/// Enable solution range adjustment after every era.
/// Note: No effect on the solution range for the current era
#[pallet::call_index(1)]
#[pallet::weight(< T as Config >::WeightInfo::enable_solution_range_adjustment())]
pub fn enable_solution_range_adjustment(
origin: OriginFor<T>,
solution_range_override: Option<u64>,
voting_solution_range_override: Option<u64>,
) -> DispatchResult {
ensure_root(origin)?;
Self::do_enable_solution_range_adjustment(
solution_range_override,
voting_solution_range_override,
)?;
frame_system::Pallet::<T>::deposit_log(
DigestItem::enable_solution_range_adjustment_and_override(solution_range_override),
);
Ok(())
}
/// Farmer vote, currently only used for extra rewards to farmers.
#[pallet::call_index(2)]
#[pallet::weight((< T as Config >::WeightInfo::vote(), DispatchClass::Operational))]
// Suppression because the custom syntax will also generate an enum and we need enum to have
// boxed value.
#[allow(clippy::boxed_local)]
pub fn vote(
origin: OriginFor<T>,
signed_vote: Box<SignedVote<BlockNumberFor<T>, T::Hash, T::AccountId>>,
) -> DispatchResult {
ensure_none(origin)?;
Self::do_vote(*signed_vote)
}
/// Enable rewards for blocks and votes at specified block height.
#[pallet::call_index(3)]
#[pallet::weight(< T as Config >::WeightInfo::enable_rewards_at())]
pub fn enable_rewards_at(
origin: OriginFor<T>,
enable_rewards_at: EnableRewardsAt<BlockNumberFor<T>>,
) -> DispatchResult {
ensure_root(origin)?;
Self::do_enable_rewards_at(enable_rewards_at)
}
/// Enable storage access for all users.
#[pallet::call_index(4)]
#[pallet::weight(< T as Config >::WeightInfo::enable_authoring_by_anyone())]
pub fn enable_authoring_by_anyone(origin: OriginFor<T>) -> DispatchResult {
ensure_root(origin)?;
AllowAuthoringByAnyone::<T>::put(true);
RootPlotPublicKey::<T>::take();
// Deposit root plot public key update such that light client can validate blocks later.
frame_system::Pallet::<T>::deposit_log(DigestItem::root_plot_public_key_update(None));
Ok(())
}
/// Update proof of time slot iterations
#[pallet::call_index(5)]
#[pallet::weight(< T as Config >::WeightInfo::set_pot_slot_iterations())]
pub fn set_pot_slot_iterations(
origin: OriginFor<T>,
slot_iterations: NonZeroU32,
) -> DispatchResult {
ensure_root(origin)?;
if slot_iterations.get() % u32::from(PotCheckpoints::NUM_CHECKPOINTS.get() * 2) != 0 {
return Err(Error::<T>::NotMultipleOfCheckpoints.into());
}
let mut pot_slot_iterations =
PotSlotIterations::<T>::get().expect("Always initialized during genesis; qed");
if pot_slot_iterations.slot_iterations >= slot_iterations {
return Err(Error::<T>::PotSlotIterationsMustIncrease.into());
}
// Can't update if already scheduled since it will cause verification issues
if let Some(pot_slot_iterations_update_value) = pot_slot_iterations.update
&& pot_slot_iterations_update_value.target_slot.is_some()
{
return Err(Error::<T>::PotSlotIterationsUpdateAlreadyScheduled.into());
}
pot_slot_iterations.update.replace(PotSlotIterationsUpdate {
// Slot will be known later when next entropy injection takes place
target_slot: None,
slot_iterations,
});
PotSlotIterations::<T>::put(pot_slot_iterations);
Ok(())
}
}
#[pallet::inherent]
impl<T: Config> ProvideInherent for Pallet<T> {
type Call = Call<T>;
type Error = InherentError;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
let inherent_data = data
.get_data::<InherentType>(&INHERENT_IDENTIFIER)
.expect("Subspace inherent data not correctly encoded")
.expect("Subspace inherent data must be provided");
let segment_headers = inherent_data.segment_headers;
if segment_headers.is_empty() {
None
} else {
Some(Call::store_segment_headers { segment_headers })
}
}
fn is_inherent_required(data: &InherentData) -> Result<Option<Self::Error>, Self::Error> {
let inherent_data = data
.get_data::<InherentType>(&INHERENT_IDENTIFIER)
.expect("Subspace inherent data not correctly encoded")
.expect("Subspace inherent data must be provided");
Ok(if inherent_data.segment_headers.is_empty() {
None
} else {
Some(InherentError::MissingSegmentHeadersList)
})
}
fn check_inherent(call: &Self::Call, data: &InherentData) -> Result<(), Self::Error> {
if let Call::store_segment_headers { segment_headers } = call {
let inherent_data = data
.get_data::<InherentType>(&INHERENT_IDENTIFIER)
.expect("Subspace inherent data not correctly encoded")
.expect("Subspace inherent data must be provided");
if segment_headers != &inherent_data.segment_headers {
return Err(InherentError::IncorrectSegmentHeadersList {
expected: inherent_data.segment_headers,
actual: segment_headers.clone(),
});
}
}
Ok(())
}
fn is_inherent(call: &Self::Call) -> bool {
matches!(call, Call::store_segment_headers { .. })
}
}
#[pallet::validate_unsigned]
impl<T: Config> ValidateUnsigned for Pallet<T> {
type Call = Call<T>;
fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
match call {
Call::store_segment_headers { segment_headers } => {
Self::validate_segment_header(source, segment_headers)
}
Call::vote { signed_vote } => Self::validate_vote(signed_vote),
_ => InvalidTransaction::Call.into(),
}
}
fn pre_dispatch(call: &Self::Call) -> Result<(), TransactionValidityError> {
match call {
Call::store_segment_headers { segment_headers } => {
Self::pre_dispatch_segment_header(segment_headers)
}
Call::vote { signed_vote } => Self::pre_dispatch_vote(signed_vote),
_ => Err(InvalidTransaction::Call.into()),
}
}
}
}
impl<T: Config> Pallet<T> {
/// Total number of pieces in the blockchain
pub fn history_size() -> HistorySize {
// Chain starts with one segment plotted, even if it is not recorded in the runtime yet
let number_of_segments = u64::from(SegmentCommitment::<T>::count()).max(1);
HistorySize::from(NonZeroU64::new(number_of_segments).expect("Not zero; qed"))
}
/// Determine whether an era change should take place at this block.
/// Assumes that initialization has already taken place.
fn should_era_change(block_number: BlockNumberFor<T>) -> bool {
block_number % T::EraDuration::get() == Zero::zero()
}
/// DANGEROUS: Enact era change. Should be done on every block where `should_era_change` has
/// returned `true`, and the caller is the only caller of this function.
///
/// This will update solution range used in consensus.
fn enact_era_change() {
let slot_probability = T::SlotProbability::get();
let current_slot = Self::current_slot();
SolutionRanges::<T>::mutate(|solution_ranges| {
let next_solution_range;
let next_voting_solution_range;
// Check if the solution range should be adjusted for next era.
if !ShouldAdjustSolutionRange::<T>::get() {
next_solution_range = solution_ranges.current;
next_voting_solution_range = solution_ranges.current;
} else if let Some(solution_range_override) = NextSolutionRangeOverride::<T>::take() {
next_solution_range = solution_range_override.solution_range;
next_voting_solution_range = solution_range_override.voting_solution_range;
} else {
next_solution_range = derive_next_solution_range(
// If Era start slot is not found it means we have just finished the first era
u64::from(EraStartSlot::<T>::get().unwrap_or_default()),
u64::from(current_slot),
slot_probability,
solution_ranges.current,
T::EraDuration::get()
.try_into()
.unwrap_or_else(|_| panic!("Era duration is always within u64; qed")),
);
next_voting_solution_range = next_solution_range
.saturating_mul(u64::from(T::ExpectedVotesPerBlock::get()) + 1);
};
solution_ranges.next.replace(next_solution_range);
solution_ranges
.voting_next
.replace(next_voting_solution_range);
if let Some(solution_range_for_rewards) = EnableRewardsBelowSolutionRange::<T>::get() {
if next_solution_range <= solution_range_for_rewards {
EnableRewardsBelowSolutionRange::<T>::take();
let next_block_number =
frame_system::Pallet::<T>::current_block_number() + One::one();
EnableRewards::<T>::put(next_block_number);
}
}
});
EraStartSlot::<T>::put(current_slot);
}
fn do_initialize(block_number: BlockNumberFor<T>) {
let pre_digest = frame_system::Pallet::<T>::digest()
.logs
.iter()
.find_map(|s| s.as_subspace_pre_digest::<T::AccountId>())
.expect("Block must always have pre-digest");
let current_slot = pre_digest.slot();
BlockSlots::<T>::mutate(|block_slots| {
if let Some(to_remove) = block_number.checked_sub(&T::BlockSlotCount::get().into()) {
block_slots.remove(&to_remove);
}
block_slots
.try_insert(block_number, current_slot)
.expect("one entry just removed before inserting; qed");
});
{
// Remove old value
CurrentBlockAuthorInfo::<T>::take();
let farmer_public_key = pre_digest.solution().public_key;
// Optional restriction for block authoring to the root user
if !AllowAuthoringByAnyone::<T>::get() {
RootPlotPublicKey::<T>::mutate(|maybe_root_plot_public_key| {
if let Some(root_plot_public_key) = maybe_root_plot_public_key {
if root_plot_public_key != &farmer_public_key {
panic!("Client bug, authoring must be only done by the root user");
}
} else {
maybe_root_plot_public_key.replace(farmer_public_key);
// Deposit root plot public key update such that light client can validate
// blocks later.
frame_system::Pallet::<T>::deposit_log(
DigestItem::root_plot_public_key_update(Some(farmer_public_key)),
);
}
});
}
let key = (
farmer_public_key,
pre_digest.solution().sector_index,
pre_digest.solution().piece_offset,
pre_digest.solution().chunk,
current_slot,
);
if !ParentBlockVoters::<T>::get().contains_key(&key) {
let (public_key, sector_index, piece_offset, chunk, slot) = key;
CurrentBlockAuthorInfo::<T>::put((
public_key,
sector_index,
piece_offset,
chunk,
slot,
Some(pre_digest.solution().reward_address.clone()),
));
}
}
CurrentBlockVoters::<T>::put(BTreeMap::<
(PublicKey, SectorIndex, PieceOffset, ScalarBytes, Slot),
(Option<T::AccountId>, RewardSignature),
>::default());
// If solution range was updated in previous block, set it as current.
if let sp_consensus_subspace::SolutionRanges {
next: Some(next),
voting_next: Some(voting_next),
..
} = SolutionRanges::<T>::get()
{
SolutionRanges::<T>::put(sp_consensus_subspace::SolutionRanges {
current: next,
next: None,
voting_current: voting_next,
voting_next: None,
});
}
let block_randomness = pre_digest
.pot_info()
.proof_of_time()
.derive_global_randomness();
// Update the block randomness.
BlockRandomness::<T>::put(block_randomness);
// Deposit solution range data such that light client can validate blocks later.
frame_system::Pallet::<T>::deposit_log(DigestItem::solution_range(
SolutionRanges::<T>::get().current,
));
// Enact era change, if necessary.
T::EraChangeTrigger::trigger::<T>(block_number);
{
let mut pot_slot_iterations =
PotSlotIterations::<T>::get().expect("Always initialized during genesis; qed");
// This is what we had after previous block
frame_system::Pallet::<T>::deposit_log(DigestItem::pot_slot_iterations(
pot_slot_iterations.slot_iterations,
));
// Check PoT slot iterations update and apply it if it is time to do so, while also
// removing corresponding storage item
if let Some(update) = pot_slot_iterations.update
&& let Some(target_slot) = update.target_slot
&& target_slot <= current_slot
{
debug!(
target: "runtime::subspace",
"Applying PoT slots update, changing to {} at block #{:?}",
update.slot_iterations,
block_number
);
pot_slot_iterations = PotSlotIterationsValue {
slot_iterations: update.slot_iterations,
update: None,
};
PotSlotIterations::<T>::put(pot_slot_iterations);
}
let pot_entropy_injection_interval = T::PotEntropyInjectionInterval::get();
let pot_entropy_injection_delay = T::PotEntropyInjectionDelay::get();
let mut entropy = PotEntropy::<T>::get();
let lookback_in_blocks = pot_entropy_injection_interval
* BlockNumberFor::<T>::from(T::PotEntropyInjectionLookbackDepth::get());
let last_entropy_injection_block =
block_number / pot_entropy_injection_interval * pot_entropy_injection_interval;
let maybe_entropy_source_block_number =
last_entropy_injection_block.checked_sub(&lookback_in_blocks);
if (block_number % pot_entropy_injection_interval).is_zero() {
let current_block_entropy = derive_pot_entropy(
&pre_digest.solution().chunk,
pre_digest.pot_info().proof_of_time(),
);
// Collect entropy every `T::PotEntropyInjectionInterval` blocks
entropy.insert(
block_number,
PotEntropyValue {
target_slot: None,
entropy: current_block_entropy,
},
);
// Update target slot for entropy injection once we know it
if let Some(entropy_source_block_number) = maybe_entropy_source_block_number {
if let Some(entropy_value) = entropy.get_mut(&entropy_source_block_number) {
let target_slot = pre_digest
.slot()
.saturating_add(pot_entropy_injection_delay);
debug!(
target: "runtime::subspace",
"Pot entropy injection will happen at slot {target_slot:?}",
);
entropy_value.target_slot.replace(target_slot);
// Schedule PoT slot iterations update at the same slot as entropy
if let Some(update) = &mut pot_slot_iterations.update
&& update.target_slot.is_none()
{
debug!(
target: "runtime::subspace",
"Scheduling PoT slots update to happen at slot {target_slot:?}"
);
update.target_slot.replace(target_slot);
PotSlotIterations::<T>::put(pot_slot_iterations);
}
}
}
PotEntropy::<T>::put(entropy.clone());
}
// Deposit consensus log item with parameters change in case corresponding entropy is
// available
if let Some(entropy_source_block_number) = maybe_entropy_source_block_number {
let maybe_entropy_value = entropy.get(&entropy_source_block_number).copied();
if let Some(PotEntropyValue {
target_slot,
entropy,
}) = maybe_entropy_value
{
let target_slot = target_slot
.expect("Target slot is guaranteed to be present due to logic above; qed");
// Check if there was a PoT slot iterations update at the same exact slot
let slot_iterations = if let Some(update) = pot_slot_iterations.update
&& let Some(update_target_slot) = update.target_slot
&& update_target_slot == target_slot
{
debug!(
target: "runtime::subspace",
"Applying PoT slots update to the next PoT parameters change"
);
update.slot_iterations
} else {
pot_slot_iterations.slot_iterations
};
frame_system::Pallet::<T>::deposit_log(DigestItem::pot_parameters_change(
PotParametersChange {
slot: target_slot,
slot_iterations,
entropy,
},
));
}
}
// Clean up old values we'll no longer need
if let Some(entry) = entropy.first_entry() {
if let Some(target_slot) = entry.get().target_slot
&& target_slot < current_slot
{
entry.remove();