forked from decred/gominer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getwork.go
320 lines (274 loc) · 7.18 KB
/
getwork.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
// Copyright (c) 2016 The Decred developers.
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"net"
"net/http"
"strconv"
"time"
"github.com/btcsuite/go-socks/socks"
"github.com/decred/gominer/stratum"
"github.com/decred/gominer/util"
"github.com/decred/gominer/work"
)
// newHTTPClient returns a new HTTP client that is configured according to the
// proxy and TLS settings in the associated connection configuration.
func newHTTPClient(cfg *config) (*http.Client, error) {
// Configure proxy if needed.
var dial func(network, addr string) (net.Conn, error)
if cfg.Proxy != "" {
proxy := &socks.Proxy{
Addr: cfg.Proxy,
Username: cfg.ProxyUser,
Password: cfg.ProxyPass,
}
dial = func(network, addr string) (net.Conn, error) {
c, err := proxy.Dial(network, addr)
if err != nil {
return nil, err
}
return c, nil
}
}
// Configure TLS if needed.
var tlsConfig *tls.Config
if !cfg.NoTLS && cfg.RPCCert != "" {
pem, err := ioutil.ReadFile(cfg.RPCCert)
if err != nil {
return nil, err
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(pem)
tlsConfig = &tls.Config{
RootCAs: pool,
InsecureSkipVerify: cfg.TLSSkipVerify,
}
}
// Create and return the new HTTP client potentially configured with a
// proxy and TLS.
client := http.Client{
Transport: &http.Transport{
Dial: dial,
TLSClientConfig: tlsConfig,
},
}
return &client, nil
}
type getWorkResponseJson struct {
Result struct {
Data string
Target string
}
Error *struct {
Code int
Message string
}
}
type getWorkSubmitResponseJson struct {
Result bool
Error *struct {
Code int
Message string
}
}
var (
httpClient *http.Client
)
const (
MaxIdleConnections int = 20
RequestTimeout int = 5
)
// init HTTPClient
func init() {
httpClient = createHTTPClient()
}
// createHTTPClient for connection re-use
func createHTTPClient() *http.Client {
client := &http.Client{
Transport: &http.Transport{
MaxIdleConnsPerHost: MaxIdleConnections,
},
Timeout: time.Duration(RequestTimeout) * time.Second,
}
return client
}
// GetWork makes a getwork RPC call and returns the result (data and target)
func GetWork() (*work.Work, error) {
// Generate a request to the configured RPC server.
protocol := "http"
if !cfg.NoTLS {
protocol = "https"
}
url := protocol + "://" + cfg.RPCServer
jsonStr := []byte(`{"jsonrpc": "2.0", "method": "getwork", "params": [], "id": 1}`)
bodyBuff := bytes.NewBuffer(jsonStr)
httpRequest, err := http.NewRequest("POST", url, bodyBuff)
if err != nil {
return nil, err
}
httpRequest.Close = true
httpRequest.Header.Set("Content-Type", "application/json")
// Configure basic access authorization.
httpRequest.SetBasicAuth(cfg.RPCUser, cfg.RPCPassword)
// Create the new HTTP client that is configured according to the user-
// specified options and submit the request.
httpClient, err := newHTTPClient(cfg)
if err != nil {
return nil, err
}
httpResponse, err := httpClient.Do(httpRequest)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(httpResponse.Body)
httpResponse.Body.Close()
if err != nil {
err = fmt.Errorf("error reading json reply: %v", err)
return nil, err
}
if httpResponse.Status != "200 OK" {
return nil, fmt.Errorf("HTTP %s: %s", httpResponse.Status, body)
}
var res getWorkResponseJson
err = json.Unmarshal(body, &res)
if err != nil {
return nil, err
}
if res.Error != nil {
return nil, fmt.Errorf("JSONRPC Error %d: %s", res.Error.Code,
res.Error.Message)
}
data, err := hex.DecodeString(res.Result.Data)
if err != nil {
return nil, err
}
if len(data) != 192 {
return nil, fmt.Errorf("Wrong data length: got %d, expected 192",
len(data))
}
target, err := hex.DecodeString(res.Result.Target)
if err != nil {
return nil, err
}
if len(target) != 32 {
return nil, fmt.Errorf("Wrong target length: got %d, expected 32",
len(target))
}
bigTarget := new(big.Int)
bigTarget.SetBytes(util.Reverse(target))
var workData [192]byte
copy(workData[:], data)
givenTs := binary.LittleEndian.Uint32(
workData[128+4*work.TimestampWord : 132+4*work.TimestampWord])
w := work.NewWork(workData, bigTarget, givenTs, uint32(time.Now().Unix()), true)
w.Target = bigTarget
return w, nil
}
// GetPoolWork gets work from a stratum enabled pool
func GetPoolWork(pool *stratum.Stratum) (*work.Work, error) {
// Get Next work for stratum and mark it as used
if pool.PoolWork.NewWork {
poolLog.Debug("Received new work from pool.")
// Mark used
pool.PoolWork.NewWork = false
if pool.PoolWork.JobID == "" {
return nil, fmt.Errorf("No work available (no job id)")
}
err := pool.PrepWork()
if err != nil {
return nil, err
}
intJob, _ := strconv.ParseInt(pool.PoolWork.JobID, 16, 0)
poolLog.Debugf("new job %v height %v", intJob, pool.PoolWork.Height)
return pool.PoolWork.Work, nil
}
// Return the work we already had, do not recalculate
if pool.PoolWork.Work != nil {
return pool.PoolWork.Work, nil
}
return nil, fmt.Errorf("No work available.")
}
// GetWork makes a getwork RPC call and returns the result (data and target)
func GetWorkSubmit(data []byte) (bool, error) {
// Generate a request to the configured RPC server.
protocol := "http"
if !cfg.NoTLS {
protocol = "https"
}
url := protocol + "://" + cfg.RPCServer
hexData := hex.EncodeToString(data)
jsonStr := []byte(`{"jsonrpc": "2.0", "method": "getwork", "params": ["` +
hexData + `"], "id": 1}`)
bodyBuff := bytes.NewBuffer(jsonStr)
httpRequest, err := http.NewRequest("POST", url, bodyBuff)
if err != nil {
return false, err
}
httpRequest.Close = true
httpRequest.Header.Set("Content-Type", "application/json")
// Configure basic access authorization.
httpRequest.SetBasicAuth(cfg.RPCUser, cfg.RPCPassword)
// Create the new HTTP client that is configured according to the user-
// specified options and submit the request.
httpClient, err := newHTTPClient(cfg)
if err != nil {
return false, err
}
httpResponse, err := httpClient.Do(httpRequest)
if err != nil {
return false, err
}
body, err := ioutil.ReadAll(httpResponse.Body)
httpResponse.Body.Close()
if err != nil {
err = fmt.Errorf("error reading json reply: %v", err)
return false, err
}
if httpResponse.Status != "200 OK" {
return false, fmt.Errorf("error calling getwork (%s): %s",
httpResponse.Status, body)
}
var res getWorkSubmitResponseJson
err = json.Unmarshal(body, &res)
if err != nil {
return false, err
}
if res.Error != nil {
return false, fmt.Errorf("JSONRPC Error %d: %s", res.Error.Code,
res.Error.Message)
}
return res.Result, nil
}
// GetPoolWorkSubmit sends the result to the stratum enabled pool
func GetPoolWorkSubmit(data []byte, pool *stratum.Stratum) (bool, error) {
pool.Lock()
defer pool.Unlock()
sub, err := pool.PrepSubmit(data)
if err != nil {
return false, err
}
// JSON encode.
m, err := json.Marshal(sub)
if err != nil {
return false, err
}
// Send.
poolLog.Tracef("%s", m)
_, err = pool.Conn.Write(m)
if err != nil {
return false, err
}
_, err = pool.Conn.Write([]byte("\n"))
if err != nil {
return false, err
}
return true, nil
}