-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathMiner.java
More file actions
1614 lines (1394 loc) · 56.6 KB
/
Miner.java
File metadata and controls
1614 lines (1394 loc) · 56.6 KB
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
/**
The MIT License (MIT)
Copyright (c) 2018 AroDev, adaptation portions (c) 2018 ProgrammerDan (Daniel Boston)
www.arionum.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of
the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.programmerdan.arionum.arionum_miner;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Random;
import java.util.Base64.Encoder;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.fusesource.jansi.Ansi.Color;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.programmerdan.arionum.arionum_miner.jna.*;
import com.diogonunes.jcdp.color.api.Ansi.Attribute;
import com.diogonunes.jcdp.color.api.Ansi.FColor;
import com.diogonunes.jcdp.color.api.Ansi.Attribute.*;
import com.diogonunes.jcdp.color.api.Ansi.BColor;
import com.diogonunes.jcdp.color.api.Ansi.FColor.*;
import com.diogonunes.jcdp.color.api.Ansi.BColor.*;
/**
* Miner wrapper.
*
* Implements hard fork 10800 -- Resistance
*/
@SuppressWarnings({ "unused" })
public class Miner implements UncaughtExceptionHandler {
public static final long UPDATING_DELAY = 2000l;
public static final long UPDATING_REPORT = 45000l;
public static final long UPDATING_STATS = 7500l;
private CPrint coPrint;
private int maxHashers;
/**
* Non-main thread group that handles submitting nonces.
*/
private final ExecutorService submitters;
/*
* Worker statistics
*/
private final ConcurrentLinkedQueue<HasherStats> deadWorkerSociety;
private final AtomicLong deadWorkers;
private final ConcurrentLinkedDeque<Report> deadWorkerSummaries;
private final ConcurrentHashMap<String, Long> deadWorkerLives;
/**
* One or more hashing threads.
*/
private final ExecutorService hashers;
protected final AtomicInteger hasherCount;
private final ConcurrentHashMap<String, Hasher> workers;
/**
* Idea here is some soft profiling; hashesPerSession records how many hashes a
* particular worker accomplishes in a session, which starts at some initial value;
* then we tune it based on observed results.
*/
private long hashesPerSession = 10l;
private static final long MIN_HASHES_PER_SESSION = 1l;
/**
* The session length is the target parameter generally tuned against
*/
private long sessionLength = 5000l;
private static final long MIN_SESSION_LENGTH = 5000l;
private static final long MAX_SESSION_LENGTH = 14000l;
private static final long REBALANCE_DELAY = 300000l;
private long lastRebalance;
private double lastRebalanceHashRate = Double.MAX_VALUE;
private double lastRebalanceTiC = 0.0d;
private long lastRebalanceSessionLength = 0l;
/**
* Last time we checked with workers
*/
private long lastWorkerReport;
/**
* Count of all hashes produced by workers.
*/
protected final AtomicLong hashes;
/**
* Record of best DL so far this block
*/
protected final AtomicLong bestDL;
/**
* Count of all submits attempted
*/
protected final AtomicLong sessionSubmits;
/**
* Count of submits rejected (orphan, or old data hashes)
*/
protected final AtomicLong sessionRejects;
protected final AtomicLong blockShares;
protected final AtomicLong blockFinds;
/**
* Let's thread off updating. We'll just hash constantly, and offload updating like submitting.
*/
private final ExecutorService updaters;
protected boolean active = false;
protected boolean colors = false;
/* ==== Now update / init vars ==== */
private MinerType type;
private AdvMode hasherMode;
/* Block / Data related */
private String node;
private String worker;
private String publicKey;
private String privateKey;
private String data;
private BigInteger difficulty;
private long limit;
private long height;
private long lastBlockUpdate;
/* Update related */
private AtomicLong lastSpeed;
private AtomicLong speedAccrue;
private long lastUpdate;
private long lastReport;
private int cycles;
private int supercycles;
private int skips;
private int failures;
private int updates;
/* stats on update timing */
private final AtomicLong updateTimeAvg;
private final AtomicLong updateTimeMax;
private final AtomicLong updateTimeMin;
private final AtomicLong updateParseTimeAvg;
private final AtomicLong updateParseTimeMax;
private final AtomicLong updateParseTimeMin;
/* stats on submission timing */
private final AtomicLong submitTimeAvg;
private final AtomicLong submitTimeMax;
private final AtomicLong submitTimeMin;
private final AtomicLong submitParseTimeAvg;
private final AtomicLong submitParseTimeMax;
private final AtomicLong submitParseTimeMin;
protected final long wallClockBegin;
/* AUTO BOT MODE */
private Profile activeProfile;
private TreeSet<Profile> evaluatedProfiles;
private ConcurrentLinkedQueue<Profile> profilesToEvaluate;
private int coreCap;
private long nextProfileSwap;
private long profilesTested;
protected static final long TEST_PERIOD = 270000; // 4.5 minutes
protected static final long INIT_DELAY = 30000; // .5 minutes
/* Future todo: reassess periodically */
private long nextReassess;
private Profile toReassess;
/* External stats reporting */
private String statsHost;
private String statsInvoke;
private String statsToken;
private boolean post;
private ConcurrentHashMap<String, HasherStats> statsStage;
private ConcurrentLinkedQueue<HasherStats> statsReport;
private final ExecutorService stats;
protected static final long REPORTING_INTERVAL = 60000l; // 60 seconds
public static void main(String[] args) {
Miner miner = null;
try (Scanner console = new Scanner(System.in)) {
if (args == null || args.length == 0) {
args = new String[] { "config.cfg" };
}
// let's try to load a config file first.
if (args.length == 1) {
// config file?
ArrayList<String> lines = new ArrayList<>();
File config = new File(args[0]);
if (config.exists() && config.canRead()) {
System.out.println(" Attempting to open " + args[0] + " as a config file for arionum-java-miner");
BufferedReader in = new BufferedReader(new FileReader(config));
String line = null;
while ((line = in.readLine()) != null) {
lines.add(line);
}
in.close();
miner = new Miner(lines.toArray(new String[] {}));
} else if (config.exists()) {
miner = new Miner(args); // will cause error, probably.
} else {
System.out.print(" Would you like to generate a config and save it to " + args[0] + "? (y/N) ");
String input = console.nextLine();
if ("y".equalsIgnoreCase(input)) {
System.out.print(" Choose type? (solo/pool) ");
String type = console.nextLine();
if ("solo".equalsIgnoreCase(type)) {
lines.add("solo");
System.out.print(" Node to connect to? ");
lines.add(console.nextLine());
System.out.print(" Public key to use with node? ");
String address = console.nextLine();
lines.add(address);
System.out.print(" Private key to use with node? ");
String paddress = console.nextLine();
lines.add(paddress);
/*System.out.println(
" Would you like autotuning to occur? This will try to maximize your H/s ");
System.out.println(
" over the course of many minutes by adjusting hashers and parameters. (y/N)");
if ("y".equalsIgnoreCase(console.nextLine())) {
lines.add("-1");
lines.add("auto");
} else {*/
int defaultHashers = Runtime.getRuntime().availableProcessors();
System.out.print(" Simultaneous hashers to run? (you have "
+ Runtime.getRuntime().availableProcessors()
+ " cores, leave blank for default of " + defaultHashers + ") ");
String iterations = console.nextLine();
if (iterations == null || iterations.trim().isEmpty()) {
lines.add(String.valueOf(defaultHashers));
} else {
lines.add(iterations);
}
/*
* System.out.print(" Core type? (standard) "); String core = console.nextLine(); if (core == null || core.trim().isEmpty()) { lines.add("stable"); } else { lines.add(core); }
*/
lines.add("standard");
//}
System.out.print(" Activate colors? (y/N) ");
if ("y".equalsIgnoreCase(console.nextLine())) {
lines.add("true");
} else {
lines.add("false");
}
String workerName = Miner.php_uniqid();
System.out.println(" Worker name to report to node? (Each worker should have a unique name, leave empty for default: " + workerName + ") ");
String tWorker = console.nextLine();
if (tWorker != null && !tWorker.trim().isEmpty()) {
lines.add(tWorker.trim());
} else {
lines.add(workerName);
}
} else if ("pool".equalsIgnoreCase(type)) {
lines.add("pool");
System.out.print(" Pool to connect to? (leave empty for http://aropool.com) ");
String pool = console.nextLine();
if (pool == null || pool.trim().isEmpty()) {
lines.add("http://aropool.com");
} else {
lines.add(pool);
}
System.out.print(" Wallet address to use to claim shares? ");
String address = console.nextLine();
lines.add(address);
/*System.out.println(
" Would you like autotuning to occur? This will try to maximize your H/s ");
System.out.println(
" over the course of many minutes by adjusting hashers and parameters. (y/N)");
if ("y".equalsIgnoreCase(console.nextLine())) {
lines.add("-1");
lines.add("auto");
} else {*/
int defaultHashers = Runtime.getRuntime().availableProcessors();
System.out.print(" Simultaneous hashers to run? (you have "
+ Runtime.getRuntime().availableProcessors()
+ " cores, leave blank for default of " + defaultHashers + ") ");
String iterations = console.nextLine();
if (iterations == null || iterations.trim().isEmpty()) {
lines.add(String.valueOf(defaultHashers));
} else {
lines.add(iterations);
}
/*
* System.out.print(" Core type? (stable/basic/debug/experimental - default stable) "); String core = console.nextLine(); if (core == null || core.trim().isEmpty()) { lines.add("stable"); } else {
* lines.add(core); }
*/
lines.add("standard");
//}
System.out.print(" Activate colors? (y/N) ");
if ("y".equalsIgnoreCase(console.nextLine())) {
lines.add("true");
} else {
lines.add("false");
}
String workerName = Miner.php_uniqid();
System.out.println(" Worker name to report to node? (Each worker should have a unique name, leave empty for default: " + workerName + ") ");
String tWorker = console.nextLine();
if (tWorker != null && !tWorker.trim().isEmpty()) {
lines.add(tWorker.trim());
} else {
lines.add(workerName);
}
} else if ("test".equalsIgnoreCase(type)) {
lines.add("test");
lines.add("http://aropool.com");
System.out.print(" address to use in test run if needed by tests? ");
String address = console.nextLine();
lines.add(address);
System.out.print(" iterations of tests to run? ");
String iterations = console.nextLine();
lines.add(iterations);
} else if ("benchmark".equalsIgnoreCase(type)) {
lines.add("benchmark");
System.out.println("Apologies, this mode is not available yet");
System.exit(1);
System.out.print(" Pool to connect to? (leave empty for http://aropool.com) ");
String pool = console.nextLine();
if (pool == null || pool.trim().isEmpty()) {
lines.add("http://aropool.com");
} else {
lines.add(pool);
}
System.out.print(" Wallet address to use to claim shares? ");
String address = console.nextLine();
lines.add(address);
System.out.print(" Location of python binary? ");
String python = console.nextLine();
lines.add(python);
System.out.print(" Location of python hasher? ");
python = console.nextLine();
lines.add(python);
System.out.print(" Location of php binary? ");
String php = console.nextLine();
lines.add(php);
System.out.print(" Location of php hasher? ");
php = console.nextLine();
lines.add(php);
int defaultHashers = Runtime.getRuntime().availableProcessors() ;
System.out.print(" Max simultaneous hashers to benchmark? (you have "
+ Runtime.getRuntime().availableProcessors() + " cores, leave blank for default of "
+ defaultHashers + ") ");
String iterations = console.nextLine();
if (iterations == null || iterations.trim().isEmpty()) {
lines.add(String.valueOf(defaultHashers));
} else {
lines.add(iterations);
}
} else {
System.err.println("I don't recognize that type. Aborting!");
System.exit(1);
}
miner = new Miner(lines.toArray(new String[] {}));
try (PrintWriter os = new PrintWriter(new FileWriter(config))) {
for (String line : lines) {
os.println(line);
}
os.flush();
} catch (IOException ie) {
System.err.println(
"Failed to save settings ... continuing. Check permissions? Error message: "
+ ie.getMessage());
}
}
}
} else {
miner = new Miner(args);
}
} catch (Exception e) {
System.err.println("Failed to initialize! Check config? Error message: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
Thread.setDefaultUncaughtExceptionHandler(miner);
miner.start();
}
public Miner(String[] args) {
this.hasherMode = AdvMode.standard;
this.worker = php_uniqid();
this.updaters = Executors.newSingleThreadExecutor();
this.submitters = Executors.newCachedThreadPool();
this.hasherCount = new AtomicInteger();
this.workers = new ConcurrentHashMap<String, Hasher>();
this.deadWorkerSociety = new ConcurrentLinkedQueue<>();
this.deadWorkers = new AtomicLong(0l);
this.deadWorkerLives = new ConcurrentHashMap<String, Long>();
this.blockFinds = new AtomicLong();
this.blockShares = new AtomicLong();
this.deadWorkerSummaries = new ConcurrentLinkedDeque<>();
/* autotune */
activeProfile = null;
TreeSet<Profile> evaluatedProfiles = new TreeSet<Profile>();
ConcurrentLinkedQueue<Profile> profilesToEvaluate = new ConcurrentLinkedQueue<Profile>();
int coreCap = Runtime.getRuntime().availableProcessors();
long nextProfileSwap = 0;
long profilesTested = 0;
/* end autotune */
/* stats report */
this.statsHost = null;
this.statsInvoke= "report.php";
this.statsToken = php_uniqid();
this.post = false;
this.statsStage = new ConcurrentHashMap<String, HasherStats>();
this.statsReport = new ConcurrentLinkedQueue<HasherStats>();
this.stats = Executors.newCachedThreadPool();
/* end stats report */
this.hashes = new AtomicLong();
this.bestDL = new AtomicLong(Long.MAX_VALUE);
this.sessionSubmits = new AtomicLong();
this.sessionRejects = new AtomicLong();
this.lastSpeed = new AtomicLong();
this.speedAccrue = new AtomicLong();
this.updateTimeAvg = new AtomicLong();
this.updateTimeMax = new AtomicLong(Long.MIN_VALUE);
this.updateTimeMin = new AtomicLong(Long.MAX_VALUE);
this.updateParseTimeAvg = new AtomicLong();
this.updateParseTimeMax = new AtomicLong(Long.MIN_VALUE);
this.updateParseTimeMin = new AtomicLong(Long.MAX_VALUE);
this.submitTimeAvg = new AtomicLong();
this.submitTimeMax = new AtomicLong(Long.MIN_VALUE);
this.submitTimeMin = new AtomicLong(Long.MAX_VALUE);
this.submitParseTimeAvg = new AtomicLong();
this.submitParseTimeMax = new AtomicLong(Long.MIN_VALUE);
this.submitParseTimeMin = new AtomicLong(Long.MAX_VALUE);
try {
this.type = MinerType.valueOf(args[0]);
this.node = args[1].trim();
this.publicKey = args[2].trim();
if (MinerType.solo.equals(this.type)) {
this.privateKey = args[3].trim();
this.maxHashers = args.length > 4 ? Integer.parseInt(args[4].trim()) : 1;
if (args.length > 5) {
this.hasherMode = AdvMode.valueOf(args[5].trim());
}
if (args.length > 6) {
this.colors = Boolean.parseBoolean(args[6].trim());
}
if (args.length > 7) {
String workerName = args[7] != null ? args[7].trim() : null;
if (workerName != null && !"".equals(workerName)) {
this.worker = workerName;
} // else we leave "new" name.
}
if (args.length > 8) {
String[] statsReport = args[8] != null ? args[8].trim().split(" ") : null;
if (statsReport != null && statsReport.length > 2) {
this.statsHost = statsReport[0];
this.statsInvoke = statsReport[1];
this.post = statsReport[2].equalsIgnoreCase("y") ? true : statsReport[2].equalsIgnoreCase("n") ? false : Boolean.parseBoolean(statsReport[2]);
}
if (statsReport != null && statsReport.length > 3) {
this.statsToken = statsReport[3];
}
}
} else if (MinerType.pool.equals(this.type)) {
this.privateKey = this.publicKey;
this.maxHashers = args.length > 3 ? Integer.parseInt(args[3].trim()) : 1;
if (args.length > 4) {
this.hasherMode = AdvMode.valueOf(args[4].trim());
}
if (args.length > 5) {
this.colors = Boolean.parseBoolean(args[5].trim());
}
if (args.length > 6) {
String workerName = args[6] != null ? args[6].trim() : null;
if (workerName != null && !"".equals(workerName)) {
this.worker = workerName;
} // else we leave "new" name.
}
if (args.length > 7) {
String[] statsReport = args[7] != null ? args[7].trim().split(" ") : null;
if (statsReport != null && statsReport.length > 2) {
this.statsHost = statsReport[0];
this.statsInvoke = statsReport[1];
this.post = statsReport[2].equalsIgnoreCase("y") ? true : statsReport[2].equalsIgnoreCase("n") ? false : Boolean.parseBoolean(statsReport[2]);
}
if (statsReport != null && statsReport.length > 3) {
this.statsToken = statsReport[3];
}
}
} else if (MinerType.test.equals(this.type)) { // internal test mode, transient benchmarking.
this.maxHashers = args.length > 3 ? Integer.parseInt(args[3].trim()) : 1;
}
if (AdvMode.auto.equals(this.hasherMode)) {
this.maxHashers = -1;
}
coPrint = new CPrint(colors);
coPrint.a(Attribute.BOLD).f(FColor.CYAN).ln("Active config:")
.clr().f(FColor.CYAN).p(" type: ").f(FColor.GREEN).ln(this.type)
.clr().f(FColor.CYAN).p(" node: ").f(FColor.GREEN).ln(this.node)
.clr().f(FColor.CYAN).p(" public-key: ").f(FColor.GREEN).ln(this.publicKey)
.clr().f(FColor.CYAN).p(" private-key: ").f(FColor.GREEN).ln(this.privateKey)
.clr().f(FColor.CYAN).p(" hasher-count: ").f(FColor.GREEN).ln(this.maxHashers)
.clr().f(FColor.CYAN).p(" hasher-mode: ").f(FColor.GREEN).ln(this.hasherMode)
.clr().f(FColor.CYAN).p(" colors: ").f(FColor.GREEN).ln(this.colors)
.clr().f(FColor.CYAN).p(" worker-name: ").f(FColor.GREEN).ln(this.worker).clr();
} catch (Exception e) {
System.err.println("Invalid configuration: " + (e.getMessage()));
System.err.println(" type: " + this.type);
System.err.println(" node: " + this.node);
System.err.println(" public-key: " + this.publicKey);
System.err.println(" private-key: " + this.privateKey);
System.err.println(" hasher-count: " + this.maxHashers);
System.err.println(" hasher-mode: " + this.hasherMode);
System.err.println(" colors: " + this.colors);
System.err.println(" worker-name: " + this.worker);
System.err.println();
System.err.println("Usage: ");
System.err.println(" java -jar arionum-miner-java.jar");
System.err.println(
" java -jar arionum-miner-java.jar pool http://aropool.com address [#hashers] [standard] [true|false] [workername]");
System.err.println(
" java -jar arionum-miner-java.jar solo node-address pubKey priKey [#hashers] [standard] [true|false] [workername]");
System.err.println(" where:");
System.err.println(" [#hashers] is # of hashers to spin up. Default 1.");
System.err.println(
" [standard] is type of hasher to run. At present, only standard. More options will come.");
System.err.println(
" [true|false] is if colored output is enabled.");
System.err.println(
" [workername] is name to report to pool or node. Should be unique per worker.");
System.exit(1);
}
coPrint.f(FColor.WHITE).a(Attribute.DARK).p("You have ")
.a(Attribute.NONE).p(Runtime.getRuntime().availableProcessors()).a(Attribute.DARK).p(" processors vs. ")
.a(Attribute.DARK).p(this.maxHashers).a(Attribute.NONE).ln(" hashers. ").clr();
this.hashers = Executors.newFixedThreadPool(
this.maxHashers > 0 ? this.maxHashers : Runtime.getRuntime().availableProcessors(),
new AggressiveAffinityThreadFactory("HashMasher", true));
this.limit = 240; // default
this.wallClockBegin = System.currentTimeMillis();
}
public void start() {
if (MinerType.test.equals(this.type)) {
startTest();
return;
}
// commit e14b696362fb port to java from arionum/miner
if (MinerType.pool.equals(this.type)) {
String decode = Utility.base58_decode(this.publicKey);
if (decode.length() != 64) {
this.coPrint.a(Attribute.BOLD).f(FColor.RED).ln("ERROR: Invalid Arionum address!").clr();
System.exit(1);
}
}
// end commit e14b696362fb
if (AdvMode.auto.equals(this.hasherMode)) {
// BOOTSTRAP
for (AdvMode mode : AdvMode.values()) {
if (mode.useThis()) {
Profile execProfile = new Profile(mode);
this.profilesToEvaluate.offer(execProfile);
}
}
nextProfileSwap = System.currentTimeMillis();
activeProfile = null;
profilesTested = 0;
}
active = true;
this.lastUpdate = wallClockBegin;
final AtomicBoolean firstRun = new AtomicBoolean(true);
cycles = 0;
supercycles = 0;
final AtomicBoolean sentSpeed = new AtomicBoolean(false);
skips = 0;
failures = 0;
updates = 0;
while (active) {
boolean updateLoop = true;
int firstAttempts = 0;
while (updateLoop) {
Future<Boolean> update = this.updaters.submit(new Callable<Boolean>() {
public Boolean call() {
long executionTimeTracker = System.currentTimeMillis();
try {
if (cycles > 0 && (System.currentTimeMillis() - lastUpdate) < (UPDATING_DELAY * .5)) {
skips++;
return Boolean.FALSE;
}
boolean endline = false;
String cummSpeed = speed();
StringBuilder extra = new StringBuilder(node);
extra.append("/mine.php?q=info");
if (MinerType.pool.equals(type)) {
extra.append("&worker=").append(URLEncoder.encode(worker, "UTF-8"));
// recommend not to constantly update this either, so send in first update then not again for 10 mins.
if (firstRun.get() || (!sentSpeed.get() && supercycles > 15)) {
extra.append("&address=").append(privateKey);
}
// All the frequent speed sends was placing a large UPDATE burden on the pool, so now
// first h/s is sent 30s after start, and every 10 mins after that. Should help.
if (!sentSpeed.get() && supercycles > 15) {
extra.append("&hashrate=").append(cummSpeed);
sentSpeed.set(true);
}
}
URL url = new URL(extra.toString());
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
// Having some weird cases on certain OSes where apparently the netstack
// is by default unbounded timeout, so the single thread executor is
// stuck forever waiting for a reply that will never come.
// This should address that.
con.setConnectTimeout(1000);
con.setReadTimeout(1000);
int status = con.getResponseCode();
lastUpdate = System.currentTimeMillis();
if (status != HttpURLConnection.HTTP_OK) {
coPrint.updateLabel().p("Update failure: ")
.a(Attribute.UNDERLINE).f(FColor.RED).b(BColor.NONE).ln(con.getResponseMessage()).clr();
con.disconnect();
failures++;
updateTime(System.currentTimeMillis() - executionTimeTracker);
return Boolean.FALSE;
}
long parseTimeTracker = System.currentTimeMillis();
JSONObject obj = (JSONObject) (new JSONParser())
.parse(new InputStreamReader(con.getInputStream()));
if (!"ok".equals((String) obj.get("status"))) {
coPrint.updateLabel().p("Update failure: ")
.a(Attribute.UNDERLINE).f(FColor.RED).b(BColor.NONE).p(obj.get(status))
.a(Attribute.LIGHT).f(FColor.CYAN).ln(". We will try again shortly!").clr();
con.disconnect();
failures++;
updateTime(System.currentTimeMillis(), executionTimeTracker, parseTimeTracker);
return Boolean.FALSE;
}
JSONObject jsonData = (JSONObject) obj.get("data");
String localData = (String) jsonData.get("block");
if (!localData.equals(data)) {
coPrint.updateLabel().p("Update transitioned to new block. ").clr();
if (lastBlockUpdate > 0) {
coPrint.updateMsg().p(" Last block took: ")
.normData().p( ((System.currentTimeMillis() - lastBlockUpdate) / 1000)).unitLabel().p("s ").clr();
}
data = localData;
lastBlockUpdate = System.currentTimeMillis();
long bestDLLastBlock = bestDL.getAndSet(Long.MAX_VALUE);
coPrint.updateLabel().p("Best DL on last block: ")
.dlData().p(bestDLLastBlock).unitLabel().p(" ").clr();
endline = true;
}
BigInteger localDifficulty = new BigInteger((String) jsonData.get("difficulty"));
if (!localDifficulty.equals(difficulty)) {
coPrint.updateMsg().p("Difficulty updated to ")
.dlData().p(localDifficulty).unitLabel().p(". ").clr();
difficulty = localDifficulty;
endline = true;
}
long localLimit = 0;
if (MinerType.pool.equals(type)) {
localLimit = Long.parseLong(jsonData.get("limit").toString());
publicKey = (String) jsonData.get("public_key");
} else {
localLimit = 240;
}
if (limit != localLimit) {
limit = localLimit;
}
long localHeight = (Long) jsonData.get("height");
if (localHeight != height) {
coPrint.updateMsg().p("New Block Height: ")
.normData().p(localHeight).unitLabel().p(". ").clr();
height = localHeight;
endline = true;
}
if (endline) {
updateWorkers();
}
long sinceLastReport = System.currentTimeMillis() - lastReport;
if (sinceLastReport > UPDATING_REPORT) {
lastReport = System.currentTimeMillis();
coPrint.ln().info().p("Node: ").textData().fs(node).p(" ")
.info().p("MinDL: ").dlData().fd(limit).p(" ")
.info().p("BestDL: ").dlData().fd(bestDL.get()).p(" ")
.info().p("Block Height: ").normData().fd(height).ln()
.p(" ").info().p("Time on Block: ").normData().fd(((System.currentTimeMillis() - lastBlockUpdate) / 1000)).unitLabel().p("s ")
.info().p("Inverse Difficulty: ").dlData().fd(difficulty.longValue()).clr();
coPrint.ln().info().p(" Updates: Last ").normData().fd((sinceLastReport / 1000))
.unitLabel().p("s").info().p(": ").normData().fd(updates)
.info().p(" Failed: ").normData().fd(failures+skips)
.info().p(" Avg Update RTT: ").normData().fd((updates > 0 ? (updateTimeAvg.get() / (updates + failures)) : 0))
.unitLabel().p("ms").clr();
coPrint.ln().info().p(" Shares: Attempted: ").normData().fd(sessionSubmits.get())
.info().p(" Rejected: ").normData().fd(sessionRejects.get())
.info().p(" Eff: ").normData().fp("%.2f", (sessionSubmits.get() > 0 ? 100d * ((double) (sessionSubmits.get() - sessionRejects.get()) / (double)sessionSubmits.get()) : 100.0d ))
.unitLabel().p("%")
.info().p(" Avg Hash/nonce: ").normData().fd((sessionSubmits.get() > 0 ? Math.floorDiv(hashes.get(), sessionSubmits.get()) : hashes.get()))
.info().p(" Avg Submit RTT: ").normData().fd((sessionSubmits.get() > 0 ? submitTimeAvg.get() / (sessionSubmits.get() + sessionRejects.get()) : 0))
.unitLabel().p("ms").clr();
coPrint.ln().info().p(" Overall: Hashes: ").normData().fd(hashes.get())
.info().p(" Mining Time: ").normData().fd(((System.currentTimeMillis() - wallClockBegin) / 1000l))
.unitLabel().p("s")
.info().p(" Avg Speed: ").normData().fs(avgSpeed(wallClockBegin))
.unitLabel().p("H/s")
.info().p(" Reported Speed: ").normData().fs(cummSpeed)
.unitLabel().p("H/s").clr();
printWorkerHeader();
updateTimeAvg.set(0);
updateTimeMax.set(Long.MIN_VALUE);
updateTimeMin.set(Long.MAX_VALUE);
updateParseTimeAvg.set(0);
updateParseTimeMax.set(Long.MIN_VALUE);
updateParseTimeMin.set(Long.MAX_VALUE);
submitParseTimeAvg.set(0);
submitParseTimeMax.set(Long.MIN_VALUE);
submitParseTimeMin.set(Long.MAX_VALUE);
skips = 0;
failures = 0;
updates = 0;
endline = true;
clearSpeed();
}
con.disconnect();
updates++;
updateTime(System.currentTimeMillis(), executionTimeTracker, parseTimeTracker);
if (endline) {
System.out.println();
}
if ((sinceLastReport % UPDATING_STATS) < UPDATING_DELAY && sinceLastReport < 5000000000l) {
printWorkerStats();
}
return Boolean.TRUE;
} catch (IOException | ParseException e) {
lastUpdate = System.currentTimeMillis();
if (!(e instanceof SocketTimeoutException)) {
coPrint.updateLabel().p("Non-fatal Update failure: ").textData().p(e.getMessage()).updateMsg().ln(" We will try again in a moment.").clr();
//e.printStackTrace();
}
failures++;
updateTime(System.currentTimeMillis() - executionTimeTracker);
return Boolean.FALSE;
}
}
});
if (firstRun.get()) { // Failures after initial are probably just temporary so we ignore them.
try {
if (update.get().booleanValue()) {
firstRun.set( false );
updateLoop = false;
} else {
firstAttempts++;
}
} catch (InterruptedException | ExecutionException e) {
coPrint.a(Attribute.BOLD).f(FColor.RED).p("Unable to successfully complete first update: ").textData().ln(e.getMessage()).clr();
} finally {
if (firstRun.get() && firstAttempts > 15) { // failure!
coPrint.a(Attribute.BOLD).f(FColor.RED).ln("Unable to contact node in pool, please check connection and try again.").clr();
active = false;
firstRun.set( false );
updateLoop = false;
break;
} else if (firstRun.get()) {
coPrint.a(Attribute.BOLD).f(FColor.RED).ln("Pool did not respond (attempt " + firstAttempts + " of 15). Trying again in 5 seconds.").clr();
try {
Thread.sleep(5000l);
} catch (InterruptedException ie) {
active = false;
firstRun.set( false );
updateLoop = false;
// interruption shuts us down.
coPrint.a(Attribute.BOLD).f(FColor.RED).ln("Interruption detection, shutting down.").clr();
}
}
}
lastWorkerReport = System.currentTimeMillis();
} else {
updateLoop = false;
}
}
if (!AdvMode.auto.equals(this.hasherMode) && this.hasherCount.get() < maxHashers) {
String workerId = this.deadWorkers.getAndIncrement() + "]" + php_uniqid();
this.deadWorkerLives.put(workerId, System.currentTimeMillis());
Hasher hasher = HasherFactory.createHasher(hasherMode, this, workerId, this.hashesPerSession, (long) this.sessionLength * 2l);
updateWorker(hasher);
this.hashers.submit(hasher);
addWorker(workerId, hasher);
} else if (AdvMode.auto.equals(this.hasherMode)) { // auto adjust!
Profile newActiveProfile = activeProfile;
// Check, have we any profile active? If not, pick a bootstrap profile.
if (activeProfile == null) {
newActiveProfile = profilesToEvaluate.poll();
// Now check, are we done profiling out current profile?
} else if (Profile.Status.DONE.equals(activeProfile.getStatus())) {
// We are done, do we have any left to check?
if (profilesToEvaluate.isEmpty()) {
// check how it stacks up; if this profile is highest, check if we have more profiling work to do.
// Otherwise, if not highest, switch to best.
evaluatedProfiles.add(activeProfile);
newActiveProfile = evaluatedProfiles.pollLast();
// We do have more to check! Let's lodge what we learned and switch profiles.
} else {
evaluatedProfiles.add(activeProfile);
newActiveProfile = profilesToEvaluate.poll();
}
}
if (activeProfile == null || !newActiveProfile.equals(activeProfile)) {
coPrint.updateMsg().p("About to evaluate profile ").textData().ln(newActiveProfile.toString()).clr();
// reconfigure!
activeProfile = newActiveProfile;
}
}
try {
Thread.sleep(UPDATING_DELAY);
} catch (InterruptedException ie) {
active = false;
// interruption shuts us down.
coPrint.a(Attribute.BOLD).f(FColor.RED).ln("Interruption detection, shutting down.").clr();
}
if (cycles == 30) {
cycles = 0;
}
if (supercycles == 300) { // 10 minutes
supercycles = 0;
sentSpeed.set(false);
}
if (cycles % 2 == 0) {
refreshFromWorkers();
}
updateStats();
cycles++;
supercycles++;
}
this.updaters.shutdown();
this.hashers.shutdown();
this.submitters.shutdown();
}
protected void addWorker(String workerId, Hasher hasher) {
workers.put(workerId, hasher);
}
protected void releaseWorker(String workerId) {
workers.remove(workerId);
}
/**
* We update all workers with latest information from pool / node
*/
protected void updateWorkers() {
workers.forEach((workerId, hasher) -> {
if (hasher != null && hasher.isActive()) {
updateWorker(hasher);
}
});
}