-
Notifications
You must be signed in to change notification settings - Fork 548
/
cpu-miner.c
4044 lines (3652 loc) · 119 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-2016 Tanguy Pruvot
* Copyright 2016-2023 Jay D Dee
*
* 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.
*/
/*
* Change log
*
* 2016-01-14: v 1.9-RC inititial limited release combining
* cpuminer-multi 1.2-prev, darkcoin-cpu-miner 1.3,
* and cp3u 2.3.2 plus some performance optimizations.
*
* 2016-02-04: v3.1 algo_gate implemntation
*/
#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 <memory.h>
#include <curl/curl.h>
#include <jansson.h>
//#include <openssl/sha.h>
//#include <mm_malloc.h>
#include "sysinfos.c"
#include "algo/sha/sha256d.h"
#ifdef WIN32
#include <winsock2.h>
#include <windows.h>
#endif
#ifdef _MSC_VER
#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
// GCC 9 warning sysctl.h is deprecated
#if ( __GNUC__ < 9 )
#include <sys/sysctl.h>
#endif
#endif // HAVE_SYS_SYSCTL_H
#endif // _MSC_VER ELSE
#ifndef WIN32
#include <sys/resource.h>
#endif
#include "miner.h"
#include "algo-gate-api.h"
#include "algo/sha/sha256-hash.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
algo_gate_t algo_gate;
bool opt_debug = false;
bool opt_debug_diff = false;
bool opt_protocol = false;
bool opt_benchmark = false;
bool opt_redirect = true;
bool opt_extranonce = true;
bool want_longpoll = false;
bool have_longpoll = false;
bool have_gbt = true;
bool allow_getwork = true;
bool want_stratum = true; // pretty useless
bool have_stratum = false;
bool stratum_down = true;
bool allow_mininginfo = true;
bool use_syslog = false;
bool use_colors = true;
static bool opt_background = false;
bool opt_quiet = false;
bool opt_randomize = false;
static int opt_retries = -1;
static int opt_fail_pause = 10;
static int opt_time_limit = 0;
static unsigned int time_limit_stop = 0;
int opt_timeout = 300;
static int opt_scantime = 0;
const int min_scantime = 1;
//static const bool opt_time = true;
enum algos opt_algo = ALGO_NULL;
char* opt_param_key = NULL;
int opt_param_n = 0;
int opt_param_r = 0;
int opt_n_threads = 0;
bool opt_sapling = false;
static uint64_t opt_affinity = 0xFFFFFFFFFFFFFFFFULL; // default, use all cores
int opt_priority = 0; // deprecated
int num_cpus = 1;
int num_cpugroups = 1; // For Windows
char *rpc_url = NULL;
char *rpc_userpass = NULL;
char *rpc_user, *rpc_pass;
char *short_url = NULL;
char *coinbase_address;
char *opt_data_file = NULL;
bool opt_verify = false;
static bool opt_stratum_keepalive = false;
static struct timeval stratum_keepalive_timer;
// Stratum typically times out in 5 minutes or 300 seconds
#define stratum_keepalive_timeout 150 // 2.5 minutes
static struct timeval stratum_reset_time;
// pk_buffer_size is used as a version selector by b58 code, therefore
// it must be set correctly to work.
const int pk_buffer_size_max = 26;
int pk_buffer_size = 25;
static unsigned char pk_script[ 26 ] = { 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;
double opt_diff_factor = 1.0;
double opt_target_factor = 1.0;
uint32_t zr5_pok = 0;
bool opt_stratum_stats = false;
bool opt_hash_meter = false;
uint32_t submitted_share_count= 0;
uint32_t accepted_share_count = 0;
uint32_t rejected_share_count = 0;
uint32_t stale_share_count = 0;
uint32_t solved_block_count = 0;
uint32_t stratum_errors = 0;
double *thr_hashrates;
double global_hashrate = 0.;
double total_hashes = 0.;
struct timeval total_hashes_time = {0,0};
double stratum_diff = 0.;
double net_diff = 0.;
double net_hashrate = 0.;
uint64_t net_blocks = 0;
uint32_t opt_work_size = 0;
bool opt_bell = false;
// conditional mining
bool *conditional_state = NULL;
//bool conditional_state[MAX_CPUS] = { 0 };
double opt_max_temp = 0.0;
double opt_max_diff = 0.0;
double opt_max_rate = 0.0;
// API
static bool opt_api_enabled = false;
char *opt_api_allow = NULL;
int opt_api_listen = 0;
int opt_api_remote = 0;
char *default_api_allow = "127.0.0.1";
int default_api_listen = 4048;
pthread_mutex_t applog_lock;
pthread_mutex_t stats_lock;
static struct timeval session_start;
static struct timeval five_min_start;
static uint64_t session_first_block = 0;
static uint64_t submit_sum = 0;
static uint64_t accept_sum = 0;
static uint64_t stale_sum = 0;
static uint64_t reject_sum = 0;
static uint64_t solved_sum = 0;
static double norm_diff_sum = 0.;
static uint32_t last_block_height = 0;
static double highest_share = 0; // highest accepted share diff
static double lowest_share = 9e99; // lowest accepted share diff
static double last_targetdiff = 0.;
#if !(defined(__WINDOWS__) || defined(_WIN64) || defined(_WIN32))
static uint32_t hi_temp = 0;
static uint32_t prev_temp = 0;
#endif
static char const short_options[] =
#ifdef HAVE_SYSLOG_H
"S"
#endif
"a:b:Bc:CDf:hK:m:n:N:p:Px:qr:R:s:t:T:o:u:O:V";
static struct work g_work __attribute__ ((aligned (64))) = {{ 0 }};
time_t g_work_time = 0;
pthread_rwlock_t g_work_lock;
static bool submit_old = false;
char* lp_id;
static void workio_cmd_free(struct workio_cmd *wc);
static int *thread_affinity_map;
// display affinity mask graphically
static void format_affinity_mask( char *mask_str, uint64_t mask )
{
#if defined(WINDOWS_CPU_GROUPS_ENABLED)
int n = num_cpus / num_cpugroups;
#else
int n = num_cpus < 64 ? num_cpus : 64;
#endif
int i;
for ( i = 0; i < n; i++ )
{
if ( mask & 1 ) mask_str[i] = '!';
else mask_str[i] = '.';
mask >>= 1;
}
memset( &mask_str[i], 0, 64 - i );
}
#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( struct thr_info *thr )
{
int thread = thr->id;
cpu_set_t set;
CPU_ZERO( &set );
CPU_SET( thread_affinity_map[ thread ], &set );
if ( opt_debug )
applog( LOG_INFO, "Binding thread %d to cpu %d",
thread, thread_affinity_map[ thread ] );
pthread_setaffinity_np( thr->pth, sizeof(set), &set );
}
#elif defined(WIN32) /* Windows */
static inline void drop_policy(void) { }
// Windows CPU groups to manage more than 64 CPUs.
// mask arg is ignored
static void affine_to_cpu( struct thr_info *thr )
{
int thread = thr->id;
unsigned long last_error;
bool ok;
#if defined(WINDOWS_CPU_GROUPS_ENABLED)
unsigned long group_size = GetActiveProcessorCount( 0 );
unsigned long group = thread / group_size;
unsigned long cpu = thread_affinity_map[ thread % group_size ];
GROUP_AFFINITY affinity;
affinity.Group = group;
affinity.Mask = 1ULL << cpu;
if ( opt_debug )
applog( LOG_INFO, "Binding thread %d to cpu %d in cpu group %d",
thread, cpu, group );
ok = SetThreadGroupAffinity( GetCurrentThread(), &affinity, NULL );
#else
unsigned long cpu = thread_affinity_map[ thread ];
uint64_t mask = 1ULL << cpu;
if ( opt_debug )
applog( LOG_INFO, "Binding thread %d to cpu %d", thread, cpu );
ok = SetThreadAffinityMask( GetCurrentThread(), mask );
#endif
if ( !ok )
{
last_error = GetLastError();
if ( !thread )
applog( LOG_WARNING, "Set affinity returned error 0x%x for thread %d",
last_error, thread );
}
}
#else
static inline void drop_policy(void) { }
static void affine_to_cpu( struct thr_info *thr ) { }
#endif
// not very useful, just index the arrray directly.
// but declaring this function in miner.h eliminates
// an annoying compiler warning for not using a static.
const char* algo_name( enum algos a ) {return algo_names[a];}
void get_currentalgo(char* buf, int sz)
{
snprintf(buf, sz, "%s", algo_names[opt_algo]);
}
void proper_exit(int reason)
{
if (opt_debug) applog(LOG_INFO,"Program exit");
#ifdef WIN32
if (opt_background) {
HWND hcon = GetConsoleWindow();
if (hcon) {
// unhide parent command line windows
ShowWindow(hcon, SW_SHOWMINNOACTIVE);
}
}
#endif
exit(reason);
}
uint32_t* get_stratum_job_ntime()
{
return (uint32_t*)stratum.job.ntime;
}
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);
}
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);
}
}
int std_get_work_data_size() { return STD_WORK_DATA_SIZE; }
// Default
bool std_le_work_decode( struct work *work )
{
int i;
const int adata_sz = algo_gate.get_work_data_size() / 4;
// const int atarget_sz = ARRAY_SIZE(work->target);
for ( i = 0; i < adata_sz; i++ )
work->data[i] = le32dec( work->data + i );
for ( i = 0; i < 8; i++ )
work->target[i] = le32dec( work->target + i );
return true;
}
bool std_be_work_decode( struct work *work )
{
int i;
const int adata_sz = algo_gate.get_work_data_size() / 4;
// const int atarget_sz = ARRAY_SIZE(work->target);
for ( i = 0; i < adata_sz; i++ )
work->data[i] = be32dec( work->data + i );
for ( i = 0; i < 8; i++ )
work->target[i] = le32dec( work->target + i );
return true;
}
static bool work_decode( const json_t *val, struct work *work )
{
const int data_size = algo_gate.get_work_data_size();
const int target_size = sizeof(work->target);
if (unlikely( !jobj_binary(val, "data", work->data, data_size) ))
{
applog(LOG_ERR, "JSON invalid data");
return false;
}
if (unlikely( !jobj_binary(val, "target", work->target, target_size) ))
{
applog(LOG_ERR, "JSON invalid target");
return false;
}
if ( unlikely( !algo_gate.work_decode( work ) ) )
return false;
// many of these aren't used solo.
net_diff =
work->targetdiff =
stratum_diff =
last_targetdiff = hash_to_diff( work->target );
work->sharediff = 0;
algo_gate.decode_extra_data( work, &net_blocks );
return true;
}
// Only used for net_hashrate with GBT/getwork, data is from previous block.
static const char *info_req =
"{\"method\": \"getmininginfo\", \"params\": [], \"id\":8}\r\n";
static bool get_mininginfo( CURL *curl, struct work *work )
{
if ( have_stratum || !allow_mininginfo )
return false;
int curl_err = 0;
json_t *val = json_rpc_call( curl, rpc_url, rpc_userpass, info_req,
&curl_err, 0 );
if ( !val && curl_err == -1 )
{
allow_mininginfo = false;
applog( LOG_NOTICE, "\"getmininginfo\" not supported, some stats not available" );
return false;
}
json_t *res = json_object_get( val, "result" );
// "blocks": 491493 (= current work height - 1)
// "difficulty": 0.99607860999999998
// "networkhashps": 56475980
if ( res )
{
double difficulty = 0.;
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 ) )
difficulty = json_real_value( key );
}
key = json_object_get( res, "networkhashps" );
if ( key )
{
if ( json_is_integer( key ) )
net_hashrate = (double) json_integer_value( key );
else if ( json_is_real( key ) )
net_hashrate = (double) json_real_value( key );
}
key = json_object_get( res, "blocks" );
if ( key && json_is_integer( key ) )
net_blocks = json_integer_value( key );
if ( opt_debug )
applog( LOG_INFO,"getmininginfo: difficulty %.5g, networkhashps %.5g, blocks %d", difficulty, net_hashrate, net_blocks );
if ( !work->height )
{
// complete missing data from getwork
if ( opt_debug )
applog( LOG_DEBUG, "work height set by getmininginfo" );
work->height = (uint32_t) net_blocks + 1;
if ( work->height > g_work.height )
restart_threads();
} // res
}
json_decref( val );
return true;
}
// hodl needs 4 but leave it at 3 until gbt better understood
//#define BLOCK_VERSION_CURRENT 3
#define BLOCK_VERSION_CURRENT 4
static bool gbt_work_decode( const json_t *val, struct work *work )
{
uint32_t prevhash[8] __attribute__ ((aligned (32)));
uint32_t target[8] __attribute__ ((aligned (32)));
unsigned char final_sapling_hash[32] __attribute__ ((aligned (32)));
uint32_t version, curtime, bits;
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;
int i, n;
bool segwit = 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;
if ( opt_debug )
applog( LOG_INFO, "GBT: SegWit is enabled" );
}
}
}
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 );
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 );
// yescryptr8g uses block version 5 and sapling.
if ( opt_sapling )
work->sapling = true;
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;
}
if ( work->sapling )
{
if ( unlikely( !jobj_binary( val, "finalsaplingroothash",
final_sapling_hash, sizeof(final_sapling_hash) ) ) )
{
applog( LOG_ERR, "JSON invalid finalsaplingroothash" );
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++] = 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++ ] = (uint8_t) pk_script_size; /* txout-script length */
memcpy( cbtx+cbtx_size, pk_script, pk_script_size );
cbtx_size += (int) 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 = (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;
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 = (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 );
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 );
}
work->tx_count = tx_count;
/* assemble block header */
algo_gate.build_block_header( work, swab32( version ),
(uint32_t*) prevhash, (uint32_t*) merkle_tree,
swab32( curtime ), le32dec( &bits ),
final_sapling_hash );
if ( unlikely( !jobj_binary( val, "target", target, sizeof(target) ) ) )
{
applog( LOG_ERR, "JSON invalid target" );
goto out;
}
// reverse the bytes in target
casti_v128( work->target, 0 ) = v128_bswap128( casti_v128( target, 1 ) );
casti_v128( work->target, 1 ) = v128_bswap128( casti_v128( target, 0 ) );
net_diff = work->targetdiff = hash_to_diff( work->target );
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 ) );
}
rc = true;
out:
/* 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 = json_is_string( tmp ) ? strdup( json_string_value( tmp ) )
: rpc_url;
have_longpoll = true;
tq_push(thr_info[longpoll_thr_id].q, lp_uri);
}
}
free( merkle_tree );
free( cbtx );
return rc;
}
// returns the unit prefix and the hashrate appropriately scaled.
void scale_hash_for_display ( double* hashrate, char* prefix )
{
if ( *hashrate < 1e4 ) *prefix = 0;
else if ( *hashrate < 1e7 ) { *prefix = 'k'; *hashrate /= 1e3; }
else if ( *hashrate < 1e10 ) { *prefix = 'M'; *hashrate /= 1e6; }
else if ( *hashrate < 1e13 ) { *prefix = 'G'; *hashrate /= 1e9; }
else if ( *hashrate < 1e16 ) { *prefix = 'T'; *hashrate /= 1e12; }
else if ( *hashrate < 1e19 ) { *prefix = 'P'; *hashrate /= 1e15; }
else if ( *hashrate < 1e22 ) { *prefix = 'E'; *hashrate /= 1e18; }
else if ( *hashrate < 1e25 ) { *prefix = 'Z'; *hashrate /= 1e21; }
else { *prefix = 'Y'; *hashrate /= 1e24; }
}
static inline void sprintf_et( char *str, long unsigned int seconds )
{
long unsigned int min = seconds / 60;
long unsigned int sec = seconds % 60;
long unsigned int hrs = min / 60;
if ( unlikely( hrs ) )
{
long unsigned int days = hrs / 24;
long unsigned int years = days / 365;
if ( years ) // 0y000d
sprintf( str, "%luy%lud", years, years % 365 );
else if ( days ) // 0d00h
sprintf( str, "%lud%02luh", days, hrs % 24 );
else // 0h00m
sprintf( str, "%luh%02lum", hrs, min % 60 );
}
else // 0m00s
sprintf( str, "%lum%02lus", min, sec );
}
const long double exp32 = EXP32; // 2**32
const long double exp48 = EXP32 * EXP16; // 2**48
const long double exp64 = EXP32 * EXP32; // 2**64
const long double exp96 = EXP32 * EXP32 * EXP32; // 2**96
const long double exp128 = EXP32 * EXP32 * EXP32 * EXP32; // 2**128
const long double exp160 = EXP32 * EXP32 * EXP32 * EXP32 * EXP16; // 2**160
struct share_stats_t
{
int share_count;
struct timeval submit_time;
double net_diff;
double share_diff;
double stratum_diff;
double target_diff;
uint32_t height;
char job_id[32];
};
#define s_stats_size 8
static struct share_stats_t share_stats[ s_stats_size ] = {{0}};
static int s_get_ptr = 0, s_put_ptr = 0;
static struct timeval last_submit_time = {0};
static inline int stats_ptr_incr( int p )
{
return ++p % s_stats_size;
}
void report_summary_log( bool force )
{
struct timeval now, et, uptime, start_time;
if ( rejected_share_count > 10 )
{
if ( rejected_share_count > ( submitted_share_count * .5 ) )
{
applog(LOG_ERR,"Excessive rejected share rate, exiting...");
exit(1);
}
else if ( rejected_share_count > ( submitted_share_count * .1 ) )