-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathstate.rs
More file actions
1337 lines (1144 loc) · 48.7 KB
/
state.rs
File metadata and controls
1337 lines (1144 loc) · 48.7 KB
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::borrow::Borrow;
use std::cmp;
use std::ops::Neg;
use anyhow::{anyhow, Error};
use cid::Cid;
use fvm_ipld_amt::Error as AmtError;
use fvm_ipld_bitfield::BitField;
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::tuple::*;
use fvm_ipld_encoding::{strict_bytes, BytesDe, CborStore};
use fvm_shared::address::Address;
use fvm_shared::clock::{ChainEpoch, EPOCH_UNDEFINED};
use fvm_shared::econ::TokenAmount;
use fvm_shared::error::ExitCode;
use fvm_shared::sector::{RegisteredPoStProof, SectorNumber, SectorSize};
use fvm_shared::{ActorID, HAMT_BIT_WIDTH};
use itertools::Itertools;
use multihash_codetable::Code;
use num_traits::Zero;
use fil_actors_runtime::runtime::policy_constants::MAX_SECTOR_NUMBER;
use fil_actors_runtime::runtime::Policy;
use fil_actors_runtime::{
actor_error, ActorContext, ActorDowncast, ActorError, Array, AsActorError, Config, Map2,
DEFAULT_HAMT_CONFIG,
};
use super::beneficiary::*;
use super::deadlines::new_deadline_info;
use super::policy::*;
use super::types::*;
use super::{
assign_deadlines, deadline_is_mutable, new_deadline_info_from_offset_and_epoch,
quant_spec_for_deadline, BitFieldQueue, Deadline, DeadlineInfo, DeadlineSectorMap, Deadlines,
PowerPair, QuantSpec, Sectors, TerminationResult, VestingFunds,
};
pub type PreCommitMap<BS> = Map2<BS, SectorNumber, SectorPreCommitOnChainInfo>;
pub const PRECOMMIT_CONFIG: Config = Config { bit_width: HAMT_BIT_WIDTH, ..DEFAULT_HAMT_CONFIG };
const PRECOMMIT_EXPIRY_AMT_BITWIDTH: u32 = 6;
pub const SECTORS_AMT_BITWIDTH: u32 = 5;
/// Balance of Miner Actor should be greater than or equal to
/// the sum of PreCommitDeposits and LockedFunds.
/// It is possible for balance to fall below the sum of PCD, LF and
/// InitialPledgeRequirements, and this is a bad state (IP Debt)
/// that limits a miner actor's behavior (i.e. no balance withdrawals)
/// Excess balance as computed by st.GetAvailableBalance will be
/// withdrawable or usable for pre-commit deposit or pledge lock-up.
#[derive(Serialize_tuple, Deserialize_tuple, Clone, Debug)]
pub struct State {
/// Contains static info about this miner
pub info: Cid,
/// Total funds locked as pre_commit_deposit
pub pre_commit_deposits: TokenAmount,
/// Total rewards and added funds locked in vesting table
pub locked_funds: TokenAmount,
/// VestingFunds (Vesting Funds schedule for the miner).
pub vesting_funds: Cid,
/// Absolute value of debt this miner owes from unpaid fees.
pub fee_debt: TokenAmount,
/// Sum of initial pledge requirements of all active sectors.
pub initial_pledge: TokenAmount,
/// Sectors that have been pre-committed but not yet proven.
/// Map, HAMT<SectorNumber, SectorPreCommitOnChainInfo>
pub pre_committed_sectors: Cid,
// PreCommittedSectorsCleanUp maintains the state required to cleanup expired PreCommittedSectors.
pub pre_committed_sectors_cleanup: Cid, // BitFieldQueue (AMT[Epoch]*BitField)
/// Allocated sector IDs. Sector IDs can never be reused once allocated.
pub allocated_sectors: Cid, // BitField
/// Information for all proven and not-yet-garbage-collected sectors.
///
/// Sectors are removed from this AMT when the partition to which the
/// sector belongs is compacted.
pub sectors: Cid, // Array, AMT[SectorNumber]*SectorOnChainInfo (sparse)
/// The first epoch in this miner's current proving period. This is the first epoch in which a PoSt for a
/// partition at the miner's first deadline may arrive. Alternatively, it is after the last epoch at which
/// a PoSt for the previous window is valid.
/// Always greater than zero, this may be greater than the current epoch for genesis miners in the first
/// WPoStProvingPeriod epochs of the chain; the epochs before the first proving period starts are exempt from Window
/// PoSt requirements.
/// Updated at the end of every period by a cron callback.
pub proving_period_start: ChainEpoch,
/// Index of the deadline within the proving period beginning at ProvingPeriodStart that has not yet been
/// finalized.
/// Updated at the end of each deadline window by a cron callback.
pub current_deadline: u64,
/// The sector numbers due for PoSt at each deadline in the current proving period, frozen at period start.
/// New sectors are added and expired ones removed at proving period boundary.
/// Faults are not subtracted from this in state, but on the fly.
pub deadlines: Cid,
/// Deadlines with outstanding fees for early sector termination.
pub early_terminations: BitField,
// True when miner cron is active, false otherwise
pub deadline_cron_active: bool,
}
#[derive(PartialEq, Eq)]
pub enum CollisionPolicy {
AllowCollisions,
DenyCollisions,
}
impl State {
#[allow(clippy::too_many_arguments)]
pub fn new<BS: Blockstore>(
policy: &Policy,
store: &BS,
info_cid: Cid,
period_start: ChainEpoch,
deadline_idx: u64,
) -> Result<Self, ActorError> {
let empty_precommit_map =
PreCommitMap::empty(store, PRECOMMIT_CONFIG, "precommits").flush()?;
let empty_precommits_cleanup_array =
Array::<BitField, BS>::new_with_bit_width(store, PRECOMMIT_EXPIRY_AMT_BITWIDTH)
.flush()
.map_err(|e| {
e.downcast_default(
ExitCode::USR_ILLEGAL_STATE,
"failed to construct empty precommits array",
)
})?;
let empty_sectors_array = Array::<Cid, BS>::new_with_bit_width(store, SECTORS_AMT_BITWIDTH)
.flush()
.map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct sectors array")
})?;
let empty_bitfield = store.put_cbor(&BitField::new(), Code::Blake2b256).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct empty bitfield")
})?;
let deadline = Deadline::new(store)?;
let empty_deadline = store.put_cbor(&deadline, Code::Blake2b256).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state")
})?;
let empty_deadlines = store
.put_cbor(&Deadlines::new(policy, empty_deadline), Code::Blake2b256)
.map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state")
})?;
let empty_vesting_funds_cid =
store.put_cbor(&VestingFunds::new(), Code::Blake2b256).map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to construct illegal state")
})?;
Ok(Self {
info: info_cid,
pre_commit_deposits: TokenAmount::default(),
locked_funds: TokenAmount::default(),
vesting_funds: empty_vesting_funds_cid,
initial_pledge: TokenAmount::default(),
fee_debt: TokenAmount::default(),
pre_committed_sectors: empty_precommit_map,
allocated_sectors: empty_bitfield,
sectors: empty_sectors_array,
proving_period_start: period_start,
current_deadline: deadline_idx,
deadlines: empty_deadlines,
early_terminations: BitField::new(),
deadline_cron_active: false,
pre_committed_sectors_cleanup: empty_precommits_cleanup_array,
})
}
pub fn get_info<BS: Blockstore>(&self, store: &BS) -> anyhow::Result<MinerInfo> {
match store.get_cbor(&self.info) {
Ok(Some(info)) => Ok(info),
Ok(None) => Err(actor_error!(not_found, "failed to get miner info").into()),
Err(e) => Err(e.downcast_wrap("failed to get miner info")),
}
}
pub fn save_info<BS: Blockstore>(
&mut self,
store: &BS,
info: &MinerInfo,
) -> anyhow::Result<()> {
let cid = store.put_cbor(&info, Code::Blake2b256)?;
self.info = cid;
Ok(())
}
/// Returns deadline calculations for the current (according to state) proving period.
pub fn deadline_info(&self, policy: &Policy, current_epoch: ChainEpoch) -> DeadlineInfo {
new_deadline_info_from_offset_and_epoch(policy, self.proving_period_start, current_epoch)
}
// Returns deadline calculations for the state recorded proving period and deadline.
// This is out of date if the a miner does not have an active miner cron
pub fn recorded_deadline_info(
&self,
policy: &Policy,
current_epoch: ChainEpoch,
) -> DeadlineInfo {
new_deadline_info(policy, self.proving_period_start, self.current_deadline, current_epoch)
}
// Returns current proving period start for the current epoch according to the current epoch and constant state offset
pub fn current_proving_period_start(
&self,
policy: &Policy,
current_epoch: ChainEpoch,
) -> ChainEpoch {
let dl_info = self.deadline_info(policy, current_epoch);
dl_info.period_start
}
/// Returns deadline calculations for the current (according to state) proving period.
pub fn quant_spec_for_deadline(&self, policy: &Policy, deadline_idx: u64) -> QuantSpec {
new_deadline_info(policy, self.proving_period_start, deadline_idx, 0).quant_spec()
}
/// Marks a set of sector numbers as having been allocated.
/// If policy is `DenyCollisions`, fails if the set intersects with the sector numbers already allocated.
pub fn allocate_sector_numbers<BS: Blockstore>(
&mut self,
store: &BS,
sector_numbers: &BitField,
policy: CollisionPolicy,
) -> Result<(), ActorError> {
let prior_allocation = store
.get_cbor(&self.allocated_sectors)
.map_err(|e| {
e.downcast_default(
ExitCode::USR_ILLEGAL_STATE,
"failed to load allocated sectors bitfield",
)
})?
.ok_or_else(|| actor_error!(illegal_state, "allocated sectors bitfield not found"))?;
if policy != CollisionPolicy::AllowCollisions {
// NOTE: A fancy merge algorithm could extract this intersection while merging, below, saving
// one iteration of the runs
let collisions = &prior_allocation & sector_numbers;
if !collisions.is_empty() {
return Err(actor_error!(
illegal_argument,
"sector numbers {:?} already allocated",
collisions
));
}
}
let new_allocation = &prior_allocation | sector_numbers;
self.allocated_sectors =
store.put_cbor(&new_allocation, Code::Blake2b256).map_err(|e| {
e.downcast_default(
ExitCode::USR_ILLEGAL_ARGUMENT,
format!(
"failed to store allocated sectors bitfield after adding {:?}",
sector_numbers,
),
)
})?;
Ok(())
}
/// Stores a pre-committed sector info, failing if the sector number is already present.
pub fn put_precommitted_sectors<BS: Blockstore>(
&mut self,
store: &BS,
precommits: Vec<SectorPreCommitOnChainInfo>,
) -> anyhow::Result<()> {
let mut precommitted =
PreCommitMap::load(store, &self.pre_committed_sectors, PRECOMMIT_CONFIG, "precommits")?;
for precommit in precommits.into_iter() {
let sector_no = precommit.info.sector_number;
let modified = precommitted
.set_if_absent(§or_no, precommit)
.with_context(|| format!("storing precommit for {}", sector_no))?;
if !modified {
return Err(anyhow!("sector {} already pre-commited", sector_no));
}
}
self.pre_committed_sectors = precommitted.flush()?;
Ok(())
}
pub fn get_precommitted_sector<BS: Blockstore>(
&self,
store: &BS,
sector_num: SectorNumber,
) -> Result<Option<SectorPreCommitOnChainInfo>, ActorError> {
let precommitted =
PreCommitMap::load(store, &self.pre_committed_sectors, PRECOMMIT_CONFIG, "precommits")?;
Ok(precommitted.get(§or_num)?.cloned())
}
/// Gets and returns the requested pre-committed sectors, skipping missing sectors.
pub fn find_precommitted_sectors<BS: Blockstore>(
&self,
store: &BS,
sector_numbers: &[SectorNumber],
) -> anyhow::Result<Vec<SectorPreCommitOnChainInfo>> {
let precommitted =
PreCommitMap::load(store, &self.pre_committed_sectors, PRECOMMIT_CONFIG, "precommits")?;
let mut result = Vec::with_capacity(sector_numbers.len());
for §or_number in sector_numbers {
let info = match precommitted
.get(§or_number)
.with_context(|| format!("loading precommit {}", sector_number))?
{
Some(info) => info.clone(),
None => continue,
};
result.push(info);
}
Ok(result)
}
pub fn delete_precommitted_sectors<BS: Blockstore>(
&mut self,
store: &BS,
sector_nums: &[SectorNumber],
) -> Result<(), ActorError> {
let mut precommitted =
PreCommitMap::load(store, &self.pre_committed_sectors, PRECOMMIT_CONFIG, "precommits")?;
for §or_num in sector_nums {
let prev_entry = precommitted.delete(§or_num)?;
if prev_entry.is_none() {
return Err(actor_error!(illegal_state, "sector {} not pre-committed", sector_num));
}
}
self.pre_committed_sectors = precommitted.flush()?;
Ok(())
}
pub fn has_sector_number<BS: Blockstore>(
&self,
store: &BS,
sector_num: SectorNumber,
) -> anyhow::Result<bool> {
let sectors = Sectors::load(store, &self.sectors)?;
Ok(sectors.get(sector_num)?.is_some())
}
pub fn put_sectors<BS: Blockstore>(
&mut self,
store: &BS,
new_sectors: Vec<SectorOnChainInfo>,
) -> anyhow::Result<()> {
let mut sectors = Sectors::load(store, &self.sectors)
.map_err(|e| e.downcast_wrap("failed to load sectors"))?;
sectors.store(new_sectors)?;
self.sectors =
sectors.amt.flush().map_err(|e| e.downcast_wrap("failed to persist sectors"))?;
Ok(())
}
pub fn get_sector<BS: Blockstore>(
&self,
store: &BS,
sector_num: SectorNumber,
) -> Result<Option<SectorOnChainInfo>, ActorError> {
let sectors = Sectors::load(store, &self.sectors)
.context_code(ExitCode::USR_ILLEGAL_STATE, "loading sectors")?;
sectors.get(sector_num)
}
pub fn delete_sectors<BS: Blockstore>(
&mut self,
store: &BS,
sector_nos: &BitField,
) -> Result<(), AmtError> {
let mut sectors = Sectors::load(store, &self.sectors)?;
for sector_num in sector_nos.iter() {
let deleted_sector = sectors
.amt
.delete(sector_num)
.map_err(|e| e.downcast_wrap("could not delete sector number"))?;
if deleted_sector.is_none() {
return Err(AmtError::Dynamic(Error::msg(format!(
"sector {} doesn't exist, failed to delete",
sector_num
))));
}
}
self.sectors = sectors.amt.flush()?;
Ok(())
}
pub fn for_each_sector<BS: Blockstore, F>(&self, store: &BS, mut f: F) -> anyhow::Result<()>
where
F: FnMut(&SectorOnChainInfo) -> anyhow::Result<()>,
{
let sectors = Sectors::load(store, &self.sectors)?;
sectors.for_each(|_, v| f(v))?;
Ok(())
}
/// Returns the deadline and partition index for a sector number.
pub fn find_sector<BS: Blockstore>(
&self,
store: &BS,
sector_number: SectorNumber,
) -> anyhow::Result<(u64, u64)> {
let deadlines = self.load_deadlines(store)?;
deadlines.find_sector(store, sector_number)
}
/// Schedules each sector to expire at its next deadline end. If it can't find
/// any given sector, it skips it.
///
/// This method assumes that each sector's power has not changed, despite the rescheduling.
///
/// Note: this method is used to "upgrade" sectors, rescheduling the now-replaced
/// sectors to expire at the end of the next deadline. Given the expense of
/// sealing a sector, this function skips missing/faulty/terminated "upgraded"
/// sectors instead of failing. That way, the new sectors can still be proved.
pub fn reschedule_sector_expirations<BS: Blockstore>(
&mut self,
policy: &Policy,
store: &BS,
current_epoch: ChainEpoch,
sector_size: SectorSize,
mut deadline_sectors: DeadlineSectorMap,
) -> anyhow::Result<Vec<SectorOnChainInfo>> {
let mut deadlines = self.load_deadlines(store)?;
let sectors = Sectors::load(store, &self.sectors)?;
let mut all_replaced = Vec::new();
for (deadline_idx, partition_sectors) in deadline_sectors.iter() {
let deadline_info = new_deadline_info(
policy,
self.current_proving_period_start(policy, current_epoch),
deadline_idx,
current_epoch,
)
.next_not_elapsed();
let new_expiration = deadline_info.last();
let mut deadline = deadlines.load_deadline(store, deadline_idx)?;
let replaced = deadline.reschedule_sector_expirations(
store,
§ors,
new_expiration,
partition_sectors,
sector_size,
deadline_info.quant_spec(),
)?;
all_replaced.extend(replaced);
deadlines.update_deadline(policy, store, deadline_idx, &deadline)?;
}
self.save_deadlines(store, deadlines)?;
Ok(all_replaced)
}
/// Assign new sectors to deadlines.
pub fn assign_sectors_to_deadlines<BS: Blockstore>(
&mut self,
policy: &Policy,
store: &BS,
current_epoch: ChainEpoch,
mut sectors: Vec<SectorOnChainInfo>,
partition_size: u64,
sector_size: SectorSize,
) -> anyhow::Result<()> {
let mut deadlines = self.load_deadlines(store)?;
// Sort sectors by number to get better runs in partition bitfields.
sectors.sort_by_key(|info| info.sector_number);
let mut deadline_vec: Vec<Option<Deadline>> =
(0..policy.wpost_period_deadlines).map(|_| None).collect();
deadlines.for_each(store, |deadline_idx, deadline| {
// Skip deadlines that aren't currently mutable.
if deadline_is_mutable(
policy,
self.current_proving_period_start(policy, current_epoch),
deadline_idx,
current_epoch,
) {
deadline_vec[deadline_idx as usize] = Some(deadline);
}
Ok(())
})?;
let deadline_to_sectors = assign_deadlines(
policy,
policy.max_partitions_per_deadline,
partition_size,
&deadline_vec,
sectors,
)?;
for (deadline_idx, deadline_sectors) in deadline_to_sectors.into_iter().enumerate() {
if deadline_sectors.is_empty() {
continue;
}
let quant = self.quant_spec_for_deadline(policy, deadline_idx as u64);
let deadline = deadline_vec[deadline_idx].as_mut().unwrap();
// The power returned from AddSectors is ignored because it's not activated (proven) yet.
let proven = false;
deadline.add_sectors(
store,
partition_size,
proven,
&deadline_sectors,
sector_size,
quant,
)?;
deadlines.update_deadline(policy, store, deadline_idx as u64, deadline)?;
}
self.save_deadlines(store, deadlines)?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn assign_sectors_to_deadline<BS: Blockstore>(
&mut self,
policy: &Policy,
store: &BS,
current_epoch: ChainEpoch,
mut sectors: Vec<SectorOnChainInfo>,
partition_size: u64,
sector_size: SectorSize,
deadline_idx: u64,
) -> Result<(), ActorError> {
let mut deadlines = self.load_deadlines(store)?;
let mut deadline = deadlines.load_deadline(store, deadline_idx)?;
// Sort sectors by number to get better runs in partition bitfields.
sectors.sort_by_key(|info| info.sector_number);
if !deadline_is_mutable(
policy,
self.current_proving_period_start(policy, current_epoch),
deadline_idx,
current_epoch,
) {
return Err(actor_error!(
illegal_argument,
"proving deadline {} must not be the current or next deadline ",
deadline_idx
));
}
let quant = self.quant_spec_for_deadline(policy, deadline_idx);
let proven = false;
deadline
.add_sectors(store, partition_size, proven, §ors, sector_size, quant)
.with_context_code(ExitCode::USR_ILLEGAL_STATE, || {
format!("failed to add sectors to deadline {}", deadline_idx)
})?;
deadlines
.update_deadline(policy, store, deadline_idx, &deadline)
.with_context_code(ExitCode::USR_ILLEGAL_STATE, || {
format!("failed to update deadline {}", deadline_idx)
})?;
self.save_deadlines(store, deadlines)
.with_context_code(ExitCode::USR_ILLEGAL_STATE, || "failed to save deadlines")?;
Ok(())
}
/// Pops up to `max_sectors` early terminated sectors from all deadlines.
///
/// Returns `true` if we still have more early terminations to process.
pub fn pop_early_terminations<BS: Blockstore>(
&mut self,
policy: &Policy,
store: &BS,
max_partitions: u64,
max_sectors: u64,
) -> anyhow::Result<(TerminationResult, /* has more */ bool)> {
// Anything to do? This lets us avoid loading the deadlines if there's nothing to do.
if self.early_terminations.is_empty() {
return Ok((Default::default(), false));
}
// Load deadlines
let mut deadlines = self.load_deadlines(store)?;
let mut result = TerminationResult::new();
let mut to_unset = Vec::new();
// Process early terminations.
for i in self.early_terminations.iter() {
let deadline_idx = i;
// Load deadline + partitions.
let mut deadline = deadlines.load_deadline(store, deadline_idx)?;
let (deadline_result, more) = deadline
.pop_early_terminations(
store,
max_partitions - result.partitions_processed,
max_sectors - result.sectors_processed,
)
.map_err(|e| {
e.downcast_wrap(format!(
"failed to pop early terminations for deadline {}",
deadline_idx
))
})?;
result += deadline_result;
if !more {
to_unset.push(i);
}
// Save the deadline
deadlines.update_deadline(policy, store, deadline_idx, &deadline)?;
if !result.below_limit(max_partitions, max_sectors) {
break;
}
}
for deadline_idx in to_unset {
self.early_terminations.unset(deadline_idx);
}
// Save back the deadlines.
self.save_deadlines(store, deadlines)?;
// Ok, check to see if we've handled all early terminations.
let no_early_terminations = self.early_terminations.is_empty();
Ok((result, !no_early_terminations))
}
/// Returns an error if the target sector cannot be found, or some other bad state is reached.
/// Returns Ok(false) if the target sector is faulty, terminated, or unproven
/// Returns Ok(true) otherwise
pub fn check_sector_active<BS: Blockstore>(
&self,
store: &BS,
deadline_idx: u64,
partition_idx: u64,
sector_number: SectorNumber,
require_proven: bool,
) -> Result<bool, ActorError> {
let dls = self.load_deadlines(store)?;
let dl = dls.load_deadline(store, deadline_idx)?;
let partition = dl.load_partition(store, partition_idx)?;
let exists = partition.sectors.get(sector_number);
if !exists {
return Err(actor_error!(
not_found;
"sector {} not a member of partition {}, deadline {}",
sector_number, partition_idx, deadline_idx
));
}
let faulty = partition.faults.get(sector_number);
if faulty {
return Ok(false);
}
let terminated = partition.terminated.get(sector_number);
if terminated {
return Ok(false);
}
let unproven = partition.unproven.get(sector_number);
if unproven && require_proven {
return Ok(false);
}
Ok(true)
}
/// Returns an error if the target sector cannot be found and/or is faulty/terminated.
pub fn check_sector_health<BS: Blockstore>(
&self,
store: &BS,
deadline_idx: u64,
partition_idx: u64,
sector_number: SectorNumber,
) -> anyhow::Result<()> {
let deadlines = self.load_deadlines(store)?;
let deadline = deadlines.load_deadline(store, deadline_idx)?;
let partition = deadline.load_partition(store, partition_idx)?;
if !partition.sectors.get(sector_number) {
return Err(actor_error!(
not_found;
"sector {} not a member of partition {}, deadline {}",
sector_number, partition_idx, deadline_idx
)
.into());
}
if partition.faults.get(sector_number) {
return Err(actor_error!(
forbidden;
"sector {} not a member of partition {}, deadline {}",
sector_number, partition_idx, deadline_idx
)
.into());
}
if partition.terminated.get(sector_number) {
return Err(actor_error!(
not_found;
"sector {} not of partition {}, deadline {} is terminated",
sector_number, partition_idx, deadline_idx
)
.into());
}
Ok(())
}
/// Loads sector info for a sequence of sectors.
pub fn load_sector_infos<BS: Blockstore>(
&self,
store: &BS,
sectors: &BitField,
) -> anyhow::Result<Vec<SectorOnChainInfo>> {
Ok(Sectors::load(store, &self.sectors)?.load_sector(sectors)?)
}
pub fn load_deadlines<BS: Blockstore>(&self, store: &BS) -> Result<Deadlines, ActorError> {
store
.get_cbor::<Deadlines>(&self.deadlines)
.map_err(|e| {
e.downcast_default(ExitCode::USR_ILLEGAL_STATE, "failed to load deadlines")
})?
.ok_or_else(
|| actor_error!(illegal_state; "failed to load deadlines {}", self.deadlines),
)
}
pub fn save_deadlines<BS: Blockstore>(
&mut self,
store: &BS,
deadlines: Deadlines,
) -> anyhow::Result<()> {
self.deadlines = store.put_cbor(&deadlines, Code::Blake2b256)?;
Ok(())
}
/// Loads the vesting funds table from the store.
pub fn load_vesting_funds<BS: Blockstore>(&self, store: &BS) -> anyhow::Result<VestingFunds> {
Ok(store
.get_cbor(&self.vesting_funds)
.map_err(|e| {
e.downcast_wrap(format!("failed to load vesting funds {}", self.vesting_funds))
})?
.ok_or_else(
|| actor_error!(not_found; "failed to load vesting funds {:?}", self.vesting_funds),
)?)
}
/// Saves the vesting table to the store.
pub fn save_vesting_funds<BS: Blockstore>(
&mut self,
store: &BS,
funds: &VestingFunds,
) -> anyhow::Result<()> {
self.vesting_funds = store.put_cbor(funds, Code::Blake2b256)?;
Ok(())
}
// Return true when the miner actor needs to continue scheduling deadline crons
pub fn continue_deadline_cron(&self) -> bool {
!self.pre_commit_deposits.is_zero()
|| !self.initial_pledge.is_zero()
|| !self.locked_funds.is_zero()
}
//
// Funds and vesting
//
pub fn add_pre_commit_deposit(&mut self, amount: &TokenAmount) -> anyhow::Result<()> {
let new_total = &self.pre_commit_deposits + amount;
if new_total.is_negative() {
return Err(anyhow!(
"negative pre-commit deposit {} after adding {} to prior {}",
new_total,
amount,
self.pre_commit_deposits
));
}
self.pre_commit_deposits = new_total;
Ok(())
}
pub fn add_initial_pledge(&mut self, amount: &TokenAmount) -> anyhow::Result<()> {
let new_total = &self.initial_pledge + amount;
if new_total.is_negative() {
return Err(anyhow!(
"negative initial pledge requirement {} after adding {} to prior {}",
new_total,
amount,
self.initial_pledge
));
}
self.initial_pledge = new_total;
Ok(())
}
pub fn apply_penalty(&mut self, penalty: &TokenAmount) -> anyhow::Result<()> {
if penalty.is_negative() {
Err(anyhow!("applying negative penalty {} not allowed", penalty))
} else {
self.fee_debt += penalty;
Ok(())
}
}
/// First vests and unlocks the vested funds AND then locks the given funds in the vesting table.
pub fn add_locked_funds<BS: Blockstore>(
&mut self,
store: &BS,
current_epoch: ChainEpoch,
vesting_sum: &TokenAmount,
spec: &VestSpec,
) -> anyhow::Result<TokenAmount> {
if vesting_sum.is_negative() {
return Err(anyhow!("negative vesting sum {}", vesting_sum));
}
let mut vesting_funds = self.load_vesting_funds(store)?;
// unlock vested funds first
let amount_unlocked = vesting_funds.unlock_vested_funds(current_epoch);
self.locked_funds -= &amount_unlocked;
if self.locked_funds.is_negative() {
return Err(anyhow!(
"negative locked funds {} after unlocking {}",
self.locked_funds,
amount_unlocked
));
}
// add locked funds now
vesting_funds.add_locked_funds(current_epoch, vesting_sum, self.proving_period_start, spec);
self.locked_funds += vesting_sum;
// save the updated vesting table state
self.save_vesting_funds(store, &vesting_funds)?;
Ok(amount_unlocked)
}
/// Draws from vesting table and unlocked funds to repay up to the fee debt.
/// Returns the amount unlocked from the vesting table and the amount taken from
/// current balance. If the fee debt exceeds the total amount available for repayment
/// the fee debt field is updated to track the remaining debt. Otherwise it is set to zero.
pub fn repay_partial_debt_in_priority_order<BS: Blockstore>(
&mut self,
store: &BS,
current_epoch: ChainEpoch,
curr_balance: &TokenAmount,
) -> Result<
(
TokenAmount, // from vesting
TokenAmount, // from balance
),
anyhow::Error,
> {
let unlocked_balance = self.get_unlocked_balance(curr_balance)?;
let fee_debt = self.fee_debt.clone();
let from_vesting = self.unlock_unvested_funds(store, current_epoch, &fee_debt)?;
if from_vesting > self.fee_debt {
return Err(anyhow!("should never unlock more than the debt we need to repay"));
}
self.fee_debt -= &from_vesting;
let from_balance = cmp::min(&unlocked_balance, &self.fee_debt).clone();
self.fee_debt -= &from_balance;
Ok((from_vesting, from_balance))
}
/// Repays the full miner actor fee debt. Returns the amount that must be
/// burnt and an error if there are not sufficient funds to cover repayment.
/// Miner state repays from unlocked funds and fails if unlocked funds are insufficient to cover fee debt.
/// FeeDebt will be zero after a successful call.
pub fn repay_debts(&mut self, curr_balance: &TokenAmount) -> anyhow::Result<TokenAmount> {
let unlocked_balance = self.get_unlocked_balance(curr_balance)?;
if unlocked_balance < self.fee_debt {
return Err(actor_error!(
insufficient_funds,
"unlocked balance can not repay fee debt ({} < {})",
unlocked_balance,
self.fee_debt
)
.into());
}
Ok(std::mem::take(&mut self.fee_debt))
}
/// Unlocks an amount of funds that have *not yet vested*, if possible.
/// The soonest-vesting entries are unlocked first.
/// Returns the amount actually unlocked.
pub fn unlock_unvested_funds<BS: Blockstore>(
&mut self,
store: &BS,
current_epoch: ChainEpoch,
target: &TokenAmount,
) -> anyhow::Result<TokenAmount> {
if target.is_zero() || self.locked_funds.is_zero() {
return Ok(TokenAmount::zero());
}
let mut vesting_funds = self.load_vesting_funds(store)?;
let amount_unlocked = vesting_funds.unlock_unvested_funds(current_epoch, target);
self.locked_funds -= &amount_unlocked;
if self.locked_funds.is_negative() {
return Err(anyhow!(
"negative locked funds {} after unlocking {}",
self.locked_funds,
amount_unlocked
));
}
self.save_vesting_funds(store, &vesting_funds)?;
Ok(amount_unlocked)
}
/// Unlocks all vesting funds that have vested before the provided epoch.
/// Returns the amount unlocked.
pub fn unlock_vested_funds<BS: Blockstore>(
&mut self,
store: &BS,
current_epoch: ChainEpoch,
) -> anyhow::Result<TokenAmount> {
if self.locked_funds.is_zero() {
return Ok(TokenAmount::zero());
}
let mut vesting_funds = self.load_vesting_funds(store)?;
let amount_unlocked = vesting_funds.unlock_vested_funds(current_epoch);
self.locked_funds -= &amount_unlocked;
if self.locked_funds.is_negative() {
return Err(anyhow!(
"vesting cause locked funds to become negative: {}",
self.locked_funds,
));
}
self.save_vesting_funds(store, &vesting_funds)?;
Ok(amount_unlocked)
}
/// CheckVestedFunds returns the amount of vested funds that have vested before the provided epoch.
pub fn check_vested_funds<BS: Blockstore>(
&self,
store: &BS,
current_epoch: ChainEpoch,
) -> anyhow::Result<TokenAmount> {
let vesting_funds = self.load_vesting_funds(store)?;
Ok(vesting_funds
.funds
.iter()
.take_while(|fund| fund.epoch < current_epoch)
.fold(TokenAmount::zero(), |acc, fund| acc + &fund.amount))