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
/
deadline_state.go
1309 lines (1119 loc) · 45.5 KB
/
deadline_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 (
"bytes"
"errors"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
xc "github.com/filecoin-project/go-state-types/exitcode"
"github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/v8/actors/builtin"
"github.com/filecoin-project/specs-actors/v8/actors/runtime/proof"
"github.com/filecoin-project/specs-actors/v8/actors/util/adt"
)
// Deadlines contains Deadline objects, describing the sectors due at the given
// deadline and their state (faulty, terminated, recovering, etc.).
type Deadlines struct {
// Note: we could inline part of the deadline struct (e.g., active/assigned sectors)
// to make new sector assignment cheaper. At the moment, assigning a sector requires
// loading all deadlines to figure out where best to assign new sectors.
Due [WPoStPeriodDeadlines]cid.Cid // []Deadline
}
// Deadline holds the state for all sectors due at a specific deadline.
type Deadline struct {
// Partitions in this deadline, in order.
// The keys of this AMT are always sequential integers beginning with zero.
Partitions cid.Cid // AMT[PartitionNumber]Partition
// Maps epochs to partitions that _may_ have sectors that expire in or
// before that epoch, either on-time or early as faults.
// Keys are quantized to final epochs in each proving deadline.
//
// NOTE: Partitions MUST NOT be removed from this queue (until the
// associated epoch has passed) even if they no longer have sectors
// expiring at that epoch. Sectors expiring at this epoch may later be
// recovered, and this queue will not be updated at that time.
ExpirationsEpochs cid.Cid // AMT[ChainEpoch]BitField
// Partitions that have been proved by window PoSts so far during the
// current challenge window.
// NOTE: This bitfield includes both partitions whose proofs
// were optimistically accepted and stored in
// OptimisticPoStSubmissions, and those whose proofs were
// verified on-chain.
PartitionsPoSted bitfield.BitField
// Partitions with sectors that terminated early.
EarlyTerminations bitfield.BitField
// The number of non-terminated sectors in this deadline (incl faulty).
LiveSectors uint64
// The total number of sectors in this deadline (incl dead).
TotalSectors uint64
// Memoized sum of faulty power in partitions.
FaultyPower PowerPair
// AMT of optimistically accepted WindowPoSt proofs, submitted during
// the current challenge window. At the end of the challenge window,
// this AMT will be moved to OptimisticPoStSubmissionsSnapshot. WindowPoSt proofs
// verified on-chain do not appear in this AMT.
OptimisticPoStSubmissions cid.Cid // AMT[]WindowedPoSt
// Snapshot of the miner's sectors AMT at the end of the previous challenge
// window for this deadline.
SectorsSnapshot cid.Cid
// Snapshot of partition state at the end of the previous challenge
// window for this deadline.
PartitionsSnapshot cid.Cid
// Snapshot of the proofs submitted by the end of the previous challenge
// window for this deadline.
//
// These proofs may be disputed via DisputeWindowedPoSt. Successfully
// disputed window PoSts are removed from the snapshot.
OptimisticPoStSubmissionsSnapshot cid.Cid
}
type WindowedPoSt struct {
// Partitions proved by this WindowedPoSt.
Partitions bitfield.BitField
// Array of proofs, one per distinct registered proof type present in
// the sectors being proven. In the usual case of a single proof type,
// this array will always have a single element (independent of number
// of partitions).
Proofs []proof.PoStProof
}
// Bitwidth of AMTs determined empirically from mutation patterns and projections of mainnet data.
const DeadlinePartitionsAmtBitwidth = 3 // Usually a small array
const DeadlineExpirationAmtBitwidth = 5
// Given that 4 partitions can be proven in one post, this AMT's height will
// only exceed the partition AMT's height at ~0.75EiB of storage.
const DeadlineOptimisticPoStSubmissionsAmtBitwidth = 2
//
// Deadlines (plural)
//
func ConstructDeadlines(emptyDeadlineCid cid.Cid) *Deadlines {
d := new(Deadlines)
for i := range d.Due {
d.Due[i] = emptyDeadlineCid
}
return d
}
func (d *Deadlines) LoadDeadline(store adt.Store, dlIdx uint64) (*Deadline, error) {
if dlIdx >= uint64(len(d.Due)) {
return nil, xc.ErrIllegalArgument.Wrapf("invalid deadline %d", dlIdx)
}
deadline := new(Deadline)
err := store.Get(store.Context(), d.Due[dlIdx], deadline)
if err != nil {
return nil, xc.ErrIllegalState.Wrapf("failed to lookup deadline %d: %w", dlIdx, err)
}
return deadline, nil
}
func (d *Deadlines) ForEach(store adt.Store, cb func(dlIdx uint64, dl *Deadline) error) error {
for dlIdx := range d.Due {
dl, err := d.LoadDeadline(store, uint64(dlIdx))
if err != nil {
return err
}
err = cb(uint64(dlIdx), dl)
if err != nil {
return err
}
}
return nil
}
func (d *Deadlines) UpdateDeadline(store adt.Store, dlIdx uint64, deadline *Deadline) error {
if dlIdx >= uint64(len(d.Due)) {
return xerrors.Errorf("invalid deadline %d", dlIdx)
}
if err := deadline.ValidateState(); err != nil {
return err
}
dlCid, err := store.Put(store.Context(), deadline)
if err != nil {
return err
}
d.Due[dlIdx] = dlCid
return nil
}
//
// Deadline (singular)
//
func ConstructDeadline(store adt.Store) (*Deadline, error) {
emptyPartitionsArrayCid, err := adt.StoreEmptyArray(store, DeadlinePartitionsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty partitions array: %w", err)
}
emptyDeadlineExpirationArrayCid, err := adt.StoreEmptyArray(store, DeadlineExpirationAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty deadline expiration array: %w", err)
}
emptySectorsSnapshotArrayCid, err := adt.StoreEmptyArray(store, SectorsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty sectors snapshot array: %w", err)
}
emptyPoStSubmissionsArrayCid, err := adt.StoreEmptyArray(store, DeadlineOptimisticPoStSubmissionsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to construct empty proofs array: %w", err)
}
return &Deadline{
Partitions: emptyPartitionsArrayCid,
ExpirationsEpochs: emptyDeadlineExpirationArrayCid,
EarlyTerminations: bitfield.New(),
LiveSectors: 0,
TotalSectors: 0,
FaultyPower: NewPowerPairZero(),
PartitionsPoSted: bitfield.New(),
OptimisticPoStSubmissions: emptyPoStSubmissionsArrayCid,
PartitionsSnapshot: emptyPartitionsArrayCid,
SectorsSnapshot: emptySectorsSnapshotArrayCid,
OptimisticPoStSubmissionsSnapshot: emptyPoStSubmissionsArrayCid,
}, nil
}
func (d *Deadline) PartitionsArray(store adt.Store) (*adt.Array, error) {
arr, err := adt.AsArray(store, d.Partitions, DeadlinePartitionsAmtBitwidth)
if err != nil {
return nil, xc.ErrIllegalState.Wrapf("failed to load partitions: %w", err)
}
return arr, nil
}
func (d *Deadline) OptimisticProofsArray(store adt.Store) (*adt.Array, error) {
arr, err := adt.AsArray(store, d.OptimisticPoStSubmissions, DeadlineOptimisticPoStSubmissionsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to load proofs: %w", err)
}
return arr, nil
}
func (d *Deadline) SectorsSnapshotArray(store adt.Store) (*adt.Array, error) {
arr, err := adt.AsArray(store, d.SectorsSnapshot, SectorsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to load sectors snapshot: %w", err)
}
return arr, nil
}
func (d *Deadline) PartitionsSnapshotArray(store adt.Store) (*adt.Array, error) {
arr, err := adt.AsArray(store, d.PartitionsSnapshot, DeadlinePartitionsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to load partitions snapshot: %w", err)
}
return arr, nil
}
func (d *Deadline) OptimisticProofsSnapshotArray(store adt.Store) (*adt.Array, error) {
arr, err := adt.AsArray(store, d.OptimisticPoStSubmissionsSnapshot, DeadlineOptimisticPoStSubmissionsAmtBitwidth)
if err != nil {
return nil, xerrors.Errorf("failed to load proofs snapshot: %w", err)
}
return arr, nil
}
func (d *Deadline) LoadPartition(store adt.Store, partIdx uint64) (*Partition, error) {
partitions, err := d.PartitionsArray(store)
if err != nil {
return nil, err
}
var partition Partition
found, err := partitions.Get(partIdx, &partition)
if err != nil {
return nil, xc.ErrIllegalState.Wrapf("failed to lookup partition %d: %w", partIdx, err)
}
if !found {
return nil, xc.ErrNotFound.Wrapf("no partition %d", partIdx)
}
return &partition, nil
}
func (d *Deadline) LoadPartitionSnapshot(store adt.Store, partIdx uint64) (*Partition, error) {
partitions, err := d.PartitionsSnapshotArray(store)
if err != nil {
return nil, err
}
var partition Partition
found, err := partitions.Get(partIdx, &partition)
if err != nil {
return nil, xerrors.Errorf("failed to lookup partition %d: %w", partIdx, err)
}
if !found {
return nil, xc.ErrNotFound.Wrapf("no partition %d", partIdx)
}
return &partition, nil
}
// Adds some partition numbers to the set expiring at an epoch.
func (d *Deadline) AddExpirationPartitions(store adt.Store, expirationEpoch abi.ChainEpoch, partitions []uint64, quant builtin.QuantSpec) error {
// Avoid doing any work if there's nothing to reschedule.
if len(partitions) == 0 {
return nil
}
queue, err := LoadBitfieldQueue(store, d.ExpirationsEpochs, quant, DeadlineExpirationAmtBitwidth)
if err != nil {
return xerrors.Errorf("failed to load expiration queue: %w", err)
}
if err = queue.AddToQueueValues(expirationEpoch, partitions...); err != nil {
return xerrors.Errorf("failed to mutate expiration queue: %w", err)
}
if d.ExpirationsEpochs, err = queue.Root(); err != nil {
return xerrors.Errorf("failed to save expiration queue: %w", err)
}
return nil
}
// PopExpiredSectors terminates expired sectors from all partitions.
// Returns the expired sector aggregates.
func (dl *Deadline) PopExpiredSectors(store adt.Store, until abi.ChainEpoch, quant builtin.QuantSpec) (*ExpirationSet, error) {
expiredPartitions, modified, err := dl.popExpiredPartitions(store, until, quant)
if err != nil {
return nil, err
} else if !modified {
return NewExpirationSetEmpty(), nil // nothing to do.
}
partitions, err := dl.PartitionsArray(store)
if err != nil {
return nil, err
}
var onTimeSectors []bitfield.BitField
var earlySectors []bitfield.BitField
allOnTimePledge := big.Zero()
allActivePower := NewPowerPairZero()
allFaultyPower := NewPowerPairZero()
var partitionsWithEarlyTerminations []uint64
// For each partition with an expiry, remove and collect expirations from the partition queue.
if err = expiredPartitions.ForEach(func(partIdx uint64) error {
var partition Partition
if found, err := partitions.Get(partIdx, &partition); err != nil {
return err
} else if !found {
return xerrors.Errorf("missing expected partition %d", partIdx)
}
partExpiration, err := partition.PopExpiredSectors(store, until, quant)
if err != nil {
return xerrors.Errorf("failed to pop expired sectors from partition %d: %w", partIdx, err)
}
onTimeSectors = append(onTimeSectors, partExpiration.OnTimeSectors)
earlySectors = append(earlySectors, partExpiration.EarlySectors)
allActivePower = allActivePower.Add(partExpiration.ActivePower)
allFaultyPower = allFaultyPower.Add(partExpiration.FaultyPower)
allOnTimePledge = big.Add(allOnTimePledge, partExpiration.OnTimePledge)
if empty, err := partExpiration.EarlySectors.IsEmpty(); err != nil {
return xerrors.Errorf("failed to count early expirations from partition %d: %w", partIdx, err)
} else if !empty {
partitionsWithEarlyTerminations = append(partitionsWithEarlyTerminations, partIdx)
}
return partitions.Set(partIdx, &partition)
}); err != nil {
return nil, err
}
if dl.Partitions, err = partitions.Root(); err != nil {
return nil, err
}
// Update early expiration bitmap.
for _, partIdx := range partitionsWithEarlyTerminations {
dl.EarlyTerminations.Set(partIdx)
}
allOnTimeSectors, err := bitfield.MultiMerge(onTimeSectors...)
if err != nil {
return nil, err
}
allEarlySectors, err := bitfield.MultiMerge(earlySectors...)
if err != nil {
return nil, err
}
// Update live sector count.
onTimeCount, err := allOnTimeSectors.Count()
if err != nil {
return nil, xerrors.Errorf("failed to count on-time expired sectors: %w", err)
}
earlyCount, err := allEarlySectors.Count()
if err != nil {
return nil, xerrors.Errorf("failed to count early expired sectors: %w", err)
}
dl.LiveSectors -= onTimeCount + earlyCount
dl.FaultyPower = dl.FaultyPower.Sub(allFaultyPower)
return NewExpirationSet(allOnTimeSectors, allEarlySectors, allOnTimePledge, allActivePower, allFaultyPower), nil
}
// Adds sectors to a deadline. It's the caller's responsibility to make sure
// that this deadline isn't currently "open" (i.e., being proved at this point
// in time).
// The sectors are assumed to be non-faulty.
// Returns the power of the added sectors (which is active yet if proven=false).
func (dl *Deadline) AddSectors(
store adt.Store, partitionSize uint64, proven bool, sectors []*SectorOnChainInfo,
ssize abi.SectorSize, quant builtin.QuantSpec,
) (PowerPair, error) {
totalPower := NewPowerPairZero()
if len(sectors) == 0 {
return totalPower, nil
}
// First update partitions, consuming the sectors
partitionDeadlineUpdates := make(map[abi.ChainEpoch][]uint64)
dl.LiveSectors += uint64(len(sectors))
dl.TotalSectors += uint64(len(sectors))
{
partitions, err := dl.PartitionsArray(store)
if err != nil {
return NewPowerPairZero(), err
}
partIdx := partitions.Length()
if partIdx > 0 {
partIdx -= 1 // try filling up the last partition first.
}
for ; len(sectors) > 0; partIdx++ {
// Get/create partition to update.
partition := new(Partition)
if found, err := partitions.Get(partIdx, partition); err != nil {
return NewPowerPairZero(), err
} else if !found {
// This case will usually happen zero times.
// It would require adding more than a full partition in one go to happen more than once.
partition, err = ConstructPartition(store)
if err != nil {
return NewPowerPairZero(), err
}
}
// Figure out which (if any) sectors we want to add to this partition.
sectorCount, err := partition.Sectors.Count()
if err != nil {
return NewPowerPairZero(), err
}
if sectorCount >= partitionSize {
continue
}
size := min64(partitionSize-sectorCount, uint64(len(sectors)))
partitionNewSectors := sectors[:size]
sectors = sectors[size:]
// Add sectors to partition.
partitionPower, err := partition.AddSectors(store, proven, partitionNewSectors, ssize, quant)
if err != nil {
return NewPowerPairZero(), err
}
totalPower = totalPower.Add(partitionPower)
// Save partition back.
err = partitions.Set(partIdx, partition)
if err != nil {
return NewPowerPairZero(), err
}
// Record deadline -> partition mapping so we can later update the deadlines.
for _, sector := range partitionNewSectors {
partitionUpdate := partitionDeadlineUpdates[sector.Expiration]
// Record each new partition once.
if len(partitionUpdate) > 0 && partitionUpdate[len(partitionUpdate)-1] == partIdx {
continue
}
partitionDeadlineUpdates[sector.Expiration] = append(partitionUpdate, partIdx)
}
}
// Save partitions back.
dl.Partitions, err = partitions.Root()
if err != nil {
return NewPowerPairZero(), err
}
}
// Next, update the expiration queue.
{
deadlineExpirations, err := LoadBitfieldQueue(store, dl.ExpirationsEpochs, quant, DeadlineExpirationAmtBitwidth)
if err != nil {
return NewPowerPairZero(), xerrors.Errorf("failed to load expiration epochs: %w", err)
}
if err = deadlineExpirations.AddManyToQueueValues(partitionDeadlineUpdates); err != nil {
return NewPowerPairZero(), xerrors.Errorf("failed to add expirations for new deadlines: %w", err)
}
if dl.ExpirationsEpochs, err = deadlineExpirations.Root(); err != nil {
return NewPowerPairZero(), err
}
}
return totalPower, nil
}
func (dl *Deadline) PopEarlyTerminations(store adt.Store, maxPartitions, maxSectors uint64) (result TerminationResult, hasMore bool, err error) {
stopErr := errors.New("stop error")
partitions, err := dl.PartitionsArray(store)
if err != nil {
return TerminationResult{}, false, err
}
var partitionsFinished []uint64
if err = dl.EarlyTerminations.ForEach(func(partIdx uint64) error {
// Load partition.
var partition Partition
found, err := partitions.Get(partIdx, &partition)
if err != nil {
return xerrors.Errorf("failed to load partition %d: %w", partIdx, err)
}
if !found {
// If the partition doesn't exist any more, no problem.
// We don't expect this to happen (compaction should re-index altered partitions),
// but it's not worth failing if it does.
partitionsFinished = append(partitionsFinished, partIdx)
return nil
}
// Pop early terminations.
partitionResult, more, err := partition.PopEarlyTerminations(
store, maxSectors-result.SectorsProcessed,
)
if err != nil {
return xerrors.Errorf("failed to pop terminations from partition: %w", err)
}
err = result.Add(partitionResult)
if err != nil {
return xerrors.Errorf("failed to merge termination result: %w", err)
}
// If we've processed all of them for this partition, unmark it in the deadline.
if !more {
partitionsFinished = append(partitionsFinished, partIdx)
}
// Save partition
err = partitions.Set(partIdx, &partition)
if err != nil {
return xerrors.Errorf("failed to store partition %v", partIdx)
}
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)
}
// Removed finished partitions from the index.
for _, finished := range partitionsFinished {
dl.EarlyTerminations.Unset(finished)
}
// Save deadline's partitions
dl.Partitions, err = partitions.Root()
if err != nil {
return TerminationResult{}, false, xerrors.Errorf("failed to update partitions")
}
// Update global early terminations bitfield.
noEarlyTerminations, err := dl.EarlyTerminations.IsEmpty()
if err != nil {
return TerminationResult{}, false, xerrors.Errorf("failed to count remaining early terminations partitions: %w", err)
}
return result, !noEarlyTerminations, nil
}
// Returns nil if nothing was popped.
func (dl *Deadline) popExpiredPartitions(store adt.Store, until abi.ChainEpoch, quant builtin.QuantSpec) (bitfield.BitField, bool, error) {
expirations, err := LoadBitfieldQueue(store, dl.ExpirationsEpochs, quant, DeadlineExpirationAmtBitwidth)
if err != nil {
return bitfield.BitField{}, false, err
}
popped, modified, err := expirations.PopUntil(until)
if err != nil {
return bitfield.BitField{}, false, xerrors.Errorf("failed to pop expiring partitions: %w", err)
}
if modified {
dl.ExpirationsEpochs, err = expirations.Root()
if err != nil {
return bitfield.BitField{}, false, err
}
}
return popped, modified, nil
}
func (dl *Deadline) TerminateSectors(
store adt.Store,
sectors Sectors,
epoch abi.ChainEpoch,
partitionSectors PartitionSectorMap,
ssize abi.SectorSize,
quant builtin.QuantSpec,
) (powerLost PowerPair, err error) {
partitions, err := dl.PartitionsArray(store)
if err != nil {
return NewPowerPairZero(), err
}
powerLost = NewPowerPairZero()
var partition Partition
if err := partitionSectors.ForEach(func(partIdx uint64, sectorNos bitfield.BitField) error {
if found, err := partitions.Get(partIdx, &partition); err != nil {
return xerrors.Errorf("failed to load partition %d: %w", partIdx, err)
} else if !found {
return xc.ErrNotFound.Wrapf("failed to find partition %d", partIdx)
}
removed, err := partition.TerminateSectors(store, sectors, epoch, sectorNos, ssize, quant)
if err != nil {
return xerrors.Errorf("failed to terminate sectors in partition %d: %w", partIdx, err)
}
err = partitions.Set(partIdx, &partition)
if err != nil {
return xerrors.Errorf("failed to store updated partition %d: %w", partIdx, err)
}
if count, err := removed.Count(); err != nil {
return xerrors.Errorf("failed to count terminated sectors in partition %d: %w", partIdx, err)
} else if count > 0 {
// Record that partition now has pending early terminations.
dl.EarlyTerminations.Set(partIdx)
// Record change to sectors and power
dl.LiveSectors -= count
} // note: we should _always_ have early terminations, unless the early termination bitfield is empty.
dl.FaultyPower = dl.FaultyPower.Sub(removed.FaultyPower)
// Aggregate power lost from active sectors
powerLost = powerLost.Add(removed.ActivePower)
return nil
}); err != nil {
return NewPowerPairZero(), err
}
// save partitions back
dl.Partitions, err = partitions.Root()
if err != nil {
return NewPowerPairZero(), xerrors.Errorf("failed to persist partitions: %w", err)
}
return powerLost, nil
}
// RemovePartitions removes the specified partitions, shifting the remaining
// ones to the left, and returning the live and dead sectors they contained.
//
// Returns an error if any of the partitions contained faulty sectors or early
// terminations.
func (dl *Deadline) RemovePartitions(store adt.Store, toRemove bitfield.BitField, quant builtin.QuantSpec) (
live, dead bitfield.BitField, removedPower PowerPair, err error,
) {
oldPartitions, err := dl.PartitionsArray(store)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to load partitions: %w", err)
}
partitionCount := oldPartitions.Length()
toRemoveSet, err := toRemove.AllMap(partitionCount)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xc.ErrIllegalArgument.Wrapf("failed to expand partitions into map: %w", err)
}
// Nothing to do.
if len(toRemoveSet) == 0 {
return bitfield.NewFromSet(nil), bitfield.NewFromSet(nil), NewPowerPairZero(), nil
}
for partIdx := range toRemoveSet { //nolint:nomaprange
if partIdx >= partitionCount {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xc.ErrIllegalArgument.Wrapf(
"partition index %d out of range [0, %d)", partIdx, partitionCount,
)
}
}
// Should already be checked earlier, but we might as well check again.
noEarlyTerminations, err := dl.EarlyTerminations.IsEmpty()
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to check for early terminations: %w", err)
}
if !noEarlyTerminations {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("cannot remove partitions from deadline with early terminations: %w", err)
}
newPartitions, err := adt.MakeEmptyArray(store, DeadlinePartitionsAmtBitwidth)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to create empty array for initializing partitions: %w", err)
}
allDeadSectors := make([]bitfield.BitField, 0, len(toRemoveSet))
allLiveSectors := make([]bitfield.BitField, 0, len(toRemoveSet))
removedPower = NewPowerPairZero()
// Define all of these out here to save allocations.
var (
lazyPartition cbg.Deferred
byteReader bytes.Reader
partition Partition
)
if err = oldPartitions.ForEach(&lazyPartition, func(partIdx int64) error {
// If we're keeping the partition as-is, append it to the new partitions array.
if _, ok := toRemoveSet[uint64(partIdx)]; !ok {
return newPartitions.AppendContinuous(&lazyPartition)
}
// Ok, actually unmarshal the partition.
byteReader.Reset(lazyPartition.Raw)
err := partition.UnmarshalCBOR(&byteReader)
byteReader.Reset(nil)
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to decode partition %d: %w", partIdx, err)
}
// Don't allow removing partitions with faulty sectors.
hasNoFaults, err := partition.Faults.IsEmpty()
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to decode faults for partition %d: %w", partIdx, err)
}
if !hasNoFaults {
return xc.ErrIllegalArgument.Wrapf("cannot remove partition %d: has faults", partIdx)
}
// Don't allow removing partitions with unproven sectors.
allProven, err := partition.Unproven.IsEmpty()
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to decode unproven for partition %d: %w", partIdx, err)
}
if !allProven {
return xc.ErrIllegalArgument.Wrapf("cannot remove partition %d: has unproven sectors", partIdx)
}
// Get the live sectors.
liveSectors, err := partition.LiveSectors()
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to calculate live sectors for partition %d: %w", partIdx, err)
}
allDeadSectors = append(allDeadSectors, partition.Terminated)
allLiveSectors = append(allLiveSectors, liveSectors)
removedPower = removedPower.Add(partition.LivePower)
return nil
}); err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("while removing partitions: %w", err)
}
dl.Partitions, err = newPartitions.Root()
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to persist new partition table: %w", err)
}
dead, err = bitfield.MultiMerge(allDeadSectors...)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to merge dead sector bitfields: %w", err)
}
live, err = bitfield.MultiMerge(allLiveSectors...)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to merge live sector bitfields: %w", err)
}
// Update sector counts.
removedDeadSectors, err := dead.Count()
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to count dead sectors: %w", err)
}
removedLiveSectors, err := live.Count()
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to count live sectors: %w", err)
}
dl.LiveSectors -= removedLiveSectors
dl.TotalSectors -= removedLiveSectors + removedDeadSectors
// Update expiration bitfields.
{
expirationEpochs, err := LoadBitfieldQueue(store, dl.ExpirationsEpochs, quant, DeadlineExpirationAmtBitwidth)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed to load expiration queue: %w", err)
}
err = expirationEpochs.Cut(toRemove)
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed cut removed partitions from deadline expiration queue: %w", err)
}
dl.ExpirationsEpochs, err = expirationEpochs.Root()
if err != nil {
return bitfield.BitField{}, bitfield.BitField{}, NewPowerPairZero(), xerrors.Errorf("failed persist deadline expiration queue: %w", err)
}
}
return live, dead, removedPower, nil
}
func (dl *Deadline) RecordFaults(
store adt.Store, sectors Sectors, ssize abi.SectorSize, quant builtin.QuantSpec,
faultExpirationEpoch abi.ChainEpoch, partitionSectors PartitionSectorMap,
) (powerDelta PowerPair, err error) {
partitions, err := dl.PartitionsArray(store)
if err != nil {
return NewPowerPairZero(), err
}
// Record partitions with some fault, for subsequently indexing in the deadline.
// Duplicate entries don't matter, they'll be stored in a bitfield (a set).
partitionsWithFault := make([]uint64, 0, len(partitionSectors))
powerDelta = NewPowerPairZero()
if err := partitionSectors.ForEach(func(partIdx uint64, sectorNos bitfield.BitField) error {
var partition Partition
if found, err := partitions.Get(partIdx, &partition); err != nil {
return xc.ErrIllegalState.Wrapf("failed to load partition %d: %w", partIdx, err)
} else if !found {
return xc.ErrNotFound.Wrapf("no such partition %d", partIdx)
}
newFaults, partitionPowerDelta, partitionNewFaultyPower, err := partition.RecordFaults(
store, sectors, sectorNos, faultExpirationEpoch, ssize, quant,
)
if err != nil {
return xerrors.Errorf("failed to declare faults in partition %d: %w", partIdx, err)
}
dl.FaultyPower = dl.FaultyPower.Add(partitionNewFaultyPower)
powerDelta = powerDelta.Add(partitionPowerDelta)
if empty, err := newFaults.IsEmpty(); err != nil {
return xerrors.Errorf("failed to count new faults: %w", err)
} else if !empty {
partitionsWithFault = append(partitionsWithFault, partIdx)
}
err = partitions.Set(partIdx, &partition)
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to store partition %d: %w", partIdx, err)
}
return nil
}); err != nil {
return NewPowerPairZero(), err
}
dl.Partitions, err = partitions.Root()
if err != nil {
return NewPowerPairZero(), xc.ErrIllegalState.Wrapf("failed to store partitions root: %w", err)
}
err = dl.AddExpirationPartitions(store, faultExpirationEpoch, partitionsWithFault, quant)
if err != nil {
return NewPowerPairZero(), xc.ErrIllegalState.Wrapf("failed to update expirations for partitions with faults: %w", err)
}
return powerDelta, nil
}
func (dl *Deadline) DeclareFaultsRecovered(
store adt.Store, sectors Sectors, ssize abi.SectorSize,
partitionSectors PartitionSectorMap,
) (err error) {
partitions, err := dl.PartitionsArray(store)
if err != nil {
return err
}
if err := partitionSectors.ForEach(func(partIdx uint64, sectorNos bitfield.BitField) error {
var partition Partition
if found, err := partitions.Get(partIdx, &partition); err != nil {
return xc.ErrIllegalState.Wrapf("failed to load partition %d: %w", partIdx, err)
} else if !found {
return xc.ErrNotFound.Wrapf("no such partition %d", partIdx)
}
if err = partition.DeclareFaultsRecovered(sectors, ssize, sectorNos); err != nil {
return xc.ErrIllegalState.Wrapf("failed to add recoveries: %w", err)
}
err = partitions.Set(partIdx, &partition)
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to update partition %d: %w", partIdx, err)
}
return nil
}); err != nil {
return err
}
// Power is not regained until the deadline end, when the recovery is confirmed.
dl.Partitions, err = partitions.Root()
if err != nil {
return xc.ErrIllegalState.Wrapf("failed to store partitions root: %w", err)
}
return nil
}
// ProcessDeadlineEnd processes all PoSt submissions, marking unproven sectors as
// faulty and clearing failed recoveries. It returns the power delta, and any
// power that should be penalized (new faults and failed recoveries).
func (dl *Deadline) ProcessDeadlineEnd(store adt.Store, quant builtin.QuantSpec, faultExpirationEpoch abi.ChainEpoch, sectors cid.Cid) (
powerDelta, penalizedPower PowerPair, err error,
) {
powerDelta = NewPowerPairZero()
penalizedPower = NewPowerPairZero()
partitions, err := dl.PartitionsArray(store)
if err != nil {
return powerDelta, penalizedPower, xerrors.Errorf("failed to load partitions: %w", err)
}
detectedAny := false
var rescheduledPartitions []uint64
for partIdx := uint64(0); partIdx < partitions.Length(); partIdx++ {
proven, err := dl.PartitionsPoSted.IsSet(partIdx)
if err != nil {
return powerDelta, penalizedPower, xerrors.Errorf("failed to check submission for partition %d: %w", partIdx, err)
}
if proven {
continue
}
var partition Partition
found, err := partitions.Get(partIdx, &partition)
if err != nil {
return powerDelta, penalizedPower, xerrors.Errorf("failed to load partition %d: %w", partIdx, err)
}
if !found {
return powerDelta, penalizedPower, xerrors.Errorf("no partition %d", partIdx)
}
// If we have no recovering power/sectors, and all power is faulty, skip
// this. This lets us skip some work if a miner repeatedly fails to PoSt.
if partition.RecoveringPower.IsZero() && partition.FaultyPower.Equals(partition.LivePower) {
continue
}
// Ok, we actually need to process this partition. Make sure we save the partition state back.
detectedAny = true
partPowerDelta, partPenalizedPower, partNewFaultyPower, err := partition.RecordMissedPost(store, faultExpirationEpoch, quant)
if err != nil {
return powerDelta, penalizedPower, xerrors.Errorf("failed to record missed PoSt for partition %v: %w", partIdx, err)
}
// We marked some sectors faulty, we need to record the new
// expiration. We don't want to do this if we're just penalizing
// the miner for failing to recover power.
if !partNewFaultyPower.IsZero() {
rescheduledPartitions = append(rescheduledPartitions, partIdx)
}
// Save new partition state.
err = partitions.Set(partIdx, &partition)
if err != nil {
return powerDelta, penalizedPower, xerrors.Errorf("failed to update partition %v: %w", partIdx, err)
}
dl.FaultyPower = dl.FaultyPower.Add(partNewFaultyPower)
powerDelta = powerDelta.Add(partPowerDelta)
penalizedPower = penalizedPower.Add(partPenalizedPower)
}
// Save modified deadline state.
if detectedAny {
dl.Partitions, err = partitions.Root()
if err != nil {
return powerDelta, penalizedPower, xc.ErrIllegalState.Wrapf("failed to store partitions: %w", err)
}
}
err = dl.AddExpirationPartitions(store, faultExpirationEpoch, rescheduledPartitions, quant)
if err != nil {
return powerDelta, penalizedPower, xc.ErrIllegalState.Wrapf("failed to update deadline expiration queue: %w", err)
}
// Reset PoSt submissions, snapshot proofs.
dl.PartitionsPoSted = bitfield.New()
dl.PartitionsSnapshot = dl.Partitions
dl.OptimisticPoStSubmissionsSnapshot = dl.OptimisticPoStSubmissions
dl.OptimisticPoStSubmissions, err = adt.StoreEmptyArray(store, DeadlineOptimisticPoStSubmissionsAmtBitwidth)
if err != nil {
return powerDelta, penalizedPower, xerrors.Errorf("failed to clear pending proofs array: %w", err)
}
// only snapshot sectors if there's a proof that might be disputed (this is equivalent to asking if the OptimisticPoStSubmissionsSnapshot is empty)
if dl.OptimisticPoStSubmissions != dl.OptimisticPoStSubmissionsSnapshot {
dl.SectorsSnapshot = sectors
} else {
emptySectorsSnapshotArrayCid, err := adt.StoreEmptyArray(store, SectorsAmtBitwidth)
if err != nil {
return powerDelta, penalizedPower, xc.ErrIllegalState.Wrapf("failed to zero out the sectors snapshot: %w", err)
}
dl.SectorsSnapshot = emptySectorsSnapshotArrayCid
}
return powerDelta, penalizedPower, nil
}
type PoStResult struct {
// Power activated or deactivated (positive or negative).
PowerDelta PowerPair
// Powers used for calculating penalties.
NewFaultyPower, RetractedRecoveryPower, RecoveredPower PowerPair