/
Farm.h
717 lines (611 loc) · 21.7 KB
/
Farm.h
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Farm.h
* @author Gav Wood <i@gavwood.com>
* @date 2015
*/
#pragma once
#include <thread>
#include <list>
#include <atomic>
#include <libdevcore/Common.h>
#include <libdevcore/Worker.h>
#include <libethcore/Common.h>
#include <libethcore/Miner.h>
#include <libethcore/BlockInfo.h>
#include <ethminer/DataLogger.h>
#include <ethminer/MultiLog.h>
namespace dev
{
namespace eth
{
// pause mining after this number of retries (lost comm with node)
unsigned const c_StopWorkAt = 4;
/*-----------------------------------------------------------------------------------
* class GenericFarm
*----------------------------------------------------------------------------------*/
template <class PoW>
class GenericFarm
{
public:
using WorkPackage = typename PoW::WorkPackage;
using Solution = typename PoW::Solution;
using Miner = GenericMiner<PoW>;
using BestHashFn = boost::function<void(uint64_t const)>;
using SetWorkFn = boost::function<void(uint64_t const)>;
using SolutionProcessedFn = boost::function<bool(unsigned, SolutionState, bool, int)>;
using CloseHitFn = boost::function<bool(uint64_t const, unsigned const, int const)>;
using HashFaultFn = boost::function<bool(int const)>;
using CountInstancesFn = std::function<unsigned()>;
using CreateInstanceFn = std::function<GenericMiner<PoW>*(GenericFarm<PoW>* _farm, unsigned _index)>;
typedef std::vector<GenericMiner<PoW>*> miners_t;
/*-----------------------------------------------------------------------------------
* class HashRates
*----------------------------------------------------------------------------------*/
class HashRates
{
public:
// this maintains hashrates per miner. all rates are MH/s.
// you need to call update before retrieving farmRate or minerRates.
HashRates(GenericFarm<PoW>* _f) : m_farm(_f) {}
void init()
{
for (std::size_t i = 0; i < m_farm->minerCount(); i++)
m_minerRates.push_back(EMA(3));
}
/**
* @brief gather and compute latest hash rates.
*/
void update()
{
WriteGuard l(x_hashRates);
m_farmRate = 0;
std::string rates;
for (std::size_t i = 0; i < m_farm->minerCount(); i++)
{
m_minerRates[i].newVal(m_farm->m_miners[i]->getHashRate());
rates.append(toString(m_minerRates[i].value()) + ", ");
m_farmRate += m_minerRates[i].value();
}
rates.resize(rates.size() - 2);
LogF << "HashRates.update: " << m_farmRate << " [" << rates << "]";
}
friend std::ostream& operator<< (std::ostream &out, const HashRates &rates)
{
std::string sep;
char szBuff[20];
ReadGuard l(rates.x_hashRates);
sprintf(szBuff, " %.1f", rates.m_farmRate);
out << szBuff << " MH/s";
if (rates.m_minerRates.size() > 1)
{
out << " [";
for (std::size_t i = 0; i < rates.m_farm->minerCount(); i++)
{
sprintf(szBuff, "%.1f", rates.minerRate(i));
out << sep << szBuff;
sep = ", ";
}
out << "]";
}
if (rates.m_farm->anyThrottling())
out << " - THROTTLING!! ";
return out;
}
float farmRate()
{
ReadGuard l(x_hashRates);
return m_farmRate;
}
float minerRate(int _miner) const
{
ReadGuard l(x_hashRates);
return m_minerRates[_miner].value();
}
// return true if any of the miner hash rates have changed by more than _delta.
// you need to call update() first before calling this.
// currently there is no support for obtaining delta change info on the farm rate.
void deltaExceeded(float _delta, bool& _deltaExceeded)
{
_deltaExceeded = false;
if (m_lastReportedRate.size() == 0)
{
// first time here. fill lastReported vectors with zeros.
m_lastReportedRate.assign(m_farm->minerCount(), 0);
}
for (int i = 0; i < m_minerRates.size(); i++)
{
if (abs(m_minerRates[i].value() - m_lastReportedRate[i]) >= _delta)
{
_deltaExceeded = true;
m_lastReportedRate[i] = m_minerRates[i].value();
}
}
}
GenericFarm<PoW>* m_farm = nullptr;
private:
mutable SharedMutex x_hashRates;
std::vector<EMA> m_minerRates;
std::vector<float> m_lastReportedRate; // used for delta change calculations
float m_farmRate = 0;
}; // class HashRates
//////////////////////////////////////////////////////////////////////////////////////////////
/*-----------------------------------------------------------------------------------
* GenericFarm Constructor
*----------------------------------------------------------------------------------*/
GenericFarm(OperationMode _opMode = OperationMode::None) : m_onBestHash(NULL)
{
m_opMode = _opMode;
m_hashRates = new HashRates(this);
if (ProgOpt::Get("CloseHits", "Enabled") == "1")
{
closeHitThreshold = std::stoull(ProgOpt::Get("CloseHits", "CloseHitThreshold").c_str());
workUnitFreq = std::stoull(ProgOpt::Get("CloseHits", "WorkUnitFrequency").c_str());
}
}
~GenericFarm()
{
stop();
}
/*-----------------------------------------------------------------------------------
* setWork
*----------------------------------------------------------------------------------*/
void setWork(bytes _challenge, h256 _target)
{
LogF << "Trace: GenericFarm::setWork, challenge=" << toHex(_challenge).substr(0, 8)
<< ", target=" << std::hex << std::setw(16) << std::setfill('0') << upper64OfHash(_target);
WriteGuard l(x_minerWork);
if (_challenge == m_challenge && _target == m_target)
return;
m_challenge = _challenge;
m_target = _target;
for (auto const& m: m_miners)
m->setWork(m_challenge, m_target);
}
/*-----------------------------------------------------------------------------------
* start
*----------------------------------------------------------------------------------*/
void start(const miners_t& _miners)
{
LogF << "Trace: GenericFarm.start";
WriteGuard l(x_minerWork);
m_miners = _miners;
m_hashFaults.assign(m_miners.size(), 0);
m_bestHash = logger.retrieveBestHash();
m_hashRates->init();
// can't call setWork until we've initialized the hash rates
//for (auto const& m : m_miners)
// m->setWork_token(m_challenge, m_target);
LogF << "Trace: GenericFarm.start [exit]";
}
/*-----------------------------------------------------------------------------------
* pauseMining
*----------------------------------------------------------------------------------*/
void pauseMining()
{
for (auto const& m : m_miners)
m->pause();
}
/*-----------------------------------------------------------------------------------
* stop
*----------------------------------------------------------------------------------*/
void stop()
{
LogF << "Trace: GenericFarm.stop";
WriteGuard l(x_minerWork);
m_miners.clear();
m_isMining = false;
}
/*-----------------------------------------------------------------------------------
* isMining
*----------------------------------------------------------------------------------*/
bool isMining()
{
return m_isMining;
}
/*-----------------------------------------------------------------------------------
* setIsMining
*----------------------------------------------------------------------------------*/
void setIsMining(bool _isMining)
{
m_isMining = _isMining;
}
/*-----------------------------------------------------------------------------------
* currentHash
*----------------------------------------------------------------------------------*/
uint64_t currentHash(int _miner)
{
// Retrieve a random hash value from the specified miner.
return m_miners[_miner]->currentHash();
}
/*-----------------------------------------------------------------------------------
* bestHash
*----------------------------------------------------------------------------------*/
uint64_t bestHash()
{
// Retrieve the current bestHash value over all miners.
ReadGuard l(x_bestHash);
return m_bestHash;
}
/*-----------------------------------------------------------------------------------
* suggestBestHash
*----------------------------------------------------------------------------------*/
void suggestBestHash(uint64_t _bh)
{
// One of the miners has found a better hash. record it if it's the best overall.
if (_bh < m_bestHash)
{
LogF << "Trace: GenericFarm::suggestBestHash : hash improvement = " << _bh;
WriteGuard l(x_bestHash);
m_bestHash = _bh;
logger.recordBestHash(_bh);
if (m_onBestHash)
m_onBestHash(_bh);
}
}
/*-----------------------------------------------------------------------------------
* onBestHash
*----------------------------------------------------------------------------------*/
void onBestHash(BestHashFn const& _handler)
{
// set a handler for best hash event. typically a call MVisRPC, which will send
// notification to MVis.
m_onBestHash = _handler;
}
/*-----------------------------------------------------------------------------------
* reportCloseHit
*----------------------------------------------------------------------------------*/
void reportCloseHit(uint64_t _closeHit, unsigned _work, int _miner)
{
// Miner is letting us know it found a close hit. work is the number of seconds elapsed
// since the previous close hit.
LogF << "Trace: GenericFarm::reportCloseHit : closeHit = " << _closeHit << ", miner = " << _miner;
m_closeHits++;
m_lastCloseHit = _closeHit;
// if we're connected to MVis, inform it of the close hit, otherwise log to disk
if (!m_onCloseHit || !m_onCloseHit(_closeHit, _work, _miner))
logger.recordCloseHit(_closeHit, _work, _miner);
}
/*-----------------------------------------------------------------------------------
* getCloseHits
*----------------------------------------------------------------------------------*/
std::string getCloseHits()
{
// formatted for screen output
std::stringstream s;
s << "Work units: " << m_closeHits << ", Last: ";
if (m_closeHits == 0)
s << "...";
else
s << m_lastCloseHit;
return s.str();
}
/*-----------------------------------------------------------------------------------
* onCloseHit
*----------------------------------------------------------------------------------*/
void onCloseHit(CloseHitFn const& _handler)
{
// set a handler for the close hit event. typically a call to MVisRPC, which will
// send notification to MVis.
m_onCloseHit = _handler;
}
/*-----------------------------------------------------------------------------------
* setCloseHitThresholds
*----------------------------------------------------------------------------------*/
void setCloseHitThresholds(uint64_t _closeHitThreshold, uint64_t _workUnitFreq)
{
// _closeHitThreshold is expressed as a literal hash value.
// _workUnitFreq is expressed as the desired number of seconds between close hits. each
// miner is responsible to convert this to a hash value based on their current hash rate.
closeHitThreshold = _closeHitThreshold;
workUnitFreq = _workUnitFreq;
for (auto const& m : m_miners)
m->calcWorkUnitThreshold();
// write the values to the ini file as well.
ProgOpt::beginUpdating();
ProgOpt::Put("CloseHits", "CloseHitThreshold", _closeHitThreshold);
ProgOpt::Put("CloseHits", "WorkUnitFrequency", _workUnitFreq);
ProgOpt::endUpdating();
}
/*-----------------------------------------------------------------------------------
* reportHashFault
*----------------------------------------------------------------------------------*/
void reportHashFault(int _miner)
{
// Miner is letting us know it experienced a hash fault.
LogF << "Trace: GenericFarm::reportHashFault : miner = " << _miner;
// keep track of numbers for this session
m_hashFaults[_miner]++;
// if we're connected to MVis, inform it of the hash fault, otherwise log to disk
if (!m_onHashFault || !m_onHashFault(_miner))
logger.recordHashFault(_miner);
}
/*-----------------------------------------------------------------------------------
* onHashFault
*----------------------------------------------------------------------------------*/
void onHashFault(HashFaultFn const& _handler)
{
// set a handler for the hash fault event. typically a call to MVisRPC, which will
// send notification to MVis.
m_onHashFault = _handler;
}
/*-----------------------------------------------------------------------------------
* getHashFaults
*----------------------------------------------------------------------------------*/
std::string getHashFaults()
{
// formatted for screen output
std::string sep;
std::stringstream s;
for (auto const& fault : m_hashFaults)
{
s << sep << fault;
sep = ", ";
}
return s.str();
}
/*-----------------------------------------------------------------------------------
* onSolutionProcessed
*----------------------------------------------------------------------------------*/
void onSolutionProcessed(SolutionProcessedFn const& _handler)
{
// set a handler for the solution processed event. typically a call to MVisRPC so
// it can notify MVis. this event occurs after we have sent the potential
// solution to the node for acceptance, and have received a response back.
m_onSolutionProcessed = _handler;
}
/*-----------------------------------------------------------------------------------
* recordSolution
*----------------------------------------------------------------------------------*/
void recordSolution(SolutionState _state, bool _stale, int _miner)
{
// we're being notified (typically by the main loop) as to the acceptance
// state of a recent solution.
if (_state == SolutionState::Accepted)
{
//LogB << ":) Submitted and accepted.";
if (_stale)
m_solutionStats.acceptedStale();
else
m_solutionStats.accepted();
}
else if (_state == SolutionState::Rejected)
{
//LogB << ":-( Not accepted.";
if (_stale)
m_solutionStats.rejectedStale();
else
m_solutionStats.rejected();
}
else
{
//LogB << "FAILURE: GPU gave incorrect result!";
m_solutionStats.failed();
}
resetBestHash();
} // recordSolution
/*-----------------------------------------------------------------------------------
* resetBestHash
*----------------------------------------------------------------------------------*/
void resetBestHash()
{
LogF << "Trace: GenericFarm.resetBestHash";
for (auto const& m : m_miners)
m->resetBestHash();
WriteGuard l(x_bestHash);
m_bestHash = ~uint64_t(0);
}
/*-----------------------------------------------------------------------------------
* getSolutionStats
*----------------------------------------------------------------------------------*/
SolutionStats getSolutionStats() {
return m_solutionStats;
}
/*-----------------------------------------------------------------------------------
* minerCount
*----------------------------------------------------------------------------------*/
int minerCount()
{
return m_miners.size();
}
/*-----------------------------------------------------------------------------------
* hashRates
*----------------------------------------------------------------------------------*/
HashRates& hashRates()
{
return *m_hashRates;
}
/*-----------------------------------------------------------------------------------
* getMinerTemps (overloaded)
*----------------------------------------------------------------------------------*/
void getMinerTemps(std::vector<double>& _temps)
{
_temps.clear();
for (auto const& m : m_miners)
_temps.push_back(m->gpuTemp());
}
/*-----------------------------------------------------------------------------------
* getMinerTemps (overloaded)
*----------------------------------------------------------------------------------*/
std::string getMinerTemps()
{
// formatted for screen output
std::string sep;
std::stringstream s;
for (auto const& m : m_miners)
{
s << sep << m->gpuTemp();
sep = ", ";
}
return s.str();
}
/*-----------------------------------------------------------------------------------
* getFanSpeeds (overloaded)
*----------------------------------------------------------------------------------*/
void getFanSpeeds(std::vector<int>& _speeds)
{
_speeds.clear();
for (auto const& m : m_miners)
_speeds.push_back(m->fanSpeed());
}
/*-----------------------------------------------------------------------------------
* getFanSpeeds (overloaded)
*----------------------------------------------------------------------------------*/
std::string getFanSpeeds()
{
// formatted for screen output
std::string sep;
std::stringstream s;
for (auto const& m : m_miners)
{
s << sep << m->fanSpeed();
sep = ", ";
}
return s.str();
}
/*-----------------------------------------------------------------------------------
* setGpuThrottle
*----------------------------------------------------------------------------------*/
void setGpuThrottle(int _gpu, int _percent)
{
m_miners.at(_gpu)->setThrottle(_percent);
}
/*-----------------------------------------------------------------------------------
* anyThrottling
*----------------------------------------------------------------------------------*/
bool anyThrottling(void)
{
// return true if any of the miners are throttling.
int t = 0;
for (auto const& m : m_miners)
t += m->throttle();
return (t > 0);
}
/*-----------------------------------------------------------------------------------
* thermalProtection
*----------------------------------------------------------------------------------*/
void thermalProtection(int _neverExceed, double _safetyShutdown)
{
for (auto const& m : m_miners)
m->thermalProtection(_neverExceed, _safetyShutdown);
// persist these settings to disk.
ProgOpt::beginUpdating();
ProgOpt::Put("ThermalProtection", "ThrottleTemp", _neverExceed);
ProgOpt::Put("ThermalProtection", "ShutDown", _safetyShutdown);
ProgOpt::endUpdating();
}
/*-----------------------------------------------------------------------------------
* tunePIDController
*----------------------------------------------------------------------------------*/
void tunePIDController(int _gpu, double _kp, double _ki, double _kd)
{
m_miners.at(_gpu)->tunePIDController(_kp, _ki, _kd);
}
/**
* @brief Called from a Miner to note a WorkPackage has a solution.
* @return true if the solution was good and the Farm should pause until more work is submitted.
*/
/*-----------------------------------------------------------------------------------
* submitProof
*----------------------------------------------------------------------------------*/
bool submitProof(h256 _nonce, Miner* _m)
{
// return true if miner should stop and wait for new work, false to keep mining
bool shouldStop = false;
LogF << "Trace: GenericFarm.submitProof - nonce = " << _nonce.hex().substr(0, 8) << ", miner = " << _m->index();
/*
we could block here if
- another miner found a solution and is submitting it
- the main loop is checking if a solution has been found
- setWork has been called with a new work package
*/
WriteGuard l(x_minerWork);
// check to see if the main loop is still processing a previous solution
if (solutionMiner == -1)
{
LogF << "Trace: GenericFarm.submitProof - setting new solution";
solutionMiner = _m->index();
solution = _nonce;
if (m_opMode == OperationMode::Solo)
{
m_challenge.clear();
for (auto const& m : m_miners)
if (m != _m)
m->setWork(m_challenge, m_target);
shouldStop = true;
} else
shouldStop = false;
} else
{
LogF << "Trace: GenericFarm.submitProof - previous solution not processed";
shouldStop = m_opMode == OperationMode::Solo;
}
return shouldStop;
}
bool solutionFound(h256& _solution, int& _miner)
{
// check if any of the miners has found a solution
WriteGuard l(x_minerWork);
if (solutionMiner != -1)
{
_miner = solutionMiner;
_solution = solution;
solutionMiner = -1;
return true;
} else
return false;
}
public:
unsigned currentBlock;
DataLogger logger;
// this value will be compared directly to the upper 64 bits of the hash.
uint64_t closeHitThreshold = 0;
// this value is in seconds -- desired close hit frequency for work units. each
// miner needs to convert it to a hash value based on their own hash rate.
int workUnitFreq = 0;
// this will get set true in case of thermal runaway.
bool shutDown = false;
// with solo mining, the userAcct and the hashingAcct are the same.
// with pool mining, the hashingAcct will be the pool ETH address, and
// the userAcct will be the user's ETH address. the userAcct is private to FarmClient.h
string hashingAcct; // account used as part of the keccak256_0xBitcoin() function
private:
mutable SharedMutex x_minerWork;
miners_t m_miners;
h256 m_target;
bytes m_challenge;
OperationMode m_opMode;
std::atomic<bool> m_isMining = {false};
friend class HashRates;
HashRates* m_hashRates;
// event functions
BestHashFn m_onBestHash;
SolutionProcessedFn m_onSolutionProcessed;
CloseHitFn m_onCloseHit;
HashFaultFn m_onHashFault;
// hash faults per miner for this session
std::vector<int> m_hashFaults;
uint64_t m_bestHash;
mutable SharedMutex x_bestHash;
mutable SharedMutex x_solutionStats;
mutable SolutionStats m_solutionStats;
// this includes work units
unsigned m_closeHits = 0;
// this includes work units
uint64_t m_lastCloseHit;
h256 solution;
int solutionMiner = -1;
};
}
}