forked from mbevand/silentarmy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1422 lines (1365 loc) · 42.6 KB
/
main.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
#define _GNU_SOURCE 1/* memrchr */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <errno.h>
#include <CL/cl.h>
#include "blake.h"
#include "_kernel.h"
#include "sha256.h"
typedef uint8_t uchar;
typedef uint32_t uint;
#include "param.h"
#define MIN(A, B) (((A) < (B)) ? (A) : (B))
#define MAX(A, B) (((A) > (B)) ? (A) : (B))
int verbose = 0;
uint32_t show_encoded = 0;
uint64_t nr_nonces = 1;
uint32_t do_list_devices = 0;
uint32_t gpu_to_use = 0;
uint32_t mining = 0;
typedef struct debug_s
{
uint32_t dropped_coll;
uint32_t dropped_stor;
} debug_t;
void debug(const char *fmt, ...)
{
va_list ap;
if (!verbose)
return ;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
void warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
void fatal(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(1);
}
uint64_t parse_num(char *str)
{
char *endptr;
uint64_t n;
n = strtoul(str, &endptr, 0);
if (endptr == str || *endptr)
fatal("'%s' is not a valid number\n", str);
return n;
}
uint64_t now(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (uint64_t)tv.tv_sec * 1000 * 1000 + tv.tv_usec;
}
void show_time(uint64_t t0)
{
uint64_t t1;
t1 = now();
fprintf(stderr, "Elapsed time: %.1f msec\n", (t1 - t0) / 1e3);
}
void set_blocking_mode(int fd, int block)
{
int f;
if (-1 == (f = fcntl(fd, F_GETFL)))
fatal("fcntl F_GETFL: %s\n", strerror(errno));
if (-1 == fcntl(fd, F_SETFL, block ? (f & ~O_NONBLOCK) : (f | O_NONBLOCK)))
fatal("fcntl F_SETFL: %s\n", strerror(errno));
}
void randomize(void *p, ssize_t l)
{
const char *fname = "/dev/urandom";
int fd;
ssize_t ret;
if (-1 == (fd = open(fname, O_RDONLY)))
fatal("open %s: %s\n", fname, strerror(errno));
if (-1 == (ret = read(fd, p, l)))
fatal("read %s: %s\n", fname, strerror(errno));
if (ret != l)
fatal("%s: short read %d bytes out of %d\n", fname, ret, l);
if (-1 == close(fd))
fatal("close %s: %s\n", fname, strerror(errno));
}
cl_mem check_clCreateBuffer(cl_context ctx, cl_mem_flags flags, size_t size,
void *host_ptr)
{
cl_int status;
cl_mem ret;
ret = clCreateBuffer(ctx, flags, size, host_ptr, &status);
if (status != CL_SUCCESS || !ret)
fatal("clCreateBuffer (%d)\n", status);
return ret;
}
void check_clSetKernelArg(cl_kernel k, cl_uint a_pos, cl_mem *a)
{
cl_int status;
status = clSetKernelArg(k, a_pos, sizeof (*a), a);
if (status != CL_SUCCESS)
fatal("clSetKernelArg (%d)\n", status);
}
void check_clEnqueueNDRangeKernel(cl_command_queue queue, cl_kernel k, cl_uint
work_dim, const size_t *global_work_offset, const size_t
*global_work_size, const size_t *local_work_size, cl_uint
num_events_in_wait_list, const cl_event *event_wait_list, cl_event
*event)
{
cl_uint status;
status = clEnqueueNDRangeKernel(queue, k, work_dim, global_work_offset,
global_work_size, local_work_size, num_events_in_wait_list,
event_wait_list, event);
if (status != CL_SUCCESS)
fatal("clEnqueueNDRangeKernel (%d)\n", status);
}
void check_clEnqueueReadBuffer(cl_command_queue queue, cl_mem buffer, cl_bool
blocking_read, size_t offset, size_t size, void *ptr, cl_uint
num_events_in_wait_list, const cl_event *event_wait_list, cl_event
*event)
{
cl_int status;
status = clEnqueueReadBuffer(queue, buffer, blocking_read, offset,
size, ptr, num_events_in_wait_list, event_wait_list, event);
if (status != CL_SUCCESS)
fatal("clEnqueueReadBuffer (%d)\n", status);
}
void hexdump(uint8_t *a, uint32_t a_len)
{
for (uint32_t i = 0; i < a_len; i++)
fprintf(stderr, "%02x", a[i]);
}
char *s_hexdump(const void *_a, uint32_t a_len)
{
const uint8_t *a = _a;
static char buf[4096];
uint32_t i;
for (i = 0; i < a_len && i + 2 < sizeof (buf); i++)
sprintf(buf + i * 2, "%02x", a[i]);
buf[i * 2] = 0;
return buf;
}
uint8_t hex2val(const char *base, size_t off)
{
const char c = base[off];
if (c >= '0' && c <= '9') return c - '0';
else if (c >= 'a' && c <= 'f') return 10 + c - 'a';
else if (c >= 'A' && c <= 'F') return 10 + c - 'A';
fatal("Invalid hex char at offset %zd: ...%c...\n", off, c);
return 0;
}
unsigned nr_compute_units(const char *gpu)
{
if (!strcmp(gpu, "rx480")) return 36;
fprintf(stderr, "Unknown GPU: %s\n", gpu);
return 0;
}
void load_file(const char *fname, char **dat, size_t *dat_len)
{
struct stat st;
int fd;
ssize_t ret;
if (-1 == (fd = open(fname, O_RDONLY)))
fatal("%s: %s\n", fname, strerror(errno));
if (fstat(fd, &st))
fatal("fstat: %s: %s\n", fname, strerror(errno));
*dat_len = st.st_size;
if (!(*dat = (char *)malloc(*dat_len + 1)))
fatal("malloc: %s\n", strerror(errno));
ret = read(fd, *dat, *dat_len);
if (ret < 0)
fatal("read: %s: %s\n", fname, strerror(errno));
if ((size_t)ret != *dat_len)
fatal("%s: partial read\n", fname);
if (close(fd))
fatal("close: %s: %s\n", fname, strerror(errno));
(*dat)[*dat_len] = 0;
}
void get_program_build_log(cl_program program, cl_device_id device)
{
cl_int status;
char val[2*1024*1024];
size_t ret = 0;
status = clGetProgramBuildInfo(program, device,
CL_PROGRAM_BUILD_LOG,
sizeof (val), // size_t param_value_size
&val, // void *param_value
&ret); // size_t *param_value_size_ret
if (status != CL_SUCCESS)
fatal("clGetProgramBuildInfo (%d)\n", status);
fprintf(stderr, "%s\n", val);
}
void dump(const char *fname, void *data, size_t len)
{
int fd;
ssize_t ret;
if (-1 == (fd = open(fname, O_WRONLY | O_CREAT | O_TRUNC, 0666)))
fatal("%s: %s\n", fname, strerror(errno));
ret = write(fd, data, len);
if (ret == -1)
fatal("write: %s: %s\n", fname, strerror(errno));
if ((size_t)ret != len)
fatal("%s: partial write\n", fname);
if (-1 == close(fd))
fatal("close: %s: %s\n", fname, strerror(errno));
}
void get_program_bins(cl_program program)
{
cl_int status;
size_t sizes;
unsigned char *p;
size_t ret = 0;
status = clGetProgramInfo(program, CL_PROGRAM_BINARY_SIZES,
sizeof (sizes), // size_t param_value_size
&sizes, // void *param_value
&ret); // size_t *param_value_size_ret
if (status != CL_SUCCESS)
fatal("clGetProgramInfo(sizes) (%d)\n", status);
if (ret != sizeof (sizes))
fatal("clGetProgramInfo(sizes) did not fill sizes (%d)\n", status);
debug("Program binary size is %zd bytes\n", sizes);
p = (unsigned char *)malloc(sizes);
status = clGetProgramInfo(program, CL_PROGRAM_BINARIES,
sizeof (p), // size_t param_value_size
&p, // void *param_value
&ret); // size_t *param_value_size_ret
if (status != CL_SUCCESS)
fatal("clGetProgramInfo (%d)\n", status);
dump("dump.co", p, sizes);
debug("program: %02x%02x%02x%02x...\n", p[0], p[1], p[2], p[3]);
}
void print_platform_info(cl_platform_id plat)
{
char name[1024];
size_t len = 0;
int status;
status = clGetPlatformInfo(plat, CL_PLATFORM_NAME, sizeof (name), &name,
&len);
if (status != CL_SUCCESS)
fatal("clGetPlatformInfo (%d)\n", status);
printf("Devices on platform \"%s\":\n", name);
fflush(stdout);
}
void print_device_info(unsigned i, cl_device_id d)
{
char name[1024];
size_t len = 0;
int status;
status = clGetDeviceInfo(d, CL_DEVICE_NAME, sizeof (name), &name, &len);
if (status != CL_SUCCESS)
fatal("clGetDeviceInfo (%d)\n", status);
printf(" ID %d: %s\n", i, name);
fflush(stdout);
}
#ifdef ENABLE_DEBUG
uint32_t has_i(uint32_t round, uint8_t *ht, uint32_t row, uint32_t i,
uint32_t mask, uint32_t *res)
{
uint32_t slot;
uint8_t *p = (uint8_t *)(ht + row * NR_SLOTS * SLOT_LEN);
uint32_t cnt = *(uint32_t *)p;
cnt = MIN(cnt, NR_SLOTS);
for (slot = 0; slot < cnt; slot++, p += SLOT_LEN)
{
if ((*(uint32_t *)(p + xi_offset_for_round(round) - 4) & mask) ==
(i & mask))
{
if (res)
*res = slot;
return 1;
}
}
return 0;
}
uint32_t has_xi(uint32_t round, uint8_t *ht, uint32_t row, uint32_t xi,
uint32_t *res)
{
uint32_t slot;
uint8_t *p = (uint8_t *)(ht + row * NR_SLOTS * SLOT_LEN);
uint32_t cnt = *(uint32_t *)p;
cnt = MIN(cnt, NR_SLOTS);
for (slot = 0; slot < cnt; slot++, p += SLOT_LEN)
{
if ((*(uint32_t *)(p + xi_offset_for_round(round))) == (xi))
{
if (res)
*res = slot;
return 1;
}
}
return 0;
}
void examine_ht(unsigned round, cl_command_queue queue, cl_mem buf_ht)
{
uint8_t *ht;
uint8_t *p;
if (verbose < 3)
return ;
ht = (uint8_t *)malloc(HT_SIZE);
if (!ht)
fatal("malloc: %s\n", strerror(errno));
check_clEnqueueReadBuffer(queue, buf_ht,
CL_TRUE, // cl_bool blocking_read
0, // size_t offset
HT_SIZE, // size_t size
ht, // void *ptr
0, // cl_uint num_events_in_wait_list
NULL, // cl_event *event_wait_list
NULL); // cl_event *event
for (unsigned row = 0; row < NR_ROWS; row++)
{
char show = 0;
uint32_t star = 0;
if (round == 0)
{
// i = 0x35c and 0x12d31f collide on first 20 bits
show |= has_i(round, ht, row, 0x35c, 0xffffffffUL, &star);
show |= has_i(round, ht, row, 0x12d31f, 0xffffffffUL, &star);
}
if (round == 1)
{
show |= has_xi(round, ht, row, 0xf0937683, &star);
}
if (round == 2)
{
show |= has_xi(round, ht, row, 0x3519d2e0, &star);
}
if (round == 3)
{
show |= has_xi(round, ht, row, 0xd6950b66, &star);
}
if (round == 4)
{
show |= has_xi(round, ht, row, 0xa92db6ab, &star);
}
if (round == 5)
{
show |= has_xi(round, ht, row, 0x2daaa343, &star);
}
if (round == 6)
{
show |= has_xi(round, ht, row, 0x53b9dd5d, &star);
}
if (round == 7)
{
show |= has_xi(round, ht, row, 0xb9d374fe, &star);
}
if (round == 8)
{
show |= has_xi(round, ht, row, 0x005ae381, &star);
}
// show |= (row < 256);
if (show)
{
debug("row %#x:\n", row);
uint32_t cnt = *(uint32_t *)(ht + row * NR_SLOTS * SLOT_LEN);
cnt = MIN(cnt, NR_SLOTS);
for (unsigned slot = 0; slot < cnt; slot++)
if (slot < NR_SLOTS)
{
p = ht + row * NR_SLOTS * SLOT_LEN + slot * SLOT_LEN;
debug("%c%02x ", (star == slot) ? '*' : ' ', slot);
for (unsigned i = 0; i < 4; i++, p++)
!slot ? debug("%02x", *p) : debug("__");
uint64_t val[3] = {0,};
for (unsigned i = 0; i < 28; i++, p++)
{
if (i == round / 2 * 4 + 4)
{
val[0] = *(uint64_t *)(p + 0);
val[1] = *(uint64_t *)(p + 8);
val[2] = *(uint64_t *)(p + 16);
debug(" | ");
}
else if (!(i % 4))
debug(" ");
debug("%02x", *p);
}
val[0] = (val[0] >> 4) | (val[1] << (64 - 4));
val[1] = (val[1] >> 4) | (val[2] << (64 - 4));
val[2] = (val[2] >> 4);
debug("\n");
}
}
}
free(ht);
}
#else
void examine_ht(unsigned round, cl_command_queue queue, cl_mem buf_ht)
{
(void)round;
(void)queue;
(void)buf_ht;
}
#endif
void examine_dbg(cl_command_queue queue, cl_mem buf_dbg, size_t dbg_size)
{
debug_t *dbg;
size_t dropped_coll_total, dropped_stor_total;
if (verbose < 2)
return ;
dbg = (debug_t *)malloc(dbg_size);
if (!dbg)
fatal("malloc: %s\n", strerror(errno));
check_clEnqueueReadBuffer(queue, buf_dbg,
CL_TRUE, // cl_bool blocking_read
0, // size_t offset
dbg_size, // size_t size
dbg, // void *ptr
0, // cl_uint num_events_in_wait_list
NULL, // cl_event *event_wait_list
NULL); // cl_event *event
dropped_coll_total = dropped_stor_total = 0;
for (unsigned tid = 0; tid < dbg_size / sizeof (*dbg); tid++)
{
dropped_coll_total += dbg[tid].dropped_coll;
dropped_stor_total += dbg[tid].dropped_stor;
if (0 && (dbg[tid].dropped_coll || dbg[tid].dropped_stor))
debug("thread %6d: dropped_coll %zd dropped_stor %zd\n", tid,
dbg[tid].dropped_coll, dbg[tid].dropped_stor);
}
debug("Dropped: %zd (coll) %zd (stor)\n",
dropped_coll_total, dropped_stor_total);
free(dbg);
}
size_t select_work_size_blake(void)
{
size_t work_size =
64 * /* thread per wavefront */
BLAKE_WPS * /* wavefront per simd */
4 * /* simd per compute unit */
nr_compute_units("rx480");
// Make the work group size a multiple of the nr of wavefronts, while
// dividing the number of inputs. This results in the worksize being a
// power of 2.
while (NR_INPUTS % work_size)
work_size += 64;
//debug("Blake: work size %zd\n", work_size);
return work_size;
}
void init_ht(cl_command_queue queue, cl_kernel k_init_ht, cl_mem buf_ht,
cl_mem rowCounters)
{
size_t global_ws = NR_ROWS / ROWS_PER_UINT;
size_t local_ws = 256;
cl_int status;
#if 0
uint32_t pat = -1;
status = clEnqueueFillBuffer(queue, buf_ht, &pat, sizeof (pat), 0,
NR_ROWS * NR_SLOTS * SLOT_LEN,
0, // cl_uint num_events_in_wait_list
NULL, // cl_event *event_wait_list
NULL); // cl_event *event
if (status != CL_SUCCESS)
fatal("clEnqueueFillBuffer (%d)\n", status);
#endif
status = clSetKernelArg(k_init_ht, 0, sizeof (buf_ht), &buf_ht);
clSetKernelArg(k_init_ht, 1, sizeof (rowCounters), &rowCounters);
if (status != CL_SUCCESS)
fatal("clSetKernelArg (%d)\n", status);
check_clEnqueueNDRangeKernel(queue, k_init_ht,
1, // cl_uint work_dim
NULL, // size_t *global_work_offset
&global_ws, // size_t *global_work_size
&local_ws, // size_t *local_work_size
0, // cl_uint num_events_in_wait_list
NULL, // cl_event *event_wait_list
NULL); // cl_event *event
}
/*
** Write ZCASH_SOL_LEN bytes representing the encoded solution as per the
** Zcash protocol specs (512 x 21-bit inputs).
**
** out ZCASH_SOL_LEN-byte buffer where the solution will be stored
** inputs array of 32-bit inputs
** n number of elements in array
*/
void store_encoded_sol(uint8_t *out, uint32_t *inputs, uint32_t n)
{
uint32_t byte_pos = 0;
int32_t bits_left = PREFIX + 1;
uint8_t x = 0;
uint8_t x_bits_used = 0;
while (byte_pos < n)
{
if (bits_left >= 8 - x_bits_used)
{
x |= inputs[byte_pos] >> (bits_left - 8 + x_bits_used);
bits_left -= 8 - x_bits_used;
x_bits_used = 8;
}
else if (bits_left > 0)
{
uint32_t mask = ~(-1 << (8 - x_bits_used));
mask = ((~mask) >> bits_left) & mask;
x |= (inputs[byte_pos] << (8 - x_bits_used - bits_left)) & mask;
x_bits_used += bits_left;
bits_left = 0;
}
else if (bits_left <= 0)
{
assert(!bits_left);
byte_pos++;
bits_left = PREFIX + 1;
}
if (x_bits_used == 8)
{
*out++ = x;
x = x_bits_used = 0;
}
}
}
/*
** Print on stdout a hex representation of the encoded solution as per the
** zcash protocol specs (512 x 21-bit inputs).
**
** inputs array of 32-bit inputs
** n number of elements in array
*/
void print_encoded_sol(uint32_t *inputs, uint32_t n)
{
uint8_t sol[ZCASH_SOL_LEN];
uint32_t i;
store_encoded_sol(sol, inputs, n);
for (i = 0; i < sizeof (sol); i++)
printf("%02x", sol[i]);
printf("\n");
fflush(stdout);
}
void print_sol(uint32_t *values, uint64_t *nonce)
{
uint32_t show_n_sols;
show_n_sols = (1 << PARAM_K);
if (verbose < 2)
show_n_sols = MIN(10, show_n_sols);
fprintf(stderr, "Soln:");
// for brievity, only print "small" nonces
if (*nonce < (1ULL << 32))
fprintf(stderr, " 0x%" PRIx64 ":", *nonce);
for (unsigned i = 0; i < show_n_sols; i++)
fprintf(stderr, " %x", values[i]);
fprintf(stderr, "%s\n", (show_n_sols != (1 << PARAM_K) ? "..." : ""));
}
/*
** Compare two 256-bit values interpreted as little-endian 256-bit integers.
*/
int32_t cmp_target_256(void *_a, void *_b)
{
uint8_t *a = _a;
uint8_t *b = _b;
int32_t i;
for (i = SHA256_TARGET_LEN - 1; i >= 0; i--)
if (a[i] != b[i])
return (int32_t)a[i] - b[i];
return 0;
}
/*
** Verify if the solution's block hash is under the target, and if yes print
** it formatted as:
** "sol: <job_id> <ntime> <nonce_rightpart> <solSize+sol>"
**
** Return 1 iff the block hash is under the target.
*/
uint32_t print_solver_line(uint32_t *values, uint8_t *header,
size_t fixed_nonce_bytes, uint8_t *target, char *job_id)
{
uint8_t buffer[ZCASH_BLOCK_HEADER_LEN + ZCASH_SOLSIZE_LEN +
ZCASH_SOL_LEN];
uint8_t hash0[SHA256_DIGEST_SIZE];
uint8_t hash1[SHA256_DIGEST_SIZE];
uint8_t *p;
p = buffer;
memcpy(p, header, ZCASH_BLOCK_HEADER_LEN);
p += ZCASH_BLOCK_HEADER_LEN;
memcpy(p, "\xfd\x40\x05", ZCASH_SOLSIZE_LEN);
p += ZCASH_SOLSIZE_LEN;
store_encoded_sol(p, values, 1 << PARAM_K);
Sha256_Onestep(buffer, sizeof (buffer), hash0);
Sha256_Onestep(hash0, sizeof (hash0), hash1);
// compare the double SHA256 hash with the target
if (cmp_target_256(target, hash1) < 0)
{
debug("Hash is above target\n");
return 0;
}
debug("Hash is under target\n");
printf("sol: %s ", job_id);
p = header + ZCASH_BLOCK_OFFSET_NTIME;
printf("%02x%02x%02x%02x ", p[0], p[1], p[2], p[3]);
printf("%s ", s_hexdump(header + ZCASH_BLOCK_HEADER_LEN - ZCASH_NONCE_LEN +
fixed_nonce_bytes, ZCASH_NONCE_LEN - fixed_nonce_bytes));
printf("%s%s\n", ZCASH_SOLSIZE_HEX,
s_hexdump(buffer + ZCASH_BLOCK_HEADER_LEN + ZCASH_SOLSIZE_LEN,
ZCASH_SOL_LEN));
fflush(stdout);
return 1;
}
int sol_cmp(const void *_a, const void *_b)
{
const uint32_t *a = _a;
const uint32_t *b = _b;
for (uint32_t i = 0; i < (1 << PARAM_K); i++)
{
if (*a != *b)
return *a - *b;
a++;
b++;
}
return 0;
}
/*
** Print all solutions.
**
** In mining mode, return the number of shares, that is the number of solutions
** that were under the target.
*/
uint32_t print_sols(sols_t *all_sols, uint64_t *nonce, uint32_t nr_valid_sols,
uint8_t *header, size_t fixed_nonce_bytes, uint8_t *target,
char *job_id)
{
uint8_t *valid_sols;
uint32_t counted;
uint32_t shares = 0;
valid_sols = malloc(nr_valid_sols * SOL_SIZE);
if (!valid_sols)
fatal("malloc: %s\n", strerror(errno));
counted = 0;
for (uint32_t i = 0; i < all_sols->nr; i++)
if (all_sols->valid[i])
{
if (counted >= nr_valid_sols)
fatal("Bug: more than %d solutions\n", nr_valid_sols);
memcpy(valid_sols + counted * SOL_SIZE, all_sols->values[i],
SOL_SIZE);
counted++;
}
assert(counted == nr_valid_sols);
// sort the solutions amongst each other, to make the solver's output
// deterministic and testable
qsort(valid_sols, nr_valid_sols, SOL_SIZE, sol_cmp);
for (uint32_t i = 0; i < nr_valid_sols; i++)
{
uint32_t *inputs = (uint32_t *)(valid_sols + i * SOL_SIZE);
if (!mining && show_encoded)
print_encoded_sol(inputs, 1 << PARAM_K);
if (verbose)
print_sol(inputs, nonce);
if (mining)
shares += print_solver_line(inputs, header, fixed_nonce_bytes,
target, job_id);
}
free(valid_sols);
return shares;
}
/*
** Sort a pair of binary blobs (a, b) which are consecutive in memory and
** occupy a total of 2*len 32-bit words.
**
** a points to the pair
** len number of 32-bit words in each pair
*/
void sort_pair(uint32_t *a, uint32_t len)
{
uint32_t *b = a + len;
uint32_t tmp, need_sorting = 0;
for (uint32_t i = 0; i < len; i++)
if (need_sorting || a[i] > b[i])
{
need_sorting = 1;
tmp = a[i];
a[i] = b[i];
b[i] = tmp;
}
else if (a[i] < b[i])
return ;
}
/*
** If solution is invalid return 0. If solution is valid, sort the inputs
** and return 1.
*/
uint32_t verify_sol(sols_t *sols, unsigned sol_i)
{
uint32_t *inputs = sols->values[sol_i];
uint32_t seen_len = (1 << (PREFIX + 1)) / 8;
uint8_t seen[seen_len];
uint32_t i;
uint8_t tmp;
// look for duplicate inputs
memset(seen, 0, seen_len);
for (i = 0; i < (1 << PARAM_K); i++)
{
if (inputs[i] / 8 >= seen_len)
{
warn("Invalid input retrieved from device: %d\n", inputs[i]);
sols->valid[sol_i] = 0;
return 0;
}
tmp = seen[inputs[i] / 8];
seen[inputs[i] / 8] |= 1 << (inputs[i] & 7);
if (tmp == seen[inputs[i] / 8])
{
// at least one input value is a duplicate
sols->valid[sol_i] = 0;
return 0;
}
}
// the valid flag is already set by the GPU, but set it again because
// I plan to change the GPU code to not set it
sols->valid[sol_i] = 1;
// sort the pairs in place
for (uint32_t level = 0; level < PARAM_K; level++)
for (i = 0; i < (1 << PARAM_K); i += (2 << level))
sort_pair(&inputs[i], 1 << level);
return 1;
}
/*
** Return the number of valid solutions.
*/
uint32_t verify_sols(cl_command_queue queue, cl_mem buf_sols, uint64_t *nonce,
uint8_t *header, size_t fixed_nonce_bytes, uint8_t *target,
char *job_id, uint32_t *shares)
{
sols_t *sols;
uint32_t nr_valid_sols;
sols = (sols_t *)malloc(sizeof (*sols));
if (!sols)
fatal("malloc: %s\n", strerror(errno));
check_clEnqueueReadBuffer(queue, buf_sols,
CL_TRUE, // cl_bool blocking_read
0, // size_t offset
sizeof (*sols), // size_t size
sols, // void *ptr
0, // cl_uint num_events_in_wait_list
NULL, // cl_event *event_wait_list
NULL); // cl_event *event
if (sols->nr > MAX_SOLS)
{
fprintf(stderr, "%d (probably invalid) solutions were dropped!\n",
sols->nr - MAX_SOLS);
sols->nr = MAX_SOLS;
}
debug("Retrieved %d potential solutions\n", sols->nr);
nr_valid_sols = 0;
for (unsigned sol_i = 0; sol_i < sols->nr; sol_i++)
nr_valid_sols += verify_sol(sols, sol_i);
uint32_t sh = print_sols(sols, nonce, nr_valid_sols, header,
fixed_nonce_bytes, target, job_id);
if (shares)
*shares = sh;
if (!mining || verbose)
fprintf(stderr, "Nonce %s: %d sol%s\n",
s_hexdump(nonce, ZCASH_NONCE_LEN), nr_valid_sols,
nr_valid_sols == 1 ? "" : "s");
debug("Stats: %d likely invalids\n", sols->likely_invalids);
free(sols);
return nr_valid_sols;
}
unsigned get_value(unsigned *data, unsigned row)
{
return data[row];
}
/*
** Attempt to find Equihash solutions for the given Zcash block header and
** nonce. The 'header' passed in argument is a 140-byte header specifying
** the nonce, which this function may auto-increment if 'do_increment'. This
** allows repeatedly calling this fuction to solve different Equihash problems.
**
** header must be a buffer allocated with ZCASH_BLOCK_HEADER_LEN bytes
** header_len number of bytes initialized in header (either 140 or 108)
** shares if not NULL, in mining mode the number of shares (ie. number
** of solutions that were under the target) are stored here
**
** Return the number of solutions found.
*/
uint32_t solve_equihash(cl_context ctx, cl_command_queue queue,
cl_kernel k_init_ht, cl_kernel *k_rounds, cl_kernel k_sols,
cl_mem *buf_ht, cl_mem buf_sols, cl_mem buf_dbg, size_t dbg_size,
uint8_t *header, size_t header_len, char do_increment,
size_t fixed_nonce_bytes, uint8_t *target, char *job_id,
uint32_t *shares, cl_mem *rowCounters)
{
blake2b_state_t blake;
cl_mem buf_blake_st;
size_t global_ws;
size_t local_work_size = 64;
uint32_t sol_found = 0;
uint64_t *nonce_ptr;
assert(header_len == ZCASH_BLOCK_HEADER_LEN);
if (mining)
assert(target && job_id);
nonce_ptr = (uint64_t *)(header + ZCASH_BLOCK_HEADER_LEN - ZCASH_NONCE_LEN);
if (do_increment)
{
// Increment the nonce
if (mining)
{
// increment bytes 17-19
(*(uint32_t *)((uint8_t *)nonce_ptr + 17))++;
// byte 20 and above must be zero
*(uint32_t *)((uint8_t *)nonce_ptr + 20) = 0;
}
else
// increment bytes 0-7
(*nonce_ptr)++;
}
debug("\nSolving nonce %s\n", s_hexdump(nonce_ptr, ZCASH_NONCE_LEN));
// Process first BLAKE2b-400 block
zcash_blake2b_init(&blake, ZCASH_HASH_LEN, PARAM_N, PARAM_K);
zcash_blake2b_update(&blake, header, 128, 0);
buf_blake_st = check_clCreateBuffer(ctx, CL_MEM_READ_ONLY |
CL_MEM_COPY_HOST_PTR, sizeof (blake.h), &blake.h);
for (unsigned round = 0; round < PARAM_K; round++)
{
if (verbose > 1)
debug("Round %d\n", round);
// Now on every round!!!!
init_ht(queue, k_init_ht, buf_ht[round % 2], rowCounters[round % 2]);
if (!round)
{
check_clSetKernelArg(k_rounds[round], 0, &buf_blake_st);
check_clSetKernelArg(k_rounds[round], 1, &buf_ht[round % 2]);
check_clSetKernelArg(k_rounds[round], 2, &rowCounters[round % 2]);
global_ws = select_work_size_blake();
}
else
{
check_clSetKernelArg(k_rounds[round], 0, &buf_ht[(round - 1) % 2]);
check_clSetKernelArg(k_rounds[round], 1, &buf_ht[round % 2]);
check_clSetKernelArg(k_rounds[round], 2, &rowCounters[(round - 1) % 2]);
check_clSetKernelArg(k_rounds[round], 3, &rowCounters[round % 2]);
global_ws = NR_ROWS;
}
check_clSetKernelArg(k_rounds[round], round == 0 ? 3 : 4, &buf_dbg);
if (round == PARAM_K - 1)
check_clSetKernelArg(k_rounds[round], 5, &buf_sols);
check_clEnqueueNDRangeKernel(queue, k_rounds[round], 1, NULL,
&global_ws, &local_work_size, 0, NULL, NULL);
examine_ht(round, queue, buf_ht[round % 2]);
examine_dbg(queue, buf_dbg, dbg_size);
}
check_clSetKernelArg(k_sols, 0, &buf_ht[0]);
check_clSetKernelArg(k_sols, 1, &buf_ht[1]);
check_clSetKernelArg(k_sols, 2, &buf_sols);
check_clSetKernelArg(k_sols, 3, &rowCounters[0]);
check_clSetKernelArg(k_sols, 4, &rowCounters[1]);
global_ws = NR_ROWS;
check_clEnqueueNDRangeKernel(queue, k_sols, 1, NULL,
&global_ws, &local_work_size, 0, NULL, NULL);
sol_found = verify_sols(queue, buf_sols, nonce_ptr, header,
fixed_nonce_bytes, target, job_id, shares);
clReleaseMemObject(buf_blake_st);
return sol_found;
}
/*
** Read a complete line from stdin. If 2 or more lines are available, store
** only the last one in the buffer.
**
** buf buffer to store the line
** len length of the buffer
** block blocking mode: do not return until a line was read
**
** Return 1 iff a line was read.
*/
int read_last_line(char *buf, size_t len, int block)
{
char *start;
size_t pos = 0;
ssize_t n;
set_blocking_mode(0, block);
while (42)
{
n = read(0, buf + pos, len - pos);
if (n == -1 && errno == EINTR)
continue ;
else if (n == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
{
if (!pos)
return 0;
warn("strange: a partial line was read\n");
// a partial line was read, continue reading it in blocking mode
// to be sure to read it completely
set_blocking_mode(0, 1);
continue ;
}
else if (n == -1)
fatal("read stdin: %s\n", strerror(errno));
else if (!n)
fatal("EOF on stdin\n");
pos += n;
if (buf[pos - 1] == '\n')
// 1 (or more) complete lines were read
break ;
}
start = memrchr(buf, '\n', pos - 1);
if (start)
{
warn("strange: more than 1 line was read\n");
// more than 1 line; copy the last line to the beginning of the buffer
pos -= (start + 1 - buf);
memmove(buf, start + 1, pos);
}
// overwrite '\n' with NUL
buf[pos - 1] = 0;
return 1;
}
/*
** Parse a string:
** "<target> <job_id> <header> <nonce_leftpart>"
** (all the parts are in hex, except job_id which is a non-whitespace string),
** decode the hex values and store them in the relevant buffers.
**
** The remaining part of <header> that is not set by
** <header><nonce_leftpart> will be randomized so that the miner
** solves a unique Equihash PoW.
**
** str string to parse
** target buffer where the <target> will be stored
** target_len size of target buffer
** job_id buffer where the <job_id> will be stored
** job_id_len size of job_id buffer
** header buffer where the <header><nonce_leftpart> will be
** concatenated and stored
** header_len size of the header_buffer
** fixed_nonce_bytes
** nr of bytes represented by <nonce_leftpart> will be stored here;
** this is the number of nonce bytes fixed by the stratum server
*/
void mining_parse_job(char *str, uint8_t *target, size_t target_len,
char *job_id, size_t job_id_len, uint8_t *header, size_t header_len,
size_t *fixed_nonce_bytes)
{
uint32_t str_i, i;
// parse target
str_i = 0;
for (i = 0; i < target_len; i++, str_i += 2)
target[i] = hex2val(str, str_i) * 16 + hex2val(str, str_i + 1);
assert(str[str_i] == ' ');
str_i++;