forked from vertcoin-project/vertminer-nvidia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vertminer.cpp
executable file
·2817 lines (2513 loc) · 73.6 KB
/
vertminer.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
* Copyright 2017-2018 aturek
*
* 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 <vertminer-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 "vertminer"
#define LP_SCANTIME 60
#include "nvml.h"
#include "snarf.h"
#ifdef USE_WRAPNVML
nvml_handle *hnvml = NULL;
#endif
enum workio_commands {
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;
bool opt_showdiff = true;
bool opt_eco_mode = false;
// todo: limit use of these flags,
// prefer the pools[] attributes
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 = 10;
static json_t *opt_config;
static const bool opt_time = true;
const enum sha_algos opt_algo = ALGO_LYRA2v2;
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, -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;
// pools (failover/getwork infos)
struct pool_infos pools[MAX_POOLS_PLUS_DEV] = { 0 };
int num_pools = 1;
int dev_pool_id = 0;
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_INITIALIZER;
pthread_mutex_t stratum_work_lock = PTHREAD_MUTEX_INITIALIZER;
struct snarfs * sf = NULL;
static unsigned char pk_script[25] = { 0 };
static size_t pk_script_size = 0;
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 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;
pthread_mutex_t *work_restart_lock = 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;
static char *lp_id;
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(NOT NECESSARY FOR VERTMINER)\n\
lyra2v2 Lyra2REv2(VertCoin)\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\
--eco Use Eco mode\n\
Auto tuning for low energy (Lyra2REv2 only)\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\
--shares-limit maximum shares [s] to mine before exiting the program.\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: 10)\n\
-n, --ndevs list cuda devices\n\
-N, --statsavg number of samples used to compute hashrate (default: 30)\n\
--coinbase-addr=ADDR payout address for solo mining\n\
--no-getwork disable getwork support\n\
--no-gbt disable getblocktemplate support (height check in solo)\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
"\
--hide-diff hide submitted block and net difficulty (old mode)\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\
-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 },
{ "coinbase-addr", 1, NULL, 1016 },
{ "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-getwork", 0, NULL, 1010 },
{ "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-shares-limit", 1, NULL, 1109 },
{ "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' },
{ "show-diff", 0, NULL, 1013 },
{ "hide-diff", 0, NULL, 1014 },
{ "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
{ "eco", 0, NULL, 1081 },
{ 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 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t g_work_time_lock = PTHREAD_MUTEX_INITIALIZER;
// get const array size (defined in vertminer.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, 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
void get_currentalgo(char* buf, int sz)
{
snprintf(buf, sz, "%s", algo_names[opt_algo]);
}
/**
* Exit app
*/
void proper_exit(int reason)
{
free_snarfs(sf);
printf("%s restarting all threads\n", __func__);
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(hnvml, device_map[n]);
}
nvml_destroy(hnvml);
}
#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 */
static void calc_network_diff(struct work *work)
{
// sample for diff 43.281 : 1c05ea29
uint32_t nbits = swab32(work->data[18]);
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_debug_diff)
applog(LOG_DEBUG, "net diff: %f -> shift %u, bits %08x", d, shift, bits);
net_diff = d;
}
#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 (opt_showdiff)
sprintf(suppl, "diff %.3f", sharediff);
else // accepted percent
sprintf(suppl, "%.2f%%", 100. * p->accepted_count / (p->accepted_count + p->rejected_count));
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, "accepted: %lu/%lu (%s), %s %s",
p->accepted_count,
p->accepted_count + p->rejected_count,
suppl, 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;
pthread_mutex_lock(&g_work_time_lock);
g_work_time = 0;
pthread_mutex_unlock(&g_work_time_lock);
}
}
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;
int idnonce = 0;
/* discard if a newer block was received */
stale_work = work->height && work->height < g_work.height;
if (!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 (!submit_old && stale_work) {
if (opt_debug)
applog(LOG_WARNING, "stale work detected, discarding");
return true;
}
uint32_t sent = 0;
uint32_t ntime, nonce;
char *ntimestr, *noncestr, *xnonce2str, *nvotestr;
uint16_t nvote = 0;
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
pthread_mutex_lock(&g_work_time_lock);
g_work_time = 0;
pthread_mutex_unlock(&g_work_time_lock);
restart_threads();
return true;
}
ntimestr = bin2hex((const uchar*)(&ntime), 4);
xnonce2str = bin2hex(work->xnonce2, work->xnonce2_len);
// store to keep/display the solved ratio/diff
stratum.sharediff = work->sharediff[idnonce];
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);
sprintf(s, "{\"method\": \"mining.submit\", \"params\": ["
"\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":%d}",
pool->user, work->job_id + 8, xnonce2str, ntimestr, noncestr, 10+idnonce);
// printf("{\"method\": \"mining.submit\", \"params\": ["
// "\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":%d}",
// pool->user, work->job_id + 8, xnonce2str, ntimestr, noncestr, 10+idnonce);
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);
return true;
}
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_submit_work(struct workio_cmd *wc, CURL *curl)
{
int failures = 0;
uint32_t pooln = wc->pooln;
// applog(LOG_DEBUG, "%s: pool %d", __func__, wc->pooln);
/* 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);
}
return true;
}
static void *workio_thread(void *userdata)
{
struct thr_info *mythr = (struct thr_info*)userdata;
CURL *curl;
bool ok = true;
curl = curl_easy_init();
if (unlikely(!curl)) {
applog(LOG_ERR, "CURL initialization failed");
return NULL;
}
while (ok && !abort_flag) {
struct workio_cmd *wc;
/* wait for workio_cmd sent to us, on our queue */
wc = (struct workio_cmd *)tq_pop(mythr->q, NULL);
if (!wc) {
ok = false;
break;
}
/* process workio_cmd */
switch (wc->cmd) {
break;
case WC_SUBMIT_WORK:
if (opt_led_mode == LED_MODE_SHARES)
gpu_led_on(device_map[wc->thr->id]);
ok = workio_submit_work(wc, curl);
if (opt_led_mode == LED_MODE_SHARES)
gpu_led_off(device_map[wc->thr->id]);
break;
case WC_ABORT:
default: /* should never happen */
ok = false;
break;
}
if (!ok && num_pools > 1 && opt_pool_failover) {
if (opt_debug_threads)
applog(LOG_DEBUG, "%s died, failover", __func__);
ok = pool_switch_next(&pools[0], -1);
tq_push(wc->thr->q, NULL); // get_work() will return false
}
workio_cmd_free(wc);
}
if (opt_debug_threads)
applog(LOG_DEBUG, "%s() died", __func__);
curl_easy_cleanup(curl);
tq_freeze(mythr->q);
return NULL;
}
static bool submit_work(struct thr_info *thr, const struct work *work_in)
{
struct workio_cmd *wc;
/* fill out work request message */
wc = (struct workio_cmd *)calloc(1, sizeof(*wc));
if (!wc)
return false;
wc->u.work = (struct work *)aligned_calloc(sizeof(*work_in));
if (!wc->u.work)
goto err_out;
wc->cmd = WC_SUBMIT_WORK;
wc->thr = thr;
memcpy(wc->u.work, work_in, sizeof(struct work));
wc->pooln = work_in->pooln;
/* send solution to workio thread */
if (!tq_push(thr_info[work_thr_id].q, wc))
goto err_out;
return true;
err_out:
workio_cmd_free(wc);
return false;
}
static bool stratum_gen_work(struct stratum_ctx *sctx, struct work *work)
{
uchar merkle_root[64] = { 0 };
int i;
if (!sctx->job.job_id) {
// applog(LOG_WARNING, "stratum_gen_work: job not yet retrieved");
return false;
}
pthread_mutex_lock(&stratum_work_lock);
// store the job ntime as high part of jobid
snprintf(work->job_id, sizeof(work->job_id), "%07x %s",
be32dec(sctx->job.ntime) & 0xfffffff, sctx->job.job_id);
work->xnonce2_len = sctx->xnonce2_size;
memcpy(work->xnonce2, sctx->job.xnonce2, sctx->xnonce2_size);
// also store the block number
work->height = sctx->job.height;
// and the pool of the current stratum
work->pooln = sctx->pooln;
/* Generate merkle root */
sha256d(merkle_root, sctx->job.coinbase, (int)sctx->job.coinbase_size);
for (i = 0; i < sctx->job.merkle_count; i++) {
memcpy(merkle_root + 32, sctx->job.merkle[i], 32);
sha256d(merkle_root, merkle_root, 64);
}
/* Increment extranonce2 */
for (i = 0; i < (int)sctx->xnonce2_size && !++sctx->job.xnonce2[i]; i++);
/* Assemble block header */
memset(work->data, 0, sizeof(work->data));
work->data[0] = le32dec(sctx->job.version);
for (i = 0; i < 8; i++)
{
work->data[1 + i] = le32dec((uint32_t *)sctx->job.prevhash + i);
}
for (i = 0; i < 8; i++)
{
work->data[9 + i] = be32dec((uint32_t *)merkle_root + i);
}
work->data[17] = le32dec(sctx->job.ntime);
work->data[18] = le32dec(sctx->job.nbits);
work->data[20] = 0x80000000;
work->data[31] = 0x00000280;
if (opt_showdiff || opt_max_diff > 0.)
calc_network_diff(work);
pthread_mutex_unlock(&stratum_work_lock);
if (opt_debug) {
uint32_t utm = work->data[17];
utm = swab32(utm);
char *tm = atime2str(utm - sctx->srvtime_diff);
char *xnonce2str = bin2hex(work->xnonce2, sctx->xnonce2_size);
applog(LOG_DEBUG, "DEBUG: job_id=%s xnonce2=%s time=%s",
work->job_id, xnonce2str, tm);
free(tm);
free(xnonce2str);
}
if (opt_difficulty == 0.)
opt_difficulty = 1.;
work_set_target(work, sctx->job.diff / (256.0 * opt_difficulty));
if (stratum_diff != sctx->job.diff) {
char sdiff[32] = { 0 };
// store for api stats
stratum_diff = sctx->job.diff;
if (opt_showdiff && work->targetdiff != stratum_diff)
snprintf(sdiff, 32, " (%.5f)", work->targetdiff);
applog(LOG_WARNING, "Stratum difficulty set to %g%s", stratum_diff, sdiff);
}
return true;
}
void restart_threads(void)
{
if (opt_debug && !opt_quiet)
applog(LOG_DEBUG,"%s", __FUNCTION__);
for (int i = 0; i < opt_n_threads && work_restart; i++)
{
pthread_mutex_lock(&work_restart_lock[i]);
work_restart[i].restart = 1;
pthread_mutex_unlock(&work_restart_lock[i]);
}
}
void restart_thread(int thr_id)
{
pthread_mutex_lock(&work_restart_lock[thr_id]);
work_restart[thr_id].restart = 1;
pthread_mutex_unlock(&work_restart_lock[thr_id]);
}
static bool wanna_mine(int thr_id, struct snarfs *sf)
{
bool state = true;
bool allow_pool_rotate = (thr_id == 0 && num_pools > 1 && !pool_is_switching);
if ((thr_id == 0) && sf && sf->do_work && !pool_is_switching)
{
if (sf->want_to_enable ^ sf->enabled)
{
state = false;
conditional_state[thr_id] = (uint8_t) !state; // only one wait message in logs
return state;
}
}
if (opt_max_temp > 0.0) {
#ifdef USE_WRAPNVML
struct cgpu_info * cgpu = &thr_info[thr_id].gpu;
float temp = gpu_temp(cgpu);
if (temp > opt_max_temp) {
if (!conditional_state[thr_id] && !opt_quiet)
gpulog(LOG_INFO, thr_id, "temperature too high (%.0f°c), waiting...", temp);
state = false;
} else if (opt_max_temp > 0. && opt_resume_temp > 0. && conditional_state[thr_id] && temp > opt_resume_temp) {
if (!thr_id && opt_debug)
applog(LOG_DEBUG, "temperature did not reach resume value %.1f...", opt_resume_temp);
state = false;
}
#endif
}
// Network Difficulty
if (opt_max_diff > 0.0 && net_diff > opt_max_diff) {
int next = pool_get_first_valid(&pools[0], cur_pooln+1);
if (num_pools > 1 && pools[next].max_diff != pools[cur_pooln].max_diff && opt_resume_diff <= 0.)
conditional_pool_rotate = allow_pool_rotate;
if (!thr_id && !conditional_state[thr_id] && !opt_quiet)
applog(LOG_INFO, "network diff too high, waiting...");
state = false;
} else if (opt_max_diff > 0. && opt_resume_diff > 0. && conditional_state[thr_id] && net_diff > opt_resume_diff) {
if (!thr_id && opt_debug)
applog(LOG_DEBUG, "network diff did not reach resume value %.3f...", opt_resume_diff);