forked from tpruvot/ccminer
-
Notifications
You must be signed in to change notification settings - Fork 38
/
ccminer.cpp
3787 lines (3402 loc) · 102 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.
*/
#include "cpuminer-config.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 <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 "miner.h"
#include "algos.h"
#include <cuda_runtime.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 60
#define HEAVYCOIN_BLKHDR_SZ 84
#define MNR_BLKHDR_SZ 80
#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;
int pooln;
};
bool opt_debug = false;
bool opt_debug_diff = false;
bool opt_debug_threads = false;
bool opt_protocol = false;
bool opt_benchmark = false;
// todo: limit use of these flags,
// prefer the pools[] attributes
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;
bool check_stratum_jobs = false;
static bool submit_old = false;
bool use_syslog = false;
bool use_colors = true;
int use_pok = 0;
static bool opt_background = false;
bool opt_quiet = false;
static int opt_retries = -1;
static int opt_fail_pause = 30;
int opt_time_limit = -1;
int opt_shares_limit = -1;
time_t firstwork_time = 0;
int opt_timeout = 300; // curl
int opt_scantime = 60;
static json_t *opt_config;
static const bool opt_time = true;
volatile enum sha_algos opt_algo = ALGO_AUTO;
int opt_n_threads = 0;
int gpu_threads = 1;
int64_t opt_affinity = -1L;
int opt_priority = 0;
static double opt_difficulty = 1.;
bool opt_extranonce = true;
bool opt_trust_pool = false;
uint16_t opt_vote = 9999;
int num_cpus;
int active_gpus;
char * device_name[MAX_GPUS];
short 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 };
uint8_t device_tlimit[MAX_GPUS] = { 0 };
int8_t device_pstate[MAX_GPUS] = { -1 };
int32_t device_led[MAX_GPUS] = { -1, -1 };
int opt_led_mode = 0;
int opt_cudaschedule = -1;
static bool opt_keep_clocks = false;
// un-linked to cmdline scrypt options (useless)
int device_batchsize[MAX_GPUS] = { 0 };
int device_texturecache[MAX_GPUS] = { 0 };
int device_singlememory[MAX_GPUS] = { 0 };
// implemented scrypt options
int parallel = 2; // All should be made on GPU
char *device_config[MAX_GPUS] = { 0 };
int device_backoff[MAX_GPUS] = { 0 };
int device_lookup_gap[MAX_GPUS] = { 0 };
int device_interactive[MAX_GPUS] = { 0 };
int opt_nfactor = 0;
bool opt_autotune = true;
char *jane_params = NULL;
// pools (failover/getwork infos)
struct pool_infos pools[MAX_POOLS] = { 0 };
int num_pools = 1;
volatile int cur_pooln = 0;
bool opt_pool_failover = true;
volatile bool pool_on_hold = false;
volatile bool pool_is_switching = false;
volatile int pool_switch_count = 0;
bool conditional_pool_rotate = false;
// current connection
char *rpc_user = NULL;
char *rpc_pass;
char *rpc_url;
char *short_url = NULL;
struct stratum_ctx stratum = { 0 };
pthread_mutex_t stratum_sock_lock;
pthread_mutex_t stratum_work_lock;
char *opt_cert;
char *opt_proxy;
long opt_proxy_type;
struct thr_info *thr_info = NULL;
static int work_thr_id;
struct thr_api *thr_api;
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;
static int app_exit_code = EXIT_CODE_OK;
pthread_mutex_t applog_lock;
pthread_mutex_t stats_lock;
double thr_hashrates[MAX_GPUS] = { 0 };
uint64_t global_hashrate = 0;
double stratum_diff = 0.0;
double net_diff = 0;
uint64_t net_hashrate = 0;
uint64_t net_blocks = 0;
// conditional mining
uint8_t conditional_state[MAX_GPUS] = { 0 };
double opt_max_temp = 0.0;
double opt_max_diff = -1.;
double opt_max_rate = -1.;
double opt_resume_temp = 0.;
double opt_resume_diff = 0.;
double opt_resume_rate = -1.;
int opt_statsavg = 30;
// strdup on char* to allow a common free() if used
static char* opt_syslog_pfx = strdup(PROGRAM_NAME);
char *opt_api_allow = strdup("127.0.0.1"); /* 0.0.0.0 for all ips */
int opt_api_remote = 0;
int opt_api_listen = 4068; /* 0 to disable */
bool opt_stratum_stats = false;
static char const usage[] = "\
Usage: " PROGRAM_NAME " [OPTIONS]\n\
Options:\n\
-a, --algo=ALGO specify the hash algorithm to use\n\
blake Blake256-14rounds(SFR)\n\
decred Blake256-14rounds(DCR)\n\
blakecoin Blake256-8rounds (BLC)\n\
vcash Blake256-8rounds (XVC)\n\
blake2s Blake2s (NEVA/XVG)\n\
keccak keccak256 (Maxcoin)\n\
hsr X13+SM3 (Hshare)\n\
lyra2 (LyraBar)\n\
lyra2v2 (VertCoin)\n\
skein Skein SHA2 (AUR/DGB/SKC)\n\
skein2 Double Skein (Woodcoin)\n\
nist5 NIST5 (Talkcoin/Power)\n\
quark Quark (Quarkcoin)\n\
qubit Qubit\n\
x11 X11 (DarkCoin)\n\
c11 C11 (Chaincoin)\n\
sib X11+gost (Sibcoin)\n\
x11evo Permuted x11 (Revolver)\n\
x13 X13 (MaruCoin)\n\
x14 X14 (BernCoin)\n\
x15 X15 (Joincoin)\n\
x17 X17 (XVG)\n\
whirlpool whirlpool (JoinCoin)\n\
lbry Lbry (Library Credits)\n\
neoscrypt Neoscrypt (FTC/PXC/UFO)\n\
sia Sia (SIAcoin)\n\
myr-gr Myriad-Groestl (SFR/AUR/DGB/XVG/MYR)\n\
veltor Thor's Riddle(?) (Veltor)\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[,N] GPU intensity 8.0-25.0 (default: auto) \n\
Decimals are allowed for fine tuning \n\
--cuda-schedule Set device threads scheduling mode (default: auto)\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\
--vote=VOTE vote (for decred and HeavyCoin)\n\
--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\
-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: 300)\n\
-s, --scantime=N upper bound on time spent scanning current work when\n\
long polling is unavailable, in seconds (default: 60)\n\
-n, --ndevs list cuda devices\n\
-N, --statsavg number of samples used to compute 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\
--no-extranonce disable extranonce subscribe on stratum\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: 3) 0 idle, 2 normal to 5 highest\n\
-b, --api-bind=port IP:port for the miner API (default: 127.0.0.1:4068), 0 disabled\n\
--api-remote Allow remote control, like pool switching\n\
--max-temp=N Only mine if gpu temp is less than specified value\n\
--max-rate=N[KMG] Only mine if net hashrate is less than specified value\n\
--max-diff=N Only mine if net difficulty is less than specified value\n\
Can be tuned with --resume-diff=N to set a resume value\n"
#if defined(__linux) || defined(_WIN64) /* via nvml */
"\
--mem-clock=3505 Set the gpu memory max clock (346.72+ driver)\n\
--gpu-clock=1150 Set the gpu engine max clock (346.72+ driver)\n\
--pstate=0[,2] Set the gpu power state (352.21+ driver)\n\
--plimit=100W Set the gpu power limit (352.21+ driver)\n"
#else /* via nvapi.dll */
"\
--mem-clock=3505 Set the gpu memory boost clock\n\
--gpu-clock=1150 Set the gpu engine boost clock\n\
--plimit=100 Set the gpu power limit in percentage\n\
--tlimit=80 Set the gpu thermal limit in degrees\n\
--led=100 Set the logo led level (0=disable, 0xFF00FF for RVB)\n"
#endif
#ifdef HAVE_SYSLOG_H
"\
-S, --syslog use system log for output messages\n\
--syslog-prefix=... allow to change syslog tool name\n"
#endif
"\
-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\
-V, --version display version information and exit\n\
-h, --help display this help text and exit\n\
";
static char const short_options[] =
#ifdef HAVE_SYSLOG_H
"S"
#endif
"a:Bc:i:Dhp:Px:f:m:nqr:R:s:t:T:o:u:O:Vd:N:b:l:L:";
struct option options[] = {
{ "algo", 1, NULL, 'a' },
{ "api-bind", 1, NULL, 'b' },
{ "api-remote", 0, NULL, 1030 },
{ "background", 0, 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 },
{ "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-extranonce", 0, NULL, 1012 },
{ "no-gbt", 0, NULL, 1011 },
{ "no-longpoll", 0, NULL, 1003 },
{ "no-stratum", 0, NULL, 1007 },
{ "no-autotune", 0, NULL, 1004 }, // scrypt
{ "interactive", 1, NULL, 1050 }, // scrypt
{ "launch-config", 1, NULL, 'l' }, // scrypt
{ "lookup-gap", 1, NULL, 'L' }, // scrypt
{ "texture-cache", 1, NULL, 1051 },// scrypt
{ "max-temp", 1, NULL, 1060 },
{ "max-diff", 1, NULL, 1061 },
{ "max-rate", 1, NULL, 1062 },
{ "resume-diff", 1, NULL, 1063 },
{ "resume-rate", 1, NULL, 1064 },
{ "resume-temp", 1, NULL, 1065 },
{ "pass", 1, NULL, 'p' },
{ "pool-name", 1, NULL, 1100 }, // pool
{ "pool-algo", 1, NULL, 1101 }, // pool
{ "pool-scantime", 1, NULL, 1102 }, // pool
{ "pool-time-limit", 1, NULL, 1108 },
{ "pool-max-diff", 1, NULL, 1161 }, // pool
{ "pool-max-rate", 1, NULL, 1162 }, // pool
{ "pool-disabled", 1, NULL, 1199 }, // pool
{ "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' },
{ "gpu-clock", 1, NULL, 1070 },
{ "mem-clock", 1, NULL, 1071 },
{ "pstate", 1, NULL, 1072 },
{ "plimit", 1, NULL, 1073 },
{ "keep-clocks", 0, NULL, 1074 },
{ "tlimit", 1, NULL, 1075 },
{ "led", 1, NULL, 1080 },
#ifdef HAVE_SYSLOG_H
{ "syslog", 0, NULL, 'S' },
{ "syslog-prefix", 1, NULL, 1018 },
#endif
{ "shares-limit", 1, NULL, 1009 },
{ "time-limit", 1, NULL, 1008 },
{ "threads", 1, NULL, 't' },
{ "vote", 1, NULL, 1022 },
{ "trust-pool", 0, NULL, 1023 },
{ "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
{ 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\
--interactive comma separated list of flags (0/1) specifying\n\
which of the CUDA device you need to run at inter-\n\
active frame rates (because it drives a display).\n\
--texture-cache comma separated list of flags (0/1/2) specifying\n\
which of the CUDA devices shall use the texture\n\
cache for mining. Kepler devices may profit.\n\
--no-autotune disable auto-tuning of kernel launch parameters\n\
";
struct work _ALIGN(64) g_work;
volatile time_t g_work_time;
pthread_mutex_t g_work_lock;
// get const array size (defined in ccminer.cpp)
int options_count()
{
int n = 0;
while (options[n].name != NULL)
n++;
return n;
}
#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, unsigned long mask) {
cpu_set_t set;
CPU_ZERO(&set);
for (uint8_t i = 0; i < num_cpus; i++) {
// cpu mask
if (mask & (1UL<<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[ 0], 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, unsigned long mask) {
cpuset_t set;
CPU_ZERO(&set);
for (uint8_t i = 0; i < num_cpus; i++) {
if (mask & (1UL<<i)) CPU_SET(i, &set);
}
cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset_t), &set);
}
#elif defined(WIN32) /* Windows */
static inline void drop_policy(void) { }
static void affine_to_cpu_mask(int id, unsigned long mask) {
if (id == -1)
SetProcessAffinityMask(GetCurrentProcess(), mask);
else
SetThreadAffinityMask(GetCurrentThread(), mask);
}
#else /* Martians */
static inline void drop_policy(void) { }
static void affine_to_cpu_mask(int id, uint8_t 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)
{
restart_threads();
if (abort_flag) /* already called */
return;
abort_flag = true;
usleep(200 * 1000);
cuda_shutdown();
if (reason == EXIT_CODE_OK && app_exit_code != EXIT_CODE_OK) {
reason = app_exit_code;
}
pthread_mutex_lock(&stats_lock);
if (check_dups)
hashlog_purge_all();
stats_purge_all();
pthread_mutex_unlock(&stats_lock);
#ifdef WIN32
timeEndPeriod(1); // else never executed
#endif
#ifdef USE_WRAPNVML
if (hnvml) {
for (int n=0; n < opt_n_threads && !opt_keep_clocks; n++) {
nvml_reset_clocks(device_map[n]);
}
nvml_destroy();
}
#endif
free(opt_syslog_pfx);
free(opt_api_allow);
//free(work_restart);
//free(thr_info);
exit(reason);
}
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;
}
/* compute nbits to get the network diff */
void calc_network_diff(struct work *work){
// sample for diff 43.281 : 1c05ea29
// todo: endian reversed on longpoll could be zr5 specific...
uint32_t nbits = have_longpoll ? work->data[18] : swab32(work->data[18]);
if (opt_algo == ALGO_LBRY) nbits = swab32(work->data[26]);
if (opt_algo == ALGO_DECRED) nbits = work->data[29];
if (opt_algo == ALGO_SIA) nbits = work->data[11]; // unsure if correct
uint32_t bits = (nbits & 0xffffff);
int16_t shift = (swab32(nbits) & 0xff); // 0x1c = 28
uint64_t diffone = 0x0000FFFF00000000ull;
double d = (double)0x0000ffff / (double)bits;
for (int m=shift; m < 29; m++) d *= 256.0;
for (int m=29; m < shift; m++) d /= 256.0;
if (opt_algo == ALGO_DECRED && shift == 28) d *= 256.0;
if (opt_debug_diff)
applog(LOG_DEBUG, "net diff: %f -> shift %u, bits %08x", d, shift, bits);
net_diff = d;
}
/* decode data from getwork (wallets and longpoll pools) */
static bool work_decode(const json_t *val, struct work *work)
{
int data_size, target_size = sizeof(work->target);
int adata_sz, atarget_sz = ARRAY_SIZE(work->target);
int i;
switch (opt_algo) {
case ALGO_DECRED:
data_size = 192;
adata_sz = 180/4;
break;
case ALGO_NEOSCRYPT:
data_size = 80;
adata_sz = data_size / 4;
break;
default:
data_size = 128;
adata_sz = data_size / 4;
}
if (!jobj_binary(val, "data", work->data, data_size)) {
json_t *obj = json_object_get(val, "data");
int len = obj ? (int) strlen(json_string_value(obj)) : 0;
if (!len || len > sizeof(work->data)*2) {
applog(LOG_ERR, "JSON invalid data (len %d <> %d)", len/2, data_size);
return false;
} else {
data_size = len / 2;
if (!jobj_binary(val, "data", work->data, data_size)) {
applog(LOG_ERR, "JSON invalid data (len %d)", data_size);
return false;
}
}
}
if (!jobj_binary(val, "target", work->target, target_size)) {
applog(LOG_ERR, "JSON invalid target");
return false;
}
work->maxvote = 0;
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);
if (!allow_mininginfo)
calc_network_diff(work);
work->targetdiff = target_to_diff(work->target);
// for api stats, on longpoll pools
stratum_diff = work->targetdiff;
work->tx_count = use_pok = 0;
/* if (work->data[0] & POK_BOOL_MASK) {
use_pok = 1;
json_t *txs = json_object_get(val, "txs");
if (txs && json_is_array(txs)) {
size_t idx, totlen = 0;
json_t *p;
json_array_foreach(txs, idx, p) {
const int tx = work->tx_count % POK_MAX_TXS;
const char* hexstr = json_string_value(p);
size_t txlen = strlen(hexstr)/2;
work->tx_count++;
if (work->tx_count > POK_MAX_TXS || txlen >= POK_MAX_TX_SZ) {
// when tx is too big, just reset use_pok for the block
use_pok = 0;
if (opt_debug) applog(LOG_WARNING,
"pok: large block ignored, tx len: %u", txlen);
work->tx_count = 0;
break;
}
hex2bin((uchar*)work->txs[tx].data, hexstr, min(txlen, POK_MAX_TX_SZ));
work->txs[tx].len = (uint32_t) (txlen);
totlen += txlen;
}
if (opt_debug)
applog(LOG_DEBUG, "block txs: %u, total len: %u", work->tx_count, totlen);
}
}*/
/* use work ntime as job id (solo-mining) */
cbin2hex(work->job_id, (const char*)&work->data[17], 4);
if (opt_algo == ALGO_DECRED) {
uint16_t vote;
// always keep last bit of votebits
memcpy(&vote, &work->data[25], 2);
vote = (opt_vote << 1) | (vote & 1);
memcpy(&work->data[25], &vote, 2);
// some random extradata to make it unique
work->data[36] = (rand()*4);
work->data[37] = (rand()*4) << 8;
// required for the longpoll pool block info...
work->height = work->data[32];
if (!have_longpoll && work->height > net_blocks + 1) {
char netinfo[64] = { 0 };
if (net_diff > 0.) {
if (net_diff != work->targetdiff)
sprintf(netinfo, ", diff %.3f, pool %.1f", net_diff, work->targetdiff);
else
sprintf(netinfo, ", diff %.3f", net_diff);
}
applog(LOG_BLUE, "%s block %d%s",
algo_names[opt_algo], work->height, netinfo);
net_blocks = work->height - 1;
}
cbin2hex(work->job_id, (const char*)&work->data[34], 4);
}
return true;
}
#define YES "yes!"
#define YAY "yay!!!"
#define BOO "booooo"
int share_result(int result, int pooln, double sharediff, const char *reason)
{
const char *flag;
char suppl[32] = { 0 };
char s[32] = { 0 };
double hashrate = 0.;
struct pool_infos *p = &pools[pooln];
pthread_mutex_lock(&stats_lock);
for (int i = 0; i < opt_n_threads; i++) {
hashrate += stats_get_speed(i, thr_hashrates[i]);
}
pthread_mutex_unlock(&stats_lock);
result ? p->accepted_count++ : p->rejected_count++;
p->last_share_time = time(NULL);
if (sharediff > p->best_share)
p->best_share = sharediff;
global_hashrate = llround(hashrate);
format_hashrate(hashrate, s);
if (!net_diff || sharediff < net_diff) {
flag = use_colors ?
(result ? CL_GRN YES : CL_RED BOO)
: (result ? "(" YES ")" : "(" BOO ")");
} else {
p->solved_count++;
flag = use_colors ?
(result ? CL_GRN YAY : CL_RED BOO)
: (result ? "(" YAY ")" : "(" BOO ")");
}
applog(LOG_NOTICE, "[S/A/T]: %lu/%lu/%lu, diff: %2.3f, %s %s",p->solved_count, p->accepted_count, p->accepted_count + p->rejected_count,sharediff, s, flag);
if (reason) {
applog(LOG_WARNING, "reject reason: %s", reason);
if (!check_dups && strncasecmp(reason, "duplicate", 9) == 0) {
applog(LOG_WARNING, "enabling duplicates check feature");
check_dups = true;
g_work_time = 0;
}
}
return 1;
}
static bool submit_upstream_work(CURL *curl, struct work *work)
{
char s[512];
struct pool_infos *pool = &pools[work->pooln];
json_t *val, *res, *reason;
bool stale_work = false;
/* 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 = strncmp(work->job_id + 8, g_work.job_id + 8, sizeof(g_work.job_id) - 8);
if (stale_work) {
pool->stales_count++;
if (opt_debug) applog(LOG_DEBUG, "outdated job %s, new %s stales=%d",
work->job_id + 8 , g_work.job_id + 8, pool->stales_count);
if (!check_stratum_jobs && pool->stales_count > 5) {
if (!opt_quiet) applog(LOG_WARNING, "Enabled stratum stale jobs workaround");
check_stratum_jobs = true;
}
}
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);
return true;
}
}
}
// if (!stale_work && opt_algo == ALGO_ZR5 && !have_stratum) {
// stale_work = (memcmp(&work->data[1], &g_work.data[1], 68));
// }
if (!submit_old && stale_work) {
if (opt_debug)
applog(LOG_WARNING, "stale work detected, discarding");
return true;
}
if (pool->type & POOL_STRATUM) {
uint32_t sent = 0;
uint32_t ntime, nonce;
char *ntimestr, *noncestr, *xnonce2str, *nvotestr;
uint16_t nvote = 0;
switch (opt_algo) {
case ALGO_BLAKE:
case ALGO_BLAKECOIN:
case ALGO_BLAKE2S:
case ALGO_VCASH:
// fast algos require that... (todo: regen hash)
check_dups = true;
le32enc(&ntime, work->data[17]);
le32enc(&nonce, work->data[19]);
break;
case ALGO_DECRED:
be16enc(&nvote, *((uint16_t*)&work->data[25]));
be32enc(&ntime, work->data[34]);
be32enc(&nonce, work->data[35]);
break;
case ALGO_LBRY:
check_dups = true;
le32enc(&ntime, work->data[25]);
le32enc(&nonce, work->data[27]);
break;
case ALGO_SIA:
be32enc(&ntime, work->data[10]);
be32enc(&nonce, work->data[8]);
break;
default:
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
g_work_time = 0;
restart_threads();
return true;
}
ntimestr = bin2hex((const uchar*)(&ntime), 4);
if (opt_algo == ALGO_DECRED) {
xnonce2str = bin2hex((const uchar*)&work->data[36], stratum.xnonce1_size);
} else if (opt_algo == ALGO_SIA) {
uint16_t high_nonce = swab32(work->data[9]) >> 16;
xnonce2str = bin2hex((unsigned char*)(&high_nonce), 2);
} else {
xnonce2str = bin2hex(work->xnonce2, work->xnonce2_len);
}
// store to keep/display the solved ratio/diff
stratum.sharediff = work->sharediff[0];
if (net_diff && stratum.sharediff > net_diff && (opt_debug || opt_debug_diff))
applog(LOG_INFO, "share diff: %.5f, possible block found!!!",
stratum.sharediff);
else if (opt_debug_diff)
applog(LOG_DEBUG, "share diff: %.5f (x %.1f)",
stratum.sharediff, work->shareratio);
if (opt_vote) { // ALGO_HEAVY ALGO_DECRED
nvotestr = bin2hex((const uchar*)(&nvote), 2);
sprintf(s, "{\"method\": \"mining.submit\", \"params\": ["
"\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":4}",
pool->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}",
pool->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 {
int data_size = 128;
int adata_sz = data_size / sizeof(uint32_t);
/* build hex string */
char *str = NULL;
if (opt_algo == ALGO_DECRED) {
data_size = 192; adata_sz = 180/4;
} else if(opt_algo == ALGO_SIA){
return sia_submit(curl,pool,work);
}
for (int i = 0; i < adata_sz; 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_pool(curl, pool, 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), work->pooln, work->sharediff[0],
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 (net_diff > 0.) {
char netinfo[64] = { 0 };
char srate[32] = { 0 };
sprintf(netinfo, "diff %.2f", net_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;
}
}
}
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)
{
struct pool_infos *pool = &pools[work->pooln];
if (!allow_gbt)
return false;
int curl_err = 0;
json_t *val = json_rpc_call_pool(curl, pool, gbt_req, false, false, &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;
}