forked from sammy007/open-ethereum-pool
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stratum_nicehash.go
359 lines (311 loc) · 7.96 KB
/
stratum_nicehash.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
package proxy
import (
"net"
"log"
"encoding/json"
"bufio"
"io"
"errors"
"time"
"github.com/gompa/open-ethereum-pool/util"
"math/rand"
"strings"
)
func (s *ProxyServer) ListenNiceHashTCP(){
timeout := util.MustParseDuration(s.config.Proxy.StratumNiceHash.Timeout)
s.timeout = timeout
addr, err := net.ResolveTCPAddr("tcp4", s.config.Proxy.StratumNiceHash.Listen)
if err != nil {
log.Fatalf("Error: %v", err)
}
server, err := net.ListenTCP("tcp4", addr)
if err != nil {
log.Fatalf("Error: %v", err)
}
defer server.Close()
log.Printf("Stratum NiceHash listening on %s", s.config.Proxy.StratumNiceHash.Listen)
var accept = make(chan int, s.config.Proxy.StratumNiceHash.MaxConn)
n := 0
for {
conn, err := server.AcceptTCP()
if err != nil {
continue
}
conn.SetKeepAlive(true)
ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
if s.policy.IsBanned(ip) || !s.policy.ApplyLimitPolicy(ip) {
conn.Close()
continue
}
n += 1
cs := &Session{conn: conn, ip: ip}
accept <- n
go func(cs *Session) {
err = s.handleNHTCPClient(cs)
if err != nil {
s.removeSession(cs)
conn.Close()
}
<-accept
}(cs)
}
}
func (s *ProxyServer) handleNHTCPClient(cs *Session) error {
cs.enc = json.NewEncoder(cs.conn)
connbuff := bufio.NewReaderSize(cs.conn, MaxReqSize)
s.setDeadline(cs.conn)
for {
data, isPrefix, err := connbuff.ReadLine()
if isPrefix {
log.Printf("Socket flood detected from %s", cs.ip)
s.policy.BanClient(cs.ip)
return err
} else if err == io.EOF {
log.Printf("Client %s disconnected", cs.ip)
s.removeSession(cs)
break
} else if err != nil {
log.Printf("Error reading from socket: %v", err)
return err
}
if len(data) > 1 {
var req StratumReq
err = json.Unmarshal(data, &req)
if err != nil {
s.policy.ApplyMalformedPolicy(cs.ip)
log.Printf("Malformed stratum request from %s: %v", cs.ip, err)
return err
}
s.setDeadline(cs.conn)
err = cs.handleNHTCPMessage(s, &req)
if err != nil {
return err
}
}
}
return nil
}
func generateRandomString(strlen int) string {
rand.Seed(time.Now().UTC().UnixNano())
const chars = "abcdefghijklmnopqrstuvwxyz0123456789"
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = chars[rand.Intn(len(chars))]
}
return string(result)
}
func(cs *Session) getNotificationResponse(s *ProxyServer, id *json.RawMessage) JSONRpcResp {
if s.Extranonce == ""{
s.Extranonce = generateRandomString(4)
}
result := make([]interface{}, 2)
param1 := make([]string, 3)
param1[0] = "mining.notify"
param1[1] = generateRandomString(32)
param1[2] = "EthereumStratum/1.0.0"
result[0] = param1
result[1] = s.Extranonce
resp := JSONRpcResp{
Id:id,
Version:"EthereumStratum/1.0.0",
Result:result,
Error: nil,
}
return resp
}
func(cs *Session) sendTCPNHError(id *json.RawMessage, message interface{}) error{
cs.Mutex.Lock()
defer cs.Mutex.Unlock()
resp := JSONRpcResp{Id: id, Error: message}
return cs.enc.Encode(&resp)
}
func(cs *Session) sendTCPNHResult(resp JSONRpcResp) error {
cs.Mutex.Lock()
defer cs.Mutex.Unlock()
return cs.enc.Encode(&resp)
}
func(cs *Session) sendTCPNHReq(resp JSONRpcReqNH) error {
cs.Mutex.Lock()
defer cs.Mutex.Unlock()
return cs.enc.Encode(&resp)
}
func(cs *Session) sendJob(s *ProxyServer, id *json.RawMessage) error {
reply, errReply := s.handleGetWorkRPC(cs)
if errReply != nil {
return cs.sendTCPNHError(id, []string{
string(errReply.Code),
errReply.Message,
})
}
cs.JobDeatils = jobDetails{
JobID: generateRandomString(8),
SeedHash: reply[1],
HeaderHash: reply[0],
}
resp := JSONRpcReqNH{
Method:"mining.notify",
Params: []interface{}{
cs.JobDeatils.JobID,
cs.JobDeatils.SeedHash,
cs.JobDeatils.HeaderHash,
true,
},
}
return cs.sendTCPNHReq(resp)
}
func (cs *Session) handleNHTCPMessage(s *ProxyServer, req *StratumReq) error {
// Handle RPC methods
switch req.Method {
case "mining.subscribe":
var params []string
err := json.Unmarshal(*req.Params, ¶ms)
if err != nil {
log.Println("Malformed stratum request params from", cs.ip)
return err
}
if params[1] != "EthereumStratum/1.0.0"{
log.Println("Unsupported stratum version from ", cs.ip)
return cs.sendTCPNHError(req.Id, "unsupported ethereum version")
}
resp := cs.getNotificationResponse(s, req.Id)
return cs.sendTCPNHResult(resp)
case "mining.authorize":
var params []string
err := json.Unmarshal(*req.Params, ¶ms)
if err != nil {
return errors.New("invalid params")
}
splitData := strings.Split(params[0], ".")
params[0] = splitData[0]
reply , errReply := s.handleLoginRPC(cs, params, req.Worker)
if errReply != nil {
return cs.sendTCPNHError(req.Id, []string{
string(errReply.Code),
errReply.Message,
})
}
resp := JSONRpcResp{Id:req.Id, Result:reply, Error:nil}
if err := cs.sendTCPNHResult(resp); err != nil{
return err
}
paramsDiff := []int64{
s.config.Proxy.Difficulty,
}
respReq := JSONRpcReqNH{Method:"mining.set_difficulty", Params:paramsDiff}
if err := cs.sendTCPNHReq(respReq); err != nil {
return err
}
return cs.sendJob(s, req.Id)
case "mining.submit":
var params []string
if err := json.Unmarshal(*req.Params, ¶ms); err != nil{
return err
}
splitData := strings.Split(params[0], ".")
id := splitData[1]
if cs.JobDeatils.JobID != params[1] {
return cs.sendTCPNHError(req.Id, "wrong job id")
}
nonce := s.Extranonce + params[2]
params = []string{
nonce,
cs.JobDeatils.SeedHash,
cs.JobDeatils.SeedHash,
}
reply, errReply := s.handleTCPSubmitRPC(cs, id, params)
if errReply != nil {
return cs.sendTCPNHError(req.Id, []string{
string(errReply.Code),
errReply.Message,
})
}
resp := JSONRpcResp{
Id: req.Id,
Result: reply,
}
if err := cs.sendTCPNHResult(resp); err != nil{
return err
}
return cs.sendJob(s, req.Id)
case "eth_submitLogin":
var params []string
err := json.Unmarshal(*req.Params, ¶ms)
if err != nil {
log.Println("Malformed stratum request params from", cs.ip)
return err
}
reply, errReply := s.handleLoginRPC(cs, params, req.Worker)
if errReply != nil {
return cs.sendTCPError(req.Id, errReply)
}
return cs.sendTCPResult(req.Id, reply)
case "eth_getWork":
reply, errReply := s.handleGetWorkRPC(cs)
if errReply != nil {
return cs.sendTCPError(req.Id, errReply)
}
return cs.sendTCPResult(req.Id, &reply)
case "eth_submitWork":
var params []string
err := json.Unmarshal(*req.Params, ¶ms)
if err != nil {
log.Println("Malformed stratum request params from", cs.ip)
return err
}
reply, errReply := s.handleTCPSubmitRPC(cs, req.Worker, params)
if errReply != nil {
return cs.sendTCPError(req.Id, errReply)
}
return cs.sendTCPResult(req.Id, &reply)
case "eth_submitHashrate":
return cs.sendTCPResult(req.Id, true)
default:
errReply := s.handleUnknownRPC(cs, req.Method)
return cs.sendTCPNHError(req.Id, []string{
string(errReply.Code),
errReply.Message,
})
}
}
func (s *ProxyServer) broadcastNewJobsNH() {
t := s.currentBlockTemplate()
if t == nil || len(t.Header) == 0 || s.isSick() {
return
}
s.sessionsMu.RLock()
defer s.sessionsMu.RUnlock()
count := len(s.sessions)
log.Printf("Broadcasting new job to %v stratumnice hash miners", count)
start := time.Now()
bcast := make(chan int, 1024)
n := 0
for m, _ := range s.sessions {
n++
bcast <- n
go func(cs *Session) {
cs.JobDeatils = jobDetails{
JobID: generateRandomString(8),
SeedHash: t.Seed,
HeaderHash: t.Header,
}
resp := JSONRpcReqNH{
Method:"mining.notify",
Params: []interface{}{
cs.JobDeatils.JobID,
cs.JobDeatils.SeedHash,
cs.JobDeatils.HeaderHash,
true,
},
}
err := cs.sendTCPNHReq(resp)
<-bcast
if err != nil {
log.Printf("Job transmit error to %v@%v: %v", cs.login, cs.ip, err)
s.removeSession(cs)
} else {
s.setDeadline(cs.conn)
}
}(m)
}
log.Printf("Jobs broadcast finished %s", time.Since(start))
}