forked from MoneroOcean/meta-miner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mm.js
executable file
·1208 lines (1101 loc) · 45.5 KB
/
mm.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
#!/usr/bin/env node
// Meta Miner: adding algo switching support to *any* stratum miner
// Algo switching is supported by https://moneroocean.stream mining pool
// Copyright 2018 MoneroOcean <https://github.com/MoneroOcean>, <support@moneroocean.stream>
// This program 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.
//
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
"use strict";
// *****************************************************************************
// *** DEPENDECIES ***
// *****************************************************************************
const fs = require('fs');
const net = require('net');
const tls = require('tls');
const path = require('path');
const child_process = require('child_process');
// *****************************************************************************
// *** CONSTS ***
// *****************************************************************************
const VERSION = "v4.4";
const DEFAULT_ALGO = "rx/0"; // this is algo that is assumed to be sent by pool if its job does not contain algo stratum extension
const AGENT = "Meta Miner " + VERSION;
// [multiplier, nr benchmark prints, regex]
// the multiplier is for supporting hashrate prints in different units
// the nr benchmark prints is to make sure hashrate has stabilized before snapping the benchmark value
const hashrate_regexes = [
[1, 1, /\[[^\]]+\] speed 2.5s\/60s\/15m [\d\.]+ ([\d\.]+)\s/], // for old xmrig
[1, 1, /\[[^\]]+\] speed 10s\/60s\/15m [\d\.n/a]+ ([\d\.]+)\s/], // for new xmrig
[1, 1, /\s+miner\s+speed 10s\/60s\/15m [\d\.n/a]+ ([\d\.]+)\s/], // for xmrig v6+
[1, 1, /Totals \(ALL\):\s+[\d\.]+\s+([1-9]\d*\.\d+|0\.[1-9]\d*)\s/], // xmr-stak
[1, 1, /Total Speed: ([\d\.]+) H\/s,/], // claymore
[1, 1, /\(Avr ([\d\.]+)H\/s\)/], // CryptoDredge
[1e3, 3, /Total[^:]+:\s*([\d\.]+)\s*kh\/s/], // TeamRedMiner variant 1 (kh/s)
[1, 3, /Total[^:]+:\s*([\d\.]+)\s*h\/s/], // TeamRedMiner variant 2 (h/s)
[1, 1, /Mining at\s+([\d\.]+) gps/], // tube4referenceMiner (use mode=rolling command line option)
[1, 1, /mining at\s+([\d\.]+) gps/], // SwapReferenceMiner (use mode=rolling command line option)
[1, 2, /Total\s+:\s+([\d\.]+) gps/], // MoneroVMiner
[1, 2, /([\d\.]+) G\/s/], // gminer
[1000000, 2, /([\d\.]+) MH\/s/], // gminer
];
function algo_hashrate_factor(algo) {
switch (algo) {
case "kawpow": return 1 / 0x100000000;
case "c29s": return 1 / 32;
case "c29b": return 1 / 40;
case "c29v": return 1 / 16;
default: return 1;
}
}
// main algos we bench for
const bench_algos = [
"cn/r",
"cn-lite/1",
"cn-heavy/xhv",
"cn-pico/trtl",
"cn/ccx",
"cn/gpu",
"argon2/chukwa",
"kawpow",
"ghostrider",
"astrobwt",
"rx/0",
"rx/graft",
"rx/arq",
"panthera",
"autolykos2",
"c29b",
"c29s",
"c29v",
"ethash",
"k12",
];
// algo and their perf that can be derived from thier main algo perf
function bench_algo_deps(bench_algo, perf) {
switch (bench_algo) {
case "cn/ccx": return {
"cn/ccx": perf,
"cn/0": perf / 2
};
case "cn/r": return {
"cn/1": perf,
"cn/2": perf,
"cn/r": perf,
"cn/rto": perf,
"cn/xao": perf,
"cn/fast": perf * 2,
"cn/half": perf * 2,
"cn/rwz": perf / 3 * 4,
"cn/zls": perf / 3 * 4,
"cn/double": perf / 2,
};
case "cn-lite/1": return {
"cn-lite/0": perf,
"cn-lite/1": perf,
};
case "cn-heavy/xhv": return {
"cn-heavy/xhv": perf,
};
case "cn-pico/trtl": return {
"cn-pico/trtl": perf,
};
case "cn/gpu": return {
"cn/gpu": perf,
};
case "argon2/chukwa": return {
"argon2/chukwa": perf,
};
case "astrobwt": return {
"astrobwt": perf,
};
case "kawpow": return {
"kawpow": perf,
};
case "rx/0": return {
"rx/0": perf,
"rx/sfx": perf,
};
case "rx/graft": return {
"rx/graft": perf,
};
case "rx/arq": return {
"rx/arq": perf,
};
case "panthera": return {
"panthera": perf,
};
case "autolykos2": return {
"autolykos2": perf,
};
case "c29b": return {
"c29b": perf,
};
case "c29s": return {
"c29s": perf,
};
case "c29v": return {
"c29v": perf,
};
case "ethash": return {
"ethash": perf,
};
case "k12": return {
"k12": perf,
};
case "ghostrider": return {
"ghostrider": perf,
};
default: return {};
}
}
// *****************************************************************************
// *** CONFIG ***
// *****************************************************************************
let console_file = process.cwd() + "/mm.json";
let c = {
proc_title: "meta-miner",
miner_host: "127.0.0.1",
miner_port: 3333,
pools: [],
algos: {},
algo_perf: {},
algo_min_time: 0,
user: null,
pass: null,
log_file: null,
watchdog: 600,
hashrate_watchdog: 0,
};
let is_quiet_mode = false;
let is_verbose_mode = false;
let is_no_config_save = false;
let is_debug = false;
let is_miner_stdin = false;
// *****************************************************************************
// *** WORKING STATE ***
// *****************************************************************************
let curr_miner_socket = null;
let curr_miner_protocol = "default"; // curr_miner_socket communication protocol that can be "default", "grin" or "eth"
let curr_pool_socket = null;
let curr_pool_last_job = null;
let curr_pool_miner_id = null;
let curr_pool_last_target = null;
let curr_miner = null;
let next_miner_to_run = null; // here we store miner command line that will be run after current miner is stopped or null if no miner is being stopped now
let curr_pool_num = 0;
let last_miner_hashrate = null;
let is_want_miner_kill = false; // true if we want to kill miner (otherwise it is restart if closed without a reason)
let curr_algo = null;
let last_algo_change_time = null;
let main_pool_check_timer = null;
let miner_proc = null;
let miner_login_cb = null;
let miner_get_first_job_cb = null;
let miner_subscribe_cb = null;
let miner_last_submit_time = null;
// *****************************************************************************
// *** FUNCTIONS ***
// *****************************************************************************
// *** inlined from tree_kill module
function tree_kill(pid, signal, callback) {
var tree = {};
var pidsToProcess = {};
tree[pid] = [];
pidsToProcess[pid] = 1;
if (typeof signal === 'function' && callback === undefined) {
callback = signal;
signal = undefined;
}
switch (process.platform) {
case 'win32':
child_process.exec('taskkill /pid ' + pid + ' /T /F', {}, callback);
break;
case 'darwin':
buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
return child_process.spawn('pgrep', ['-P', parentPid]);
}, function () {
killAll(tree, signal, callback);
});
break;
default: // Linux
buildProcessTree(pid, tree, pidsToProcess, function (parentPid) {
return child_process.spawn('ps', ['-o', 'pid', '--no-headers', '--ppid', parentPid]);
}, function () {
killAll(tree, signal, callback);
});
break;
}
};
function killAll (tree, signal, callback) {
var killed = {};
try {
Object.keys(tree).forEach(function (pid) {
tree[pid].forEach(function (pidpid) {
if (!killed[pidpid]) {
killPid(pidpid, signal);
killed[pidpid] = 1;
}
});
if (!killed[pid]) {
killPid(pid, signal);
killed[pid] = 1;
}
});
} catch (err) {
if (callback) {
return callback(err);
} else {
throw err;
}
}
if (callback) {
return callback();
}
}
function killPid(pid, signal) {
try {
process.kill(parseInt(pid, 10), signal);
}
catch (err) {
if (err.code !== 'ESRCH') throw err;
}
}
function buildProcessTree(parentPid, tree, pidsToProcess, spawnChildProcessesList, cb) {
var ps = spawnChildProcessesList(parentPid);
var allData = '';
ps.stdout.on('data', function (data) {
var data = data.toString('ascii');
allData += data;
});
var onClose = function (code) {
delete pidsToProcess[parentPid];
if (code != 0) {
// no more parent processes
if (Object.keys(pidsToProcess).length == 0) {
cb();
}
return;
}
allData.match(/\d+/g).forEach(function (pid) {
pid = parseInt(pid, 10);
tree[parentPid].push(pid);
tree[pid] = [];
pidsToProcess[pid] = 1;
buildProcessTree(pid, tree, pidsToProcess, spawnChildProcessesList, cb);
});
};
ps.on('close', onClose);
}
// *** Console/log output
function log(msg) {
console.log(">>> " + msg);
if (c.log_file) fs.appendFileSync(c.log_file, ">>> " + msg + "\n");
}
function err(msg) {
console.error("!!! " + msg);
if (c.log_file) fs.appendFileSync(c.log_file, "!!! " + msg + "\n");
}
function print_all_messages(str) {
process.stdout.write(str);
if (c.log_file) fs.appendFileSync(c.log_file, str);
if (c.hashrate_watchdog) {
const str2 = str.replace(/\x1b\[[0-9;]*m/g, ""); // remove all colors
for (let i in hashrate_regexes) {
const hashrate_regex = hashrate_regexes[i];
const m = str2.match(hashrate_regex[2]);
if (m) last_miner_hashrate = parseFloat(m[1]) * hashrate_regex[0] * algo_hashrate_factor(curr_algo);
}
}
}
function print_messages(str) {
if (!is_quiet_mode) print_all_messages(str);
}
// *** Miner socket processing
function set_curr_miner(socket, protocol) {
curr_miner_socket = socket;
curr_miner_protocol = protocol ? protocol : "default";
}
function grin_json_reply(method, result) {
return JSON.stringify({jsonrpc: "2.0", method: method, result: result}) + "\n";
}
function json_reply(json, result) {
return JSON.stringify({jsonrpc: "2.0", id: json.id, error: null, result: result}) + "\n";
}
function miner_socket_write(miner_socket, message) {
if (is_debug) log("Meta-Miner message to miner: " + message);
miner_socket.write(message);
}
function pool_socket_write(pool_socket, message) {
if (is_debug) log("Meta-Miner message to pool: " + message);
pool_socket.write(message);
}
let miner_server = net.createServer(function (miner_socket) {
if (curr_miner_socket) {
err("Miner server on " + c.miner_host + ":" + c.miner_port + " port is already connected (please make sure you do not have other miner running)");
miner_socket.end();
return;
}
if (is_verbose_mode) log("Miner server on " + c.miner_host + ":" + c.miner_port + " port connected from " + miner_socket.remoteAddress);
let miner_data_buff = "";
miner_socket.on('data', function (msg) {
miner_data_buff += msg;
if (miner_data_buff.indexOf('\n') === -1) return;
let messages = miner_data_buff.split('\n');
let incomplete_line = miner_data_buff.slice(-1) === '\n' ? '' : messages.pop();
for (let i = 0; i < messages.length; i++) {
let message = messages[i];
if (message.trim() === '') continue;
let json;
try {
json = JSON.parse(message);
} catch (e) {
err("Can't parse message from the miner: " + message);
continue;
}
if (is_debug) log("Miner message: " + JSON.stringify(json));
if (json.method === "login") {
if (curr_miner_socket) { // need to restart miner in case of second login attempt to clean its internal state
replace_miner(curr_miner);
} else {
miner_login_cb(json, miner_socket);
if (curr_miner_protocol !== "grin") miner_get_first_job_cb(json, miner_socket);
}
} else if (json.method === "mining.authorize") {
miner_login_cb(json, miner_socket);
miner_get_first_job_cb(json, miner_socket);
} else if (json.method === "getjobtemplate") { // only for grin
miner_get_first_job_cb(json, miner_socket);
} else if (json.method === "mining.subscribe") { // only for eth/raven
miner_subscribe_cb(json, miner_socket);
} else if (json.method === "mining.extranonce.subscribe") { // only for eth/raven
miner_socket_write(miner_socket, json_reply(json, true));
} else if (curr_pool_socket) {
pool_socket_write(curr_pool_socket, JSON.stringify(json) + "\n");
if (json.method === "submit" || json.method === "mining.submit") miner_last_submit_time = Date.now();
} else if (json.method !== "keepalived") {
err("Can't write miner reply to the pool since its socket is closed");
}
}
miner_data_buff = incomplete_line;
});
miner_socket.on('end', function() {
if (is_verbose_mode) log("Miner socket was closed");
if (curr_pool_socket && curr_miner_socket) err("Pool (" + c.pools[curr_pool_num] + ") <-> miner link was broken due to closed miner socket");
set_curr_miner(null);
});
miner_socket.on('error', function() {
err("Miner socket error");
if (curr_pool_socket && curr_miner_socket) err("Pool (" + c.pools[curr_pool_num] + ") <-> miner link was broken due to miner socket error");
miner_socket.destroy();
set_curr_miner(null);
});
});
// *** Miner start helpers
function start_miner_raw(exe, args, out_cb) {
const cmd = exe + " " + args.join(" ");
if (is_verbose_mode) log("Starting miner: " + cmd);
last_miner_hashrate = null;
last_algo_change_time = null;
is_want_miner_kill = false;
let proc = child_process.spawn(exe, args, is_miner_stdin ? {stdio: ['inherit', 'pipe', 'pipe']} : {});
proc.stdout.on('data', (data) => {
if (out_cb) out_cb(`${data}`);
});
proc.stderr.on('data', (data) => {
if (out_cb) out_cb(`${data}`);
});
proc.on('close', (code) => {
if (is_verbose_mode) {
if (code) err("Miner '" + cmd + "' exited with nonzero code " + code);
else log("Miner '" + cmd + "' exited with zero code");
}
if (curr_pool_socket && !is_want_miner_kill) {
log("Restarting '" + cmd + "' miner that was closed unexpectedly");
miner_proc = start_miner_raw(exe, args, out_cb);
}
});
proc.on('error', (error) => {
err("Failed to start '" + cmd + "' miner: " + error);
});
return proc;
}
function start_miner(cmd, out_cb) {
let args = cmd.match(/"[^"]+"|'[^']+'|\S+/g);
let exe = args.shift();
return start_miner_raw(exe, args, out_cb);
}
// *** Pool socket processing
function connect_pool(pool_num, pool_ok_cb, pool_new_msg_cb, pool_err_cb) {
let pool_address_parts = c.pools[pool_num].split(/:/);
const host = pool_address_parts[0];
let port = pool_address_parts[1];
let m = port.match(/^(?:ssl|tls)(\d+)$/);
let is_tls = false;
if (m) { is_tls = true; port = m[1]; }
let pool_socket = is_tls ? tls.connect(port, host, { rejectUnauthorized: false }) : net.connect(port, host);
pool_socket.on('connect', function () {
pool_socket_write(pool_socket, JSON.stringify({
id: 1, jsonrpc: "2.0", method: "login", params: {
login: c.user, pass: c.pass, agent: AGENT,
algo: Object.keys(c.algos), "algo-perf": c.algo_perf, "algo-min-time": c.algo_min_time
}
}) + "\n");
});
let is_pool_ok = false;
let pool_data_buff = "";
pool_socket.on('data', function (msg) {
pool_data_buff += msg;
if (pool_data_buff.indexOf('\n') === -1) return;
let messages = pool_data_buff.split('\n');
let incomplete_line = pool_data_buff.slice(-1) === '\n' ? '' : messages.pop();
for (let i = 0; i < messages.length; i++) {
let message = messages[i];
if (message.trim() === '') continue;
let json;
try {
json = JSON.parse(message);
} catch (e) {
err("Can't parse message from the pool (" + c.pools[pool_num] + "): " + message);
continue;
}
if (is_debug) log("Pool message: " + JSON.stringify(json));
if (!is_pool_ok && json.error === null) {
pool_ok_cb(pool_num, pool_socket);
is_pool_ok = true;
}
if (is_pool_ok) {
if (json.id === "mm" && json.error === null && json.result instanceof Object && json.result.status === "KEEPALIVED") {
if (is_verbose_mode) log("Keepalive reply recieved from the pool");
} else {
pool_new_msg_cb(json);
}
} else err("Ignoring pool (" + c.pools[pool_num] + ") message since pool not reported no errors yet: " + JSON.stringify(json));
}
pool_data_buff = incomplete_line;
});
pool_socket.on('end', function() {
pool_socket.destroy();
if (!is_pool_ok) {
err("Pool (" + c.pools[pool_num] + ") socket closed before sending first job");
pool_err_cb(pool_num);
} else if (is_verbose_mode) log("Pool (" + c.pools[pool_num] + ") socket closed");
});
pool_socket.on('error', function() {
err("Pool (" + c.pools[pool_num] + ") socket error");
pool_socket.destroy();
pool_err_cb(pool_num);
});
}
// *** connect_pool function callbacks
function set_main_pool_check_timer() {
if (is_verbose_mode) log("Will retry connection attempt to the main pool in 90 seconds");
main_pool_check_timer = setTimeout(connect_pool, 90*1000, 0, pool_ok, pool_new_msg, pool_err);
}
function pool_ok(pool_num, pool_socket) {
if (pool_num) {
if (!main_pool_check_timer) set_main_pool_check_timer();
} else {
if (main_pool_check_timer) {
if (is_verbose_mode) log("Stopped main pool connection attempts since its connection was established");
clearTimeout(main_pool_check_timer);
main_pool_check_timer = null;
}
}
if (curr_pool_socket) {
if (is_verbose_mode) log("Closing " + c.pools[curr_pool_num] + " pool socket");
curr_pool_socket.destroy();
}
if (!is_quiet_mode) log("Connected to " + c.pools[pool_num] + " pool");
if (!curr_pool_socket && curr_miner_socket) log("Pool (" + c.pools[pool_num] + ") <-> miner link was established due to new pool connection");
curr_pool_num = pool_num;
curr_pool_socket = pool_socket;
}
function replace_miner(next_miner) {
if (miner_proc) {
if (next_miner_to_run === null) {
next_miner_to_run = next_miner;
if (is_verbose_mode) log("Stopping '" + curr_miner + "' miner");
miner_proc.on('close', (code) => {
miner_proc = start_miner(next_miner_to_run, print_all_messages);
next_miner_to_run = null;
});
is_want_miner_kill = true;
tree_kill(miner_proc.pid);
} else {
next_miner_to_run = next_miner;
}
} else {
miner_proc = start_miner(next_miner, print_all_messages);
}
}
function pool_new_msg(json) {
let next_job_algo = null;
// record job updates and diff changes initiated by the pool
if ("method" in json) switch (json.method) {
case "job":
next_job_algo = "params" in json && "algo" in json.params ? json.params.algo : DEFAULT_ALGO; // for usual jobs
curr_pool_last_job = json.params;
break;
case "mining.notify":
next_job_algo = "algo" in json ? json.algo : DEFAULT_ALGO; // for Raven/Eth jobs
curr_pool_last_job = json.params;
break;
case "mining.set_target":
case "mining.set_difficulty":
curr_pool_last_target = json;
} else if ("result" in json && json.result instanceof Object && "id" in json.result) { // record miner id in login pool reply and job if any
curr_pool_miner_id = json.result.id;
if ("job" in json.result) {
next_job_algo = "algo" in json.result.job ? json.result.job.algo : DEFAULT_ALGO; // for the first job
curr_pool_last_job = json.result.job;
}
}
if (next_job_algo !== null) {
if (!(next_job_algo in c.algos)) {
err("Ignoring job with unknown algo " + next_job_algo + " sent by the pool (" + c.pools[curr_pool_num] + ")");
return;
}
if (curr_algo != next_job_algo) last_algo_change_time = Date.now();
curr_algo = next_job_algo;
const next_miner = c.algos[next_job_algo];
if (!curr_miner || curr_miner != next_miner) {
set_curr_miner(null);
if (!is_quiet_mode) log("Starting miner '" + next_miner + "' to process new " + next_job_algo + " algo");
curr_miner = next_miner;
replace_miner(next_miner);
}
}
if (curr_miner_socket) switch (curr_miner_protocol) {
case "grin":
if (next_job_algo !== null) miner_socket_write(curr_miner_socket, grin_json_reply("getjobtemplate", curr_pool_last_job));
else {
let grin_json = json;
if ("result" in grin_json && "status" in grin_json.result && grin_json.result.status === "OK") {
grin_json.method = "submit";
grin_json.result = "ok";
}
miner_socket_write(curr_miner_socket, JSON.stringify(grin_json) + "\n");
}
break;
default:
miner_socket_write(curr_miner_socket, JSON.stringify(json) + "\n");
}
}
function pool_err(pool_num) {
if (pool_num === 0 && curr_pool_num) { // this is main pool attempt error while we are on backup pool
if (!main_pool_check_timer) err("[INTERNAL ERROR] Unexpected main_pool_check_timer state in pool_err");
set_main_pool_check_timer();
return;
}
if (curr_pool_num != pool_num) err("[INTERNAL ERROR] Unexpected pool_num in pool_err");
if (curr_pool_socket && curr_miner_socket) err("Pool (" + c.pools[pool_num] + ") <-> miner link was broken due to pool socket error");
curr_pool_socket = null;
curr_pool_last_job = null;
curr_pool_miner_id = null;
curr_pool_last_target = null;
if (++ curr_pool_num >= c.pools.length) {
if (is_verbose_mode) log("Waiting 60 seconds before trying to connect to the same pools once again");
setTimeout(connect_pool, 60*1000, curr_pool_num = 0, pool_ok, pool_new_msg, pool_err);
} else {
connect_pool(curr_pool_num, pool_ok, pool_new_msg, pool_err);
}
}
// *** Miner execution checks
function set_first_miner_user_pass(json) {
if ("method" in json && "params" in json) {
if (c.user === null) {
if (json.method === "login" && (json.params instanceof Object) && "login" in json.params) {
c.user = json.params.login;
} else if (json.method === "mining.authorize" && Array.isArray(json.params) && json.params.length >= 1) {
c.user = json.params[0];
}
if (is_verbose_mode) log("Setting pool user to '" + c.user + "'");
}
if (c.pass === null) {
if (json.method === "login" && (json.params instanceof Object) && "pass" in json.params) {
c.pass = json.params.pass;
} else if (json.method === "mining.authorize" && Array.isArray(json.params) && json.params.length >= 2) {
c.pass = json.params[1];
}
if (is_verbose_mode) log("Setting pool pass to '" + c.pass + "'");
}
}
}
function check_miners(smart_miners, miners, cb) {
let check_miners = [];
smart_miners.forEach(function (cmd) {
check_miners.push(function(resolve) {
let miner_proc = null;
let timeout = setTimeout(function () {
err("Miner '" + cmd + "' was not connected and will be ignored");
miner_proc.on('close', (code) => { resolve(); });
tree_kill(miner_proc.pid);
}, 60*1000);
miner_login_cb = function(json) {
clearTimeout(timeout);
set_first_miner_user_pass(json);
if ("params" in json && (json.params instanceof Object) && "algo" in json.params && (json.params.algo instanceof Array)) {
json.params.algo.forEach(function (algo) {
if (is_verbose_mode) {
if (c.algos[algo]) log("Setting " + algo + " algo from '" + c.algos[algo] + "' to '" + cmd + "' miner");
else log("Setting " + algo + " algo to '" + cmd + "' miner");
}
c.algos[algo] = cmd;
c.algos[algo.replace('cryptonight', 'cn')] = cmd;
c.algos[algo.replace('randomx', 'rx')] = cmd;
});
} else {
err("Miner '" + cmd + "' does not report any algo and will be ignored");
}
miner_proc.on('close', (code) => { resolve(); });
tree_kill(miner_proc.pid);
};
miner_get_first_job_cb = function() {};
miner_subscribe_cb = function(json, miner_socket) {
miner_socket_write(miner_socket, json_reply(json, [ [ "mining.notify", "check", "EthereumStratum/1.0.0" ], "00", 7 ] ));
};
miner_proc = start_miner(cmd, print_messages);
});
});
for (let algo in miners) {
check_miners.push(function(resolve) {
const cmd = miners[algo];
let miner_proc = null;
let timeout = setTimeout(function () {
err("Miner '" + cmd + "' was not connected and will be ignored");
miner_proc.on('close', (code) => { resolve(); });
tree_kill(miner_proc.pid);
}, 60*1000);
miner_login_cb = function(json) {
clearTimeout(timeout);
set_first_miner_user_pass(json);
if (is_verbose_mode) {
if (c.algos[algo]) log("Setting " + algo + " algo from '" + c.algos[algo] + "' to '" + cmd + "' miner");
else log("Setting " + algo + " algo to '" + cmd + "' miner");
}
c.algos[algo] = cmd;
c.algos[algo.replace('cryptonight', 'cn')] = cmd;
c.algos[algo.replace('randomx', 'rx')] = cmd;
miner_proc.on('close', (code) => { resolve(); });
tree_kill(miner_proc.pid);
};
miner_get_first_job_cb = function() {};
miner_subscribe_cb = function(json, miner_socket) {
miner_socket_write(miner_socket, json_reply(json, [ [ "mining.notify", "check", "EthereumStratum/1.0.0" ], "00", 7 ] ));
};
miner_proc = start_miner(cmd, print_messages);
});
}
if (!is_quiet_mode && check_miners.length) log("Checking miner configurations (make sure they all configured to connect to " + c.miner_host + ":" + c.miner_port + " pool)");
function next_miner_check() {
if (check_miners.length === 0) return cb();
const check_miner = check_miners.shift();
check_miner(next_miner_check);
}
next_miner_check();
}
// *** Miner performance runs
function do_miner_perf_runs(cb) {
let miner_perf_runs = [];
for (let algo of bench_algos) {
if (c.algo_perf[algo] || !(algo in c.algos)) continue;
miner_perf_runs.push(function(resolve) {
log("Checking miner performance for " + algo + " algo");
const cmd = c.algos[algo];
let miner_proc = null;
let timeout = setTimeout(function () {
err("Can't find performance data in '" + cmd + "' miner output");
miner_proc.on('close', (code) => { resolve(); });
tree_kill(miner_proc.pid);
}, 5*60*1000);
miner_login_cb = function(json, miner_socket) {
curr_miner_protocol = json.method === "mining.authorize" ? "eth" : (json.id === "Stratum" || json.params.algorithm === "cuckarood29v" ? "grin" : "default");
switch (curr_miner_protocol) {
case "grin": miner_socket_write(miner_socket, grin_json_reply("login", "ok")); break;
case "eth": miner_socket_write(miner_socket, json_reply(json, true)); break;
}
};
miner_get_first_job_cb = function(json, miner_socket) {
switch (curr_miner_protocol) {
case "grin": miner_socket_write(miner_socket, JSON.stringify({
jsonrpc: "2.0",
id: "Stratum",
error: null,
method: "getjobtemplate",
result: {
difficulty: 99999999,
pre_pow: "0c0ccbc9035e0000000026c1674f64401b00e6c50b681f21bb5d5bb07be6d4a9d12a8cb2b493c9c039fee90877199a9dc04dccd734cf9b4b30eae84d06b94da19614536f3a87b0fe65f201",
algo: "cuckaroo",
edgebits: 29,
proofsize: algo === "c29s" ? 32 : (algo === "c29b" ? 40 : 48),
noncebytes: 4,
height: 0,
job_id: "100000000000000",
id: "100000000000000",
status: "OK",
}
}) + "\n");
break;
case "eth": switch (algo) {
case "kawpow": miner_socket_write(miner_socket, JSON.stringify({
jsonrpc: "2.0",
method: "mining.notify",
params: [
"benchmark1", // job_id
"4c38e8a5f7b2944d1e4274635d828519b97bc64a1f1c7896ecdbb139988aa0e8", // blob
"accf7d1311da015b8dd41569c845c0ac739f0637707b8a117119fe1b5aeaa011", // seed hash
"000000000002bd75000000000000000000000000000000000000000000000000", // target
true,
1500000,
"1b0290a7",
]
}) + "\n");
break;
case "ethash": miner_socket_write(miner_socket, JSON.stringify({
jsonrpc: "2.0",
method: "mining.set_difficulty",
params: [
1000000
],
}) + "\n" + JSON.stringify({
jsonrpc: "2.0",
method: "mining.notify",
params: [
"benchmark1", // job_id
"e79f0f63030bf691445c2b9d0266b24a9619e355194067f2ad2c73a8e0a26c65", // seed hash
"feb4243b885cd1af5337979f5d81849335cab197b4993e5c61ea4b43b43dbbc6", // hash
true,
]
}) + "\n");
break;
case "autolykos2": miner_socket_write(miner_socket, JSON.stringify({
jsonrpc: "2.0",
method: "mining.notify",
params: [
"benchmark1", // job_id
539302, // height
"920b5e8ed76f90e760469f04391ffaef3b5ecf1e1cb9363c449f490bc1564663", // hash
"",
"",
2, // block version
"82463468449557216163199121184281840485288878744226428810224501", // target
"",
true
]
}) + "\n");
break;
}
break;
default: miner_socket_write(miner_socket, JSON.stringify({
jsonrpc: "2.0",
id: "id" in json ? json.id : 1,
error: null,
result: {
id: "benchmark",
status: "OK",
job: {
target: "01000000",
blob: "7f7ffeeaa0db054f15eca39c843cb82c15e5c5a7743e06536cb541d4e96e90ffd31120b7703aa90000000076a6f6e34a9977c982629d8fe6c8b45024cafca109eef92198784891e0df41bc03",
seed_hash: "0000000000000000000000000000000000000000000000000000000000000001",
algo: algo,
height: 0,
job_id: "benchmark1",
id: "benchmark",
}
}
}) + "\n");
}
};
miner_subscribe_cb = function(json, miner_socket) {
miner_socket_write(miner_socket, json_reply(json, [ [ "mining.notify", "benchmark", "EthereumStratum/1.0.0" ], "00", 7 ] ));
};
let nr_prints_needed = -1;
let nr_prints_found = 0;
miner_proc = start_miner(cmd, function(str) {
print_messages(str);
str = str.replace(/\x1b\[[0-9;]*m/g, ""); // remove all colors
for (let i in hashrate_regexes) {
const hashrate_regex = hashrate_regexes[i];
const m = str.match(hashrate_regex[2]);
if (m) {
if (nr_prints_needed < 0) nr_prints_needed = hashrate_regex[1];
const hashrate = parseFloat(m[1]) * hashrate_regex[0] * algo_hashrate_factor(algo);
if (++nr_prints_found >= nr_prints_needed) {
const algo_deps = bench_algo_deps(algo, hashrate);
for (let algo_dep in algo_deps) {
log("Setting performance for " + algo_dep + " algo to " + algo_deps[algo_dep]);
c.algo_perf[algo_dep] = algo_deps[algo_dep];
}
miner_proc.on('close', (code) => { clearTimeout(timeout); resolve(); });
tree_kill(miner_proc.pid);
break;
} else {
log("Read performance for " + algo + " algo to " + hashrate + ", waiting for " +
(nr_prints_needed - nr_prints_found) + " more print(s).");
}
}
}
});
});
}
function next_miner_perf_run() {
if (miner_perf_runs.length === 0) return cb();
const miner_perf_run = miner_perf_runs.shift();
miner_perf_run(next_miner_perf_run);
}
next_miner_perf_run();
}
// *** Command line option handling
function print_help() {
console.log("Usage: mm.js [<config_file.json>] [options]");
console.log("Adding algo switching support to *any* stratum miner");
console.log("<config_file.json> is file name of config file to load before parsing options (mm.json by default)");
console.log("Config file and options should define at least one pool and miner:");
console.log("Options:");
console.log("\t--proc_title=<title> (-t): \t<title> to use as the process.title (default: meta-miner)");
console.log("\t--pool=<pool> (-p): \t<pool> is in pool_address:pool_port format, where pool_port can be <port_number> or ssl<port_number>");
console.log("\t--host=<hostname>: \tdefines host that will be used for miner connections (localhost 127.0.0.1 by default)");
console.log("\t--port=<number>: \tdefines port that will be used for miner connections (3333 by default)");
console.log("\t--user=<wallet> (-u): \t<wallet> to use as pool user login (will be taken from the first miner otherwise)");
console.log("\t--pass=<miner_id>: \t<miner_id> to use as pool pass login (will be taken from the first miner otherwise)");
console.log("\t--perf_<algo>=<hashrate> \tSets hashrate for algo that is: " + bench_algos.join(", "));
console.log("\t--algo_min_time=<seconds> \tSets <seconds> minimum time pool should keep our miner on one algo (0 default, set higher for starting miners)");
console.log("\t--miner=<command_line> (-m): \t<command_line> to start smart miner that can report algo itself");
console.log("\t--<algo>=<command_line>: \t<command_line> to start miner for <algo> that can not report it itself");
console.log("\t--watchdog=<seconds> (-w): \trestart miner if is does not submit work for <seconds> (600 by default, 0 to disable)");
console.log("\t--hashrate_watchdog=<percent>: \trestart miner if is hashrate dropped below <percent> value of of its expected hashrate (0 by default to disable)");
console.log("\t--miner_stdin: \tenables stdin (input) in miner");
console.log("\t--quiet (-q): \tdo not show miner output during configuration and also less messages");
console.log("\t--verbose (-v): \tshow more messages");
console.log("\t--debug: \tshow pool and miner messages");
console.log("\t--log=<file_name>: \t<file_name> of output log");
console.log("\t--no-config-save: \tDo not save config file");
console.log("\t--help (-help,-h,-?): \tPrints this help text");
}
function parse_argv(cb) {
let smart_miners = [];
let miners = {};
if (process.argv.length === 2) {
if (!load_config_file()) {
print_help();
cb();
return;
}
}
process.argv.slice(2).forEach(function (val, index) {
let m;
if (index === 0) {
if ((m = val.match(/^(.+\.json)$/)) && fs.existsSync(path.resolve(m[1]))) {
console_file = m[1];
load_config_file();
return;
} else {
load_config_file();
}
}
if (m = val.match(/^(?:--?help|-h|-\?)$/)) {
print_help();
process.exit(0);
} else if (m = val.match(/^(?:--proc_title|-t)=(.+)$/)) {
c.proc_title = m[1];
} else if (m = val.match(/^(?:--quiet|-q)$/)) {