forked from demining/CryptoDeepTools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqianshiBTC.c
1515 lines (1375 loc) · 39.4 KB
/
qianshiBTC.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
/*
* qianshiBTC.c
* (C) 2015 basil, all rights reserved,
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <assert.h>
#include <ctype.h>
#include <getopt.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#define USE_ASM_X86_64
#define USE_FIELD_5X52
#define USE_NUM_GMP
#define USE_FIELD_INV_NUM
#define USE_SCALAR_4X64
#define USE_SCALAR_INV_BUILTIN
#define HAVE___INT128
#include "secp256k1.c"
#include "hash160.c"
static secp256k1_context_t *cxt;
/****************************************************************************/
// LINUX CRUFT:
#ifdef LINUX
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
typedef pthread_t thread;
typedef pthread_mutex_t mutex;
static inline void mutex_init(mutex *m)
{
int res = pthread_mutex_init(m, NULL);
assert(res == 0);
}
static inline void mutex_lock(mutex *m)
{
int res = pthread_mutex_lock(m);
assert(res == 0);
}
static inline void mutex_unlock(mutex *m)
{
int res = pthread_mutex_unlock(m);
assert(res == 0);
}
static thread spawn_thread(void *(f)(void *), void *arg)
{
thread t;
int res = pthread_create(&t, NULL, f, (void *)arg);
if (res != 0)
return (thread)NULL;
return t;
}
static void join_thread(thread t)
{
pthread_join(t, NULL);
}
static size_t num_threads(void)
{
return (size_t)sysconf(_SC_NPROCESSORS_ONLN);
}
static bool init_rand(void *data, size_t size)
{
FILE *stream = fopen("/dev/urandom", "r");
if (stream == NULL)
return false;
bool ok = (fread(data, sizeof(uint8_t), size, stream) == size);
fclose(stream);
return ok;
}
static void set_bold(bool bold)
{
if (!isatty(1))
return;
if (bold)
printf("\33[1m");
else
printf("\33[0m");
}
static uint64_t get_time(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
#define bswap16 __builtin_bswap16
#endif
/****************************************************************************/
// WINDOWS CRUFT:
#ifdef WINDOWS
#define _CRT_RAND_S
#include <stdlib.h>
#include <windows.h>
typedef HANDLE thread;
typedef HANDLE mutex;
static inline void mutex_init(mutex *m)
{
*m = CreateMutex(NULL, FALSE, NULL);
assert(*m != NULL);
}
static inline void mutex_lock(mutex *m)
{
DWORD res = WaitForSingleObject(*m, INFINITE);
assert(res == WAIT_OBJECT_0);
}
static inline void mutex_unlock(mutex *m)
{
BOOL res = ReleaseMutex(*m);
assert(res);
}
static thread spawn_thread(void *(f)(void *), void *arg)
{
return CreateThread(NULL, 1, (LPTHREAD_START_ROUTINE)f,
(LPVOID)arg, 0, NULL);
}
static void join_thread(thread t)
{
WaitForSingleObject(t, INFINITE);
}
static size_t num_threads(void)
{
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
}
static bool init_rand(void *data, size_t size)
{
size_t size0 = size / sizeof(unsigned) + 1;
assert(size0 * sizeof(unsigned) >= size);
unsigned data0[size0];
for (size_t i = 0; i < size0; i++)
{
int err = rand_s(data0 + i);
if (err != 0)
return false;
}
memcpy(data, data0, size);
return true;
}
static void set_bold(bool bold)
{
HANDLE console = GetStdHandle(STD_ERROR_HANDLE);
if (bold)
SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN |
FOREGROUND_BLUE | FOREGROUND_INTENSITY);
else
SetConsoleTextAttribute(console, FOREGROUND_RED | FOREGROUND_GREEN |
FOREGROUND_BLUE);
}
static uint64_t get_time(void)
{
return (uint64_t)GetTickCount64();
}
#define bswap16(x) (((uint16_t)(x) << 8) | ((uint16_t)(x) >> 8))
#endif
/****************************************************************************/
// HASH FUNCTIONS:
union uint256_s
{
uint8_t i8[32];
uint16_t i16[16];
uint32_t i32[8];
uint64_t i64[4];
};
typedef union uint256_s uint256_t;
/*
* SHA256
*/
static inline uint256_t sha256(const void *data, size_t len)
{
secp256k1_sha256_t cxt;
secp256k1_sha256_initialize(&cxt);
secp256k1_sha256_write(&cxt, (uint8_t *)data, (int)len);
uint256_t res;
secp256k1_sha256_finalize(&cxt, (uint8_t *)&res);
return res;
}
/*
* SHA256d
*/
static uint256_t sha256d(const void *data, size_t len)
{
uint256_t hsh = sha256(data, len);
hsh = sha256(&hsh, sizeof(hsh));
return hsh;
}
/****************************************************************************/
// RANDOM NUMBERS:
struct seed
{
uint256_t seed;
uint128_t counter;
};
/*
* Create a new random seed.
*/
static struct seed *make_seed(void)
{
struct seed *seed = (struct seed *)malloc(sizeof(struct seed));
assert(seed != NULL);
seed->counter = 0;
if (!init_rand(seed, sizeof(struct seed)))
{
fprintf(stderr, "error: failed to init random seed\n");
exit(EXIT_FAILURE);
}
if (seed->counter == 0) // Sanity check...
{
fprintf(stderr, "error: random seed initialization failed\n");
exit(EXIT_FAILURE);
}
return seed;
}
/*
* Get a new random number.
*/
static uint256_t rand256(struct seed *seed)
{
seed->counter++;
return sha256(seed, sizeof(struct seed));
}
/****************************************************************************/
// OUTPUT:
/*
* Base58 encode
*/
static const char* base58str =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
static bool base58_encode(char *str, size_t slen, const uint8_t *data,
size_t dlen)
{
size_t i = 0;
for (; i < dlen && data[i] == 0x0; i++)
;
size_t zeroes = i; // Retained zeroes.
char b58[(dlen - i) * 138 / 100 + 1];
memset(b58, 0, sizeof(b58));
for (; i < dlen; i++)
{
int carry = (int)data[i];
for (ssize_t j = sizeof(b58)-1; j >= 0; j--)
{
carry += 256 * b58[j];
b58[j] = carry % 58;
carry /= 58;
}
assert(carry == 0);
}
for (i = 0; i < sizeof(b58) && b58[i] == 0; i++)
;
size_t zeroes2 = i; // Dropped zeroes.
if (zeroes + sizeof(b58) - zeroes2 + 1 > slen)
return false;
memset(str, '1', zeroes);
size_t j;
for (j = zeroes; i < sizeof(b58); i++, j++)
str[j] = base58str[b58[i]];
str[j] = '\0';
return true;
}
/*
* Base58check encode.
*/
static bool base58check_encode(char *str, size_t slen, const uint8_t *data,
size_t dlen)
{
uint256_t hsh = sha256d(data, dlen);
uint8_t tmp[dlen + 4];
memcpy(tmp, data, dlen);
tmp[dlen+0] = hsh.i8[0];
tmp[dlen+1] = hsh.i8[1];
tmp[dlen+2] = hsh.i8[2];
tmp[dlen+3] = hsh.i8[3];
return base58_encode(str, slen, tmp, sizeof(tmp));
}
/*
* Base64 encode.
*/
static bool base64_encode(char *str, size_t slen, const uint8_t *data,
size_t dlen)
{
static const char *base64str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl"
"mnopqrstuvwxyz0123456789+/";
if (slen < (dlen+2)/3*4 + 1)
return false;
int mode = 0, left = 0;
const uint8_t *end = data + dlen;
size_t i = 0;
while (data < end)
{
int enc = *(data++);
switch (mode)
{
case 0:
str[i++] = base64str[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1:
str[i++] = base64str[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2:
str[i++] = base64str[left | (enc >> 6)];
str[i++] = base64str[enc & 63];
mode = 0;
break;
}
}
if (mode != 0)
{
str[i++] = base64str[left];
str[i++] = '=';
if (mode == 1)
str[i++] = '=';
}
str[i++] = '\0';
return true;
}
/*
* Make an address string from a hash160.
*/
static void make_addr(char *str, size_t slen, uint160_t x)
{
uint8_t raw_addr[1 + sizeof(x)];
raw_addr[0] = 0;
memcpy(raw_addr+1, &x, sizeof(x));
if (!base58check_encode(str, slen, raw_addr, sizeof(raw_addr)))
{
fprintf(stderr, "error: failed to generate address\n");
exit(EXIT_FAILURE);
}
}
/*
* Generate a hash160 from a public key,
*/
static uint160_t gen_hash160(const uint8_t *pub_key)
{
uint160_t hsh160 = hash160(pub_key);
return hsh160;
}
/*
* Make a WIF (compressed) string from a private key.
*/
static void make_wif(char *str, size_t slen, uint256_t priv_key)
{
uint8_t raw_wif[34];
raw_wif[0] = 0x80;
memcpy(raw_wif+1, &priv_key, sizeof(priv_key));
raw_wif[33] = 0x01;
if (!base58check_encode(str, slen, raw_wif, sizeof(raw_wif)))
{
fprintf(stderr, "error: failed to create WIF\n");
exit(EXIT_FAILURE);
}
}
/*
* Make a signature (proof you own the private keys).
*/
static void make_sig(char *str, size_t slen, const char *message0,
uint256_t key)
{
const char *magic = "Bitcoin Signed Message:\n";
size_t mlen = strlen(magic);
size_t mlen0 = strlen(message0);
char message[mlen + mlen0 + 2];
message[0] = mlen;
memcpy(message+1, magic, mlen);
message[mlen+1] = mlen0;
memcpy(message+mlen+2, message0, mlen0);
uint256_t msg = sha256d(message, mlen + mlen0 + 2);
uint8_t sig[65];
int rec = -1;
int res = secp256k1_ecdsa_sign_compact(cxt, msg.i8, sig+1, key.i8,
secp256k1_nonce_function_rfc6979, NULL, &rec);
if (res == 0 || rec == -1)
{
fprintf(stderr, "error: failed to generate signature\n");
exit(EXIT_FAILURE);
}
sig[0] = 27 + rec + 4;
if (!base64_encode(str, slen, sig, sizeof(sig)))
{
fprintf(stderr, "error: failed to generate signature\n");
exit(EXIT_FAILURE);
}
}
// Get a "nybble".
#define get_nybble(xs, i) \
((i)%2 == 1? (xs)[(i)/2] & 0xF: (xs)[(i)/2] >> 4)
/****************************************************************************/
// STEP FUNCTION:
//
// Given a hash160 H comprised on {h0, h1, .., h9} 16-bit parts, then H is
// mapped to a public key P as follows:
// P = G.base[h0] + G.offset[h1] + .. + G.offset[h9]
// The calculation is truncated according to the length n. The corresponding
// private key P' is:
// P' = base[h0] + offset[h1] + .. + offset[h9]
// Each (offset[i], G.offset[i]) and (base[i], G.base[i]) is chosen randomly
// and computed in advanced.
#define BASE_MAX 0xFFFF
static secp256k1_gej_t bases[BASE_MAX];
static secp256k1_scalar_t priv_bases[BASE_MAX];
#define OFFSET_MAX_COL 9
#define OFFSET_MAX_ROW BASE_MAX
#define BITS 16
#define NUM_PARTS(n) (((n) - 1) / 16 + 1)
#define NUM_INIT_WORKERS 4
static secp256k1_ge_t offsets[OFFSET_MAX_ROW][OFFSET_MAX_COL];
static secp256k1_scalar_t priv_offsets[OFFSET_MAX_ROW][OFFSET_MAX_COL];
// Prototypes:
static bool read_pub_table(FILE *stream);
static bool write_pub_table(FILE *stream);
static bool read_priv_table(FILE *stream);
static bool write_priv_table(FILE *stream);
/*
* Initialization worker.
*/
static void *init_worker(void *arg)
{
struct seed *seed = make_seed();
size_t i = (size_t)arg;
for (size_t j = 0; j < OFFSET_MAX_ROW; j++)
{
int overflow = 0;
do
{
uint256_t x = rand256(seed);
secp256k1_scalar_set_b32(&priv_offsets[j][i], x.i8, &overflow);
}
while (overflow);
secp256k1_gej_t tmp;
secp256k1_ecmult_gen(&cxt->ecmult_gen_ctx, &tmp, &priv_offsets[j][i]);
secp256k1_ge_set_gej(&offsets[j][i], &tmp);
}
free(seed);
putchar('.');
fflush(stdout);
return NULL;
}
/*
* Initialize the base and offet tables.
*/
static void init(ssize_t n, const char *priv_name, const char *pub_name)
{
if (pub_name != NULL)
{
FILE *stream = fopen(pub_name, "r");
if (stream != NULL)
{
if (!read_pub_table(stream))
{
fprintf(stderr, "error: failed to read \"%s\"\n", pub_name);
exit(EXIT_FAILURE);
}
fclose(stream);
fputs("RRRRRRRRRR", stdout);
return;
}
n = 160; // Full n for job mode.
}
n = NUM_PARTS(n)-1;
thread ts[OFFSET_MAX_COL];
for (size_t i = 0; i < n; i++)
{
ts[i] = spawn_thread(init_worker, (void *)i);
if (ts[i] == (thread)NULL)
{
fprintf(stderr, "error: failed to spawn init worker thread\n");
exit(EXIT_FAILURE);
}
}
struct seed *seed = make_seed();
for (size_t i = 0; i < BASE_MAX; i++)
{
int overflow = 0;
do
{
uint256_t x = rand256(seed);
secp256k1_scalar_set_b32(&priv_bases[i], x.i8, &overflow);
}
while (overflow);
secp256k1_ecmult_gen(&cxt->ecmult_gen_ctx, &bases[i], &priv_bases[i]);
}
free(seed);
putchar('.');
fflush(stdout);
for (size_t i = 0; i < n; i++)
join_thread(ts[i]);
if (pub_name != NULL)
{
FILE *stream = fopen(pub_name, "w");
if (stream == NULL || !write_pub_table(stream))
{
fprintf(stderr, "error: failed to write \"%s\"\n", pub_name);
exit(EXIT_FAILURE);
}
fclose(stream);
stream = fopen(priv_name, "w");
if (stream == NULL || !write_priv_table(stream))
{
fprintf(stderr, "error: failed to write \"%s\"\n", priv_name);
exit(EXIT_FAILURE);
}
fclose(stream);
}
}
/*
* Get bits from memory.
*/
static uint16_t get_bits(size_t n, const uint16_t *val, size_t i)
{
static const size_t NUM_BITS = 8*sizeof(uint16_t);
if (n < i * NUM_BITS)
return 0;
n -= i * NUM_BITS;
uint16_t bits = bswap16(val[i]);
if (n >= NUM_BITS)
return bits;
bits &= ((uint16_t)0xFFFF << (NUM_BITS - n));
return bits;
}
/*
* Generate a public key from a hash160.
*/
static void gen_pub_key(uint8_t *pub_key, size_t n, uint160_t x)
{
size_t idx = get_bits(n, x.i16, 0);
secp256k1_gej_t r = bases[idx];
for (size_t i = 1; i < NUM_PARTS(n); i++)
{
size_t col = i - 1;
size_t row = get_bits(n, x.i16, i);
secp256k1_gej_add_ge(&r, &r, &offsets[row][col]);
}
secp256k1_ge_t s;
secp256k1_ge_set_gej(&s, &r);
pub_key[0] = 0x02 | (secp256k1_fe_is_odd(&s.y) ? 0x01 : 0x00);
secp256k1_fe_get_b32(pub_key+1, &s.x);
}
/*
* Generate a private key from a hash160.
*/
static uint256_t gen_priv_key(size_t n, uint160_t x)
{
size_t idx = get_bits(n, x.i16, 0);
secp256k1_scalar_t r = priv_bases[idx];
for (size_t i = 1; i < NUM_PARTS(n); i++)
{
size_t col = i - 1;
size_t row = get_bits(n, x.i16, i);
secp256k1_scalar_add(&r, &r, &priv_offsets[row][col]);
}
uint256_t y;
secp256k1_scalar_get_b32(y.i8, &r);
return y;
}
/*
* STEP FUNCTION:
* Generate a new hash160 that depends on an old hash160 (and n).
*/
static inline uint160_t f(size_t n, uint160_t x)
{
uint8_t pub_key[33];
gen_pub_key(pub_key, n, x);
uint160_t hsh160 = hash160(pub_key);
return hsh160;
}
/****************************************************************************/
// TESTS
/*
* Test if two hash160 values are equal (for a given n).
*/
static bool is_equal(size_t n, uint160_t x, uint160_t y)
{
for (size_t i = 0; i < NUM_PARTS(n); i++)
{
uint16_t a = get_bits(n, x.i16, i);
uint16_t b = get_bits(n, y.i16, i);
if (a != b)
return false;
}
return true;
}
/*
* Test if a hash160 is "distinguished".
*/
static bool is_distinguished(size_t z, uint160_t x)
{
if (z == 0)
return true;
for (size_t i = 0; i < NUM_PARTS(z); i++)
{
uint16_t a = get_bits(z, x.i16, i);
if (a != 0)
return false;
}
return true;
}
/*
* Make a hash160 distinguished.
*/
static uint160_t make_distinguished(size_t z, uint160_t x)
{
size_t j = z / 8, k = z % 8;
for (size_t i = 0; i < j; i++)
x.i8[i] = 0;
x.i8[j] &= (0xFF >> k);
return x;
}
/****************************************************************************/
// WORK TABLE
//
// Stores found work for collision detection.
struct entry
{
uint160_t start;
uint160_t end;
struct entry *next;
};
#define TABLE_MAX 8192
static struct entry *table[TABLE_MAX] = {NULL};
static mutex table_lock;
static bool collision = false;
static uint160_t c1; // First collider
static uint160_t c2; // Second collider
static uint160_t c3; // Collision result
#define lock_table() mutex_lock(&table_lock)
#define unlock_table() mutex_unlock(&table_lock)
#define FAUX_COLLISION (-1)
#define COLLISION 0
#define NO_COLLISION 1
#define STOP 2
static void write_work(FILE *stream, bool comment, size_t n, size_t z,
uint160_t start, uint160_t end);
/*
* Get the collision result.
*/
static void get_collision(uint160_t *x, uint160_t *y, uint160_t *end)
{
assert(collision);
*x = c1;
*y = c2;
if (end != NULL)
*end = c3;
}
/*
* Work found, add it to the table. Result indicates whether the work
* corresponds to a (faux) collision or not.
*/
static int add_work(FILE *stream, size_t n, size_t z, uint160_t start,
uint160_t end)
{
struct entry *entry = (struct entry *)malloc(sizeof(struct entry));
if (entry == NULL)
{
fprintf(stderr, "error: failed to allocate %lu bytes for entry",
sizeof(struct entry));
exit(EXIT_FAILURE);
}
entry->start = start;
entry->end = end;
entry->next = NULL;
uint16_t hsh = 0;
for (size_t i = 0; i < NUM_PARTS(n); i++)
hsh += get_bits(n, end.i16, i);
hsh = hsh % TABLE_MAX;
lock_table();
if (collision)
{
unlock_table();
free(entry);
return STOP;
}
if (table[hsh] == NULL)
table[hsh] = entry;
else
{
struct entry *curr = table[hsh], *prev = NULL;
while (curr != NULL)
{
if (is_equal(n, curr->end, entry->end))
{
if (is_equal(n, curr->start, entry->start))
{
// Faux collision:
unlock_table();
free(entry);
return FAUX_COLLISION;
}
// Collision:
collision = true;
c1 = curr->start;
c2 = entry->start;
c3 = curr->end;
write_work(stream, true, n, z, start, end);
unlock_table();
free(entry);
return COLLISION;
}
prev = curr;
curr = curr->next;
}
prev->next = entry;
}
write_work(stream, false, n, z, start, end);
unlock_table();
return NO_COLLISION;
}
/*
* Reset the work table state.
*/
static void reset_table(void)
{
lock_table();
collision = false;
for (size_t i = 0; i < TABLE_MAX; i++)
{
struct entry *curr = table[i];
while (curr != NULL)
{
struct entry *next = curr->next;
free(curr);
curr = next;
}
table[i] = NULL;
}
unlock_table();
}
/****************************************************************************/
// WORK:
struct info
{
uint160_t x;
size_t n;
size_t z;
FILE *stream;
size_t z0;
uint160_t end;
};
// Stop when true. A mere `volatile' should be OK here, although this is a
// bad idea in general.
static volatile bool stop = false;
/*
* Spawn a worker thread.
*/
static void *worker(void *arg);
static thread spawn_worker(FILE *stream, size_t n, size_t z, uint160_t x,
size_t z0, uint160_t end)
{
struct info *info = (struct info *)malloc(sizeof(struct info));
assert(info != NULL);
info->x = x;
info->n = n;
info->z = z;
info->stream = stream;
info->z0 = z0;
info->end = end;
thread t = spawn_thread(worker, info);
if (t == (thread)NULL)
{
fprintf(stderr, "error: failed to spawn thread");
exit(EXIT_FAILURE);
}
return t;
}
/*
* The worker thread. Finds pairs (x, y) of distinguished hash160s such that
* y = f(f(f(...f(x)...))). The aim is to find a "Y", i.e. a pair of work
* of the form (x, y) and (x', y) for x != x', and thus indicating a
* collision.
*/
static void write_hash160(FILE *stream, uint160_t x);
static void *worker(void *arg)
{
struct info *info = (struct info *)arg;
uint160_t x = info->x;
size_t n = info->n;
size_t z = info->z;
size_t z0 = info->z0;
uint160_t end = info->end;
FILE *stream = info->stream;
free(info);
while (true)
{
// COMPUTE WORK:
uint160_t y = f(n, x);
while (!stop && !is_distinguished(z, y))
y = f(n, y);
if (stop)
return NULL;
if (!is_distinguished(z, x))
{
// Work is not usable if x is not distinguished.
putchar('U');
fflush(stdout);
x = y;
continue;
}
// Add work to the data-base:
int res = add_work(stream, n, z, x, y);
switch (res)
{
case NO_COLLISION:
putchar('.');
fflush(stdout);
break;
case COLLISION:
stop = true;
putchar('Y');
fflush(stdout);
return NULL;
case STOP:
return NULL;
case FAUX_COLLISION:
{
// Useless collision for a repeated x = wasted work.
// Less likely for larger n.
putchar('X');
fflush(stdout);
// Reset search:
uint256_t hsh = sha256(&y, sizeof(y));
memcpy(&x, &hsh, sizeof(x));
x = make_distinguished(z, x);
continue;
}
}
if (is_distinguished(z0, y))
{
if (!is_equal(n, y, end))
{
stop = true;
fprintf(stderr, "error: something went wrong; collision is not "
"valid (bug or hardware error?)\n");
fprintf(stderr, "expected: ");
write_hash160(stderr, end);
fprintf(stderr, "\ngot : ");
write_hash160(stderr, y);
putc('\n', stderr);
exit(EXIT_FAILURE);
}
putchar('S');
fflush(stdout);
return NULL;
}
x = y;
}
}
/****************************************************************************/
// I/O
static void write_hash160(FILE *stream, uint160_t x)
{
for (size_t i = 0; i < sizeof(x); i++)
fprintf(stream, "%.2x", x.i8[i]);
}
static bool read_hash160(FILE *stream, uint160_t *x)
{
for (size_t i = 0; i < sizeof(uint160_t); i++)
{
char hex[3] = {getc(stream), getc(stream), '\0'};
if (!isxdigit(hex[0]) || !isxdigit(hex[1]))
return false;
x->i8[i] = strtoul(hex, NULL, 16);
}
return true;
}
static void write_work(FILE *stream, bool comment, size_t n, size_t z,
uint160_t start, uint160_t end)
{
if (stream == NULL)
return;
if (comment)
fputs("# ", stream);
fprintf(stream, "W%.3u%.3u ", (unsigned)n, (unsigned)z);
write_hash160(stream, end);
putc(' ', stream);
write_hash160(stream, start);
putc('\n', stream);
fflush(stream);