-
Notifications
You must be signed in to change notification settings - Fork 7
/
proxy.js
1703 lines (1601 loc) · 77.7 KB
/
proxy.js
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const cluster = require('cluster');
const net = require('net');
const tls = require('tls');
const http = require('http');
const moment = require('moment');
const fs = require('fs');
const async = require('async');
const support = require('./lib/support.js')();
global.config = require('./config.json');
const PROXY_VERSION = "0.26.6";
const DEFAULT_ALGO = [ "rx/0" ];
const DEFAULT_ALGO_PERF = { "rx/0": 1, "rx/loki": 1 };
/*
General file design/where to find things.
Internal Variables
IPC Registry
Combined Functions
Pool Definition
Master Functions
Miner Definition
Slave Functions
API Calls (Master-Only)
System Init
*/
let debug = {
pool: require('debug')('pool'),
diff: require('debug')('diff'),
blocks: require('debug')('blocks'),
shares: require('debug')('shares'),
miners: require('debug')('miners'),
workers: require('debug')('workers'),
balancer: require('debug')('balancer'),
misc: require('debug')('misc')
};
global.threadName = '';
const nonceCheck32 = new RegExp("^[0-9a-f]{8}$");
const nonceCheck64 = new RegExp("^[0-9a-f]{16}$");
let activePorts = [];
let httpResponse = ' 200 OK\nContent-Type: text/plain\nContent-Length: 19\n\nMining Proxy Online';
let activeMiners = {};
let activeCoins = {};
let bans = {};
let activePools = {};
let activeWorkers = {};
let defaultPools = {};
let accessControl = {};
let lastAccessControlLoadTime = null;
let masterStats = {shares: 0, blocks: 0, hashes: 0};
// IPC Registry
function masterMessageHandler(worker, message, handle) {
if (typeof message !== 'undefined' && 'type' in message){
switch (message.type) {
case 'blockFind':
case 'shareFind':
if (message.host in activePools){
activePools[message.host].sendShare(worker, message.data);
}
break;
case 'needPoolState':
worker.send({
type: 'poolState',
data: Object.keys(activePools)
});
for (let hostname in activePools){
if (activePools.hasOwnProperty(hostname)){
if (!is_active_pool(hostname)) continue;
let pool = activePools[hostname];
worker.send({
host: hostname,
type: 'newBlockTemplate',
data: pool.coinFuncs.getMasterJob(pool, worker.id)
});
}
}
break;
case 'workerStats':
activeWorkers[worker.id][message.minerID] = message.data;
break;
}
}
}
function slaveMessageHandler(message) {
switch (message.type) {
case 'newBlockTemplate':
if (message.host in activePools){
if(activePools[message.host].activeBlocktemplate){
debug.workers(`Received a new block template for ${message.host} and have one in cache. Storing`);
activePools[message.host].pastBlockTemplates.enq(activePools[message.host].activeBlocktemplate);
} else {
debug.workers(`Received a new block template for ${message.host} do not have one in cache.`);
}
activePools[message.host].activeBlocktemplate = new activePools[message.host].coinFuncs.BlockTemplate(message.data);
for (let miner in activeMiners){
if (activeMiners.hasOwnProperty(miner)){
let realMiner = activeMiners[miner];
if (realMiner.pool === message.host){
realMiner.pushNewJob();
}
}
}
}
break;
case 'poolState':
message.data.forEach(function(hostname){
if(!(hostname in activePools)){
global.config.pools.forEach(function(poolData){
if (!poolData.coin) poolData.coin = "xmr";
if (hostname === poolData.hostname){
activePools[hostname] = new Pool(poolData);
}
});
}
});
break;
case 'changePool':
if (activeMiners.hasOwnProperty(message.worker) && activePools.hasOwnProperty(message.pool)){
activeMiners[message.worker].pool = message.pool;
activeMiners[message.worker].pushNewJob(true);
}
break;
case 'disablePool':
if (activePools.hasOwnProperty(message.pool)){
activePools[message.pool].active = false;
checkActivePools();
}
break;
case 'enablePool':
if (activePools.hasOwnProperty(message.pool)){
activePools[message.pool].active = true;
process.send({type: 'needPoolState'});
}
break;
}
}
// Combined Functions
function readConfig() {
let local_conf = JSON.parse(fs.readFileSync('config.json'));
if (typeof global.config === 'undefined') {
global.config = {};
}
for (let key in local_conf) {
if (local_conf.hasOwnProperty(key) && (typeof global.config[key] === 'undefined' || global.config[key] !== local_conf[key])) {
global.config[key] = local_conf[key];
}
}
if (!cluster.isMaster) {
activatePorts();
}
}
// Pool Definition
function Pool(poolData){
/*
Pool data is the following:
{
"hostname": "pool.supportxmr.com",
"port": 7777,
"ssl": false,
"share": 80,
"username": "",
"password": "",
"keepAlive": true,
"coin": "xmr"
}
Client Data format:
{
"method":"submit",
"params":{
"id":"12e168f2-db42-4eea-b56a-f1e7d57f94c9",
"job_id":"/4FIQEI/Qq++EzzH1e03oTrWF5Ed",
"nonce":"9e008000",
"result":"4eee0b966418fdc3ec1a684322715e65765554f11ff8f7fed3f75ac45ef20300"
},
"id":1
}
*/
this.hostname = poolData.hostname;
this.port = poolData.port;
this.ssl = poolData.ssl;
this.share = poolData.share;
this.username = poolData.username;
this.password = poolData.password;
this.keepAlive = poolData.keepAlive;
this.default = poolData.default;
this.devPool = poolData.hasOwnProperty('devPool') && poolData.devPool === true;
this.coin = poolData.coin;
this.pastBlockTemplates = support.circularBuffer(4);
this.coinFuncs = require(`./lib/${this.coin}.js`)();
this.activeBlocktemplate = null;
this.active = true;
this.sendId = 1;
this.sendLog = {};
this.poolJobs = {};
this.socket = null;
this.allowSelfSignedSSL = true;
// Partial checks for people whom havn't upgraded yet
if (poolData.hasOwnProperty('allowSelfSignedSSL')){
this.allowSelfSignedSSL = !poolData.allowSelfSignedSSL;
}
const algo_arr = poolData.algo ? (poolData.algo instanceof Array ? poolData.algo : [poolData.algo]) : DEFAULT_ALGO;
this.default_algo_set = {};
this.algos = {};
for (let i in algo_arr) this.algos[algo_arr[i]] = this.default_algo_set[algo_arr[i]] = 1;
this.algos_perf = this.default_algos_perf = poolData.algo_perf && poolData.algo_perf instanceof Object ? poolData.algo_perf : DEFAULT_ALGO_PERF;
this.blob_type = poolData.blob_type;
setInterval(function(pool) {
if (pool.keepAlive && pool.socket && is_active_pool(pool.hostname)) pool.sendData('keepalived');
}, 30000, this);
this.close_socket = function(){
try {
if (this.socket !== null){
this.socket.end();
this.socket.destroy();
}
} catch (e) {
console.warn(global.threadName + "Had issues murdering the old socket. Om nom: " + e)
}
this.socket = null;
};
this.disable = function(){
for (let worker in cluster.workers){
if (cluster.workers.hasOwnProperty(worker)){
cluster.workers[worker].send({type: 'disablePool', pool: this.hostname});
}
}
this.active = false;
this.close_socket();
};
this.connect = function(hostname){
function connect2(pool) {
pool.close_socket();
if (pool.ssl){
pool.socket = tls.connect(pool.port, pool.hostname, {rejectUnauthorized: pool.allowSelfSignedSSL})
.on('connect', () => { poolSocket(pool.hostname); })
.on('error', (err) => {
setTimeout(connect2, 30*1000, pool);
console.warn(`${global.threadName}SSL pool socket connect error from ${pool.hostname}: ${err}`);
});
} else {
pool.socket = net.connect(pool.port, pool.hostname)
.on('connect', () => { poolSocket(pool.hostname); })
.on('error', (err) => {
setTimeout(connect2, 30*1000, pool);
console.warn(`${global.threadName}Plain pool socket connect error from ${pool.hostname}: ${err}`);
});
}
}
let pool = activePools[hostname];
pool.disable();
connect2(pool);
};
this.sendData = function (method, params) {
if (typeof params === 'undefined'){
params = {};
}
let rawSend = {
method: method,
id: this.sendId++,
};
if (typeof this.id !== 'undefined'){
params.id = this.id;
}
rawSend.params = params;
if (this.socket === null || !this.socket.writable){
return false;
}
this.socket.write(JSON.stringify(rawSend) + '\n');
this.sendLog[rawSend.id] = rawSend;
debug.pool(`Sent ${JSON.stringify(rawSend)} to ${this.hostname}`);
};
this.login = function () {
this.sendData('login', {
login: this.username,
pass: this.password,
agent: 'xmr-node-proxy/' + PROXY_VERSION,
"algo": Object.keys(this.algos),
"algo-perf": this.algos_perf
});
this.active = true;
for (let worker in cluster.workers){
if (cluster.workers.hasOwnProperty(worker)){
cluster.workers[worker].send({type: 'enablePool', pool: this.hostname});
}
}
};
this.update_algo_perf = function (algos, algos_perf) {
// do not update not changed algo/algo-perf
const prev_algos = this.algos;
const prev_algos_perf = this.algos_perf;
const prev_algos_str = JSON.stringify(Object.keys(prev_algos));
const prev_algos_perf_str = JSON.stringify(prev_algos_perf);
const algos_str = JSON.stringify(Object.keys(algos));
const algos_perf_str = JSON.stringify(algos_perf);
if ( algos_str === prev_algos_str && algos_perf_str === prev_algos_perf_str) return;
const curr_time = Date.now();
if (!this.last_common_algo_notify_time || curr_time - this.last_common_algo_notify_time > 5*60*1000 || algos_str !== prev_algos_str) {
console.log("Setting common algo: " + algos_str + " with algo-perf: " + algos_perf_str + " for pool " + this.hostname);
this.last_common_algo_notify_time = curr_time;
}
this.sendData('getjob', {
"algo": Object.keys(this.algos = algos),
"algo-perf": (this.algos_perf = algos_perf)
});
};
this.sendShare = function (worker, shareData) {
//btID - Block template ID in the poolJobs circ buffer.
let job = this.poolJobs[worker.id].toarray().filter(function (job) {
return job.id === shareData.btID;
})[0];
if (job) {
let submitParams = {
job_id: job.masterJobID,
nonce: shareData.nonce,
workerNonce: shareData.workerNonce,
poolNonce: job.poolNonce
};
if (shareData.resultHash) submitParams.result = shareData.resultHash;
if (shareData.pow) submitParams.pow = shareData.pow;
this.sendData('submit', submitParams);
}
};
}
// Master Functions
/*
The master performs the following tasks:
1. Serve all API calls.
2. Distribute appropriately modified block template bases to all pool servers.
3. Handle all to/from the various pool servers.
4. Manage and suggest miner changes in order to achieve correct h/s balancing between the various systems.
*/
function connectPools(){
global.config.pools.forEach(function (poolData) {
if (!poolData.coin) poolData.coin = "xmr";
if (activePools.hasOwnProperty(poolData.hostname)){
return;
}
activePools[poolData.hostname] = new Pool(poolData);
activePools[poolData.hostname].connect(poolData.hostname);
});
let seen_coins = {};
if (global.config.developerShare > 0){
for (let pool in activePools){
if (activePools.hasOwnProperty(pool)){
if (seen_coins.hasOwnProperty(activePools[pool].coin)){
return;
}
let devPool = activePools[pool].coinFuncs.devPool;
if (activePools.hasOwnProperty(devPool.hostname)){
return;
}
activePools[devPool.hostname] = new Pool(devPool);
activePools[devPool.hostname].connect(devPool.hostname);
seen_coins[activePools[pool].coin] = true;
}
}
}
for (let coin in seen_coins){
if (seen_coins.hasOwnProperty(coin)){
activeCoins[coin] = true;
}
}
}
let poolStates = {};
function balanceWorkers(){
/*
This function deals with handling how the pool deals with getting traffic balanced to the various pools.
Step 1: Enumerate all workers (Child servers), and their miners/coins into known states
Step 1: Enumerate all miners, move their H/S into a known state tagged to the coins and pools
Step 2: Enumerate all pools, verify the percentages as fractions of 100.
Step 3: Determine if we're sharing with the developers (Woohoo! You're the best if you do!)
Step 4: Process the state information to determine splits/moves.
Step 5: Notify child processes of other pools to send traffic to if needed.
The Master, as the known state holder of all information, deals with handling this data.
*/
let minerStates = {};
poolStates = {};
for (let poolName in activePools){
if (activePools.hasOwnProperty(poolName)){
let pool = activePools[poolName];
if (!poolStates.hasOwnProperty(pool.coin)){
poolStates[pool.coin] = { 'totalPercentage': 0, 'activePoolCount': 0, 'devPool': false};
}
poolStates[pool.coin][poolName] = {
miners: {},
hashrate: 0,
percentage: pool.share,
devPool: pool.devPool,
idealRate: 0
};
if(pool.devPool){
poolStates[pool.coin].devPool = poolName;
debug.balancer(`Found a developer pool enabled. Pool is: ${poolName}`);
} else if (is_active_pool(poolName)) {
poolStates[pool.coin].totalPercentage += pool.share;
++ poolStates[pool.coin].activePoolCount;
} else {
console.error(`${global.threadName}Pool ${poolName} is disabled due to issues with it`);
}
if (!minerStates.hasOwnProperty(pool.coin)){
minerStates[pool.coin] = {
hashrate: 0
};
}
}
}
/*
poolStates now contains an object that looks approximately like:
poolStates = {
'xmr':
{
'mine.xmrpool.net': {
'miners': {},
'hashrate': 0,
'percentage': 20,
'devPool': false,
'amtChange': 0
},
'donations.xmrpool.net': {
'miners': {},
'hashrate': 0,
'percentage': 0,
'devPool': true,
'amtChange': 0
},
'devPool': 'donations.xmrpool.net',
'totalPercentage': 20
}
}
*/
for (let coin in poolStates){
if(poolStates.hasOwnProperty(coin)){
if (poolStates[coin].totalPercentage !== 100){
debug.balancer(`Pools on ${coin} are using ${poolStates[coin].totalPercentage}% balance. Adjusting.`);
// Need to adjust all the pools that aren't the dev pool.
if (poolStates[coin].totalPercentage) {
let percentModifier = 100 / poolStates[coin].totalPercentage;
for (let pool in poolStates[coin]){
if (poolStates[coin].hasOwnProperty(pool) && activePools.hasOwnProperty(pool)){
if (poolStates[coin][pool].devPool || !is_active_pool(pool)) continue;
poolStates[coin][pool].percentage *= percentModifier;
}
}
} else if (poolStates[coin].activePoolCount) {
let addModifier = 100 / poolStates[coin].activePoolCount;
for (let pool in poolStates[coin]){
if (poolStates[coin].hasOwnProperty(pool) && activePools.hasOwnProperty(pool)){
if (poolStates[coin][pool].devPool || !is_active_pool(pool)) continue;
poolStates[coin][pool].percentage += addModifier;
}
}
} else {
debug.balancer(`No active pools for ${coin} coin, so waiting for the next cycle.`);
continue;
}
}
delete(poolStates[coin].totalPercentage);
delete(poolStates[coin].activePoolCount);
}
}
/*
poolStates now contains an object that looks approximately like:
poolStates = {
'xmr':
{
'mine.xmrpool.net': {
'miners': {},
'hashrate': 0,
'percentage': 100,
'devPool': false
},
'donations.xmrpool.net': {
'miners': {},
'hashrate': 0,
'percentage': 0,
'devPool': true
},
'devPool': 'donations.xmrpool.net',
}
}
*/
for (let workerID in activeWorkers){
if (activeWorkers.hasOwnProperty(workerID)){
for (let minerID in activeWorkers[workerID]){
if (activeWorkers[workerID].hasOwnProperty(minerID)){
let miner = activeWorkers[workerID][minerID];
try {
let minerCoin = miner.coin;
if (!minerStates.hasOwnProperty(minerCoin)){
minerStates[minerCoin] = {
hashrate: 0
};
}
minerStates[minerCoin].hashrate += miner.avgSpeed;
poolStates[minerCoin][miner.pool].hashrate += miner.avgSpeed;
poolStates[minerCoin][miner.pool].miners[`${workerID}_${minerID}`] = miner.avgSpeed;
} catch (err) {}
}
}
}
}
/*
poolStates now contains the hashrate per pool. This can be compared against minerStates/hashRate to determine
the approximate hashrate that should be moved between pools once the general hashes/second per pool/worker
is determined.
*/
for (let coin in poolStates){
if (poolStates.hasOwnProperty(coin) && minerStates.hasOwnProperty(coin)){
let coinMiners = minerStates[coin];
let coinPools = poolStates[coin];
let devPool = coinPools.devPool;
let highPools = {};
let lowPools = {};
delete(coinPools.devPool);
if (devPool){
let devHashrate = Math.floor(coinMiners.hashrate * (global.config.developerShare/100));
coinMiners.hashrate -= devHashrate;
coinPools[devPool].idealRate = devHashrate;
debug.balancer(`DevPool on ${coin} is enabled. Set to ${global.config.developerShare}% and ideally would have ${coinPools[devPool].idealRate}. Currently has ${coinPools[devPool].hashrate}`);
if (is_active_pool(devPool) && coinPools[devPool].idealRate > coinPools[devPool].hashrate){
lowPools[devPool] = coinPools[devPool].idealRate - coinPools[devPool].hashrate;
debug.balancer(`Pool ${devPool} is running a low hashrate compared to ideal. Want to increase by: ${lowPools[devPool]} h/s`);
} else if (!is_active_pool(devPool) || coinPools[devPool].idealRate < coinPools[devPool].hashrate){
highPools[devPool] = coinPools[devPool].hashrate - coinPools[devPool].idealRate;
debug.balancer(`Pool ${devPool} is running a high hashrate compared to ideal. Want to decrease by: ${highPools[devPool]} h/s`);
}
}
for (let pool in coinPools){
if (coinPools.hasOwnProperty(pool) && pool !== devPool && activePools.hasOwnProperty(pool)){
coinPools[pool].idealRate = Math.floor(coinMiners.hashrate * (coinPools[pool].percentage/100));
if (is_active_pool(pool) && coinPools[pool].idealRate > coinPools[pool].hashrate){
lowPools[pool] = coinPools[pool].idealRate - coinPools[pool].hashrate;
debug.balancer(`Pool ${pool} is running a low hashrate compared to ideal. Want to increase by: ${lowPools[pool]} h/s`);
} else if (!is_active_pool(pool) || coinPools[pool].idealRate < coinPools[pool].hashrate){
highPools[pool] = coinPools[pool].hashrate - coinPools[pool].idealRate;
debug.balancer(`Pool ${pool} is running a high hashrate compared to ideal. Want to decrease by: ${highPools[pool]} h/s`);
}
//activePools[pool].share = coinPools[pool].percentage;
}
}
if (Object.keys(highPools).length === 0 && Object.keys(lowPools).length === 0){
debug.balancer(`No high or low ${coin} coin pools, so waiting for the next cycle.`);
continue;
}
let freed_miners = {};
if (Object.keys(highPools).length > 0){
for (let pool in highPools){
if (highPools.hasOwnProperty(pool)){
for (let miner in coinPools[pool].miners){
if (coinPools[pool].miners.hasOwnProperty(miner)){
if ((!is_active_pool(pool) || coinPools[pool].miners[miner] <= highPools[pool]) && coinPools[pool].miners[miner] !== 0){
highPools[pool] -= coinPools[pool].miners[miner];
freed_miners[miner] = coinPools[pool].miners[miner];
debug.balancer(`Freeing up ${miner} on ${pool} for ${freed_miners[miner]} h/s`);
delete(coinPools[pool].miners[miner]);
}
}
}
}
}
}
let minerChanges = {};
if (Object.keys(lowPools).length > 0){
for (let pool in lowPools){
if (lowPools.hasOwnProperty(pool)){
minerChanges[pool] = [];
// fit low pools without overflow
if (Object.keys(freed_miners).length > 0){
for (let miner in freed_miners){
if (freed_miners.hasOwnProperty(miner)){
if (freed_miners[miner] <= lowPools[pool]){
minerChanges[pool].push(miner);
lowPools[pool] -= freed_miners[miner];
debug.balancer(`Snagging up ${miner} for ${pool} for ${freed_miners[miner]} h/s`);
delete(freed_miners[miner]);
}
}
}
}
if(lowPools[pool] > 100){
for (let donatorPool in coinPools){
if(coinPools.hasOwnProperty(donatorPool) && !lowPools.hasOwnProperty(donatorPool)){
for (let miner in coinPools[donatorPool].miners){
if (coinPools[donatorPool].miners.hasOwnProperty(miner)){
if (coinPools[donatorPool].miners[miner] <= lowPools[pool] && coinPools[donatorPool].miners[miner] !== 0){
minerChanges[pool].push(miner);
lowPools[pool] -= coinPools[donatorPool].miners[miner];
debug.balancer(`Moving ${miner} for ${pool} from ${donatorPool} for ${coinPools[donatorPool].miners[miner]} h/s`);
delete(coinPools[donatorPool].miners[miner]);
}
if (lowPools[pool] < 50){
break;
}
}
}
if (lowPools[pool] < 50){
break;
}
}
}
}
}
}
// fit low pools with overflow except devPool
if (Object.keys(freed_miners).length > 0){
for (let pool in lowPools){
if (lowPools.hasOwnProperty(pool) && pool !== devPool){
if (!(pool in minerChanges)) minerChanges[pool] = [];
for (let miner in freed_miners){
if (freed_miners.hasOwnProperty(miner)){
minerChanges[pool].push(miner);
lowPools[pool] -= freed_miners[miner];
debug.balancer(`Moving overflow ${miner} for ${pool} for ${freed_miners[miner]} h/s`);
delete(freed_miners[miner]);
}
}
}
}
}
}
for (let pool in minerChanges){
if(minerChanges.hasOwnProperty(pool) && minerChanges[pool].length > 0){
minerChanges[pool].forEach(function(miner){
let minerBits = miner.split('_');
if (cluster.workers[minerBits[0]]) cluster.workers[minerBits[0]].send({
type: 'changePool',
worker: minerBits[1],
pool: pool
});
});
}
}
}
}
}
let hs_algo = ""; // common algo for human_hashrate
function enumerateWorkerStats() {
let stats, global_stats = {miners: 0, hashes: 0, hashRate: 0, diff: 0};
let pool_algos = {};
let pool_algos_perf = {};
for (let poolID in activeWorkers){
if (activeWorkers.hasOwnProperty(poolID)){
stats = {
miners: 0,
hashes: 0,
hashRate: 0,
diff: 0
};
let inactivityDeadline = (typeof global.config.minerInactivityTime === 'undefined') ? Math.floor((Date.now())/1000) - 120
: (global.config.minerInactivityTime <= 0 ? 0 : Math.floor((Date.now())/1000) - global.config.minerInactivityTime);
for (let workerID in activeWorkers[poolID]){
if (activeWorkers[poolID].hasOwnProperty(workerID)) {
let workerData = activeWorkers[poolID][workerID];
if (typeof workerData !== 'undefined') {
try{
if (workerData.lastContact < inactivityDeadline){
delete activeWorkers[poolID][workerID];
continue;
}
++ stats.miners;
stats.hashes += workerData.hashes;
stats.hashRate += workerData.avgSpeed;
stats.diff += workerData.diff;
// process smart miners and assume all other miners to only support pool algo
let miner_algos = workerData.algos;
if (!miner_algos) miner_algos = activePools[workerData.pool].default_algo_set;
if (workerData.pool in pool_algos) { // compute union of miner_algos and pool_algos[workerData.pool]
for (let algo in pool_algos[workerData.pool]) {
if (!(algo in miner_algos)) delete pool_algos[workerData.pool][algo];
}
} else {
pool_algos[workerData.pool] = miner_algos;
pool_algos_perf[workerData.pool] = {};
}
if (workerData.algos_perf) { // only process smart miners and add algo_perf from all smart miners
for (let algo in workerData.algos_perf) {
if (algo in pool_algos_perf[workerData.pool]) pool_algos_perf[workerData.pool][algo] += workerData.algos_perf[algo];
else pool_algos_perf[workerData.pool][algo] = workerData.algos_perf[algo];
}
}
} catch (err) {
delete activeWorkers[poolID][workerID];
}
} else {
delete activeWorkers[poolID][workerID];
}
}
}
global_stats.miners += stats.miners;
global_stats.hashes += stats.hashes;
global_stats.hashRate += stats.hashRate;
global_stats.diff += stats.diff;
debug.workers(`Worker: ${poolID} currently has ${stats.miners} miners connected at ${stats.hashRate} h/s with an average diff of ${Math.floor(stats.diff/stats.miners)}`);
}
}
let pool_hs = "";
for (let coin in poolStates) {
if (!poolStates.hasOwnProperty(coin)) continue;
for (let pool in poolStates[coin]) {
if (!poolStates[coin].hasOwnProperty(pool) || !activePools.hasOwnProperty(pool) || poolStates[coin][pool].devPool || poolStates[coin][pool].hashrate === 0) continue;
if (pool_hs != "") pool_hs += ", ";
pool_hs += `${pool}/${poolStates[coin][pool].percentage.toFixed(2)}%`;
}
}
if (pool_hs != "") pool_hs = " (" + pool_hs + ")";
// do update of algo/algo-perf if it was changed
hs_algo = ""; // common algo for human_hashrate
for (let pool in pool_algos) {
let pool_algos_perf2 = pool_algos_perf[pool];
if (Object.keys(pool_algos_perf2).length === 0) pool_algos_perf2 = activePools[pool].default_algos_perf;
activePools[pool].update_algo_perf(pool_algos[pool], pool_algos_perf2);
if (Object.keys(pool_algos[pool]).length == 1) {
if ("c29s" in pool_algos[pool]) hs_algo = (hs_algo === "c29s" || hs_algo === "") ? "c29s" : "h/s";
else if ("c29v" in pool_algos[pool]) hs_algo = (hs_algo === "c29v" || hs_algo === "") ? "c29v" : "h/s";
else hs_algo = "h/s";
} else {
hs_algo = "h/s";
}
}
const hs = support.human_hashrate(global_stats.hashRate, hs_algo);
console.log(`The proxy currently has ${global_stats.miners} miners connected at ${hs}${pool_hs}` + (global_stats.miners ? ` with an average diff of ${Math.floor(global_stats.diff/global_stats.miners)}` : ""));
}
function poolSocket(hostname){
let pool = activePools[hostname];
let socket = pool.socket;
let dataBuffer = '';
socket.on('data', (d) => {
dataBuffer += d;
if (dataBuffer.indexOf('\n') !== -1) {
let messages = dataBuffer.split('\n');
let incomplete = dataBuffer.slice(-1) === '\n' ? '' : messages.pop();
for (let i = 0; i < messages.length; i++) {
let message = messages[i];
if (message.trim() === '') {
continue;
}
let jsonData;
try {
jsonData = JSON.parse(message);
}
catch (e) {
if (message.indexOf('GET /') === 0) {
if (message.indexOf('HTTP/1.1') !== -1) {
socket.end('HTTP/1.1' + httpResponse);
break;
}
else if (message.indexOf('HTTP/1.0') !== -1) {
socket.end('HTTP/1.0' + httpResponse);
break;
}
}
console.warn(`${global.threadName}Pool wrong reply error from ${pool.hostname}: ${message}`);
socket.destroy();
break;
}
handlePoolMessage(jsonData, pool.hostname);
}
dataBuffer = incomplete;
}
}).on('error', (err) => {
console.warn(`${global.threadName}Pool socket error from ${pool.hostname}: ${err}`);
activePools[pool.hostname].disable();
setTimeout(activePools[pool.hostname].connect, 30*1000, pool.hostname);
}).on('close', () => {
console.warn(`${global.threadName}Pool socket closed from ${pool.hostname}`);
activePools[pool.hostname].disable();
setTimeout(activePools[pool.hostname].connect, 30*1000, pool.hostname);
});
socket.setKeepAlive(true);
socket.setEncoding('utf8');
console.log(`${global.threadName}Connected to pool: ${pool.hostname}`);
pool.login();
}
function handlePoolMessage(jsonData, hostname){
let pool = activePools[hostname];
debug.pool(`Received ${JSON.stringify(jsonData)} from ${pool.hostname}`);
if (jsonData.hasOwnProperty('method')){
// The only time method is set, is with a push of data. Everything else is a reply/
if (jsonData.method === 'job'){
handleNewBlockTemplate(jsonData.params, hostname);
}
} else {
if (jsonData.error !== null){
console.error(`${global.threadName}Error response from pool ${pool.hostname}: ${JSON.stringify(jsonData.error)}`);
if ((jsonData.error instanceof Object) && (typeof jsonData.error.message === 'string') && jsonData.error.message.includes("Unauthenticated")) activePools[hostname].disable();
return;
}
let sendLog = pool.sendLog[jsonData.id];
switch(sendLog.method){
case 'login':
pool.id = jsonData.result.id;
handleNewBlockTemplate(jsonData.result.job, hostname);
break;
case 'getjob':
// null for same job
if (jsonData.result !== null) handleNewBlockTemplate(jsonData.result, hostname);
break;
case 'submit':
sendLog.accepted = true;
break;
}
}
}
function handleNewBlockTemplate(blockTemplate, hostname){
if (!blockTemplate) {
console.error(`${global.threadName}Empty response from pool ${hostname}`);
activePools[hostname].disable();
return;
}
let pool = activePools[hostname];
let algo_variant = "";
if (blockTemplate.algo) algo_variant += "algo: " + blockTemplate.algo;
if (blockTemplate.variant) {
if (algo_variant != "") algo_variant += ", ";
algo_variant += "variant: " + blockTemplate.variant;
}
if (algo_variant != "") algo_variant = " (" + algo_variant + ")";
console.log(`Received new block template on ${blockTemplate.height} height${algo_variant} with ${blockTemplate.target_diff} target difficulty from ${pool.hostname}`);
if(pool.activeBlocktemplate){
if (pool.activeBlocktemplate.job_id === blockTemplate.job_id){
debug.pool('No update with this job, it is an upstream dupe');
return;
}
debug.pool('Storing the previous block template');
pool.pastBlockTemplates.enq(pool.activeBlocktemplate);
}
if (!blockTemplate.algo) blockTemplate.algo = pool.coinFuncs.detectAlgo(pool.default_algo_set, 16 * parseInt(blockTemplate.blocktemplate_blob[0]) + parseInt(blockTemplate.blocktemplate_blob[1]));
if (!blockTemplate.blob_type) blockTemplate.blob_type = pool.blob_type;
pool.activeBlocktemplate = new pool.coinFuncs.MasterBlockTemplate(blockTemplate);
for (let id in cluster.workers){
if (cluster.workers.hasOwnProperty(id)){
cluster.workers[id].send({
host: hostname,
type: 'newBlockTemplate',
data: pool.coinFuncs.getMasterJob(pool, id)
});
}
}
}
function is_active_pool(hostname) {
let pool = activePools[hostname];
if ((cluster.isMaster && !pool.socket) || !pool.active || pool.activeBlocktemplate === null) return false;
let top_height = 0;
for (let poolName in activePools){
if (!activePools.hasOwnProperty(poolName)) continue;
let pool2 = activePools[poolName];
if (pool2.coin != pool.coin) continue;
if ((cluster.isMaster && !pool2.socket) || !pool2.active || pool2.activeBlocktemplate === null) continue;
if (Math.abs(pool2.activeBlocktemplate.height - pool.activeBlocktemplate.height) > 1000) continue; // different coin templates, can't compare here
if (pool2.activeBlocktemplate.height > top_height) top_height = pool2.activeBlocktemplate.height;
}
if (pool.activeBlocktemplate.height < top_height - 5) return false;
return true;
}
// Miner Definition
function Miner(id, params, ip, pushMessage, portData, minerSocket) {
// Arguments
// minerId, params, ip, pushMessage, portData
// Username Layout - <address in BTC or XMR>.<Difficulty>
// Password Layout - <password>.<miner identifier>.<payment ID for XMR>
// Default function is to use the password so they can login. Identifiers can be unique, payment ID is last.
// If there is no miner identifier, then the miner identifier is set to the password
// If the password is x, aka, old-logins, we're not going to allow detailed review of miners.
const login_diff_split = params.login ? params.login.split("+") : "";
if (!params.pass) params.pass = "x";
const pass_algo_split = params.pass.split("~");
const pass_split = pass_algo_split[0].split(":");
// Miner Variables
this.coin = portData.coin;
this.coinFuncs = require(`./lib/${this.coin}.js`)();
this.coinSettings = global.config.coinSettings[this.coin];
this.login = login_diff_split[0]; // Documentation purposes only.
this.user = login_diff_split[0]; // For accessControl and workerStats.
this.password = pass_split[0]; // For accessControl and workerStats.
this.agent = params.agent; // Documentation purposes only.
this.ip = ip; // Documentation purposes only.
if (pass_algo_split.length == 2) {
const algo_name = pass_algo_split[1];
params.algo = [ algo_name ];
params["algo-perf"] = {};
params["algo-perf"][algo_name] = 1;
}
if (params.algo && (params.algo instanceof Array)) { // To report union of defined algo set to the pool for all its miners
for (let i in params.algo) {
this.algos = {};
for (let i in params.algo) this.algos[params.algo[i]] = 1;
}
}
this.algos_perf = params["algo-perf"]; // To report sum of defined algo_perf to the pool for all its miners
this.socket = minerSocket;
this.pushMessage = pushMessage;
this.getNewJob = function (bashCache) {
return this.coinFuncs.getJob(this, activePools[this.pool].activeBlocktemplate, bashCache);
};
this.pushNewJob = function (bashCache) {
const job = this.getNewJob(bashCache);
if (this.protocol === "grin") {
this.pushMessage({method: 'getjobtemplate', result: job});
} else {
this.pushMessage({method: 'job', params: job});
}
};
this.error = "";
this.valid_miner = true;
this.incremented = false;
this.fixed_diff = false;
this.difficulty = portData.diff;
this.connectTime = Date.now();
if (!defaultPools.hasOwnProperty(portData.coin) || !is_active_pool(defaultPools[portData.coin])) {
for (let poolName in activePools){
if (activePools.hasOwnProperty(poolName)){
let pool = activePools[poolName];
if (pool.coin != portData.coin || pool.devPool) continue;
if (is_active_pool(poolName)) {
this.pool = poolName;
break;
}
}
}
}
if (!this.pool) this.pool = defaultPools[portData.coin];
if (login_diff_split.length === 2) {
this.fixed_diff = true;
this.difficulty = Number(login_diff_split[1]);
this.user = login_diff_split[0];
} else if (login_diff_split.length > 2) {
this.error = "Too many options in the login field";
this.valid_miner = false;
}
if (activePools[this.pool].activeBlocktemplate === null){
this.error = "No active block template";
this.valid_miner = false;
}
// Verify if user/password is in allowed client connects
if (!isAllowedLogin(this.user, this.password)) {
this.error = "Unauthorized access";
this.valid_miner = false;
}
this.id = id;
this.heartbeat = function () {
this.lastContact = Date.now();
};
this.heartbeat();
// VarDiff System
this.lastShareTime = Date.now() / 1000 || 0;
this.shares = 0;
this.blocks = 0;
this.hashes = 0;
this.validJobs = support.circularBuffer(5);
this.cachedJob = null;