/
contractor.go
1744 lines (1518 loc) · 56.8 KB
/
contractor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package autopilot
import (
"context"
"errors"
"fmt"
"math"
"sort"
"strings"
"sync"
"time"
"github.com/montanaflynn/stats"
rhpv2 "go.sia.tech/core/rhp/v2"
rhpv3 "go.sia.tech/core/rhp/v3"
"go.sia.tech/core/types"
"go.sia.tech/renterd/api"
"go.sia.tech/renterd/hostdb"
"go.sia.tech/renterd/internal/utils"
"go.sia.tech/renterd/wallet"
"go.sia.tech/renterd/worker"
"go.uber.org/zap"
)
const (
// broadcastRevisionRetriesPerInterval is the number of chances we give a
// contract that fails to broadcst to be broadcasted again within a single
// contract broadcast interval.
broadcastRevisionRetriesPerInterval = 5
// estimatedFileContractTransactionSetSize is the estimated blockchain size
// of a transaction set between a renter and a host that contains a file
// contract.
estimatedFileContractTransactionSetSize = 2048
// failedRenewalForgivenessPeriod is the amount of time we wait before
// punishing a contract for not being able to refresh
failedRefreshForgivenessPeriod = 24 * time.Hour
// leewayPctCandidateHosts is the leeway we apply when fetching candidate
// hosts, we fetch ~10% more than required
leewayPctCandidateHosts = 1.1
// leewayPctRequiredContracts is the leeway we apply on the amount of
// contracts the config dictates we should have, we'll only form new
// contracts if the number of contracts dips below 90% of the required
// contracts
//
// NOTE: updating this value indirectly affects 'maxKeepLeeway'
leewayPctRequiredContracts = 0.9
// maxInitialContractFundingDivisor and minInitialContractFundingDivisor
// define a range we use when calculating the initial contract funding
maxInitialContractFundingDivisor = uint64(10)
minInitialContractFundingDivisor = uint64(20)
// minAllowedScoreLeeway is a factor by which a host can be under the lowest
// score found in a random sample of scores before being considered not
// usable.
minAllowedScoreLeeway = 500
// targetBlockTime is the average block time of the Sia network
targetBlockTime = 10 * time.Minute
// timeoutHostPriceTable is the amount of time we wait to receive a price
// table from the host
timeoutHostPriceTable = 30 * time.Second
// timeoutHostRevision is the amount of time we wait to receive the latest
// revision from the host. This is set to 4 minutes since siad currently
// blocks for 3 minutes when trying to fetch a revision and not having
// enough funds in the account used for fetching it. That way we are
// guaranteed to receive the host's ErrBalanceInsufficient.
// TODO: This can be lowered once the network uses hostd.
timeoutHostRevision = 4 * time.Minute
// timeoutHostScan is the amount of time we wait for a host scan to be
// completed
timeoutHostScan = 30 * time.Second
// timeoutBroadcastRevision is the amount of time we wait for the broadcast
// of a revision to succeed.
timeoutBroadcastRevision = time.Minute
// timeoutPruneContract is the amount of time we wait for a contract to get
// pruned.
timeoutPruneContract = 10 * time.Minute
)
type (
contractor struct {
ap *Autopilot
churn *accumulatedChurn
resolver *ipResolver
logger *zap.SugaredLogger
maintenanceTxnIDs []types.TransactionID
revisionBroadcastInterval time.Duration
revisionLastBroadcast map[types.FileContractID]time.Time
revisionSubmissionBuffer uint64
firstRefreshFailure map[types.FileContractID]time.Time
mu sync.Mutex
pruning bool
pruningLastStart time.Time
cachedHostInfo map[types.PublicKey]hostInfo
cachedDataStored map[types.PublicKey]uint64
cachedMinScore float64
}
hostInfo struct {
Usable bool
UnusableResult unusableHostResult
}
scoredHost struct {
host hostdb.Host
score float64
}
contractInfo struct {
contract api.Contract
settings rhpv2.HostSettings
priceTable rhpv3.HostPriceTable
usable bool
recoverable bool
}
contractSetAdditions struct {
HostKey types.PublicKey `json:"hostKey"`
Additions []contractSetAddition `json:"additions"`
}
contractSetAddition struct {
Size uint64 `json:"size"`
Time api.TimeRFC3339 `json:"time"`
}
contractSetRemovals struct {
HostKey types.PublicKey `json:"hostKey"`
Removals []contractSetRemoval `json:"removals"`
}
contractSetRemoval struct {
Size uint64 `json:"size"`
Reason string `json:"reasons"`
Time api.TimeRFC3339 `json:"time"`
}
renewal struct {
from api.ContractMetadata
to api.ContractMetadata
ci contractInfo
}
)
func newContractor(ap *Autopilot, revisionSubmissionBuffer uint64, revisionBroadcastInterval time.Duration) *contractor {
return &contractor{
ap: ap,
churn: newAccumulatedChurn(),
logger: ap.logger.Named("contractor"),
revisionBroadcastInterval: revisionBroadcastInterval,
revisionLastBroadcast: make(map[types.FileContractID]time.Time),
revisionSubmissionBuffer: revisionSubmissionBuffer,
firstRefreshFailure: make(map[types.FileContractID]time.Time),
resolver: newIPResolver(ap.shutdownCtx, resolverLookupTimeout, ap.logger.Named("resolver")),
}
}
func (c *contractor) Status() (bool, time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
return c.pruning, c.pruningLastStart
}
func (c *contractor) performContractMaintenance(ctx context.Context, w Worker) (bool, error) {
// skip contract maintenance if we're stopped or not synced
if c.ap.isStopped() {
return false, nil
}
c.logger.Info("performing contract maintenance")
// convenience variables
state := c.ap.State()
// no maintenance if no hosts are requested
//
// NOTE: this is an important check because we assume Contracts.Amount is
// not zero in several places
if state.cfg.Contracts.Amount == 0 {
c.logger.Warn("contracts is set to zero, skipping contract maintenance")
return false, nil
}
// no maintenance if no allowance was set
if state.cfg.Contracts.Allowance.IsZero() {
c.logger.Warn("allowance is set to zero, skipping contract maintenance")
return false, nil
}
// no maintenance if no period was set
if state.cfg.Contracts.Period == 0 {
c.logger.Warn("period is set to zero, skipping contract maintenance")
return false, nil
}
// fetch current contract set
currentSet, err := c.ap.bus.Contracts(ctx, api.ContractsOpts{ContractSet: state.cfg.Contracts.Set})
if err != nil && !strings.Contains(err.Error(), api.ErrContractSetNotFound.Error()) {
return false, err
}
isInCurrentSet := make(map[types.FileContractID]struct{})
for _, c := range currentSet {
isInCurrentSet[c.ID] = struct{}{}
}
c.logger.Infof("contract set '%s' holds %d contracts", state.cfg.Contracts.Set, len(currentSet))
// fetch all contracts from the worker.
start := time.Now()
resp, err := w.Contracts(ctx, timeoutHostRevision)
if err != nil {
return false, err
}
if resp.Error != "" {
c.logger.Error(resp.Error)
}
contracts := resp.Contracts
c.logger.Infof("fetched %d contracts from the worker, took %v", len(resp.Contracts), time.Since(start))
// prune contract refresh failure map
c.pruneContractRefreshFailures(contracts)
// run revision broadcast
c.runRevisionBroadcast(ctx, w, contracts, isInCurrentSet)
// sort contracts by their size
sort.Slice(contracts, func(i, j int) bool {
return contracts[i].FileSize() > contracts[j].FileSize()
})
// get used hosts
usedHosts := make(map[types.PublicKey]struct{})
for _, contract := range contracts {
usedHosts[contract.HostKey] = struct{}{}
}
// compile map of stored data per host
contractData := make(map[types.FileContractID]uint64)
hostData := make(map[types.PublicKey]uint64)
for _, c := range contracts {
contractData[c.ID] = c.FileSize()
hostData[c.HostKey] += c.FileSize()
}
// fetch all hosts
hosts, err := c.ap.bus.SearchHosts(ctx, api.SearchHostOptions{Limit: -1, FilterMode: api.HostFilterModeAllowed})
if err != nil {
return false, err
}
// check if any used hosts have lost data to warn the user
var toDismiss []types.Hash256
for _, h := range hosts {
if h.Interactions.LostSectors > 0 {
c.ap.RegisterAlert(ctx, newLostSectorsAlert(h.PublicKey, h.Interactions.LostSectors))
} else {
toDismiss = append(toDismiss, alertIDForHost(alertLostSectorsID, h.PublicKey))
}
}
if len(toDismiss) > 0 {
c.ap.DismissAlert(ctx, toDismiss...)
}
// fetch candidate hosts
candidates, unusableHosts, err := c.candidateHosts(ctx, hosts, usedHosts, hostData, smallestValidScore) // avoid 0 score hosts
if err != nil {
return false, err
}
// min score to pass checks
var minScore float64
if len(hosts) > 0 {
minScore = c.calculateMinScore(candidates, state.cfg.Contracts.Amount)
} else {
c.logger.Warn("could not calculate min score, no hosts found")
}
// fetch consensus state
cs, err := c.ap.bus.ConsensusState(ctx)
if err != nil {
return false, err
}
// create gouging checker
gc := worker.NewGougingChecker(state.gs, cs, state.fee, state.cfg.Contracts.Period, state.cfg.Contracts.RenewWindow)
// prepare hosts for cache
hostInfos := make(map[types.PublicKey]hostInfo)
for _, h := range hosts {
// ignore the pricetable's HostBlockHeight by setting it to our own blockheight
h.PriceTable.HostBlockHeight = cs.BlockHeight
isUsable, unusableResult := isUsableHost(state.cfg, state.rs, gc, h, minScore, hostData[h.PublicKey])
hostInfos[h.PublicKey] = hostInfo{
Usable: isUsable,
UnusableResult: unusableResult,
}
}
// update cache.
c.mu.Lock()
c.cachedHostInfo = hostInfos
c.cachedDataStored = hostData
c.cachedMinScore = minScore
c.mu.Unlock()
// run checks
updatedSet, toArchive, toStopUsing, toRefresh, toRenew, err := c.runContractChecks(ctx, w, contracts, isInCurrentSet, minScore)
if err != nil {
return false, fmt.Errorf("failed to run contract checks, err: %v", err)
}
// archive contracts
if len(toArchive) > 0 {
c.logger.Infof("archiving %d contracts: %+v", len(toArchive), toArchive)
if err := c.ap.bus.ArchiveContracts(ctx, toArchive); err != nil {
c.logger.Errorf("failed to archive contracts, err: %v", err) // continue
}
}
// calculate remaining funds
remaining := c.remainingFunds(contracts)
// calculate 'limit' amount of contracts we want to renew
var limit int
if len(toRenew) > 0 {
// when renewing, prioritise contracts that have already been in the set
// before and out of those prefer the largest ones.
sort.Slice(toRenew, func(i, j int) bool {
_, icsI := isInCurrentSet[toRenew[i].contract.ID]
_, icsJ := isInCurrentSet[toRenew[j].contract.ID]
if icsI && !icsJ {
return true
} else if !icsI && icsJ {
return false
}
return toRenew[i].contract.FileSize() > toRenew[j].contract.FileSize()
})
for len(updatedSet)+limit < int(state.cfg.Contracts.Amount) && limit < len(toRenew) {
// as long as we're missing contracts, increase the renewal limit
limit++
}
}
// run renewals on contracts that are not in updatedSet yet. We only renew
// up to 'limit' of those to avoid having too many contracts in the updated
// set afterwards
var renewed []renewal
if limit > 0 {
var toKeep []api.ContractMetadata
renewed, toKeep = c.runContractRenewals(ctx, w, toRenew, &remaining, limit)
for _, ri := range renewed {
if ri.ci.usable || ri.ci.recoverable {
updatedSet = append(updatedSet, ri.to)
}
contractData[ri.to.ID] = contractData[ri.from.ID]
}
updatedSet = append(updatedSet, toKeep...)
}
// run contract refreshes
refreshed, err := c.runContractRefreshes(ctx, w, toRefresh, &remaining)
if err != nil {
c.logger.Errorf("failed to refresh contracts, err: %v", err) // continue
} else {
for _, ri := range refreshed {
if ri.ci.usable || ri.ci.recoverable {
updatedSet = append(updatedSet, ri.to)
}
contractData[ri.to.ID] = contractData[ri.from.ID]
}
}
// to avoid forming new contracts as soon as we dip below
// 'Contracts.Amount', we define a threshold but only if we have more
// contracts than 'Contracts.Amount' already
threshold := state.cfg.Contracts.Amount
if uint64(len(contracts)) > state.cfg.Contracts.Amount {
threshold = addLeeway(threshold, leewayPctRequiredContracts)
}
// check if we need to form contracts and add them to the contract set
var formed []api.ContractMetadata
if uint64(len(updatedSet)) < threshold {
// no need to try and form contracts if wallet is completely empty
wallet, err := c.ap.bus.Wallet(ctx)
if err != nil {
c.logger.Errorf("failed to fetch wallet, err: %v", err)
return false, err
} else if wallet.Confirmed.IsZero() && wallet.Unconfirmed.IsZero() {
c.logger.Warn("contract formations skipped, wallet is empty")
} else {
formed, err = c.runContractFormations(ctx, w, candidates, usedHosts, unusableHosts, state.cfg.Contracts.Amount-uint64(len(updatedSet)), &remaining)
if err != nil {
c.logger.Errorf("failed to form contracts, err: %v", err) // continue
} else {
for _, fc := range formed {
updatedSet = append(updatedSet, fc)
contractData[fc.ID] = 0
}
}
}
}
// cap the amount of contracts we want to keep to the configured amount
for _, contract := range updatedSet {
if _, exists := contractData[contract.ID]; !exists {
c.logger.Errorf("contract %v not found in contractData", contract.ID)
}
}
if len(updatedSet) > int(state.cfg.Contracts.Amount) {
// sort by contract size
sort.Slice(updatedSet, func(i, j int) bool {
return contractData[updatedSet[i].ID] > contractData[updatedSet[j].ID]
})
for _, contract := range updatedSet[state.cfg.Contracts.Amount:] {
toStopUsing[contract.ID] = "truncated"
}
updatedSet = updatedSet[:state.cfg.Contracts.Amount]
}
// convert to set of file contract ids
var newSet []types.FileContractID
for _, contract := range updatedSet {
newSet = append(newSet, contract.ID)
}
// update contract set
if c.ap.isStopped() {
return false, errors.New("autopilot stopped before maintenance could be completed")
}
err = c.ap.bus.SetContractSet(ctx, state.cfg.Contracts.Set, newSet)
if err != nil {
return false, err
}
// return whether the maintenance changed the contract set
return c.computeContractSetChanged(ctx, state.cfg.Contracts.Set, currentSet, updatedSet, formed, refreshed, renewed, toStopUsing, contractData), nil
}
func (c *contractor) computeContractSetChanged(ctx context.Context, name string, oldSet, newSet []api.ContractMetadata, formed []api.ContractMetadata, refreshed, renewed []renewal, toStopUsing map[types.FileContractID]string, contractData map[types.FileContractID]uint64) bool {
// build set lookups
inOldSet := make(map[types.FileContractID]struct{})
for _, c := range oldSet {
inOldSet[c.ID] = struct{}{}
}
inNewSet := make(map[types.FileContractID]struct{})
for _, c := range newSet {
inNewSet[c.ID] = struct{}{}
}
// build renewal lookups
renewalsFromTo := make(map[types.FileContractID]types.FileContractID)
renewalsToFrom := make(map[types.FileContractID]types.FileContractID)
for _, c := range append(refreshed, renewed...) {
renewalsFromTo[c.from.ID] = c.to.ID
renewalsToFrom[c.to.ID] = c.from.ID
}
// log added and removed contracts
setAdditions := make(map[types.FileContractID]contractSetAdditions)
setRemovals := make(map[types.FileContractID]contractSetRemovals)
now := api.TimeNow()
for _, contract := range oldSet {
_, exists := inNewSet[contract.ID]
_, renewed := inNewSet[renewalsFromTo[contract.ID]]
if !exists && !renewed {
reason, ok := toStopUsing[contract.ID]
if !ok {
reason = "unknown"
}
if _, exists := setRemovals[contract.ID]; !exists {
setRemovals[contract.ID] = contractSetRemovals{
HostKey: contract.HostKey,
}
}
removals := setRemovals[contract.ID]
removals.Removals = append(removals.Removals, contractSetRemoval{
Size: contractData[contract.ID],
Reason: reason,
Time: now,
})
setRemovals[contract.ID] = removals
c.logger.Infof("contract %v was removed from the contract set, size: %v, reason: %v", contract.ID, contractData[contract.ID], reason)
}
}
for _, contract := range newSet {
_, existed := inOldSet[contract.ID]
_, renewed := renewalsToFrom[contract.ID]
if !existed && !renewed {
if _, exists := setAdditions[contract.ID]; !exists {
setAdditions[contract.ID] = contractSetAdditions{
HostKey: contract.HostKey,
}
}
additions := setAdditions[contract.ID]
additions.Additions = append(additions.Additions, contractSetAddition{
Size: contractData[contract.ID],
Time: now,
})
setAdditions[contract.ID] = additions
c.logger.Infof("contract %v was added to the contract set, size: %v", contract.ID, contractData[contract.ID])
}
}
// log renewed contracts that did not make it into the contract set
for _, fcid := range renewed {
_, exists := inNewSet[fcid.to.ID]
if !exists {
c.logger.Infof("contract %v was renewed but did not make it into the contract set, size: %v", fcid, contractData[fcid.to.ID])
}
}
// log a warning if the contract set does not contain enough contracts
logFn := c.logger.Infow
if len(newSet) < int(c.ap.State().rs.TotalShards) {
logFn = c.logger.Warnw
}
// record churn metrics
var metrics []api.ContractSetChurnMetric
for fcid := range setAdditions {
metrics = append(metrics, api.ContractSetChurnMetric{
Name: c.ap.state.cfg.Contracts.Set,
ContractID: fcid,
Direction: api.ChurnDirAdded,
Timestamp: now,
})
}
for fcid, removal := range setRemovals {
metrics = append(metrics, api.ContractSetChurnMetric{
Name: c.ap.state.cfg.Contracts.Set,
ContractID: fcid,
Direction: api.ChurnDirRemoved,
Reason: removal.Removals[0].Reason,
Timestamp: now,
})
}
if len(metrics) > 0 {
if err := c.ap.bus.RecordContractSetChurnMetric(ctx, metrics...); err != nil {
c.logger.Error("failed to record contract set churn metric:", err)
}
}
// log the contract set after maintenance
logFn(
"contractset after maintenance",
"formed", len(formed),
"renewed", len(renewed),
"refreshed", len(refreshed),
"contracts", len(newSet),
"added", len(setAdditions),
"removed", len(setRemovals),
)
hasChanged := len(setAdditions)+len(setRemovals) > 0
if hasChanged {
if !c.ap.HasAlert(ctx, alertChurnID) {
c.churn.Reset()
}
c.churn.Apply(setAdditions, setRemovals)
c.ap.RegisterAlert(ctx, c.churn.Alert(name))
}
return hasChanged
}
func (c *contractor) performWalletMaintenance(ctx context.Context) error {
if c.ap.isStopped() {
return nil // skip contract maintenance if we're not synced
}
c.logger.Info("performing wallet maintenance")
// convenience variables
b := c.ap.bus
l := c.logger
state := c.ap.State()
cfg := state.cfg
period := state.period
renewWindow := cfg.Contracts.RenewWindow
// no contracts - nothing to do
if cfg.Contracts.Amount == 0 {
l.Warn("wallet maintenance skipped, no contracts wanted")
return nil
}
// no allowance - nothing to do
if cfg.Contracts.Allowance.IsZero() {
l.Warn("wallet maintenance skipped, no allowance set")
return nil
}
// fetch consensus state
cs, err := c.ap.bus.ConsensusState(ctx)
if err != nil {
l.Warnf("wallet maintenance skipped, fetching consensus state failed with err: %v", err)
return err
}
// fetch wallet balance
wallet, err := b.Wallet(ctx)
if err != nil {
l.Warnf("wallet maintenance skipped, fetching wallet balance failed with err: %v", err)
return err
}
balance := wallet.Confirmed
// register an alert if balance is low
if balance.Cmp(cfg.Contracts.Allowance) < 0 {
c.ap.RegisterAlert(ctx, newAccountLowBalanceAlert(state.address, balance, cfg.Contracts.Allowance, cs.BlockHeight, renewWindow, endHeight(cfg, period)))
} else {
c.ap.DismissAlert(ctx, alertLowBalanceID)
}
// pending maintenance transaction - nothing to do
pending, err := b.WalletPending(ctx)
if err != nil {
return nil
}
for _, txn := range pending {
for _, mTxnID := range c.maintenanceTxnIDs {
if mTxnID == txn.ID() {
l.Infof("wallet maintenance skipped, pending transaction found with id %v", mTxnID)
return nil
}
}
}
wantedNumOutputs := 10
// enough outputs - nothing to do
available, err := b.WalletOutputs(ctx)
if err != nil {
return err
}
if uint64(len(available)) >= uint64(wantedNumOutputs) {
l.Infof("no wallet maintenance needed, plenty of outputs available (%v>=%v)", len(available), uint64(wantedNumOutputs))
return nil
}
wantedNumOutputs -= len(available)
// figure out the amount per output
amount := cfg.Contracts.Allowance.Div64(uint64(wantedNumOutputs))
// redistribute outputs
ids, err := b.WalletRedistribute(ctx, wantedNumOutputs, amount)
if err != nil {
return fmt.Errorf("failed to redistribute wallet into %d outputs of amount %v, balance %v, err %v", wantedNumOutputs, amount, balance, err)
}
l.Infof("wallet maintenance succeeded, txns %v", ids)
c.maintenanceTxnIDs = ids
return nil
}
func (c *contractor) runContractChecks(ctx context.Context, w Worker, contracts []api.Contract, inCurrentSet map[types.FileContractID]struct{}, minScore float64) (toKeep []api.ContractMetadata, toArchive, toStopUsing map[types.FileContractID]string, toRefresh, toRenew []contractInfo, _ error) {
if c.ap.isStopped() {
return
}
c.logger.Info("running contract checks")
// convenience variables
state := c.ap.State()
// fetch consensus state
cs, err := c.ap.bus.ConsensusState(ctx)
if err != nil {
return nil, nil, nil, nil, nil, err
}
// create new IP filter
ipFilter := c.newIPFilter()
// calculate 'maxKeepLeeway' which defines the amount of contracts we'll be
// lenient towards when we fail to either fetch a valid price table or the
// contract's revision
maxKeepLeeway := addLeeway(state.cfg.Contracts.Amount, 1-leewayPctRequiredContracts)
remainingKeepLeeway := maxKeepLeeway
var notfound int
defer func() {
c.logger.Infow(
"contracts checks completed",
"contracts", len(contracts),
"notfound", notfound,
"usedKeepLeeway", maxKeepLeeway-remainingKeepLeeway,
"toKeep", len(toKeep),
"toArchive", len(toArchive),
"toRefresh", len(toRefresh),
"toRenew", len(toRenew),
)
}()
// return variables
toArchive = make(map[types.FileContractID]string)
toStopUsing = make(map[types.FileContractID]string)
// when checking the contracts, do so from largest to smallest. That way, we
// prefer larger hosts on redundant networks.
contracts = append([]api.Contract{}, contracts...)
sort.Slice(contracts, func(i, j int) bool {
return contracts[i].FileSize() > contracts[j].FileSize()
})
// check all contracts
for _, contract := range contracts {
// break if autopilot is stopped
if c.ap.isStopped() {
break
}
// convenience variables
fcid := contract.ID
// check if contract is ready to be archived.
if cs.BlockHeight > contract.EndHeight()-c.revisionSubmissionBuffer {
toArchive[fcid] = errContractExpired.Error()
} else if contract.Revision != nil && contract.Revision.RevisionNumber == math.MaxUint64 {
toArchive[fcid] = errContractMaxRevisionNumber.Error()
} else if contract.RevisionNumber == math.MaxUint64 {
toArchive[fcid] = errContractMaxRevisionNumber.Error()
} else if contract.State == api.ContractStatePending && cs.BlockHeight-contract.StartHeight > contractConfirmationDeadline {
toArchive[fcid] = errContractNotConfirmed.Error()
}
if _, archived := toArchive[fcid]; archived {
toStopUsing[fcid] = toArchive[fcid]
continue
}
// fetch host from hostdb
hk := contract.HostKey
host, err := c.ap.bus.Host(ctx, hk)
if err != nil {
c.logger.Errorw(fmt.Sprintf("missing host, err: %v", err), "hk", hk)
toStopUsing[fcid] = errHostNotFound.Error()
notfound++
continue
}
// if the host is blocked we ignore it, it might be unblocked later
if host.Blocked {
c.logger.Infow("unusable host", "hk", hk, "fcid", fcid, "reasons", errHostBlocked.Error())
toStopUsing[fcid] = errHostBlocked.Error()
continue
}
// if the host doesn't have a valid pricetable, update it if we were
// able to obtain a revision
invalidPT := contract.Revision == nil
if contract.Revision != nil {
if err := refreshPriceTable(ctx, w, &host.Host); err != nil {
c.logger.Errorf("could not fetch price table for host %v: %v", host.PublicKey, err)
invalidPT = true
}
}
// refresh the consensus state
if css, err := c.ap.bus.ConsensusState(ctx); err != nil {
c.logger.Errorf("could not fetch consensus state, err: %v", err)
} else {
cs = css
}
// use a new gouging checker for every contract
gc := worker.NewGougingChecker(state.gs, cs, state.fee, state.cfg.Contracts.Period, state.cfg.Contracts.RenewWindow)
// set the host's block height to ours to disable the height check in
// the gouging checks, in certain edge cases the renter might unsync and
// would therefor label all hosts as unusable and go on to create a
// whole new set of contracts with new hosts
host.PriceTable.HostBlockHeight = cs.BlockHeight
// decide whether the host is still good
usable, unusableResult := isUsableHost(state.cfg, state.rs, gc, host, minScore, contract.FileSize())
if !usable {
reasons := unusableResult.reasons()
toStopUsing[fcid] = strings.Join(reasons, ",")
c.logger.Infow("unusable host", "hk", hk, "fcid", fcid, "reasons", reasons)
continue
}
// if we were not able to the contract's revision, we can't properly
// perform the checks that follow, however we do want to be lenient if
// this contract is in the current set and we still have leeway left
if contract.Revision == nil {
if _, found := inCurrentSet[fcid]; !found || remainingKeepLeeway == 0 {
toStopUsing[fcid] = errContractNoRevision.Error()
} else if !state.cfg.Hosts.AllowRedundantIPs && ipFilter.IsRedundantIP(contract.HostIP, contract.HostKey) {
toStopUsing[fcid] = fmt.Sprintf("%v; %v", errHostRedundantIP, errContractNoRevision)
} else {
toKeep = append(toKeep, contract.ContractMetadata)
remainingKeepLeeway-- // we let it slide
}
continue // can't perform contract checks without revision
}
// if we were not able to get a valid price table for the host, but we
// did pass the host checks, we only want to be lenient if this contract
// is in the current set and only for a certain number of times,
// controlled by maxKeepLeeway
if invalidPT {
if _, found := inCurrentSet[fcid]; !found || remainingKeepLeeway == 0 {
toStopUsing[fcid] = "no valid price table"
continue
}
remainingKeepLeeway-- // we let it slide
}
// decide whether the contract is still good
ci := contractInfo{contract: contract, priceTable: host.PriceTable.HostPriceTable, settings: host.Settings}
usable, recoverable, refresh, renew, reasons := c.isUsableContract(state.cfg, state, ci, cs.BlockHeight, ipFilter)
ci.usable = usable
ci.recoverable = recoverable
if !usable {
c.logger.Infow(
"unusable contract",
"hk", hk,
"fcid", fcid,
"reasons", reasons,
"refresh", refresh,
"renew", renew,
"recoverable", recoverable,
)
}
if len(reasons) > 0 {
toStopUsing[fcid] = strings.Join(reasons, ",")
}
if renew {
toRenew = append(toRenew, ci)
} else if refresh {
toRefresh = append(toRefresh, ci)
} else if usable {
toKeep = append(toKeep, ci.contract.ContractMetadata)
}
}
return toKeep, toArchive, toStopUsing, toRefresh, toRenew, nil
}
func (c *contractor) runContractFormations(ctx context.Context, w Worker, candidates scoredHosts, usedHosts map[types.PublicKey]struct{}, unusableHosts unusableHostResult, missing uint64, budget *types.Currency) (formed []api.ContractMetadata, _ error) {
if c.ap.isStopped() {
return nil, nil
}
// convenience variables
state := c.ap.State()
shouldFilter := !state.cfg.Hosts.AllowRedundantIPs
c.logger.Infow(
"run contract formations",
"usedHosts", len(usedHosts),
"required", state.cfg.Contracts.Amount,
"missing", missing,
"budget", budget,
)
defer func() {
c.logger.Infow(
"contract formations completed",
"formed", len(formed),
"budget", budget,
)
}()
// select candidates
wanted := int(addLeeway(missing, leewayPctCandidateHosts))
selected := candidates.randSelectByScore(wanted)
// print warning if we couldn't find enough hosts were found
c.logger.Infof("looking for %d candidate hosts", wanted)
if len(selected) < wanted {
msg := "no candidate hosts found"
if len(selected) > 0 {
msg = fmt.Sprintf("only found %d candidate host(s) out of the %d we wanted", len(selected), wanted)
}
if len(candidates) >= wanted {
c.logger.Warnw(msg, unusableHosts.keysAndValues()...)
} else {
c.logger.Infow(msg, unusableHosts.keysAndValues()...)
}
}
// fetch consensus state
cs, err := c.ap.bus.ConsensusState(ctx)
if err != nil {
return nil, err
}
lastStateUpdate := time.Now()
// prepare a gouging checker
gc := worker.NewGougingChecker(state.gs, cs, state.fee, state.cfg.Contracts.Period, state.cfg.Contracts.RenewWindow)
// prepare an IP filter that contains all used hosts
ipFilter := c.newIPFilter()
if shouldFilter {
for _, h := range candidates {
if _, used := usedHosts[h.host.PublicKey]; used {
_ = ipFilter.IsRedundantIP(h.host.NetAddress, h.host.PublicKey)
}
}
}
// calculate min/max contract funds
minInitialContractFunds, maxInitialContractFunds := initialContractFundingMinMax(state.cfg)
for h := 0; missing > 0 && h < len(selected); h++ {
host := selected[h].host
// break if the autopilot is stopped
if c.ap.isStopped() {
break
}
// fetch a new price table if necessary
if err := refreshPriceTable(ctx, w, &host); err != nil {
c.logger.Errorf("failed to fetch price table for candidate host %v: %v", host.PublicKey, err)
continue
}
// fetch a new consensus state if necessary, we have to do this
// frequently to ensure we're not performing gouging checks with old
// consensus state
if time.Since(lastStateUpdate) > time.Minute {
if css, err := c.ap.bus.ConsensusState(ctx); err != nil {
c.logger.Errorf("could not fetch consensus state, err: %v", err)
} else {
cs = css
gc = worker.NewGougingChecker(state.gs, cs, state.fee, state.cfg.Contracts.Period, state.cfg.Contracts.RenewWindow)
}
}
// perform gouging checks on the fly to ensure the host is not gouging its prices
if breakdown := gc.Check(nil, &host.PriceTable.HostPriceTable); breakdown.Gouging() {
c.logger.Errorw("candidate host became unusable", "hk", host.PublicKey, "reasons", breakdown.String())
continue
}
// check if we already have a contract with a host on that subnet
if shouldFilter && ipFilter.IsRedundantIP(host.NetAddress, host.PublicKey) {
continue
}
formedContract, proceed, err := c.formContract(ctx, w, host, minInitialContractFunds, maxInitialContractFunds, budget)
if err == nil {
// add contract to contract set
formed = append(formed, formedContract)
missing--
}
if !proceed {
break
}
}
return formed, nil
}
// runRevisionBroadcast broadcasts contract revisions from the current set of
// contracts. Since we are migrating away from all contracts not in the set and
// are not uploading to those contracts anyway, we only worry about contracts in
// the set.
func (c *contractor) runRevisionBroadcast(ctx context.Context, w Worker, allContracts []api.Contract, isInSet map[types.FileContractID]struct{}) {
if c.revisionBroadcastInterval == 0 {
return // not enabled
}
cs, err := c.ap.bus.ConsensusState(ctx)
if err != nil {
c.logger.Warnf("revision broadcast failed to fetch blockHeight: %v", err)
return
}
bh := cs.BlockHeight
successful, failed := 0, 0
for _, contract := range allContracts {
// check whether broadcasting is necessary
timeSinceRevisionHeight := targetBlockTime * time.Duration(bh-contract.RevisionHeight)
timeSinceLastTry := time.Since(c.revisionLastBroadcast[contract.ID])
_, inSet := isInSet[contract.ID]
if !inSet || contract.RevisionHeight == math.MaxUint64 || timeSinceRevisionHeight < c.revisionBroadcastInterval || timeSinceLastTry < c.revisionBroadcastInterval/broadcastRevisionRetriesPerInterval {
continue // nothing to do
}
// remember that we tried to broadcast this contract now