/
bus.go
2424 lines (2177 loc) · 77.1 KB
/
bus.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 bus
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"runtime"
"sort"
"strings"
"time"
"go.sia.tech/core/consensus"
rhpv2 "go.sia.tech/core/rhp/v2"
rhpv3 "go.sia.tech/core/rhp/v3"
"go.sia.tech/core/types"
"go.sia.tech/gofakes3"
"go.sia.tech/jape"
"go.sia.tech/renterd/alerts"
"go.sia.tech/renterd/api"
"go.sia.tech/renterd/build"
"go.sia.tech/renterd/bus/client"
"go.sia.tech/renterd/hostdb"
"go.sia.tech/renterd/object"
"go.sia.tech/renterd/wallet"
"go.sia.tech/renterd/webhooks"
"go.sia.tech/siad/modules"
"go.uber.org/zap"
)
// Client re-exports the client from the client package.
type Client struct {
*client.Client
}
// NewClient returns a new bus client.
func NewClient(addr, password string) *Client {
return &Client{
client.New(
addr,
password,
),
}
}
type (
// A ChainManager manages blockchain state.
ChainManager interface {
AcceptBlock(types.Block) error
BlockAtHeight(height uint64) (types.Block, bool)
IndexAtHeight(height uint64) (types.ChainIndex, error)
LastBlockTime() time.Time
Subscribe(s modules.ConsensusSetSubscriber, ccID modules.ConsensusChangeID, cancel <-chan struct{}) error
Synced() bool
TipState() consensus.State
}
// A Syncer can connect to other peers and synchronize the blockchain.
Syncer interface {
BroadcastTransaction(txn types.Transaction, dependsOn []types.Transaction)
Connect(addr string) error
Peers() []string
SyncerAddress(ctx context.Context) (string, error)
}
// A TransactionPool can validate and relay unconfirmed transactions.
TransactionPool interface {
AcceptTransactionSet(txns []types.Transaction) error
Close() error
RecommendedFee() types.Currency
Subscribe(subscriber modules.TransactionPoolSubscriber)
Transactions() []types.Transaction
UnconfirmedParents(txn types.Transaction) ([]types.Transaction, error)
}
// A Wallet can spend and receive siacoins.
Wallet interface {
Address() types.Address
Balance() (spendable, confirmed, unconfirmed types.Currency, _ error)
FundTransaction(cs consensus.State, txn *types.Transaction, amount types.Currency, useUnconfirmedTxns bool) ([]types.Hash256, error)
Height() uint64
Redistribute(cs consensus.State, outputs int, amount, feePerByte types.Currency, pool []types.Transaction) ([]types.Transaction, []types.Hash256, error)
ReleaseInputs(txn ...types.Transaction)
SignTransaction(cs consensus.State, txn *types.Transaction, toSign []types.Hash256, cf types.CoveredFields) error
Transactions(before, since time.Time, offset, limit int) ([]wallet.Transaction, error)
UnspentOutputs() ([]wallet.SiacoinElement, error)
}
// A HostDB stores information about hosts.
HostDB interface {
Host(ctx context.Context, hostKey types.PublicKey) (api.Host, error)
HostsForScanning(ctx context.Context, maxLastScan time.Time, offset, limit int) ([]hostdb.HostAddress, error)
RecordHostScans(ctx context.Context, scans []hostdb.HostScan) error
RecordPriceTables(ctx context.Context, priceTableUpdate []hostdb.PriceTableUpdate) error
RemoveOfflineHosts(ctx context.Context, minRecentScanFailures uint64, maxDowntime time.Duration) (uint64, error)
ResetLostSectors(ctx context.Context, hk types.PublicKey) error
SearchHosts(ctx context.Context, filterMode, addressContains string, keyIn []types.PublicKey, offset, limit int) ([]api.Host, error)
HostAllowlist(ctx context.Context) ([]types.PublicKey, error)
HostBlocklist(ctx context.Context) ([]string, error)
UpdateHostAllowlistEntries(ctx context.Context, add, remove []types.PublicKey, clear bool) error
UpdateHostBlocklistEntries(ctx context.Context, add, remove []string, clear bool) error
}
// A MetadataStore stores information about contracts and objects.
MetadataStore interface {
AddContract(ctx context.Context, c rhpv2.ContractRevision, contractPrice, totalCost types.Currency, startHeight uint64, state string) (api.ContractMetadata, error)
AddRenewedContract(ctx context.Context, c rhpv2.ContractRevision, contractPrice, totalCost types.Currency, startHeight uint64, renewedFrom types.FileContractID, state string) (api.ContractMetadata, error)
AncestorContracts(ctx context.Context, fcid types.FileContractID, minStartHeight uint64) ([]api.ArchivedContract, error)
ArchiveContract(ctx context.Context, id types.FileContractID, reason string) error
ArchiveContracts(ctx context.Context, toArchive map[types.FileContractID]string) error
ArchiveAllContracts(ctx context.Context, reason string) error
Contract(ctx context.Context, id types.FileContractID) (api.ContractMetadata, error)
Contracts(ctx context.Context, opts api.ContractsOpts) ([]api.ContractMetadata, error)
ContractSets(ctx context.Context) ([]string, error)
RecordContractSpending(ctx context.Context, records []api.ContractSpendingRecord) error
RemoveContractSet(ctx context.Context, name string) error
RenewedContract(ctx context.Context, renewedFrom types.FileContractID) (api.ContractMetadata, error)
SetContractSet(ctx context.Context, set string, contracts []types.FileContractID) error
ContractRoots(ctx context.Context, id types.FileContractID) ([]types.Hash256, error)
ContractSizes(ctx context.Context) (map[types.FileContractID]api.ContractSize, error)
ContractSize(ctx context.Context, id types.FileContractID) (api.ContractSize, error)
DeleteHostSector(ctx context.Context, hk types.PublicKey, root types.Hash256) (int, error)
Bucket(_ context.Context, bucketName string) (api.Bucket, error)
CreateBucket(_ context.Context, bucketName string, policy api.BucketPolicy) error
DeleteBucket(_ context.Context, bucketName string) error
ListBuckets(_ context.Context) ([]api.Bucket, error)
UpdateBucketPolicy(ctx context.Context, bucketName string, policy api.BucketPolicy) error
CopyObject(ctx context.Context, srcBucket, dstBucket, srcPath, dstPath, mimeType string, metadata api.ObjectUserMetadata) (api.ObjectMetadata, error)
ListObjects(ctx context.Context, bucketName, prefix, sortBy, sortDir, marker string, limit int) (api.ObjectsListResponse, error)
Object(ctx context.Context, bucketName, path string) (api.Object, error)
ObjectMetadata(ctx context.Context, bucketName, path string) (api.Object, error)
ObjectEntries(ctx context.Context, bucketName, path, prefix, sortBy, sortDir, marker string, offset, limit int) ([]api.ObjectMetadata, bool, error)
ObjectsBySlabKey(ctx context.Context, bucketName string, slabKey object.EncryptionKey) ([]api.ObjectMetadata, error)
ObjectsStats(ctx context.Context, opts api.ObjectsStatsOpts) (api.ObjectsStatsResponse, error)
RemoveObject(ctx context.Context, bucketName, path string) error
RemoveObjects(ctx context.Context, bucketName, prefix string) error
RenameObject(ctx context.Context, bucketName, from, to string, force bool) error
RenameObjects(ctx context.Context, bucketName, from, to string, force bool) error
SearchObjects(ctx context.Context, bucketName, substring string, offset, limit int) ([]api.ObjectMetadata, error)
UpdateObject(ctx context.Context, bucketName, path, contractSet, ETag, mimeType string, metadata api.ObjectUserMetadata, o object.Object) error
AbortMultipartUpload(ctx context.Context, bucketName, path string, uploadID string) (err error)
AddMultipartPart(ctx context.Context, bucketName, path, contractSet, eTag, uploadID string, partNumber int, slices []object.SlabSlice) (err error)
CompleteMultipartUpload(ctx context.Context, bucketName, path, uploadID string, parts []api.MultipartCompletedPart, opts api.CompleteMultipartOptions) (_ api.MultipartCompleteResponse, err error)
CreateMultipartUpload(ctx context.Context, bucketName, path string, ec object.EncryptionKey, mimeType string, metadata api.ObjectUserMetadata) (api.MultipartCreateResponse, error)
MultipartUpload(ctx context.Context, uploadID string) (resp api.MultipartUpload, _ error)
MultipartUploads(ctx context.Context, bucketName, prefix, keyMarker, uploadIDMarker string, maxUploads int) (resp api.MultipartListUploadsResponse, _ error)
MultipartUploadParts(ctx context.Context, bucketName, object string, uploadID string, marker int, limit int64) (resp api.MultipartListPartsResponse, _ error)
MarkPackedSlabsUploaded(ctx context.Context, slabs []api.UploadedPackedSlab) error
PackedSlabsForUpload(ctx context.Context, lockingDuration time.Duration, minShards, totalShards uint8, set string, limit int) ([]api.PackedSlab, error)
SlabBuffers(ctx context.Context) ([]api.SlabBuffer, error)
AddPartialSlab(ctx context.Context, data []byte, minShards, totalShards uint8, contractSet string) (slabs []object.SlabSlice, bufferSize int64, err error)
FetchPartialSlab(ctx context.Context, key object.EncryptionKey, offset, length uint32) ([]byte, error)
Slab(ctx context.Context, key object.EncryptionKey) (object.Slab, error)
RefreshHealth(ctx context.Context) error
UnhealthySlabs(ctx context.Context, healthCutoff float64, set string, limit int) ([]api.UnhealthySlab, error)
UpdateSlab(ctx context.Context, s object.Slab, contractSet string) error
}
// An AutopilotStore stores autopilots.
AutopilotStore interface {
Autopilot(ctx context.Context, id string) (api.Autopilot, error)
Autopilots(ctx context.Context) ([]api.Autopilot, error)
UpdateAutopilot(ctx context.Context, ap api.Autopilot) error
}
// A SettingStore stores settings.
SettingStore interface {
DeleteSetting(ctx context.Context, key string) error
Setting(ctx context.Context, key string) (string, error)
Settings(ctx context.Context) ([]string, error)
UpdateSetting(ctx context.Context, key, value string) error
}
// EphemeralAccountStore persists information about accounts. Since accounts
// are rapidly updated and can be recovered, they are only loaded upon
// startup and persisted upon shutdown.
EphemeralAccountStore interface {
Accounts(context.Context) ([]api.Account, error)
SaveAccounts(context.Context, []api.Account) error
SetUncleanShutdown(context.Context) error
}
MetricsStore interface {
ContractSetMetrics(ctx context.Context, start time.Time, n uint64, interval time.Duration, opts api.ContractSetMetricsQueryOpts) ([]api.ContractSetMetric, error)
ContractPruneMetrics(ctx context.Context, start time.Time, n uint64, interval time.Duration, opts api.ContractPruneMetricsQueryOpts) ([]api.ContractPruneMetric, error)
RecordContractPruneMetric(ctx context.Context, metrics ...api.ContractPruneMetric) error
ContractMetrics(ctx context.Context, start time.Time, n uint64, interval time.Duration, opts api.ContractMetricsQueryOpts) ([]api.ContractMetric, error)
RecordContractMetric(ctx context.Context, metrics ...api.ContractMetric) error
PruneMetrics(ctx context.Context, metric string, cutoff time.Time) error
ContractSetChurnMetrics(ctx context.Context, start time.Time, n uint64, interval time.Duration, opts api.ContractSetChurnMetricsQueryOpts) ([]api.ContractSetChurnMetric, error)
RecordContractSetChurnMetric(ctx context.Context, metrics ...api.ContractSetChurnMetric) error
WalletMetrics(ctx context.Context, start time.Time, n uint64, interval time.Duration, opts api.WalletMetricsQueryOpts) ([]api.WalletMetric, error)
}
)
type bus struct {
startTime time.Time
cm ChainManager
s Syncer
tp TransactionPool
as AutopilotStore
eas EphemeralAccountStore
hdb HostDB
ms MetadataStore
ss SettingStore
mtrcs MetricsStore
w Wallet
accounts *accounts
contractLocks *contractLocks
uploadingSectors *uploadingSectorsCache
alerts alerts.Alerter
alertMgr *alerts.Manager
hooks *webhooks.Manager
logger *zap.SugaredLogger
}
// Handler returns an HTTP handler that serves the bus API.
func (b *bus) Handler() http.Handler {
return jape.Mux(map[string]jape.Handler{
"GET /accounts": b.accountsHandlerGET,
"POST /account/:id": b.accountHandlerGET,
"POST /account/:id/add": b.accountsAddHandlerPOST,
"POST /account/:id/lock": b.accountsLockHandlerPOST,
"POST /account/:id/unlock": b.accountsUnlockHandlerPOST,
"POST /account/:id/update": b.accountsUpdateHandlerPOST,
"POST /account/:id/requiressync": b.accountsRequiresSyncHandlerPOST,
"POST /account/:id/resetdrift": b.accountsResetDriftHandlerPOST,
"GET /alerts": b.handleGETAlerts,
"POST /alerts/dismiss": b.handlePOSTAlertsDismiss,
"POST /alerts/register": b.handlePOSTAlertsRegister,
"GET /autopilots": b.autopilotsListHandlerGET,
"GET /autopilot/:id": b.autopilotsHandlerGET,
"PUT /autopilot/:id": b.autopilotsHandlerPUT,
"GET /buckets": b.bucketsHandlerGET,
"POST /buckets": b.bucketsHandlerPOST,
"PUT /bucket/:name/policy": b.bucketsHandlerPolicyPUT,
"DELETE /bucket/:name": b.bucketHandlerDELETE,
"GET /bucket/:name": b.bucketHandlerGET,
"POST /consensus/acceptblock": b.consensusAcceptBlock,
"GET /consensus/network": b.consensusNetworkHandler,
"GET /consensus/siafundfee/:payout": b.contractTaxHandlerGET,
"GET /consensus/state": b.consensusStateHandler,
"GET /contracts": b.contractsHandlerGET,
"DELETE /contracts/all": b.contractsAllHandlerDELETE,
"POST /contracts/archive": b.contractsArchiveHandlerPOST,
"GET /contracts/prunable": b.contractsPrunableDataHandlerGET,
"GET /contracts/renewed/:id": b.contractsRenewedIDHandlerGET,
"GET /contracts/sets": b.contractsSetsHandlerGET,
"PUT /contracts/set/:set": b.contractsSetHandlerPUT,
"DELETE /contracts/set/:set": b.contractsSetHandlerDELETE,
"POST /contracts/spending": b.contractsSpendingHandlerPOST,
"GET /contract/:id": b.contractIDHandlerGET,
"POST /contract/:id": b.contractIDHandlerPOST,
"DELETE /contract/:id": b.contractIDHandlerDELETE,
"POST /contract/:id/acquire": b.contractAcquireHandlerPOST,
"GET /contract/:id/ancestors": b.contractIDAncestorsHandler,
"POST /contract/:id/keepalive": b.contractKeepaliveHandlerPOST,
"POST /contract/:id/renewed": b.contractIDRenewedHandlerPOST,
"POST /contract/:id/release": b.contractReleaseHandlerPOST,
"GET /contract/:id/roots": b.contractIDRootsHandlerGET,
"GET /contract/:id/size": b.contractSizeHandlerGET,
"GET /hosts": b.hostsHandlerGETDeprecated,
"GET /hosts/allowlist": b.hostsAllowlistHandlerGET,
"PUT /hosts/allowlist": b.hostsAllowlistHandlerPUT,
"GET /hosts/blocklist": b.hostsBlocklistHandlerGET,
"PUT /hosts/blocklist": b.hostsBlocklistHandlerPUT,
"POST /hosts/pricetables": b.hostsPricetableHandlerPOST,
"POST /hosts/remove": b.hostsRemoveHandlerPOST,
"POST /hosts/scans": b.hostsScanHandlerPOST,
"GET /hosts/scanning": b.hostsScanningHandlerGET,
"GET /host/:hostkey": b.hostsPubkeyHandlerGET,
"POST /host/:hostkey/resetlostsectors": b.hostsResetLostSectorsPOST,
"PUT /metric/:key": b.metricsHandlerPUT,
"GET /metric/:key": b.metricsHandlerGET,
"DELETE /metric/:key": b.metricsHandlerDELETE,
"POST /multipart/create": b.multipartHandlerCreatePOST,
"POST /multipart/abort": b.multipartHandlerAbortPOST,
"POST /multipart/complete": b.multipartHandlerCompletePOST,
"PUT /multipart/part": b.multipartHandlerUploadPartPUT,
"GET /multipart/upload/:id": b.multipartHandlerUploadGET,
"POST /multipart/listuploads": b.multipartHandlerListUploadsPOST,
"POST /multipart/listparts": b.multipartHandlerListPartsPOST,
"GET /objects/*path": b.objectsHandlerGET,
"PUT /objects/*path": b.objectsHandlerPUT,
"DELETE /objects/*path": b.objectsHandlerDELETE,
"POST /objects/copy": b.objectsCopyHandlerPOST,
"POST /objects/rename": b.objectsRenameHandlerPOST,
"POST /objects/list": b.objectsListHandlerPOST,
"GET /params/gouging": b.paramsHandlerGougingGET,
"GET /params/upload": b.paramsHandlerUploadGET,
"GET /slabbuffers": b.slabbuffersHandlerGET,
"POST /slabbuffer/done": b.packedSlabsHandlerDonePOST,
"POST /slabbuffer/fetch": b.packedSlabsHandlerFetchPOST,
"POST /search/hosts": b.searchHostsHandlerPOST,
"GET /search/objects": b.searchObjectsHandlerGET,
"DELETE /sectors/:hk/:root": b.sectorsHostRootHandlerDELETE,
"GET /settings": b.settingsHandlerGET,
"GET /setting/:key": b.settingKeyHandlerGET,
"PUT /setting/:key": b.settingKeyHandlerPUT,
"DELETE /setting/:key": b.settingKeyHandlerDELETE,
"POST /slabs/migration": b.slabsMigrationHandlerPOST,
"GET /slabs/partial/:key": b.slabsPartialHandlerGET,
"POST /slabs/partial": b.slabsPartialHandlerPOST,
"POST /slabs/refreshhealth": b.slabsRefreshHealthHandlerPOST,
"GET /slab/:key": b.slabHandlerGET,
"GET /slab/:key/objects": b.slabObjectsHandlerGET,
"PUT /slab": b.slabHandlerPUT,
"GET /state": b.stateHandlerGET,
"GET /stats/objects": b.objectsStatshandlerGET,
"GET /syncer/address": b.syncerAddrHandler,
"POST /syncer/connect": b.syncerConnectHandler,
"GET /syncer/peers": b.syncerPeersHandler,
"GET /txpool/recommendedfee": b.txpoolFeeHandler,
"GET /txpool/transactions": b.txpoolTransactionsHandler,
"POST /txpool/broadcast": b.txpoolBroadcastHandler,
"POST /upload/:id": b.uploadTrackHandlerPOST,
"DELETE /upload/:id": b.uploadFinishedHandlerDELETE,
"POST /upload/:id/sector": b.uploadAddSectorHandlerPOST,
"GET /wallet": b.walletHandler,
"POST /wallet/discard": b.walletDiscardHandler,
"POST /wallet/fund": b.walletFundHandler,
"GET /wallet/outputs": b.walletOutputsHandler,
"GET /wallet/pending": b.walletPendingHandler,
"POST /wallet/prepare/form": b.walletPrepareFormHandler,
"POST /wallet/prepare/renew": b.walletPrepareRenewHandler,
"POST /wallet/redistribute": b.walletRedistributeHandler,
"POST /wallet/sign": b.walletSignHandler,
"GET /wallet/transactions": b.walletTransactionsHandler,
"GET /webhooks": b.webhookHandlerGet,
"POST /webhooks": b.webhookHandlerPost,
"POST /webhooks/action": b.webhookActionHandlerPost,
"POST /webhook/delete": b.webhookHandlerDelete,
})
}
// Shutdown shuts down the bus.
func (b *bus) Shutdown(ctx context.Context) error {
b.hooks.Close()
accounts := b.accounts.ToPersist()
err := b.eas.SaveAccounts(ctx, accounts)
if err != nil {
b.logger.Errorf("failed to save %v accounts: %v", len(accounts), err)
} else {
b.logger.Infof("successfully saved %v accounts", len(accounts))
}
return err
}
func (b *bus) fetchSetting(ctx context.Context, key string, value interface{}) error {
if val, err := b.ss.Setting(ctx, key); err != nil {
return fmt.Errorf("could not get contract set settings: %w", err)
} else if err := json.Unmarshal([]byte(val), &value); err != nil {
b.logger.Panicf("failed to unmarshal %v settings '%s': %v", key, val, err)
}
return nil
}
func (b *bus) consensusAcceptBlock(jc jape.Context) {
var block types.Block
if jc.Decode(&block) != nil {
return
}
if jc.Check("failed to accept block", b.cm.AcceptBlock(block)) != nil {
return
}
}
func (b *bus) syncerAddrHandler(jc jape.Context) {
addr, err := b.s.SyncerAddress(jc.Request.Context())
if jc.Check("failed to fetch syncer's address", err) != nil {
return
}
jc.Encode(addr)
}
func (b *bus) syncerPeersHandler(jc jape.Context) {
jc.Encode(b.s.Peers())
}
func (b *bus) syncerConnectHandler(jc jape.Context) {
var addr string
if jc.Decode(&addr) == nil {
jc.Check("couldn't connect to peer", b.s.Connect(addr))
}
}
func (b *bus) consensusStateHandler(jc jape.Context) {
jc.Encode(b.consensusState())
}
func (b *bus) consensusNetworkHandler(jc jape.Context) {
jc.Encode(api.ConsensusNetwork{
Name: b.cm.TipState().Network.Name,
})
}
func (b *bus) txpoolFeeHandler(jc jape.Context) {
fee := b.tp.RecommendedFee()
jc.Encode(fee)
}
func (b *bus) txpoolTransactionsHandler(jc jape.Context) {
jc.Encode(b.tp.Transactions())
}
func (b *bus) txpoolBroadcastHandler(jc jape.Context) {
var txnSet []types.Transaction
if jc.Decode(&txnSet) == nil {
jc.Check("couldn't broadcast transaction set", b.tp.AcceptTransactionSet(txnSet))
}
}
func (b *bus) bucketsHandlerGET(jc jape.Context) {
resp, err := b.ms.ListBuckets(jc.Request.Context())
if jc.Check("couldn't list buckets", err) != nil {
return
}
jc.Encode(resp)
}
func (b *bus) bucketsHandlerPOST(jc jape.Context) {
var bucket api.BucketCreateRequest
if jc.Decode(&bucket) != nil {
return
} else if bucket.Name == "" {
jc.Error(errors.New("no name provided"), http.StatusBadRequest)
return
} else if jc.Check("failed to create bucket", b.ms.CreateBucket(jc.Request.Context(), bucket.Name, bucket.Policy)) != nil {
return
}
}
func (b *bus) bucketsHandlerPolicyPUT(jc jape.Context) {
var req api.BucketUpdatePolicyRequest
if jc.Decode(&req) != nil {
return
} else if bucket := jc.PathParam("name"); bucket == "" {
jc.Error(errors.New("no bucket name provided"), http.StatusBadRequest)
return
} else if jc.Check("failed to create bucket", b.ms.UpdateBucketPolicy(jc.Request.Context(), bucket, req.Policy)) != nil {
return
}
}
func (b *bus) bucketHandlerDELETE(jc jape.Context) {
var name string
if jc.DecodeParam("name", &name) != nil {
return
} else if name == "" {
jc.Error(errors.New("no name provided"), http.StatusBadRequest)
return
} else if jc.Check("failed to delete bucket", b.ms.DeleteBucket(jc.Request.Context(), name)) != nil {
return
}
}
func (b *bus) bucketHandlerGET(jc jape.Context) {
var name string
if jc.DecodeParam("name", &name) != nil {
return
} else if name == "" {
jc.Error(errors.New("parameter 'name' is required"), http.StatusBadRequest)
return
}
bucket, err := b.ms.Bucket(jc.Request.Context(), name)
if errors.Is(err, api.ErrBucketNotFound) {
jc.Error(err, http.StatusNotFound)
return
} else if jc.Check("failed to fetch bucket", err) != nil {
return
}
jc.Encode(bucket)
}
func (b *bus) walletHandler(jc jape.Context) {
address := b.w.Address()
spendable, confirmed, unconfirmed, err := b.w.Balance()
if jc.Check("couldn't fetch wallet balance", err) != nil {
return
}
jc.Encode(api.WalletResponse{
ScanHeight: b.w.Height(),
Address: address,
Confirmed: confirmed,
Spendable: spendable,
Unconfirmed: unconfirmed,
})
}
func (b *bus) walletTransactionsHandler(jc jape.Context) {
var before, since time.Time
offset := 0
limit := -1
if jc.DecodeForm("before", (*api.TimeRFC3339)(&before)) != nil ||
jc.DecodeForm("since", (*api.TimeRFC3339)(&since)) != nil ||
jc.DecodeForm("offset", &offset) != nil ||
jc.DecodeForm("limit", &limit) != nil {
return
}
txns, err := b.w.Transactions(before, since, offset, limit)
if jc.Check("couldn't load transactions", err) == nil {
jc.Encode(txns)
}
}
func (b *bus) walletOutputsHandler(jc jape.Context) {
utxos, err := b.w.UnspentOutputs()
if jc.Check("couldn't load outputs", err) == nil {
jc.Encode(utxos)
}
}
func (b *bus) walletFundHandler(jc jape.Context) {
var wfr api.WalletFundRequest
if jc.Decode(&wfr) != nil {
return
}
txn := wfr.Transaction
if len(txn.MinerFees) == 0 {
// if no fees are specified, we add some
fee := b.tp.RecommendedFee().Mul64(b.cm.TipState().TransactionWeight(txn))
txn.MinerFees = []types.Currency{fee}
}
toSign, err := b.w.FundTransaction(b.cm.TipState(), &txn, wfr.Amount.Add(txn.MinerFees[0]), wfr.UseUnconfirmedTxns)
if jc.Check("couldn't fund transaction", err) != nil {
return
}
parents, err := b.tp.UnconfirmedParents(txn)
if jc.Check("couldn't load transaction dependencies", err) != nil {
b.w.ReleaseInputs(txn)
return
}
jc.Encode(api.WalletFundResponse{
Transaction: txn,
ToSign: toSign,
DependsOn: parents,
})
}
func (b *bus) walletSignHandler(jc jape.Context) {
var wsr api.WalletSignRequest
if jc.Decode(&wsr) != nil {
return
}
err := b.w.SignTransaction(b.cm.TipState(), &wsr.Transaction, wsr.ToSign, wsr.CoveredFields)
if jc.Check("couldn't sign transaction", err) == nil {
jc.Encode(wsr.Transaction)
}
}
func (b *bus) walletRedistributeHandler(jc jape.Context) {
var wfr api.WalletRedistributeRequest
if jc.Decode(&wfr) != nil {
return
}
if wfr.Outputs == 0 {
jc.Error(errors.New("'outputs' has to be greater than zero"), http.StatusBadRequest)
return
}
cs := b.cm.TipState()
txns, toSign, err := b.w.Redistribute(cs, wfr.Outputs, wfr.Amount, b.tp.RecommendedFee(), b.tp.Transactions())
if jc.Check("couldn't redistribute money in the wallet into the desired outputs", err) != nil {
return
}
var ids []types.TransactionID
if len(txns) == 0 {
jc.Encode(ids)
return
}
for i := 0; i < len(txns); i++ {
err = b.w.SignTransaction(cs, &txns[i], toSign, types.CoveredFields{WholeTransaction: true})
if jc.Check("couldn't sign the transaction", err) != nil {
b.w.ReleaseInputs(txns...)
return
}
ids = append(ids, txns[i].ID())
}
if jc.Check("couldn't broadcast the transaction", b.tp.AcceptTransactionSet(txns)) != nil {
b.w.ReleaseInputs(txns...)
return
}
jc.Encode(ids)
}
func (b *bus) walletDiscardHandler(jc jape.Context) {
var txn types.Transaction
if jc.Decode(&txn) == nil {
b.w.ReleaseInputs(txn)
}
}
func (b *bus) walletPrepareFormHandler(jc jape.Context) {
var wpfr api.WalletPrepareFormRequest
if jc.Decode(&wpfr) != nil {
return
}
if wpfr.HostKey == (types.PublicKey{}) {
jc.Error(errors.New("no host key provided"), http.StatusBadRequest)
return
}
if wpfr.RenterKey == (types.PublicKey{}) {
jc.Error(errors.New("no renter key provided"), http.StatusBadRequest)
return
}
cs := b.cm.TipState()
fc := rhpv2.PrepareContractFormation(wpfr.RenterKey, wpfr.HostKey, wpfr.RenterFunds, wpfr.HostCollateral, wpfr.EndHeight, wpfr.HostSettings, wpfr.RenterAddress)
cost := rhpv2.ContractFormationCost(cs, fc, wpfr.HostSettings.ContractPrice)
txn := types.Transaction{
FileContracts: []types.FileContract{fc},
}
txn.MinerFees = []types.Currency{b.tp.RecommendedFee().Mul64(cs.TransactionWeight(txn))}
toSign, err := b.w.FundTransaction(cs, &txn, cost.Add(txn.MinerFees[0]), true)
if jc.Check("couldn't fund transaction", err) != nil {
return
}
cf := wallet.ExplicitCoveredFields(txn)
err = b.w.SignTransaction(cs, &txn, toSign, cf)
if jc.Check("couldn't sign transaction", err) != nil {
b.w.ReleaseInputs(txn)
return
}
parents, err := b.tp.UnconfirmedParents(txn)
if jc.Check("couldn't load transaction dependencies", err) != nil {
b.w.ReleaseInputs(txn)
return
}
jc.Encode(append(parents, txn))
}
func (b *bus) walletPrepareRenewHandler(jc jape.Context) {
var wprr api.WalletPrepareRenewRequest
if jc.Decode(&wprr) != nil {
return
}
if wprr.RenterKey == nil {
jc.Error(errors.New("no renter key provided"), http.StatusBadRequest)
return
}
cs := b.cm.TipState()
// Create the final revision from the provided revision.
finalRevision := wprr.Revision
finalRevision.MissedProofOutputs = finalRevision.ValidProofOutputs
finalRevision.Filesize = 0
finalRevision.FileMerkleRoot = types.Hash256{}
finalRevision.RevisionNumber = math.MaxUint64
// Prepare the new contract.
fc, basePrice, err := rhpv3.PrepareContractRenewal(wprr.Revision, wprr.HostAddress, wprr.RenterAddress, wprr.RenterFunds, wprr.MinNewCollateral, wprr.PriceTable, wprr.ExpectedNewStorage, wprr.EndHeight)
if jc.Check("couldn't prepare contract renewal", err) != nil {
return
}
// Create the transaction containing both the final revision and new
// contract.
txn := types.Transaction{
FileContracts: []types.FileContract{fc},
FileContractRevisions: []types.FileContractRevision{finalRevision},
MinerFees: []types.Currency{wprr.PriceTable.TxnFeeMaxRecommended.Mul64(4096)},
}
// Compute how much renter funds to put into the new contract.
cost := rhpv3.ContractRenewalCost(cs, wprr.PriceTable, fc, txn.MinerFees[0], basePrice)
// Fund the txn. We are not signing it yet since it's not complete. The host
// still needs to complete it and the revision + contract are signed with
// the renter key by the worker.
toSign, err := b.w.FundTransaction(cs, &txn, cost, true)
if jc.Check("couldn't fund transaction", err) != nil {
return
}
// Add any required parents.
parents, err := b.tp.UnconfirmedParents(txn)
if jc.Check("couldn't load transaction dependencies", err) != nil {
b.w.ReleaseInputs(txn)
return
}
jc.Encode(api.WalletPrepareRenewResponse{
ToSign: toSign,
TransactionSet: append(parents, txn),
})
}
func (b *bus) walletPendingHandler(jc jape.Context) {
isRelevant := func(txn types.Transaction) bool {
addr := b.w.Address()
for _, sci := range txn.SiacoinInputs {
if sci.UnlockConditions.UnlockHash() == addr {
return true
}
}
for _, sco := range txn.SiacoinOutputs {
if sco.Address == addr {
return true
}
}
return false
}
txns := b.tp.Transactions()
relevant := txns[:0]
for _, txn := range txns {
if isRelevant(txn) {
relevant = append(relevant, txn)
}
}
jc.Encode(relevant)
}
func (b *bus) hostsHandlerGETDeprecated(jc jape.Context) {
offset := 0
limit := -1
if jc.DecodeForm("offset", &offset) != nil || jc.DecodeForm("limit", &limit) != nil {
return
}
// fetch hosts
hosts, err := b.hdb.SearchHosts(jc.Request.Context(), api.HostFilterModeAllowed, "", nil, offset, limit)
if jc.Check(fmt.Sprintf("couldn't fetch hosts %d-%d", offset, offset+limit), err) != nil {
return
}
jc.Encode(hosts)
}
func (b *bus) searchHostsHandlerPOST(jc jape.Context) {
var req api.SearchHostsRequest
if jc.Decode(&req) != nil {
return
}
// TODO: on the next major release:
// - properly default search params
// - properly validate and return 400
hosts, err := b.hdb.SearchHosts(jc.Request.Context(), req.FilterMode, req.AddressContains, req.KeyIn, req.Offset, req.Limit)
if jc.Check(fmt.Sprintf("couldn't fetch hosts %d-%d", req.Offset, req.Offset+req.Limit), err) != nil {
return
}
jc.Encode(hosts)
}
func (b *bus) hostsRemoveHandlerPOST(jc jape.Context) {
var hrr api.HostsRemoveRequest
if jc.Decode(&hrr) != nil {
return
}
if hrr.MaxDowntimeHours == 0 {
jc.Error(errors.New("maxDowntime must be non-zero"), http.StatusBadRequest)
return
}
if hrr.MinRecentScanFailures == 0 {
jc.Error(errors.New("minRecentScanFailures must be non-zero"), http.StatusBadRequest)
return
}
removed, err := b.hdb.RemoveOfflineHosts(jc.Request.Context(), hrr.MinRecentScanFailures, time.Duration(hrr.MaxDowntimeHours))
if jc.Check("couldn't remove offline hosts", err) != nil {
return
}
jc.Encode(removed)
}
func (b *bus) hostsScanningHandlerGET(jc jape.Context) {
offset := 0
limit := -1
maxLastScan := time.Now()
if jc.DecodeForm("offset", &offset) != nil || jc.DecodeForm("limit", &limit) != nil || jc.DecodeForm("lastScan", (*api.TimeRFC3339)(&maxLastScan)) != nil {
return
}
hosts, err := b.hdb.HostsForScanning(jc.Request.Context(), maxLastScan, offset, limit)
if jc.Check(fmt.Sprintf("couldn't fetch hosts %d-%d", offset, offset+limit), err) != nil {
return
}
jc.Encode(hosts)
}
func (b *bus) hostsPubkeyHandlerGET(jc jape.Context) {
var hostKey types.PublicKey
if jc.DecodeParam("hostkey", &hostKey) != nil {
return
}
host, err := b.hdb.Host(jc.Request.Context(), hostKey)
if jc.Check("couldn't load host", err) == nil {
jc.Encode(host)
}
}
func (b *bus) hostsResetLostSectorsPOST(jc jape.Context) {
var hostKey types.PublicKey
if jc.DecodeParam("hostkey", &hostKey) != nil {
return
}
err := b.hdb.ResetLostSectors(jc.Request.Context(), hostKey)
if jc.Check("couldn't reset lost sectors", err) != nil {
return
}
}
func (b *bus) hostsScanHandlerPOST(jc jape.Context) {
var req api.HostsScanRequest
if jc.Decode(&req) != nil {
return
}
if jc.Check("failed to record scans", b.hdb.RecordHostScans(jc.Request.Context(), req.Scans)) != nil {
return
}
}
func (b *bus) hostsPricetableHandlerPOST(jc jape.Context) {
var req api.HostsPriceTablesRequest
if jc.Decode(&req) != nil {
return
}
if jc.Check("failed to record interactions", b.hdb.RecordPriceTables(jc.Request.Context(), req.PriceTableUpdates)) != nil {
return
}
}
func (b *bus) contractsSpendingHandlerPOST(jc jape.Context) {
var records []api.ContractSpendingRecord
if jc.Decode(&records) != nil {
return
}
if jc.Check("failed to record spending metrics for contract", b.ms.RecordContractSpending(jc.Request.Context(), records)) != nil {
return
}
}
func (b *bus) hostsAllowlistHandlerGET(jc jape.Context) {
allowlist, err := b.hdb.HostAllowlist(jc.Request.Context())
if jc.Check("couldn't load allowlist", err) == nil {
jc.Encode(allowlist)
}
}
func (b *bus) hostsAllowlistHandlerPUT(jc jape.Context) {
ctx := jc.Request.Context()
var req api.UpdateAllowlistRequest
if jc.Decode(&req) == nil {
if len(req.Add)+len(req.Remove) > 0 && req.Clear {
jc.Error(errors.New("cannot add or remove entries while clearing the allowlist"), http.StatusBadRequest)
return
} else if jc.Check("couldn't update allowlist entries", b.hdb.UpdateHostAllowlistEntries(ctx, req.Add, req.Remove, req.Clear)) != nil {
return
}
}
}
func (b *bus) hostsBlocklistHandlerGET(jc jape.Context) {
blocklist, err := b.hdb.HostBlocklist(jc.Request.Context())
if jc.Check("couldn't load blocklist", err) == nil {
jc.Encode(blocklist)
}
}
func (b *bus) hostsBlocklistHandlerPUT(jc jape.Context) {
ctx := jc.Request.Context()
var req api.UpdateBlocklistRequest
if jc.Decode(&req) == nil {
if len(req.Add)+len(req.Remove) > 0 && req.Clear {
jc.Error(errors.New("cannot add or remove entries while clearing the blocklist"), http.StatusBadRequest)
return
} else if jc.Check("couldn't update blocklist entries", b.hdb.UpdateHostBlocklistEntries(ctx, req.Add, req.Remove, req.Clear)) != nil {
return
}
}
}
func (b *bus) contractsHandlerGET(jc jape.Context) {
var cs string
if jc.DecodeForm("contractset", &cs) != nil {
return
}
contracts, err := b.ms.Contracts(jc.Request.Context(), api.ContractsOpts{
ContractSet: cs,
})
if jc.Check("couldn't load contracts", err) == nil {
jc.Encode(contracts)
}
}
func (b *bus) contractsRenewedIDHandlerGET(jc jape.Context) {
var id types.FileContractID
if jc.DecodeParam("id", &id) != nil {
return
}
md, err := b.ms.RenewedContract(jc.Request.Context(), id)
if jc.Check("faild to fetch renewed contract", err) == nil {
jc.Encode(md)
}
}
func (b *bus) contractsArchiveHandlerPOST(jc jape.Context) {
var toArchive api.ContractsArchiveRequest
if jc.Decode(&toArchive) != nil {
return
}
jc.Check("failed to archive contracts", b.ms.ArchiveContracts(jc.Request.Context(), toArchive))
}
func (b *bus) contractsSetsHandlerGET(jc jape.Context) {
sets, err := b.ms.ContractSets(jc.Request.Context())
if jc.Check("couldn't fetch contract sets", err) == nil {
jc.Encode(sets)
}
}
func (b *bus) contractsSetHandlerPUT(jc jape.Context) {
var contractIds []types.FileContractID
if set := jc.PathParam("set"); set == "" {
jc.Error(errors.New("path parameter 'set' can not be empty"), http.StatusBadRequest)
} else if jc.Decode(&contractIds) == nil {
jc.Check("could not add contracts to set", b.ms.SetContractSet(jc.Request.Context(), set, contractIds))
}
}
func (b *bus) contractsSetHandlerDELETE(jc jape.Context) {
if set := jc.PathParam("set"); set != "" {
jc.Check("could not remove contract set", b.ms.RemoveContractSet(jc.Request.Context(), set))
}
}
func (b *bus) contractAcquireHandlerPOST(jc jape.Context) {
var id types.FileContractID
if jc.DecodeParam("id", &id) != nil {
return
}
var req api.ContractAcquireRequest
if jc.Decode(&req) != nil {
return
}
lockID, err := b.contractLocks.Acquire(jc.Request.Context(), req.Priority, id, time.Duration(req.Duration))
if jc.Check("failed to acquire contract", err) != nil {
return
}
jc.Encode(api.ContractAcquireResponse{
LockID: lockID,
})
}
func (b *bus) contractKeepaliveHandlerPOST(jc jape.Context) {
var id types.FileContractID
if jc.DecodeParam("id", &id) != nil {
return
}
var req api.ContractKeepaliveRequest
if jc.Decode(&req) != nil {
return
}
err := b.contractLocks.KeepAlive(id, req.LockID, time.Duration(req.Duration))
if jc.Check("failed to extend lock duration", err) != nil {