This repository has been archived by the owner on Jun 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 102
/
miner_state.go
1242 lines (1053 loc) · 44.2 KB
/
miner_state.go
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
package miner
import (
"fmt"
"reflect"
"sort"
addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/dline"
xc "github.com/filecoin-project/go-state-types/exitcode"
cid "github.com/ipfs/go-cid"
xerrors "golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/v8/actors/builtin"
"github.com/filecoin-project/specs-actors/v8/actors/util/adt"
)
// Balance of Miner Actor should be greater than or equal to
// the sum of PreCommitDeposits and LockedFunds.
// It is possible for balance to fall below the sum of
// PCD, LF and InitialPledgeRequirements, and this is a bad
// state (IP Debt) that limits a miner actor's behavior (i.e. no balance withdrawals)
// Excess balance as computed by st.GetAvailableBalance will be
// withdrawable or usable for pre-commit deposit or pledge lock-up.
type State struct {
// Information not related to sectors.
Info cid.Cid
PreCommitDeposits abi.TokenAmount // Total funds locked as PreCommitDeposits
LockedFunds abi.TokenAmount // Total rewards and added funds locked in vesting table
VestingFunds cid.Cid // VestingFunds (Vesting Funds schedule for the miner).
FeeDebt abi.TokenAmount // Absolute value of debt this miner owes from unpaid fees
InitialPledge abi.TokenAmount // Sum of initial pledge requirements of all active sectors
// Sectors that have been pre-committed but not yet proven.
PreCommittedSectors cid.Cid // Map, HAMT[SectorNumber]SectorPreCommitOnChainInfo
// PreCommittedSectorsCleanUp maintains the state required to cleanup expired PreCommittedSectors.
PreCommittedSectorsCleanUp cid.Cid // BitFieldQueue (AMT[Epoch]*BitField)
// Allocated sector IDs. Sector IDs can never be reused once allocated.
AllocatedSectors cid.Cid // BitField
// Information for all proven and not-yet-garbage-collected sectors.
//
// Sectors are removed from this AMT when the partition to which the
// sector belongs is compacted.
Sectors cid.Cid // Array, AMT[SectorNumber]SectorOnChainInfo (sparse)
// DEPRECATED. This field will change names and no longer be updated every proving period in a future upgrade
// The first epoch in this miner's current proving period. This is the first epoch in which a PoSt for a
// partition at the miner's first deadline may arrive. Alternatively, it is after the last epoch at which
// a PoSt for the previous window is valid.
// Always greater than zero, this may be greater than the current epoch for genesis miners in the first
// WPoStProvingPeriod epochs of the chain; the epochs before the first proving period starts are exempt from Window
// PoSt requirements.
// Updated at the end of every period by a cron callback.
ProvingPeriodStart abi.ChainEpoch
// DEPRECATED. This field will be removed from state in a future upgrade.
// Index of the deadline within the proving period beginning at ProvingPeriodStart that has not yet been
// finalized.
// Updated at the end of each deadline window by a cron callback.
CurrentDeadline uint64
// The sector numbers due for PoSt at each deadline in the current proving period, frozen at period start.
// New sectors are added and expired ones removed at proving period boundary.
// Faults are not subtracted from this in state, but on the fly.
Deadlines cid.Cid
// Deadlines with outstanding fees for early sector termination.
EarlyTerminations bitfield.BitField
// True when miner cron is active, false otherwise
DeadlineCronActive bool
}
// Bitwidth of AMTs determined empirically from mutation patterns and projections of mainnet data.
const PrecommitCleanUpAmtBitwidth = 6
const SectorsAmtBitwidth = 5
type MinerInfo struct {
// Account that owns this miner.
// - Income and returned collateral are paid to this address.
// - This address is also allowed to change the worker address for the miner.
Owner addr.Address // Must be an ID-address.
// Worker account for this miner.
// The associated pubkey-type address is used to sign blocks and messages on behalf of this miner.
Worker addr.Address // Must be an ID-address.
// Additional addresses that are permitted to submit messages controlling this actor (optional).
ControlAddresses []addr.Address // Must all be ID addresses.
PendingWorkerKey *WorkerKeyChange
// Byte array representing a Libp2p identity that should be used when connecting to this miner.
PeerId abi.PeerID
// Slice of byte arrays representing Libp2p multi-addresses used for establishing a connection with this miner.
Multiaddrs []abi.Multiaddrs
// The proof type used for Window PoSt for this miner.
// A miner may commit sectors with different seal proof types (but compatible sector size and
// corresponding PoSt proof types).
WindowPoStProofType abi.RegisteredPoStProof
// Amount of space in each sector committed by this miner.
// This is computed from the proof type and represented here redundantly.
SectorSize abi.SectorSize
// The number of sectors in each Window PoSt partition (proof).
// This is computed from the proof type and represented here redundantly.
WindowPoStPartitionSectors uint64
// The next epoch this miner is eligible for certain permissioned actor methods
// and winning block elections as a result of being reported for a consensus fault.
ConsensusFaultElapsed abi.ChainEpoch
// A proposed new owner account for this miner.
// Must be confirmed by a message from the pending address itself.
PendingOwnerAddress *addr.Address
}
type WorkerKeyChange struct {
NewWorker addr.Address // Must be an ID address
EffectiveAt abi.ChainEpoch
}
// Information provided by a miner when pre-committing a sector.
type SectorPreCommitInfo struct {
SealProof abi.RegisteredSealProof
SectorNumber abi.SectorNumber
SealedCID cid.Cid `checked:"true"` // CommR
SealRandEpoch abi.ChainEpoch
DealIDs []abi.DealID
Expiration abi.ChainEpoch
ReplaceCapacity bool // Whether to replace a "committed capacity" no-deal sector (requires non-empty DealIDs)
// The committed capacity sector to replace, and it's deadline/partition location
ReplaceSectorDeadline uint64
ReplaceSectorPartition uint64
ReplaceSectorNumber abi.SectorNumber
}
// Information stored on-chain for a pre-committed sector.
type SectorPreCommitOnChainInfo struct {
Info SectorPreCommitInfo
PreCommitDeposit abi.TokenAmount
PreCommitEpoch abi.ChainEpoch
DealWeight abi.DealWeight // Integral of active deals over sector lifetime
VerifiedDealWeight abi.DealWeight // Integral of active verified deals over sector lifetime
}
// Information stored on-chain for a proven sector.
type SectorOnChainInfo struct {
SectorNumber abi.SectorNumber
SealProof abi.RegisteredSealProof // The seal proof type implies the PoSt proof/s
SealedCID cid.Cid // CommR
DealIDs []abi.DealID
Activation abi.ChainEpoch // Epoch during which the sector proof was accepted
Expiration abi.ChainEpoch // Epoch during which the sector expires
DealWeight abi.DealWeight // Integral of active deals over sector lifetime
VerifiedDealWeight abi.DealWeight // Integral of active verified deals over sector lifetime
InitialPledge abi.TokenAmount // Pledge collected to commit this sector
ExpectedDayReward abi.TokenAmount // Expected one day projection of reward for sector computed at activation time
ExpectedStoragePledge abi.TokenAmount // Expected twenty day projection of reward for sector computed at activation time
ReplacedSectorAge abi.ChainEpoch // Age of sector this sector replaced or zero
ReplacedDayReward abi.TokenAmount // Day reward of sector this sector replace or zero
SectorKeyCID *cid.Cid // The original SealedSectorCID, only gets set on the first ReplicaUpdate
}
func ConstructState(store adt.Store, infoCid cid.Cid, periodStart abi.ChainEpoch, deadlineIndex uint64) (*State, error) {
emptyPrecommitMapCid, err := adt.StoreEmptyMap(store, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty map: %w", err)
}
emptyPrecommitsCleanUpArrayCid, err := adt.StoreEmptyArray(store, PrecommitCleanUpAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty precommits array: %w", err)
}
emptySectorsArrayCid, err := adt.StoreEmptyArray(store, SectorsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty sectors array: %w", err)
}
emptyBitfield := bitfield.NewFromSet(nil)
emptyBitfieldCid, err := store.Put(store.Context(), emptyBitfield)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty bitfield: %w", err)
}
emptyDeadline, err := ConstructDeadline(store)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty deadline: %w", err)
}
emptyDeadlineCid, err := store.Put(store.Context(), emptyDeadline)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty deadline: %w", err)
}
emptyDeadlines := ConstructDeadlines(emptyDeadlineCid)
emptyDeadlinesCid, err := store.Put(store.Context(), emptyDeadlines)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty deadlines: %w", err)
}
emptyVestingFundsCid, err := store.Put(store.Context(), ConstructVestingFunds())
if err != nil {
return nil, xerrors.Errorf("failed to construct empty vesting funds: %w", err)
}
return &State{
Info: infoCid,
PreCommitDeposits: abi.NewTokenAmount(0),
LockedFunds: abi.NewTokenAmount(0),
FeeDebt: abi.NewTokenAmount(0),
VestingFunds: emptyVestingFundsCid,
InitialPledge: abi.NewTokenAmount(0),
PreCommittedSectors: emptyPrecommitMapCid,
PreCommittedSectorsCleanUp: emptyPrecommitsCleanUpArrayCid,
AllocatedSectors: emptyBitfieldCid,
Sectors: emptySectorsArrayCid,
ProvingPeriodStart: periodStart,
CurrentDeadline: deadlineIndex,
Deadlines: emptyDeadlinesCid,
EarlyTerminations: bitfield.New(),
DeadlineCronActive: false,
}, nil
}
func ConstructMinerInfo(owner, worker addr.Address, controlAddrs []addr.Address, pid []byte, multiAddrs []abi.Multiaddrs,
windowPoStProofType abi.RegisteredPoStProof) (*MinerInfo, error) {
sectorSize, err := windowPoStProofType.SectorSize()
if err != nil {
return nil, xc.ErrIllegalArgument.Wrapf("invalid sector size: %w", err)
}
partitionSectors, err := builtin.PoStProofWindowPoStPartitionSectors(windowPoStProofType)
if err != nil {
return nil, xc.ErrIllegalArgument.Wrapf("invalid partition sectors: %w", err)
}
return &MinerInfo{
Owner: owner,
Worker: worker,
ControlAddresses: controlAddrs,
PendingWorkerKey: nil,
PeerId: pid,
Multiaddrs: multiAddrs,
WindowPoStProofType: windowPoStProofType,
SectorSize: sectorSize,
WindowPoStPartitionSectors: partitionSectors,
ConsensusFaultElapsed: abi.ChainEpoch(-1),
PendingOwnerAddress: nil,
}, nil
}
func (st *State) GetInfo(store adt.Store) (*MinerInfo, error) {
var info MinerInfo
if err := store.Get(store.Context(), st.Info, &info); err != nil {
return nil, xerrors.Errorf("failed to get miner info %w", err)
}
return &info, nil
}
func (st *State) SaveInfo(store adt.Store, info *MinerInfo) error {
c, err := store.Put(store.Context(), info)
if err != nil {
return err
}
st.Info = c
return nil
}
// Returns deadline calculations for the current proving period, according to the current epoch and constant state offset
func (st *State) DeadlineInfo(currEpoch abi.ChainEpoch) *dline.Info {
return NewDeadlineInfoFromOffsetAndEpoch(st.ProvingPeriodStart, currEpoch)
}
// Returns deadline calculations for the state recorded proving period and deadline. This is out of date if the a
// miner does not have an active miner cron
func (st *State) RecordedDeadlineInfo(currEpoch abi.ChainEpoch) *dline.Info {
return NewDeadlineInfo(st.ProvingPeriodStart, st.CurrentDeadline, currEpoch)
}
// Returns current proving period start for the current epoch according to the current epoch and constant state offset
func (st *State) CurrentProvingPeriodStart(currEpoch abi.ChainEpoch) abi.ChainEpoch {
dlInfo := st.DeadlineInfo(currEpoch)
return dlInfo.PeriodStart
}
// Returns deadline calculations for the current (according to state) proving period
func (st *State) QuantSpecForDeadline(dlIdx uint64) builtin.QuantSpec {
return QuantSpecForDeadline(NewDeadlineInfo(st.ProvingPeriodStart, dlIdx, 0))
}
type CollisionPolicy bool
const (
DenyCollisions = CollisionPolicy(false)
AllowCollisions = CollisionPolicy(true)
)
// Marks a set of sector numbers as having been allocated.
// If policy is `DenyCollisions`, fails if the set intersects with the sector numbers already allocated.
func (st *State) AllocateSectorNumbers(store adt.Store, sectorNos bitfield.BitField, policy CollisionPolicy) error {
var priorAllocation bitfield.BitField
if err := store.Get(store.Context(), st.AllocatedSectors, &priorAllocation); err != nil {
return xc.ErrIllegalState.Wrapf("failed to load allocated sectors bitfield: %w", err)
}
if policy != AllowCollisions {
// NOTE: A fancy merge algorithm could extract this intersection while merging, below, saving
// one iteration of the runs.
collisions, err := bitfield.IntersectBitField(priorAllocation, sectorNos)
if err != nil {
return xerrors.Errorf("failed to intersect sector numbers: %w", err)
}
if empty, err := collisions.IsEmpty(); err != nil {
return xerrors.Errorf("failed to check if intersection is empty: %w", err)
} else if !empty {
return xc.ErrIllegalArgument.Wrapf("sector numbers %v already allocated", collisions)
}
}
newAllocation, err := bitfield.MergeBitFields(priorAllocation, sectorNos)
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to merge allocated bitfield with mask: %w", err)
}
if root, err := store.Put(store.Context(), newAllocation); err != nil {
return xc.ErrIllegalArgument.Wrapf("failed to store allocated sectors bitfield after adding %v: %w", sectorNos, err)
} else {
st.AllocatedSectors = root
}
return nil
}
// Stores a pre-committed sector info, failing if the sector number is already present.
func (st *State) PutPrecommittedSectors(store adt.Store, precommits ...*SectorPreCommitOnChainInfo) error {
precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth)
if err != nil {
return err
}
for _, precommit := range precommits {
// NOTE: HAMT batch operations could reduce total state read/write cost of this batch.
if modified, err := precommitted.PutIfAbsent(SectorKey(precommit.Info.SectorNumber), precommit); err != nil {
return xerrors.Errorf("failed to store pre-commitment for %v: %w", precommit, err)
} else if !modified {
return xerrors.Errorf("sector %v already pre-committed", precommit.Info.SectorNumber)
}
}
st.PreCommittedSectors, err = precommitted.Root()
return err
}
func (st *State) GetPrecommittedSector(store adt.Store, sectorNo abi.SectorNumber) (*SectorPreCommitOnChainInfo, bool, error) {
precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, false, err
}
var info SectorPreCommitOnChainInfo
found, err := precommitted.Get(SectorKey(sectorNo), &info)
if err != nil {
return nil, false, xerrors.Errorf("failed to load precommitment for %v: %w", sectorNo, err)
}
return &info, found, nil
}
// Load all precommits or fail trying
func (st *State) GetAllPrecommittedSectors(store adt.Store, sectorNos bitfield.BitField) ([]*SectorPreCommitOnChainInfo, error) {
precommits := make([]*SectorPreCommitOnChainInfo, 0)
precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, err
}
if err := sectorNos.ForEach(func(sectorNo uint64) error {
if sectorNo > abi.MaxSectorNumber {
return xc.ErrIllegalArgument.Wrapf("sector number greater than maximum")
}
var info SectorPreCommitOnChainInfo
found, err := precommitted.Get(SectorKey(abi.SectorNumber(sectorNo)), &info)
if err != nil {
return err
}
if !found {
return xc.ErrNotFound.Wrapf("sector %d not found", sectorNo)
}
precommits = append(precommits, &info)
return nil
}); err != nil {
return nil, err
}
return precommits, nil
}
// This method gets and returns the requested pre-committed sectors, skipping
// missing sectors.
func (st *State) FindPrecommittedSectors(store adt.Store, sectorNos ...abi.SectorNumber) ([]*SectorPreCommitOnChainInfo, error) {
precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, err
}
result := make([]*SectorPreCommitOnChainInfo, 0, len(sectorNos))
for _, sectorNo := range sectorNos {
var info SectorPreCommitOnChainInfo
found, err := precommitted.Get(SectorKey(sectorNo), &info)
if err != nil {
return nil, xerrors.Errorf("failed to load precommitment for %v: %w", sectorNo, err)
}
if !found {
// TODO #564 log: "failed to get precommitted sector on sector %d, dropping from prove commit set"
continue
}
result = append(result, &info)
}
return result, nil
}
func (st *State) DeletePrecommittedSectors(store adt.Store, sectorNos ...abi.SectorNumber) error {
precommitted, err := adt.AsMap(store, st.PreCommittedSectors, builtin.DefaultHamtBitwidth)
if err != nil {
return err
}
for _, sectorNo := range sectorNos {
err = precommitted.Delete(SectorKey(sectorNo))
if err != nil {
return xerrors.Errorf("failed to delete precommitment for %v: %w", sectorNo, err)
}
}
st.PreCommittedSectors, err = precommitted.Root()
return err
}
func (st *State) HasSectorNo(store adt.Store, sectorNo abi.SectorNumber) (bool, error) {
sectors, err := LoadSectors(store, st.Sectors)
if err != nil {
return false, err
}
_, found, err := sectors.Get(sectorNo)
if err != nil {
return false, xerrors.Errorf("failed to get sector %v: %w", sectorNo, err)
}
return found, nil
}
func (st *State) PutSectors(store adt.Store, newSectors ...*SectorOnChainInfo) error {
sectors, err := LoadSectors(store, st.Sectors)
if err != nil {
return xerrors.Errorf("failed to load sectors: %w", err)
}
err = sectors.Store(newSectors...)
if err != nil {
return err
}
st.Sectors, err = sectors.Root()
if err != nil {
return xerrors.Errorf("failed to persist sectors: %w", err)
}
return nil
}
func (st *State) GetSector(store adt.Store, sectorNo abi.SectorNumber) (*SectorOnChainInfo, bool, error) {
sectors, err := LoadSectors(store, st.Sectors)
if err != nil {
return nil, false, err
}
return sectors.Get(sectorNo)
}
func (st *State) DeleteSectors(store adt.Store, sectorNos bitfield.BitField) error {
sectors, err := LoadSectors(store, st.Sectors)
if err != nil {
return err
}
err = sectorNos.ForEach(func(sectorNo uint64) error {
if err = sectors.Delete(sectorNo); err != nil {
return xerrors.Errorf("failed to delete sector %v: %w", sectorNos, err)
}
return nil
})
if err != nil {
return err
}
st.Sectors, err = sectors.Root()
return err
}
// Iterates sectors.
// The pointer provided to the callback is not safe for re-use. Copy the pointed-to value in full to hold a reference.
func (st *State) ForEachSector(store adt.Store, f func(*SectorOnChainInfo)) error {
sectors, err := LoadSectors(store, st.Sectors)
if err != nil {
return err
}
var sector SectorOnChainInfo
return sectors.ForEach(§or, func(idx int64) error {
f(§or)
return nil
})
}
func (st *State) FindSector(store adt.Store, sno abi.SectorNumber) (uint64, uint64, error) {
deadlines, err := st.LoadDeadlines(store)
if err != nil {
return 0, 0, err
}
return FindSector(store, deadlines, sno)
}
// Assign new sectors to deadlines.
func (st *State) AssignSectorsToDeadlines(
store adt.Store, currentEpoch abi.ChainEpoch, sectors []*SectorOnChainInfo, partitionSize uint64, sectorSize abi.SectorSize,
) error {
deadlines, err := st.LoadDeadlines(store)
if err != nil {
return err
}
// Sort sectors by number to get better runs in partition bitfields.
sort.Slice(sectors, func(i, j int) bool {
return sectors[i].SectorNumber < sectors[j].SectorNumber
})
var deadlineArr [WPoStPeriodDeadlines]*Deadline
if err = deadlines.ForEach(store, func(idx uint64, dl *Deadline) error {
// Skip deadlines that aren't currently mutable.
if deadlineIsMutable(st.CurrentProvingPeriodStart(currentEpoch), idx, currentEpoch) {
deadlineArr[int(idx)] = dl
}
return nil
}); err != nil {
return err
}
deadlineToSectors, err := assignDeadlines(MaxPartitionsPerDeadline, partitionSize, &deadlineArr, sectors)
if err != nil {
return xerrors.Errorf("failed to assign sectors to deadlines: %w", err)
}
for dlIdx, deadlineSectors := range deadlineToSectors {
if len(deadlineSectors) == 0 {
continue
}
quant := st.QuantSpecForDeadline(uint64(dlIdx))
dl := deadlineArr[dlIdx]
// The power returned from AddSectors is ignored because it's not activated (proven) yet.
proven := false
if _, err := dl.AddSectors(store, partitionSize, proven, deadlineSectors, sectorSize, quant); err != nil {
return err
}
if err := deadlines.UpdateDeadline(store, uint64(dlIdx), dl); err != nil {
return err
}
}
if err := st.SaveDeadlines(store, deadlines); err != nil {
return err
}
return nil
}
// Pops up to max early terminated sectors from all deadlines.
//
// Returns hasMore if we still have more early terminations to process.
func (st *State) PopEarlyTerminations(store adt.Store, maxPartitions, maxSectors uint64) (result TerminationResult, hasMore bool, err error) {
stopErr := xerrors.New("stop error")
// Anything to do? This lets us avoid loading the deadlines if there's nothing to do.
noEarlyTerminations, err := st.EarlyTerminations.IsEmpty()
if err != nil {
return TerminationResult{}, false, xerrors.Errorf("failed to count deadlines with early terminations: %w", err)
} else if noEarlyTerminations {
return TerminationResult{}, false, nil
}
// Load deadlines
deadlines, err := st.LoadDeadlines(store)
if err != nil {
return TerminationResult{}, false, xerrors.Errorf("failed to load deadlines: %w", err)
}
// Process early terminations.
if err = st.EarlyTerminations.ForEach(func(dlIdx uint64) error {
// Load deadline + partitions.
dl, err := deadlines.LoadDeadline(store, dlIdx)
if err != nil {
return xerrors.Errorf("failed to load deadline %d: %w", dlIdx, err)
}
deadlineResult, more, err := dl.PopEarlyTerminations(store, maxPartitions-result.PartitionsProcessed, maxSectors-result.SectorsProcessed)
if err != nil {
return xerrors.Errorf("failed to pop early terminations for deadline %d: %w", dlIdx, err)
}
err = result.Add(deadlineResult)
if err != nil {
return xerrors.Errorf("failed to merge result from popping early terminations from deadline: %w", err)
}
if !more {
// safe to do while iterating.
st.EarlyTerminations.Unset(dlIdx)
}
// Save the deadline
err = deadlines.UpdateDeadline(store, dlIdx, dl)
if err != nil {
return xerrors.Errorf("failed to store deadline %d: %w", dlIdx, err)
}
if result.BelowLimit(maxPartitions, maxSectors) {
return nil
}
return stopErr
}); err != nil && err != stopErr {
return TerminationResult{}, false, xerrors.Errorf("failed to walk early terminations bitfield for deadlines: %w", err)
}
// Save back the deadlines.
err = st.SaveDeadlines(store, deadlines)
if err != nil {
return TerminationResult{}, false, xerrors.Errorf("failed to save deadlines: %w", err)
}
// Ok, check to see if we've handled all early terminations.
noEarlyTerminations, err = st.EarlyTerminations.IsEmpty()
if err != nil {
return TerminationResult{}, false, xerrors.Errorf("failed to count remaining early terminations deadlines")
}
return result, !noEarlyTerminations, nil
}
// Returns an error if the target sector cannot be found, or some other bad state is reached.
// Returns false if the target sector is faulty, terminated, or unproven
// Returns true otherwise
func (st *State) CheckSectorActive(store adt.Store, dlIdx, pIdx uint64, sector abi.SectorNumber, requireProven bool) (bool, error) {
dls, err := st.LoadDeadlines(store)
if err != nil {
return false, err
}
dl, err := dls.LoadDeadline(store, dlIdx)
if err != nil {
return false, err
}
partition, err := dl.LoadPartition(store, pIdx)
if err != nil {
return false, err
}
if exists, err := partition.Sectors.IsSet(uint64(sector)); err != nil {
return false, xc.ErrIllegalState.Wrapf("failed to decode sectors bitfield (deadline %d, partition %d): %w", dlIdx, pIdx, err)
} else if !exists {
return false, xc.ErrNotFound.Wrapf("sector %d not a member of partition %d, deadline %d", sector, pIdx, dlIdx)
}
if faulty, err := partition.Faults.IsSet(uint64(sector)); err != nil {
return false, xc.ErrIllegalState.Wrapf("failed to decode faults bitfield (deadline %d, partition %d): %w", dlIdx, pIdx, err)
} else if faulty {
return false, nil
}
if terminated, err := partition.Terminated.IsSet(uint64(sector)); err != nil {
return false, xc.ErrIllegalState.Wrapf("failed to decode terminated bitfield (deadline %d, partition %d): %w", dlIdx, pIdx, err)
} else if terminated {
return false, nil
}
if unproven, err := partition.Unproven.IsSet(uint64(sector)); err != nil {
return false, xc.ErrIllegalState.Wrapf("failed to decode unproven bitfield (deadline %d, partition %d): %w", dlIdx, pIdx, err)
} else if unproven && requireProven {
return false, nil
}
return true, nil
}
// Loads sector info for a sequence of sectors.
func (st *State) LoadSectorInfos(store adt.Store, sectors bitfield.BitField) ([]*SectorOnChainInfo, error) {
sectorsArr, err := LoadSectors(store, st.Sectors)
if err != nil {
return nil, err
}
return sectorsArr.Load(sectors)
}
func (st *State) LoadDeadlines(store adt.Store) (*Deadlines, error) {
var deadlines Deadlines
if err := store.Get(store.Context(), st.Deadlines, &deadlines); err != nil {
return nil, xc.ErrIllegalState.Wrapf("failed to load deadlines (%s): %w", st.Deadlines, err)
}
return &deadlines, nil
}
func (st *State) SaveDeadlines(store adt.Store, deadlines *Deadlines) error {
c, err := store.Put(store.Context(), deadlines)
if err != nil {
return err
}
st.Deadlines = c
return nil
}
// LoadVestingFunds loads the vesting funds table from the store
func (st *State) LoadVestingFunds(store adt.Store) (*VestingFunds, error) {
var funds VestingFunds
if err := store.Get(store.Context(), st.VestingFunds, &funds); err != nil {
return nil, xerrors.Errorf("failed to load vesting funds (%s): %w", st.VestingFunds, err)
}
return &funds, nil
}
// SaveVestingFunds saves the vesting table to the store
func (st *State) SaveVestingFunds(store adt.Store, funds *VestingFunds) error {
c, err := store.Put(store.Context(), funds)
if err != nil {
return err
}
st.VestingFunds = c
return nil
}
// Return true when the miner actor needs to continue scheduling deadline crons
func (st *State) ContinueDeadlineCron() bool {
return !st.PreCommitDeposits.IsZero() ||
!st.InitialPledge.IsZero() ||
!st.LockedFunds.IsZero()
}
//
// Funds and vesting
//
func (st *State) AddPreCommitDeposit(amount abi.TokenAmount) error {
newTotal := big.Add(st.PreCommitDeposits, amount)
if newTotal.LessThan(big.Zero()) {
return xerrors.Errorf("negative pre-commit deposit %v after adding %v to prior %v", newTotal, amount, st.PreCommitDeposits)
}
st.PreCommitDeposits = newTotal
return nil
}
func (st *State) AddInitialPledge(amount abi.TokenAmount) error {
newTotal := big.Add(st.InitialPledge, amount)
if newTotal.LessThan(big.Zero()) {
return xerrors.Errorf("negative initial pledge %v after adding %v to prior %v", newTotal, amount, st.InitialPledge)
}
st.InitialPledge = newTotal
return nil
}
// AddLockedFunds first vests and unlocks the vested funds AND then locks the given funds in the vesting table.
func (st *State) AddLockedFunds(store adt.Store, currEpoch abi.ChainEpoch, vestingSum abi.TokenAmount, spec *VestSpec) (vested abi.TokenAmount, err error) {
if vestingSum.LessThan(big.Zero()) {
return big.Zero(), xerrors.Errorf("negative amount to lock %s", vestingSum)
}
vestingFunds, err := st.LoadVestingFunds(store)
if err != nil {
return big.Zero(), xerrors.Errorf("failed to load vesting funds: %w", err)
}
// unlock vested funds first
amountUnlocked := vestingFunds.unlockVestedFunds(currEpoch)
st.LockedFunds = big.Sub(st.LockedFunds, amountUnlocked)
if st.LockedFunds.LessThan(big.Zero()) {
return big.Zero(), xerrors.Errorf("negative locked funds %v after unlocking %v", st.LockedFunds, amountUnlocked)
}
// add locked funds now
vestingFunds.addLockedFunds(currEpoch, vestingSum, st.ProvingPeriodStart, spec)
st.LockedFunds = big.Add(st.LockedFunds, vestingSum)
// save the updated vesting table state
if err := st.SaveVestingFunds(store, vestingFunds); err != nil {
return big.Zero(), xerrors.Errorf("failed to save vesting funds: %w", err)
}
return amountUnlocked, nil
}
// ApplyPenalty adds the provided penalty to fee debt.
func (st *State) ApplyPenalty(penalty abi.TokenAmount) error {
if penalty.LessThan(big.Zero()) {
return xerrors.Errorf("applying negative penalty %v not allowed", penalty)
}
st.FeeDebt = big.Add(st.FeeDebt, penalty)
return nil
}
// Draws from vesting table and unlocked funds to repay up to the fee debt.
// Returns the amount unlocked from the vesting table and the amount taken from
// current balance. If the fee debt exceeds the total amount available for repayment
// the fee debt field is updated to track the remaining debt. Otherwise it is set to zero.
func (st *State) RepayPartialDebtInPriorityOrder(store adt.Store, currEpoch abi.ChainEpoch, currBalance abi.TokenAmount) (fromVesting abi.TokenAmount, fromBalance abi.TokenAmount, err error) {
unlockedBalance, err := st.GetUnlockedBalance(currBalance)
if err != nil {
return big.Zero(), big.Zero(), err
}
// Pay fee debt with locked funds first
fromVesting, err = st.UnlockUnvestedFunds(store, currEpoch, st.FeeDebt)
if err != nil {
return abi.NewTokenAmount(0), abi.NewTokenAmount(0), err
}
// We should never unlock more than the debt we need to repay
if fromVesting.GreaterThan(st.FeeDebt) {
return big.Zero(), big.Zero(), xerrors.Errorf("unlocked more vesting funds %v than required for debt %v", fromVesting, st.FeeDebt)
}
st.FeeDebt = big.Sub(st.FeeDebt, fromVesting)
fromBalance = big.Min(unlockedBalance, st.FeeDebt)
st.FeeDebt = big.Sub(st.FeeDebt, fromBalance)
return fromVesting, fromBalance, nil
}
// Repays the full miner actor fee debt. Returns the amount that must be
// burnt and an error if there are not sufficient funds to cover repayment.
// Miner state repays from unlocked funds and fails if unlocked funds are insufficient to cover fee debt.
// FeeDebt will be zero after a successful call.
func (st *State) repayDebts(currBalance abi.TokenAmount) (abi.TokenAmount, error) {
unlockedBalance, err := st.GetUnlockedBalance(currBalance)
if err != nil {
return big.Zero(), err
}
if unlockedBalance.LessThan(st.FeeDebt) {
return big.Zero(), xc.ErrInsufficientFunds.Wrapf("unlocked balance can not repay fee debt (%v < %v)", unlockedBalance, st.FeeDebt)
}
debtToRepay := st.FeeDebt
st.FeeDebt = big.Zero()
return debtToRepay, nil
}
// Unlocks an amount of funds that have *not yet vested*, if possible.
// The soonest-vesting entries are unlocked first.
// Returns the amount actually unlocked.
func (st *State) UnlockUnvestedFunds(store adt.Store, currEpoch abi.ChainEpoch, target abi.TokenAmount) (abi.TokenAmount, error) {
// Nothing to unlock, don't bother loading any state.
if target.IsZero() || st.LockedFunds.IsZero() {
return big.Zero(), nil
}
vestingFunds, err := st.LoadVestingFunds(store)
if err != nil {
return big.Zero(), xerrors.Errorf("failed tp load vesting funds: %w", err)
}
amountUnlocked := vestingFunds.unlockUnvestedFunds(currEpoch, target)
st.LockedFunds = big.Sub(st.LockedFunds, amountUnlocked)
if st.LockedFunds.LessThan(big.Zero()) {
return big.Zero(), xerrors.Errorf("negative locked funds %v after unlocking %v", st.LockedFunds, amountUnlocked)
}
if err := st.SaveVestingFunds(store, vestingFunds); err != nil {
return big.Zero(), xerrors.Errorf("failed to save vesting funds: %w", err)
}
return amountUnlocked, nil
}
// Unlocks all vesting funds that have vested before the provided epoch.
// Returns the amount unlocked.
func (st *State) UnlockVestedFunds(store adt.Store, currEpoch abi.ChainEpoch) (abi.TokenAmount, error) {
// Short-circuit to avoid loading vesting funds if we don't have any.
if st.LockedFunds.IsZero() {
return big.Zero(), nil
}
vestingFunds, err := st.LoadVestingFunds(store)
if err != nil {
return big.Zero(), xerrors.Errorf("failed to load vesting funds: %w", err)
}
amountUnlocked := vestingFunds.unlockVestedFunds(currEpoch)
st.LockedFunds = big.Sub(st.LockedFunds, amountUnlocked)
if st.LockedFunds.LessThan(big.Zero()) {
return big.Zero(), xerrors.Errorf("vesting cause locked funds negative %v", st.LockedFunds)
}
err = st.SaveVestingFunds(store, vestingFunds)
if err != nil {
return big.Zero(), xerrors.Errorf("failed to save vesing funds: %w", err)
}
return amountUnlocked, nil
}
// CheckVestedFunds returns the amount of vested funds that have vested before the provided epoch.
func (st *State) CheckVestedFunds(store adt.Store, currEpoch abi.ChainEpoch) (abi.TokenAmount, error) {
vestingFunds, err := st.LoadVestingFunds(store)
if err != nil {
return big.Zero(), xerrors.Errorf("failed to load vesting funds: %w", err)
}
amountVested := abi.NewTokenAmount(0)
for i := range vestingFunds.Funds {
vf := vestingFunds.Funds[i]
epoch := vf.Epoch
amount := vf.Amount
if epoch >= currEpoch {
break
}
amountVested = big.Add(amountVested, amount)
}
return amountVested, nil
}
// Unclaimed funds that are not locked -- includes free funds and does not
// account for fee debt. Always greater than or equal to zero
func (st *State) GetUnlockedBalance(actorBalance abi.TokenAmount) (abi.TokenAmount, error) {
unlockedBalance := big.Subtract(actorBalance, st.LockedFunds, st.PreCommitDeposits, st.InitialPledge)
if unlockedBalance.LessThan(big.Zero()) {
return big.Zero(), xerrors.Errorf("negative unlocked balance %v", unlockedBalance)
}
return unlockedBalance, nil
}
// Unclaimed funds. Actor balance - (locked funds, precommit deposit, initial pledge, fee debt)
// Can go negative if the miner is in IP debt
func (st *State) GetAvailableBalance(actorBalance abi.TokenAmount) (abi.TokenAmount, error) {
unlockedBalance, err := st.GetUnlockedBalance(actorBalance)
if err != nil {
return big.Zero(), err
}
return big.Subtract(unlockedBalance, st.FeeDebt), nil
}
func (st *State) CheckBalanceInvariants(balance abi.TokenAmount) error {
if st.PreCommitDeposits.LessThan(big.Zero()) {
return xerrors.Errorf("pre-commit deposit is negative: %v", st.PreCommitDeposits)
}
if st.LockedFunds.LessThan(big.Zero()) {
return xerrors.Errorf("locked funds is negative: %v", st.LockedFunds)
}
if st.InitialPledge.LessThan(big.Zero()) {
return xerrors.Errorf("initial pledge is negative: %v", st.InitialPledge)
}
if st.FeeDebt.LessThan(big.Zero()) {
return xerrors.Errorf("fee debt is negative: %v", st.FeeDebt)
}
minBalance := big.Sum(st.PreCommitDeposits, st.LockedFunds, st.InitialPledge)
if balance.LessThan(minBalance) {
return xerrors.Errorf("balance %v below required %v", balance, minBalance)
}
return nil
}
func (st *State) IsDebtFree() bool {
return st.FeeDebt.LessThanEqual(big.Zero())
}
// pre-commit clean up
func (st *State) QuantSpecEveryDeadline() builtin.QuantSpec {
return builtin.NewQuantSpec(WPoStChallengeWindow, st.ProvingPeriodStart)
}
func (st *State) AddPreCommitCleanUps(store adt.Store, cleanUpEvents map[abi.ChainEpoch][]uint64) error {
// Load BitField Queue for sector expiry
quant := st.QuantSpecEveryDeadline()
queue, err := LoadBitfieldQueue(store, st.PreCommittedSectorsCleanUp, quant, PrecommitCleanUpAmtBitwidth)
if err != nil {
return xerrors.Errorf("failed to load pre-commit clean up queue: %w", err)
}