-
Notifications
You must be signed in to change notification settings - Fork 10
/
cpu-miner.c
2388 lines (2149 loc) · 60.8 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-2017 pooler
*
* 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>
#ifdef WIN32
#include <windows.h>
#else
#include <errno.h>
#include <signal.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 <jansson.h>
#include <curl/curl.h>
#include "compat.h"
#include "miner.h"
#define PROGRAM_NAME "minerd"
#define LP_SCANTIME 60
#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 inline void affine_to_cpu(int id, int cpu)
{
cpu_set_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
sched_setaffinity(0, sizeof(set), &set);
}
#elif defined(__FreeBSD__) /* FreeBSD specific policy and affinity management */
#include <sys/cpuset.h>
static inline void drop_policy(void)
{
}
static inline void affine_to_cpu(int id, int cpu)
{
cpuset_t set;
CPU_ZERO(&set);
CPU_SET(cpu, &set);
cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset_t), &set);
}
#else
static inline void drop_policy(void)
{
}
static inline void affine_to_cpu(int id, int cpu)
{
}
#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_SCRYPT, /* scrypt(1024,1,1) */
ALGO_SHA256D, /* SHA-256d */
};
static const char *algo_names[] = {
[ALGO_SCRYPT] = "scrypt",
[ALGO_SHA256D] = "sha256d",
};
bool opt_debug = false;
bool opt_protocol = false;
static bool opt_benchmark = false;
bool opt_redirect = true;
bool want_longpoll = true;
bool have_longpoll = false;
bool have_gbt = true;
bool want_stratum = true;
bool have_stratum = false;
bool use_syslog = false;
static bool opt_background = false;
static bool opt_quiet = false;
static int opt_retries = -1;
static int opt_fail_pause = 30;
int opt_timeout = 0;
static int opt_scantime = 5;
static enum algos opt_algo = ALGO_SCRYPT;
static int opt_scrypt_n = 1024;
static int opt_n_threads;
static int num_processors;
static char *rpc_url;
static char *rpc_userpass;
static char *rpc_user, *rpc_pass;
static int pk_script_size;
static unsigned char pk_script[25];
static char coinbase_sig[101] = "";
char *opt_cert;
char *opt_proxy;
long opt_proxy_type;
struct thr_info *thr_info;
static int work_thr_id;
int longpoll_thr_id = -1;
int stratum_thr_id = -1;
struct work_restart *work_restart = NULL;
static struct stratum_ctx stratum;
pthread_mutex_t applog_lock;
static pthread_mutex_t stats_lock;
static unsigned long accepted_count = 0L;
static unsigned long rejected_count = 0L;
static double *thr_hashrates;
#ifdef HAVE_GETOPT_LONG
#include <getopt.h>
#else
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
#endif
static char const usage[] = "\
Usage: " PROGRAM_NAME " [OPTIONS]\n\
Options:\n\
-a, --algo=ALGO specify the algorithm to use\n\
scrypt scrypt(1024, 1, 1) (default)\n\
scrypt:N scrypt(N, 1, 1)\n\
sha256d SHA-256d\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\
-T, --timeout=N timeout for long polling, in seconds (default: none)\n\
-s, --scantime=N upper bound on time spent scanning current work when\n\
long polling is unavailable, in seconds (default: 5)\n\
--coinbase-addr=ADDR payout address for solo mining\n\
--coinbase-sig=TEXT data to insert in the coinbase when possible\n\
--no-longpoll disable long polling support\n\
--no-gpoabt disable getpoablocktemplate support\n\
--no-stratum disable X-Stratum support\n\
--no-redirect ignore requests to change the URL of the mining server\n\
-q, --quiet disable per-thread hashmeter output\n\
-D, --debug enable debug output\n\
-P, --protocol-dump verbose dump of protocol-level activities\n"
#ifdef HAVE_SYSLOG_H
"\
-S, --syslog use system log for output messages\n"
#endif
#ifndef WIN32
"\
-B, --background run the miner in the background\n"
#endif
"\
--benchmark run in offline benchmark mode\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[] =
#ifndef WIN32
"B"
#endif
#ifdef HAVE_SYSLOG_H
"S"
#endif
"a:c:Dhp:Px:qr:R:s:t:T:o:u:O:V";
static struct option const options[] = {
{ "algo", 1, NULL, 'a' },
#ifndef WIN32
{ "background", 0, NULL, 'B' },
#endif
{ "benchmark", 0, NULL, 1005 },
{ "cert", 1, NULL, 1001 },
{ "coinbase-addr", 1, NULL, 1013 },
{ "coinbase-sig", 1, NULL, 1015 },
{ "config", 1, NULL, 'c' },
{ "debug", 0, NULL, 'D' },
{ "help", 0, NULL, 'h' },
{ "no-gbt", 0, NULL, 1011 },
{ "no-longpoll", 0, NULL, 1003 },
{ "no-redirect", 0, NULL, 1009 },
{ "no-stratum", 0, NULL, 1007 },
{ "pass", 1, NULL, 'p' },
{ "protocol-dump", 0, NULL, 'P' },
{ "proxy", 1, NULL, 'x' },
{ "quiet", 0, NULL, 'q' },
{ "retries", 1, NULL, 'r' },
{ "retry-pause", 1, NULL, 'R' },
{ "scantime", 1, NULL, 's' },
#ifdef HAVE_SYSLOG_H
{ "syslog", 0, NULL, 'S' },
#endif
{ "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 }
};
/*
* PoA block has the following info
* version
* previouspoablockhash
* transactions
* coinbasevalue
* noncerange
* curtime
* bits
* height
* posblocksaudited {
* {
"data": "3c8808918e261978f631dd810b14ed8881dfca595115d9a0d1d09b07cdb0656a",
}
* }
* */
struct work {
uint32_t data[32];
uint32_t target[8];
int height;
uint32_t merkleRoot[8];
char *txs; //streamed transactions
char *pos_data; //streamed pos audited blocks
char *workid;
uint32_t previousPoABlockHash[8];
uint32_t hashPoAMerkleRoot[8]; //
uint32_t integratedHash[8];
uint32_t minedHash[8];
uint32_t version;
uint32_t time;
uint32_t bits;
char *job_id;
size_t xnonce2_len;
unsigned char *xnonce2;
};
static struct work g_work;
static time_t g_work_time;
static pthread_mutex_t g_work_lock;
static bool submit_old = false;
static char *lp_id;
static inline void work_free(struct work *w)
{
free(w->txs);
w->txs = NULL;
free(w->workid);
w->workid = NULL;
free(w->job_id);
w->job_id = NULL;
free(w->xnonce2);
w->xnonce2 = NULL;
free(w->pos_data);
w->pos_data = NULL;
}
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->pos_data)
dest->pos_data = strdup(src->pos_data);
if (src->workid)
dest->workid = strdup(src->workid);
if (src->job_id)
dest->job_id = strdup(src->job_id);
if (src->xnonce2) {
dest->xnonce2 = malloc(src->xnonce2_len);
memcpy(dest->xnonce2, src->xnonce2, src->xnonce2_len);
}
}
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(buf, hexstr, buflen))
return false;
return true;
}
static bool work_decode(const json_t *val, struct work *work)
{
int i;
if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
applog(LOG_ERR, "JSON invalid data");
goto err_out;
}
if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
applog(LOG_ERR, "JSON invalid target");
goto err_out;
}
for (i = 0; i < ARRAY_SIZE(work->data); i++)
work->data[i] = le32dec(work->data + i);
for (i = 0; i < ARRAY_SIZE(work->target); i++)
work->target[i] = le32dec(work->target + i);
return true;
err_out:
return false;
}
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;
unsigned char *cbtx = NULL;
int tx_count, tx_size;
unsigned char txc_vi[9];
unsigned char (*merkle_tree)[32] = NULL;
bool coinbase_append = false;
bool submit_coinbase = false;
bool segwit = false;
json_t *tmp, *txa;
bool rc = false;
tmp = json_object_get(val, "rules");
if (tmp && json_is_array(tmp)) {
n = 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, "segwit") || !strcmp(s, "!segwit"))
segwit = true;
}
}
tmp = json_object_get(val, "mutable");
if (tmp && json_is_array(tmp)) {
n = 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;
}
}
tmp = json_object_get(val, "height");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid height");
goto out;
}
work->height = json_integer_value(tmp);
tmp = json_object_get(val, "version");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid version");
goto out;
}
version = json_integer_value(tmp);
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 = 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 = 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 += 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 ? strlen(cbtx_hex) / 2 : 0;
cbtx = 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) {
goto out;
}
tmp = json_object_get(val, "coinbasevalue");
if (!tmp || !json_is_number(tmp)) {
applog(LOG_ERR, "JSON invalid coinbasevalue");
goto out;
}
cbvalue = json_is_integer(tmp) ? json_integer_value(tmp) : json_number_value(tmp);
cbtx = 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 (n < 0x100 && n >= 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++] = segwit ? 2 : 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++] = pk_script_size; /* txout-script length */
memcpy(cbtx+cbtx_size, pk_script, pk_script_size);
cbtx_size += pk_script_size;
if (segwit) {
unsigned char (*wtree)[32] = calloc(tx_count + 2, 32);
memset(cbtx+cbtx_size, 0, 8); /* value */
cbtx_size += 8;
cbtx[cbtx_size++] = 38; /* txout-script length */
cbtx[cbtx_size++] = 0x6a; /* txout-script */
cbtx[cbtx_size++] = 0x24;
cbtx[cbtx_size++] = 0xaa;
cbtx[cbtx_size++] = 0x21;
cbtx[cbtx_size++] = 0xa9;
cbtx[cbtx_size++] = 0xed;
for (i = 0; i < tx_count; i++) {
const json_t *tx = json_array_get(txa, i);
const json_t *hash = json_object_get(tx, "hash");
if (!hash || !hex2bin(wtree[1+i], json_string_value(hash), 32)) {
applog(LOG_ERR, "JSON invalid transaction hash");
free(wtree);
goto out;
}
memrev(wtree[1+i], 32);
}
n = tx_count + 1;
while (n > 1) {
if (n % 2)
memcpy(wtree[n], wtree[n-1], 32);
n = (n + 1) / 2;
for (i = 0; i < n; i++)
sha256d(wtree[i], wtree[2*i], 64);
}
memset(wtree[1], 0, 32); /* witness reserved value = 0 */
sha256d(cbtx+cbtx_size, wtree[0], 64);
cbtx_size += 32;
free(wtree);
}
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 = 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 ? 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 = 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 = malloc(32 * ((1 + tx_count + 1) & ~1));
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 ? strlen(tx_hex) / 2 : 0;
if (segwit) {
const char *txid = json_string_value(json_object_get(tmp, "txid"));
if (!txid || !hex2bin(merkle_tree[1 + i], txid, 32)) {
applog(LOG_ERR, "JSON invalid transaction txid");
goto out;
}
memrev(merkle_tree[1 + i], 32);
} else {
unsigned char *tx = 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);
free(tx);
}
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);
tmp = json_object_get(val, "workid");
if (tmp) {
if (!json_is_string(tmp)) {
applog(LOG_ERR, "JSON invalid workid");
goto out;
}
work->workid = strdup(json_string_value(tmp));
}
/* Long polling */
tmp = json_object_get(val, "longpollid");
if (want_longpoll && json_is_string(tmp)) {
free(lp_id);
lp_id = strdup(json_string_value(tmp));
if (!have_longpoll) {
char *lp_uri;
tmp = json_object_get(val, "longpolluri");
lp_uri = strdup(json_is_string(tmp) ? json_string_value(tmp) : rpc_url);
have_longpoll = true;
tq_push(thr_info[longpoll_thr_id].q, lp_uri);
}
}
rc = true;
out:
free(cbtx);
free(merkle_tree);
return rc;
}
/*
* PoA block has the following info
* version
* previouspoablockhash
* poamerkleroot
* coinbasetxn
* transactions
* coinbasevalue
* noncerange
* curtime
* bits
* height
* posblocksaudited {
* {
"data": "3c8808918e261978f631dd810b14ed8881dfca595115d9a0d1d09b07cdb0656a"
},...
* }
*
* work->data format: unit in uint32_t
* version: 1
* time: 1
* bits: 1
* nonce: 1
* hashMerkleRoot: 8
* hashPoAInterated: 8 ==> hash of hashPrevPoABlock and hashPoAMerkleRoot
* */
static bool gpoabt_work_decode(const json_t *val, struct work *work)
{
int i, n;
uint32_t version, curtime, bits;
uint32_t prevpoahash[8], hashPoAMerkleRoot[8], integratedHash[8];
uint32_t target[8];
int cbtx_size;
unsigned char *cbtx = NULL;
int tx_count, tx_size, pos_count, pos_size;
unsigned char txc_vi[9];
unsigned char(*merkle_tree)[32] = NULL;
bool coinbase_append = false;
bool submit_coinbase = false;
bool segwit = false;
json_t *tmp, *txa, *pos_audited;
bool rc = false;
tmp = json_object_get(val, "height");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid height");
goto out;
}
work->height = json_integer_value(tmp);
applog(LOG_INFO, "%s: Height = %d", __func__, work->height);
tmp = json_object_get(val, "version");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid version");
goto out;
}
version = json_integer_value(tmp);
work->version = version;
applog(LOG_INFO, "%s: Version = %d", __func__, work->version);
tmp = json_object_get(val, "curtime");
if (!tmp || !json_is_integer(tmp)) {
applog(LOG_ERR, "JSON invalid curtime");
goto out;
}
curtime = json_integer_value(tmp);
work->time = curtime;
if (unlikely(!jobj_binary(val, "bits", &bits, sizeof(bits)))) {
applog(LOG_ERR, "JSON invalid bits");
goto out;
}
memcpy(&(work->bits), &bits, sizeof(bits));
applog(LOG_INFO, "%s: bits = %x", __func__, work->bits);
if (unlikely(!jobj_binary(val, "previouspoablockhash", prevpoahash, sizeof(prevpoahash)))) {
applog(LOG_ERR, "JSON invalid previouspoablockhash");
goto out;
}
for (i = 0; i < 8; i++)
work->previousPoABlockHash[7 - i] = le32dec(prevpoahash + i);
if (unlikely(!jobj_binary(val, "poamerkleroot", hashPoAMerkleRoot, sizeof(hashPoAMerkleRoot)))) {
applog(LOG_ERR, "JSON invalid poamerkleroot");
goto out;
}
for (i = 0; i < 8; i++)
work->hashPoAMerkleRoot[7 - i] = le32dec(hashPoAMerkleRoot + i);
//build integrated hash
char *integratedHashData = malloc(64);
memcpy(integratedHashData, work->previousPoABlockHash, 32);
memcpy(integratedHashData + 32, work->hashPoAMerkleRoot, 32);
sha256d(integratedHash, integratedHashData, 64);
memcpy(work->integratedHash, integratedHash, 32);
/* find count and size of posblocksaudited transactions */
pos_audited = json_object_get(val, "posblocksaudited");
if (!pos_audited || !json_is_array(pos_audited)) {
applog(LOG_ERR, "JSON invalid transactions");
goto out;
}
pos_count = json_array_size(pos_audited);
int n_pos = varint_encode(txc_vi, pos_count);
pos_size = pos_count * 40;
work->pos_data = malloc(2 * (n_pos + pos_size) + 1);
/*if (work->pos_data == NULL) {
applog(LOG_INFO, "%s: malloc pos data failed", __func__);
}*/
//applog(LOG_INFO, "%s: success work->pos_data malloc size = %d", __func__, 2 * (n_pos + pos_size) + 1);
//applog(LOG_INFO, "%s: copy txc_vi", __func__);
bin2hex(work->pos_data, txc_vi, n_pos);
//applog(LOG_INFO, "%s: strncpy", __func__);
applog(LOG_INFO, "%s: pos_count = %d", __func__, pos_count);
//char *pos_data = malloc(pos_count * 40 * 2 + 1); //the size of posinfo = 40 byte
for (i = 0; i < pos_count; i++) {
const json_t *pos = json_array_get(pos_audited, i);
const char *pos_hex = json_string_value(json_object_get(pos, "data"));
if (!pos_hex) {
applog(LOG_ERR, "JSON invalid PoS block info");
goto out;
}
strcat(work->pos_data, pos_hex);
}
/* build coinbase transaction */
//applog(LOG_INFO, "%s: build coinbase transaction", __func__);
tmp = json_object_get(val, "coinbasetxn");
if (tmp) {
const char *cbtx_hex = json_string_value(json_object_get(tmp, "data"));
//applog(LOG_INFO, "%s: Found coinbasetxn, data = %s", __func__, cbtx_hex);
cbtx_size = cbtx_hex ? strlen(cbtx_hex) / 2 : 0;
cbtx = malloc(cbtx_size + 100);
applog(LOG_INFO, "%s: Malloc cbtx, size = %d", __func__, cbtx_size + 100);
if (cbtx_size < 60 || !hex2bin(cbtx, cbtx_hex, cbtx_size)) {
applog(LOG_ERR, "JSON invalid coinbasetxn");
goto out;
}
//applog(LOG_INFO, "%s: Success build coinbase", __func__);
} //PoA block always has a coinbasetxn, the following will possible be never executed
else {
int64_t cbvalue;
if (!pk_script_size) {
goto out;
}
tmp = json_object_get(val, "coinbasevalue");
if (!tmp || !json_is_number(tmp)) {
applog(LOG_ERR, "JSON invalid coinbasevalue");
goto out;
}
cbvalue = json_is_integer(tmp) ? json_integer_value(tmp) : json_number_value(tmp);
cbtx = 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 (n < 0x100 && n >= 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++] = segwit ? 2 : 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++] = pk_script_size; /* txout-script length */
memcpy(cbtx + cbtx_size, pk_script, pk_script_size);
cbtx_size += 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 = 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 ? 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);
work->txs = malloc(2 * (n + cbtx_size) + 1);
bin2hex(work->txs, txc_vi, n);
bin2hex(work->txs + 2 * n, cbtx, cbtx_size);
/* generate merkle root */
merkle_tree = malloc(32 * ((1 + 1) & ~1));
sha256d(merkle_tree[0], cbtx, cbtx_size);
//PoA block has only one transaction: the coinbase transaction
/*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 ? strlen(tx_hex) / 2 : 0;
if (segwit) {
const char *txid = json_string_value(json_object_get(tmp, "txid"));
if (!txid || !hex2bin(merkle_tree[1 + i], txid, 32)) {
applog(LOG_ERR, "JSON invalid transaction txid");
goto out;
}
memrev(merkle_tree[1 + i], 32);
}
else {
unsigned char *tx = 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);
free(tx);
}
if (!submit_coinbase)
strcat(work->txs, tx_hex);
}*/
/* assemble block header */
work->data[0] = swab32(version);
for (i = 0; i < 8; i++)
work->data[1 + i] = be32dec(integratedHash + 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);
char targetHex[2*32 + 1];
bin2hex(targetHex, target, 32);
tmp = json_object_get(val, "workid");
if (tmp) {
if (!json_is_string(tmp)) {
applog(LOG_ERR, "JSON invalid workid");
goto out;
}
work->workid = strdup(json_string_value(tmp));
}
//Temporarily disable polling
/* Long polling */
/*tmp = json_object_get(val, "longpollid");
if (want_longpoll && json_is_string(tmp)) {
free(lp_id);
lp_id = strdup(json_string_value(tmp));
if (!have_longpoll) {
char *lp_uri;
tmp = json_object_get(val, "longpolluri");
lp_uri = strdup(json_is_string(tmp) ? json_string_value(tmp) : rpc_url);
have_longpoll = true;
tq_push(thr_info[longpoll_thr_id].q, lp_uri);
}
}*/
rc = true;
out:
free(cbtx);
free(merkle_tree);