-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathlib.rs
1841 lines (1632 loc) · 75.4 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::cmp::min;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use cid::multihash::Multihash;
use cid::Cid;
use fil_actors_runtime::reward::ThisEpochRewardReturn;
use frc46_token::token::types::{BalanceReturn, TransferFromParams, TransferFromReturn};
use fvm_ipld_bitfield::BitField;
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::ipld_block::IpldBlock;
use fvm_ipld_encoding::{RawBytes, DAG_CBOR};
use fvm_ipld_hamt::BytesKey;
use fvm_shared::address::Address;
use fvm_shared::bigint::BigInt;
use fvm_shared::clock::{ChainEpoch, EPOCH_UNDEFINED};
use fvm_shared::crypto::hash::SupportedHashes;
use fvm_shared::deal::DealID;
use fvm_shared::econ::TokenAmount;
use fvm_shared::error::ExitCode;
use fvm_shared::piece::PieceInfo;
use fvm_shared::sector::{RegisteredSealProof, SectorNumber, SectorSize, StoragePower};
use fvm_shared::sys::SendFlags;
use fvm_shared::{ActorID, METHOD_CONSTRUCTOR, METHOD_SEND};
use integer_encoding::VarInt;
use log::{info, warn};
use num_derive::FromPrimitive;
use num_traits::Zero;
use fil_actors_runtime::cbor::{deserialize, serialize};
use fil_actors_runtime::runtime::builtins::Type;
use fil_actors_runtime::runtime::{ActorCode, Policy, Runtime};
use fil_actors_runtime::{
actor_dispatch, actor_error, deserialize_block, ActorContext, ActorDowncast, ActorError,
AsActorError, BURNT_FUNDS_ACTOR_ADDR, CRON_ACTOR_ADDR, DATACAP_TOKEN_ACTOR_ADDR,
REWARD_ACTOR_ADDR, STORAGE_POWER_ACTOR_ADDR, SYSTEM_ACTOR_ADDR, VERIFIED_REGISTRY_ACTOR_ADDR,
};
use fil_actors_runtime::{extract_send_result, BatchReturnGen, FIRST_ACTOR_SPECIFIC_EXIT_CODE};
use crate::balance_table::BalanceTable;
use crate::ext::verifreg::{AllocationID, AllocationRequest};
pub use self::deal::*;
use self::policy::*;
pub use self::state::*;
pub use self::types::*;
// exports for testing
pub mod balance_table;
#[doc(hidden)]
pub mod ext;
pub mod policy;
pub mod testing;
mod deal;
mod emit;
mod state;
mod types;
#[cfg(feature = "fil-actor")]
fil_actors_runtime::wasm_trampoline!(Actor);
pub const NO_ALLOCATION_ID: u64 = 0;
// Indicates that information about a past deal is no longer available.
pub const EX_DEAL_EXPIRED: ExitCode = ExitCode::new(FIRST_ACTOR_SPECIFIC_EXIT_CODE);
// Indicates that information about a deal's activation is not yet available.
pub const EX_DEAL_NOT_ACTIVATED: ExitCode = ExitCode::new(FIRST_ACTOR_SPECIFIC_EXIT_CODE + 1);
/// Market actor methods available
#[derive(FromPrimitive)]
#[repr(u64)]
pub enum Method {
Constructor = METHOD_CONSTRUCTOR,
AddBalance = 2,
WithdrawBalance = 3,
PublishStorageDeals = 4,
VerifyDealsForActivation = 5,
BatchActivateDeals = 6,
OnMinerSectorsTerminate = 7,
// ComputeDataCommitment = 8, // Deprecated
CronTick = 9,
// Method numbers derived from FRC-0042 standards
AddBalanceExported = frc42_dispatch::method_hash!("AddBalance"),
WithdrawBalanceExported = frc42_dispatch::method_hash!("WithdrawBalance"),
PublishStorageDealsExported = frc42_dispatch::method_hash!("PublishStorageDeals"),
GetBalanceExported = frc42_dispatch::method_hash!("GetBalance"),
GetDealDataCommitmentExported = frc42_dispatch::method_hash!("GetDealDataCommitment"),
GetDealClientExported = frc42_dispatch::method_hash!("GetDealClient"),
GetDealProviderExported = frc42_dispatch::method_hash!("GetDealProvider"),
GetDealLabelExported = frc42_dispatch::method_hash!("GetDealLabel"),
GetDealTermExported = frc42_dispatch::method_hash!("GetDealTerm"),
GetDealTotalPriceExported = frc42_dispatch::method_hash!("GetDealTotalPrice"),
GetDealClientCollateralExported = frc42_dispatch::method_hash!("GetDealClientCollateral"),
GetDealProviderCollateralExported = frc42_dispatch::method_hash!("GetDealProviderCollateral"),
GetDealVerifiedExported = frc42_dispatch::method_hash!("GetDealVerified"),
GetDealActivationExported = frc42_dispatch::method_hash!("GetDealActivation"),
GetDealSectorExported = frc42_dispatch::method_hash!("GetDealSector"),
SettleDealPaymentsExported = frc42_dispatch::method_hash!("SettleDealPayments"),
SectorContentChangedExported = ext::miner::SECTOR_CONTENT_CHANGED,
}
/// Market Actor
pub struct Actor;
impl Actor {
pub fn constructor(rt: &impl Runtime) -> Result<(), ActorError> {
rt.validate_immediate_caller_is(std::iter::once(&SYSTEM_ACTOR_ADDR))?;
let st = State::new(rt.store())?;
rt.create(&st)?;
Ok(())
}
/// Deposits the received value into the balance held in escrow.
fn add_balance(rt: &impl Runtime, params: AddBalanceParams) -> Result<(), ActorError> {
let msg_value = rt.message().value_received();
if msg_value <= TokenAmount::zero() {
return Err(actor_error!(
illegal_argument,
"balance to add must be greater than zero was: {}",
msg_value
));
}
rt.validate_immediate_caller_accept_any()?;
let (nominal, _, _) = escrow_address(rt, ¶ms.provider_or_client)?;
rt.transaction(|st: &mut State, rt| {
st.add_balance_to_escrow_table(rt.store(), &nominal, &msg_value)?;
Ok(())
})?;
Ok(())
}
/// Attempt to withdraw the specified amount from the balance held in escrow.
/// If less than the specified amount is available, yields the entire available balance.
fn withdraw_balance(
rt: &impl Runtime,
params: WithdrawBalanceParams,
) -> Result<WithdrawBalanceReturn, ActorError> {
if params.amount < TokenAmount::zero() {
return Err(actor_error!(illegal_argument, "negative amount: {}", params.amount));
}
let (nominal, recipient, approved) = escrow_address(rt, ¶ms.provider_or_client)?;
// for providers -> only corresponding owner or worker can withdraw
// for clients -> only the client i.e the recipient can withdraw
rt.validate_immediate_caller_is(&approved)?;
let amount_extracted = rt.transaction(|st: &mut State, rt| {
let ex = st.withdraw_balance_from_escrow_table(rt.store(), &nominal, ¶ms.amount)?;
Ok(ex)
})?;
extract_send_result(rt.send_simple(
&recipient,
METHOD_SEND,
None,
amount_extracted.clone(),
))?;
Ok(WithdrawBalanceReturn { amount_withdrawn: amount_extracted })
}
/// Returns the escrow balance and locked amount for an address.
fn get_balance(
rt: &impl Runtime,
params: GetBalanceParams,
) -> Result<GetBalanceReturn, ActorError> {
rt.validate_immediate_caller_accept_any()?;
let account = params.account;
let nominal = rt.resolve_address(&account).ok_or_else(|| {
actor_error!(illegal_argument, "failed to resolve address {}", account)
})?;
let account = Address::new_id(nominal);
let store = rt.store();
let st: State = rt.state()?;
let balances = BalanceTable::from_root(store, &st.escrow_table, "escrow table")?;
let locks = BalanceTable::from_root(store, &st.locked_table, "locked table")?;
let balance = balances.get(&account)?;
let locked = locks.get(&account)?;
Ok(GetBalanceReturn { balance, locked })
}
/// Publish a new set of storage deals (not yet included in a sector).
fn publish_storage_deals(
rt: &impl Runtime,
params: PublishStorageDealsParams,
) -> Result<PublishStorageDealsReturn, ActorError> {
rt.validate_immediate_caller_accept_any()?;
if params.deals.is_empty() {
return Err(actor_error!(illegal_argument, "Empty deals parameter"));
}
// All deals should have the same provider so get worker once
let provider_raw = params.deals[0].proposal.provider;
let provider_id = rt.resolve_address(&provider_raw).ok_or_else(|| {
actor_error!(not_found, "failed to resolve provider address {}", provider_raw)
})?;
let code_id = rt
.get_actor_code_cid(&provider_id)
.ok_or_else(|| actor_error!(not_found, "no code ID for address {}", provider_id))?;
if rt.resolve_builtin_actor_type(&code_id) != Some(Type::Miner) {
return Err(actor_error!(
illegal_argument,
"deal provider is not a storage miner actor"
));
}
let caller = rt.message().caller();
let caller_status: ext::miner::IsControllingAddressReturn =
deserialize_block(extract_send_result(rt.send_simple(
&Address::new_id(provider_id),
ext::miner::IS_CONTROLLING_ADDRESS_EXPORTED,
IpldBlock::serialize_cbor(&ext::miner::IsControllingAddressParam {
address: caller,
})?,
TokenAmount::zero(),
))?)?;
if !caller_status.is_controlling {
return Err(actor_error!(
forbidden,
"caller {} is not worker or control address of provider {}",
caller,
provider_id
));
}
// Deals that passed `AuthenticateMessage` and other state-less checks.
let mut validity_index: Vec<bool> = Vec::with_capacity(params.deals.len());
let baseline_power = request_current_baseline_power(rt)?;
let (network_raw_power, _) = request_current_network_power(rt)?;
// We perform these checks before loading state since the call to `AuthenticateMessage` could recurse
for (di, deal) in params.deals.iter().enumerate() {
let valid = if let Err(e) = validate_deal(rt, deal, &network_raw_power, &baseline_power)
{
info!("invalid deal {}: {}", di, e);
false
} else {
true
};
validity_index.push(valid);
}
struct ValidDeal {
proposal: DealProposal,
serialized_proposal: RawBytes,
cid: Cid,
}
// Deals that passed validation.
let mut valid_deals: Vec<ValidDeal> = Vec::with_capacity(params.deals.len());
// CIDs of valid proposals.
let mut proposal_cid_lookup = BTreeSet::new();
let mut total_client_lockup: BTreeMap<ActorID, TokenAmount> = BTreeMap::new();
// Client datacap balance remaining after allocations for deals processed so far.
let mut client_datacap_remaining: BTreeMap<ActorID, TokenAmount> = BTreeMap::new();
// Verified allocation requests to make for each client, paired with the proposal CID.
let mut client_alloc_reqs: BTreeMap<ActorID, Vec<(Cid, AllocationRequest)>> =
BTreeMap::new();
let mut total_provider_lockup = TokenAmount::zero();
let mut valid_input_bf = BitField::default();
let curr_epoch = rt.curr_epoch();
let state: State = rt.state()?;
for (di, mut deal) in params.deals.into_iter().enumerate() {
if !*validity_index.get(di).context_code(
ExitCode::USR_ASSERTION_FAILED,
"validity index has incorrect length",
)? {
continue;
}
if deal.proposal.provider != Address::new_id(provider_id)
&& deal.proposal.provider != provider_raw
{
info!(
"invalid deal {}: cannot publish deals from multiple providers in one batch",
di
);
continue;
}
let client_id = match rt.resolve_address(&deal.proposal.client) {
Some(client) => client,
_ => {
info!(
"invalid deal {}: failed to resolve proposal.client address {} for deal",
di, deal.proposal.client
);
continue;
}
};
// drop deals with insufficient lock up to cover costs
let mut client_lockup =
total_client_lockup.get(&client_id).cloned().unwrap_or_default();
client_lockup += deal.proposal.client_balance_requirement();
let client_balance_ok =
state.balance_covered(rt.store(), Address::new_id(client_id), &client_lockup)?;
if !client_balance_ok {
info!("invalid deal: {}: insufficient client funds to cover proposal cost", di);
continue;
}
let mut provider_lockup = total_provider_lockup.clone();
provider_lockup += &deal.proposal.provider_collateral;
let provider_balance_ok = state.balance_covered(
rt.store(),
Address::new_id(provider_id),
&provider_lockup,
)?;
if !provider_balance_ok {
info!("invalid deal: {}: insufficient provider funds to cover proposal cost", di);
continue;
}
// drop duplicate deals
// Normalise provider and client addresses in the proposal stored on chain.
// Must happen after signature verification and before taking cid.
deal.proposal.provider = Address::new_id(provider_id);
deal.proposal.client = Address::new_id(client_id);
let serialized_proposal = serialize(&deal.proposal, "normalized deal proposal")
.context_code(ExitCode::USR_SERIALIZATION, "failed to serialize")?;
let pcid = serialized_deal_cid(rt, &serialized_proposal).map_err(
|e| actor_error!(illegal_argument; "failed to take cid of proposal {}: {}", di, e),
)?;
// check proposalCids for duplication within message batch
// check state PendingProposals for duplication across messages
let duplicate_in_state = state.has_pending_deal(rt.store(), &pcid)?;
let duplicate_in_message = proposal_cid_lookup.contains(&pcid);
if duplicate_in_state || duplicate_in_message {
info!("invalid deal {}: cannot publish duplicate deal proposal", di);
continue;
}
// Fetch each client's datacap balance and calculate the amount of datacap required for
// each client's verified deals.
// Drop any verified deals for which the client has insufficient datacap.
if deal.proposal.verified_deal {
let remaining_datacap = match client_datacap_remaining.get(&client_id).cloned() {
None => balance_of(rt, &Address::new_id(client_id))
.with_context_code(ExitCode::USR_NOT_FOUND, || {
format!("failed to get datacap balance for client {}", client_id)
})?,
Some(client_data) => client_data,
};
let piece_datacap_required =
TokenAmount::from_whole(deal.proposal.piece_size.0 as i64);
if remaining_datacap < piece_datacap_required {
client_datacap_remaining.insert(client_id, remaining_datacap);
continue; // Drop the deal
}
client_datacap_remaining
.insert(client_id, remaining_datacap - piece_datacap_required);
client_alloc_reqs
.entry(client_id)
.or_default()
.push((pcid, alloc_request_for_deal(&deal.proposal, rt.policy(), curr_epoch)));
}
total_provider_lockup = provider_lockup;
total_client_lockup.insert(client_id, client_lockup);
proposal_cid_lookup.insert(pcid);
valid_deals.push(ValidDeal { proposal: deal.proposal, serialized_proposal, cid: pcid });
valid_input_bf.set(di as u64)
}
// Make datacap allocation requests by transferring datacap tokens, once per client.
// Record the allocation ID for each deal proposal CID.
let mut deal_allocation_ids: BTreeMap<Cid, AllocationID> = BTreeMap::new();
for (client_id, cids_and_reqs) in client_alloc_reqs.iter() {
let reqs: Vec<AllocationRequest> =
cids_and_reqs.iter().map(|(_, req)| req.clone()).collect();
let params = datacap_transfer_request(&Address::new_id(*client_id), reqs)?;
// A datacap transfer is all-or-nothing.
// We expect it to succeed because we checked the client's balance earlier.
let alloc_ids = transfer_from(rt, params)
.with_context_code(ExitCode::USR_ILLEGAL_STATE, || {
format!("failed to transfer datacap from client {}", *client_id)
})?;
if alloc_ids.len() != cids_and_reqs.len() {
return Err(
actor_error!(illegal_state; "datacap transfer returned {} allocation IDs for {} requests",
alloc_ids.len(), cids_and_reqs.len()),
);
}
for ((cid, _), alloc_id) in cids_and_reqs.iter().zip(alloc_ids.iter()) {
deal_allocation_ids.insert(*cid, *alloc_id);
}
}
let valid_deal_count = valid_input_bf.len();
if valid_deal_count != valid_deals.len() as u64 {
return Err(actor_error!(
illegal_state,
"{} valid deals but valid_deal_count {}",
valid_deals.len(),
valid_deal_count
));
}
if valid_deal_count == 0 {
return Err(actor_error!(illegal_argument, "All deal proposals invalid"));
}
let mut new_deal_ids = Vec::with_capacity(valid_deals.len());
rt.transaction(|st: &mut State, rt| {
let mut pending_deals: Vec<Cid> = vec![];
let mut deal_proposals: Vec<(DealID, DealProposal)> = vec![];
let mut deals_by_epoch: Vec<(ChainEpoch, DealID)> = vec![];
let mut pending_deal_allocation_ids: Vec<(DealID, AllocationID)> = vec![];
// All storage dealProposals will be added in an atomic transaction; this operation will be unrolled if any of them fails.
// This should only fail on programmer error because all expected invalid conditions should be filtered in the first set of checks.
for valid_deal in valid_deals.iter() {
st.lock_client_and_provider_balances(rt.store(), &valid_deal.proposal)?;
// Store the proposal CID in pending deals set.
pending_deals.push(valid_deal.cid);
// Allocate a deal ID and store the proposal in the proposals AMT.
let deal_id = st.generate_storage_deal_id();
deal_proposals.push((deal_id, valid_deal.proposal.clone()));
// Store verified allocation (if any) in the pending allocation IDs map.
// It will be removed when the deal is activated or expires.
if let Some(alloc_id) = deal_allocation_ids.get(&valid_deal.cid) {
pending_deal_allocation_ids.push((deal_id, *alloc_id));
}
// Randomize the first epoch for when the deal will be processed so an attacker isn't able to
// schedule too many deals for the same tick.
deals_by_epoch.push((
next_update_epoch(
deal_id,
rt.policy().deal_updates_interval,
valid_deal.proposal.start_epoch,
),
deal_id,
));
new_deal_ids.push(deal_id);
}
st.put_pending_deals(rt.store(), &pending_deals)?;
st.put_deal_proposals(rt.store(), &deal_proposals)?;
st.put_pending_deal_allocation_ids(rt.store(), &pending_deal_allocation_ids)?;
st.put_deals_by_epoch(rt.store(), &deals_by_epoch)?;
Ok(())
})?;
// notify clients, any failures cause the entire publish_storage_deals method to fail
// it's unsafe to ignore errors here, since that could be used to attack storage contract clients
// that might be unaware they're making storage deals
for (valid_deal, &deal_id) in valid_deals.iter().zip(&new_deal_ids) {
_ = extract_send_result(rt.send_simple(
&valid_deal.proposal.client,
MARKET_NOTIFY_DEAL_METHOD,
IpldBlock::serialize_cbor(&MarketNotifyDealParams {
proposal: valid_deal.serialized_proposal.to_vec(),
deal_id,
})?,
TokenAmount::zero(),
))
.with_context_code(ExitCode::USR_ILLEGAL_ARGUMENT, || {
format!("failed to notify deal with proposal cid {}", valid_deal.cid)
})?;
emit::deal_published(
rt,
valid_deal.proposal.client.id().unwrap(),
valid_deal.proposal.provider.id().unwrap(),
deal_id,
)?;
}
Ok(PublishStorageDealsReturn { ids: new_deal_ids, valid_deals: valid_input_bf })
}
/// Verify that a given set of storage deals is valid for a sector currently being PreCommitted
/// and return UnsealedCID for the set of deals.
fn verify_deals_for_activation(
rt: &impl Runtime,
params: VerifyDealsForActivationParams,
) -> Result<VerifyDealsForActivationReturn, ActorError> {
rt.validate_immediate_caller_type(std::iter::once(&Type::Miner))?;
let miner_addr = rt.message().caller();
let curr_epoch = rt.curr_epoch();
let st: State = rt.state()?;
let proposal_array = st.load_proposals(rt.store())?;
let mut unsealed_cids = Vec::with_capacity(params.sectors.len());
for sector in params.sectors.iter() {
let sector_proposals = get_proposals(&proposal_array, §or.deal_ids, st.next_id)?;
let sector_size = sector
.sector_type
.sector_size()
.map_err(|e| actor_error!(illegal_argument, "sector size unknown: {}", e))?;
validate_deals_for_sector(
§or_proposals,
&miner_addr,
sector.sector_expiry,
curr_epoch,
Some(sector_size),
)
.context("failed to validate deal proposals for activation")?;
let commd = if sector.deal_ids.is_empty() {
None
} else {
let proposals_iter = sector_proposals.iter().map(|(_, p)| p);
Some(compute_data_commitment(rt, proposals_iter, sector.sector_type)?)
};
unsealed_cids.push(commd);
}
Ok(VerifyDealsForActivationReturn { unsealed_cids })
}
/// Activate a set of deals grouped by sector, returning the size and
/// extra info about verified deals.
/// Sectors' deals are activated in parameter-defined order.
/// Each sector's deals are activated or fail as a group, but independently of other sectors.
/// Note that confirming all deals fit within a sector is the caller's responsibility
/// (and is implied by confirming the sector's data commitment is derived from the deal peices).
// see https://github.com/filecoin-project/builtin-actors/issues/1308
fn batch_activate_deals(
rt: &impl Runtime,
params: BatchActivateDealsParams,
) -> Result<BatchActivateDealsResult, ActorError> {
rt.validate_immediate_caller_type(std::iter::once(&Type::Miner))?;
let miner_addr = rt.message().caller();
let curr_epoch = rt.curr_epoch();
let (activations, batch_ret) = rt.transaction(|st: &mut State, rt| {
let proposals = st.load_proposals(rt.store())?;
let states = st.load_deal_states(rt.store())?;
let pending_deals = st.load_pending_deals(rt.store())?;
let mut pending_deal_allocation_ids =
st.load_pending_deal_allocation_ids(rt.store())?;
let mut deal_states: Vec<(DealID, DealState)> = vec![];
let mut batch_gen = BatchReturnGen::new(params.sectors.len());
let mut activations: Vec<SectorDealActivation> = vec![];
let mut activated_deals: HashSet<DealID> = HashSet::new();
let mut sectors_deals: Vec<(SectorNumber, Vec<DealID>)> = vec![];
'sector: for sector in params.sectors {
let mut sector_deal_ids = sector.deal_ids.clone();
sector_deal_ids.sort();
if sector_deal_ids.windows(2).any(|w| w[0] == w[1]) {
log::warn!("failed to activate sector, duplicate deal");
batch_gen.add_fail(ExitCode::USR_ILLEGAL_ARGUMENT);
continue;
}
let mut validated_proposals = vec![];
// Iterate once to validate all the requested deals.
// If a deal fails, skip the whole sector.
for &deal_id in §or.deal_ids {
// Check each deal is present only once, within and across sectors.
if activated_deals.contains(&deal_id) {
log::warn!("failed to activate sector, duplicated deal {}", deal_id);
batch_gen.add_fail(ExitCode::USR_ILLEGAL_ARGUMENT);
continue 'sector;
}
let proposal = match preactivate_deal(
rt,
deal_id,
&proposals,
&states,
&pending_deals,
&miner_addr,
sector.sector_expiry,
curr_epoch,
st.next_id,
)? {
Ok(v) => v,
Err(e) => {
log::warn!("failed to activate deal: {}", e);
batch_gen.add_fail(e.exit_code());
continue 'sector;
}
};
validated_proposals.push(proposal);
}
let mut activated = vec![];
// Given that all deals validated, prepare the state updates for them all.
// There's no continue below here to ensure updates are consistent.
// Any error must abort.
for (deal_id, proposal) in sector.deal_ids.iter().zip(&validated_proposals) {
activated_deals.insert(*deal_id);
// Extract and remove any verified allocation ID for the pending deal.
let alloc_id =
pending_deal_allocation_ids.delete(deal_id)?.unwrap_or(NO_ALLOCATION_ID);
activated.push(ActivatedDeal {
client: proposal.client.id().unwrap(),
allocation_id: alloc_id,
data: proposal.piece_cid,
size: proposal.piece_size,
});
// Prepare initial deal state.
deal_states.push((
*deal_id,
DealState {
sector_number: sector.sector_number,
sector_start_epoch: curr_epoch,
last_updated_epoch: EPOCH_UNDEFINED,
slash_epoch: EPOCH_UNDEFINED,
},
));
}
let data_commitment = if params.compute_cid && !sector.deal_ids.is_empty() {
Some(compute_data_commitment(rt, &validated_proposals, sector.sector_type)?)
} else {
None
};
sectors_deals.push((sector.sector_number, sector.deal_ids.clone()));
activations.push(SectorDealActivation { activated, unsealed_cid: data_commitment });
for (deal_id, proposal) in sector.deal_ids.iter().zip(&validated_proposals) {
emit::deal_activated(
rt,
*deal_id,
proposal.client.id().unwrap(),
proposal.provider.id().unwrap(),
)?;
}
batch_gen.add_success();
}
st.put_deal_states(rt.store(), &deal_states)?;
st.put_sector_deal_ids(rt.store(), miner_addr.id().unwrap(), §ors_deals)?;
st.save_pending_deal_allocation_ids(&mut pending_deal_allocation_ids)?;
Ok((activations, batch_gen.gen()))
})?;
Ok(BatchActivateDealsResult { activations, activation_results: batch_ret })
}
/// Receives notification of a change to sector content, which may satisfy to activate a deal.
/// Deals are activated or fail independently, including in the same sector.
/// This is an alternative to ActivateDeals.
fn sector_content_changed(
rt: &impl Runtime,
params: ext::miner::SectorContentChangedParams,
) -> Result<ext::miner::SectorContentChangedReturn, ActorError> {
rt.validate_immediate_caller_type(std::iter::once(&Type::Miner))?;
let miner_addr = rt.message().caller();
let curr_epoch = rt.curr_epoch();
let sectors_ret = rt.transaction(|st: &mut State, rt| {
let proposals = st.load_proposals(rt.store())?;
let states = st.load_deal_states(rt.store())?;
let pending_deals = st.load_pending_deals(rt.store())?;
let mut pending_deal_allocation_ids =
st.load_pending_deal_allocation_ids(rt.store())?;
let mut deal_states: Vec<(DealID, DealState)> = vec![];
let mut activated_deals: HashSet<DealID> = HashSet::new();
let mut sectors_deals: Vec<(SectorNumber, Vec<DealID>)> = vec![];
let mut sectors_ret: Vec<ext::miner::SectorReturn> = vec![];
for sector in ¶ms.sectors {
let mut sector_deal_ids: Vec<DealID> = vec![];
let mut pieces_ret: Vec<_> =
vec![ext::miner::PieceReturn { accepted: false }; sector.added.len()];
for (piece, ret) in sector.added.iter().zip(&mut pieces_ret) {
let deal_id: DealID = match deserialize(&piece.payload, "deal id") {
Ok(v) => v,
Err(e) => {
log::warn!("failed to deserialize deal id {:?}: {}", piece.payload, e);
continue;
}
};
if activated_deals.contains(&deal_id) {
log::warn!("duplicated deal {}", deal_id);
continue;
}
let proposal = match preactivate_deal(
rt,
deal_id,
&proposals,
&states,
&pending_deals,
&miner_addr,
sector.minimum_commitment_epoch,
curr_epoch,
st.next_id,
)? {
Ok(id) => id,
Err(e) => {
log::warn!("failed to activate deal {}: {}", deal_id, e);
continue;
}
};
if piece.data != proposal.piece_cid {
log::warn!(
"deal {} piece CID {} doesn't match {}",
deal_id,
piece.data,
proposal.piece_cid
);
continue;
}
if piece.size != proposal.piece_size {
log::warn!(
"deal {} piece size {} doesn't match {}",
deal_id,
piece.size.0,
proposal.piece_size.0
);
continue;
}
// No continue below here, to ensure state changes are consistent.
activated_deals.insert(deal_id);
emit::deal_activated(
rt,
deal_id,
proposal.client.id().unwrap(),
proposal.provider.id().unwrap(),
)?;
// Remove any verified allocation ID for the pending deal.
pending_deal_allocation_ids.delete(&deal_id)?;
deal_states.push((
deal_id,
DealState {
sector_number: sector.sector,
sector_start_epoch: curr_epoch,
last_updated_epoch: EPOCH_UNDEFINED,
slash_epoch: EPOCH_UNDEFINED,
},
));
sector_deal_ids.push(deal_id);
ret.accepted = true;
}
sectors_deals.push((sector.sector, sector_deal_ids));
assert_eq!(pieces_ret.len(), sector.added.len(), "mismatched piece returns");
sectors_ret.push(ext::miner::SectorReturn { added: pieces_ret });
}
st.put_deal_states(rt.store(), &deal_states)?;
st.put_sector_deal_ids(rt.store(), miner_addr.id().unwrap(), §ors_deals)?;
st.save_pending_deal_allocation_ids(&mut pending_deal_allocation_ids)?;
assert_eq!(sectors_ret.len(), params.sectors.len(), "mismatched sector returns");
Ok(sectors_ret)
})?;
Ok(ext::miner::SectorContentChangedReturn { sectors: sectors_ret })
}
/// Terminate a set of deals in response to their containing sector being terminated.
/// Slash provider collateral, refund client collateral, and refund partial unpaid escrow
/// amount to client.
fn on_miner_sectors_terminate(
rt: &impl Runtime,
params: OnMinerSectorsTerminateParams,
) -> Result<(), ActorError> {
rt.validate_immediate_caller_type(std::iter::once(&Type::Miner))?;
let miner_addr = rt.message().caller();
let burn_amount = rt.transaction(|st: &mut State, rt| {
// Load the deal proposals and deal states once
let proposals = st.load_proposals(rt.store())?;
let states = st.load_deal_states(rt.store())?;
// The sector deals mapping is removed all at once.
// Note there may be some deal states that are not removed here,
// despite deletion of this mapping, e.g. for expired but not-yet-settled deals.
// The sector->deal mapping is no longer needed (the deal state has sector number too).
let all_deal_ids = st.pop_sector_deal_ids(
rt.store(),
miner_addr.id().unwrap(),
params.sectors.iter(),
)?;
let mut total_slashed = TokenAmount::zero();
for id in all_deal_ids {
let deal = proposals
.get(id)
.with_context_code(ExitCode::USR_ILLEGAL_STATE, || {
format!("failed to load deal proposal {}", id)
})?
.cloned();
// The deal may have expired and been deleted before the sector is terminated.
// Nothing to do, but continue execution for the other deals.
if deal.is_none() {
info!("couldn't find deal {}", id);
continue;
}
let deal = deal.unwrap();
if deal.provider != miner_addr {
return Err(actor_error!(
illegal_state,
"caller {} is not the provider {} of deal {}",
miner_addr,
deal.provider,
id
));
}
// do not slash expired deals
if deal.end_epoch <= params.epoch {
info!("deal {} expired, not slashing", id);
continue;
}
let mut state: DealState = states
.get(id)
.with_context_code(ExitCode::USR_ILLEGAL_STATE, || {
format!("failed to load deal state {}", id)
})?
.cloned()
.ok_or_else(|| actor_error!(illegal_argument, "no state for deal {}", id))?;
// If a deal is already slashed, there should be no existing state for it
// but we process it here for deletion anyway
if state.slash_epoch != EPOCH_UNDEFINED {
warn!("deal {}, already slashed, terminating now anyway", id);
}
// Deals that were never processed may still have a pending proposal linked
if state.last_updated_epoch == EPOCH_UNDEFINED {
let dcid = deal_cid(rt, &deal)?;
st.remove_pending_deal(rt.store(), dcid)?;
}
state.slash_epoch = params.epoch;
total_slashed += st.process_slashed_deal(rt.store(), &deal, &state)?;
st.remove_completed_deal(rt.store(), id)?;
emit::deal_terminated(
rt,
id,
deal.client.id().unwrap(),
deal.provider.id().unwrap(),
)?;
}
Ok(total_slashed)
})?;
if burn_amount.is_positive() {
extract_send_result(rt.send_simple(
&BURNT_FUNDS_ACTOR_ADDR,
METHOD_SEND,
None,
burn_amount,
))?;
}
Ok(())
}
fn cron_tick(rt: &impl Runtime) -> Result<(), ActorError> {
rt.validate_immediate_caller_is(std::iter::once(&CRON_ACTOR_ADDR))?;
let mut amount_slashed = TokenAmount::zero();
let curr_epoch = rt.curr_epoch();
rt.transaction(|st: &mut State, rt| {
let last_cron = st.last_cron;
let mut provider_deals_to_remove =
BTreeMap::<ActorID, BTreeMap<SectorNumber, Vec<DealID>>>::new();
let mut new_updates_scheduled: BTreeMap<ChainEpoch, Vec<DealID>> = BTreeMap::new();
let mut epochs_completed: Vec<ChainEpoch> = vec![];
for i in (last_cron + 1)..=rt.curr_epoch() {
let deal_ids = st.get_deals_for_epoch(rt.store(), i)?;
for deal_id in deal_ids {
let deal_proposal = match st.find_proposal(rt.store(), deal_id)? {
Some(dp) => dp,
// proposal might have been cleaned up by manual settlement or termination prior to reaching
// this scheduled cron tick. nothing more to do for this deal
None => continue,
};
let dcid = deal_cid(rt, &deal_proposal)?;
let mut state = match st.get_active_deal_or_process_timeout(
rt.store(),
curr_epoch,
deal_id,
&deal_proposal,
&dcid,
)? {
LoadDealState::Loaded(state) => state,
LoadDealState::ProposalExpired(expiration_penalty) => {
amount_slashed += expiration_penalty;
continue;
}
LoadDealState::TooEarly => {
return Err(actor_error!(
illegal_state,
"deal {} processed before start epoch {}",
deal_id,
deal_proposal.start_epoch
))
}
};
if state.last_updated_epoch == EPOCH_UNDEFINED {
st.remove_pending_deal(rt.store(), dcid)?.ok_or_else(|| {
actor_error!(
illegal_state,
"failed to delete pending proposal: does not exist"
)
})?;
// newly activated deals are not scheduled for cron processing. they are handled explicitly by
// calling ProcessDealUpdates method with specific deal ids.
// the code below this point handles legacy deals that are already scheduled for cron processing
continue;
}
// https://github.com/filecoin-project/builtin-actors/issues/1389
// handling of legacy deals is still done in cron. we handle such deals here and continue to
// reschedule them. eventually, all legacy deals will expire and the below code can be removed.
let (slash_amount, _payment_amount, completed, remove_deal) = st
.process_deal_update(
rt.store(),
&state,
&deal_proposal,
&dcid,
curr_epoch,
)?;
if remove_deal {
// TODO: remove handling for terminated-deal slashing when marked-for-termination deals are all processed
// https://github.com/filecoin-project/builtin-actors/issues/1388
amount_slashed += slash_amount;
// Delete proposal and state simultaneously.
st.remove_completed_deal(rt.store(), deal_id)?;
// All proposals are stored with normalised addresses.
let provider = deal_proposal.provider.id().unwrap();
provider_deals_to_remove
.entry(provider)
.or_default()
.entry(state.sector_number)
.or_default()
.push(deal_id);
if !completed {
emit::deal_terminated(
rt,
deal_id,
deal_proposal.client.id().unwrap(),
deal_proposal.provider.id().unwrap(),
)?;
}
} else {
if !slash_amount.is_zero() {
return Err(actor_error!(
illegal_state,
"continuing deal {} should not be slashed",
deal_id
));
}
state.last_updated_epoch = curr_epoch;
st.put_deal_states(rt.store(), &[(deal_id, state)])?;
// Compute and record the next epoch in which this deal will be updated.