/
rhp.go
511 lines (453 loc) · 17.9 KB
/
rhp.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
package rhp
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"time"
"go.sia.tech/core/consensus"
"go.sia.tech/core/types"
)
const (
// SectorSize is the size of one sector in bytes.
SectorSize = 1 << 22 // 4 MiB
// SegmentSize is the size of one segment in bytes.
SegmentSize = 64
)
func round4KiB(n uint64) uint64 {
return (n + (1<<12 - 1)) &^ (1<<12 - 1)
}
// A Transport is a pair of protocol and address that a host may be reached on.
type Transport struct {
Protocol string `json:"protocol"`
Address string `json:"address"`
}
// HostPrices specify a time-bound set of parameters used to calculate the cost
// of various RPCs.
type HostPrices struct {
ContractPrice types.Currency `json:"contractPrice"`
Collateral types.Currency `json:"collateral"`
StoragePrice types.Currency `json:"storagePrice"`
IngressPrice types.Currency `json:"ingressPrice"`
EgressPrice types.Currency `json:"egressPrice"`
TipHeight uint64 `json:"tipHeight"`
ValidUntil time.Time `json:"validUntil"`
// covers above fields
Signature types.Signature `json:"signature"`
}
func (hp HostPrices) ReadSectorCost(length uint64) types.Currency {
return hp.EgressPrice.Mul64(round4KiB(length))
}
func (hp HostPrices) WriteSectorCost(sector []byte) types.Currency {
return hp.IngressPrice.Mul64(round4KiB(uint64(len(sector))))
}
// HostSettings specify the settings of a host.
type HostSettings struct {
ProtocolVersion [3]uint8 `json:"protocolVersion"`
Release string `json:"release"`
Transports []Transport `json:"transports"`
WalletAddress types.Address `json:"walletAddress"`
AcceptingContracts bool `json:"acceptingContracts"`
MaxCollateral types.Currency `json:"maxCollateral"`
MaxDuration uint64 `json:"maxDuration"`
RemainingStorage uint64 `json:"remainingStorage"`
TotalStorage uint64 `json:"totalStorage"`
Prices HostPrices `json:"prices"`
}
// Sign signs the host prices with the given key.
func (hs *HostSettings) Sign(sk types.PrivateKey) {
// NOTE: this is a method on HostSettings (rather than HostPrices itself)
// because that gives us access to the protocol version.
h := types.NewHasher()
hs.Prices.Signature = types.Signature{}
hs.Prices.EncodeTo(h.E)
hs.Prices.Signature = sk.SignHash(h.Sum())
}
// A WriteAction adds or modifies sectors within a contract.
type WriteAction struct {
Type uint8 `json:"type"`
Root types.Hash256 `json:"root,omitempty"` // Append
A uint64 `json:"a,omitempty"` // Swap
B uint64 `json:"b,omitempty"` // Swap
N uint64 `json:"n,omitempty"` // Trim
}
// WriteAction types.
const (
ActionAppend = iota + 1
ActionSwap
ActionTrim
ActionUpdate // TODO: implement
)
// An Account represents an ephemeral balance that can be funded via contract
// revision and spent to pay for RPCs.
type Account types.PublicKey
// String implements fmt.Stringer.
func (a Account) String() string { return fmt.Sprintf("acct:%x", a[:]) }
// MarshalText implements encoding.TextMarshaler.
func (a Account) MarshalText() ([]byte, error) { return []byte(a.String()), nil }
// UnmarshalText implements encoding.TextUnmarshaler.
func (a *Account) UnmarshalText(b []byte) error {
n, err := hex.Decode(a[:], bytes.TrimPrefix(b, []byte("acct:")))
if err != nil {
return fmt.Errorf("decoding acct:<hex> failed: %w", err)
} else if n < len(a) {
return io.ErrUnexpectedEOF
}
return nil
}
// An AccountToken authorizes an account action.
type AccountToken struct {
Account Account `json:"account"`
ValidUntil time.Time `json:"validUntil"`
Signature types.Signature `json:"signature"`
}
func (at *AccountToken) sigHash() types.Hash256 {
h := types.NewHasher()
at.Account.EncodeTo(h.E)
h.E.WriteTime(at.ValidUntil)
return h.Sum()
}
// Sign signs the account token with the given key.
func (at *AccountToken) Sign(sk types.PrivateKey) {
at.Signature = sk.SignHash(at.sigHash())
}
// Verify verifies the account token.
func (at AccountToken) Verify() bool {
return types.PublicKey(at.Account).VerifyHash(at.sigHash(), at.Signature)
}
// GenerateAccount generates a pair of private key and Account from a secure
// entropy source.
func GenerateAccount() (types.PrivateKey, Account) {
sk := types.GeneratePrivateKey()
return sk, Account(sk.PublicKey())
}
type (
// RPCSettingsRequest implements Request.
RPCSettingsRequest struct{}
// RPCSettingsResponse implements Object.
RPCSettingsResponse struct {
Settings HostSettings `json:"settings"`
}
// RPCFormContractRequest implements Request.
RPCFormContractRequest struct {
Prices HostPrices `json:"prices"`
Contract types.V2FileContract `json:"contract"`
RenterInputs []types.V2SiacoinInput `json:"renterInputs"`
RenterParents []types.V2Transaction `json:"renterParents"`
}
// RPCFormContractResponse implements Object.
RPCFormContractResponse struct {
HostInputs []types.V2SiacoinInput `json:"hostInputs"`
HostParents []types.V2Transaction `json:"hostParents"`
}
// RPCFormContractSecondResponse implements Object.
RPCFormContractSecondResponse struct {
RenterContractSignature types.Signature `json:"renterContractSignature"`
RenterSatisfiedPolicies []types.SatisfiedPolicy `json:"renterSatisfiedPolicies"`
}
// RPCFormContractThirdResponse implements Object.
RPCFormContractThirdResponse struct {
HostContractSignature types.Signature `json:"hostContractSignature"`
HostSatisfiedPolicies []types.SatisfiedPolicy `json:"hostSatisfiedPolicies"`
}
// RPCRenewContractRequest implements Request.
RPCRenewContractRequest struct {
Prices HostPrices `json:"prices"`
Renewal types.V2FileContractResolution `json:"renewal"`
RenterInputs []types.V2SiacoinInput `json:"renterInputs"`
RenterParents []types.V2Transaction `json:"renterParents"`
}
// RPCRenewContractResponse implements Object.
RPCRenewContractResponse struct {
HostInputs []types.V2SiacoinInput `json:"hostInputs"`
HostParents []types.V2Transaction `json:"hostParents"`
}
// RPCRenewContractSecondResponse implements Object.
RPCRenewContractSecondResponse struct {
RenterContractSignature types.Signature `json:"renterContractSignature"`
RenterSatisfiedPolicies []types.SatisfiedPolicy `json:"renterSatisfiedPolicies"`
}
// RPCRenewContractThirdResponse implements Object.
RPCRenewContractThirdResponse struct {
HostContractSignature types.Signature `json:"hostContractSignature"`
HostSatisfiedPolicies []types.SatisfiedPolicy `json:"hostSatisfiedPolicies"`
}
// RPCModifySectorsRequest implements Request.
RPCModifySectorsRequest struct {
Prices HostPrices `json:"prices"`
Actions []WriteAction `json:"actions"`
}
// RPCModifySectorsResponse implements Object.
RPCModifySectorsResponse struct {
Proof []types.Hash256 `json:"proof"`
}
// RPCModifySectorsSecondResponse implements Object.
RPCModifySectorsSecondResponse struct {
RenterSignature types.Signature `json:"renterSignature"`
}
// RPCModifySectorsThirdResponse implements Object.
RPCModifySectorsThirdResponse struct {
HostSignature types.Signature `json:"hostSignature"`
}
// RPCLatestRevisionRequest implements Request.
RPCLatestRevisionRequest struct {
ContractID types.FileContractID `json:"contractID"`
}
// RPCLatestRevisionResponse implements Object.
RPCLatestRevisionResponse struct {
Contract types.V2FileContract `json:"contract"`
}
// RPCReadSectorRequest implements Request.
RPCReadSectorRequest struct {
Prices HostPrices `json:"prices"`
Token AccountToken `json:"token"`
Root types.Hash256 `json:"root"`
Offset uint64 `json:"offset"`
Length uint64 `json:"length"`
}
// RPCReadSectorResponse implements Object.
RPCReadSectorResponse struct {
Proof []types.Hash256 `json:"proof"`
Sector []byte `json:"sector"`
}
// RPCWriteSectorRequest implements Request.
RPCWriteSectorRequest struct {
Prices HostPrices `json:"prices"`
Token AccountToken `json:"token"`
Sector []byte `json:"sector"` // extended to SectorSize by host
}
// RPCWriteSectorResponse implements Object.
RPCWriteSectorResponse struct {
Root types.Hash256 `json:"root"`
}
// RPCSectorRootsRequest implements Request.
RPCSectorRootsRequest struct {
Prices HostPrices `json:"prices"`
ContractID types.FileContractID `json:"contractID"`
RenterSignature types.Signature `json:"renterSignature"`
Offset uint64 `json:"offset"`
Length uint64 `json:"length"`
}
// RPCSectorRootsResponse implements Object.
RPCSectorRootsResponse struct {
Proof []types.Hash256 `json:"proof"`
Roots []types.Hash256 `json:"roots"`
HostSignature types.Signature `json:"hostSignature"`
}
// RPCAccountBalanceRequest implements Request.
RPCAccountBalanceRequest struct {
Account Account `json:"account"`
}
// RPCAccountBalanceResponse implements Object.
RPCAccountBalanceResponse struct {
Balance types.Currency `json:"balance"`
}
// An AccountDeposit represents a transfer into an account.
AccountDeposit struct {
Account Account `json:"account"`
Amount types.Currency `json:"amount"`
}
// RPCFundAccountRequest implements Request.
RPCFundAccountRequest struct {
ContractID types.FileContractID `json:"contractID"`
Deposits []AccountDeposit `json:"deposits"`
RenterSignature types.Signature `json:"renterSignature"`
}
// RPCFundAccountResponse implements Object.
RPCFundAccountResponse struct {
Balances []types.Currency `json:"balances"`
HostSignature types.Signature `json:"hostSignature"`
}
)
// A Request is the initial request object for an RPC.
type Request interface {
Object
ID() types.Specifier
}
// ID implements Request.
func (RPCAccountBalanceRequest) ID() types.Specifier { return types.NewSpecifier("AccountBalance") }
// ID implements Request.
func (RPCFormContractRequest) ID() types.Specifier { return types.NewSpecifier("FormContract") }
// ID implements Request.
func (RPCFundAccountRequest) ID() types.Specifier { return types.NewSpecifier("FundAccount") }
// ID implements Request.
func (RPCLatestRevisionRequest) ID() types.Specifier { return types.NewSpecifier("LatestRevision") }
// ID implements Request.
func (RPCModifySectorsRequest) ID() types.Specifier { return types.NewSpecifier("ModifySectors") }
// ID implements Request.
func (RPCReadSectorRequest) ID() types.Specifier { return types.NewSpecifier("ReadSector") }
// ID implements Request.
func (RPCRenewContractRequest) ID() types.Specifier { return types.NewSpecifier("RenewContract") }
// ID implements Request.
func (RPCSectorRootsRequest) ID() types.Specifier { return types.NewSpecifier("SectorRoots") }
// ID implements Request.
func (RPCSettingsRequest) ID() types.Specifier { return types.NewSpecifier("Settings") }
// ID implements Request.
func (RPCWriteSectorRequest) ID() types.Specifier { return types.NewSpecifier("WriteSector") }
var idMap = map[types.Specifier]func() Request{
(RPCAccountBalanceRequest{}).ID(): func() Request { return new(RPCAccountBalanceRequest) },
(RPCFormContractRequest{}).ID(): func() Request { return new(RPCFormContractRequest) },
(RPCFundAccountRequest{}).ID(): func() Request { return new(RPCFundAccountRequest) },
(RPCLatestRevisionRequest{}).ID(): func() Request { return new(RPCLatestRevisionRequest) },
(RPCModifySectorsRequest{}).ID(): func() Request { return new(RPCModifySectorsRequest) },
(RPCReadSectorRequest{}).ID(): func() Request { return new(RPCReadSectorRequest) },
(RPCRenewContractRequest{}).ID(): func() Request { return new(RPCRenewContractRequest) },
(RPCSectorRootsRequest{}).ID(): func() Request { return new(RPCSectorRootsRequest) },
(RPCSettingsRequest{}).ID(): func() Request { return new(RPCSettingsRequest) },
(RPCWriteSectorRequest{}).ID(): func() Request { return new(RPCWriteSectorRequest) },
}
// RequestforID returns the intial request object for a given ID, or nil if the
// ID is not recognized.
func RequestforID(id types.Specifier) Request {
if r := idMap[id]; r != nil {
return r()
}
return nil
}
func NewContract(hs HostSettings, allowance, collateral types.Currency, proofHeight uint64, renterAddress types.Address, renterPublicKey, hostPublicKey types.PublicKey) types.V2FileContract {
const proofWindow = 144
return types.V2FileContract{
Filesize: 0,
FileMerkleRoot: types.Hash256{},
ProofHeight: proofHeight,
ExpirationHeight: proofHeight + proofWindow,
RenterOutput: types.SiacoinOutput{
Value: allowance,
Address: renterAddress,
},
HostOutput: types.SiacoinOutput{
Value: collateral.Add(hs.Prices.ContractPrice),
Address: hs.WalletAddress,
},
HostCollateral: collateral,
RenterPublicKey: renterPublicKey,
HostPublicKey: hostPublicKey,
RevisionNumber: 0,
}
}
func ContractCost(cs consensus.State, hs HostSettings, fc types.V2FileContract, minerFee types.Currency) (renter, host types.Currency) {
return fc.RenterOutput.Value.Add(hs.Prices.ContractPrice).Add(minerFee), fc.HostOutput.Value.Sub(hs.Prices.ContractPrice)
}
func FormContractTransaction(cs consensus.State, req RPCFormContractRequest, resp RPCFormContractResponse) types.V2Transaction {
txn := types.V2Transaction{
FileContracts: []types.V2FileContract{req.Contract},
MinerFee: types.ZeroCurrency, // TODO
}
var renterSum types.Currency
for _, sci := range req.RenterInputs {
txn.SiacoinInputs = append(txn.SiacoinInputs, sci)
renterSum = renterSum.Add(sci.Parent.SiacoinOutput.Value)
}
if change := renterSum.Sub(req.Contract.RenterOutput.Value); !change.IsZero() { // TODO
txn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{
Value: change,
Address: req.Contract.RenterOutput.Address,
})
}
var hostSum types.Currency
for _, sci := range resp.HostInputs {
txn.SiacoinInputs = append(txn.SiacoinInputs, sci)
hostSum = hostSum.Add(sci.Parent.SiacoinOutput.Value)
}
if change := hostSum.Sub(req.Contract.HostOutput.Value); !change.IsZero() { // TODO
txn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{
Value: change,
Address: req.Contract.HostOutput.Address,
})
}
return txn
}
func SignFormContractTransaction(txn *types.V2Transaction, resp2 RPCFormContractSecondResponse, resp3 RPCFormContractThirdResponse) {
txn.FileContracts[0].RenterSignature = resp2.RenterContractSignature
txn.FileContracts[0].HostSignature = resp3.HostContractSignature
for i := range txn.SiacoinInputs {
sci := &txn.SiacoinInputs[i]
if i < len(resp2.RenterSatisfiedPolicies) {
sci.SatisfiedPolicy = resp2.RenterSatisfiedPolicies[i]
} else {
sci.SatisfiedPolicy = resp3.HostSatisfiedPolicies[i-len(resp2.RenterSatisfiedPolicies)]
}
}
}
func RenewContractTransaction(cs consensus.State, req RPCRenewContractRequest, resp RPCRenewContractResponse) types.V2Transaction {
renewal := req.Renewal.Resolution.(*types.V2FileContractRenewal)
txn := types.V2Transaction{
FileContractResolutions: []types.V2FileContractResolution{req.Renewal},
MinerFee: types.ZeroCurrency, // TODO
}
var renterSum types.Currency
for _, sci := range req.RenterInputs {
txn.SiacoinInputs = append(txn.SiacoinInputs, sci)
renterSum = renterSum.Add(sci.Parent.SiacoinOutput.Value)
}
if change := renterSum.Sub(renewal.NewContract.RenterOutput.Value); !change.IsZero() { // TODO
txn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{
Value: change,
Address: renewal.NewContract.RenterOutput.Address,
})
}
var hostSum types.Currency
for _, sci := range resp.HostInputs {
txn.SiacoinInputs = append(txn.SiacoinInputs, sci)
hostSum = hostSum.Add(sci.Parent.SiacoinOutput.Value)
}
if change := hostSum.Sub(renewal.NewContract.HostOutput.Value); !change.IsZero() { // TODO
txn.SiacoinOutputs = append(txn.SiacoinOutputs, types.SiacoinOutput{
Value: change,
Address: renewal.NewContract.HostOutput.Address,
})
}
return txn
}
func SignRenewContractTransaction(txn *types.V2Transaction, resp2 RPCRenewContractSecondResponse, resp3 RPCRenewContractThirdResponse) {
txn.FileContracts[0].RenterSignature = resp2.RenterContractSignature
txn.FileContracts[0].HostSignature = resp3.HostContractSignature
for i := range txn.SiacoinInputs {
sci := &txn.SiacoinInputs[i]
if i < len(resp2.RenterSatisfiedPolicies) {
sci.SatisfiedPolicy = resp2.RenterSatisfiedPolicies[i]
} else {
sci.SatisfiedPolicy = resp3.HostSatisfiedPolicies[i-len(resp2.RenterSatisfiedPolicies)]
}
}
}
func pay(fc types.V2FileContract, amount types.Currency) types.V2FileContract {
if fc.RenterOutput.Value.Cmp(amount) < 0 {
amount = fc.RenterOutput.Value
}
fc.RenterOutput.Value = fc.RenterOutput.Value.Sub(amount)
fc.HostOutput.Value = fc.HostOutput.Value.Add(amount)
return fc
}
func pledge(fc types.V2FileContract, amount types.Currency) types.V2FileContract {
if fc.HostCollateral.Cmp(amount) < 0 {
amount = fc.HostCollateral
}
fc.HostCollateral = fc.HostCollateral.Sub(amount)
return fc
}
func ReviseForModifySectors(fc types.V2FileContract, req RPCModifySectorsRequest, resp RPCModifySectorsResponse) types.V2FileContract {
old := fc.Filesize
for _, action := range req.Actions {
switch action.Type {
case ActionAppend:
fc.Filesize += SectorSize // NOTE: ingress cost paid via account
case ActionTrim:
fc.Filesize -= SectorSize * action.N
}
}
if fc.Filesize > old {
size := fc.Filesize - old
duration := fc.ProofHeight - req.Prices.TipHeight
fc = pay(fc, req.Prices.StoragePrice.Mul64(size).Mul64(duration))
fc = pledge(fc, req.Prices.Collateral.Mul64(size).Mul64(duration))
}
fc.FileMerkleRoot = resp.Proof[len(resp.Proof)-1] // TODO
return fc
}
func ReviseForSectorRoots(fc types.V2FileContract, prices HostPrices, numRoots uint64) types.V2FileContract {
return pay(fc, prices.EgressPrice.Mul64(round4KiB(32*numRoots)))
}
func ReviseForFundAccount(fc types.V2FileContract, amount types.Currency) types.V2FileContract {
return pay(fc, amount)
}