forked from KlausT/ccminer
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ccminer.cpp
4276 lines (3912 loc) · 101 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-2017 pooler
* Copyright 2014-2015 tpruvot
* Copyright 2017 Pieter Wuille
*
* 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.
*/
#ifndef WIN32
#include "ccminer-config.h"
#else
#include "ccminer-config-win.h"
#endif
#include "cuda_runtime_api.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cinttypes>
#include <unistd.h>
#include <cmath>
#include <sys/time.h>
#include <ctime>
#include <csignal>
#include <curl/curl.h>
#include <jansson.h>
#include <openssl/sha.h>
#ifdef WIN32
#include <windows.h>
#include <cstdint>
#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
using namespace std;
#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 25
#define MNR_BLKHDR_SZ 80
double expectedblocktime(const uint32_t *target);
extern void get_cuda_arch(int *version);
extern int cuda_arch[MAX_GPUS];
// from cuda.cpp
int cuda_num_devices();
void cuda_devicenames();
void cuda_devicereset();
int cuda_finddevice(char *name);
void cuda_print_devices();
void cuda_get_device_sm();
void cuda_reset_device(int thr_id, bool *init);
#include "nvml.h"
#ifdef USE_WRAPNVML
nvml_handle *hnvml = NULL;
#endif
enum workio_commands {
WC_GET_WORK,
WC_SUBMIT_WORK,
};
struct workio_cmd {
enum workio_commands cmd;
struct thr_info *thr;
union {
struct work *work;
} u;
};
bool opt_debug_diff = false;
bool opt_debug_threads = false;
bool opt_showdiff = true;
bool opt_hwmonitor = true;
const char *algo_names[] =
{
"invalid",
"bitcoin",
"blake",
"blakecoin",
"c11",
"deep",
"dmd-gr",
"doom", /* is luffa */
"fresh",
"fugue256",
"groestl",
"keccak",
"jackpot",
"luffa",
"lyra2v2",
"lyra2v3",
"myr-gr",
"nist5",
"penta",
"quark",
"qubit",
"sia",
"skein",
"s3",
"whirl",
"whirlpoolx",
"x11",
"x13",
"x14",
"x15",
"x17",
"lyra2re",
"lyra2z",
"lyra2z330",
"yescrypt",
"yescryptr8",
"yescryptr16",
"yescryptr16v2",
"yescryptr24",
"yescryptr32",
"vanilla",
"neoscrypt"
};
char curl_err_str[CURL_ERROR_SIZE];
bool opt_verify = true;
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 = true;
bool allow_mininginfo = true;
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 = 20;
int opt_timeout = 120;
static int opt_scantime = 25;
static json_t *opt_config = nullptr;
enum sha_algos opt_algo = ALGO_INVALID;
int opt_n_threads = 0;
int gpu_threads = 1;
int opt_affinity = -1;
int opt_priority = 0;
static double opt_difficulty = 1; // CH
static bool opt_extranonce = true;
bool opt_trust_pool = false;
int num_cpus;
int active_gpus;
bool need_nvsettings = false;
bool need_memclockrst = false;
char * device_name[MAX_GPUS] = { nullptr };
int device_map[MAX_GPUS] = { 0 };
long device_sm[MAX_GPUS] = { 0 };
uint32_t gpus_intensity[MAX_GPUS] = {0};
int32_t device_mem_offsets[MAX_GPUS] = {0};
uint32_t device_gpu_clocks[MAX_GPUS] = {0};
uint32_t device_mem_clocks[MAX_GPUS] = {0};
uint32_t device_plimit[MAX_GPUS] = {0};
int8_t device_pstate[MAX_GPUS];
int32_t device_led[MAX_GPUS] = {-1, -1};
int opt_led_mode = 0;
int opt_cudaschedule = -1;
uint8_t device_tlimit[MAX_GPUS] = {0};
char *rpc_user = NULL;
static char *rpc_url = nullptr;
static char *rpc_userpass = nullptr;
static char *rpc_pass = nullptr;
static char *short_url = NULL;
char *opt_cert = nullptr;
char *opt_proxy = nullptr;
long opt_proxy_type;
struct thr_info *thr_info = nullptr;
static int work_thr_id;
struct thr_api *thr_api = nullptr;
int longpoll_thr_id = -1;
int stratum_thr_id = -1;
int api_thr_id = -1;
bool stratum_need_reset = false;
volatile bool abort_flag = false;
struct work_restart *work_restart = NULL;
bool send_stale;
struct stratum_ctx stratum = { 0 };
bool stop_mining = false;
volatile bool mining_has_stopped[MAX_GPUS];
unsigned int cudaschedule = cudaDeviceScheduleBlockingSync;
FILE *logfilepointer;
char *logfilename;
bool opt_logfile = false;
pthread_mutex_t applog_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER;
uint32_t accepted_count = 0L;
uint32_t rejected_count = 0L;
double thr_hashrates[MAX_GPUS];
uint64_t global_hashrate = 0;
double global_diff = 0.0;
uint64_t net_hashrate = 0;
uint64_t net_blocks = 0;
int opt_statsavg = 30;
uint16_t opt_api_listen = 0; /* 0 to disable */
bool opt_stratum_stats = true;
static char* opt_syslog_pfx = nullptr;
char *opt_api_allow = nullptr;
#ifndef ORG
bool allow_getwork = true;
static unsigned char pk_script[42] = { 0 };
static size_t pk_script_size = 0;
static char *lp_id;
bool opt_segwit_mode = false;
bool opt_eco_mode = false;
char *yescrypt_key = NULL;
size_t yescrypt_key_len = 0;
uint32_t yescrypt_param_N = 0;
uint32_t yescrypt_param_r = 0;
uint32_t yescrypt_param_p = 0;
#endif
#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\
bitcoin Bitcoin\n\
blake Blake 256 (SFR/NEOS)\n\
blakecoin Fast Blake 256 (8 rounds)\n\
c11 X11 variant\n\
deep Deepcoin\n\
dmd-gr Diamond-Groestl\n\
fresh Freshcoin (shavite 80)\n\
fugue256 Fuguecoin\n\
groestl Groestlcoin\n\
jackpot Jackpot (JHA)\n\
keccak Keccak-256 (Maxcoin)\n\
luffa Doomcoin\n\
lyra2v2 VertCoin\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\
sia Siacoin (at pools compatible to siamining.com) \n\
skein Skein SHA2 (Skeincoin)\n\
s3 S3 (1Coin)\n\
x11 X11 (DarkCoin)\n\
x13 X13 (MaruCoin)\n\
x14 X14\n\
x15 X15\n\
x17 X17 (peoplecurrency)\n\
vanilla Blake 256 8 rounds\n\
whirl Whirlcoin (old whirlpool)\n\
whirlpoolx Vanillacoin \n"
#ifndef ORG
"\
yescrypt Globlboost-Y (BSTY) or any params\n\
yescryptr8 BitZeny (ZNY)\n\
yescryptr16 Yenten (YTN)\n\
yescryptr16v2 PPTP\n\
yescryptr24 JagariCoinR\n\
yescryptr32 WAVI\n"
#endif
"\
-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-factor Divide difficulty by this factor (default 1.0) \n\
-m, --diff-multiplier Multiply difficulty by this value (default 1.0) \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\
-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\
-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"
#ifndef ORG
"\
--eco use eco mode (Lyra2REv2 only)\n\
--segwit Agree with Segwit (Solo Mining only)\n\
--coinbase-addr=ADDR payout address for solo mining\n\
--no-getwork disable getwork support\n\
--yescrypt-param set params(N,r,p) for yescrypt\n\
--yescrypt-key set key for yescrypt\n"
#endif
"\
-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\
-e disable extranonce\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\
--cuda-schedule set CUDA scheduling option:\n\
0: BlockingSync (default)\n\
1: Spin\n\
2: Yield\n\
-b, --api-bind=... IP address and port number for the miner API (example: 127.0.0.1:4068)\n\
--logfile=FILE create logfile\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\
--no-cpu-verify don't verify the found results\n\
-c, --config=FILE load a JSON-format configuration file\n\
-V, --version display version information and exit\n\
-h, --help display this help text and exit\n"
#if defined(USE_WRAPNVML) && (defined(__linux) || defined(_WIN64)) /* via nvml */
"\
--mem-clock=N Set the gpu memory max clock (346.72+ driver)\n\
--gpu-clock=N Set the gpu engine max clock (346.72+ driver)\n\
--pstate=N (not for 10xx cards) Set the gpu power state (352.21+ driver)\n\
--plimit=N Set the gpu power limit (352.21+ driver)\n"
#endif
"";
static char const short_options[] =
#ifdef HAVE_SYSLOG_H
"S"
#endif
"a:c:i:Dhp:Px:nqr:R:s:t:T:o:u:O:Vd:f:m:N:b:eB";
static struct option const options[] =
{
{"algo", 1, NULL, 'a'},
{"api-bind", 1, NULL, 'b'},
{"background", 0, NULL, 'B'},
{"benchmark", 0, NULL, 1005},
{"cert", 1, NULL, 1001},
{"no-cpu-verify", 0, NULL, 1022},
{"config", 1, NULL, 'c'},
{"cputest", 0, NULL, 1006},
{"cpu-affinity", 1, NULL, 1020},
{"cpu-priority", 1, NULL, 1021},
{"cuda-schedule", 1, NULL, 1025},
{"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},
{"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'},
{"scantime", 1, NULL, 's'},
{"statsavg", 1, NULL, 'N'},
#ifdef HAVE_SYSLOG_H
{"syslog", 0, NULL, 'S'},
{"syslog-prefix", 1, NULL, 1008},
#endif
{"threads", 1, NULL, 't'},
{"Disable extranounce support", 1, NULL, 'e'},
{"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-multiplier", 1, NULL, 'm'},
{"diff-factor", 1, NULL, 'f'},
{"diff", 1, NULL, 'f'}, // compat
{"gpu-clock", 1, NULL, 1070},
{"mem-clock", 1, NULL, 1071},
{"pstate", 1, NULL, 1072},
{"plimit", 1, NULL, 1073},
{"logfile", 1, NULL, 1074},
#ifndef ORG
{ "eco", 0, NULL, 1081 },
{ "coinbase-addr", 1, NULL, 1016 },
{ "no-getwork", 0, NULL, 1010 },
{ "segwit", 0, NULL, 1083 },
{ "yescrypt-param", 1, NULL, 1084 },
{ "yescrypt-key", 1, NULL, 1085 },
#endif
{0, 0, 0, 0}
};
struct work _ALIGN(64) g_work;
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); printf("%d \n", i);
}
}
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
#ifdef WIN32
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);
}
#else // OSX is not linux
static inline void drop_policy(void)
{
}
static void affine_to_cpu_mask(int id, uint8_t mask)
{
}
#endif
#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
*/
static bool already_exiting = false; // make sure only one thread executes proper_exit()
void proper_exit(int reason)
{
extern struct stratum_ctx stratum;
if(already_exiting)
sleep(10);
else
{
already_exiting = true;
if(opt_n_threads > 0)
{
time_t start = time(NULL);
stop_mining = true;
applog(LOG_INFO, "stopping %d threads", opt_n_threads);
bool everything_stopped;
do
{
everything_stopped = true;
for(int i = 0; i < opt_n_threads; i++)
{
if(!mining_has_stopped[i])
everything_stopped = false;
}
} while(!everything_stopped && (time(NULL) - start) < 5);
applog(LOG_INFO, "resetting GPUs");
cuda_devicereset();
}
pthread_mutex_lock(&stratum.sock_lock);
curl_global_cleanup();
pthread_mutex_unlock(&stratum.sock_lock);
#ifdef WIN32
timeEndPeriod(1);
#endif
#ifdef USE_WRAPNVML
if(hnvml)
{
for(int n = 0; n < opt_n_threads; n++)
{
nvml_reset_clocks(hnvml, device_map[n]);
}
nvml_destroy(hnvml);
}
if(need_memclockrst)
{
#ifdef WIN32
for(int n = 0; n < opt_n_threads; n++)
{
nvapi_toggle_clocks(n, false);
}
#endif
}
#endif
}
if(opt_logfile)
fclose(logfilepointer);
sleep(1);
exit(reason);
}
static size_t 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 == NULL))
{
applog(LOG_ERR, "JSON key '%s' not found", key);
return false;
}
hexstr = json_string_value(tmp);
if(unlikely(hexstr == NULL))
{
applog(LOG_ERR, "JSON key '%s' is not a string", key);
return false;
}
if(strlen(hexstr) / 2 <= buflen)
hex2bin((uchar*)buf, hexstr, buflen);
else
return 0;
return strlen(hexstr)/2;
}
static bool work_decode(const json_t *val, struct work *work)
{
int target_size;
int midstate_size = sizeof(work->midstate);
int atarget_sz = ARRAY_SIZE(work->target);
int i;
size_t data_size = jobj_binary(val, "data", work->data, sizeof(work->data));
if(opt_algo != ALGO_NEO && data_size != 128)
{
applog(LOG_ERR, "JSON invalid data");
return false;
}
work->datasize = data_size;
int adata_sz = (int)data_size / 4;
target_size = (int)jobj_binary(val, "target", work->target, sizeof(work->target));
if(target_size != sizeof(work->target))
{
applog(LOG_ERR, "JSON invalid target", target_size);
return false;
}
for(i = 0; i < adata_sz; i++)
work->data[i] = le32dec(work->data + i);
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 */
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[32] = { 0 };
double hashrate = 0.;
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);
format_hashrate(hashrate, s);
applog(LOG_NOTICE, "accepted: %lu/%lu (%.2f%%), %s %s",
accepted_count,
accepted_count + rejected_count,
100. * accepted_count / (accepted_count + rejected_count),
s,
use_colors ?
(result ? CL_GRN "yay!!!" : CL_RED "booooo")
: (result ? "(yay!!!)" : "(booooo)"));
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 block was received */
stale_work = !send_stale && (work->height && work->height < g_work.height);
if(have_stratum && !stale_work)
{
pthread_mutex_lock(&g_work_lock);
if(strlen(work->job_id + 8))
{
if(!send_stale && strncmp(work->job_id + 8, g_work.job_id + 8, sizeof(g_work.job_id) - 8) != 0)
stale_work = true;
else
stale_work = false;
}
if(!send_stale && stale_work)
{
if(opt_debug) applog(LOG_DEBUG, "outdated job %s, new %s",
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, "block %u was already solved", work->height, wheight.height);
return true;
}
}
}
if(!send_stale && stale_work)
{
// if(opt_debug)
applog(LOG_WARNING, "stale share detected, discarding");
rejected_count++;
return true;
}
calc_diff(work, 0);
if(have_stratum)
{
uint32_t sent = 0;
uint32_t ntime, nonce;
char *ntimestr, *noncestr, *xnonce2str;
if(opt_algo != ALGO_SIA)
{
le32enc(&ntime, work->data[17]);
le32enc(&nonce, work->data[19]);
noncestr = bin2hex((const uchar*)(&nonce), 4);
ntimestr = bin2hex((const uchar*)(&ntime), 4);
}
else
{
le32enc(&ntime, work->data[10]);
uint64_t ntime64 = ntime;
le32enc(&nonce, work->data[8]);
uint64_t nonce64 = nonce;
le32enc(&nonce, work->data[9]);
nonce64 += (uint64_t)nonce << 32;
noncestr = bin2hex((const uchar*)(&nonce64), 8);
ntimestr = bin2hex((const uchar*)(&ntime64), 8);
}
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
g_work_time = 0;
restart_threads();
return true;
}
xnonce2str = bin2hex(work->xnonce2, work->xnonce2_len);
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");
return false;
}
if(check_dups)
hashlog_remember_submit(work, nonce);
}
#ifndef ORG
else if (work->txs2) {
char data_str[2 * sizeof(work->data) + 1];
char *req;
int datasize = work->sapling ? 112 : 80;
for (int i = 0; i < ARRAY_SIZE(work->data); i++)
be32enc(work->data + i, work->data[i]);
cbin2hex(data_str, (char *)work->data, datasize);
if (work->workid) {
char *params;
val = json_object();
json_object_set_new(val, "workid", json_string(work->workid));
params = json_dumps(val, 0);
json_decref(val);
req = (char*)malloc(128 + 2 * datasize + strlen(work->txs2) + strlen(params));
sprintf(req,
"{\"method\": \"submitblock\", \"params\": [\"%s%s\", %s], \"id\":4}\r\n",
data_str, work->txs2, params);
free(params);
}
else {
req = (char*)malloc(128 + 2 * 2 * datasize + strlen(work->txs2));
sprintf(req,
"{\"method\": \"submitblock\", \"params\": [\"%s%s\"], \"id\":4}\r\n",
data_str, work->txs2);
}
val = json_rpc_call(curl, rpc_url, rpc_userpass, req, false, false, NULL);
free(req);
if (unlikely(!val)) {
applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
return false;
}
res = json_object_get(val, "result");
int ret;
if (json_is_object(res))
{
char *res_str;
bool sumres = false;
void *iter = json_object_iter(res);
while (iter) {
if (json_is_null(json_object_iter_value(iter)))\
{
sumres = true;
break;
}
iter = json_object_iter_next(res, iter);
}
res_str = json_dumps(res, 0);
ret = share_result(sumres, res_str);
free(res_str);
} else {
ret = share_result(json_is_null(res), json_string_value(res));
}
if (!ret)
{
if (check_dups)
hashlog_purge_job(work->job_id);
}
json_decref(val);
}
#endif
else
{
/* build hex string */
char *str = NULL;
for(int i = 0; i < (work->datasize >> 2); i++)
le32enc(work->data + i, work->data[i]);
str = bin2hex((uchar*)work->data, work->datasize);
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");
int ret;
if (json_is_object(res))
{
char *res_str;
bool sumres = false;
void *iter = json_object_iter(res);
while (iter) {
if (json_is_null(json_object_iter_value(iter)))\
{
sumres = true;
break;
}
iter = json_object_iter_next(res, iter);
}
res_str = json_dumps(res, 0);
ret = share_result(sumres, res_str);
free(res_str);
} else {
ret = share_result(json_is_null(res), json_string_value(res));
}
if (!ret)
{
if(check_dups)
hashlog_purge_job(work->job_id);
}
json_decref(val);
free(str);
}
return true;
}
#ifndef ORG
#define BLOCK_VERSION_CURRENT 255
#endif
/* 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, block 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)
{
if(!have_stratum && allow_mininginfo && global_diff > 0)
{
char netinfo[64] = { 0 };
char srate[32] = { 0 };
sprintf(netinfo, "diff %.2f", global_diff);
if(net_hashrate)
{
format_hashrate((double)net_hashrate, srate);
strcat(netinfo, ", net ");
strcat(netinfo, srate);
}
applog(LOG_BLUE, "%s block %d, %s",
algo_names[opt_algo], work->height, netinfo);
}
else
{
applog(LOG_BLUE, "%s %s block %d", short_url,
algo_names[opt_algo], work->height);
}