forked from NebulousLabs/Sia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
negotiate.go
234 lines (204 loc) · 6.65 KB
/
negotiate.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
package renter
import (
"errors"
"io"
"net"
"os"
"time"
"github.com/NebulousLabs/Sia/crypto"
"github.com/NebulousLabs/Sia/encoding"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/types"
)
const (
defaultWindowSize = 288 // 48 Hours
)
// createContractTransaction takes contract terms and a merkle root and uses
// them to build a transaction containing a file contract that satisfies the
// terms, including providing an input balance. The transaction does not get
// signed.
func (r *Renter) createContractTransaction(terms modules.ContractTerms, merkleRoot crypto.Hash) (txn types.Transaction, id string, err error) {
// Get the payout as set by the missed proofs, and the client fund as determined by the terms.
sizeCurrency := types.NewCurrency64(terms.FileSize)
durationCurrency := types.NewCurrency64(uint64(terms.Duration))
clientCost := terms.Price.Mul(sizeCurrency).Mul(durationCurrency)
hostCollateral := terms.Collateral.Mul(sizeCurrency).Mul(durationCurrency)
payout := clientCost.Add(hostCollateral)
// Fill out the contract.
contract := types.FileContract{
FileMerkleRoot: merkleRoot,
FileSize: terms.FileSize,
WindowStart: terms.DurationStart + terms.Duration,
WindowEnd: terms.DurationStart + terms.Duration + terms.WindowSize,
Payout: payout,
ValidProofOutputs: terms.ValidProofOutputs,
MissedProofOutputs: terms.MissedProofOutputs,
}
// Create the transaction.
id, err = r.wallet.RegisterTransaction(txn)
if err != nil {
return
}
_, err = r.wallet.FundTransaction(id, clientCost)
if err != nil {
return
}
txn, _, err = r.wallet.AddFileContract(id, contract)
if err != nil {
return
}
return
}
// An uploadWriter writes bytes while updating the piece's 'Transferred'
// field.
type uploadWriter struct {
piece *filePiece
w io.Writer
}
// Write implements the io.Writer interface. Each write updates the filePiece's
// Transferred field. This allows upload progress to be monitored in real-time.
func (uw *uploadWriter) Write(b []byte) (int, error) {
n, err := uw.w.Write(b)
uw.piece.Transferred += uint64(n)
return n, err
}
// negotiateContract creates a file contract for a host according to the
// requests of the host. There is an assumption that only hosts with acceptable
// terms will be put into the hostdb.
func (r *Renter) negotiateContract(host modules.HostSettings, up modules.FileUploadParams, piece *filePiece) error {
lockID := r.mu.RLock()
height := r.blockHeight
r.mu.RUnlock(lockID)
key, err := crypto.GenerateTwofishKey()
if err != nil {
return err
}
file, err := os.Open(up.Filename)
if err != nil {
return err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return err
}
filesize := uint64(info.Size())
// Get the price and payout.
sizeCurrency := types.NewCurrency64(filesize)
durationCurrency := types.NewCurrency64(uint64(up.Duration))
clientCost := host.Price.Mul(sizeCurrency).Mul(durationCurrency)
hostCollateral := host.Collateral.Mul(sizeCurrency).Mul(durationCurrency)
payout := clientCost.Add(hostCollateral)
validOutputValue := payout.Sub(types.FileContract{Payout: payout}.Tax())
// Create the contract terms.
terms := modules.ContractTerms{
FileSize: filesize,
Duration: up.Duration,
DurationStart: height - 1,
WindowSize: defaultWindowSize,
Price: host.Price,
Collateral: host.Collateral,
ValidProofOutputs: []types.SiacoinOutput{
{Value: validOutputValue, UnlockHash: host.UnlockHash},
},
MissedProofOutputs: []types.SiacoinOutput{
{Value: validOutputValue, UnlockHash: types.ZeroUnlockHash},
},
}
// TODO: This is a hackish sleep, we need to be certain that all dependent
// transactions have propgated to the host's transaction pool. Instead,
// built into the protocol should be a step where any dependent
// transactions are automatically provided.
time.Sleep(types.RenterZeroConfDelay)
// Perform the negotiations with the host through a network call.
conn, err := net.DialTimeout("tcp", string(host.IPAddress), 10e9)
if err != nil {
return err
}
defer conn.Close()
err = encoding.WriteObject(conn, [8]byte{'C', 'o', 'n', 't', 'r', 'a', 'c', 't'})
if err != nil {
return err
}
// Send the contract terms and read the response.
if err = encoding.WriteObject(conn, terms); err != nil {
return err
}
var response string
if err = encoding.ReadObject(conn, &response, 128); err != nil {
return err
}
if response != modules.AcceptTermsResponse {
return errors.New(response)
}
// Encrypt and transmit the file data while calculating its Merkle root.
tee := io.TeeReader(
// wrap file reader in encryption layer
key.NewReader(file),
// each byte we read from tee will also be written to conn;
// the uploadWriter updates the piece's 'Transferred' field
&uploadWriter{piece, conn},
)
merkleRoot, err := crypto.ReaderMerkleRoot(tee)
if err != nil {
return err
}
// Create the transaction holding the contract. This is done first so the
// transaction is created sooner, which will impact the user's wallet
// balance faster vs. waiting for the whole thing to upload before
// affecting the user's balance.
unsignedTxn, txnRef, err := r.createContractTransaction(terms, merkleRoot)
if err != nil {
return err
}
// Send the unsigned transaction to the host.
err = encoding.WriteObject(conn, unsignedTxn)
if err != nil {
return err
}
// The host will respond with a transaction with the collateral added.
// Add the collateral inputs from the host to the original wallet
// transaction.
var collateralTxn types.Transaction
err = encoding.ReadObject(conn, &collateralTxn, 16e3)
if err != nil {
return err
}
for i := len(unsignedTxn.SiacoinInputs); i < len(collateralTxn.SiacoinInputs); i++ {
_, _, err = r.wallet.AddSiacoinInput(txnRef, collateralTxn.SiacoinInputs[i])
if err != nil {
return err
}
}
signedTxn, err := r.wallet.SignTransaction(txnRef, true)
if err != nil {
return err
}
// Send the signed transaction back to the host.
err = encoding.WriteObject(conn, signedTxn)
if err != nil {
return err
}
// Read an ack from the host that all is well.
var ack bool
err = encoding.ReadObject(conn, &ack, 1)
if err != nil {
return err
}
if !ack {
return errors.New("host negotiation failed")
}
// TODO: We don't actually watch the blockchain to make sure that the
// file contract made it.
// Negotiation was successful; update the filePiece.
lockID = r.mu.Lock()
piece.Active = true
piece.Repairing = false
piece.Contract = signedTxn.FileContracts[0]
piece.ContractID = signedTxn.FileContractID(0)
piece.HostIP = host.IPAddress
piece.EncryptionKey = key
r.save()
r.mu.Unlock(lockID)
return nil
}