-
Notifications
You must be signed in to change notification settings - Fork 13
/
proofer.go
401 lines (329 loc) · 8.99 KB
/
proofer.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
// SPDX-License-Identifier: ISC
// Copyright (c) 2014-2019 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"encoding/binary"
"encoding/json"
"fmt"
"math"
"runtime"
"sync"
"sync/atomic"
"time"
zmq "github.com/pebbe/zmq4"
"github.com/bitmark-inc/bitmarkd/blockdigest"
"github.com/bitmark-inc/bitmarkd/blockrecord"
"github.com/bitmark-inc/exitwithstatus"
"github.com/bitmark-inc/logger"
)
const (
proofRequest = "inproc://blocks.request" // to fair-queue block requests
dispatch = "inproc://blocks.dispatch" // proofer fetches from here
errorProoferID = -1
prooferLoggerPrefix = "proofer"
)
var (
proofQueueDepth uint64
)
type Proofer interface {
StartHashing()
StopHashing()
IsWorking() bool
Refresh()
}
type ProoferData struct {
sync.RWMutex
eventuallyThreadCount uint32
prevThreadCount uint32
proofIDs []bool
stopChannel chan struct{}
log *logger.L
workingNow bool
cpuCount int
reader ConfigReader
}
func newProofer(log *logger.L, reader ConfigReader) Proofer {
cpuCount := runtime.NumCPU()
return &ProoferData{
log: log,
proofIDs: make([]bool, cpuCount),
stopChannel: make(chan struct{}, cpuCount),
cpuCount: cpuCount,
workingNow: true,
reader: reader,
}
}
func (p *ProoferData) StartHashing() {
p.log.Infof("receive start hashing request, current active thread %d",
p.targetThreadCount())
p.setWorking(true)
if p.targetThreadCount() < 1 {
p.createProofer(p.reader.OptimalThreadCount())
}
}
func (p *ProoferData) StopHashing() {
p.log.Infof("receive stop hashing request, current active thread %d",
p.targetThreadCount())
p.setWorking(false)
p.deleteProofer(int32(p.targetThreadCount()))
}
func (p *ProoferData) deleteProofer(count int32) {
p.log.Infof("delete %d goroutine from hashing", count)
for i := int32(0); i < count; i++ {
p.eventuallyThreadCount--
p.log.Debug("send signal to stop channel")
p.stopChannel <- struct{}{}
}
}
func (p *ProoferData) IsWorking() bool {
return p.workingNow
}
func (p *ProoferData) setWorking(working bool) {
p.workingNow = working
}
func (p *ProoferData) Refresh() {
p.log.Infof("goroutine active count: %d, target count: %d",
p.targetThreadCount(),
p.reader.OptimalThreadCount(),
)
p.log.Infof("proofer setting change: %t, workable: %t",
p.changed(),
p.IsWorking(),
)
if !p.changed() || !p.IsWorking() {
return
}
increment := p.differenceToTargetThreadCount(
p.reader.OptimalThreadCount(),
p.targetThreadCount(),
)
p.log.Infof("refresh settings, active goroutine %d, increase %d goroutine from hashing",
p.targetThreadCount(), increment)
if increment > 0 {
p.createProofer(uint32(increment))
return
}
p.deleteProofer(-increment)
}
func (p *ProoferData) changed() bool {
return p.prevThreadCount != p.reader.OptimalThreadCount()
}
func (p *ProoferData) activeThreadIncrement(threadNum uint32) {
p.Lock()
defer p.Unlock()
p.proofIDs[threadNum] = true
}
func (p *ProoferData) activeThreadDecrement(threadNum uint32) {
p.Lock()
defer p.Unlock()
p.proofIDs[threadNum] = false
}
func (p *ProoferData) targetThreadCount() uint32 {
p.Lock()
defer p.Unlock()
return p.eventuallyThreadCount
}
func ProofQueueIncrement() {
atomic.AddUint64(&proofQueueDepth, 1)
}
func ProofQueueDecrement() {
atomic.AddUint64(&proofQueueDepth, 0xffffffffffffffff)
}
// this provides a single submission point for hashing requests
// multiple proof threads can attach and fair queuing takes place
func ProofProxy() {
go func() {
err := proofForwarder()
logger.PanicIfError("proofProxy", err)
}()
}
// internal proxy forwarding loop
func proofForwarder() error {
in, err := zmq.NewSocket(zmq.PULL)
if nil != err {
return err
}
defer in.Close()
in.SetLinger(0)
err = in.Bind(proofRequest)
if nil != err {
return err
}
out, err := zmq.NewSocket(zmq.PUSH)
if nil != err {
return err
}
defer out.Close()
_ = out.SetLinger(0)
err = out.Bind(dispatch)
if nil != err {
return err
}
// possibly use this: ProxySteerable(frontend, backend, capture, control *Socket) error
// with a control socket for clean shutdown
return zmq.Proxy(in, out, nil)
}
func (p *ProoferData) nextProoferID() (int, error) {
var idx int
found := false
loop:
for k, v := range p.proofIDs {
if !v {
idx = k
found = true
break loop
}
}
if !found {
return errorProoferID, fmt.Errorf("all proofer are used, abort")
}
return idx, nil
}
func (p *ProoferData) createProofer(threadCount uint32) {
p.log.Infof("increase %d goroutine for hashing", threadCount)
for i := uint32(0); i < threadCount; i++ {
p.eventuallyThreadCount++
proofID, err := p.nextProoferID()
if nil != err {
return
}
prflog := logger.New(fmt.Sprintf("proofer-%d", proofID))
prflog.Infof("add new goroutine (%d out of this round increament %d)",
i+1, threadCount)
err = p.ProofThread(prflog, uint32(proofID))
if nil != err {
prflog.Criticalf("proof[%d]: error: %s", proofID, err)
exitwithstatus.Message("proofer: proof[%d]: error: %s", proofID, err)
}
}
}
func (p *ProoferData) differenceToTargetThreadCount(
targetThreadCount,
currentThreadCount uint32,
) int32 {
difference := int32(targetThreadCount) - int32(currentThreadCount)
if math.Abs(float64(difference)) < math.Abs(float64(p.cpuCount)) {
return int32(difference)
}
if targetThreadCount > currentThreadCount {
return int32(p.cpuCount)
}
return int32(-p.cpuCount + 1)
}
func (p *ProoferData) ProofThread(log *logger.L, threadNum uint32) error {
log.Infof("starting goroutine %d…", threadNum)
// block request channel
request, err := zmq.NewSocket(zmq.PULL)
if nil != err {
return err
}
request.SetLinger(0)
err = request.Connect(dispatch)
if nil != err {
request.Close()
return err
}
submit, err := zmq.NewSocket(zmq.PUSH)
if nil != err {
request.Close()
return err
}
submit.SetLinger(0)
err = submit.Connect(submission)
if nil != err {
request.Close()
submit.Close()
return err
}
// go auth_do_handler()
// // basic socket options
// //socket.SetIpv6(true) // ***** FIX THIS find fix for FreeBSD libzmq4 ****
// socket.SetSndtimeo(SEND_TIMEOUT)
// socket.SetLinger(LINGER_TIME)
// socket.SetRouterMandatory(0) // discard unroutable packets
// socket.SetRouterHandover(true) // allow quick reconnect for a given public key
// socket.SetImmediate(false) // queue messages sent to disconnected peer
poller := zmq.NewPoller()
poller.Add(request, zmq.POLLIN)
p.activeThreadIncrement(threadNum)
// background process
go func() {
defer request.Close()
defer p.activeThreadDecrement(threadNum)
receiver:
for {
request, err := request.RecvMessageBytes(0)
if nil != err {
log.Criticalf("RecvMessageBytes error: %s", err)
logger.Panicf("proofer error: %s", err)
}
ProofQueueDecrement()
log.Infof("received data: %s", request)
// flush short messages
if len(request) < 2 {
continue receiver
}
// split message request
submitter := request[0]
block := request[1]
MaximumSeconds := 120 * time.Second
var item PublishedItem
json.Unmarshal(block, &item)
log.Infof("received item: %v", item)
// attempt to determine nonce
timeout := time.After(MaximumSeconds)
start := time.Now()
count := 0
blk := item.Header
nonceLoop:
for i := 0; true; i++ {
select {
case <-timeout:
break nonceLoop
case <-p.stopChannel:
log.Infof("proofer %d receive stop event, terminate", threadNum)
break receiver
default:
readyList, _ := poller.Poll(0) // time.Millisecond)
//log.Infof("ready list: %v", readyList)
//log.Infof("ready list length: %d", len(readyList))
if 1 == len(readyList) {
log.Info("new request, break nonceLoop")
break nonceLoop
}
}
// adjust Nonce, and compute new digest
blk.Nonce++
packed := blk.Pack()
digest := blockdigest.NewDigest(packed[:])
count++
if 0 == i%10 {
log.Infof("nonce[%d]: 0x%08x", i, blk.Nonce)
}
// possible value if leading zero byte
if 0 == digest[31] {
log.Infof("job: %q nonce: 0x%016x", item.Job, blk.Nonce)
log.Infof("digest: %v", digest)
nonce := make([]byte, blockrecord.NonceSize)
binary.LittleEndian.PutUint64(nonce, uint64(blk.Nonce))
_, err := submit.SendBytes(submitter, zmq.SNDMORE) // routing address
logger.PanicIfError("submit send", err)
_, err = submit.SendBytes(submitter, zmq.SNDMORE) // destination check
logger.PanicIfError("submit send", err)
_, err = submit.Send(item.Job, zmq.SNDMORE) // job id
logger.PanicIfError("submit send", err)
_, err = submit.SendBytes(nonce, 0) // actual data
logger.PanicIfError("submit send", err)
// ************** if actual difficulty is met
// if ... { break nonceLoop }
}
}
// compute hash rate
rate := float64(count) / time.Since(start).Minutes()
log.Infof("hash rate: %f H/min", rate)
}
}()
return nil
}