-
Notifications
You must be signed in to change notification settings - Fork 7
/
ccminer.cpp
3040 lines (2700 loc) · 74.9 KB
/
ccminer.cpp
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
/*
* Copyright 2010 Jeff Garzik
* Copyright 2012-2014 pooler
*
* 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 2 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "cpuminer-config.h"
#include "cuda_runtime_api.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <curl/curl.h>
#include <jansson.h>
#include <openssl/sha.h>
#ifdef WIN32
#include <windows.h>
#include <stdint.h>
#else
#include <errno.h>
#include <sys/resource.h>
#if HAVE_SYS_SYSCTL_H
#include <sys/types.h>
#if HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <sys/sysctl.h>
#endif
#endif
//#include "nvml.h"
#include "cuda_runtime.h"
//#include "gpu_utils.h"
#include "miner.h"
#ifdef WIN32
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib")
#include "compat/winansi.h"
BOOL WINAPI ConsoleHandler(DWORD);
#endif
#define PROGRAM_NAME "ccminer"
#define LP_SCANTIME 30
#define HEAVYCOIN_BLKHDR_SZ 84
#define MNR_BLKHDR_SZ 80
// from cuda.cpp
int cuda_num_devices();
void cuda_devicenames();
void cuda_devicenames();
void cuda_devicereset();
void cuda_print_devices();
int cuda_finddevice(char *name);
#include "nvml.h"
#ifdef USE_WRAPNVML
nvml_handle *hnvml = NULL;
#endif
enum workio_commands {
WC_GET_WORK,
WC_SUBMIT_WORK,
WC_ABORT,
};
struct workio_cmd {
enum workio_commands cmd;
struct thr_info *thr;
union {
struct work *work;
} u;
};
enum sha_algos {
ALGO_BASTION,
ALGO_BITC,
ALGO_BITCOIN,
ALGO_BLAKE,
ALGO_BLAKECOIN,
ALGO_C11,
ALGO_DEEP,
ALGO_DMD_GR,
ALGO_DOOM,
ALGO_FRESH,
ALGO_FUGUE256, /* Fugue256 */
ALGO_GROESTL,
ALGO_HEAVY, /* Heavycoin hash */
ALGO_KECCAK,
ALGO_JACKPOT,
ALGO_LUFFA_DOOM,
ALGO_LYRA2,
ALGO_LYRA2v2,
ALGO_MJOLLNIR, /* Hefty hash */
ALGO_MYR_GR,
ALGO_NIST5,
ALGO_PENTABLAKE,
ALGO_QUARK,
ALGO_QUBIT,
ALGO_SCRYPT,
ALGO_SCRYPT_JANE,
ALGO_SKEIN,
ALGO_S3,
ALGO_SPREADX11,
ALGO_WHC,
ALGO_WHCX,
ALGO_X11,
ALGO_X13,
ALGO_X14,
ALGO_X15,
ALGO_X17,
ALGO_NEO,
ALGO_COUNT
};
static const char *algo_names[] = {
"bastion",
"credit",
"bitcoin",
"blake",
"blakecoin",
"c11",
"deep",
"dmd-gr",
"doom", /* is luffa */
"fresh",
"fugue256",
"groestl",
"heavy",
"keccak",
"jackpot",
"luffa",
"lyra2",
"lyra2v2",
"mjollnir",
"myr-gr",
"nist5",
"penta",
"quark",
"qubit",
"scrypt",
"scrypt-jane",
"skein",
"s3",
"spread",
"whirl",
"whirlpoolx",
"x11",
"x13",
"x14",
"x15",
"x17",
"neoscrypt",
""
};
bool opt_broken_neo_wallet = false; // HACK: Drop this flag once neoscrypt wallets are fixed to send 80byte data
bool opt_debug = false;
bool opt_protocol = false;
bool opt_benchmark = false;
bool want_longpoll = true;
bool have_longpoll = false;
bool want_stratum = true;
bool have_stratum = false;
bool allow_gbt = false;
bool check_dups = false;
static bool submit_old = false;
bool use_syslog = false;
bool use_colors = true;
static bool opt_background = false;
bool opt_quiet = false;
static int opt_retries = -1;
static int opt_fail_pause = 5;
static int opt_time_limit = 0;
int opt_timeout = 270;
static int opt_scantime = 5;
static json_t *opt_config;
static const bool opt_time = true;
static enum sha_algos opt_algo = ALGO_X11;
int opt_n_threads = 0;
int opt_n_gputhreads = 1;
int opt_affinity = -1;
int opt_priority = 0;
static double opt_difficulty = 1; // CH
static bool opt_extranonce = true;
bool opt_cpumining = false;
bool opt_trust_pool = false;
uint16_t opt_vote = 9999;
int num_cpus = 0;
int active_gpus = 0;
char * device_name[MAX_GPUS];
int device_map[MAX_GPUS] = { 0, 1, 2, 3, 4, 5, 6, 7,8,9,10,11,12,13,14,15,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 };
long device_sm[MAX_GPUS] = { 0 };
int device_memspeed[MAX_GPUS] = { 0 };
int device_gpuspeed[MAX_GPUS] = { 0 };
uint32_t gpus_intensity[MAX_GPUS] = { 0 };
int device_interactive[MAX_GPUS] = { 0 };
int device_batchsize[MAX_GPUS] = { 0 };
int device_backoff[MAX_GPUS] = { 0 };
int device_lookup_gap[MAX_GPUS] = { 0 };
int device_texturecache[MAX_GPUS] = { 0 };
int device_singlememory[MAX_GPUS] = { 0 };
char *device_config[MAX_GPUS] = { 0 };
int opt_nfactor = 0;
int parallel = 2;
bool autotune = true;
bool opt_autotune = true;
bool abort_flag = false;
bool scan_abort_flag = false;
bool network_fail_flag = false;
char *jane_params = NULL;
char *rpc_user = NULL;
static char *rpc_url = NULL;
static char *rpc_userpass = NULL;
static char *rpc_pass = NULL;
static char *short_url = NULL;
char *opt_cert = NULL;
char *opt_proxy = NULL;
long opt_proxy_type = -1;
struct thr_info *thr_info = NULL;
static int work_thr_id = -1;
struct thr_api *thr_api = NULL;
int longpoll_thr_id = -1;
int stratum_thr_id = -1;
int api_thr_id = -1;
bool stratum_need_reset = false;
struct work_restart *work_restart = NULL;
struct stratum_ctx stratum = { 0 };
static pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
uint32_t accepted_count = 0L;
uint32_t rejected_count = 0L;
static double thr_hashrates[MAX_GPUS] = { 0 };
uint64_t global_hashrate = 0;
double global_diff = 0.0;
uint32_t opt_statsavg = 30;
static char* opt_syslog_pfx = NULL;
char *opt_api_allow = NULL;
int opt_api_listen = 0; /* 0 to disable */
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
#endif
static char const usage[] = "\
Usage: " PROGRAM_NAME " [OPTIONS]\n\
Options:\n\
-a, --algo=ALGO specify the hash algorithm to use\n\
bastion bastioncoin\n\
bitcoin Bitcoin\n\
blake Blake 256 (SFR/NEOS)\n\
blakecoin Fast Blake 256 (8 rounds)\n\
c11/flax X11 variant\n\
credit Credit\n\
deep Deepcoin\n\
dmd-gr Diamond-Groestl\n\
fresh Freshcoin (shavite 80)\n\
fugue256 Fuguecoin\n\
groestl Groestlcoin\n\
heavy Heavycoin\n\
jackpot Jackpot\n\
keccak Keccak-256 (Maxcoin)\n\
luffa Doomcoin\n\
lyra2 Lyrabar\n\
lyra2v2 VertCoin\n\
mjollnir Mjollnircoin\n\
myr-gr Myriad-Groestl\n\
neoscrypt neoscrypt (FeatherCoin)\n\
nist5 NIST5 (TalkCoin)\n\
penta Pentablake hash (5x Blake 512)\n\
quark Quark\n\
qubit qubit\n\
scrypt Scrypt\n\
scrypt-jane Scrypt-jane Chacha\n\
skein Skein\n\
s3 S3 (1Coin)\n\
spread Spread\n\
x11 X11 (DarkCoin)\n\
x13 X13 (MaruCoin)\n\
x14 X14\n\
x15 X15\n\
x17 X17 (peoplecurrency)\n\
yescrypt yescrypt\n\
whirl Whirlcoin (old whirlpool)\n\
whirlpoolx Vanillacoin \n\
-d, --devices Comma separated list of CUDA devices to use. \n\
Device IDs start counting from 0! Alternatively takes\n\
string names of your cards like gtx780ti or gt640#2\n\
(matching 2nd gt640 in the PC)\n\
-i --intensity=N GPU intensity 8-31 (default: auto) \n\
Decimals are allowed for fine tuning \n\
-f, --diff Divide difficulty by this factor (std is 1) \n\
-v, --vote=VOTE block reward vote (for HeavyCoin)\n\
-m, --trust-pool trust the max block reward vote (maxvote) sent by the pool\n\
-o, --url=URL URL of mining server\n\
-O, --userpass=U:P username:password pair for mining server\n\
-u, --user=USERNAME username for mining server\n\
-p, --pass=PASSWORD password for mining server\n\
--cert=FILE certificate for mining server using SSL\n\
-x, --proxy=[PROTOCOL://]HOST[:PORT] connect through a proxy\n\
-t, --threads=N number of miner threads (default: number of nVidia GPUs)\n\
-g, --gputhreads=N number of threads per gpu (default: 1)\n\
-r, --retries=N number of times to retry if a network call fails\n\
(default: retry indefinitely)\n\
-R, --retry-pause=N time to pause between retries, in seconds (default: 30)\n\
--time-limit maximum time [s] to mine before exiting the program.\n\
-T, --timeout=N network timeout, in seconds (default: 270)\n\
-s, --scantime=N upper bound on time spent scanning current work when\n\
long polling is unavailable, in seconds (default: 5)\n\
-n, --ndevs list cuda devices\n\
-N, --statsavg number of samples used to display hashrate (default: 30)\n\
--no-gbt disable getblocktemplate support (height check in solo)\n\
--no-longpoll disable X-Long-Polling support\n\
--no-stratum disable X-Stratum support\n\
-q, --quiet disable per-thread hashmeter output\n\
--no-color disable colored output\n\
-D, --debug enable debug output\n\
-P, --protocol-dump verbose dump of protocol-level activities\n\
--cpu-affinity set process affinity to cpu core(s), mask 0x3 for cores 0 and 1\n\
--cpu-priority set process priority (default: 0 idle, 2 normal to 5 highest)\n\
-b, --api-bind IP/Port for the miner API (default: 127.0.0.1:4068)\n\
-S, --syslog use system log for output messages\n\
--syslog - prefix = ... allow to change syslog tool name\n\
-B, --background run the miner in the background\n\
--benchmark run in offline benchmark mode\n\
--cputest debug hashes from cpu algorithms\n\
-c, --config=FILE load a JSON-format configuration file\n\
-C, --cpu-mining Enable the cpu to aid the gpu. (warning: uses more power)\n\
-V, --version display version information and exit\n\
-h, --help display this help text and exit\n\
-X, --XIntensity intensity GPU intensity(default: auto) \n\
--broken-neo-wallet Use 84byte data for broken neoscrypt wallets.\n\
";
char const short_options[] = "SX:a:c:i:Dhp:Px:qr:R:s:t:T:o:u:O:Vd:f:mv:N:n:b:g:l:L:e:M:C";
struct option const options[] = {
{ "algo", 1, NULL, 'a' },
{ "api-bind", 1, NULL, 'b' },
{ "benchmark", 0, NULL, 1005 },
{ "cert", 1, NULL, 1001 },
{ "config", 1, NULL, 'c' },
{ "cputest", 0, NULL, 1006 },
{ "cpu-affinity", 1, NULL, 1020 },
{ "cpu-priority", 1, NULL, 1021 },
{ "debug", 0, NULL, 'D' },
{ "help", 0, NULL, 'h' },
{ "intensity", 1, NULL, 'i' },
{ "ndevs", 0, NULL, 'n' },
{ "no-color", 0, NULL, 1002 },
{ "no-gbt", 0, NULL, 1011 },
{ "no-longpoll", 0, NULL, 1003 },
{ "no-stratum", 0, NULL, 1007 },
{ "no-autotune", 0, NULL, 1004 }, // scrypt
{ "launch-config", 0, NULL, 'l' }, // scrypt
{ "lookup-gap", 0, NULL, 'L' }, // scrypt
{ "pass", 1, NULL, 'p' },
{ "protocol-dump", 0, NULL, 'P' },
{ "proxy", 1, NULL, 'x' },
{ "quiet", 0, NULL, 'q' },
{ "retries", 1, NULL, 'r' },
{ "retry-pause", 1, NULL, 'R' },
{ "syslog", 0, NULL, 'S' },
{ "syslog-prefix", 1, NULL, 1008 },
{ "scantime", 1, NULL, 's' },
{ "statsavg", 1, NULL, 'N' },
{ "time-limit", 1, NULL, 1008 },
{ "threads", 1, NULL, 't' },
{ "gputhreads", 1, NULL, 'g' },
{ "gpu-engine", 1, NULL, 1070 },
{ "gpu-memclock", 1, NULL, 1071 },
{ "Disable extranounce support", 1, NULL, 'e' },
{ "vote", 1, NULL, 'v' },
{ "trust-pool", 0, NULL, 'm' },
{ "timeout", 1, NULL, 'T' },
{ "url", 1, NULL, 'o' },
{ "user", 1, NULL, 'u' },
{ "userpass", 1, NULL, 'O' },
{ "version", 0, NULL, 'V' },
{ "devices", 1, NULL, 'd' },
{ "diff", 1, NULL, 'f' },
{ "X", 1, NULL, 'X'},
{ "cpu-mining", 0, NULL, 'C'},
{ "broken-neo-wallet", 0, NULL, 1030},
{ 0, 0, 0, 0 }
};
static char const scrypt_usage[] = "\n\
Scrypt specific options:\n\
-l, --launch-config gives the launch configuration for each kernel\n\
in a comma separated list, one per device.\n\
-L, --lookup-gap Divides the per-hash memory requirement by this factor\n\
by storing only every N'th value in the scratchpad.\n\
Default is 1.\n\
--no-autotune disable auto-tuning of kernel launch parameters\n\
";
static struct work _ALIGN(64) g_work;
static time_t g_work_time;
static pthread_mutex_t g_work_lock = PTHREAD_MUTEX_INITIALIZER;
#ifdef __linux /* Linux specific policy and affinity management */
#include <sched.h>
static inline void drop_policy(void) {
struct sched_param param;
param.sched_priority = 0;
#ifdef SCHED_IDLE
if (unlikely(sched_setscheduler(0, SCHED_IDLE, ¶m) == -1))
#endif
#ifdef SCHED_BATCH
sched_setscheduler(0, SCHED_BATCH, ¶m);
#endif
}
static void affine_to_cpu_mask(int id, uint8_t mask) {
cpu_set_t set;
CPU_ZERO(&set);
for (uint8_t i = 0; i < num_cpus; i++) {
// cpu mask
if (mask & (1<<i)) { CPU_SET(i, &set); }
}
if (id == -1) {
// process affinity
sched_setaffinity(0, sizeof(&set), &set);
} else {
// thread only
pthread_setaffinity_np(thr_info[id].pth, sizeof(&set), &set);
}
}
#elif defined(__FreeBSD__) /* FreeBSD specific policy and affinity management */
#include <sys/cpuset.h>
static inline void drop_policy(void) { }
static void affine_to_cpu_mask(int id, uint8_t mask) {
cpuset_t set;
CPU_ZERO(&set);
for (uint8_t i = 0; i < num_cpus; i++) {
if (mask & (1<<i)) CPU_SET(i, &set);
}
cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset_t), &set);
}
#else /* Windows */
static inline void drop_policy(void) { }
static void affine_to_cpu_mask(int id, uint8_t mask) {
if (id == -1)
SetProcessAffinityMask(GetCurrentProcess(), mask);
else
SetThreadAffinityMask(GetCurrentThread(), mask);
}
#endif
static bool get_blocktemplate(CURL *curl, struct work *work);
void get_currentalgo(char* buf, int sz)
{
snprintf(buf, sz, "%s", algo_names[opt_algo]);
}
/**
* Exit app
*/
#define CCEXIT_SIG -1
void proper_exit(int reason)
{
struct thr_info* thr = NULL;
abort_flag = true;
if (thr_info && work_thr_id != -1)
thr = &thr_info[work_thr_id];
if (thr && thr->q)
tq_freeze(thr->q);
if (reason != CCEXIT_SIG) {
#ifdef USE_WRAPNVML
if (hnvml)
nvml_destroy(hnvml);
#endif
free(opt_syslog_pfx);
opt_syslog_pfx = NULL;
free(opt_api_allow);
opt_api_allow = NULL;
hashlog_purge_all();
stats_purge_all();
cuda_devicereset();
}
}
static bool jobj_binary(const json_t *obj, const char *key,
void *buf, size_t buflen)
{
const char *hexstr;
json_t *tmp;
tmp = json_object_get(obj, key);
if (unlikely(!tmp)) {
applog(LOG_ERR, "JSON key '%s' not found", key);
return false;
}
hexstr = json_string_value(tmp);
if (unlikely(!hexstr)) {
applog(LOG_ERR, "JSON key '%s' is not a string", key);
return false;
}
if (!hex2bin((uchar*)buf, hexstr, buflen))
return false;
return true;
}
static bool work_decode(const json_t *val, struct work *work)
{
int data_size, midstate_size;
switch (opt_algo) {
case ALGO_NEO:
data_size = opt_broken_neo_wallet ? 84 : 80;
break;
case ALGO_BITC:
data_size = 168;
midstate_size = sizeof(work->midstate);
break;
default:
data_size = 128; // original sizeof(work->data); however data is now 64*4bit
}
int adata_sz = data_size >> 2;
int target_size = sizeof(work->target);
int atarget_sz = target_size >> 2;
int i;
// printf("data size %d",data_size);
if (unlikely(!jobj_binary(val, "data", work->data, data_size))) {
applog(LOG_ERR, "JSON inval data");
return false;
}
if (unlikely(!jobj_binary(val, "target", work->target, target_size))) {
applog(LOG_ERR, "JSON inval target");
return false;
}
if (opt_algo == ALGO_BITC) {
if (unlikely(!jobj_binary(val, "midstate", work->midstate, midstate_size))) {
applog(LOG_ERR, "JSON inval midstate");
return false;
}
for (i = 0; i < midstate_size>>2; i++)
work->midstate[i] = le32dec(work->midstate + i);
}
if (opt_algo == ALGO_HEAVY) {
if (unlikely(!jobj_binary(val, "maxvote", &work->maxvote, sizeof(work->maxvote)))) {
work->maxvote = 2048;
}
}
else work->maxvote = 0;
// printf("the data: \n");
for (i = 0; i < adata_sz; i++)
work->data[i] = le32dec(work->data + i);
// printf("i %d %08x \n",i, work->data[i]);}
// printf("\n");
for (i = 0; i < atarget_sz; i++)
work->target[i] = le32dec(work->target + i);
json_t *jr = json_object_get(val, "noncerange");
if (jr) {
const char * hexstr = json_string_value(jr);
if (likely(hexstr)) {
// never seen yet...
hex2bin((uchar*)work->noncerange.u64, hexstr, 8);
applog(LOG_DEBUG, "received noncerange: %08x-%08x",
work->noncerange.u32[0], work->noncerange.u32[1]);
}
}
/* use work ntime as job id (solo-mining) */
cbin2hex(work->job_id, (const char*)&work->data[17], 4);
return true;
}
/**
* Calculate the work difficulty as double
* Not sure it works with pools
*/
static void calc_diff(struct work *work, int known)
{
// sample for diff 32.53 : 00000007de5f0000
const uint64_t diffone = 0xFFFF000000000000ull;
uint64_t *data64, d64;
char rtarget[32];
swab256(rtarget, work->target);
data64 = (uint64_t *)(rtarget + 3); /* todo: index (3) can be tuned here */
if (opt_algo == ALGO_HEAVY) {
data64 = (uint64_t *)(rtarget + 2);
}
d64 = swab64(*data64);
if (unlikely(!d64))
d64 = 1;
work->difficulty = (double)diffone / d64;
if (opt_difficulty > 0.) {
work->difficulty /= opt_difficulty;
}
}
static int share_result(int result, const char *reason)
{
char s[345];
double hashrate = 0.;
const char *sres;
pthread_mutex_lock(&stats_lock);
for (int i = 0; i < opt_n_threads; i++) {
hashrate += stats_get_speed(i, thr_hashrates[i]);
}
result ? accepted_count++ : rejected_count++;
pthread_mutex_unlock(&stats_lock);
global_hashrate = llround(hashrate);
if (use_colors)
sres = (result ? CL_GRN "yes!" : CL_RED "nooooo");
else
sres = (result ? "(yes!!!)" : "(nooooo)");
switch (opt_algo) {
case ALGO_BASTION:
sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", hashrate);
applog(LOG_NOTICE, "accepted: %lu/%lu (%.2f%%), %s H/s %s",
accepted_count, accepted_count + rejected_count,
100. * accepted_count / (accepted_count + rejected_count), s, sres);
break;
default:
sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", hashrate / 1000.0);
applog(LOG_NOTICE, "accepted: %lu/%lu (%.2f%%), %s kH/s %s",
accepted_count, accepted_count + rejected_count,
100. * accepted_count / (accepted_count + rejected_count), s, sres);
break;
}
if (reason) {
applog(LOG_WARNING, "reject reason: %s", reason);
if (strncmp(reason, "Duplicate share", 15) == 0 && !check_dups) {
// applog(LOG_WARNING, "enabling duplicates check feature");
// check_dups = true;
}
return 0;
}
return 1;
}
static bool submit_upstream_work(CURL *curl, struct work *work)
{
json_t *val, *res, *reason;
bool stale_work = false;
char s[384];
/* discard if a newer bloc was received */
/*
stale_work = work->height && work->height < g_work.height;
if (have_stratum && !stale_work) {
pthread_mutex_lock(&g_work_lock);
if (strlen(work->job_id + 8))
stale_work = strcmp(work->job_id + 8, g_work.job_id + 8);
pthread_mutex_unlock(&g_work_lock);
}
*/
if (!have_stratum && !stale_work && allow_gbt) {
struct work wheight = { 0 };
if (get_blocktemplate(curl, &wheight)) {
if (work->height && work->height < wheight.height) {
if (opt_debug)
applog(LOG_WARNING, "bloc %u was already solved", work->height, wheight.height);
return true;
}
}
}
if (stale_work) {
if (opt_debug)
applog(LOG_WARNING, "stale work detected, discarding");
return true;
}
calc_diff(work, 0);
if (have_stratum)
{
uint32_t sent = 0;
uint32_t ntime, nonce;
uint16_t nvote;
char *ntimestr, *noncestr, *xnonce2str, *nvotestr;
le32enc(&ntime, work->data[17]);
le32enc(&nonce, work->data[19]);
noncestr = bin2hex((const uchar*)(&nonce), 4);
if (check_dups)
sent = hashlog_already_submittted(work->job_id, nonce);
if (sent > 0) {
sent = (uint32_t)time(NULL) - sent;
if (!opt_quiet) {
applog(LOG_WARNING, "nonce %s was already sent %u seconds ago", noncestr, sent);
hashlog_dump_job(work->job_id);
}
free(noncestr);
// prevent useless computing on some pools
stratum_need_reset = true;
for (int i = 0; i < opt_n_threads; i++)
work_restart[i].restart = 1;
return true;
}
ntimestr = bin2hex((const uchar*)(&ntime), 4);
xnonce2str = bin2hex(work->xnonce2, work->xnonce2_len);
if (opt_algo == ALGO_HEAVY) {
be16enc(&nvote, *((uint16_t*)&work->data[20]));
nvotestr = bin2hex((const uchar*)(&nvote), 2);
sprintf(s,
"{\"method\": \"mining.submit\", \"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":4}",
rpc_user, work->job_id + 8, xnonce2str, ntimestr, noncestr, nvotestr);
free(nvotestr);
}
else {
sprintf(s,
"{\"method\": \"mining.submit\", \"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":4}",
rpc_user, work->job_id + 8, xnonce2str, ntimestr, noncestr);
}
free(xnonce2str);
free(ntimestr);
free(noncestr);
gettimeofday(&stratum.tv_submit, NULL);
if (unlikely(!stratum_send_line(&stratum, s))) {
applog(LOG_ERR, "submit_upstream_work stratum_send_line failed");
sleep(10);
return false;
}
if (check_dups)
hashlog_remember_submit(work, nonce);
}
else {
/* build hex string */
char *str = NULL;
int data_size;
switch (opt_algo)
{
case ALGO_NEO:
data_size = opt_broken_neo_wallet ? 84 : 80;
break;
case ALGO_BITC:
data_size = 168;
break;
default:
data_size = 128;
break;
}
if (opt_algo != ALGO_HEAVY && opt_algo != ALGO_MJOLLNIR) {
for (int i = 0; i < (data_size >> 2); i++)
le32enc(work->data + i, work->data[i]);
}
str = bin2hex((uchar*)work->data, data_size);
if (unlikely(!str)) {
applog(LOG_ERR, "submit_upstream_work OOM");
return false;
}
/* build JSON-RPC request */
sprintf(s,
"{\"method\": \"getwork\", \"params\": [\"%s\"], \"id\":4}\r\n",
str);
/* issue JSON-RPC request */
val = json_rpc_call(curl, rpc_url, rpc_userpass, s, false, false, NULL);
if (unlikely(!val)) {
applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
return false;
}
res = json_object_get(val, "result");
reason = json_object_get(val, "reject-reason");
if (!share_result(json_is_true(res), reason ? json_string_value(reason) : NULL)) {
if (check_dups)
hashlog_purge_job(work->job_id);
}
json_decref(val);
free(str);
}
return true;
}
/* simplified method to only get some extra infos in solo mode */
static bool gbt_work_decode(const json_t *val, struct work *work)
{
json_t *err = json_object_get(val, "error");
if (err && !json_is_null(err)) {
allow_gbt = false;
applog(LOG_INFO, "GBT not supported, bloc height unavailable");
return false;
}
if (!work->height) {
// complete missing data from getwork
json_t *key = json_object_get(val, "height");
if (key && json_is_integer(key)) {
work->height = (uint32_t) json_integer_value(key);
if (!opt_quiet && work->height > g_work.height) {
applog(LOG_BLUE, "%s %s block %d", short_url,
algo_names[opt_algo], work->height);
g_work.height = work->height;
}
}
}
return true;
}
#define GBT_CAPABILITIES "[\"coinbasetxn\", \"coinbasevalue\", \"longpoll\", \"workid\"]"
static const char *gbt_req =
"{\"method\": \"getblocktemplate\", \"params\": ["
// "{\"capabilities\": " GBT_CAPABILITIES "}"
"], \"id\":0}\r\n";
static bool get_blocktemplate(CURL *curl, struct work *work)
{
if (!allow_gbt)
return false;
json_t *val = json_rpc_call(curl, rpc_url, rpc_userpass, gbt_req,
want_longpoll, false, NULL);
if (!val)
return false;
bool rc = gbt_work_decode(json_object_get(val, "result"), work);
json_decref(val);
return rc;
}
static const char *rpc_req =
"{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
static bool get_upstream_work(CURL *curl, struct work *work)
{
json_t *val;
bool rc;
struct timeval tv_start, tv_end, diff;
gettimeofday(&tv_start, NULL);
val = json_rpc_call(curl, rpc_url, rpc_userpass, rpc_req,
want_longpoll, false, NULL);
gettimeofday(&tv_end, NULL);
if (have_stratum) {
if (val)
json_decref(val);
return true;
}
if (!val)
return false;
rc = work_decode(json_object_get(val, "result"), work);
if (opt_protocol && rc) {
timeval_subtract(&diff, &tv_end, &tv_start);
/* show time because curl can be slower against versions/config */
applog(LOG_DEBUG, "got new work in %.2f ms",
(1000.0 * diff.tv_sec) + (0.001 * diff.tv_usec));
}
json_decref(val);
get_blocktemplate(curl, work);
return rc;
}
static void workio_cmd_free(struct workio_cmd *wc)
{
if (!wc)
return;
switch (wc->cmd) {
case WC_SUBMIT_WORK:
aligned_free(wc->u.work);
break;
default: /* do nothing */
break;
}
memset(wc, 0, sizeof(*wc)); /* poison */
free(wc);
}
static void workio_abort()
{
struct workio_cmd *wc;
/* fill out work request message */
wc = (struct workio_cmd *)calloc(1, sizeof(*wc));
if (!wc)
return;
wc->cmd = WC_ABORT;
/* send work request to workio thread */
if (!tq_push(thr_info[work_thr_id].q, wc)) {
workio_cmd_free(wc);
}
}
static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
{
struct work *ret_work;
int failures = 0;
ret_work = (struct work*)aligned_calloc(sizeof(*ret_work));
if (!ret_work)
return false;
/* obtain new work from bitcoin via JSON-RPC */
while (!get_upstream_work(curl, ret_work)) {
if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
aligned_free(ret_work);
return false;
}
/* pause, then restart work-request loop */
applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
opt_fail_pause);
sleep(opt_fail_pause);
}
/* send work to requesting thread */
if (!tq_push(wc->thr->q, ret_work))
aligned_free(ret_work);
return true;
}
static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
{
int failures = 0;
/* submit solution to bitcoin via JSON-RPC */
while (!submit_upstream_work(curl, wc->u.work)) {
if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
applog(LOG_ERR, "...terminating workio thread");
return false;
}
/* pause, then restart work-request loop */
if (!opt_benchmark)
applog(LOG_ERR, "...retry after %d seconds", opt_fail_pause);
sleep(opt_fail_pause);