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
/
Copy pathminer_actor.go
2846 lines (2404 loc) · 116 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"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/go-state-types/dline"
"github.com/filecoin-project/go-state-types/exitcode"
rtt "github.com/filecoin-project/go-state-types/rt"
miner0 "github.com/filecoin-project/specs-actors/actors/builtin/miner"
miner2 "github.com/filecoin-project/specs-actors/v2/actors/builtin/miner"
miner3 "github.com/filecoin-project/specs-actors/v3/actors/builtin/miner"
cid "github.com/ipfs/go-cid"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/v7/actors/builtin"
"github.com/filecoin-project/specs-actors/v7/actors/builtin/market"
"github.com/filecoin-project/specs-actors/v7/actors/builtin/power"
"github.com/filecoin-project/specs-actors/v7/actors/builtin/reward"
"github.com/filecoin-project/specs-actors/v7/actors/runtime"
"github.com/filecoin-project/specs-actors/v7/actors/runtime/proof"
. "github.com/filecoin-project/specs-actors/v7/actors/util"
"github.com/filecoin-project/specs-actors/v7/actors/util/adt"
"github.com/filecoin-project/specs-actors/v7/actors/util/smoothing"
)
type Runtime = runtime.Runtime
const (
// The first 1000 actor-specific codes are left open for user error, i.e. things that might
// actually happen without programming error in the actor code.
//ErrToBeDetermined = exitcode.FirstActorSpecificExitCode + iota
// The following errors are particular cases of illegal state.
// They're not expected to ever happen, but if they do, distinguished codes can help us
// diagnose the problem.
ErrBalanceInvariantBroken = 1000
)
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.ApplyRewards,
15: a.ReportConsensusFault,
16: a.WithdrawBalance,
17: a.ConfirmSectorProofsValid,
18: a.ChangeMultiaddrs,
19: a.CompactPartitions,
20: a.CompactSectorNumbers,
21: a.ConfirmUpdateWorkerKey,
22: a.RepayDebt,
23: a.ChangeOwnerAddress,
24: a.DisputeWindowedPoSt,
25: a.PreCommitSectorBatch,
26: a.ProveCommitAggregate,
}
}
func (a Actor) Code() cid.Cid {
return builtin.StorageMinerActorCodeID
}
func (a Actor) State() cbor.Er {
return new(State)
}
var _ runtime.VMActor = 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) *abi.EmptyValue {
rt.ValidateImmediateCallerIs(builtin.InitActorAddr)
checkControlAddresses(rt, params.ControlAddrs)
checkPeerInfo(rt, params.PeerId, params.Multiaddrs)
if !CanWindowPoStProof(params.WindowPoStProofType) {
rt.Abortf(exitcode.ErrIllegalArgument, "proof type %d not allowed for new miner actors", params.WindowPoStProofType)
}
owner := resolveControlAddress(rt, params.OwnerAddr)
worker := resolveWorkerAddress(rt, params.WorkerAddr)
controlAddrs := make([]addr.Address, 0, len(params.ControlAddrs))
for _, ca := range params.ControlAddrs {
resolved := resolveControlAddress(rt, ca)
controlAddrs = append(controlAddrs, resolved)
}
currEpoch := rt.CurrEpoch()
offset, err := assignProvingPeriodOffset(rt.Receiver(), currEpoch, rt.HashBlake2b)
builtin.RequireNoErr(rt, err, exitcode.ErrSerialization, "failed to assign proving period offset")
periodStart := currentProvingPeriodStart(currEpoch, offset)
builtin.RequireState(rt, periodStart <= currEpoch, "computed proving period start %d after current epoch %d", periodStart, currEpoch)
deadlineIndex := currentDeadlineIndex(currEpoch, periodStart)
builtin.RequireState(rt, deadlineIndex < WPoStPeriodDeadlines, "computed proving deadline index %d invalid", deadlineIndex)
info, err := ConstructMinerInfo(owner, worker, controlAddrs, params.PeerId, params.Multiaddrs, params.WindowPoStProofType)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to construct initial miner info")
infoCid := rt.StorePut(info)
store := adt.AsStore(rt)
state, err := ConstructState(store, infoCid, periodStart, deadlineIndex)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to construct state")
rt.StateCreate(state)
return nil
}
/////////////
// Control //
/////////////
// type GetControlAddressesReturn struct {
// Owner addr.Address
// Worker addr.Address
// ControlAddrs []addr.Address
// }
type GetControlAddressesReturn = miner2.GetControlAddressesReturn
func (a Actor) ControlAddresses(rt Runtime, _ *abi.EmptyValue) *GetControlAddressesReturn {
rt.ValidateImmediateCallerAcceptAny()
var st State
rt.StateReadonly(&st)
info := getMinerInfo(rt, &st)
return &GetControlAddressesReturn{
Owner: info.Owner,
Worker: info.Worker,
ControlAddrs: info.ControlAddresses,
}
}
//type ChangeWorkerAddressParams struct {
// NewWorker addr.Address
// NewControlAddrs []addr.Address
//}
type ChangeWorkerAddressParams = miner0.ChangeWorkerAddressParams
// ChangeWorkerAddress will ALWAYS overwrite the existing control addresses with the control addresses passed in the params.
// If a nil addresses slice is passed, the control addresses will be cleared.
// A worker change will be scheduled if the worker passed in the params is different from the existing worker.
func (a Actor) ChangeWorkerAddress(rt Runtime, params *ChangeWorkerAddressParams) *abi.EmptyValue {
checkControlAddresses(rt, params.NewControlAddrs)
newWorker := resolveWorkerAddress(rt, params.NewWorker)
var controlAddrs []addr.Address
for _, ca := range params.NewControlAddrs {
resolved := resolveControlAddress(rt, ca)
controlAddrs = append(controlAddrs, resolved)
}
var st State
rt.StateTransaction(&st, func() {
info := getMinerInfo(rt, &st)
// Only the Owner is allowed to change the newWorker and control addresses.
rt.ValidateImmediateCallerIs(info.Owner)
// save the new control addresses
info.ControlAddresses = controlAddrs
// save newWorker addr key change request
if newWorker != info.Worker && info.PendingWorkerKey == nil {
info.PendingWorkerKey = &WorkerKeyChange{
NewWorker: newWorker,
EffectiveAt: rt.CurrEpoch() + WorkerKeyChangeDelay,
}
}
err := st.SaveInfo(adt.AsStore(rt), info)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "could not save miner info")
})
return nil
}
// Triggers a worker address change if a change has been requested and its effective epoch has arrived.
func (a Actor) ConfirmUpdateWorkerKey(rt Runtime, params *abi.EmptyValue) *abi.EmptyValue {
var st State
rt.StateTransaction(&st, func() {
info := getMinerInfo(rt, &st)
// Only the Owner is allowed to change the newWorker.
rt.ValidateImmediateCallerIs(info.Owner)
processPendingWorker(info, rt, &st)
})
return nil
}
// Proposes or confirms a change of owner address.
// If invoked by the current owner, proposes a new owner address for confirmation. If the proposed address is the
// current owner address, revokes any existing proposal.
// If invoked by the previously proposed address, with the same proposal, changes the current owner address to be
// that proposed address.
func (a Actor) ChangeOwnerAddress(rt Runtime, newAddress *addr.Address) *abi.EmptyValue {
if newAddress.Empty() {
rt.Abortf(exitcode.ErrIllegalArgument, "empty address")
}
if newAddress.Protocol() != addr.ID {
rt.Abortf(exitcode.ErrIllegalArgument, "owner address must be an ID address")
}
var st State
rt.StateTransaction(&st, func() {
info := getMinerInfo(rt, &st)
if rt.Caller() == info.Owner || info.PendingOwnerAddress == nil {
// Propose new address.
rt.ValidateImmediateCallerIs(info.Owner)
info.PendingOwnerAddress = newAddress
} else { // info.PendingOwnerAddress != nil
// Confirm the proposal.
// This validates that the operator can in fact use the proposed new address to sign messages.
rt.ValidateImmediateCallerIs(*info.PendingOwnerAddress)
if *newAddress != *info.PendingOwnerAddress {
rt.Abortf(exitcode.ErrIllegalArgument, "expected confirmation of %v, got %v",
info.PendingOwnerAddress, newAddress)
}
info.Owner = *info.PendingOwnerAddress
}
// Clear any resulting no-op change.
if info.PendingOwnerAddress != nil && *info.PendingOwnerAddress == info.Owner {
info.PendingOwnerAddress = nil
}
err := st.SaveInfo(adt.AsStore(rt), info)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save miner info")
})
return nil
}
//type ChangePeerIDParams struct {
// NewID abi.PeerID
//}
type ChangePeerIDParams = miner0.ChangePeerIDParams
func (a Actor) ChangePeerID(rt Runtime, params *ChangePeerIDParams) *abi.EmptyValue {
checkPeerInfo(rt, params.NewID, nil)
var st State
rt.StateTransaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(append(info.ControlAddresses, info.Owner, 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
//}
type ChangeMultiaddrsParams = miner0.ChangeMultiaddrsParams
func (a Actor) ChangeMultiaddrs(rt Runtime, params *ChangeMultiaddrsParams) *abi.EmptyValue {
checkPeerInfo(rt, nil, params.NewMultiaddrs)
var st State
rt.StateTransaction(&st, func() {
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(append(info.ControlAddresses, info.Owner, 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 bitfield.BitField
//}
type PoStPartition = miner0.PoStPartition
// 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 []proof.PoStProof
// // The epoch at which these proofs is being committed to a particular chain.
// // NOTE: This field should be removed in the future. See
// // https://github.com/filecoin-project/specs-actors/issues/1094
// ChainCommitEpoch abi.ChainEpoch
// // The ticket randomness on the chain at the chain commit epoch.
// ChainCommitRand abi.Randomness
//}
type SubmitWindowedPoStParams = miner0.SubmitWindowedPoStParams
// Invoked by miner's worker address to submit their fallback post
func (a Actor) SubmitWindowedPoSt(rt Runtime, params *SubmitWindowedPoStParams) *abi.EmptyValue {
currEpoch := rt.CurrEpoch()
store := adt.AsStore(rt)
var st State
// Verify that the miner has passed exactly 1 proof.
if len(params.Proofs) != 1 {
rt.Abortf(exitcode.ErrIllegalArgument, "expected exactly one proof, got %d", len(params.Proofs))
}
if !CanWindowPoStProof(params.Proofs[0].PoStProof) {
rt.Abortf(exitcode.ErrIllegalArgument, "proof type %d not allowed", params.Proofs[0].PoStProof)
}
if params.Deadline >= WPoStPeriodDeadlines {
rt.Abortf(exitcode.ErrIllegalArgument, "invalid deadline %d of %d", params.Deadline, WPoStPeriodDeadlines)
}
// Technically, ChainCommitRand should be _exactly_ 32 bytes. However:
// 1. It's convenient to allow smaller slices when testing.
// 2. Nothing bad will happen if the caller provides too little randomness.
if len(params.ChainCommitRand) > abi.RandomnessLength {
rt.Abortf(exitcode.ErrIllegalArgument, "expected at most %d bytes of randomness, got %d", abi.RandomnessLength, len(params.ChainCommitRand))
}
var postResult *PoStResult
var info *MinerInfo
rt.StateTransaction(&st, func() {
info = getMinerInfo(rt, &st)
maxProofSize, err := info.WindowPoStProofType.ProofSize()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to determine max window post proof size")
rt.ValidateImmediateCallerIs(append(info.ControlAddresses, info.Owner, info.Worker)...)
// Make sure the miner is using the correct proof type.
if params.Proofs[0].PoStProof != info.WindowPoStProofType {
rt.Abortf(exitcode.ErrIllegalArgument, "expected proof of type %d, got proof of type %d", info.WindowPoStProofType, params.Proofs[0])
}
// Make sure the proof size doesn't exceed the max. We could probably check for an exact match, but this is safer.
if maxSize := maxProofSize * uint64(len(params.Partitions)); uint64(len(params.Proofs[0].ProofBytes)) > maxSize {
rt.Abortf(exitcode.ErrIllegalArgument, "expected proof to be smaller than %d bytes", maxSize)
}
// 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)
}
currDeadline := st.DeadlineInfo(currEpoch)
// 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)
}
// Verify that the PoSt was committed to the chain at most WPoStChallengeLookback+WPoStChallengeWindow in the past.
if params.ChainCommitEpoch < currDeadline.Challenge {
rt.Abortf(exitcode.ErrIllegalArgument, "expected chain commit epoch %d to be after %d", params.ChainCommitEpoch, currDeadline.Challenge)
}
if params.ChainCommitEpoch >= currEpoch {
rt.Abortf(exitcode.ErrIllegalArgument, "chain commit epoch %d must be less than the current epoch %d", params.ChainCommitEpoch, currEpoch)
}
// Verify the chain commit randomness.
commRand := rt.GetRandomnessFromTickets(crypto.DomainSeparationTag_PoStChainCommit, params.ChainCommitEpoch, nil)
if !bytes.Equal(commRand, params.ChainCommitRand) {
rt.Abortf(exitcode.ErrIllegalArgument, "post commit randomness mismatched")
}
sectors, err := LoadSectors(store, st.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors")
deadlines, err := st.LoadDeadlines(adt.AsStore(rt))
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadlines")
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're correct. Instead,
// it snapshots the deadline's state and the submitted proofs at the end of the challenge window and
// allows third-parties to dispute these proofs.
//
// While we could perform _all_ operations at the end of challenge window, we do as we can here to avoid
// overloading cron.
faultExpiration := currDeadline.Last() + FaultMaxAge
postResult, err = deadline.RecordProvenSectors(store, sectors, info.SectorSize, QuantSpecForDeadline(currDeadline), faultExpiration, params.Partitions)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to process post submission for deadline %d", params.Deadline)
// Make sure we actually proved something.
provenSectors, err := bitfield.SubtractBitField(postResult.Sectors, postResult.IgnoredSectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to determine proven sectors for deadline %d", params.Deadline)
noSectors, err := provenSectors.IsEmpty()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to determine if any sectors were proven", params.Deadline)
if noSectors {
// Abort verification if all sectors are (now) faults. There's nothing to prove.
// It's not rational for a miner to submit a Window PoSt marking *all* non-faulty sectors as skipped,
// since that will just cause them to pay a penalty at deadline end that would otherwise be zero
// if they had *not* declared them.
rt.Abortf(exitcode.ErrIllegalArgument, "cannot prove partitions with no active sectors")
}
// If we're not recovering power, record the proof for optimistic verification.
if postResult.RecoveredPower.IsZero() {
err = deadline.RecordPoStProofs(store, postResult.Partitions, params.Proofs)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to record proof for optimistic verification", params.Deadline)
} else {
// otherwise, check the proof
sectorInfos, err := sectors.LoadForProof(postResult.Sectors, postResult.IgnoredSectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors for post verification")
err = verifyWindowedPost(rt, currDeadline.Challenge, sectorInfos, params.Proofs)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "window post failed")
}
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)
rt.StateReadonly(&st)
err := st.CheckBalanceInvariants(rt.CurrentBalance())
builtin.RequireNoErr(rt, err, ErrBalanceInvariantBroken, "balance invariants broken")
return nil
}
// type DisputeWindowedPoStParams struct {
// Deadline uint64
// PoStIndex uint64 // only one is allowed at a time to avoid loading too many sector infos.
// }
type DisputeWindowedPoStParams = miner3.DisputeWindowedPoStParams
func (a Actor) DisputeWindowedPoSt(rt Runtime, params *DisputeWindowedPoStParams) *abi.EmptyValue {
rt.ValidateImmediateCallerType(builtin.CallerTypesSignable...)
reporter := rt.Caller()
if params.Deadline >= WPoStPeriodDeadlines {
rt.Abortf(exitcode.ErrIllegalArgument, "invalid deadline %d of %d", params.Deadline, WPoStPeriodDeadlines)
}
currEpoch := rt.CurrEpoch()
// Note: these are going to be slightly inaccurate as time
// will have moved on from when the post was actually
// submitted.
//
// However, these are estimates _anyways_.
epochReward := requestCurrentEpochBlockReward(rt)
pwrTotal := requestCurrentTotalPower(rt)
toBurn := abi.NewTokenAmount(0)
toReward := abi.NewTokenAmount(0)
pledgeDelta := abi.NewTokenAmount(0)
powerDelta := NewPowerPairZero()
var st State
rt.StateTransaction(&st, func() {
dlInfo := st.DeadlineInfo(currEpoch)
if !deadlineAvailableForOptimisticPoStDispute(dlInfo.PeriodStart, params.Deadline, currEpoch) {
rt.Abortf(exitcode.ErrForbidden, "can only dispute window posts during the dispute window (%d epochs after the challenge window closes)", WPoStDisputeWindow)
}
info := getMinerInfo(rt, &st)
penalisedPower := NewPowerPairZero()
store := adt.AsStore(rt)
// Check proof
{
// Find the proving period start for the deadline in question.
ppStart := dlInfo.PeriodStart
if dlInfo.Index < params.Deadline {
ppStart -= WPoStProvingPeriod
}
targetDeadline := NewDeadlineInfo(ppStart, params.Deadline, currEpoch)
// Load the target deadline.
deadlinesCurrent, err := st.LoadDeadlines(store)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadlines")
dlCurrent, err := deadlinesCurrent.LoadDeadline(store, params.Deadline)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load deadline")
// Take the post from the snapshot for dispute.
// This operation REMOVES the PoSt from the snapshot so
// it can't be disputed again. If this method fails,
// this operation must be rolled back.
partitions, proofs, err := dlCurrent.TakePoStProofs(store, params.PoStIndex)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load proof for dispute")
// Load the partition info we need for the dispute.
disputeInfo, err := dlCurrent.LoadPartitionsForDispute(store, partitions)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load partition info for dispute")
// This includes power that is no longer active (e.g., due to sector terminations).
// It must only be used for penalty calculations, not power adjustments.
penalisedPower = disputeInfo.DisputedPower
// Load sectors for the dispute.
sectors, err := LoadSectors(store, st.Sectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors array")
sectorInfos, err := sectors.LoadForProof(disputeInfo.AllSectorNos, disputeInfo.IgnoredSectorNos)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to load sectors to dispute window post")
// Check proof, we fail if validation succeeds.
err = verifyWindowedPost(rt, targetDeadline.Challenge, sectorInfos, proofs)
if err == nil {
rt.Abortf(exitcode.ErrIllegalArgument, "failed to dispute valid post")
return
}
rt.Log(rtt.INFO, "successfully disputed: %s", err)
// Ok, now we record faults. This always works because
// we don't allow compaction/moving sectors during the
// challenge window.
//
// However, some of these sectors may have been
// terminated. That's fine, we'll skip them.
faultExpirationEpoch := targetDeadline.Last() + FaultMaxAge
powerDelta, err = dlCurrent.RecordFaults(store, sectors, info.SectorSize, QuantSpecForDeadline(targetDeadline), faultExpirationEpoch, disputeInfo.DisputedSectors)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to declare faults")
err = deadlinesCurrent.UpdateDeadline(store, params.Deadline, dlCurrent)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to update deadline %d", params.Deadline)
err = st.SaveDeadlines(store, deadlinesCurrent)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to save deadlines")
}
// Penalties.
{
// Calculate the base penalty.
penaltyBase := PledgePenaltyForInvalidWindowPoSt(
epochReward.ThisEpochRewardSmoothed,
pwrTotal.QualityAdjPowerSmoothed,
penalisedPower.QA,
)
// Calculate the target reward.
rewardTarget := RewardForDisputedWindowPoSt(info.WindowPoStProofType, penalisedPower)
// Compute the target penalty by adding the
// base penalty to the target reward. We don't
// take reward out of the penalty as the miner
// could end up receiving a substantial
// portion of their fee back as a reward.
penaltyTarget := big.Add(penaltyBase, rewardTarget)
err := st.ApplyPenalty(penaltyTarget)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to apply penalty")
penaltyFromVesting, penaltyFromBalance, err := st.RepayPartialDebtInPriorityOrder(store, currEpoch, rt.CurrentBalance())
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to pay debt")
toBurn = big.Add(penaltyFromVesting, penaltyFromBalance)
// Now, move as much of the target reward as
// we can from the burn to the reward.
toReward = big.Min(toBurn, rewardTarget)
toBurn = big.Sub(toBurn, toReward)
pledgeDelta = penaltyFromVesting.Neg()
}
})
requestUpdatePower(rt, powerDelta)
if !toReward.IsZero() {
// Try to send the reward to the reporter.
code := rt.Send(reporter, builtin.MethodSend, nil, toReward, &builtin.Discard{})
// If we fail, log and burn the reward to make sure the balances remain correct.
if !code.IsSuccess() {
rt.Log(rtt.ERROR, "failed to send reward")
toBurn = big.Add(toBurn, toReward)
}
}
burnFunds(rt, toBurn)
notifyPledgeChanged(rt, pledgeDelta)
rt.StateReadonly(&st)
err := st.CheckBalanceInvariants(rt.CurrentBalance())
builtin.RequireNoErr(rt, err, ErrBalanceInvariantBroken, "balance invariants broken")
return nil
}
///////////////////////
// Sector Commitment //
///////////////////////
//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
//}
type PreCommitSectorParams = miner0.SectorPreCommitInfo
// Pledges to seal and commit a single sector.
// See PreCommitSectorBatch for details.
// This method may be deprecated and removed in the future.
func (a Actor) PreCommitSector(rt Runtime, params *PreCommitSectorParams) *abi.EmptyValue {
// This is a direct method call to self, not a message send.
batchParams := &PreCommitSectorBatchParams{Sectors: []miner0.SectorPreCommitInfo{*params}}
a.PreCommitSectorBatch(rt, batchParams)
return nil
}
type PreCommitSectorBatchParams struct {
Sectors []miner0.SectorPreCommitInfo
}
// Pledges the miner to seal and commit some new sectors.
// The caller specifies sector numbers, sealed sector data CIDs, seal randomness epoch, expiration, and the IDs
// of any storage deals contained in the sector data. The storage deal proposals must be already submitted
// to the storage market actor.
// A pre-commitment may specify an existing committed-capacity sector that the committed sector will replace
// when proven.
// This method calculates the sector's power, locks a pre-commit deposit for the sector, stores information about the
// sector in state and waits for it to be proven or expire.
func (a Actor) PreCommitSectorBatch(rt Runtime, params *PreCommitSectorBatchParams) *abi.EmptyValue {
currEpoch := rt.CurrEpoch()
if len(params.Sectors) == 0 {
rt.Abortf(exitcode.ErrIllegalArgument, "batch empty")
} else if len(params.Sectors) > PreCommitSectorBatchMaxSize {
rt.Abortf(exitcode.ErrIllegalArgument, "batch of %d too large, max %d", len(params.Sectors), PreCommitSectorBatchMaxSize)
}
// Check per-sector preconditions before opening state transaction or sending other messages.
challengeEarliest := currEpoch - MaxPreCommitRandomnessLookback
sectorsDeals := make([]market.SectorDeals, len(params.Sectors))
sectorNumbers := bitfield.New()
for i, precommit := range params.Sectors {
// Bitfied.IsSet() is fast when there are only locally-set values.
set, err := sectorNumbers.IsSet(uint64(precommit.SectorNumber))
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "error checking sector number")
if set {
rt.Abortf(exitcode.ErrIllegalArgument, "duplicate sector number %d", precommit.SectorNumber)
}
sectorNumbers.Set(uint64(precommit.SectorNumber))
if !CanPreCommitSealProof(precommit.SealProof) {
rt.Abortf(exitcode.ErrIllegalArgument, "unsupported seal proof type %v", precommit.SealProof)
}
if precommit.SectorNumber > abi.MaxSectorNumber {
rt.Abortf(exitcode.ErrIllegalArgument, "sector number %d out of range 0..(2^63-1)", precommit.SectorNumber)
}
if !precommit.SealedCID.Defined() {
rt.Abortf(exitcode.ErrIllegalArgument, "sealed CID undefined")
}
if precommit.SealedCID.Prefix() != SealedCIDPrefix {
rt.Abortf(exitcode.ErrIllegalArgument, "sealed CID had wrong prefix")
}
if precommit.SealRandEpoch >= currEpoch {
rt.Abortf(exitcode.ErrIllegalArgument, "seal challenge epoch %v must be before now %v", precommit.SealRandEpoch, rt.CurrEpoch())
}
if precommit.SealRandEpoch < challengeEarliest {
rt.Abortf(exitcode.ErrIllegalArgument, "seal challenge epoch %v too old, must be after %v", precommit.SealRandEpoch, challengeEarliest)
}
// Require sector lifetime meets minimum by assuming activation happens at last epoch permitted for seal proof.
// This could make sector maximum lifetime validation more lenient if the maximum sector limit isn't hit first.
maxActivation := currEpoch + MaxProveCommitDuration[precommit.SealProof]
validateExpiration(rt, maxActivation, precommit.Expiration, precommit.SealProof)
if precommit.ReplaceCapacity {
rt.Abortf(exitcode.SysErrForbidden, "cc upgrade through precommit discontinued, use lightweight cc upgrade instead")
}
sectorsDeals[i] = market.SectorDeals{
SectorExpiry: precommit.Expiration,
DealIDs: precommit.DealIDs,
}
}
// gather information from other actors
rewardStats := requestCurrentEpochBlockReward(rt)
pwrTotal := requestCurrentTotalPower(rt)
dealWeights := requestDealWeights(rt, sectorsDeals)
if len(dealWeights.Sectors) != len(params.Sectors) {
rt.Abortf(exitcode.ErrIllegalState, "deal weight request returned %d records, expected %d",
len(dealWeights.Sectors), len(params.Sectors))
}
store := adt.AsStore(rt)
var st State
var err error
feeToBurn := abi.NewTokenAmount(0)
var needsCron bool
rt.StateTransaction(&st, func() {
// Aggregate fee applies only when batching.
if len(params.Sectors) > 1 {
aggregateFee := AggregatePreCommitNetworkFee(len(params.Sectors), rt.BaseFee())
// AggregateFee applied to fee debt to consolidate burn with outstanding debts
err := st.ApplyPenalty(aggregateFee)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to apply penalty")
}
// available balance already accounts for fee debt so it is correct to call
// this before RepayDebts. We would have to
// subtract fee debt explicitly if we called this after.
availableBalance, err := st.GetAvailableBalance(rt.CurrentBalance())
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to calculate available balance")
feeToBurn = RepayDebtsOrAbort(rt, &st)
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(append(info.ControlAddresses, info.Owner, info.Worker)...)
if ConsensusFaultActive(info, currEpoch) {
rt.Abortf(exitcode.ErrForbidden, "pre-commit not allowed during active consensus fault")
}
chainInfos := make([]*SectorPreCommitOnChainInfo, len(params.Sectors))
totalDepositRequired := big.Zero()
cleanUpEvents := map[abi.ChainEpoch][]uint64{}
dealCountMax := SectorDealsMax(info.SectorSize)
for i, precommit := range params.Sectors {
// Sector must have the same Window PoSt proof type as the miner's recorded seal type.
sectorWPoStProof, err := precommit.SealProof.RegisteredWindowPoStProof()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "failed to lookup Window PoSt proof type for sector seal proof %d", precommit.SealProof)
if sectorWPoStProof != info.WindowPoStProofType {
rt.Abortf(exitcode.ErrIllegalArgument, "sector Window PoSt proof type %d must match miner Window PoSt proof type %d (seal proof type %d)",
sectorWPoStProof, info.WindowPoStProofType, precommit.SealProof)
}
if uint64(len(precommit.DealIDs)) > dealCountMax {
rt.Abortf(exitcode.ErrIllegalArgument, "too many deals for sector %d > %d", len(precommit.DealIDs), dealCountMax)
}
// Ensure total deal space does not exceed sector size.
dealWeight := dealWeights.Sectors[i]
if dealWeight.DealSpace > uint64(info.SectorSize) {
rt.Abortf(exitcode.ErrIllegalArgument, "deals too large to fit in sector %d > %d", dealWeight.DealSpace, info.SectorSize)
}
if precommit.ReplaceCapacity {
validateReplaceSector(rt, &st, store, &precommit)
}
// Estimate the sector weight using the current epoch as an estimate for activation,
// and compute the pre-commit deposit using that weight.
// The sector's power will be recalculated when it's proven.
duration := precommit.Expiration - currEpoch
sectorWeight := QAPowerForWeight(info.SectorSize, duration, dealWeight.DealWeight, dealWeight.VerifiedDealWeight)
depositReq := PreCommitDepositForPower(rewardStats.ThisEpochRewardSmoothed, pwrTotal.QualityAdjPowerSmoothed, sectorWeight)
// Build on-chain record.
chainInfos[i] = &SectorPreCommitOnChainInfo{
Info: SectorPreCommitInfo(precommit),
PreCommitDeposit: depositReq,
PreCommitEpoch: currEpoch,
DealWeight: dealWeight.DealWeight,
VerifiedDealWeight: dealWeight.VerifiedDealWeight,
}
totalDepositRequired = big.Add(totalDepositRequired, depositReq)
// Calculate pre-commit cleanup
msd, ok := MaxProveCommitDuration[precommit.SealProof]
if !ok {
rt.Abortf(exitcode.ErrIllegalArgument, "no max seal duration set for proof type: %d", precommit.SealProof)
}
// PreCommitCleanUpDelay > 0 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.
cleanUpBound := currEpoch + msd + ExpiredPreCommitCleanUpDelay
cleanUpEvents[cleanUpBound] = append(cleanUpEvents[cleanUpBound], uint64(precommit.SectorNumber))
}
// Batch update actor state.
if availableBalance.LessThan(totalDepositRequired) {
rt.Abortf(exitcode.ErrInsufficientFunds, "insufficient funds %v for pre-commit deposit: %v", availableBalance, totalDepositRequired)
}
err = st.AddPreCommitDeposit(totalDepositRequired)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to add pre-commit deposit %v", totalDepositRequired)
err = st.AllocateSectorNumbers(store, sectorNumbers, DenyCollisions)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to allocate sector ids %v", sectorNumbers)
err = st.PutPrecommittedSectors(store, chainInfos...)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to write pre-committed sectors")
err = st.AddPreCommitCleanUps(store, cleanUpEvents)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to add pre-commit expiry to queue")
// Activate miner cron
needsCron = !st.DeadlineCronActive
st.DeadlineCronActive = true
})
burnFunds(rt, feeToBurn)
rt.StateReadonly(&st)
err = st.CheckBalanceInvariants(rt.CurrentBalance())
builtin.RequireNoErr(rt, err, ErrBalanceInvariantBroken, "balance invariants broken")
if needsCron {
newDlInfo := st.DeadlineInfo(currEpoch)
enrollCronEvent(rt, newDlInfo.Last(), &CronEventPayload{
EventType: CronEventProvingDeadline,
})
}
return nil
}
type ProveCommitAggregateParams struct {
SectorNumbers bitfield.BitField
AggregateProof []byte
}
// Checks state of the corresponding sector pre-commitments and verifies aggregate proof of replication
// of these sectors. If valid, the sectors' deals are activated, sectors are assigned a deadline and charged pledge
// and precommit state is removed.
func (a Actor) ProveCommitAggregate(rt Runtime, params *ProveCommitAggregateParams) *abi.EmptyValue {
aggSectorsCount, err := params.SectorNumbers.Count()
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to count aggregated sectors")
if aggSectorsCount > MaxAggregatedSectors {
rt.Abortf(exitcode.ErrIllegalArgument, "too many sectors addressed, addressed %d want <= %d", aggSectorsCount, MaxAggregatedSectors)
} else if aggSectorsCount < MinAggregatedSectors {
rt.Abortf(exitcode.ErrIllegalArgument, "too few sectors addressed, addressed %d want >= %d", aggSectorsCount, MinAggregatedSectors)
}
if uint64(len(params.AggregateProof)) > MaxAggregateProofSize {
rt.Abortf(exitcode.ErrIllegalArgument, "sector prove-commit proof of size %d exceeds max size of %d",
len(params.AggregateProof), MaxAggregateProofSize)
}
store := adt.AsStore(rt)
var st State
rt.StateReadonly(&st)
info := getMinerInfo(rt, &st)
rt.ValidateImmediateCallerIs(append(info.ControlAddresses, info.Owner, info.Worker)...)
precommits, err := st.GetAllPrecommittedSectors(store, params.SectorNumbers)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to get precommits")
// compute data commitments and validate each precommit
computeDataCommitmentsInputs := make([]*market.SectorDataSpec, len(precommits))
precommitsToConfirm := []*SectorPreCommitOnChainInfo{}
for i, precommit := range precommits {
msd, ok := MaxProveCommitDuration[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.Log(rtt.WARN, "skipping commitment for sector %d, too late at %d, due %d", precommit.Info.SectorNumber, rt.CurrEpoch(), proveCommitDue)
} else {
precommitsToConfirm = append(precommitsToConfirm, precommit)
}
// All sealProof types should match
if i >= 1 {
prevSealProof := precommits[i-1].Info.SealProof
builtin.RequireState(rt, prevSealProof == precommit.Info.SealProof, "aggregate contains mismatched seal proofs %d and %d", prevSealProof, precommit.Info.SealProof)
}
computeDataCommitmentsInputs[i] = &market.SectorDataSpec{
SectorType: precommit.Info.SealProof,
DealIDs: precommit.Info.DealIDs,
}
}
// compute shared verification inputs
commDs := requestUnsealedSectorCIDs(rt, computeDataCommitmentsInputs...)
svis := make([]proof.AggregateSealVerifyInfo, 0)
receiver := rt.Receiver()
minerActorID, err := addr.IDFromAddress(receiver)
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "runtime provided non-ID receiver address %s", receiver)
buf := new(bytes.Buffer)
err = receiver.MarshalCBOR(buf)
receiverBytes := buf.Bytes()
builtin.RequireNoErr(rt, err, exitcode.ErrSerialization, "failed to marshal address for seal verification challenge")
for i, precommit := range precommits {
interactiveEpoch := precommit.PreCommitEpoch + PreCommitChallengeDelay
if rt.CurrEpoch() <= interactiveEpoch {
rt.Abortf(exitcode.ErrForbidden, "too early to prove sector %d", precommit.Info.SectorNumber)
}
svInfoRandomness := rt.GetRandomnessFromTickets(crypto.DomainSeparationTag_SealRandomness, precommit.Info.SealRandEpoch, receiverBytes)
svInfoInteractiveRandomness := rt.GetRandomnessFromBeacon(crypto.DomainSeparationTag_InteractiveSealChallengeSeed, interactiveEpoch, receiverBytes)
svi := proof.AggregateSealVerifyInfo{
Number: precommit.Info.SectorNumber,
InteractiveRandomness: abi.InteractiveSealRandomness(svInfoInteractiveRandomness),
Randomness: abi.SealRandomness(svInfoRandomness),
SealedCID: precommit.Info.SealedCID,
UnsealedCID: commDs[i],
}
svis = append(svis, svi)
}
builtin.RequireState(rt, len(precommits) > 0, "bitfield non-empty but zero precommits read from state")
sealProof := precommits[0].Info.SealProof
err = rt.VerifyAggregateSeals(
proof.AggregateSealVerifyProofAndInfos{
Infos: svis,
Proof: params.AggregateProof,
Miner: abi.ActorID(minerActorID),
SealProof: sealProof,
AggregateProof: abi.RegisteredAggregationProof_SnarkPackV1,
})
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalArgument, "aggregate seal verify failed")
rew := requestCurrentEpochBlockReward(rt)
pwr := requestCurrentTotalPower(rt)
confirmSectorProofsValid(rt, precommitsToConfirm, rew.ThisEpochBaselinePower, rew.ThisEpochRewardSmoothed, pwr.QualityAdjPowerSmoothed)
// Compute and burn the aggregate network fee. We need to re-load the state as
// confirmSectorProofsValid can change it.
rt.StateReadonly(&st)
aggregateFee := AggregateProveCommitNetworkFee(len(precommitsToConfirm), rt.BaseFee())
unlockedBalance, err := st.GetUnlockedBalance(rt.CurrentBalance())
builtin.RequireNoErr(rt, err, exitcode.ErrIllegalState, "failed to determine unlocked balance")
if unlockedBalance.LessThan(aggregateFee) {
rt.Abortf(exitcode.ErrInsufficientFunds,
"remaining unlocked funds after prove-commit (%s) are insufficient to pay aggregation fee of %s",
unlockedBalance, aggregateFee,
)
}
burnFunds(rt, aggregateFee)
err = st.CheckBalanceInvariants(rt.CurrentBalance())
builtin.RequireNoErr(rt, err, ErrBalanceInvariantBroken, "balance invariants broken")
return nil
}
//type ProveCommitSectorParams struct {
// SectorNumber abi.SectorNumber
// Proof []byte
//}
type ProveCommitSectorParams = miner0.ProveCommitSectorParams
// 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) *abi.EmptyValue {
rt.ValidateImmediateCallerAcceptAny()
if params.SectorNumber > abi.MaxSectorNumber {
rt.Abortf(exitcode.ErrIllegalArgument, "sector number greater than maximum")
}