forked from NebulousLabs/Sia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hostcmd.go
515 lines (447 loc) · 15.9 KB
/
hostcmd.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
package main
import (
"fmt"
"math/big"
"os"
"sort"
"strings"
"text/tabwriter"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/node/api/client"
"github.com/NebulousLabs/Sia/types"
"github.com/spf13/cobra"
)
var (
hostAnnounceCmd = &cobra.Command{
Use: "announce",
Short: "Announce yourself as a host",
Long: `Announce yourself as a host on the network.
Announcing will also configure the host to start accepting contracts.
You can revert this by running:
siac host config acceptingcontracts false
You may also supply a specific address to be announced, e.g.:
siac host announce my-host-domain.com:9001
Doing so will override the standard connectivity checks.`,
Run: hostannouncecmd,
}
hostCmd = &cobra.Command{
Use: "host",
Short: "Perform host actions",
Long: "View or modify host settings.",
Run: wrap(hostcmd),
}
hostConfigCmd = &cobra.Command{
Use: "config [setting] [value]",
Short: "Modify host settings",
Long: `Modify host settings.
Available settings:
acceptingcontracts: boolean
maxduration: blocks
maxdownloadbatchsize: bytes
maxrevisebatchsize: bytes
netaddress: string
windowsize: blocks
collateral: currency
collateralbudget: currency
maxcollateral: currency
mincontractprice: currency
mindownloadbandwidthprice: currency / TB
minstorageprice: currency / TB / Month
minuploadbandwidthprice: currency / TB
Currency units can be specified, e.g. 10SC; run 'siac help wallet' for details.
Durations (maxduration and windowsize) must be specified in either blocks (b),
hours (h), days (d), or weeks (w). A block is approximately 10 minutes, so one
hour is six blocks, a day is 144 blocks, and a week is 1008 blocks.
For a description of each parameter, see doc/API.md.
To configure the host to accept new contracts, set acceptingcontracts to true:
siac host config acceptingcontracts true
`,
Run: wrap(hostconfigcmd),
}
hostContractCmd = &cobra.Command{
Use: "contracts",
Short: "Show host contracts",
Long: `Show host contracts sorted by expiration height.
Available output types:
value: show financial information
status: show status information
`,
Run: wrap(hostcontractcmd),
}
hostFolderAddCmd = &cobra.Command{
Use: "add [path] [size]",
Short: "Add a storage folder to the host",
Long: "Add a storage folder to the host, specifying how much data it should store",
Run: wrap(hostfolderaddcmd),
}
hostFolderCmd = &cobra.Command{
Use: "folder",
Short: "Add, remove, or resize a storage folder",
Long: "Add, remove, or resize a storage folder.",
}
hostFolderRemoveCmd = &cobra.Command{
Use: "remove [path]",
Short: "Remove a storage folder from the host",
Long: `Remove a storage folder from the host. Note that this does not delete any
data; it will instead be distributed across the remaining storage folders.`,
Run: wrap(hostfolderremovecmd),
}
hostFolderResizeCmd = &cobra.Command{
Use: "resize [path] [size]",
Short: "Resize a storage folder",
Long: `Change how much data a storage folder should store. If the new size is less
than what the folder is currently storing, data will be distributed across the
other storage folders.`,
Run: wrap(hostfolderresizecmd),
}
hostSectorCmd = &cobra.Command{
Use: "sector",
Short: "Add or delete a sector (add not supported)",
Long: `Add or delete a sector. Adding is not currently supported. Note that
deleting a sector may impact host revenue.`,
}
hostSectorDeleteCmd = &cobra.Command{
Use: "delete [root]",
Short: "Delete a sector",
Long: `Delete a sector, identified by its Merkle root. Note that deleting a
sector may impact host revenue.`,
Run: wrap(hostsectordeletecmd),
}
)
// hostcmd is the handler for the command `siac host`.
// Prints info about the host and its storage folders.
func hostcmd() {
hg, err := httpClient.HostGet()
if err != nil {
die("Could not fetch host settings:", err)
}
sg, err := httpClient.HostStorageGet()
if err != nil {
die("Could not fetch storage info:", err)
}
es := hg.ExternalSettings
fm := hg.FinancialMetrics
is := hg.InternalSettings
nm := hg.NetworkMetrics
// calculate total storage available and remaining
var totalstorage, storageremaining uint64
for _, folder := range sg.Folders {
totalstorage += folder.Capacity
storageremaining += folder.CapacityRemaining
}
// convert price from bytes/block to TB/Month
price := currencyUnits(is.MinStoragePrice.Mul(modules.BlockBytesPerMonthTerabyte))
// calculate total revenue
totalRevenue := fm.ContractCompensation.
Add(fm.StorageRevenue).
Add(fm.DownloadBandwidthRevenue).
Add(fm.UploadBandwidthRevenue)
totalPotentialRevenue := fm.PotentialContractCompensation.
Add(fm.PotentialStorageRevenue).
Add(fm.PotentialDownloadBandwidthRevenue).
Add(fm.PotentialUploadBandwidthRevenue)
// determine the display method for the net address.
netaddr := es.NetAddress
if is.NetAddress == "" {
netaddr += " (automatically determined)"
} else {
netaddr += " (manually specified)"
}
var connectabilityString string
if hg.WorkingStatus == "working" {
connectabilityString = "Host appears to be working."
} else if hg.WorkingStatus == "not working" && hg.ConnectabilityStatus == "connectable" {
connectabilityString = "Nobody is connecting to host. Try re-announcing."
} else if hg.WorkingStatus == "checking" || hg.ConnectabilityStatus == "checking" {
connectabilityString = "Host is checking status (takes a few minues)."
} else {
connectabilityString = "Host is not connectable (re-checks every few minutes)."
}
if hostVerbose {
// describe net address
fmt.Printf(`General Info:
Connectability Status: %v
Host Internal Settings:
acceptingcontracts: %v
maxduration: %v Weeks
maxdownloadbatchsize: %v
maxrevisebatchsize: %v
netaddress: %v
windowsize: %v Hours
collateral: %v / TB / Month
collateralbudget: %v
maxcollateral: %v Per Contract
mincontractprice: %v
mindownloadbandwidthprice: %v / TB
minstorageprice: %v / TB / Month
minuploadbandwidthprice: %v / TB
Host Financials:
Contract Count: %v
Transaction Fee Compensation: %v
Potential Fee Compensation: %v
Transaction Fee Expenses: %v
Storage Revenue: %v
Potential Storage Revenue: %v
Locked Collateral: %v
Risked Collateral: %v
Lost Collateral: %v
Download Revenue: %v
Potential Download Revenue: %v
Upload Revenue: %v
Potential Upload Revenue: %v
RPC Stats:
Error Calls: %v
Unrecognized Calls: %v
Download Calls: %v
Renew Calls: %v
Revise Calls: %v
Settings Calls: %v
FormContract Calls: %v
`,
connectabilityString,
yesNo(is.AcceptingContracts), periodUnits(is.MaxDuration),
filesizeUnits(int64(is.MaxDownloadBatchSize)),
filesizeUnits(int64(is.MaxReviseBatchSize)), netaddr,
is.WindowSize/6,
currencyUnits(is.Collateral.Mul(modules.BlockBytesPerMonthTerabyte)),
currencyUnits(is.CollateralBudget),
currencyUnits(is.MaxCollateral),
currencyUnits(is.MinContractPrice),
currencyUnits(is.MinDownloadBandwidthPrice.Mul(modules.BytesPerTerabyte)),
currencyUnits(is.MinStoragePrice.Mul(modules.BlockBytesPerMonthTerabyte)),
currencyUnits(is.MinUploadBandwidthPrice.Mul(modules.BytesPerTerabyte)),
fm.ContractCount, currencyUnits(fm.ContractCompensation),
currencyUnits(fm.PotentialContractCompensation),
currencyUnits(fm.TransactionFeeExpenses),
currencyUnits(fm.StorageRevenue),
currencyUnits(fm.PotentialStorageRevenue),
currencyUnits(fm.LockedStorageCollateral),
currencyUnits(fm.RiskedStorageCollateral),
currencyUnits(fm.LostStorageCollateral),
currencyUnits(fm.DownloadBandwidthRevenue),
currencyUnits(fm.PotentialDownloadBandwidthRevenue),
currencyUnits(fm.UploadBandwidthRevenue),
currencyUnits(fm.PotentialUploadBandwidthRevenue),
nm.ErrorCalls, nm.UnrecognizedCalls, nm.DownloadCalls,
nm.RenewCalls, nm.ReviseCalls, nm.SettingsCalls,
nm.FormContractCalls)
} else {
fmt.Printf(`Host info:
Connectability Status: %v
Storage: %v (%v used)
Price: %v / TB / Month
Max Duration: %v Weeks
Accepting Contracts: %v
Anticipated Revenue: %v
Locked Collateral: %v
Revenue: %v
`,
connectabilityString,
filesizeUnits(int64(totalstorage)),
filesizeUnits(int64(totalstorage-storageremaining)), price,
periodUnits(is.MaxDuration),
yesNo(is.AcceptingContracts), currencyUnits(totalPotentialRevenue),
currencyUnits(fm.LockedStorageCollateral),
currencyUnits(totalRevenue))
}
// if wallet is locked print warning
walletstatus, walleterr := httpClient.WalletGet()
if walleterr != nil {
fmt.Print("\nWarning:\n Could not get wallet status. A working wallet is needed in order to operate your host. Error: ")
fmt.Println(walleterr)
} else if !walletstatus.Unlocked {
fmt.Println("\nWarning:\n Your wallet is locked. You must unlock your wallet for the host to function properly.")
}
fmt.Println("\nStorage Folders:")
// display storage folder info
sort.Slice(sg.Folders, func(i, j int) bool {
return sg.Folders[i].Path < sg.Folders[j].Path
})
if len(sg.Folders) == 0 {
fmt.Println("No storage folders configured")
return
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 4, ' ', 0)
fmt.Fprintf(w, "\tUsed\tCapacity\t%% Used\tPath\n")
for _, folder := range sg.Folders {
curSize := int64(folder.Capacity - folder.CapacityRemaining)
pctUsed := 100 * (float64(curSize) / float64(folder.Capacity))
fmt.Fprintf(w, "\t%s\t%s\t%.2f\t%s\n", filesizeUnits(curSize), filesizeUnits(int64(folder.Capacity)), pctUsed, folder.Path)
}
w.Flush()
}
// hostconfigcmd is the handler for the command `siac host config [setting] [value]`.
// Modifies host settings.
func hostconfigcmd(param, value string) {
var err error
switch param {
// currency (convert to hastings)
case "collateralbudget", "maxcollateral", "mincontractprice":
value, err = parseCurrency(value)
if err != nil {
die("Could not parse "+param+":", err)
}
// currency/TB (convert to hastings/byte)
case "mindownloadbandwidthprice", "minuploadbandwidthprice":
hastings, err := parseCurrency(value)
if err != nil {
die("Could not parse "+param+":", err)
}
i, _ := new(big.Int).SetString(hastings, 10)
c := types.NewCurrency(i).Div(modules.BytesPerTerabyte)
value = c.String()
// currency/TB/month (convert to hastings/byte/block)
case "collateral", "minstorageprice":
hastings, err := parseCurrency(value)
if err != nil {
die("Could not parse "+param+":", err)
}
i, _ := new(big.Int).SetString(hastings, 10)
c := types.NewCurrency(i).Div(modules.BlockBytesPerMonthTerabyte)
value = c.String()
// bool (allow "yes" and "no")
case "acceptingcontracts":
switch strings.ToLower(value) {
case "yes":
value = "true"
case "no":
value = "false"
}
// duration (convert to blocks)
case "maxduration", "windowsize":
value, err = parsePeriod(value)
if err != nil {
die("Could not parse "+param+":", err)
}
// other valid settings
case "maxdownloadbatchsize", "maxrevisebatchsize", "netaddress":
// invalid settings
default:
die("\"" + param + "\" is not a host setting")
}
err = httpClient.HostModifySettingPost(client.HostParam(param), value)
if err != nil {
die("Failed to update host settings:", err)
}
fmt.Println("Host settings updated.")
// get the estimated conversion rate.
eg, err := httpClient.HostEstimateScoreGet(param, value)
if err != nil {
if err.Error() == "cannot call /host/estimatescore without the renter module" {
// score estimate requires the renter module
return
}
die("could not get host score estimate:", err)
}
fmt.Printf("Estimated conversion rate: %v%%\n", eg.ConversionRate)
}
// hostcontractcmd is the handler for the command `siac host contracts [type]`.
func hostcontractcmd() {
cg, err := httpClient.HostContractInfoGet()
if err != nil {
die("Could not fetch host contract info:", err)
}
sort.Slice(cg.Contracts, func(i, j int) bool { return cg.Contracts[i].ExpirationHeight < cg.Contracts[j].ExpirationHeight })
w := tabwriter.NewWriter(os.Stdout, 0, 0, 4, ' ', 0)
switch hostContractOutputType {
case "value":
fmt.Fprintf(w, "Obligation Id\tObligation Status\tContract Cost\tLocked Collateral\tRisked Collateral\tPotential Revenue\tExpiration Height\tTransaction Fees\n")
for _, so := range cg.Contracts {
potentialRevenue := so.PotentialDownloadRevenue.Add(so.PotentialUploadRevenue).Add(so.PotentialStorageRevenue)
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s\n", so.ObligationId, strings.TrimPrefix(so.ObligationStatus, "obligation"), currencyUnits(so.ContractCost), currencyUnits(so.LockedCollateral),
currencyUnits(so.RiskedCollateral), currencyUnits(potentialRevenue), so.ExpirationHeight, currencyUnits(so.TransactionFeesAdded))
}
case "status":
fmt.Fprintf(w, "Obligation ID\tObligation Status\tExpiration Height\tOrigin Confirmed\tRevision Constructed\tRevision Confirmed\tProof Constructed\tProof Confirmed\n")
for _, so := range cg.Contracts {
fmt.Fprintf(w, "%s\t%s\t%d\t%t\t%t\t%t\t%t\t%t\n", so.ObligationId, strings.TrimPrefix(so.ObligationStatus, "obligation"), so.ExpirationHeight, so.OriginConfirmed,
so.RevisionConstructed, so.RevisionConfirmed, so.ProofConstructed, so.ProofConfirmed)
}
default:
die("\"" + hostContractOutputType + "\" is not a format")
}
w.Flush()
}
// hostannouncecmd is the handler for the command `siac host announce`.
// Announces yourself as a host to the network. Optionally takes an address to
// announce as.
func hostannouncecmd(cmd *cobra.Command, args []string) {
var err error
switch len(args) {
case 0:
err = httpClient.HostAnnouncePost()
case 1:
err = httpClient.HostAnnounceAddrPost(modules.NetAddress(args[0]))
default:
cmd.UsageFunc()(cmd)
os.Exit(exitCodeUsage)
}
if err != nil {
die("Could not announce host:", err)
}
fmt.Println("Host announcement submitted to network.")
// start accepting contracts
err = httpClient.HostModifySettingPost(client.HostParamAcceptingContracts, true)
if err != nil {
die("Could not configure host to accept contracts:", err)
}
fmt.Println(`The host has also been configured to accept contracts.
To revert this, run:
siac host config acceptingcontracts false`)
}
// hostfolderaddcmd adds a folder to the host.
func hostfolderaddcmd(path, size string) {
size, err := parseFilesize(size)
if err != nil {
die("Could not parse size:", err)
}
// round size down to nearest multiple of 256MiB
var sizeUint64 uint64
fmt.Sscan(size, &sizeUint64)
sizeUint64 /= 64 * modules.SectorSize
sizeUint64 *= 64 * modules.SectorSize
err = httpClient.HostStorageFoldersAddPost(abs(path), sizeUint64)
if err != nil {
die("Could not add folder:", err)
}
fmt.Println("Added folder", path)
}
// hostfolderremovecmd removes a folder from the host.
func hostfolderremovecmd(path string) {
err := httpClient.HostStorageFoldersRemovePost(abs(path))
if err != nil {
die("Could not remove folder:", err)
}
fmt.Println("Removed folder", path)
}
// hostfolderresizecmd resizes a folder in the host.
func hostfolderresizecmd(path, newsize string) {
newsize, err := parseFilesize(newsize)
if err != nil {
die("Could not parse size:", err)
}
// round size down to nearest multiple of 256MiB
var sizeUint64 uint64
fmt.Sscan(newsize, &sizeUint64)
sizeUint64 /= 64 * modules.SectorSize
sizeUint64 *= 64 * modules.SectorSize
err = httpClient.HostStorageFoldersResizePost(abs(path), sizeUint64)
if err != nil {
die("Could not resize folder:", err)
}
fmt.Printf("Resized folder %v to %v\n", path, newsize)
}
// hostsectordeletecmd deletes a sector from the host.
func hostsectordeletecmd(root string) {
var hash crypto.Hash
err := hash.LoadString(root)
if err != nil {
die("Could not parse root:", err)
}
err = httpClient.HostStorageSectorsDeletePost(hash)
if err != nil {
die("Could not delete sector:", err)
}
fmt.Println("Deleted sector", root)
}