-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathdatum_protocol.c
More file actions
1992 lines (1658 loc) · 62.1 KB
/
datum_protocol.c
File metadata and controls
1992 lines (1658 loc) · 62.1 KB
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
/*
*
* DATUM Gateway
* Decentralized Alternative Templates for Universal Mining
*
* This file is part of OCEAN's Bitcoin mining decentralization
* project, DATUM.
*
* https://ocean.xyz
*
* ---
*
* Copyright (c) 2024-2025 Bitcoin Ocean, LLC & Jason Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
// DATUM Client protocol implementation
// Encrypted and on the wire has 7.999 bits of entropy per byte in testing. completely uncompressable.
// TODO: Clean this up and break up various functions
// TODO: Generalize encryption related operations vs repeated code
// TODO: Implement versioning on the protocol for feature lists
// TODO: Add pool-side assistance with startup to ensure that the client's node is fully sync'd with the network
// TODO: Optionally allow pool to suggest node peers
// TODO: Implement graceful negotiation of chain forks
// TODO: Implement preciousblock for pool blocks not found by the client
// TODO: Handle network failures that aren't immediately obvious more gracefully (like not receiving responses to server commands)
// TODO: Implement resuiming of work without allowing one client to cause duplicate work for another
#include <sodium.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <inttypes.h>
#include "datum_utils.h"
#include "datum_protocol.h"
#include "datum_conf.h"
#include "datum_stratum.h"
#include "datum_blocktemplates.h"
#include "datum_coinbaser.h"
#include "datum_queue.h"
#include "git_version.h"
#ifdef __APPLE__
#include "portable_mutex.h"
#endif
atomic_int datum_protocol_client_active = 0;
DATUM_ENC_KEYS local_datum_keys;
DATUM_ENC_KEYS session_datum_keys;
DATUM_ENC_KEYS session_remote_datum_keys;
DATUM_ENC_KEYS pool_keys;
DATUM_ENC_PRECOMP session_precomp;
unsigned char datum_state = 0;
int server_out_buf = 0;
int server_in_buf = 0;
int protocol_state = 0;
unsigned char server_send_buffer[DATUM_PROTOCOL_BUFFER_SIZE];
unsigned char server_recv_buffer[DATUM_PROTOCOL_BUFFER_SIZE];
uint32_t sending_header_key = 0xDC871829; // initial send header key ... changed by handshake function
uint32_t receiving_header_key = 0; // set by handshake function
unsigned char session_nonce_sender[crypto_box_NONCEBYTES];
unsigned char session_nonce_receiver[crypto_box_NONCEBYTES];
pthread_mutex_t datum_protocol_sender_stage1_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t datum_protocol_send_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
unsigned char datum_protocol_next_job_idx = 0;
pthread_mutex_t datum_protocol_next_job_idx_lock = PTHREAD_MUTEX_INITIALIZER;
T_DATUM_PROTOCOL_JOB datum_jobs[MAX_DATUM_PROTOCOL_JOBS];
pthread_rwlock_t datum_jobs_rwlock = PTHREAD_RWLOCK_INITIALIZER;
// Share tallies for decentralized mining
uint64_t datum_accepted_share_count = 0;
uint64_t datum_accepted_share_diff = 0;
uint64_t datum_rejected_share_count = 0;
uint64_t datum_rejected_share_diff = 0;
uint64_t datum_last_accepted_share_tsms = 0;
uint64_t datum_last_accepted_share_local_tsms = 0;
uint64_t datum_protocol_mainloop_tsms = 0;
uint64_t latest_server_msg_tsms = 0;
// may be used by this thread when crafting replies to server commands
unsigned char temp_data[DATUM_PROTOCOL_MAX_CMD_DATA_SIZE + 16384];
unsigned char datum_protocol_setup_new_job_idx(void *sx) {
// Called by the stratum job updater. Must be thread safe.
// give the stratum job updater a new job ID for us to work with
// The server will track up to 8 unique jobs.
T_DATUM_STRATUM_JOB *s = (T_DATUM_STRATUM_JOB *)sx;
unsigned char a;
pthread_mutex_lock(&datum_protocol_next_job_idx_lock);
a = datum_protocol_next_job_idx;
datum_protocol_next_job_idx++;
if (datum_protocol_next_job_idx >= MAX_DATUM_PROTOCOL_JOBS) {
datum_protocol_next_job_idx = 0;
}
pthread_mutex_unlock(&datum_protocol_next_job_idx_lock);
pthread_rwlock_wrlock(&datum_jobs_rwlock);
memset(&datum_jobs[a], 0, sizeof(T_DATUM_PROTOCOL_JOB));
datum_jobs[a].sjob = s;
datum_jobs[a].datum_job_id = a;
pthread_rwlock_unlock(&datum_jobs_rwlock);
return a;
}
static inline void datum_xor_header_key(void *h, uint32_t key) {
*((uint32_t *)h) ^= key;
}
uint32_t datum_header_xor_feedback(const uint32_t i) {
uint32_t s = 0xb10cfeed;
uint32_t h = s;
uint32_t k = i;
k *= 0xcc9e2d51;
k = (k << 15) | (k >> 17);
k *= 0x1b873593;
h ^= k;
h = (h << 13) | (h >> 19);
h = h * 5 + 0xe6546b64;
h ^= 4;
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
// Take the hexidecimal public key string and store it in a DATUM_ENC_KEYS
int datum_pubkey_to_struct(const char *input, DATUM_ENC_KEYS *key) {
int i;
if (input[0] == 0) return -1;
if (strlen(input) != 128) {
DLOG_FATAL("Pool public key is not the correct length!");
return -1;
}
for(i=0;i<32;i++) {
key->pk_ed25519[i] = hex2bin_uchar(&input[i<<1]);
}
for(i=0;i<32;i++) {
key->pk_x25519[i] = hex2bin_uchar(&input[64+(i<<1)]);
}
return 0;
}
// Prepare session encryption precomputation
void datum_encrypt_prep_precomp(DATUM_ENC_KEYS *remote, DATUM_ENC_KEYS *local, DATUM_ENC_PRECOMP *precomp) {
precomp->local = local;
precomp->remote = remote;
if (crypto_box_beforenm(precomp->precomp_remote, remote->pk_x25519, local->sk_x25519) != 0) {
DLOG_ERROR("Could not precompute encryption keys.");
}
}
// Buffer data to the server. Raw, already encrypted and part of the protocol.
int datum_protocol_chars_to_server(unsigned char *s, int len) {
if (!len) return 0;
pthread_mutex_lock(&datum_protocol_send_buffer_lock);
if ((server_out_buf + len) >= DATUM_PROTOCOL_BUFFER_SIZE) {
pthread_mutex_unlock(&datum_protocol_send_buffer_lock);
return -1;
}
if (len > (DATUM_PROTOCOL_BUFFER_SIZE-(server_out_buf)-1)) {
len = DATUM_PROTOCOL_BUFFER_SIZE-(server_out_buf)-1;
}
if ((server_out_buf+len) >= DATUM_PROTOCOL_BUFFER_SIZE) {
DLOG_ERROR("DATUM Server send overrun!");
pthread_mutex_unlock(&datum_protocol_send_buffer_lock);
return -1;
}
memcpy(&server_send_buffer[server_out_buf], s, len);
server_out_buf += len;
pthread_mutex_unlock(&datum_protocol_send_buffer_lock);
return len;
}
int datum_protocol_mining_cmd(void *data, int len) {
// protocol cmd 5
// encypt and send a standard mining sub-command
// this can be called from other threads so must be thread safe!
T_DATUM_PROTOCOL_HEADER h;
int i;
memset(&h, 0, sizeof(T_DATUM_PROTOCOL_HEADER));
h.is_encrypted_channel = true;
h.proto_cmd = 5;
h.cmd_len = len;
h.cmd_len += crypto_box_MACBYTES;
// sends of encrypted data must remain ordered
// we have to lock here for both the header obfuscation and the nonce increment
pthread_mutex_lock(&datum_protocol_sender_stage1_lock);
crypto_box_easy_afternm(data, data, len, session_nonce_sender, session_precomp.precomp_remote);
//DLOG_DEBUG("mining cmd 5--- len %d, send header key %8.8x, raw %8.8lx", h.cmd_len, sending_header_key, (unsigned long)upk_u32le(h, 0));
datum_xor_header_key(&h, sending_header_key);
sending_header_key = datum_header_xor_feedback(sending_header_key);
datum_increment_session_nonce(session_nonce_sender);
i = datum_protocol_chars_to_server((unsigned char *)&h, sizeof(T_DATUM_PROTOCOL_HEADER));
if (i < 1) {
pthread_mutex_unlock(&datum_protocol_sender_stage1_lock);
return -1;
}
i = datum_protocol_chars_to_server((unsigned char *)data, len + crypto_box_MACBYTES);
if (i < 1) {
pthread_mutex_unlock(&datum_protocol_sender_stage1_lock);
return -1;
}
pthread_mutex_unlock(&datum_protocol_sender_stage1_lock);
return 0;
}
pthread_mutex_t datum_protocol_coinbaser_fetch_mutex = PTHREAD_MUTEX_INITIALIZER;
#ifdef __APPLE__
// Declare the state for the timed mutex only for Apple
static timed_mutex_state_t datum_protocol_coinbaser_fetch_state;
#endif
pthread_cond_t datum_protocol_coinbaser_fetch_cond = PTHREAD_COND_INITIALIZER;
unsigned char datum_coinbaser_v2_response_buf[2][32768] = { 0 };
unsigned char *datum_coinbaser_v2_response = NULL;
unsigned char datum_coinbaser_v2_response_buf_idx = 0;
uint64_t datum_coinbaser_v2_response_value[2] = { 0, 0 };
int datum_coinbaser_v2_response_len[2] = { 0, 0 };
int datum_protocol_coinbaser_fetch_response(int len, unsigned char *data) {
if (len < 12) {
DLOG_DEBUG("Invalid coinbaser received!");
return 0;
}
// Coinbaser response from server. stash appropriately!
struct timespec ts;
int rc;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5; // Set timeout to 5 seconds from now
uint32_t x;
uint64_t v;
v = upk_u64le(data, 0);
x = upk_u32le(data, 8);
if ((x > 32768-1) || (x<1) || x > (unsigned int)(len - 12)) {
DLOG_DEBUG("Invalid coinbaser received! %lu %lu", (unsigned long)x, (unsigned long)(len-12));
return 0;
}
#ifdef __APPLE__
rc = apple_mutex_timedlock(&datum_protocol_coinbaser_fetch_mutex, &datum_protocol_coinbaser_fetch_state, &ts);
#else
rc = pthread_mutex_timedlock(&datum_protocol_coinbaser_fetch_mutex, &ts);
#endif
if (rc != 0) {
DLOG_DEBUG("Could not get a lock on the coinbaser reception mutex after 5 seconds... bug?");
return 0;
}
// mutex is locked
if (datum_coinbaser_v2_response_buf_idx == 0) {
datum_coinbaser_v2_response_buf_idx = 1;
} else {
datum_coinbaser_v2_response_buf_idx = 0;
}
datum_coinbaser_v2_response = datum_coinbaser_v2_response_buf[datum_coinbaser_v2_response_buf_idx];
memcpy(datum_coinbaser_v2_response, &data[12], x);
datum_coinbaser_v2_response_value[datum_coinbaser_v2_response_buf_idx] = v;
datum_coinbaser_v2_response_len[datum_coinbaser_v2_response_buf_idx] = x;
pthread_cond_signal(&datum_protocol_coinbaser_fetch_cond); // Signal the condition variable
#ifdef __APPLE__
apple_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex, &datum_protocol_coinbaser_fetch_state);
#else
pthread_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex);
#endif
return 1;
}
int datum_protocol_coinbaser_fetch(void *sptr) {
// Called by the coinbaser thread to request a coinbase split
// The coinbaser thread expects this to actually result in a processed coinbase split, so we need to churn
// here until that's ready or times out.
T_DATUM_STRATUM_JOB *s = (T_DATUM_STRATUM_JOB *)sptr;
uint64_t value = s->coinbase_value;
unsigned char msg[128 + crypto_box_MACBYTES];
int i = 0, j;
int rc;
struct timespec ts;
s->available_coinbase_outputs_count = 0;
if (value < 31250000) { // mainnet epoch V
return 0;
}
msg[0] = 0x10; i++; // Fetch Coinbaser subcmd
pk_u64le(msg, 1, value); i += 8; // value we have available with this job
// the job's previous block hash. this ensures that the remote end knows which block this payout is related to
// in the event of a chain split.
memcpy(&msg[i], s->prevhash_bin, 32); i+=32;
msg[i] = 0xFE; i++;
// pad
j = 1 + (rand() % 80);
memset(&msg[i], rand(), j);
i+=j;
if (datum_protocol_client_active != 3) {
return 0;
}
datum_protocol_mining_cmd(msg, i);
// spin here for up to 5 seconds while awaiting a coinbaser response from DATUM Prime
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 5; // Set timeout to 5 seconds
#ifdef __APPLE__
apple_mutex_lock(&datum_protocol_coinbaser_fetch_mutex, &datum_protocol_coinbaser_fetch_state);
#else
pthread_mutex_lock(&datum_protocol_coinbaser_fetch_mutex);
#endif
rc = pthread_cond_timedwait(&datum_protocol_coinbaser_fetch_cond, &datum_protocol_coinbaser_fetch_mutex, &ts);
if (rc == ETIMEDOUT) {
#ifdef __APPLE__
apple_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex, &datum_protocol_coinbaser_fetch_state);
#else
pthread_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex);
#endif
DLOG_DEBUG("Timeout waiting for coinbaser response from DATUM Prime");
return 0;
}
if (rc != 0) {
DLOG_DEBUG("Error waiting for coinbaser response from DATUM Prime");
#ifdef __APPLE__
apple_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex, &datum_protocol_coinbaser_fetch_state);
#else
pthread_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex);
#endif
return 0;
}
i = 0;
// process received coinbase
if ((datum_coinbaser_v2_response) && (datum_coinbaser_v2_response_value[datum_coinbaser_v2_response_buf_idx] == value)) {
i = datum_coinbaser_v2_parse(s, datum_coinbaser_v2_response, datum_coinbaser_v2_response_len[datum_coinbaser_v2_response_buf_idx], false);
}
#ifdef __APPLE__
apple_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex, &datum_protocol_coinbaser_fetch_state);
#else
pthread_mutex_unlock(&datum_protocol_coinbaser_fetch_mutex);
#endif
return i;
}
int datum_protocol_ping_response(T_DATUM_PROTOCOL_HEADER *h, unsigned char *data) {
// TODO: Not implemented, but should be done for keepalive
return 1;
}
int datum_protocol_client_configure(int len, unsigned char *data) {
// Server->Client configuration changes. This can be called at any time by the server
// to make updates to these important variables.
int i=0;
unsigned char a;
DLOG_DEBUG("client configuration cmd received from DATUM server");
char msg[1024];
if (i >= len || data[i] != 1) {
err:
DLOG_ERROR("Bad configuration version from server. Is this client up to date?");
return 0;
}
i++;
// read pool addr script
if (i >= len) goto err;
a = data[i]; i++;
if (i + a > len) goto err;
memcpy(datum_config.override_mining_pool_scriptsig, &data[i], a); i+=a;
datum_config.override_mining_pool_scriptsig_len = a;
// prime ID
if (i + 4 > len) goto err;
datum_config.prime_id = upk_u32le(data, i); i+=4;
// pool coinbase tag
if (i >= len) goto err;
a = data[i]; i++;
if (i + a > len) goto err;
memcpy(datum_config.override_mining_coinbase_tag_primary, &data[i], a); i+=a;
datum_config.override_mining_coinbase_tag_primary[a] = 0;
if (i + 8 > len) goto err;
datum_config.override_vardiff_min = upk_u64le(data, i); i+=8;
if (datum_config.override_vardiff_min != roundDownToPowerOfTwo_64(datum_config.override_vardiff_min)) {
DLOG_WARN("Server specified a minimum difficulty that is not a power of two! Is your client up to date? Rounding up to a power of two! (%"PRIu64" to %"PRIu64")", datum_config.override_vardiff_min, roundDownToPowerOfTwo_64(datum_config.override_vardiff_min)<<1);
datum_config.override_vardiff_min = roundDownToPowerOfTwo_64(datum_config.override_vardiff_min)<<1;
}
if (i + 2 > len) goto err;
if ((data[i] != 0) || (data[i+1] != 0xFE)) {
DLOG_ERROR("Invalid data structure in configuration :( Is this client up to date???");
return 0;
}
memset(msg, 0, (datum_config.override_mining_pool_scriptsig_len<<1)+2);
for(i=0;i<datum_config.override_mining_pool_scriptsig_len;i++) {
uchar_to_hex(&msg[i<<1], datum_config.override_mining_pool_scriptsig[i]);
}
DLOG_DEBUG("DATUM Pool Payout Scriptsig: (len %d) %s",datum_config.override_mining_pool_scriptsig_len, msg);
DLOG_DEBUG("DATUM Pool Coinbase Tag: \"%s\"",datum_config.override_mining_coinbase_tag_primary);
DLOG_DEBUG("DATUM Pool Prime ID: %8.8lx", (unsigned long)datum_config.prime_id);
DLOG_DEBUG("DATUM Pool Min Diff: %"PRIu64,datum_config.override_vardiff_min);
datum_state = 3; // fully ready to make work
return 1;
}
int datum_protocol_job_validation_stxlist(unsigned char *data) {
// similar to compact blocks, we're going to send a list of short transaction IDs for the requested job
unsigned char job_index = data[0];
T_DATUM_PROTOCOL_JOB *dj;
T_DATUM_STRATUM_JOB *sj;
T_DATUM_TEMPLATE_DATA *block_template;
unsigned char msg[128*1024];
uint64_t siphash;
unsigned char siphash_key[16];
unsigned char crosscheck[32] = { // starting point for the txn hash crosscheck
0xA3, 0x4F, 0xC1, 0x9C, 0x5E, 0x88, 0x76, 0x12,
0x0A, 0x79, 0x3E, 0xF1, 0x6C, 0x93, 0x54, 0xAF,
0xB8, 0x1D, 0xE8, 0x5A, 0x20, 0xC7, 0x94, 0x38,
0x6F, 0xA1, 0x02, 0xD9, 0x4A, 0x7B, 0xF0, 0x11
};
int i = 0, j;
if (job_index >= 8) {
// error response to 0x50 0x10
msg[i] = 0x50; i++;
msg[i] = 0x90; i++;
msg[i] = 0xFF; i++;
msg[i] = 0xF3; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
pthread_rwlock_rdlock(&datum_jobs_rwlock);
dj = &datum_jobs[job_index];
sj = dj->sjob;
if (!sj) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x10
msg[i] = 0x50; i++;
msg[i] = 0x90; i++;
msg[i] = job_index; i++;
msg[i] = 0xF0; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
block_template = sj->block_template;
if (!block_template) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x10
msg[i] = 0x50; i++;
msg[i] = 0x90; i++;
msg[i] = job_index; i++;
msg[i] = 0xF1; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
if (block_template->txn_count == 0) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// there are no transactions in this block...
// normal response, except our tx count is 0
// since tx count = 0, we dont need anything else
msg[i] = 0x50; i++;
msg[i] = 0x90; i++;
msg[i] = job_index; i++;
msg[i] = 0x01; i++;
msg[i++] = 0; msg[i++] = 0;
// no need to send the crosscheck... there's nothing to crosscheck!
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
if (block_template->txn_count > 16383) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x10
msg[i] = 0x50; i++;
msg[i] = 0x90; i++;
msg[i] = job_index; i++;
msg[i] = 0xF2; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
// ok, we're good
msg[i] = 0x50; i++;
msg[i] = 0x90; i++;
msg[i] = job_index; i++;
msg[i] = 0x01; i++;
pk_u16le(msg, i, block_template->txn_count); i += 2;
// we don't have the benefit that compact blocks have of fully having something unknown to an attacker before an attack
// like the block hash. so we'll do the next best thing and use the client's public signing key mixed with the pool's
// as the "key" for siphash
for(j=0;j<16;j++) {
siphash_key[j] = (local_datum_keys.pk_ed25519[j] ^ pool_keys.pk_ed25519[j]) ^ 0x55;
}
for(j=0;j<block_template->txn_count;j++) {
siphash = datum_siphash_mod8(block_template->txns[j].hash_bin, 32, siphash_key);
// store 48-bits of the hash in the message
pk_u32le(msg, i, siphash & 0xFFFFFFFF); i += 4;
pk_u16le(msg, i, (siphash >> 32) & 0xFFFF); i += 2;
// keep a running xor of all hashes for a final crosscheck
// not intended to be secure, but is fast enough for an initial server side pass/fail
// should be virtually impossible, due to the search space, to attack anyway
for (int k = 0; k < 0x20; ++k) crosscheck[k] ^= block_template->txns[j].hash_bin[k];
}
// we dont need the template data anymore, unlock!
pthread_rwlock_unlock(&datum_jobs_rwlock);
// cap off the message with the running XOR
memcpy(&msg[i], &crosscheck[0], 0x20); i += 0x20;
msg[i] = 0xFE; i++;
// pad with some randomness
j = 1 + (rand() % 111);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i); // let 'er rip
DLOG_DEBUG("sent short txn list to server for job %d (%d bytes)",job_index,i);
return 1;
}
int datum_protocol_job_validation_stxlist_byid(unsigned char *data) {
// the server is requesting missing transactions
// send them
unsigned char job_index = data[0];
uint16_t req_count = upk_u16le(data, 1);
T_DATUM_PROTOCOL_JOB *dj;
T_DATUM_STRATUM_JOB *sj;
T_DATUM_TEMPLATE_DATA *block_template;
unsigned char *msg = &temp_data[0]; // global temp var for constructing messages within the datum protocol thread
uint16_t req_id;
int i = 0, j,k=3;
if (job_index >= 8) {
// error response to 0x50 0x11
msg[i] = 0x50; i++;
msg[i] = 0x91; i++;
msg[i] = 0xFF; i++;
msg[i] = 0xF3; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
pthread_rwlock_rdlock(&datum_jobs_rwlock);
dj = &datum_jobs[job_index];
sj = dj->sjob;
if (!sj) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x11
msg[i] = 0x50; i++;
msg[i] = 0x91; i++;
msg[i] = job_index; i++;
msg[i] = 0xF0; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
block_template = sj->block_template;
if (!block_template) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x11
msg[i] = 0x50; i++;
msg[i] = 0x91; i++;
msg[i] = job_index; i++;
msg[i] = 0xF1; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
if ((req_count == 0) || (req_count > block_template->txn_count)) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x11
msg[i] = 0x50; i++;
msg[i] = 0x91; i++;
msg[i] = job_index; i++;
msg[i] = 0xF4; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
// ok, make it happen.
msg[i] = 0x50; i++;
msg[i] = 0x91; i++;
msg[i] = job_index; i++;
msg[i] = 0x01; i++;
pk_u16le(msg, i, req_count); i += 2;
for(j=0;j<req_count;j++) {
req_id = upk_u16le(data, k); k += 2;
if (req_id >= block_template->txn_count) {
// error....
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x11
i = 0; // reset index
msg[i] = 0x50; i++;
msg[i] = 0x91; i++;
msg[i] = job_index; i++;
msg[i] = 0xF4; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
// size is stored as 3 bytes for consistency.
// this is technically redundant, as the server can derive this by decoding the transaction
// however, we're future-proofing just a little here for a tiny bit of overhead.
pk_u16le(msg, i, ((uint32_t)(block_template->txns[req_id].size) & 0xFFFF)); i += 2;
msg[i] = (uint16_t)((block_template->txns[req_id].size >> 16) & 0xFF); i++;
memcpy(&msg[i], block_template->txns[req_id].txn_data_binary, block_template->txns[req_id].size);
i += block_template->txns[req_id].size;
}
// done with the job.
pthread_rwlock_unlock(&datum_jobs_rwlock);
msg[i] = 0xFE; i++;
// pad with some randomness
j = 1 + (rand() % 111);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i); // let 'er rip
DLOG_DEBUG("sent full txns to server for job %d (%d bytes for %d txns)",job_index,i,(int)req_count);
return 1;
}
int datum_protocol_job_validation_sblock(unsigned char *data) {
// the server decided our template probably is too unique from what it knows about, or was
// otherwise not able to validate the block using faster negotiations.
// It would like us to just send the entire transaction blob for validation as-is.
// This is reasonable and required. The server should already have the rest of the data needed
// to construct a block to fully validate.
unsigned char job_index = data[0];
T_DATUM_PROTOCOL_JOB *dj;
T_DATUM_STRATUM_JOB *sj;
T_DATUM_TEMPLATE_DATA *block_template;
unsigned char *msg = &temp_data[0]; // global temp var for constructing messages within the datum protocol thread
int i = 0, j;
if (job_index >= 8) {
// error response to 0x50 0x12
msg[i] = 0x50; i++;
msg[i] = 0x92; i++;
msg[i] = 0xFF; i++;
msg[i] = 0xF3; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
pthread_rwlock_rdlock(&datum_jobs_rwlock);
dj = &datum_jobs[job_index];
sj = dj->sjob;
if (!sj) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x12
msg[i] = 0x50; i++;
msg[i] = 0x92; i++;
msg[i] = job_index; i++;
msg[i] = 0xF0; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
block_template = sj->block_template;
if (!block_template) {
pthread_rwlock_unlock(&datum_jobs_rwlock);
// error response to 0x50 0x12
msg[i] = 0x50; i++;
msg[i] = 0x92; i++;
msg[i] = job_index; i++;
msg[i] = 0xF1; i++;
// pad with some randomness
j = 1 + (rand() % 100);
memset(&msg[i], rand(), j);
i+=j;
datum_protocol_mining_cmd(msg, i);
return 1;
}
msg[i] = 0x50; i++;
msg[i] = 0x92; i++;
msg[i] = job_index; i++;
msg[i] = 0x01; i++;
pk_u16le(msg, i, block_template->txn_count); i += 2;
for(j=0;j<block_template->txn_count;j++) {
// size is stored as 3 bytes for consistency.
// this is technically redundant, as the server can derive this by decoding the transaction
// however, we're future-proofing just a little here for a tiny bit of overhead.
// since the block data must be < 4MB, max 16384 txns, this adds at most 50KB, which fits in our 2^22 byte send max
pk_u16le(msg, i, ((uint32_t)(block_template->txns[j].size) & 0xFFFF)); i += 2;
msg[i] = (uint16_t)((block_template->txns[j].size >> 16) & 0xFF); i++;
// dump the raw txn in
memcpy(&msg[i], block_template->txns[j].txn_data_binary, block_template->txns[j].size);
i += block_template->txns[j].size;
}
pthread_rwlock_unlock(&datum_jobs_rwlock);
msg[i] = 0xFE; i++;
// no random data here for size safety. this is also already expensive, potentially taking seconds to transmit.
datum_protocol_mining_cmd(msg, i); // let 'er rip
DLOG_DEBUG("sent full block of txns to server for job %d (%d bytes)",job_index,i);
return 1;
}
int datum_protocol_job_validation_cmd(int len, unsigned char *data) {
unsigned char cmd = data[0];
unsigned char *p = data;
if (len < 2) return 0;
p++;
// sub sub cmd
switch (cmd) {
case 0x10: {
// send short txn list
return datum_protocol_job_validation_stxlist(p);
break;
}
case 0x11: {
// send the requested txns
// 16-bit indexes
return datum_protocol_job_validation_stxlist_byid(p);
break;
}
case 0x12: {
// send the entire block, except the coinbase txn
return datum_protocol_job_validation_sblock(p);
break;
}
// TODO: Implement a job differences mechanism to save bandwidth on new work vs stxids
default: break;
}
return 1;
}
// TODO: Ensure all shares are responded to! Currently this has no bearing on anything, just logging
int datum_protocol_share_response(int len, unsigned char *data) {
if (len < 9) {
DLOG_DEBUG("Invalid share response received!");
return 0;
}
if (data[0] == DATUM_POW_SHARE_RESPONSE_REJECTED) {
DLOG_DEBUG("DATUM server rejected our share! Reason code: %d / TargetPOT: %2.2x / Job ID: %d / Nonce: %8.8x",
(int)upk_u16le(data, 1),
data[7], (int)data[8], upk_u32le(data, 3));
datum_rejected_share_count++;
if (data[7] != 0xFF) {
datum_rejected_share_diff += 1<<data[7];
} else {
datum_rejected_share_diff += datum_config.override_vardiff_min;
}
return 1;
}
if ((data[0] != DATUM_POW_SHARE_RESPONSE_ACCEPTED) && (data[0] != DATUM_POW_SHARE_RESPONSE_ACCEPTED_TENTATIVELY)) {
DLOG_DEBUG("Unknown share response %2.2x. Your client may need to be upgraded!", data[0]);
return 1;
}
// share accepted
DLOG_DEBUG("Share accepted: NONCE: %8.8lx / TargetPOT: %2.2x / Job ID: %d", (unsigned long)upk_u32le(data, 3),
data[7], (int)data[8]);
datum_accepted_share_count++;
datum_accepted_share_diff += 1<<data[7];
datum_last_accepted_share_tsms = datum_protocol_mainloop_tsms;
return 1;
}
// Main mining related command. Has sub commands
int datum_protocol_mining_cmd5(T_DATUM_PROTOCOL_HEADER *h, unsigned char *data) {
if (!h->cmd_len) return 0;
switch(*data) {
case 0x99: {
if (!h->is_signed) {
DLOG_ERROR("Received unsigned client configuration from DATUM server!");
return 0;
}
return datum_protocol_client_configure(h->cmd_len-1, &data[1]);
break;
}
case 0x11: {
// Coinbaser response!
return datum_protocol_coinbaser_fetch_response(h->cmd_len-1, &data[1]);
break;
}
case 0x50: {
// Job validation commands
return datum_protocol_job_validation_cmd(h->cmd_len-1, &data[1]);
break;
}
case 0x8F: {
// share response
return datum_protocol_share_response(h->cmd_len-1, &data[1]);
break;
}
case 0xF9: {
// Server says we should check for a new block template immediately
DLOG_DEBUG("DATUM server blocknotify");
datum_blocktemplates_notifynew(NULL, 0);
return 1;
break;
}
default: {
DLOG_WARN("Received unknown mining command %2.2X from DATUM Server. Perhaps you need to upgrade this DATUM Gateway?", *data);
return 0;
}
}
return 0;
}