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_actor.go
2200 lines (1840 loc) · 86 KB
/
miner_actor.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"
"encoding/binary"
"fmt"
"math"
addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
cid "github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
abi "github.com/filecoin-project/specs-actors/actors/abi"
big "github.com/filecoin-project/specs-actors/actors/abi/big"
builtin "github.com/filecoin-project/specs-actors/actors/builtin"
market "github.com/filecoin-project/specs-actors/actors/builtin/market"
power "github.com/filecoin-project/specs-actors/actors/builtin/power"
"github.com/filecoin-project/specs-actors/actors/builtin/reward"
crypto "github.com/filecoin-project/specs-actors/actors/crypto"
vmr "github.com/filecoin-project/specs-actors/actors/runtime"
exitcode "github.com/filecoin-project/specs-actors/actors/runtime/exitcode"
. "github.com/filecoin-project/specs-actors/actors/util"
adt "github.com/filecoin-project/specs-actors/actors/util/adt"
"github.com/filecoin-project/specs-actors/actors/util/smoothing"
)
type Runtime = vmr.Runtime
type CronEventType int64
const (
CronEventWorkerKeyChange CronEventType = iota
CronEventPreCommitExpiry
CronEventProvingDeadline
CronEventProcessEarlyTerminations
)
type CronEventPayload struct {
EventType CronEventType
Sectors *abi.BitField
}
// Identifier for a single partition within a miner.
type PartitionKey struct {
Deadline uint64
Partition uint64
}
type Actor struct{}
func (a Actor) Exports() []interface{} {
return []interface{}{
builtin.MethodConstructor: a.Constructor,
2: a.ControlAddresses,
3: a.ChangeWorkerAddress,
4: a.ChangePeerID,
5: a.SubmitWindowedPoSt,
6: a.PreCommitSector,
7: a.ProveCommitSector,
8: a.ExtendSectorExpiration,
9: a.TerminateSectors,
10: a.DeclareFaults,
11: a.DeclareFaultsRecovered,
12: a.OnDeferredCronEvent,
13: a.CheckSectorProven,
14: a.AddLockedFund,
15: a.ReportConsensusFault,
16: a.WithdrawBalance,
17: a.ConfirmSectorProofsValid,
18: a.ChangeMultiaddrs,
19: a.CompactPartitions,
}
}
var _ abi.Invokee = Actor{}
/////////////////
// Constructor //
/////////////////
// Storage miner actors are created exclusively by the storage power actor. In order to break a circular dependency
// between the two, the construction parameters are defined in the power actor.
type ConstructorParams = power.MinerConstructorParams
func (a Actor) Constructor(rt Runtime, params *ConstructorParams) *adt.EmptyValue {
rt.ValidateImmediateCallerIs(builtin.InitActorAddr)
_, ok := SupportedProofTypes[params.SealProofType]
if !ok {
rt.Abortf(exitcode.ErrIllegalArgument, "proof type %d not allowed for new miner actors", params.SealProofType)
}
owner := resolveOwnerAddress(rt, params.OwnerAddr)
worker := resolveWorkerAddress(rt, params.WorkerAddr)
emptyMap, err := adt.MakeEmptyMap(adt.AsStore(rt)).Root()
if err != nil {
rt.Abortf(exitcode.ErrIllegalState, "failed to construct initial state: %v", err)
}
emptyArray, err := adt.MakeEmptyArray(adt.AsStore(rt)).Root()
if err != nil {
rt.Abortf(exitcode.ErrIllegalState, "failed to construct initial state: %v", err)
}
emptyBitfield := bitfield.NewFromSet(nil)
emptyBitfieldCid := rt.Store().Put(emptyBitfield)
emptyDeadline := ConstructDeadline(emptyArray)
emptyDeadlineCid := rt.Store().Put(emptyDeadline)
emptyDeadlines := ConstructDeadlines(emptyDeadlineCid)
emptyDeadlinesCid := rt.Store().Put(emptyDeadlines)
currEpoch := rt.CurrEpoch()
offset, err := assignProvingPeriodOffset(rt.Message().Receiver(), currEpoch, rt.Syscalls().HashBlake2b)
builtin.RequireNoErr(rt, err, exitcode.ErrSerialization, "failed to assign proving period offset")
periodStart := nextProvingPeriodStart(currEpoch, offset)
Assert(periodStart > currEpoch)
info, err := ConstructMinerInfo(owner, worker, params.PeerId, params.Multiaddrs, params.SealProofType)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "failed to construct initial miner info")
infoCid := rt.Store().Put(info)
state, err := ConstructState(infoCid, periodStart, emptyBitfieldCid, emptyArray, emptyMap, emptyDeadlinesCid)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "failed to construct state")
rt.State().Create(state)
// Register first cron callback for epoch before the first proving period starts.
enrollCronEvent(rt, periodStart-1, &CronEventPayload{
EventType: CronEventProvingDeadline,
})
return nil
}
/////////////
// Control //
/////////////
type GetControlAddressesReturn struct {
Owner addr.Address
Worker addr.Address
}
func (a Actor) ControlAddresses(rt Runtime, _ *adt.EmptyValue) *GetControlAddressesReturn {
rt.ValidateImmediateCallerAcceptAny()
var st State
rt.State().Readonly(&st)
info := getMinerInfo(rt, &st)
return &GetControlAddressesReturn{
Owner: info.Owner,
Worker: info.Worker,
}
}
type ChangeWorkerAddressParams struct {
NewWorker addr.Address
}
func (a Actor) ChangeWorkerAddress(rt Runtime, params *ChangeWorkerAddressParams) *adt.EmptyValue {
var effectiveEpoch abi.ChainEpoch
var st State
rt.State().Transaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Owner)
worker := resolveWorkerAddress(rt, params.NewWorker)
effectiveEpoch = rt.CurrEpoch() + WorkerKeyChangeDelay
// This may replace another pending key change.
info.PendingWorkerKey = &WorkerKeyChange{
NewWorker: worker,
EffectiveAt: effectiveEpoch,
}
err := st.SaveInfo(adt.AsStore(rt), info)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "could not save miner info")
})
cronPayload := CronEventPayload{
EventType: CronEventWorkerKeyChange,
}
enrollCronEvent(rt, effectiveEpoch, &cronPayload)
return nil
}
type ChangePeerIDParams struct {
NewID abi.PeerID
}
func (a Actor) ChangePeerID(rt Runtime, params *ChangePeerIDParams) *adt.EmptyValue {
// TODO: Consider limiting the maximum number of bytes used by the peer ID on-chain.
// https://github.com/filecoin-project/specs-actors/issues/712
var st State
rt.State().Transaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Worker)
info.PeerId = params.NewID
err := st.SaveInfo(adt.AsStore(rt), info)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "could not save miner info")
})
return nil
}
type ChangeMultiaddrsParams struct {
NewMultiaddrs []abi.Multiaddrs
}
func (a Actor) ChangeMultiaddrs(rt Runtime, params *ChangeMultiaddrsParams) *adt.EmptyValue {
// TODO: Consider limiting the maximum number of bytes used by multiaddrs on-chain.
// https://github.com/filecoin-project/specs-actors/issues/712
var st State
rt.State().Transaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Worker)
info.Multiaddrs = params.NewMultiaddrs
err := st.SaveInfo(adt.AsStore(rt), info)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "could not save miner info")
})
return nil
}
//////////////////
// WindowedPoSt //
//////////////////
type PoStPartition struct {
// Partitions are numbered per-deadline, from zero.
Index uint64
// Sectors skipped while proving that weren't already declared faulty
Skipped *abi.BitField
}
// Information submitted by a miner to provide a Window PoSt.
type SubmitWindowedPoStParams struct {
// The deadline index which the submission targets.
Deadline uint64
// The partitions being proven.
Partitions []PoStPartition
// 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 []abi.PoStProof
}
// Invoked by miner's worker address to submit their fallback post
func (a Actor) SubmitWindowedPoSt(rt Runtime, params *SubmitWindowedPoStParams) *adt.EmptyValue {
currEpoch := rt.CurrEpoch()
store := adt.AsStore(rt)
var st State
if params.Deadline >= WPoStPeriodDeadlines {
rt.Abortf(exitcode.ErrIllegalArgument, "invalid deadline %d of %d", params.Deadline, WPoStPeriodDeadlines)
}
// TODO: limit the length of proofs array https://github.com/filecoin-project/specs-actors/issues/416
// Get the total power/reward. We need these to compute penalties.
rewardStats := requestCurrentEpochBlockReward(rt)
pwrTotal := requestCurrentTotalPower(rt)
penaltyTotal := abi.NewTokenAmount(0)
pledgeDelta := abi.NewTokenAmount(0)
var postResult *PoStResult
var info *MinerInfo
rt.State().Transaction(&st, func() {
info = getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Worker)
// Validate that the miner didn't try to prove too many partitions at once.
submissionPartitionLimit := loadPartitionsSectorsMax(info.WindowPoStPartitionSectors)
if uint64(len(params.Partitions)) > submissionPartitionLimit {
rt.Abortf(exitcode.ErrIllegalArgument, "too many partitions %d, limit %d", len(params.Partitions), submissionPartitionLimit)
}
// Load and check deadline.
currDeadline := st.DeadlineInfo(currEpoch)
deadlines, err := st.LoadDeadlines(adt.AsStore(rt))
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadlines")
// Check that the miner state indicates that the current proving deadline has started.
// This should only fail if the cron actor wasn't invoked, and matters only in case that it hasn't been
// invoked for a whole proving period, and hence the missed PoSt submissions from the prior occurrence
// of this deadline haven't been processed yet.
if !currDeadline.IsOpen() {
rt.Abortf(exitcode.ErrIllegalState, "proving period %d not yet open at %d", currDeadline.PeriodStart, currEpoch)
}
// The miner may only submit a proof for the current deadline.
if params.Deadline != currDeadline.Index {
rt.Abortf(exitcode.ErrIllegalArgument, "invalid deadline %d at epoch %d, expected %d",
params.Deadline, currEpoch, currDeadline.Index)
}
sectors, err := LoadSectors(store, st.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors")
deadline, err := deadlines.LoadDeadline(store, params.Deadline)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadline %d", params.Deadline)
// Record proven sectors/partitions, returning updates to power and the final set of sectors
// proven/skipped.
//
// NOTE: This function does not actually check the proofs but does assume that they'll be
// successfully validated. The actual proof verification is done below in verifyWindowedPost.
//
// If proof verification fails, the this deadline MUST NOT be saved and this function should
// be aborted.
faultExpiration := currDeadline.Last() + FaultMaxAge
postResult, err = deadline.RecordProvenSectors(store, sectors, info.SectorSize, currDeadline.QuantSpec(), faultExpiration, params.Partitions)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to process post submission for deadline %d", params.Deadline)
// Validate proofs
// Load sector infos for proof, substituting a known-good sector for known-faulty sectors.
// Note: this is slightly sub-optimal, loading info for the recovering sectors again after they were already
// loaded above.
sectorInfos, err := st.LoadSectorInfosForProof(store, postResult.Sectors, postResult.IgnoredSectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load proven sector info")
// Skip verification if all sectors are faults.
// We still need to allow this call to succeed so the miner can declare a whole partition as skipped.
if len(sectorInfos) > 0 {
// Verify the proof.
// A failed verification doesn't immediately cause a penalty; the miner can try again.
//
// This function aborts on failure.
verifyWindowedPost(rt, currDeadline.Challenge, sectorInfos, params.Proofs)
}
// Penalize new skipped faults and retracted recoveries as undeclared faults.
// These pay a higher fee than faults declared before the deadline challenge window opened.
undeclaredPenaltyPower := postResult.PenaltyPower()
undeclaredPenaltyTarget := PledgePenaltyForUndeclaredFault(
rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, undeclaredPenaltyPower.QA,
)
// Subtract the "ongoing" fault fee from the amount charged now, since it will be charged at
// the end-of-deadline cron.
undeclaredPenaltyTarget = big.Sub(undeclaredPenaltyTarget, PledgePenaltyForDeclaredFault(
rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, undeclaredPenaltyPower.QA,
))
// Penalize recoveries as declared faults (a lower fee than the undeclared, above).
// It sounds odd, but because faults are penalized in arrears, at the _end_ of the faulty period, we must
// penalize recovered sectors here because they won't be penalized by the end-of-deadline cron for the
// immediately-prior faulty period.
declaredPenaltyTarget := PledgePenaltyForDeclaredFault(
rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, postResult.RecoveredPower.QA,
)
// Note: We could delay this charge until end of deadline, but that would require more accounting state.
totalPenaltyTarget := big.Add(undeclaredPenaltyTarget, declaredPenaltyTarget)
unlockedBalance := st.GetUnlockedBalance(rt.CurrentBalance())
vestingPenaltyTotal, balancePenaltyTotal, err := st.PenalizeFundsInPriorityOrder(store, currEpoch, totalPenaltyTarget, unlockedBalance)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to unlock penalty for %v", undeclaredPenaltyPower)
penaltyTotal = big.Add(vestingPenaltyTotal, balancePenaltyTotal)
pledgeDelta = big.Sub(pledgeDelta, vestingPenaltyTotal)
err = deadlines.UpdateDeadline(store, params.Deadline, deadline)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to update deadline %d", params.Deadline)
err = st.SaveDeadlines(store, deadlines)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save deadlines")
})
// Restore power for recovered sectors. Remove power for new faults.
// NOTE: It would be permissible to delay the power loss until the deadline closes, but that would require
// additional accounting state.
// https://github.com/filecoin-project/specs-actors/issues/414
requestUpdatePower(rt, postResult.PowerDelta())
// Burn penalties.
burnFunds(rt, penaltyTotal)
notifyPledgeChanged(rt, pledgeDelta)
return nil
}
///////////////////////
// Sector Commitment //
///////////////////////
// Proposals must be posted on chain via sma.PublishStorageDeals before PreCommitSector.
// Optimization: PreCommitSector could contain a list of deals that are not published yet.
func (a Actor) PreCommitSector(rt Runtime, params *SectorPreCommitInfo) *adt.EmptyValue {
if _, ok := SupportedProofTypes[params.SealProof]; !ok {
rt.Abortf(exitcode.ErrIllegalArgument, "unsupported seal proof type: %s", params.SealProof)
}
if params.SectorNumber > abi.MaxSectorNumber {
rt.Abortf(exitcode.ErrIllegalArgument, "sector number %d out of range 0..(2^63-1)", params.SectorNumber)
}
if !params.SealedCID.Defined() {
rt.Abortf(exitcode.ErrIllegalArgument, "sealed CID undefined")
}
if params.SealedCID.Prefix() != SealedCIDPrefix {
rt.Abortf(exitcode.ErrIllegalArgument, "sealed CID had wrong prefix")
}
if params.SealRandEpoch >= rt.CurrEpoch() {
rt.Abortf(exitcode.ErrIllegalArgument, "seal challenge epoch %v must be before now %v", params.SealRandEpoch, rt.CurrEpoch())
}
challengeEarliest := sealChallengeEarliest(rt.CurrEpoch(), params.SealProof)
if params.SealRandEpoch < challengeEarliest {
// The subsequent commitment proof can't possibly be accepted because the seal challenge will be deemed
// too old. Note that passing this check doesn't guarantee the proof will be soon enough, depending on
// when it arrives.
rt.Abortf(exitcode.ErrIllegalArgument, "seal challenge epoch %v too old, must be after %v", params.SealRandEpoch, challengeEarliest)
}
if params.Expiration <= rt.CurrEpoch() {
rt.Abortf(exitcode.ErrIllegalArgument, "sector expiration %v must be after now (%v)", params.Expiration, rt.CurrEpoch())
}
if params.ReplaceCapacity && len(params.DealIDs) == 0 {
rt.Abortf(exitcode.ErrIllegalArgument, "cannot replace sector without committing deals")
}
if params.ReplaceSectorDeadline >= WPoStPeriodDeadlines {
rt.Abortf(exitcode.ErrIllegalArgument, "invalid deadline %d", params.ReplaceSectorDeadline)
}
if params.ReplaceSectorNumber > abi.MaxSectorNumber {
rt.Abortf(exitcode.ErrIllegalArgument, "invalid sector number %d", params.ReplaceSectorNumber)
}
// gather information from other actors
rewardStats := requestCurrentEpochBlockReward(rt)
pwrTotal := requestCurrentTotalPower(rt)
dealWeight := requestDealWeight(rt, params.DealIDs, rt.CurrEpoch(), params.Expiration)
store := adt.AsStore(rt)
var st State
newlyVested := big.Zero()
rt.State().Transaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Worker)
if params.SealProof != info.SealProofType {
rt.Abortf(exitcode.ErrIllegalArgument, "sector seal proof %v must match miner seal proof type %d", params.SealProof, info.SealProofType)
}
maxDealLimit := dealPerSectorLimit(info.SectorSize)
if uint64(len(params.DealIDs)) > maxDealLimit {
rt.Abortf(exitcode.ErrIllegalArgument, "too many deals for sector %d > %d", len(params.DealIDs), maxDealLimit)
}
err := st.AllocateSectorNumber(store, params.SectorNumber)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to allocate sector id %d", params.SectorNumber)
// The following two checks shouldn't be necessary, but it can't
// hurt to double-check (unless it's really just too
// expensive?).
_, preCommitFound, err := st.GetPrecommittedSector(store, params.SectorNumber)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to check pre-commit %v", params.SectorNumber)
if preCommitFound {
rt.Abortf(exitcode.ErrIllegalState, "sector %v already pre-committed", params.SectorNumber)
}
sectorFound, err := st.HasSectorNo(store, params.SectorNumber)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to check sector %v", params.SectorNumber)
if sectorFound {
rt.Abortf(exitcode.ErrIllegalState, "sector %v already committed", params.SectorNumber)
}
validateExpiration(rt, rt.CurrEpoch(), params.Expiration, params.SealProof)
depositMinimum := big.Zero()
if params.ReplaceCapacity {
replaceSector := validateReplaceSector(rt, &st, store, params)
// Note the replaced sector's initial pledge as a lower bound for the new sector's deposit
depositMinimum = replaceSector.InitialPledge
}
newlyVested, err = st.UnlockVestedFunds(store, rt.CurrEpoch())
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to vest funds")
availableBalance := st.GetAvailableBalance(rt.CurrentBalance())
duration := params.Expiration - rt.CurrEpoch()
sectorWeight := QAPowerForWeight(info.SectorSize, duration, dealWeight.DealWeight, dealWeight.VerifiedDealWeight)
depositReq := big.Max(
PreCommitDepositForPower(rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, sectorWeight),
depositMinimum,
)
if availableBalance.LessThan(depositReq) {
rt.Abortf(exitcode.ErrInsufficientFunds, "insufficient funds for pre-commit deposit: %v", depositReq)
}
st.AddPreCommitDeposit(depositReq)
st.AssertBalanceInvariants(rt.CurrentBalance())
if err := st.PutPrecommittedSector(store, &SectorPreCommitOnChainInfo{
Info: *params,
PreCommitDeposit: depositReq,
PreCommitEpoch: rt.CurrEpoch(),
DealWeight: dealWeight.DealWeight,
VerifiedDealWeight: dealWeight.VerifiedDealWeight,
}); err != nil {
rt.Abortf(exitcode.ErrIllegalState, "failed to write pre-committed sector %v: %v", params.SectorNumber, err)
}
})
notifyPledgeChanged(rt, newlyVested.Neg())
bf := abi.NewBitField()
bf.Set(uint64(params.SectorNumber))
// Request deferred Cron check for PreCommit expiry check.
cronPayload := CronEventPayload{
EventType: CronEventPreCommitExpiry,
Sectors: bf,
}
msd, ok := MaxSealDuration[params.SealProof]
if !ok {
rt.Abortf(exitcode.ErrIllegalArgument, "no max seal duration set for proof type: %d", params.SealProof)
}
// The +1 here is critical for the batch verification of proofs. Without it, if a proof arrived exactly on the
// due epoch, ProveCommitSector would accept it, then the expiry event would remove it, and then
// ConfirmSectorProofsValid would fail to find it.
expiryBound := rt.CurrEpoch() + msd + 1
enrollCronEvent(rt, expiryBound, &cronPayload)
return nil
}
type ProveCommitSectorParams struct {
SectorNumber abi.SectorNumber
Proof []byte
}
// Checks state of the corresponding sector pre-commitment, then schedules the proof to be verified in bulk
// by the power actor.
// If valid, the power actor will call ConfirmSectorProofsValid at the end of the same epoch as this message.
func (a Actor) ProveCommitSector(rt Runtime, params *ProveCommitSectorParams) *adt.EmptyValue {
rt.ValidateImmediateCallerAcceptAny()
store := adt.AsStore(rt)
var st State
rt.State().Readonly(&st)
// Verify locked funds are are at least the sum of sector initial pledges.
// Note that this call does not actually compute recent vesting, so the reported locked funds may be
// slightly higher than the true amount (i.e. slightly in the miner's favour).
// Computing vesting here would be almost always redundant since vesting is quantized to ~daily units.
// Vesting will be at most one proving period old if computed in the cron callback.
verifyPledgeMeetsInitialRequirements(rt, &st)
sectorNo := params.SectorNumber
precommit, found, err := st.GetPrecommittedSector(store, sectorNo)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load pre-committed sector %v", sectorNo)
if !found {
rt.Abortf(exitcode.ErrNotFound, "no pre-committed sector %v", sectorNo)
}
msd, ok := MaxSealDuration[precommit.Info.SealProof]
if !ok {
rt.Abortf(exitcode.ErrIllegalState, "no max seal duration for proof type: %d", precommit.Info.SealProof)
}
proveCommitDue := precommit.PreCommitEpoch + msd
if rt.CurrEpoch() > proveCommitDue {
rt.Abortf(exitcode.ErrIllegalArgument, "commitment proof for %d too late at %d, due %d", sectorNo, rt.CurrEpoch(), proveCommitDue)
}
svi := getVerifyInfo(rt, &SealVerifyStuff{
SealedCID: precommit.Info.SealedCID,
InteractiveEpoch: precommit.PreCommitEpoch + PreCommitChallengeDelay,
SealRandEpoch: precommit.Info.SealRandEpoch,
Proof: params.Proof,
DealIDs: precommit.Info.DealIDs,
SectorNumber: precommit.Info.SectorNumber,
RegisteredSealProof: precommit.Info.SealProof,
})
_, code := rt.Send(
builtin.StoragePowerActorAddr,
builtin.MethodsPower.SubmitPoRepForBulkVerify,
svi,
abi.NewTokenAmount(0),
)
builtin.RequireSuccess(rt, code, "failed to submit proof for bulk verification")
return nil
}
func (a Actor) ConfirmSectorProofsValid(rt Runtime, params *builtin.ConfirmSectorProofsParams) *adt.EmptyValue {
rt.ValidateImmediateCallerIs(builtin.StoragePowerActorAddr)
// get network stats from other actors
rewardStats := requestCurrentEpochBlockReward(rt)
pwrTotal := requestCurrentTotalPower(rt)
circulatingSupply := rt.TotalFilCircSupply()
// 1. Activate deals, skipping pre-commits with invalid deals.
// - calls the market actor.
// 2. Reschedule replacement sector expiration.
// - loads and saves sectors
// - loads and saves deadlines/partitions
// 3. Add new sectors.
// - loads and saves sectors.
// - loads and saves deadlines/partitions
//
// Ideally, we'd combine some of these operations, but at least we have
// a constant number of them.
var st State
rt.State().Readonly(&st)
store := adt.AsStore(rt)
info := getMinerInfo(rt, &st)
//
// Activate storage deals.
//
// This skips missing pre-commits.
precommittedSectors, err := st.FindPrecommittedSectors(store, params.Sectors...)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load pre-committed sectors")
// Committed-capacity sectors licensed for early removal by new sectors being proven.
replaceSectors := make(DeadlineSectorMap)
// Pre-commits for new sectors.
var preCommits []*SectorPreCommitOnChainInfo
for _, precommit := range precommittedSectors {
// Check (and activate) storage deals associated to sector. Abort if checks failed.
// TODO: we should batch these calls...
// https://github.com/filecoin-project/specs-actors/issues/474
_, code := rt.Send(
builtin.StorageMarketActorAddr,
builtin.MethodsMarket.ActivateDeals,
&market.ActivateDealsParams{
DealIDs: precommit.Info.DealIDs,
SectorExpiry: precommit.Info.Expiration,
},
abi.NewTokenAmount(0),
)
if code != exitcode.Ok {
rt.Log(vmr.INFO, "failed to activate deals on sector %d, dropping from prove commit set", precommit.Info.SectorNumber)
continue
}
preCommits = append(preCommits, precommit)
if precommit.Info.ReplaceCapacity {
err := replaceSectors.AddValues(
precommit.Info.ReplaceSectorDeadline,
precommit.Info.ReplaceSectorPartition,
uint64(precommit.Info.ReplaceSectorNumber),
)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "failed to record sectors for replacement")
}
}
// When all prove commits have failed abort early
if len(preCommits) == 0 {
rt.Abortf(exitcode.ErrIllegalArgument, "all prove commits failed to validate")
}
var newPower PowerPair
totalPledge := big.Zero()
totalPrecommitDeposit := big.Zero()
newSectors := make([]*SectorOnChainInfo, 0)
newlyVested := big.Zero()
rt.State().Transaction(&st, func() {
// Schedule expiration for replaced sectors to the end of their next deadline window.
// They can't be removed right now because we want to challenge them immediately before termination.
err = st.RescheduleSectorExpirations(store, rt.CurrEpoch(), info.SectorSize, replaceSectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to replace sector expirations")
newSectorNos := make([]abi.SectorNumber, 0, len(preCommits))
for _, precommit := range preCommits {
// compute initial pledge
activation := rt.CurrEpoch()
duration := precommit.Info.Expiration - activation
power := QAPowerForWeight(info.SectorSize, duration, precommit.DealWeight, precommit.VerifiedDealWeight)
dayReward := ExpectedRewardForPower(rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, power, builtin.EpochsInDay)
storagePledge := ExpectedRewardForPower(rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, power, InitialPledgeProjectionPeriod)
initialPledge := InitialPledgeForPower(power, rewardStats.ThisEpochBaselinePower, pwrTotal.PledgeCollateral,
rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, circulatingSupply)
totalPrecommitDeposit = big.Add(totalPrecommitDeposit, precommit.PreCommitDeposit)
totalPledge = big.Add(totalPledge, initialPledge)
newSectorInfo := SectorOnChainInfo{
SectorNumber: precommit.Info.SectorNumber,
SealProof: precommit.Info.SealProof,
SealedCID: precommit.Info.SealedCID,
DealIDs: precommit.Info.DealIDs,
Expiration: precommit.Info.Expiration,
Activation: activation,
DealWeight: precommit.DealWeight,
VerifiedDealWeight: precommit.VerifiedDealWeight,
InitialPledge: initialPledge,
ExpectedDayReward: dayReward,
ExpectedStoragePledge: storagePledge,
}
newSectors = append(newSectors, &newSectorInfo)
newSectorNos = append(newSectorNos, newSectorInfo.SectorNumber)
}
err = st.PutSectors(store, newSectors...)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to put new sectors")
err = st.DeletePrecommittedSectors(store, newSectorNos...)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to delete precommited sectors")
newPower, err = st.AssignSectorsToDeadlines(store, rt.CurrEpoch(), newSectors, info.WindowPoStPartitionSectors, info.SectorSize)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to assign new sectors to deadlines")
// Add sector and pledge lock-up to miner state
newlyVested, err = st.UnlockVestedFunds(store, rt.CurrEpoch())
if err != nil {
rt.Abortf(exitcode.ErrIllegalState, "failed to vest new funds: %s", err)
}
// Unlock deposit for successful proofs, make it available for lock-up as initial pledge.
st.AddPreCommitDeposit(totalPrecommitDeposit.Neg())
availableBalance := st.GetAvailableBalance(rt.CurrentBalance())
if availableBalance.LessThan(totalPledge) {
rt.Abortf(exitcode.ErrInsufficientFunds, "insufficient funds for aggregate initial pledge requirement %s, available: %s", totalPledge, availableBalance)
}
st.AddInitialPledgeRequirement(totalPledge)
st.AssertBalanceInvariants(rt.CurrentBalance())
})
// Request power and pledge update for activated sector.
requestUpdatePower(rt, newPower)
notifyPledgeChanged(rt, big.Sub(totalPledge, newlyVested))
return nil
}
type CheckSectorProvenParams struct {
SectorNumber abi.SectorNumber
}
func (a Actor) CheckSectorProven(rt Runtime, params *CheckSectorProvenParams) *adt.EmptyValue {
rt.ValidateImmediateCallerAcceptAny()
var st State
rt.State().Readonly(&st)
store := adt.AsStore(rt)
sectorNo := params.SectorNumber
if _, found, err := st.GetSector(store, sectorNo); err != nil {
rt.Abortf(exitcode.ErrIllegalState, "failed to load proven sector %v", sectorNo)
} else if !found {
rt.Abortf(exitcode.ErrNotFound, "sector %v not proven", sectorNo)
}
return nil
}
/////////////////////////
// Sector Modification //
/////////////////////////
type ExtendSectorExpirationParams struct {
Extensions []ExpirationExtension
}
type ExpirationExtension struct {
Deadline uint64
Partition uint64
Sectors *abi.BitField
NewExpiration abi.ChainEpoch
}
// Changes the expiration epoch for a sector to a new, later one.
// The sector must not be terminated or faulty.
// The sector's power is recomputed for the new expiration.
func (a Actor) ExtendSectorExpiration(rt Runtime, params *ExtendSectorExpirationParams) *adt.EmptyValue {
if uint64(len(params.Extensions)) > AddressedPartitionsMax {
rt.Abortf(exitcode.ErrIllegalArgument, "too many declarations %d, max %d", len(params.Extensions), AddressedPartitionsMax)
}
// limit the number of sectors declared at once
// https://github.com/filecoin-project/specs-actors/issues/416
var sectorCount uint64
for _, decl := range params.Extensions {
if decl.Deadline >= WPoStPeriodDeadlines {
rt.Abortf(exitcode.ErrIllegalArgument, "deadline %d not in range 0..%d", decl.Deadline, WPoStPeriodDeadlines)
}
count, err := decl.Sectors.Count()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument,
"failed to count sectors for deadline %d, partition %d",
decl.Deadline, decl.Partition,
)
if sectorCount > math.MaxUint64-count {
rt.Abortf(exitcode.ErrIllegalArgument, "sector bitfield integer overflow")
}
sectorCount += count
}
if sectorCount > AddressedSectorsMax {
rt.Abortf(exitcode.ErrIllegalArgument,
"too many sectors for declaration %d, max %d",
sectorCount, AddressedSectorsMax,
)
}
powerDelta := NewPowerPairZero()
pledgeDelta := big.Zero()
store := adt.AsStore(rt)
var st State
rt.State().Transaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Worker)
deadlines, err := st.LoadDeadlines(adt.AsStore(rt))
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadlines")
// Group declarations by deadline, and remember iteration order.
declsByDeadline := map[uint64][]*ExpirationExtension{}
var deadlinesToLoad []uint64
for i := range params.Extensions {
// Take a pointer to the value inside the slice, don't
// take a reference to the temporary loop variable as it
// will be overwritten every iteration.
decl := ¶ms.Extensions[i]
if _, ok := declsByDeadline[decl.Deadline]; !ok {
deadlinesToLoad = append(deadlinesToLoad, decl.Deadline)
}
declsByDeadline[decl.Deadline] = append(declsByDeadline[decl.Deadline], decl)
}
sectors, err := LoadSectors(store, st.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors array")
for _, dlIdx := range deadlinesToLoad {
deadline, err := deadlines.LoadDeadline(store, dlIdx)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadline %d", dlIdx)
partitions, err := deadline.PartitionsArray(store)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load partitions for deadline %d", dlIdx)
quant := st.QuantSpecForDeadline(dlIdx)
for _, decl := range declsByDeadline[dlIdx] {
key := PartitionKey{dlIdx, decl.Partition}
var partition Partition
found, err := partitions.Get(decl.Partition, &partition)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load partition %v", key)
if !found {
rt.Abortf(exitcode.ErrNotFound, "no such partition %v", key)
}
oldSectors, err := sectors.Load(decl.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors")
newSectors := make([]*SectorOnChainInfo, len(oldSectors))
for i, sector := range oldSectors {
if decl.NewExpiration < sector.Expiration {
rt.Abortf(exitcode.ErrIllegalArgument, "cannot reduce sector expiration to %d from %d",
decl.NewExpiration, sector.Expiration)
}
validateExpiration(rt, sector.Activation, decl.NewExpiration, sector.SealProof)
newSector := *sector
newSector.Expiration = decl.NewExpiration
newSectors[i] = &newSector
}
// Overwrite sector infos.
err = sectors.Store(newSectors...)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to update sectors %v", decl.Sectors)
// Remove old sectors from partition and assign new sectors.
partitionPowerDelta, partitionPledgeDelta, err := partition.ReplaceSectors(store, oldSectors, newSectors, info.SectorSize, quant)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to replaces sector expirations at %v", key)
powerDelta = powerDelta.Add(partitionPowerDelta)
pledgeDelta = big.Add(pledgeDelta, partitionPledgeDelta) // expected to be zero, see note below.
err = partitions.Set(decl.Partition, &partition)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save partition", key)
}
deadline.Partitions, err = partitions.Root()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save partitions for deadline %d", dlIdx)
err = deadlines.UpdateDeadline(store, dlIdx, deadline)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save deadline %d", dlIdx)
}
st.Sectors, err = sectors.Root()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save sectors")
err = st.SaveDeadlines(store, deadlines)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save deadlines")
})
requestUpdatePower(rt, powerDelta)
// Note: the pledge delta is expected to be zero, since pledge is not re-calculated for the extension.
// But in case that ever changes, we can do the right thing here.
notifyPledgeChanged(rt, pledgeDelta)
return nil
}
type TerminateSectorsParams struct {
Terminations []TerminationDeclaration
}
type TerminationDeclaration struct {
Deadline uint64
Partition uint64
Sectors *abi.BitField
}
type TerminateSectorsReturn struct {
// Set to true if all early termination work has been completed. When
// false, the miner may choose to repeatedly invoke TerminateSectors
// with no new sectors to process the remainder of the pending
// terminations. While pending terminations are outstanding, the miner
// will not be able to withdraw funds.
Done bool
}
// Marks some sectors as terminated at the present epoch, earlier than their
// scheduled termination, and adds these sectors to the early termination queue.
// This method then processes up to AddressedSectorsMax sectors and
// AddressedPartitionsMax partitions from the early termination queue,
// terminating deals, paying fines, and returning pledge collateral. While
// sectors remain in this queue:
//
// 1. The miner will be unable to withdraw funds.
// 2. The chain will process up to AddressedSectorsMax sectors and
// AddressedPartitionsMax per epoch until the queue is empty.
//
// The sectors are immediately ignored for Window PoSt proofs, and should be
// masked in the same way as faulty sectors. A miner terminating sectors in the
// current deadline must be careful to compute an appropriate Window PoSt proof
// for the sectors that will be active at the time the PoSt is submitted.
//
// This function may be invoked with no new sectors to explicitly process the
// next batch of sectors.
func (a Actor) TerminateSectors(rt Runtime, params *TerminateSectorsParams) *TerminateSectorsReturn {
// Note: this cannot terminate pre-committed but un-proven sectors.
// They must be allowed to expire (and deposit burnt).
toProcess := make(DeadlineSectorMap)
for _, term := range params.Terminations {
err := toProcess.Add(term.Deadline, term.Partition, term.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument,
"failed to process deadline %d, partition %d", term.Deadline, term.Partition,
)
}
err := toProcess.Check(AddressedPartitionsMax, AddressedSectorsMax)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "cannot process requested parameters")
var hadEarlyTerminations bool
var st State
store := adt.AsStore(rt)
currEpoch := rt.CurrEpoch()
powerDelta := NewPowerPairZero()
rt.State().Transaction(&st, func() {
hadEarlyTerminations = havePendingEarlyTerminations(rt, &st)
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(info.Worker)
deadlines, err := st.LoadDeadlines(adt.AsStore(rt))
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadlines")
// We're only reading the sectors, so there's no need to save this back.
// However, we still want to avoid re-loading this array per-partition.
sectors, err := LoadSectors(store, st.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors")
err = toProcess.ForEach(func(dlIdx uint64, partitionSectors PartitionSectorMap) error {
quant := st.QuantSpecForDeadline(dlIdx)
deadline, err := deadlines.LoadDeadline(store, dlIdx)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadline %d", dlIdx)
removedPower, err := deadline.TerminateSectors(store, sectors, currEpoch, partitionSectors, info.SectorSize, quant)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to terminate sectors in deadline %d", dlIdx)
st.EarlyTerminations.Set(dlIdx)
powerDelta = powerDelta.Sub(removedPower)
err = deadlines.UpdateDeadline(store, dlIdx, deadline)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to update deadline %d", dlIdx)
return nil
})
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to walk sectors")
err = st.SaveDeadlines(store, deadlines)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save deadlines")
})
// Now, try to process these sectors.
more := processEarlyTerminations(rt)
if more && !hadEarlyTerminations {
// We have remaining terminations, and we didn't _previously_
// have early terminations to process, schedule a cron job.
// NOTE: This isn't quite correct. If we repeatedly fill, empty,
// fill, and empty, the queue, we'll keep scheduling new cron
// jobs. However, in practice, that shouldn't be all that bad.
scheduleEarlyTerminationWork(rt)