-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathmod.rs
4345 lines (3876 loc) · 160 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use log::{error, info, warn};
mod bitfield_queue;
mod deadline_assignment;
mod deadline_state;
mod deadlines;
mod expiration_queue;
mod monies;
mod partition_state;
mod policy;
mod sector_map;
mod sectors;
mod state;
mod termination;
mod types;
mod vesting_state;
pub use bitfield_queue::*;
pub use deadline_assignment::*;
pub use deadline_state::*;
pub use deadlines::*;
pub use expiration_queue::*;
pub use monies::*;
pub use partition_state::*;
pub use policy::*;
pub use sector_map::*;
pub use sectors::*;
pub use state::*;
pub use termination::*;
pub use types::*;
pub use vesting_state::*;
use crate::{
account::Method as AccountMethod,
actor_error,
market::{self, ActivateDealsParams, ComputeDataCommitmentReturn, SectorDataSpec, SectorDeals},
power::MAX_MINER_PROVE_COMMITS_PER_EPOCH,
};
use crate::{
is_principal, smooth::FilterEstimate, ACCOUNT_ACTOR_CODE_ID, BURNT_FUNDS_ACTOR_ADDR,
CALLER_TYPES_SIGNABLE, INIT_ACTOR_ADDR, REWARD_ACTOR_ADDR, STORAGE_MARKET_ACTOR_ADDR,
STORAGE_POWER_ACTOR_ADDR,
};
use crate::{
market::{
ComputeDataCommitmentParamsRef, Method as MarketMethod, OnMinerSectorsTerminateParams,
OnMinerSectorsTerminateParamsRef, VerifyDealsForActivationParamsRef,
VerifyDealsForActivationReturn,
},
power::CurrentTotalPowerReturn,
};
use crate::{
power::{EnrollCronEventParams, Method as PowerMethod},
reward::ThisEpochRewardReturn,
ActorDowncast,
};
use address::{Address, Payload, Protocol};
use bitfield::{BitField, UnvalidatedBitField, Validate};
use byteorder::{BigEndian, ByteOrder, WriteBytesExt};
use cid::{Cid, Code::Blake2b256, Prefix};
use clock::ChainEpoch;
use crypto::DomainSeparationTag::{
self, InteractiveSealChallengeSeed, SealRandomness, WindowedPoStChallengeSeed,
};
use encoding::{BytesDe, Cbor};
use fil_types::{
deadlines::DeadlineInfo, AggregateSealVerifyInfo, AggregateSealVerifyProofAndInfos,
InteractiveSealRandomness, PoStProof, PoStRandomness, RegisteredSealProof,
SealRandomness as SealRandom, SealVerifyInfo, SealVerifyParams, SectorID, SectorInfo,
SectorNumber, SectorSize, WindowPoStVerifyInfo, MAX_SECTOR_NUMBER, RANDOMNESS_LENGTH,
};
use ipld_blockstore::BlockStore;
use num_bigint::bigint_ser::BigIntSer;
use num_bigint::BigInt;
use num_derive::FromPrimitive;
use num_traits::{FromPrimitive, Signed, Zero};
use runtime::{ActorCode, Runtime};
use std::collections::{hash_map::Entry, HashMap};
use std::error::Error as StdError;
use std::{iter, ops::Neg};
use vm::{
ActorError, DealID, ExitCode, MethodNum, Serialized, TokenAmount, METHOD_CONSTRUCTOR,
METHOD_SEND,
};
// 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.
// 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.
use ExitCode::ErrPlaceholder as ErrBalanceInvariantBroken;
// * Updated to specs-actors commit: 17d3c602059e5c48407fb3c34343da87e6ea6586 (v0.9.12)
/// Storage Miner actor methods available
#[derive(FromPrimitive)]
#[repr(u64)]
pub enum Method {
Constructor = METHOD_CONSTRUCTOR,
ControlAddresses = 2,
ChangeWorkerAddress = 3,
ChangePeerID = 4,
SubmitWindowedPoSt = 5,
PreCommitSector = 6,
ProveCommitSector = 7,
ExtendSectorExpiration = 8,
TerminateSectors = 9,
DeclareFaults = 10,
DeclareFaultsRecovered = 11,
OnDeferredCronEvent = 12,
CheckSectorProven = 13,
ApplyRewards = 14,
ReportConsensusFault = 15,
WithdrawBalance = 16,
ConfirmSectorProofsValid = 17,
ChangeMultiaddrs = 18,
CompactPartitions = 19,
CompactSectorNumbers = 20,
ConfirmUpdateWorkerKey = 21,
RepayDebt = 22,
ChangeOwnerAddress = 23,
DisputeWindowedPoSt = 24,
PreCommitSectorBatch = 25,
ProveCommitAggregate = 26,
}
/// Miner Actor
/// here in order to update the Power Actor to v3.
pub struct Actor;
impl Actor {
pub fn constructor<BS, RT>(
rt: &mut RT,
params: MinerConstructorParams,
) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
rt.validate_immediate_caller_is(&[*INIT_ACTOR_ADDR])?;
check_control_addresses(¶ms.control_addresses)?;
check_peer_info(¶ms.peer_id, ¶ms.multi_addresses)?;
let owner = resolve_control_address(rt, params.owner)?;
let worker = resolve_worker_address(rt, params.worker)?;
let control_addresses: Vec<_> = params
.control_addresses
.into_iter()
.map(|address| resolve_control_address(rt, address))
.collect::<Result<_, _>>()?;
let current_epoch = rt.curr_epoch();
let blake2b = |b: &[u8]| rt.hash_blake2b(b);
let offset = assign_proving_period_offset(*rt.message().receiver(), current_epoch, blake2b)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrSerialization,
"failed to assign proving period offset",
)
})?;
let period_start = current_proving_period_start(current_epoch, offset);
if period_start > current_epoch {
return Err(actor_error!(
ErrIllegalState,
"computed proving period start {} after current epoch {}",
period_start,
current_epoch
));
}
let deadline_idx = current_deadline_index(current_epoch, period_start);
if deadline_idx >= WPOST_PERIOD_DEADLINES as usize {
return Err(actor_error!(
ErrIllegalState,
"computed proving deadline index {} invalid",
deadline_idx
));
}
let info = MinerInfo::new(
owner,
worker,
control_addresses,
params.peer_id,
params.multi_addresses,
params.window_post_proof_type,
)
.map_err(|e| {
actor_error!(
ErrIllegalState,
"failed to construct initial miner info: {}",
e
)
})?;
let info_cid = rt.store().put(&info, Blake2b256).map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
"failed to construct illegal state",
)
})?;
let st = State::new(rt.store(), info_cid, period_start, deadline_idx).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to construct state")
})?;
rt.create(&st)?;
Ok(())
}
fn control_addresses<BS, RT>(rt: &mut RT) -> Result<GetControlAddressesReturn, ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
rt.validate_immediate_caller_accept_any()?;
let state: State = rt.state()?;
let info = get_miner_info(rt.store(), &state)?;
Ok(GetControlAddressesReturn {
owner: info.owner,
worker: info.worker,
control_addresses: info.control_addresses,
})
}
/// Will ALWAYS overwrite the existing control addresses with the control addresses passed in the params.
/// If an empty addresses vector 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.
fn change_worker_address<BS, RT>(
rt: &mut RT,
params: ChangeWorkerAddressParams,
) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
check_control_addresses(¶ms.new_control_addresses)?;
let new_worker = resolve_worker_address(rt, params.new_worker)?;
let control_addresses: Vec<Address> = params
.new_control_addresses
.into_iter()
.map(|address| resolve_control_address(rt, address))
.collect::<Result<_, _>>()?;
rt.transaction(|state: &mut State, rt| {
let mut info = get_miner_info(rt.store(), state)?;
// Only the Owner is allowed to change the new_worker and control addresses.
rt.validate_immediate_caller_is(std::iter::once(&info.owner))?;
// save the new control addresses
info.control_addresses = control_addresses;
// save new_worker addr key change request
if new_worker != info.worker && info.pending_worker_key.is_none() {
info.pending_worker_key = Some(WorkerKeyChange {
new_worker,
effective_at: rt.curr_epoch() + WORKER_KEY_CHANGE_DELAY,
})
}
state.save_info(rt.store(), &info).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "could not save miner info")
})?;
Ok(())
})?;
Ok(())
}
/// Triggers a worker address change if a change has been requested and its effective epoch has arrived.
fn confirm_update_worker_key<BS, RT>(rt: &mut RT) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
rt.transaction(|state: &mut State, rt| {
let mut info = get_miner_info(rt.store(), &state)?;
rt.validate_immediate_caller_is(std::iter::once(&info.owner))?;
process_pending_worker(&mut info, rt, state)?;
Ok(())
})
}
/// 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.
fn change_owner_address<BS, RT>(rt: &mut RT, new_address: Address) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
// * Cannot match go checking for undef address, does go impl allow this to be
// * deserialized over the wire? If so, a workaround will be needed
if !matches!(new_address.protocol(), Protocol::ID) {
return Err(actor_error!(
ErrIllegalArgument,
"owner address must be an ID address"
));
}
rt.transaction(|state: &mut State, rt| {
let mut info = get_miner_info(rt.store(), &state)?;
if rt.message().caller() == &info.owner || info.pending_owner_address.is_none() {
rt.validate_immediate_caller_is(std::iter::once(&info.owner))?;
info.pending_owner_address = Some(new_address);
} else {
let pending_address = info.pending_owner_address.unwrap();
rt.validate_immediate_caller_is(std::iter::once(&pending_address))?;
if new_address != pending_address {
return Err(actor_error!(
ErrIllegalArgument,
"expected confirmation of {} got {}",
pending_address,
new_address
));
}
info.owner = pending_address;
}
// Clear any no-op change
if let Some(p_addr) = info.pending_owner_address {
if p_addr == info.owner {
info.pending_owner_address = None;
}
}
state.save_info(rt.store(), &info).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to save miner info")
})?;
Ok(())
})
}
fn change_peer_id<BS, RT>(rt: &mut RT, params: ChangePeerIDParams) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
check_peer_info(¶ms.new_id, &[])?;
rt.transaction(|state: &mut State, rt| {
let mut info = get_miner_info(rt.store(), state)?;
rt.validate_immediate_caller_is(
info.control_addresses
.iter()
.chain(&[info.worker, info.owner]),
)?;
info.peer_id = params.new_id;
state.save_info(rt.store(), &info).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "could not save miner info")
})?;
Ok(())
})?;
Ok(())
}
fn change_multiaddresses<BS, RT>(
rt: &mut RT,
params: ChangeMultiaddrsParams,
) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
check_peer_info(&[], ¶ms.new_multi_addrs)?;
rt.transaction(|state: &mut State, rt| {
let mut info = get_miner_info(rt.store(), state)?;
rt.validate_immediate_caller_is(
info.control_addresses
.iter()
.chain(&[info.worker, info.owner]),
)?;
info.multi_address = params.new_multi_addrs;
state.save_info(rt.store(), &info).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "could not save miner info")
})?;
Ok(())
})?;
Ok(())
}
/// Invoked by miner's worker address to submit their fallback post
fn submit_windowed_post<BS, RT>(
rt: &mut RT,
mut params: SubmitWindowedPoStParams,
) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
let current_epoch = rt.curr_epoch();
if params.deadline >= WPOST_PERIOD_DEADLINES as usize {
return Err(actor_error!(
ErrIllegalArgument,
"invalid deadline {} of {}",
params.deadline,
WPOST_PERIOD_DEADLINES
));
}
if params.chain_commit_rand.0.len() > RANDOMNESS_LENGTH {
return Err(actor_error!(
ErrIllegalArgument,
"expected at most {} bytes of randomness, got {}",
RANDOMNESS_LENGTH,
params.chain_commit_rand.0.len()
));
}
let post_result = rt.transaction(|state: &mut State, rt| {
let info = get_miner_info(rt.store(), state)?;
let max_proof_size = info.window_post_proof_type.proof_size().map_err(|e| {
actor_error!(
ErrIllegalState,
"failed to determine max window post proof size: {}",
e
)
})?;
rt.validate_immediate_caller_is(
info.control_addresses
.iter()
.chain(&[info.worker, info.owner]),
)?;
// Verify that the miner has passed exactly 1 proof.
if params.proofs.len() != 1 {
return Err(actor_error!(
ErrIllegalArgument,
"expected exactly one proof, got {}",
params.proofs.len()
));
}
// Make sure the miner is using the correct proof type.
if params.proofs[0].post_proof != info.window_post_proof_type {
return Err(actor_error!(
ErrIllegalArgument,
"expected proof of type {:?}, got {:?}",
params.proofs[0].post_proof,
info.window_post_proof_type
));
}
// Make sure the proof size doesn't exceed the max. We could probably check for an exact match, but this is safer.
let max_size = max_proof_size * params.partitions.len();
if params.proofs[0].proof_bytes.len() > max_size {
return Err(actor_error!(
ErrIllegalArgument,
"expect proof to be smaller than {} bytes",
max_size
));
}
// Validate that the miner didn't try to prove too many partitions at once.
let submission_partition_limit =
load_partitions_sectors_max(info.window_post_partition_sectors);
if params.partitions.len() as u64 > submission_partition_limit {
return Err(actor_error!(
ErrIllegalArgument,
"too many partitions {}, limit {}",
params.partitions.len(),
submission_partition_limit
));
}
let current_deadline = state.deadline_info(current_epoch);
// 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 !current_deadline.is_open() {
return Err(actor_error!(
ErrIllegalState,
"proving period {} not yet open at {}",
current_deadline.period_start,
current_epoch
));
}
// The miner may only submit a proof for the current deadline.
if params.deadline != current_deadline.index as usize {
return Err(actor_error!(
ErrIllegalArgument,
"invalid deadline {} at epoch {}, expected {}",
params.deadline,
current_epoch,
current_deadline.index
));
}
// Verify that the PoSt was committed to the chain at most
// WPoStChallengeLookback+WPoStChallengeWindow in the past.
if params.chain_commit_epoch < current_deadline.challenge {
return Err(actor_error!(
ErrIllegalArgument,
"expected chain commit epoch {} to be after {}",
params.chain_commit_epoch,
current_deadline.challenge
));
}
if params.chain_commit_epoch >= current_epoch {
return Err(actor_error!(
ErrIllegalArgument,
"chain commit epoch {} must be less tha the current epoch {}",
params.chain_commit_epoch,
current_epoch
));
}
// Verify the chain commit randomness
let comm_rand = rt.get_randomness_from_tickets(
DomainSeparationTag::PoStChainCommit,
params.chain_commit_epoch,
&[],
)?;
if comm_rand != params.chain_commit_rand {
return Err(actor_error!(
ErrIllegalArgument,
"post commit randomness mismatched"
));
}
let sectors = Sectors::load(rt.store(), &state.sectors).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors")
})?;
let mut deadlines = state
.load_deadlines(rt.store())
.map_err(|e| e.wrap("failed to load deadlines"))?;
let mut deadline = deadlines
.load_deadline(rt.store(), params.deadline)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
format!("failed to load deadline {}", 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.
let fault_expiration = current_deadline.last() + FAULT_MAX_AGE;
let post_result = deadline
.record_proven_sectors(
rt.store(),
§ors,
info.sector_size,
current_deadline.quant_spec(),
fault_expiration,
&mut params.partitions,
)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
format!(
"failed to process post submission for deadline {}",
params.deadline
),
)
})?;
// Make sure we actually proved something.
let proven_sectors = &post_result.sectors - &post_result.ignored_sectors;
if proven_sectors.is_empty() {
// 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.
return Err(actor_error!(
ErrIllegalArgument,
"cannot prove partitions with no active sectors"
));
}
// If we're not recovering power, record the proof for optimistic verification.
if post_result.recovered_power.is_zero() {
deadline
.record_post_proofs(rt.store(), &post_result.partitions, ¶ms.proofs)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
"failed to record proof for optimistic verification",
)
})?
} else {
// 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.
let sector_infos = sectors
.load_for_proof(&post_result.sectors, &post_result.ignored_sectors)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
"failed to load sectors for post verification",
)
})?;
verify_windowed_post(rt, current_deadline.challenge, §or_infos, params.proofs)
.map_err(|e| e.wrap("window post failed"))?;
}
let deadline_idx = params.deadline;
deadlines
.update_deadline(rt.store(), params.deadline, &deadline)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
format!("failed to update deadline {}", deadline_idx),
)
})?;
state.save_deadlines(rt.store(), deadlines).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to save deadlines")
})?;
Ok(post_result)
})?;
// 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
request_update_power(rt, post_result.power_delta)?;
let state: State = rt.state()?;
state
.check_balance_invariants(&rt.current_balance()?)
.map_err(|e| {
ActorError::new(
ErrBalanceInvariantBroken,
format!("balance invariants broken: {}", e),
)
})?;
Ok(())
}
/// 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.
fn prove_commit_aggregate<BS, RT>(
rt: &mut RT,
mut params: ProveCommitAggregateParams,
) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
let sector_numbers = params
.sector_numbers
.validate()
.map_err(|e| actor_error!(ErrIllegalArgument, "Invalid Bitfield argument:{}", e))?;
let agg_sectors_count = sector_numbers.len();
if agg_sectors_count > MAX_AGGREGATED_SECTORS {
return Err(actor_error!(
ErrIllegalArgument,
"too many sectors addressed, addressed {} want <= {}",
agg_sectors_count,
MAX_AGGREGATED_SECTORS
));
} else if agg_sectors_count < MIN_AGGREGATED_SECTORS {
return Err(actor_error!(
ErrIllegalArgument,
"too few sectors addressed, addressed {} want >= {}",
agg_sectors_count,
MIN_AGGREGATED_SECTORS
));
}
if params.aggregate_proof.len() > MAX_AGGREGATED_PROOF_SIZE {
return Err(actor_error!(
ErrIllegalArgument,
"sector prove-commit proof of size {} exceeds max size of {}",
params.aggregate_proof.len(),
MAX_AGGREGATED_PROOF_SIZE
));
}
let state: State = rt.state()?;
let info = get_miner_info(rt.store(), &state)?;
rt.validate_immediate_caller_is(
info.control_addresses
.iter()
.chain(&[info.worker, info.owner]),
)?;
let store = rt.store();
let precommits = state
.get_all_precommitted_sectors(store, sector_numbers)
.map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to get precommits")
})?;
// compute data commitments and validate each precommit
let mut compute_data_commitments_inputs = Vec::with_capacity(precommits.len());
let mut precommits_to_confirm = Vec::new();
for (i, precommit) in precommits.iter().enumerate() {
let msd = max_prove_commit_duration(precommit.info.seal_proof).ok_or_else(|| {
actor_error!(
ErrIllegalState,
"no max seal duration for proof type: {}",
i64::from(precommit.info.seal_proof)
)
})?;
let prove_commit_due = precommit.pre_commit_epoch + msd;
if rt.curr_epoch() > prove_commit_due {
log::warn!(
"skipping commitment for sector {}, too late at {}, due {}",
precommit.info.sector_number,
rt.curr_epoch(),
prove_commit_due,
)
} else {
precommits_to_confirm.push(precommit.clone());
}
// All seal proof types should match
if i >= 1 {
let prev_seal_proof = precommits[i - 1].info.seal_proof;
if prev_seal_proof != precommit.info.seal_proof {
return Err(actor_error!(
ErrIllegalState,
"aggregate contains mismatched seal proofs {} and {}",
i64::from(prev_seal_proof),
i64::from(precommit.info.seal_proof)
));
}
}
compute_data_commitments_inputs.push(SectorDataSpec {
deal_ids: precommit.info.deal_ids.clone(),
sector_type: precommit.info.seal_proof,
});
}
let comm_ds = request_unsealed_sector_cids(rt, &compute_data_commitments_inputs)?;
let mut svis = Vec::new();
let miner_actor_id: u64 = if let Payload::ID(i) = rt.message().receiver().payload() {
*i
} else {
return Err(actor_error!(
ErrIllegalState,
"runtime provided non-ID receiver address {}",
rt.message().receiver()
));
};
let receiver_bytes = rt.message().receiver().marshal_cbor().map_err(|e| {
ActorError::from(e).wrap("failed to marshal address for seal verification challenge")
})?;
for (i, precommit) in precommits.iter().enumerate() {
let interactive_epoch = precommit.pre_commit_epoch + PRE_COMMIT_CHALLENGE_DELAY;
if rt.curr_epoch() <= interactive_epoch {
return Err(actor_error!(
ErrForbidden,
"too early to prove sector {}",
precommit.info.sector_number
));
}
let sv_info_randomness = rt.get_randomness_from_tickets(
SealRandomness,
precommit.info.seal_rand_epoch,
&receiver_bytes,
)?;
let sv_info_interactive_randomness = rt.get_randomness_from_beacon(
InteractiveSealChallengeSeed,
interactive_epoch,
&receiver_bytes,
)?;
let svi = AggregateSealVerifyInfo {
sector_number: precommit.info.sector_number,
randomness: sv_info_randomness,
interactive_randomness: sv_info_interactive_randomness,
sealed_cid: precommit.info.sealed_cid,
unsealed_cid: comm_ds[i],
};
svis.push(svi);
}
let seal_proof = precommits[0].info.seal_proof;
if precommits.is_empty() {
return Err(actor_error!(
ErrIllegalState,
"bitfield non-empty but zero precommits read from state"
));
}
rt.verify_aggregate_seals(&AggregateSealVerifyProofAndInfos {
miner: miner_actor_id,
seal_proof,
aggregate_proof: fil_types::RegisteredAggregateProof::SnarkPackV1,
proof: params.aggregate_proof,
infos: svis,
})
.map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalArgument, "aggregate seal verify failed")
})?;
confirm_sector_proofs_valid_internal(rt, precommits_to_confirm.clone())?;
// Compute and burn the aggregate network fee. We need to re-load the state as
// confirmSectorProofsValid can change it.
let state: State = rt.state()?;
let aggregate_fee =
aggregate_network_fee(precommits_to_confirm.len() as i64, rt.base_fee());
let unlocked_balance = state
.get_unlocked_balance(&rt.current_balance()?)
.map_err(|_e| actor_error!(ErrIllegalState, "failed to determine unlocked balance"))?;
if unlocked_balance < aggregate_fee {
return Err(actor_error!(
ErrInsufficientFunds,
"remaining unlocked funds after prove-commit {} are insufficient to pay aggregation fee of {}",
unlocked_balance,
aggregate_fee
));
}
burn_funds(rt, aggregate_fee)?;
state
.check_balance_invariants(&rt.current_balance()?)
.map_err(|e| {
ActorError::new(
ErrBalanceInvariantBroken,
format!("balance invariants broken: {}", e),
)
})?;
Ok(())
}
fn dispute_windowed_post<BS, RT>(
rt: &mut RT,
params: DisputeWindowedPoStParams,
) -> Result<(), ActorError>
where
BS: BlockStore,
RT: Runtime<BS>,
{
rt.validate_immediate_caller_type(CALLER_TYPES_SIGNABLE.iter())?;
let reporter = *rt.message().caller();
if params.deadline >= WPOST_PERIOD_DEADLINES as usize {
return Err(actor_error!(
ErrIllegalArgument,
"invalid deadline {} of {}",
params.deadline,
WPOST_PERIOD_DEADLINES
));
}
let current_epoch = rt.curr_epoch();
// 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_.
let epoch_reward = request_current_epoch_block_reward(rt)?;
let power_total = request_current_total_power(rt)?;
let (pledge_delta, mut to_burn, power_delta, to_reward) =
rt.transaction(|st: &mut State, rt| {
let dl_info = st.deadline_info(current_epoch);
if !deadline_available_for_optimistic_post_dispute(
dl_info.period_start,
params.deadline,
current_epoch,
) {
return Err(actor_error!(
ErrForbidden,
"can only dispute window posts during the dispute window\
({} epochs after the challenge window closes)",
WPOST_DISPUTE_WINDOW
));
}
let info = get_miner_info(rt.store(), st)?;
// --- check proof ---
// Find the proving period start for the deadline in question.
let mut pp_start = dl_info.period_start;
if dl_info.index < params.deadline as u64 {
pp_start -= WPOST_PROVING_PERIOD
}
let target_deadline = new_deadline_info(pp_start, params.deadline, current_epoch);
// Load the target deadline
let mut deadlines_current = st
.load_deadlines(rt.store())
.map_err(|e| e.wrap("failed to load deadlines"))?;
let mut dl_current = deadlines_current
.load_deadline(rt.store(), params.deadline)
.map_err(|e| {
e.downcast_default(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.
let (partitions, proofs) = dl_current
.take_post_proofs(rt.store(), params.post_index)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
"failed to load proof for dispute",
)
})?;
// Load the partition info we need for the dispute.
let mut dispute_info = dl_current
.load_partitions_for_dispute(rt.store(), partitions)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
"failed to load partition 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.
let penalised_power = dispute_info.disputed_power.clone();
// Load sectors for the dispute.
let sectors = Sectors::load(rt.store(), &st.sectors).map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to load sectors array")
})?;
let sector_infos = sectors
.load_for_proof(
&dispute_info.all_sector_nos,
&dispute_info.ignored_sector_nos,
)
.map_err(|e| {
e.downcast_default(
ExitCode::ErrIllegalState,
"failed to load sectors to dispute window post",
)
})?;
// Check proof, we fail if validation succeeds.
match verify_windowed_post(rt, target_deadline.challenge, §or_infos, proofs) {
Ok(()) => {
return Err(actor_error!(
ErrIllegalArgument,
"failed to dispute valid post"
));
}
Err(e) => {
info!("Successfully disputed: {}", e);
}
}
// 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.
let fault_expiration_epoch = target_deadline.last() + FAULT_MAX_AGE;
let power_delta = dl_current
.record_faults(
rt.store(),
§ors,
info.sector_size,
quant_spec_for_deadline(&target_deadline),
fault_expiration_epoch,
&mut dispute_info.disputed_sectors,
)
.map_err(|e| {
e.downcast_default(ExitCode::ErrIllegalState, "failed to declare faults")
})?;
deadlines_current
.update_deadline(rt.store(), params.deadline, &dl_current)