forked from tpruvot/cpuminer-multi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpu-miner.c
3649 lines (3333 loc) · 95.1 KB
/
cpu-miner.c
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 Lucas Jones
* Copyright 2014 Tanguy Pruvot
*
* 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>
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <curl/curl.h>
#include <jansson.h>
#include <openssl/sha.h>
#ifdef _MSC_VER
#include <windows.h>
#include <stdint.h>
#else
#include <errno.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
#ifndef WIN32
#include <sys/resource.h>
#endif
#include "miner.h"
#ifdef WIN32
#include "compat/winansi.h"
BOOL WINAPI ConsoleHandler(DWORD);
#endif
#ifdef _MSC_VER
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib")
#endif
#define LP_SCANTIME 60
#ifndef min
#define min(a,b) (a>b ? b : a)
#define max(a,b) (a<b ? b : a)
#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;
};
enum algos {
ALGO_KECCAK, /* Keccak (old) */
ALGO_KECCAKC, /* Keccak */
ALGO_HEAVY, /* Heavy */
ALGO_NEOSCRYPT, /* NeoScrypt(128, 2, 1) with Salsa20/20 and ChaCha20/20 */
ALGO_QUARK, /* Quark */
ALGO_ALLIUM, /* Garlicoin double lyra2 */
ALGO_ALLIUMV2, /* AlliumV2 (Tuxcoin) */
ALGO_AXIOM, /* Shabal 256 Memohash */
ALGO_BASTION,
ALGO_BLAKE, /* Blake 256 */
ALGO_BLAKECOIN, /* Simplified 8 rounds Blake 256 */
ALGO_BLAKE2S, /* Blake2s */
ALGO_BMW, /* BMW 256 */
ALGO_C11, /* C11 Chaincoin/Flaxcoin X11 variant */
ALGO_CRYPTOLIGHT, /* cryptonight-light (Aeon) */
ALGO_CRYPTONIGHT, /* CryptoNight */
ALGO_DECRED, /* Decred */
ALGO_DMD_GR, /* Diamond */
ALGO_DROP, /* Dropcoin */
ALGO_FRESH, /* Fresh */
ALGO_GROESTL, /* Groestl */
ALGO_JHA,
ALGO_LBRY, /* Lbry Sha Ripemd */
ALGO_LUFFA, /* Luffa (Joincoin, Doom) */
ALGO_LYRA2, /* Lyra2RE */
ALGO_LYRA2REV2, /* Lyra2REv2 (Vertcoin) */
ALGO_MYR_GR, /* Myriad Groestl */
ALGO_NIST5, /* Nist5 */
ALGO_PENTABLAKE, /* Pentablake */
ALGO_PHI1612,
ALGO_PHI2,
ALGO_PLUCK, /* Pluck (Supcoin) */
ALGO_QUBIT, /* Qubit */
ALGO_SCRYPT, /* scrypt */
ALGO_SCRYPTJANE, /* Chacha */
ALGO_SHAVITE3, /* Shavite3 */
ALGO_SHA256D, /* SHA-256d */
ALGO_SIA, /* Blake2-B */
ALGO_SIB, /* X11 + gost (Sibcoin) */
ALGO_SKEIN, /* Skein */
ALGO_SKEIN2, /* Double skein (Woodcoin) */
ALGO_SONOA,
ALGO_S3, /* S3 */
ALGO_TIMETRAVEL, /* Timetravel-8 (Machinecoin) */
ALGO_BITCORE, /* Timetravel-10 (Bitcore) */
ALGO_TRIBUS, /* Denarius jh/keccak/echo */
ALGO_VANILLA, /* Vanilla (Blake256 8-rounds - double sha256) */
ALGO_VELTOR, /* Skein Shavite Shabal Streebog */
ALGO_X11EVO, /* Permuted X11 */
ALGO_X11, /* X11 */
ALGO_X12,
ALGO_X13, /* X13 */
ALGO_X14, /* X14 */
ALGO_X15, /* X15 */
ALGO_X16R,
ALGO_X16S,
ALGO_X17, /* X17 */
ALGO_XEVAN,
ALGO_YESCRYPT,
ALGO_ZR5,
ALGO_COUNT
};
static const char *algo_names[] = {
"keccak",
"keccakc",
"heavy",
"neoscrypt",
"quark",
"allium",
"alliumv2",
"axiom",
"bastion",
"blake",
"blakecoin",
"blake2s",
"bmw",
"c11",
"cryptolight",
"cryptonight",
"decred",
"dmd-gr",
"drop",
"fresh",
"groestl",
"jha",
"lbry",
"luffa",
"lyra2re",
"lyra2rev2",
"myr-gr",
"nist5",
"pentablake",
"phi1612",
"phi2",
"pluck",
"qubit",
"scrypt",
"scrypt-jane",
"shavite3",
"sha256d",
"sia",
"sib",
"skein",
"skein2",
"sonoa",
"s3",
"timetravel",
"bitcore",
"tribus",
"vanilla",
"veltor",
"x11evo",
"x11",
"x12",
"x13",
"x14",
"x15",
"x16r",
"x16s",
"x17",
"xevan",
"yescrypt",
"zr5",
"\0"
};
bool opt_debug = false;
bool opt_debug_diff = false;
bool opt_protocol = false;
bool opt_benchmark = false;
bool opt_redirect = true;
bool opt_showdiff = true;
bool opt_extranonce = true;
bool want_longpoll = true;
bool have_longpoll = false;
bool have_gbt = true;
bool allow_getwork = true;
bool want_stratum = true;
bool have_stratum = false;
bool opt_stratum_stats = false;
bool allow_mininginfo = true;
bool use_syslog = false;
bool use_colors = true;
static bool opt_background = false;
bool opt_quiet = false;
int opt_maxlograte = 5;
bool opt_randomize = false;
static int opt_retries = -1;
static int opt_fail_pause = 10;
static int opt_time_limit = 0;
int opt_timeout = 300;
static int opt_scantime = 5;
static enum algos opt_algo = ALGO_SCRYPT;
static int opt_scrypt_n = 1024;
static int opt_pluck_n = 128;
static unsigned int opt_nfactor = 6;
int opt_n_threads = 0;
int64_t opt_affinity = -1L;
int opt_priority = 0;
int num_cpus;
char *rpc_url;
char *rpc_userpass;
char *rpc_user, *rpc_pass;
char *short_url = NULL;
static unsigned char pk_script[25] = { 0 };
static size_t pk_script_size = 0;
static char coinbase_sig[101] = { 0 };
char *opt_cert;
char *opt_proxy;
long opt_proxy_type;
struct thr_info *thr_info;
int work_thr_id;
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;
bool jsonrpc_2 = false;
char rpc2_id[64] = "";
char *rpc2_blob = NULL;
size_t rpc2_bloblen = 0;
uint32_t rpc2_target = 0;
char *rpc2_job_id = NULL;
bool aes_ni_supported = false;
double opt_diff_factor = 1.0;
pthread_mutex_t rpc2_job_lock;
pthread_mutex_t rpc2_login_lock;
pthread_mutex_t applog_lock;
pthread_mutex_t stats_lock;
uint32_t zr5_pok = 0;
bool use_roots = false;
uint32_t solved_count = 0L;
uint32_t accepted_count = 0L;
uint32_t rejected_count = 0L;
double *thr_hashrates;
uint64_t global_hashrate = 0;
double stratum_diff = 0.;
double net_diff = 0.;
double net_hashrate = 0.;
uint64_t net_blocks = 0;
// conditional mining
bool conditional_state[MAX_CPUS] = { 0 };
double opt_max_temp = 0.0;
double opt_max_diff = 0.0;
double opt_max_rate = 0.0;
uint32_t opt_work_size = 0; /* default */
char *opt_api_allow = NULL;
int opt_api_remote = 0;
int opt_api_listen = 4048; /* 0 to disable */
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
#endif
static char const usage[] = "\
Usage: " PACKAGE_NAME " [OPTIONS]\n\
Options:\n\
-a, --algo=ALGO specify the algorithm to use\n\
allium Garlicoin double lyra2\n\
alliumV2 AlliumV2 (Tuxcoin)\n\
axiom Shabal-256 MemoHash\n\
bitcore Timetravel with 10 algos\n\
blake Blake-256 14-rounds (SFR)\n\
blakecoin Blake-256 single sha256 merkle\n\
blake2s Blake2-S (256)\n\
bmw BMW 256\n\
c11/flax C11\n\
cryptolight Cryptonight-light\n\
cryptonight Monero\n\
decred Blake-256 14-rounds 180 bytes\n\
dmd-gr Diamond-Groestl\n\
drop Dropcoin\n\
fresh Fresh\n\
groestl GroestlCoin\n\
heavy Heavy\n\
jha JHA\n\
keccak Keccak (Old and deprecated)\n\
keccakc Keccak (CreativeCoin)\n\
luffa Luffa\n\
lyra2re Lyra2RE\n\
lyra2rev2 Lyra2REv2 (Vertcoin)\n\
myr-gr Myriad-Groestl\n\
neoscrypt NeoScrypt(128, 2, 1)\n\
nist5 Nist5\n\
pluck Pluck:128 (Supcoin)\n\
pentablake Pentablake\n\
phi LUX initial algo\n\
phi2 LUX newer algo\n\
quark Quark\n\
qubit Qubit\n\
scrypt scrypt(1024, 1, 1) (default)\n\
scrypt:N scrypt(N, 1, 1)\n\
scrypt-jane:N (with N factor from 4 to 30)\n\
shavite3 Shavite3\n\
sha256d SHA-256d\n\
sia Blake2-B\n\
sib X11 + gost (SibCoin)\n\
skein Skein+Sha (Skeincoin)\n\
skein2 Double Skein (Woodcoin)\n\
sonoa A series of 97 hashes from x17\n\
s3 S3\n\
timetravel Timetravel (Machinecoin)\n\
vanilla Blake-256 8-rounds\n\
x11evo Permuted x11\n\
x11 X11\n\
x12 X12\n\
x13 X13\n\
x14 X14\n\
x15 X15\n\
x16r X16R (Raven)\n\
x16s X16S (Pigeon)\n\
x17 X17\n\
xevan Xevan (BitSend)\n\
yescrypt Yescrypt\n\
zr5 ZR5\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 processors)\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=N maximum time [s] to mine before exiting the program.\n\
-T, --timeout=N timeout for long poll and stratum (default: 300 seconds)\n\
-s, --scantime=N upper bound on time spent scanning current work when\n\
long polling is unavailable, in seconds (default: 5)\n\
--randomize Randomize scan range start to reduce duplicates\n\
-f, --diff-factor Divide req. difficulty by this factor (std is 1.0)\n\
-m, --diff-multiplier Multiply difficulty by this factor (std is 1.0)\n\
-n, --nfactor neoscrypt N-Factor\n\
--coinbase-addr=ADDR payout address for solo mining\n\
--coinbase-sig=TEXT data to insert in the coinbase when possible\n\
--max-log-rate limit per-core hashrate logs (default: 5s)\n\
--no-longpoll disable long polling support\n\
--no-getwork disable getwork support\n\
--no-gbt disable getblocktemplate support\n\
--no-stratum disable X-Stratum support\n\
--no-extranonce disable Stratum extranonce support\n\
--no-redirect ignore requests to change the URL of the mining server\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\
--hide-diff Hide submitted block and net difficulty\n"
#ifdef HAVE_SYSLOG_H
"\
-S, --syslog use system log for output messages\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\
--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:4048)\n\
--api-remote Allow remote control\n\
--max-temp=N Only mine if cpu temp is less than specified value (linux)\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\
-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:b:Bc:CDf:hm:n:p:Px:qr:R:s:t:T:o:u:O:V";
static struct option const options[] = {
{ "algo", 1, NULL, 'a' },
{ "api-bind", 1, NULL, 'b' },
{ "api-remote", 0, NULL, 1030 },
{ "background", 0, NULL, 'B' },
{ "benchmark", 0, NULL, 1005 },
{ "cputest", 0, NULL, 1006 },
{ "cert", 1, NULL, 1001 },
{ "coinbase-addr", 1, NULL, 1016 },
{ "coinbase-sig", 1, NULL, 1015 },
{ "config", 1, NULL, 'c' },
{ "cpu-affinity", 1, NULL, 1020 },
{ "cpu-priority", 1, NULL, 1021 },
{ "no-color", 0, NULL, 1002 },
{ "debug", 0, NULL, 'D' },
{ "diff-factor", 1, NULL, 'f' },
{ "diff", 1, NULL, 'f' }, // deprecated (alias)
{ "diff-multiplier", 1, NULL, 'm' },
{ "help", 0, NULL, 'h' },
{ "nfactor", 1, NULL, 'n' },
{ "no-gbt", 0, NULL, 1011 },
{ "no-getwork", 0, NULL, 1010 },
{ "no-longpoll", 0, NULL, 1003 },
{ "no-redirect", 0, NULL, 1009 },
{ "no-stratum", 0, NULL, 1007 },
{ "no-extranonce", 0, NULL, 1012 },
{ "max-temp", 1, NULL, 1060 },
{ "max-diff", 1, NULL, 1061 },
{ "max-rate", 1, NULL, 1062 },
{ "pass", 1, NULL, 'p' },
{ "protocol", 0, NULL, 'P' },
{ "protocol-dump", 0, NULL, 'P' },
{ "proxy", 1, NULL, 'x' },
{ "quiet", 0, NULL, 'q' },
{ "retries", 1, NULL, 'r' },
{ "retry-pause", 1, NULL, 'R' },
{ "randomize", 0, NULL, 1024 },
{ "scantime", 1, NULL, 's' },
{ "show-diff", 0, NULL, 1013 },
{ "hide-diff", 0, NULL, 1014 },
{ "max-log-rate", 1, NULL, 1019 },
#ifdef HAVE_SYSLOG_H
{ "syslog", 0, NULL, 'S' },
#endif
{ "time-limit", 1, NULL, 1008 },
{ "threads", 1, NULL, 't' },
{ "timeout", 1, NULL, 'T' },
{ "url", 1, NULL, 'o' },
{ "user", 1, NULL, 'u' },
{ "userpass", 1, NULL, 'O' },
{ "version", 0, NULL, 'V' },
{ 0, 0, 0, 0 }
};
static struct work g_work = {{ 0 }};
static time_t g_work_time = 0;
static pthread_mutex_t g_work_lock;
static bool submit_old = false;
static char *lp_id;
static void workio_cmd_free(struct workio_cmd *wc);
#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
}
#ifdef __BIONIC__
#define pthread_setaffinity_np(tid,sz,s) {} /* only do process affinity */
#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(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
static inline void drop_policy(void) { }
static void affine_to_cpu_mask(int id, unsigned long mask) { }
#endif
void get_currentalgo(char* buf, int sz)
{
if (opt_algo == ALGO_SCRYPTJANE)
snprintf(buf, sz, "%s:%d", algo_names[opt_algo], opt_scrypt_n);
else
snprintf(buf, sz, "%s", algo_names[opt_algo]);
}
void proper_exit(int reason)
{
#ifdef WIN32
if (opt_background) {
HWND hcon = GetConsoleWindow();
if (hcon) {
// unhide parent command line windows
ShowWindow(hcon, SW_SHOWMINNOACTIVE);
}
}
#endif
exit(reason);
}
static inline void work_free(struct work *w)
{
if (w->txs) free(w->txs);
if (w->workid) free(w->workid);
if (w->job_id) free(w->job_id);
if (w->xnonce2) free(w->xnonce2);
}
static inline void work_copy(struct work *dest, const struct work *src)
{
memcpy(dest, src, sizeof(struct work));
if (src->txs)
dest->txs = strdup(src->txs);
if (src->workid)
dest->workid = strdup(src->workid);
if (src->job_id)
dest->job_id = strdup(src->job_id);
if (src->xnonce2) {
dest->xnonce2 = (uchar*) malloc(src->xnonce2_len);
memcpy(dest->xnonce2, src->xnonce2, src->xnonce2_len);
}
}
/* compute nbits to get the network diff */
static 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
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; // testnet
if (opt_debug_diff)
applog(LOG_DEBUG, "net diff: %f -> shift %u, bits %08x", d, shift, bits);
net_diff = d;
}
static bool work_decode(const json_t *val, struct work *work)
{
int i;
int data_size = 128, target_size = sizeof(work->target);
int adata_sz = 32, atarget_sz = ARRAY_SIZE(work->target);
if (opt_algo == ALGO_DROP || opt_algo == ALGO_NEOSCRYPT || opt_algo == ALGO_ZR5) {
data_size = 80; target_size = 32;
adata_sz = 20;
atarget_sz = target_size / sizeof(uint32_t);
} else if (opt_algo == ALGO_DECRED) {
allow_mininginfo = false;
data_size = 192;
adata_sz = 180/4;
} else if (use_roots) {
data_size = 144;
adata_sz = 36;
}
if (jsonrpc_2) {
return rpc2_job_decode(val, work);
}
if (unlikely(!jobj_binary(val, "data", work->data, data_size))) {
applog(LOG_ERR, "JSON invalid data");
goto err_out;
}
if (unlikely(!jobj_binary(val, "target", work->target, target_size))) {
applog(LOG_ERR, "JSON invalid target");
goto err_out;
}
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 ((opt_showdiff || opt_max_diff > 0.) && !allow_mininginfo)
calc_network_diff(work);
work->targetdiff = target_to_diff(work->target);
// for api stats, on longpoll pools
stratum_diff = work->targetdiff;
if (opt_algo == ALGO_DROP || opt_algo == ALGO_ZR5) {
#define POK_BOOL_MASK 0x00008000
#define POK_DATA_MASK 0xFFFF0000
if (work->data[0] & POK_BOOL_MASK) {
applog(LOG_BLUE, "POK received: %08xx", work->data[0]);
zr5_pok = work->data[0] & POK_DATA_MASK;
}
} else if (opt_algo == ALGO_DECRED) {
// some random extradata to make the work unique
work->data[36] = (rand()*4);
work->height = work->data[32];
// required for the getwork pools (multicoin.co)
if (!have_longpoll && work->height > net_blocks + 1) {
char netinfo[64] = { 0 };
if (opt_showdiff && net_diff > 0.) {
if (net_diff != work->targetdiff)
sprintf(netinfo, ", diff %.3f, target %.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;
}
} else if (opt_algo == ALGO_PHI2) {
if (work->data[0] & (1<<30)) use_roots = true;
else for (i = 20; i < 36; i++) {
if (work->data[i]) { use_roots = true; break; }
}
}
return true;
err_out:
return false;
}
// 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 || have_longpoll || !allow_mininginfo)
return false;
int curl_err = 0;
json_t *val = json_rpc_call(curl, rpc_url, rpc_userpass, info_req, &curl_err, 0);
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, "difficulty");
if (key) {
if (json_is_object(key))
key = json_object_get(key, "proof-of-work");
if (json_is_real(key))
net_diff = json_real_value(key);
}
key = json_object_get(res, "networkhashps");
if (key && json_is_integer(key)) {
net_hashrate = (double) json_integer_value(key);
}
key = json_object_get(res, "blocks");
if (key && json_is_integer(key)) {
net_blocks = json_integer_value(key);
}
if (!work->height) {
// complete missing data from getwork
work->height = (uint32_t) net_blocks + 1;
if (work->height > g_work.height) {
restart_threads();
if (!opt_quiet) {
char netinfo[64] = { 0 };
char srate[32] = { 0 };
sprintf(netinfo, "diff %.2f", net_diff);
if (net_hashrate) {
format_hashrate(net_hashrate, srate);
strcat(netinfo, ", net ");
strcat(netinfo, srate);
}
applog(LOG_BLUE, "%s block %d, %s",
algo_names[opt_algo], work->height, netinfo);
}
}
}
}
}
json_decref(val);
return true;
}
#define BLOCK_VERSION_CURRENT 3
static bool gbt_work_decode(const json_t *val, struct work *work)
{
int i, n;
uint32_t version, curtime, bits;
uint32_t prevhash[8];
uint32_t target[8];
int cbtx_size;
uchar *cbtx = NULL;
int tx_count, tx_size;
uchar txc_vi[9];
uchar(*merkle_tree)[32] = NULL;
bool coinbase_append = false;
bool submit_coinbase = false;
bool version_force = false;
bool version_reduce = false;
json_t *tmp, *txa;
bool rc = false;
tmp = json_object_get(val, "mutable");
if (tmp && json_is_array(tmp)) {
n = (int) json_array_size(tmp);
for (i = 0; i < n; i++) {
const char *s = json_string_value(json_array_get(tmp, i));
if (!s)
continue;
if (!strcmp(s, "coinbase/append"))
coinbase_append = true;
else if (!strcmp(s, "submit/coinbase"))
submit_coinbase = true;
else if (!strcmp(s, "version/force"))
version_force = true;
else if (!strcmp(s, "version/reduce"))
version_reduce = true;
}
}
tmp = json_object_get(val, "height");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid height");
goto out;
}
work->height = (int) json_integer_value(tmp);
applog(LOG_BLUE, "Current block is %d", work->height);
tmp = json_object_get(val, "version");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid version");
goto out;
}
version = (uint32_t) json_integer_value(tmp);
if ((version & 0xffU) > BLOCK_VERSION_CURRENT) {
if (version_reduce) {
version = (version & ~0xffU) | BLOCK_VERSION_CURRENT;
} else if (have_gbt && allow_getwork && !version_force) {
applog(LOG_DEBUG, "Switching to getwork, gbt version %d", version);
have_gbt = false;
goto out;
} else if (!version_force) {
applog(LOG_ERR, "Unrecognized block version: %u", version);
goto out;
}
}
if (unlikely(!jobj_binary(val, "previousblockhash", prevhash, sizeof(prevhash)))) {
applog(LOG_ERR, "JSON invalid previousblockhash");
goto out;
}
tmp = json_object_get(val, "curtime");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid curtime");
goto out;
}
curtime = (uint32_t) json_integer_value(tmp);
if (unlikely(!jobj_binary(val, "bits", &bits, sizeof(bits)))) {
applog(LOG_ERR, "JSON invalid bits");
goto out;
}
/* find count and size of transactions */
txa = json_object_get(val, "transactions");
if (!txa || !json_is_array(txa)) {
applog(LOG_ERR, "JSON invalid transactions");
goto out;
}
tx_count = (int) json_array_size(txa);
tx_size = 0;
for (i = 0; i < tx_count; i++) {
const json_t *tx = json_array_get(txa, i);
const char *tx_hex = json_string_value(json_object_get(tx, "data"));
if (!tx_hex) {
applog(LOG_ERR, "JSON invalid transactions");
goto out;
}
tx_size += (int) (strlen(tx_hex) / 2);
}
/* build coinbase transaction */
tmp = json_object_get(val, "coinbasetxn");
if (tmp) {
const char *cbtx_hex = json_string_value(json_object_get(tmp, "data"));
cbtx_size = cbtx_hex ? (int) strlen(cbtx_hex) / 2 : 0;
cbtx = (uchar*) malloc(cbtx_size + 100);
if (cbtx_size < 60 || !hex2bin(cbtx, cbtx_hex, cbtx_size)) {
applog(LOG_ERR, "JSON invalid coinbasetxn");
goto out;
}
} else {
int64_t cbvalue;
if (!pk_script_size) {
if (allow_getwork) {
applog(LOG_INFO, "No payout address provided, switching to getwork");
have_gbt = false;
} else
applog(LOG_ERR, "No payout address provided");
goto out;
}
tmp = json_object_get(val, "coinbasevalue");
if (!tmp || !json_is_number(tmp)) {
applog(LOG_ERR, "JSON invalid coinbasevalue");
goto out;
}
cbvalue = (int64_t) (json_is_integer(tmp) ? json_integer_value(tmp) : json_number_value(tmp));
cbtx = (uchar*) malloc(256);
le32enc((uint32_t *)cbtx, 1); /* version */
cbtx[4] = 1; /* in-counter */
memset(cbtx+5, 0x00, 32); /* prev txout hash */
le32enc((uint32_t *)(cbtx+37), 0xffffffff); /* prev txout index */
cbtx_size = 43;
/* BIP 34: height in coinbase */
for (n = work->height; n; n >>= 8)
cbtx[cbtx_size++] = n & 0xff;
/* If the last byte pushed is >= 0x80, then we need to add
another zero byte to signal that the block height is a
positive number. */
if (cbtx[cbtx_size - 1] & 0x80)
cbtx[cbtx_size++] = 0;
cbtx[42] = cbtx_size - 43;
cbtx[41] = cbtx_size - 42; /* scriptsig length */
le32enc((uint32_t *)(cbtx+cbtx_size), 0xffffffff); /* sequence */
cbtx_size += 4;
cbtx[cbtx_size++] = 1; /* out-counter */
le32enc((uint32_t *)(cbtx+cbtx_size), (uint32_t)cbvalue); /* value */
le32enc((uint32_t *)(cbtx+cbtx_size+4), cbvalue >> 32);
cbtx_size += 8;
cbtx[cbtx_size++] = (uint8_t) pk_script_size; /* txout-script length */
memcpy(cbtx+cbtx_size, pk_script, pk_script_size);
cbtx_size += (int) pk_script_size;
le32enc((uint32_t *)(cbtx+cbtx_size), 0); /* lock time */
cbtx_size += 4;
coinbase_append = true;
}
if (coinbase_append) {
unsigned char xsig[100];
int xsig_len = 0;
if (*coinbase_sig) {
n = (int) strlen(coinbase_sig);
if (cbtx[41] + xsig_len + n <= 100) {
memcpy(xsig+xsig_len, coinbase_sig, n);
xsig_len += n;
} else {
applog(LOG_WARNING, "Signature does not fit in coinbase, skipping");
}
}
tmp = json_object_get(val, "coinbaseaux");
if (tmp && json_is_object(tmp)) {
void *iter = json_object_iter(tmp);
while (iter) {
unsigned char buf[100];
const char *s = json_string_value(json_object_iter_value(iter));
n = s ? (int) (strlen(s) / 2) : 0;
if (!s || n > 100 || !hex2bin(buf, s, n)) {
applog(LOG_ERR, "JSON invalid coinbaseaux");
break;
}
if (cbtx[41] + xsig_len + n <= 100) {
memcpy(xsig+xsig_len, buf, n);
xsig_len += n;
}
iter = json_object_iter_next(tmp, iter);
}
}
if (xsig_len) {
unsigned char *ssig_end = cbtx + 42 + cbtx[41];
int push_len = cbtx[41] + xsig_len < 76 ? 1 :
cbtx[41] + 2 + xsig_len > 100 ? 0 : 2;
n = xsig_len + push_len;
memmove(ssig_end + n, ssig_end, cbtx_size - 42 - cbtx[41]);
cbtx[41] += n;
if (push_len == 2)
*(ssig_end++) = 0x4c; /* OP_PUSHDATA1 */
if (push_len)
*(ssig_end++) = xsig_len;
memcpy(ssig_end, xsig, xsig_len);
cbtx_size += n;
}
}
n = varint_encode(txc_vi, 1 + tx_count);
work->txs = (char*) malloc(2 * (n + cbtx_size + tx_size) + 1);
bin2hex(work->txs, txc_vi, n);
bin2hex(work->txs + 2*n, cbtx, cbtx_size);
/* generate merkle root */
merkle_tree = (uchar(*)[32]) calloc(((1 + tx_count + 1) & ~1), 32);
sha256d(merkle_tree[0], cbtx, cbtx_size);
for (i = 0; i < tx_count; i++) {
tmp = json_array_get(txa, i);
const char *tx_hex = json_string_value(json_object_get(tmp, "data"));
const int tx_size = tx_hex ? (int) (strlen(tx_hex) / 2) : 0;
unsigned char *tx = (uchar*) malloc(tx_size);
if (!tx_hex || !hex2bin(tx, tx_hex, tx_size)) {
applog(LOG_ERR, "JSON invalid transactions");
free(tx);
goto out;
}
sha256d(merkle_tree[1 + i], tx, tx_size);
if (!submit_coinbase)
strcat(work->txs, tx_hex);
}
n = 1 + tx_count;
while (n > 1) {
if (n % 2) {
memcpy(merkle_tree[n], merkle_tree[n-1], 32);
++n;
}
n /= 2;
for (i = 0; i < n; i++)
sha256d(merkle_tree[i], merkle_tree[2*i], 64);
}
/* assemble block header */
work->data[0] = swab32(version);
for (i = 0; i < 8; i++)
work->data[8 - i] = le32dec(prevhash + i);
for (i = 0; i < 8; i++)
work->data[9 + i] = be32dec((uint32_t *)merkle_tree[0] + i);
work->data[17] = swab32(curtime);
work->data[18] = le32dec(&bits);
memset(work->data + 19, 0x00, 52);
work->data[20] = 0x80000000;
work->data[31] = 0x00000280;
if (unlikely(!jobj_binary(val, "target", target, sizeof(target)))) {
applog(LOG_ERR, "JSON invalid target");
goto out;
}
for (i = 0; i < ARRAY_SIZE(work->target); i++)
work->target[7 - i] = be32dec(target + i);