forked from KlausT/ccminer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ccminer.cpp
3087 lines (2787 loc) · 71 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
* Copyright 2014-2015 tpruvot
*
* 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();
#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;
};
static const char *algo_names[] = {
"bitcoin",
"blake",
"blakecoin",
"c11",
"deep",
"dmd-gr",
"doom", /* is luffa */
"fresh",
"fugue256",
"groestl",
"keccak",
"jackpot",
"luffa",
"lyra2v2",
"myr-gr",
"nist5",
"penta",
"quark",
"qubit",
"sia",
"skein",
"s3",
"whirl",
"whirlpoolx",
"x11",
"x13",
"x14",
"x15",
"x17",
"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 = 10;
int opt_timeout = 120;
static int opt_scantime = 25;
static json_t *opt_config = nullptr;
static const bool opt_time = true;
enum sha_algos opt_algo;
int opt_n_threads = 0;
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;
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};
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];
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;
struct work_restart *work_restart = NULL;
struct stratum_ctx stratum = { 0 };
bool stop_mining = false;
volatile bool mining_has_stopped[MAX_GPUS];
pthread_mutex_t applog_lock = PTHREAD_MUTEX_INITIALIZER;
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];
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 = 4068; /* 0 to disable */
bool opt_stratum_stats = true;
static char* opt_syslog_pfx = nullptr;
char *opt_api_allow = nullptr;
#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\
-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\
-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\
-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\
--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 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[] =
#ifndef WIN32
"B"
#endif
#ifdef HAVE_SYSLOG_H
"S"
#endif
"a:c:i:Dhp:Px:nqr:R:s:t:T:o:u:O:Vd:f:m:N:b:e";
static struct option const options[] =
{
{ "algo", 1, NULL, 'a' },
{ "api-bind", 1, NULL, 'b' },
#ifndef WIN32
{ "background", 0, NULL, 'B' },
#endif
{ "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 },
{ "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},
{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 /* 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
*/
void proper_exit(int reason)
{
#ifdef USE_WRAPNVML
if(hnvml)
nvml_destroy(hnvml);
#endif
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();
}
curl_global_cleanup();
#ifdef WIN32
timeEndPeriod(1);
#endif
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 = 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, "block %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;
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);
}
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");
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, 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);
}
g_work.height = work->height;
if(!have_stratum)
{
double x = expectedblocktime(work->target);
if(x != 0.0)
applog(LOG_BLUE, "50%% chance to find a block in about %.2f days", x);
}
}
}
}
return true;
}
#define GBT_CAPABILITIES "[\"coinbasetxn\", \"coinbasevalue\", \"longpoll\", \"workid\"]"
static const char *gbt_req =
"{\"method\": \"getblocktemplate\", \"params\": ["
// "{\"capabilities\": " GBT_CAPABILITIES "}"
"], \"id\":9}\r\n";
static bool get_blocktemplate(CURL *curl, struct work *work)
{
if(!allow_gbt)
return false;
int curl_err = 0;
json_t *val = json_rpc_call(curl, rpc_url, rpc_userpass, gbt_req,
want_longpoll, have_longpoll, &curl_err);
if(!val && curl_err == -1)
{
// when getblocktemplate is not supported, disable it
allow_gbt = false;
if(!opt_quiet)
{
applog(LOG_BLUE, "gbt not supported, block height notices disabled");
}
return false;
}
bool rc = gbt_work_decode(json_object_get(val, "result"), work);
json_decref(val);
return rc;
}
// good alternative for wallet mining, difficulty and net hashrate
static const char *info_req =
"{\"method\": \"getmininginfo\", \"params\": [], \"id\":8}\r\n";
static bool get_mininginfo(CURL *curl, struct work *work)
{
if(have_stratum || !allow_mininginfo)
return false;
int curl_err = 0;
json_t *val = json_rpc_call(curl, rpc_url, rpc_userpass, info_req,
want_longpoll, have_longpoll, &curl_err);
if(!val && curl_err == -1)
{
allow_mininginfo = false;
if(opt_debug)
{
applog(LOG_DEBUG, "getmininginfo not supported");
}
return false;
}
else
{
json_t *res = json_object_get(val, "result");
// "blocks": 491493 (= current work height - 1)
// "difficulty": 0.99607860999999998
// "networkhashps": 56475980
if(res)
{
json_t *key = json_object_get(res, "powdifficulty");
if(key && json_is_real(key))
{
global_diff = json_real_value(key);
}
key = json_object_get(res, "difficulty");
if(key && json_is_real(key))
{
global_diff = json_real_value(key);
}
key = json_object_get(res, "networkhashps");
if(key && json_is_integer(key))
{
net_hashrate = json_integer_value(key);
}
key = json_object_get(res, "blocks");
if(key && json_is_integer(key))
{
net_blocks = json_integer_value(key);
}
}
}
json_decref(val);
return true;
}
// time (in days) for a 50% chance to find a block
double expectedblocktime(const uint32_t *target)
{
double x = 0.0;
if(global_hashrate == 0)
return 0;
else
{
for(int i = 0; i < 8; i++)
{
x *= 4294967296.0;
x += target[7 - i];
}
if(x != 0.0)
return 115792089237316195423570985008687907853269984665640564039457584007913129639935.0 / x / (double)global_hashrate / 86400.0;
else
return 0.0;
}
}
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_mininginfo(curl, work);
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 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))