This repository has been archived by the owner on Nov 2, 2018. It is now read-only.
/
renter.go
744 lines (673 loc) · 26.5 KB
/
renter.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
package api
import (
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/NebulousLabs/Sia/build"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/modules/renter"
"github.com/NebulousLabs/Sia/types"
"github.com/julienschmidt/httprouter"
)
var (
// recommendedHosts is the number of hosts that the renter will form
// contracts with if the value is not specified explicitly in the call to
// SetSettings.
recommendedHosts = build.Select(build.Var{
Standard: uint64(50),
Dev: uint64(2),
Testing: uint64(1),
}).(uint64)
// requiredHosts specifies the minimum number of hosts that must be set in
// the renter settings for the renter settings to be valid. This minimum is
// there to prevent users from shooting themselves in the foot.
requiredHosts = build.Select(build.Var{
Standard: uint64(20),
Dev: uint64(1),
Testing: uint64(1),
}).(uint64)
// requiredParityPieces specifies the minimum number of parity pieces that
// must be used when uploading a file. This minimum exists to prevent users
// from shooting themselves in the foot.
requiredParityPieces = build.Select(build.Var{
Standard: int(12),
Dev: int(0),
Testing: int(0),
}).(int)
// requiredRedundancy specifies the minimum redundancy that will be
// accepted by the renter when uploading a file. This minimum exists to
// prevent users from shooting themselves in the foot.
requiredRedundancy = build.Select(build.Var{
Standard: float64(2),
Dev: float64(1),
Testing: float64(1),
}).(float64)
// requiredRenewWindow establishes the minimum allowed renew window for the
// renter settings. This minimum is here to prevent users from shooting
// themselves in the foot.
requiredRenewWindow = build.Select(build.Var{
Standard: types.BlockHeight(288),
Dev: types.BlockHeight(1),
Testing: types.BlockHeight(1),
}).(types.BlockHeight)
)
type (
// RenterGET contains various renter metrics.
RenterGET struct {
Settings modules.RenterSettings `json:"settings"`
FinancialMetrics modules.ContractorSpending `json:"financialmetrics"`
CurrentPeriod types.BlockHeight `json:"currentperiod"`
}
// RenterContract represents a contract formed by the renter.
RenterContract struct {
// Amount of contract funds that have been spent on downloads.
DownloadSpending types.Currency `json:"downloadspending"`
// Block height that the file contract ends on.
EndHeight types.BlockHeight `json:"endheight"`
// Fees paid in order to form the file contract.
Fees types.Currency `json:"fees"`
// Public key of the host the contract was formed with.
HostPublicKey types.SiaPublicKey `json:"hostpublickey"`
// ID of the file contract.
ID types.FileContractID `json:"id"`
// A signed transaction containing the most recent contract revision.
LastTransaction types.Transaction `json:"lasttransaction"`
// Address of the host the file contract was formed with.
NetAddress modules.NetAddress `json:"netaddress"`
// Remaining funds left for the renter to spend on uploads & downloads.
RenterFunds types.Currency `json:"renterfunds"`
// Size of the file contract, which is typically equal to the number of
// bytes that have been uploaded to the host.
Size uint64 `json:"size"`
// Block height that the file contract began on.
StartHeight types.BlockHeight `json:"startheight"`
// Amount of contract funds that have been spent on storage.
StorageSpending types.Currency `json:"storagespending"`
// DEPRECATED: This is the exact same value as StorageSpending, but it has
// incorrect capitalization. This was fixed in 1.3.2, but this field is kept
// to preserve backwards compatibility on clients who depend on the
// incorrect capitalization. This field will be removed in the future, so
// clients should switch to the StorageSpending field (above) with the
// correct lowercase name.
StorageSpendingDeprecated types.Currency `json:"StorageSpending"`
// Total cost to the wallet of forming the file contract.
TotalCost types.Currency `json:"totalcost"`
// Amount of contract funds that have been spent on uploads.
UploadSpending types.Currency `json:"uploadspending"`
// Signals if contract is good for uploading data
GoodForUpload bool `json:"goodforupload"`
// Signals if contract is good for a renewal
GoodForRenew bool `json:"goodforrenew"`
}
// RenterContracts contains the renter's contracts.
RenterContracts struct {
Contracts []RenterContract `json:"contracts"`
ActiveContracts []RenterContract `json:"activecontracts"`
InactiveContracts []RenterContract `json:"inactivecontracts"`
ExpiredContracts []RenterContract `json:"expiredcontracts"`
}
// RenterDownloadQueue contains the renter's download queue.
RenterDownloadQueue struct {
Downloads []DownloadInfo `json:"downloads"`
}
// RenterFile lists the file queried.
RenterFile struct {
File modules.FileInfo `json:"file"`
}
// RenterFiles lists the files known to the renter.
RenterFiles struct {
Files []modules.FileInfo `json:"files"`
}
// RenterLoad lists files that were loaded into the renter.
RenterLoad struct {
FilesAdded []string `json:"filesadded"`
}
// RenterPricesGET lists the data that is returned when a GET call is made
// to /renter/prices.
RenterPricesGET struct {
modules.RenterPriceEstimation
}
// RenterShareASCII contains an ASCII-encoded .sia file.
RenterShareASCII struct {
ASCIIsia string `json:"asciisia"`
}
// DownloadInfo contains all client-facing information of a file.
DownloadInfo struct {
Destination string `json:"destination"` // The destination of the download.
DestinationType string `json:"destinationtype"` // Can be "file", "memory buffer", or "http stream".
Filesize uint64 `json:"filesize"` // DEPRECATED. Same as 'Length'.
Length uint64 `json:"length"` // The length requested for the download.
Offset uint64 `json:"offset"` // The offset within the siafile requested for the download.
SiaPath string `json:"siapath"` // The siapath of the file used for the download.
Completed bool `json:"completed"` // Whether or not the download has completed.
EndTime time.Time `json:"endtime"` // The time when the download fully completed.
Error string `json:"error"` // Will be the empty string unless there was an error.
Received uint64 `json:"received"` // Amount of data confirmed and decoded.
StartTime time.Time `json:"starttime"` // The time when the download was started.
StartTimeUnix int64 `json:"starttimeunix"` // The time when the download was started in unix format.
TotalDataTransferred uint64 `json:"totaldatatransferred"` // The total amount of data transferred, including negotiation, overdrive etc.
}
)
// renterHandlerGET handles the API call to /renter.
func (api *API) renterHandlerGET(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
settings := api.renter.Settings()
periodStart := api.renter.CurrentPeriod()
WriteJSON(w, RenterGET{
Settings: settings,
FinancialMetrics: api.renter.PeriodSpending(),
CurrentPeriod: periodStart,
})
}
// renterHandlerPOST handles the API call to set the Renter's settings.
func (api *API) renterHandlerPOST(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
// Get the existing settings
settings := api.renter.Settings()
// Scan the allowance amount. (optional parameter)
if f := req.FormValue("funds"); f != "" {
funds, ok := scanAmount(f)
if !ok {
WriteError(w, Error{"unable to parse funds"}, http.StatusBadRequest)
return
}
settings.Allowance.Funds = funds
}
// Scan the number of hosts to use. (optional parameter)
if h := req.FormValue("hosts"); h != "" {
var hosts uint64
if _, err := fmt.Sscan(h, &hosts); err != nil {
WriteError(w, Error{"unable to parse hosts: " + err.Error()}, http.StatusBadRequest)
return
} else if hosts != 0 && hosts < requiredHosts {
WriteError(w, Error{fmt.Sprintf("insufficient number of hosts, need at least %v but have %v", recommendedHosts, hosts)}, http.StatusBadRequest)
} else {
settings.Allowance.Hosts = hosts
}
} else if settings.Allowance.Hosts == 0 {
// Sane defaults if host haven't been set before.
settings.Allowance.Hosts = recommendedHosts
}
// Scan the period. (optional parameter)
if p := req.FormValue("period"); p != "" {
var period types.BlockHeight
if _, err := fmt.Sscan(p, &period); err != nil {
WriteError(w, Error{"unable to parse period: " + err.Error()}, http.StatusBadRequest)
return
}
settings.Allowance.Period = types.BlockHeight(period)
} else if settings.Allowance.Period == 0 {
WriteError(w, Error{"period needs to be set if it hasn't been set before"}, http.StatusBadRequest)
return
}
// Scan the renew window. (optional parameter)
if rw := req.FormValue("renewwindow"); rw != "" {
var renewWindow types.BlockHeight
if _, err := fmt.Sscan(rw, &renewWindow); err != nil {
WriteError(w, Error{"unable to parse renewwindow: " + err.Error()}, http.StatusBadRequest)
return
} else if renewWindow != 0 && types.BlockHeight(renewWindow) < requiredRenewWindow {
WriteError(w, Error{fmt.Sprintf("renew window is too small, must be at least %v blocks but have %v blocks", requiredRenewWindow, renewWindow)}, http.StatusBadRequest)
return
} else {
settings.Allowance.RenewWindow = types.BlockHeight(renewWindow)
}
} else if settings.Allowance.RenewWindow == 0 {
// Sane defaults if renew window hasn't been set before.
settings.Allowance.RenewWindow = settings.Allowance.Period / 2
}
// Scan the download speed limit. (optional parameter)
if d := req.FormValue("maxdownloadspeed"); d != "" {
var downloadSpeed int64
if _, err := fmt.Sscan(d, &downloadSpeed); err != nil {
WriteError(w, Error{"unable to parse downloadspeed: " + err.Error()}, http.StatusBadRequest)
return
}
settings.MaxDownloadSpeed = downloadSpeed
}
// Scan the upload speed limit. (optional parameter)
if u := req.FormValue("maxuploadspeed"); u != "" {
var uploadSpeed int64
if _, err := fmt.Sscan(u, &uploadSpeed); err != nil {
WriteError(w, Error{"unable to parse uploadspeed: " + err.Error()}, http.StatusBadRequest)
return
}
settings.MaxUploadSpeed = uploadSpeed
}
// Scan the stream cache size. (optional parameter)
if dcs := req.FormValue("streamcachesize"); dcs != "" {
var streamCacheSize uint64
if _, err := fmt.Sscan(dcs, &streamCacheSize); err != nil {
WriteError(w, Error{"unable to parse streamcachesize: " + err.Error()}, http.StatusBadRequest)
return
}
settings.StreamCacheSize = streamCacheSize
}
// Set the settings in the renter.
err := api.renter.SetSettings(settings)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}
// renterContractsHandler handles the API call to request the Renter's
// contracts.
//
// Active contracts are contracts that the renter is actively using to store
// data and can upload, download, and renew
//
// Inactive contracts are contracts that are not currently being used by the
// renter because they are !goodForRenew, but have endheights that are in the
// future so could potentially become active again
//
// Expired contracts are contracts who's endheights are in the past
func (api *API) renterContractsHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
// Parse flags
inactive, err := scanBool(req.FormValue("inactive"))
if err != nil {
return
}
expired, err := scanBool(req.FormValue("expired"))
if err != nil {
return
}
// Get current block height for reference
blockHeight := api.cs.Height()
// Get active contracts
contracts := []RenterContract{}
activeContracts := []RenterContract{}
inactiveContracts := []RenterContract{}
expiredContracts := []RenterContract{}
for _, c := range api.renter.Contracts() {
var size uint64
if len(c.Transaction.FileContractRevisions) != 0 {
size = c.Transaction.FileContractRevisions[0].NewFileSize
}
// Fetch host address
var netAddress modules.NetAddress
hdbe, exists := api.renter.Host(c.HostPublicKey)
if exists {
netAddress = hdbe.NetAddress
}
// Fetch utilities for contract
var goodForUpload bool
var goodForRenew bool
if utility, ok := api.renter.ContractUtility(c.HostPublicKey); ok {
goodForUpload = utility.GoodForUpload
goodForRenew = utility.GoodForRenew
}
contract := RenterContract{
DownloadSpending: c.DownloadSpending,
EndHeight: c.EndHeight,
Fees: c.TxnFee.Add(c.SiafundFee).Add(c.ContractFee),
GoodForUpload: goodForUpload,
GoodForRenew: goodForRenew,
HostPublicKey: c.HostPublicKey,
ID: c.ID,
LastTransaction: c.Transaction,
NetAddress: netAddress,
RenterFunds: c.RenterFunds,
Size: size,
StartHeight: c.StartHeight,
StorageSpending: c.StorageSpending,
StorageSpendingDeprecated: c.StorageSpending,
TotalCost: c.TotalCost,
UploadSpending: c.UploadSpending,
}
if goodForRenew {
activeContracts = append(activeContracts, contract)
} else if inactive && !goodForRenew {
inactiveContracts = append(inactiveContracts, contract)
}
contracts = append(contracts, contract)
}
// Get expired contracts
if expired || inactive {
for _, c := range api.renter.OldContracts() {
var size uint64
if len(c.Transaction.FileContractRevisions) != 0 {
size = c.Transaction.FileContractRevisions[0].NewFileSize
}
// Fetch host address
var netAddress modules.NetAddress
hdbe, exists := api.renter.Host(c.HostPublicKey)
if exists {
netAddress = hdbe.NetAddress
}
// Fetch utilities for contract
var goodForUpload bool
var goodForRenew bool
if utility, ok := api.renter.ContractUtility(c.HostPublicKey); ok {
goodForUpload = utility.GoodForUpload
goodForRenew = utility.GoodForRenew
}
contract := RenterContract{
DownloadSpending: c.DownloadSpending,
EndHeight: c.EndHeight,
Fees: c.TxnFee.Add(c.SiafundFee).Add(c.ContractFee),
GoodForUpload: goodForUpload,
GoodForRenew: goodForRenew,
HostPublicKey: c.HostPublicKey,
ID: c.ID,
LastTransaction: c.Transaction,
NetAddress: netAddress,
RenterFunds: c.RenterFunds,
Size: size,
StartHeight: c.StartHeight,
StorageSpending: c.StorageSpending,
StorageSpendingDeprecated: c.StorageSpending,
TotalCost: c.TotalCost,
UploadSpending: c.UploadSpending,
}
if expired && c.EndHeight < blockHeight {
expiredContracts = append(expiredContracts, contract)
} else if inactive && c.EndHeight >= blockHeight {
inactiveContracts = append(inactiveContracts, contract)
}
}
}
WriteJSON(w, RenterContracts{
Contracts: contracts,
ActiveContracts: activeContracts,
InactiveContracts: inactiveContracts,
ExpiredContracts: expiredContracts,
})
}
// renterClearDownloadsHandler handles the API call to request to clear the download queue.
func (api *API) renterClearDownloadsHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
var afterTime time.Time
beforeTime := types.EndOfTime
beforeStr, afterStr := req.FormValue("before"), req.FormValue("after")
if beforeStr != "" {
beforeInt, err := strconv.ParseInt(beforeStr, 10, 64)
if err != nil {
WriteError(w, Error{"parsing integer value for parameter `before` failed: " + err.Error()}, http.StatusBadRequest)
return
}
beforeTime = time.Unix(0, beforeInt)
}
if afterStr != "" {
afterInt, err := strconv.ParseInt(afterStr, 10, 64)
if err != nil {
WriteError(w, Error{"parsing integer value for parameter `after` failed: " + err.Error()}, http.StatusBadRequest)
return
}
afterTime = time.Unix(0, afterInt)
}
err := api.renter.ClearDownloadHistory(afterTime, beforeTime)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}
// renterDownloadsHandler handles the API call to request the download queue.
func (api *API) renterDownloadsHandler(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
var downloads []DownloadInfo
for _, di := range api.renter.DownloadHistory() {
downloads = append(downloads, DownloadInfo{
Destination: di.Destination,
DestinationType: di.DestinationType,
Filesize: di.Length,
Length: di.Length,
Offset: di.Offset,
SiaPath: di.SiaPath,
Completed: di.Completed,
EndTime: di.EndTime,
Error: di.Error,
Received: di.Received,
StartTime: di.StartTime,
StartTimeUnix: di.StartTimeUnix,
TotalDataTransferred: di.TotalDataTransferred,
})
}
WriteJSON(w, RenterDownloadQueue{
Downloads: downloads,
})
}
// renterLoadHandler handles the API call to load a '.sia' file.
func (api *API) renterLoadHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
source := req.FormValue("source")
if !filepath.IsAbs(source) {
WriteError(w, Error{"source must be an absolute path"}, http.StatusBadRequest)
return
}
files, err := api.renter.LoadSharedFiles(source)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteJSON(w, RenterLoad{FilesAdded: files})
}
// renterLoadAsciiHandler handles the API call to load a '.sia' file
// in ASCII form.
func (api *API) renterLoadASCIIHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
files, err := api.renter.LoadSharedFilesASCII(req.FormValue("asciisia"))
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteJSON(w, RenterLoad{FilesAdded: files})
}
// renterRenameHandler handles the API call to rename a file entry in the
// renter.
func (api *API) renterRenameHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
err := api.renter.RenameFile(strings.TrimPrefix(ps.ByName("siapath"), "/"), req.FormValue("newsiapath"))
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}
// renterFileHandler handles the API call to return specific file.
func (api *API) renterFileHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
file, err := api.renter.File(strings.TrimPrefix(ps.ByName("siapath"), "/"))
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteJSON(w, RenterFile{
File: file,
})
}
// renterFilesHandler handles the API call to list all of the files.
func (api *API) renterFilesHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
WriteJSON(w, RenterFiles{
Files: api.renter.FileList(),
})
}
// renterPricesHandler reports the expected costs of various actions given the
// renter settings and the set of available hosts.
func (api *API) renterPricesHandler(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
WriteJSON(w, RenterPricesGET{
RenterPriceEstimation: api.renter.PriceEstimation(),
})
}
// renterDeleteHandler handles the API call to delete a file entry from the
// renter.
func (api *API) renterDeleteHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
err := api.renter.DeleteFile(strings.TrimPrefix(ps.ByName("siapath"), "/"))
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}
// renterDownloadHandler handles the API call to download a file.
func (api *API) renterDownloadHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
params, err := parseDownloadParameters(w, req, ps)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
if params.Async {
err = api.renter.DownloadAsync(params)
} else {
err = api.renter.Download(params)
}
if err != nil {
WriteError(w, Error{"download failed: " + err.Error()}, http.StatusInternalServerError)
return
}
if params.Httpwriter == nil {
// `httpresp=true` causes writes to w before this line is run, automatically
// adding `200 Status OK` code to response. Calling this results in a
// multiple calls to WriteHeaders() errors.
WriteSuccess(w)
return
}
}
// renterDownloadAsyncHandler handles the API call to download a file asynchronously.
func (api *API) renterDownloadAsyncHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
req.ParseForm()
req.Form.Set("async", "true")
api.renterDownloadHandler(w, req, ps)
}
// parseDownloadParameters parses the download parameters passed to the
// /renter/download endpoint. Validation of these parameters is done by the
// renter.
func parseDownloadParameters(w http.ResponseWriter, req *http.Request, ps httprouter.Params) (modules.RenterDownloadParameters, error) {
destination := req.FormValue("destination")
// The offset and length in bytes.
offsetparam := req.FormValue("offset")
lengthparam := req.FormValue("length")
// Determines whether the response is written to response body.
httprespparam := req.FormValue("httpresp")
// Determines whether to return on completion of download or straight away.
// If httprespparam is present, this parameter is ignored.
asyncparam := req.FormValue("async")
// Parse the offset and length parameters.
var offset, length uint64
if len(offsetparam) > 0 {
_, err := fmt.Sscan(offsetparam, &offset)
if err != nil {
return modules.RenterDownloadParameters{}, build.ExtendErr("could not decode the offset as uint64: ", err)
}
}
if len(lengthparam) > 0 {
_, err := fmt.Sscan(lengthparam, &length)
if err != nil {
return modules.RenterDownloadParameters{}, build.ExtendErr("could not decode the offset as uint64: ", err)
}
}
// Parse the httpresp parameter.
httpresp, err := scanBool(httprespparam)
if err != nil {
return modules.RenterDownloadParameters{}, build.ExtendErr("httpresp parameter could not be parsed", err)
}
// Parse the async parameter.
async, err := scanBool(asyncparam)
if err != nil {
return modules.RenterDownloadParameters{}, build.ExtendErr("async parameter could not be parsed", err)
}
siapath := strings.TrimPrefix(ps.ByName("siapath"), "/") // Sia file name.
dp := modules.RenterDownloadParameters{
Destination: destination,
Async: async,
Length: length,
Offset: offset,
SiaPath: siapath,
}
if httpresp {
dp.Httpwriter = w
}
return dp, nil
}
// renterShareHandler handles the API call to create a '.sia' file that
// shares a set of file.
func (api *API) renterShareHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
destination := req.FormValue("destination")
// Check that the destination path is absolute.
if !filepath.IsAbs(destination) {
WriteError(w, Error{"destination must be an absolute path"}, http.StatusBadRequest)
return
}
err := api.renter.ShareFiles(strings.Split(req.FormValue("siapaths"), ","), destination)
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteSuccess(w)
}
// renterShareAsciiHandler handles the API call to return a '.sia' file
// in ascii form.
func (api *API) renterShareASCIIHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
ascii, err := api.renter.ShareFilesASCII(strings.Split(req.FormValue("siapaths"), ","))
if err != nil {
WriteError(w, Error{err.Error()}, http.StatusBadRequest)
return
}
WriteJSON(w, RenterShareASCII{
ASCIIsia: ascii,
})
}
// renterStreamHandler handles downloads from the /renter/stream endpoint
func (api *API) renterStreamHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
siaPath := strings.TrimPrefix(ps.ByName("siapath"), "/")
fileName, streamer, err := api.renter.Streamer(siaPath)
if err != nil {
WriteError(w, Error{fmt.Sprintf("failed to create download streamer: %v", err)},
http.StatusInternalServerError)
return
}
http.ServeContent(w, req, fileName, time.Time{}, streamer)
}
// renterUploadHandler handles the API call to upload a file.
func (api *API) renterUploadHandler(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
source := req.FormValue("source")
if !filepath.IsAbs(source) {
WriteError(w, Error{"source must be an absolute path"}, http.StatusBadRequest)
return
}
// Check whether the erasure coding parameters have been supplied.
var ec modules.ErasureCoder
if req.FormValue("datapieces") != "" || req.FormValue("paritypieces") != "" {
// Check that both values have been supplied.
if req.FormValue("datapieces") == "" || req.FormValue("paritypieces") == "" {
WriteError(w, Error{"must provide both the datapieces parameter and the paritypieces parameter if specifying erasure coding parameters"}, http.StatusBadRequest)
return
}
// Parse the erasure coding parameters.
var dataPieces, parityPieces int
_, err := fmt.Sscan(req.FormValue("datapieces"), &dataPieces)
if err != nil {
WriteError(w, Error{"unable to read parameter 'datapieces': " + err.Error()}, http.StatusBadRequest)
return
}
_, err = fmt.Sscan(req.FormValue("paritypieces"), &parityPieces)
if err != nil {
WriteError(w, Error{"unable to read parameter 'paritypieces': " + err.Error()}, http.StatusBadRequest)
return
}
// Verify that sane values for parityPieces and redundancy are being
// supplied.
if parityPieces < requiredParityPieces {
WriteError(w, Error{fmt.Sprintf("a minimum of %v parity pieces is required, but %v parity pieces requested", parityPieces, requiredParityPieces)}, http.StatusBadRequest)
return
}
redundancy := float64(dataPieces+parityPieces) / float64(dataPieces)
if float64(dataPieces+parityPieces)/float64(dataPieces) < requiredRedundancy {
WriteError(w, Error{fmt.Sprintf("a redundancy of %.2f is required, but redundancy of %.2f supplied", redundancy, requiredRedundancy)}, http.StatusBadRequest)
return
}
// Create the erasure coder.
ec, err = renter.NewRSCode(dataPieces, parityPieces)
if err != nil {
WriteError(w, Error{"unable to encode file using the provided parameters: " + err.Error()}, http.StatusBadRequest)
return
}
}
// Call the renter to upload the file.
err := api.renter.Upload(modules.FileUploadParams{
Source: source,
SiaPath: strings.TrimPrefix(ps.ByName("siapath"), "/"),
ErasureCode: ec,
})
if err != nil {
WriteError(w, Error{"upload failed: " + err.Error()}, http.StatusInternalServerError)
return
}
WriteSuccess(w)
}