-
Notifications
You must be signed in to change notification settings - Fork 79
/
lib.rs
5208 lines (4640 loc) · 200 KB
/
lib.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 2019-2022 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::iter;
use std::ops::Neg;
use anyhow::{anyhow, Error};
use byteorder::{BigEndian, ByteOrder, WriteBytesExt};
use cid::Cid;
use fvm_ipld_bitfield::{BitField, Validate};
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::{from_slice, BytesDe, Cbor, CborStore, RawBytes};
use fvm_shared::address::{Address, Payload, Protocol};
use fvm_shared::bigint::{BigInt, Integer};
use fvm_shared::clock::ChainEpoch;
use fvm_shared::deal::DealID;
use fvm_shared::econ::TokenAmount;
use fvm_shared::error::*;
use fvm_shared::randomness::*;
use fvm_shared::reward::ThisEpochRewardReturn;
use fvm_shared::sector::*;
use fvm_shared::smooth::FilterEstimate;
use fvm_shared::{MethodNum, METHOD_CONSTRUCTOR, METHOD_SEND};
use log::{error, info, warn};
use multihash::Code::Blake2b256;
use num_derive::FromPrimitive;
use num_traits::{FromPrimitive, Zero};
pub use beneficiary::*;
pub use bitfield_queue::*;
pub use commd::*;
pub use deadline_assignment::*;
pub use deadline_info::*;
pub use deadline_state::*;
pub use deadlines::*;
pub use expiration_queue::*;
use fil_actors_runtime::cbor::{deserialize, serialize, serialize_vec};
use fil_actors_runtime::runtime::builtins::Type;
use fil_actors_runtime::runtime::{ActorCode, DomainSeparationTag, Policy, Runtime};
use fil_actors_runtime::{
actor_error, cbor, ActorContext, ActorDowncast, ActorError, BURNT_FUNDS_ACTOR_ADDR,
CALLER_TYPES_SIGNABLE, INIT_ACTOR_ADDR, REWARD_ACTOR_ADDR, STORAGE_MARKET_ACTOR_ADDR,
STORAGE_POWER_ACTOR_ADDR, VERIFIED_REGISTRY_ACTOR_ADDR,
};
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::*;
// 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.
#[cfg(feature = "fil-actor")]
fil_actors_runtime::wasm_trampoline!(Actor);
mod beneficiary;
mod bitfield_queue;
mod commd;
mod deadline_assignment;
mod deadline_info;
mod deadline_state;
mod deadlines;
mod expiration_queue;
#[doc(hidden)]
pub mod ext;
mod monies;
mod partition_state;
mod policy;
mod sector_map;
mod sectors;
mod state;
mod termination;
pub mod testing;
mod types;
mod vesting_state;
// 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.
// * 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,
ProveReplicaUpdates = 27,
PreCommitSectorBatch2 = 28,
ProveReplicaUpdates2 = 29,
ChangeBeneficiary = 30,
GetBeneficiary = 31,
ExtendSectorExpiration2 = 32,
}
pub const ERR_BALANCE_INVARIANTS_BROKEN: ExitCode = ExitCode::new(1000);
/// 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(std::iter::once(&INIT_ACTOR_ADDR))?;
check_control_addresses(rt.policy(), ¶ms.control_addresses)?;
check_peer_info(rt.policy(), ¶ms.peer_id, ¶ms.multi_addresses)?;
check_valid_post_proof_type(rt.policy(), params.window_post_proof_type)?;
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 policy = rt.policy();
let current_epoch = rt.curr_epoch();
let blake2b = |b: &[u8]| rt.hash_blake2b(b);
let offset =
assign_proving_period_offset(policy, rt.message().receiver(), current_epoch, blake2b)
.map_err(|e| {
e.downcast_default(
ExitCode::USR_SERIALIZATION,
"failed to assign proving period offset",
)
})?;
let period_start = current_proving_period_start(policy, current_epoch, offset);
if period_start > current_epoch {
return Err(actor_error!(
illegal_state,
"computed proving period start {} after current epoch {}",
period_start,
current_epoch
));
}
let deadline_idx = current_deadline_index(policy, current_epoch, period_start);
if deadline_idx >= policy.wpost_period_deadlines {
return Err(actor_error!(
illegal_state,
"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,
)?;
let info_cid = rt.store().put_cbor(&info, Blake2b256).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state")
})?;
let st =
State::new(policy, rt.store(), info_cid, period_start, deadline_idx).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "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(rt.policy(), ¶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() + rt.policy().worker_key_change_delay,
})
}
state.save_info(rt.store(), &info).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "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!(illegal_argument, "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!(
illegal_argument,
"expected confirmation of {} got {}",
pending_address,
new_address
));
}
// Change beneficiary address to new owner if current beneficiary address equal to old owner address
if info.beneficiary == info.owner {
info.beneficiary = pending_address;
}
// Cancel pending beneficiary term change when the owner changes
info.pending_beneficiary_term = None;
// Set the new owner 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::USR_ILLEGAL_STATE, "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>,
{
let policy = rt.policy();
check_peer_info(policy, ¶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::USR_ILLEGAL_STATE, "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>,
{
let policy = rt.policy();
check_peer_info(policy, &[], ¶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::USR_ILLEGAL_STATE, "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();
{
let policy = rt.policy();
if params.proofs.len() != 1 {
return Err(actor_error!(
illegal_argument,
"expected exactly one proof, got {}",
params.proofs.len()
));
}
if check_valid_post_proof_type(policy, params.proofs[0].post_proof).is_err() {
return Err(actor_error!(
illegal_argument,
"proof type {:?} not allowed",
params.proofs[0].post_proof
));
}
if params.deadline >= policy.wpost_period_deadlines {
return Err(actor_error!(
illegal_argument,
"invalid deadline {} of {}",
params.deadline,
policy.wpost_period_deadlines
));
}
if params.chain_commit_rand.0.len() > RANDOMNESS_LENGTH {
return Err(actor_error!(
illegal_argument,
"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!(illegal_state, "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!(
illegal_argument,
"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!(
illegal_argument,
"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!(
illegal_argument,
"expected 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(rt.policy(), info.window_post_partition_sectors);
if params.partitions.len() as u64 > submission_partition_limit {
return Err(actor_error!(
illegal_argument,
"too many partitions {}, limit {}",
params.partitions.len(),
submission_partition_limit
));
}
let current_deadline = state.deadline_info(rt.policy(), 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!(
illegal_state,
"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 {
return Err(actor_error!(
illegal_argument,
"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!(
illegal_argument,
"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!(
illegal_argument,
"chain commit epoch {} must be less than 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 Randomness(comm_rand.into()) != params.chain_commit_rand {
return Err(actor_error!(illegal_argument, "post commit randomness mismatched"));
}
let sectors = Sectors::load(rt.store(), &state.sectors).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "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.policy(), rt.store(), params.deadline).map_err(|e| {
e.downcast_default(
ExitCode::USR_ILLEGAL_STATE,
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 policy = rt.policy();
let fault_expiration = current_deadline.last() + policy.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::USR_ILLEGAL_STATE,
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!(
illegal_argument,
"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::USR_ILLEGAL_STATE,
"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::USR_ILLEGAL_STATE,
"failed to load sectors for post verification",
)
})?;
if !verify_windowed_post(
rt,
current_deadline.challenge,
§or_infos,
params.proofs,
)
.map_err(|e| e.wrap("window post failed"))?
{
return Err(actor_error!(illegal_argument, "invalid post was submitted"));
}
}
let deadline_idx = params.deadline;
deadlines.update_deadline(policy, rt.store(), params.deadline, &deadline).map_err(
|e| {
e.downcast_default(
ExitCode::USR_ILLEGAL_STATE,
format!("failed to update deadline {}", deadline_idx),
)
},
)?;
state.save_deadlines(rt.store(), deadlines).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "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(balance_invariants_broken)?;
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,
params: ProveCommitAggregateParams,
) -> Result<(), ActorError>
where
BS: Blockstore,
RT: Runtime<BS>,
{
let sector_numbers = params.sector_numbers.validate().map_err(|e| {
actor_error!(illegal_state, "Failed to validate bitfield for aggregated sectors: {}", e)
})?;
let agg_sectors_count = sector_numbers.len();
{
let policy = rt.policy();
if agg_sectors_count > policy.max_aggregated_sectors {
return Err(actor_error!(
illegal_argument,
"too many sectors addressed, addressed {} want <= {}",
agg_sectors_count,
policy.max_aggregated_sectors
));
} else if agg_sectors_count < policy.min_aggregated_sectors {
return Err(actor_error!(
illegal_argument,
"too few sectors addressed, addressed {} want >= {}",
agg_sectors_count,
policy.min_aggregated_sectors
));
}
if params.aggregate_proof.len() > policy.max_aggregated_proof_size {
return Err(actor_error!(
illegal_argument,
"sector prove-commit proof of size {} exceeds max size of {}",
params.aggregate_proof.len(),
policy.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::USR_ILLEGAL_STATE, "failed to get precommits")
})?;
// validate each precommit
let mut precommits_to_confirm = Vec::new();
for (i, precommit) in precommits.iter().enumerate() {
let msd = max_prove_commit_duration(rt.policy(), precommit.info.seal_proof)
.ok_or_else(|| {
actor_error!(
illegal_state,
"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!(
illegal_state,
"aggregate contains mismatched seal proofs {} and {}",
i64::from(prev_seal_proof),
i64::from(precommit.info.seal_proof)
));
}
}
}
let mut svis = Vec::with_capacity(precommits.len());
let miner_actor_id: u64 = if let Payload::ID(i) = rt.message().receiver().payload() {
*i
} else {
return Err(actor_error!(
illegal_state,
"runtime provided non-ID receiver address {}",
rt.message().receiver()
));
};
let receiver_bytes =
serialize_vec(&rt.message().receiver(), "address for seal verification challenge")?;
for precommit in precommits.iter() {
let interactive_epoch =
precommit.pre_commit_epoch + rt.policy().pre_commit_challenge_delay;
if rt.curr_epoch() <= interactive_epoch {
return Err(actor_error!(
forbidden,
"too early to prove sector {}",
precommit.info.sector_number
));
}
let sv_info_randomness = rt.get_randomness_from_tickets(
DomainSeparationTag::SealRandomness,
precommit.info.seal_rand_epoch,
&receiver_bytes,
)?;
let sv_info_interactive_randomness = rt.get_randomness_from_beacon(
DomainSeparationTag::InteractiveSealChallengeSeed,
interactive_epoch,
&receiver_bytes,
)?;
let unsealed_cid = precommit.info.unsealed_cid.get_cid(precommit.info.seal_proof)?;
let svi = AggregateSealVerifyInfo {
sector_number: precommit.info.sector_number,
randomness: Randomness(sv_info_randomness.into()),
interactive_randomness: Randomness(sv_info_interactive_randomness.into()),
sealed_cid: precommit.info.sealed_cid,
unsealed_cid,
};
svis.push(svi);
}
let seal_proof = precommits[0].info.seal_proof;
if precommits.is_empty() {
return Err(actor_error!(
illegal_state,
"bitfield non-empty but zero precommits read from state"
));
}
rt.verify_aggregate_seals(&AggregateSealVerifyProofAndInfos {
miner: miner_actor_id,
seal_proof,
aggregate_proof: RegisteredAggregateProof::SnarkPackV2,
proof: params.aggregate_proof,
infos: svis,
})
.map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_ARGUMENT, "aggregate seal verify failed")
})?;
let rew = request_current_epoch_block_reward(rt)?;
let pwr = request_current_total_power(rt)?;
confirm_sector_proofs_valid_internal(
rt,
precommits_to_confirm.clone(),
&rew.this_epoch_baseline_power,
&rew.this_epoch_reward_smoothed,
&pwr.quality_adj_power_smoothed,
)?;
// 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_prove_commit_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!(illegal_state, "failed to determine unlocked balance"))?;
if unlocked_balance < aggregate_fee {
return Err(actor_error!(
insufficient_funds,
"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(balance_invariants_broken)?;
Ok(())
}
fn prove_replica_updates<BS, RT>(
rt: &mut RT,
params: ProveReplicaUpdatesParams,
) -> Result<BitField, ActorError>
where
// + Clone because we messed up and need to keep a copy around between transactions.
// https://github.com/filecoin-project/builtin-actors/issues/133
BS: Blockstore + Clone,
RT: Runtime<BS>,
{
// In this entry point, the unsealed CID is computed from deals via the market actor.
// A future entry point will take the unsealed CID as parameter
let updates = params
.updates
.into_iter()
.map(|ru| ReplicaUpdateInner {
sector_number: ru.sector_number,
deadline: ru.deadline,
partition: ru.partition,
new_sealed_cid: ru.new_sealed_cid,
new_unsealed_cid: None,
deals: ru.deals,
update_proof_type: ru.update_proof_type,
replica_proof: ru.replica_proof,
})
.collect();
Self::prove_replica_updates_inner(rt, updates)
}
fn prove_replica_updates2<BS, RT>(
rt: &mut RT,
params: ProveReplicaUpdatesParams2,
) -> Result<BitField, ActorError>
where
// + Clone because we messed up and need to keep a copy around between transactions.
// https://github.com/filecoin-project/builtin-actors/issues/133
BS: Blockstore + Clone,
RT: Runtime<BS>,
{
let updates = params
.updates
.into_iter()
.map(|ru| ReplicaUpdateInner {
sector_number: ru.sector_number,
deadline: ru.deadline,
partition: ru.partition,
new_sealed_cid: ru.new_sealed_cid,
new_unsealed_cid: Some(ru.new_unsealed_cid),
deals: ru.deals,
update_proof_type: ru.update_proof_type,
replica_proof: ru.replica_proof,
})
.collect();
Self::prove_replica_updates_inner(rt, updates)
}
fn prove_replica_updates_inner<BS, RT>(
rt: &mut RT,
updates: Vec<ReplicaUpdateInner>,
) -> Result<BitField, ActorError>
where
// + Clone because we messed up and need to keep a copy around between transactions.
// https://github.com/filecoin-project/builtin-actors/issues/133
BS: Blockstore + Clone,
RT: Runtime<BS>,
{
// Validate inputs
if updates.len() > rt.policy().prove_replica_updates_max_size {
return Err(actor_error!(
illegal_argument,
"too many updates ({} > {})",
updates.len(),
rt.policy().prove_replica_updates_max_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.owner, info.worker]),
)?;
let sector_store = rt.store().clone();
let mut sectors = Sectors::load(§or_store, &state.sectors).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load sectors array")
})?;
let mut power_delta = PowerPair::zero();
let mut pledge_delta = TokenAmount::zero();
struct UpdateAndSectorInfo<'a> {
update: &'a ReplicaUpdateInner,
sector_info: SectorOnChainInfo,
deal_spaces: ext::market::DealSpaces,
}
let mut sectors_deals = Vec::<ext::market::SectorDeals>::new();
let mut sectors_data_spec = Vec::<ext::market::SectorDataSpec>::new();
let mut validated_updates = Vec::<UpdateAndSectorInfo>::new();
let mut sector_numbers = BitField::new();
for update in updates.iter() {
let set = sector_numbers.get(update.sector_number);
if set {
info!("duplicate sector being updated {}, skipping", update.sector_number,);
continue;
}
if sector_numbers.try_set(update.sector_number).is_err() {
info!("invalid sector number, skipping");
continue;
}
if update.replica_proof.len() > 4096 {
info!(
"update proof is too large ({}), skipping sector {}",
update.replica_proof.len(),
update.sector_number,
);
continue;
}
if update.deals.is_empty() {
info!("must have deals to update, skipping sector {}", update.sector_number,);
continue;
}
if update.deals.len() as u64 > sector_deals_max(rt.policy(), info.sector_size) {
info!("more deals than policy allows, skipping sector {}", update.sector_number,);
continue;
}
if update.deadline >= rt.policy().wpost_period_deadlines {
info!(
"deadline {} not in range 0..{}, skipping sector {}",
update.deadline,
rt.policy().wpost_period_deadlines,
update.sector_number
);
continue;
}