-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathdatum_stratum.c
More file actions
2292 lines (1952 loc) · 78.5 KB
/
datum_stratum.c
File metadata and controls
2292 lines (1952 loc) · 78.5 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.
*
*/
// Stratum V1 server for providing work to mining hardware supporting Stratum V1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <errno.h>
#include <jansson.h>
#include <inttypes.h>
#include <sys/resource.h>
#include "datum_gateway.h"
#include "datum_stratum.h"
#include "datum_stratum_dupes.h"
#include "datum_jsonrpc.h"
#include "datum_utils.h"
#include "datum_blocktemplates.h"
#include "datum_sockets.h"
#include "datum_conf.h"
#include "datum_coinbaser.h"
#include "datum_submitblock.h"
#include "datum_protocol.h"
T_DATUM_SOCKET_APP *global_stratum_app = NULL;
int stratum_job_next = 0;
T_DATUM_STRATUM_JOB stratum_job_list[MAX_STRATUM_JOBS];
int global_latest_stratum_job_index = -1;
T_DATUM_STRATUM_JOB *global_cur_stratum_jobs[MAX_STRATUM_JOBS] = { 0 };
pthread_rwlock_t stratum_global_job_ptr_lock = PTHREAD_RWLOCK_INITIALIZER;
uint16_t stratum_enprefix = 0;
pthread_rwlock_t stratum_global_latest_empty_stat = PTHREAD_RWLOCK_INITIALIZER;
uint64_t stratum_latest_empty_complete_count = 0;
bool stratum_latest_empty_ready_for_full = 0;
uint64_t stratum_latest_empty_job_index = 0;
uint64_t stratum_latest_empty_sent_count = 0;
// Global counters for total shares from stratum clients
// These counters track all share submissions from connected miners,
// providing accurate statistics for solo mining operations where pool
// share counters would remain at zero.
uint64_t stratum_client_accepted_share_count = 0;
uint64_t stratum_client_accepted_share_diff = 0;
uint64_t stratum_client_rejected_share_count = 0;
uint64_t stratum_client_rejected_share_diff = 0;
pthread_rwlock_t need_coinbaser_rwlocks[MAX_STRATUM_JOBS];
bool need_coinbaser_rwlocks_init_done = false;
void stratum_latest_empty_increment_complete(uint64_t index, int clients_notified) {
pthread_rwlock_wrlock(&stratum_global_latest_empty_stat);
if ((stratum_latest_empty_job_index == index) && (!stratum_latest_empty_ready_for_full)) {
stratum_latest_empty_complete_count++;
stratum_latest_empty_sent_count += clients_notified;
}
pthread_rwlock_unlock(&stratum_global_latest_empty_stat);
}
bool stratum_latest_empty_check_ready_for_full(void) {
bool a = false;
pthread_rwlock_rdlock(&stratum_global_latest_empty_stat);
if (stratum_latest_empty_ready_for_full) {
a = true;
}
pthread_rwlock_unlock(&stratum_global_latest_empty_stat);
return a;
}
void datum_stratum_v1_shutdown_all(void) {
int ret;
unsigned int shutdown_threads = 0;
if (!global_stratum_app) {
DLOG_DEBUG("Disconnect request for all stratum clients, but stratum thread is not ready.");
return;
}
for (int tid = 0; tid < global_stratum_app->max_threads; ++tid) {
if (!global_stratum_app->datum_threads[tid].is_active) continue;
ret = pthread_mutex_lock(&global_stratum_app->datum_threads[tid].thread_data_lock);
if (ret != 0) {
DLOG_FATAL("Could not lock mutex for thread data on TID %d: %s", tid, strerror(ret));
panic_from_thread(__LINE__); // Is this panic worthy? should never happen
return;
}
// Send request to gracefully boot all clients from the thread
global_stratum_app->datum_threads[tid].empty_request = true;
shutdown_threads++;
pthread_mutex_unlock(&global_stratum_app->datum_threads[tid].thread_data_lock);
}
DLOG_INFO("Sent disconnect request for all stratum clients to %u threads.", shutdown_threads);
return;
}
// Started as its own pthread during startup
void *datum_stratum_v1_socket_server(void *arg) {
// setup the stratum v1 DATUM socket server
T_DATUM_SOCKET_APP *app;
pthread_t pthread_datum_stratum_socket_server;
int ret;
int i,j;
struct rlimit rlimit;
uint64_t ram_allocated = 0;
DLOG_DEBUG("Stratum V1 server startup");
// Setup the socket "app" for Stratum V1
app = (T_DATUM_SOCKET_APP *)calloc(1,sizeof(T_DATUM_SOCKET_APP));
if (!app) {
DLOG_FATAL("Could not allocate memory for Stratum V1 server app metadata! (%lu bytes)", (unsigned long)sizeof(T_DATUM_SOCKET_APP));
panic_from_thread(__LINE__);
return NULL;
}
ram_allocated += sizeof(T_DATUM_SOCKET_APP);
memset(app, 0, sizeof(T_DATUM_SOCKET_APP));
strcpy(app->name, "Stratum V1 Server");
// setup callbacks
app->init_func = datum_stratum_v1_socket_thread_init;
app->loop_func = datum_stratum_v1_socket_thread_loop;
app->client_cmd_func = datum_stratum_v1_socket_thread_client_cmd;
app->closed_client_func = datum_stratum_v1_socket_thread_client_closed;
app->new_client_func = datum_stratum_v1_socket_thread_client_new;
// set listen port
app->listen_port = datum_config.stratum_v1_listen_port;
// setup limits
app->max_clients_thread = datum_config.stratum_v1_max_clients_per_thread;
app->max_threads = datum_config.stratum_v1_max_threads;
app->max_clients = datum_config.stratum_v1_max_clients;
// Our memory rationale here is to do as few dynamic allocations as possible.
// We'll also never give up this memory, so no heap fragmentation risk.
// allocate memory for DATUM socket thread data
app->datum_threads = (T_DATUM_THREAD_DATA *) calloc(app->max_threads + 1, sizeof(T_DATUM_THREAD_DATA));
if (!app->datum_threads) {
DLOG_FATAL("Could not allocate memory for Stratum V1 server thread pool data! (%lu bytes)", (unsigned long)(sizeof(T_DATUM_THREAD_DATA) * (app->max_threads + 1)));
panic_from_thread(__LINE__);
return NULL;
}
ram_allocated += (sizeof(T_DATUM_THREAD_DATA) * (app->max_threads + 1));
// allocate memory for our per-thread data
// allocate once for the whole chunk, and set the pointers. no need to do tons of calls for a static block of data
app->datum_threads[0].app_thread_data = calloc(app->max_threads + 1, sizeof(T_DATUM_STRATUM_THREADPOOL_DATA));
if (!app->datum_threads[0].app_thread_data) {
DLOG_FATAL("Could not allocate memory for Stratum V1 server thread pool app data! (%lu bytes)", (unsigned long)(sizeof(T_DATUM_STRATUM_THREADPOOL_DATA) * (app->max_threads + 1)));
panic_from_thread(__LINE__);
return NULL;
}
for(i=1;i<app->max_threads;i++) {
app->datum_threads[i].app_thread_data = &((char *)app->datum_threads[0].app_thread_data)[sizeof(T_DATUM_STRATUM_THREADPOOL_DATA)*i];
}
ram_allocated += (sizeof(T_DATUM_STRATUM_THREADPOOL_DATA) * (app->max_threads + 1));
// allocate memory for our per-client data
// we need to allocate this per thread, since max clients could be lower
// so our RAM usage will be based on app->max_threads*app->max_clients_thread, sadly, even if this is higher
// T_DATUM_MINER_DATA
app->datum_threads[0].client_data[0].app_client_data = calloc(((app->max_threads*app->max_clients_thread)+1), sizeof(T_DATUM_MINER_DATA));
if (!app->datum_threads[0].client_data[0].app_client_data) {
DLOG_FATAL("Could not allocate memory for Stratum V1 server per-client data! (%lu bytes)", (unsigned long)(((app->max_threads*app->max_clients_thread)+1) * sizeof(T_DATUM_MINER_DATA)));
panic_from_thread(__LINE__);
return NULL;
}
ram_allocated += ((app->max_threads*app->max_clients_thread)+1) * sizeof(T_DATUM_MINER_DATA);
for(i=0;i<app->max_threads;i++) {
for(j=0;j<app->max_clients_thread;j++) {
if (!((i == 0) && (j == 0))) {
app->datum_threads[i].client_data[j].app_client_data = &((char *)app->datum_threads[0].client_data[0].app_client_data)[((i*app->max_clients_thread)+j) * sizeof(T_DATUM_MINER_DATA)];
}
}
}
// init locks for each job
for (i = 0; i < MAX_STRATUM_JOBS; i++) {
pthread_rwlock_init(&need_coinbaser_rwlocks[i], NULL);
}
need_coinbaser_rwlocks_init_done = true;
// Backup thread for submitting blocks found to our node and additional nodes.
DLOG_DEBUG("Starting submitblock thread");
datum_submitblock_init();
pthread_rwlock_rdlock(&stratum_global_job_ptr_lock);
i = global_latest_stratum_job_index;
pthread_rwlock_unlock(&stratum_global_job_ptr_lock);
// we wait for the block template thread to have work for us before moving on.
if (i < 0) {
DLOG_DEBUG("Waiting for our first job before starting listening server...");
j = 0;
i = global_latest_stratum_job_index;
while(i<0) {
usleep(50000);
pthread_rwlock_rdlock(&stratum_global_job_ptr_lock);
i = global_latest_stratum_job_index;
pthread_rwlock_unlock(&stratum_global_job_ptr_lock);
j++;
if (j > 500 && j % 100 == 1) {
DLOG_ERROR("Did not see an initial stratum job after ~%d seconds. Is your node properly setup?", j / 20);
}
}
}
// start the DATUM socket server
DLOG_DEBUG("Starting listener thread %p",app);
ret = pthread_create(&pthread_datum_stratum_socket_server, NULL, datum_gateway_listener_thread, app);
if (ret != 0) {
DLOG_FATAL("Could not pthread_create for DATUM socket listener!: %s", strerror(ret));
panic_from_thread(__LINE__);
return NULL;
}
DLOG_INFO("Stratum V1 Server Init complete.");
DLOG_DEBUG("%"PRIu64" MB of RAM allocated for Stratum V1 server data.", ram_allocated>>20);
// TODO: If limits are too low, attempt to set our ulimits in case we're allowed to do so but it hasn't been done before executing.
if (!getrlimit(RLIMIT_NOFILE, &rlimit)) {
if (app->max_clients > rlimit.rlim_max) {
DLOG_WARN("*** NOTE *** Max Stratum clients (%llu) exceeds hard open file limit (Soft: %llu / Hard: %llu)", (unsigned long long)app->max_clients, (unsigned long long)rlimit.rlim_cur, (unsigned long long)rlimit.rlim_max);
DLOG_WARN("*** NOTE *** Adjust max open file hard limit or you WILL run into issues before reaching max clients!");
} else if (app->max_clients > rlimit.rlim_cur) {
DLOG_WARN("*** NOTE *** Max Stratum clients (%llu) exceeds open file soft limit (Soft: %llu / Hard: %llu)", (unsigned long long)app->max_clients, (unsigned long long)rlimit.rlim_cur, (unsigned long long)rlimit.rlim_max);
DLOG_WARN("*** NOTE *** You should increase the soft open file limit to prevent issues as you approach max clients!");
}
}
global_stratum_app = app;
while (1) {
// do periodic global stratum things here
// If we're on an empty block waiting for a full one, handle that state transition here.
pthread_rwlock_wrlock(&stratum_global_latest_empty_stat);
if (!stratum_latest_empty_ready_for_full) {
// we're still on an empty wait-for-full
if (stratum_latest_empty_complete_count >= app->datum_active_threads) {
// we are done!
stratum_latest_empty_ready_for_full = true;
DLOG_INFO("Empty work send completed. Sent to %llu clients across %llu threads", (unsigned long long)stratum_latest_empty_sent_count, (unsigned long long)stratum_latest_empty_complete_count);
}
}
pthread_rwlock_unlock(&stratum_global_latest_empty_stat);
usleep(11000);
}
return NULL;
}
int datum_stratum_v1_global_subscriber_count(void) {
int j, kk, ii;
T_DATUM_MINER_DATA *m;
if (!global_stratum_app) return 0;
kk = 0;
for(j=0;j<global_stratum_app->max_threads;j++) {
for(ii=0;ii<global_stratum_app->max_clients_thread;ii++) {
if (global_stratum_app->datum_threads[j].client_data[ii].fd > 0) {
m = global_stratum_app->datum_threads[j].client_data[ii].app_client_data;
if (m->subscribed) kk++;
}
}
}
return kk;
}
// TODO: Make this more accurate by tracking work over a longer period of time per user
double datum_stratum_v1_est_total_th_sec(void) {
double hr;
unsigned char astat;
double thr = 0.0;
T_DATUM_MINER_DATA *m = NULL;
uint64_t tsms;
int j,ii;
if (!global_stratum_app) return 0;
tsms = current_time_millis();
for(j=0;j<global_stratum_app->max_threads;j++) {
for(ii=0;ii<global_stratum_app->max_clients_thread;ii++) {
if (global_stratum_app->datum_threads[j].client_data[ii].fd > 0) {
m = global_stratum_app->datum_threads[j].client_data[ii].app_client_data;
if (m->subscribed) {
astat = m->stats.active_index?0:1; // inverted
hr = 0.0;
if ((m->stats.last_swap_ms > 0) && (m->stats.diff_accepted[astat] > 0)) {
hr = ((double)m->stats.diff_accepted[astat] / (double)((double)m->stats.last_swap_ms/1000.0)) * 0.004294967296; // Th/sec based on shares/sec
}
if (((double)(tsms - m->stats.last_swap_tsms)/1000.0) < 180.0) {
thr += hr;
}
}
}
}
}
return thr;
}
void datum_stratum_v1_socket_thread_client_closed(T_DATUM_CLIENT_DATA *c, const char *msg) {
DLOG_DEBUG("Stratum client connection closed. (%s)", msg);
}
void datum_stratum_v1_socket_thread_client_new(T_DATUM_CLIENT_DATA *c) {
T_DATUM_MINER_DATA * const m = c->app_client_data;
DLOG_DEBUG("New Stratum client connected. %d",c->fd);
// clear miner data for connection
memset(m, 0, sizeof(T_DATUM_MINER_DATA));
m->sdata = (T_DATUM_STRATUM_THREADPOOL_DATA *)c->datum_thread->app_thread_data;
m->stats.last_swap_tsms = m->stats.last_share_tsms;
static uint64_t unique_id_ctr = 0;
m->unique_id = unique_id_ctr++;
// set initial connection time
// if this is the first client on the thread, we won't have a loop_tsms yet
if (m->sdata->loop_tsms > 0) {
m->connect_tsms = m->sdata->loop_tsms;
} else {
m->connect_tsms = current_time_millis();
}
}
void datum_stratum_v1_socket_thread_init(T_DATUM_THREAD_DATA *my) {
T_DATUM_STRATUM_THREADPOOL_DATA *sdata = (T_DATUM_STRATUM_THREADPOOL_DATA *)my->app_thread_data;
pthread_rwlock_rdlock(&stratum_global_job_ptr_lock);
sdata->latest_stratum_job_index = global_latest_stratum_job_index;
sdata->cur_stratum_job = global_cur_stratum_jobs[global_latest_stratum_job_index];
pthread_rwlock_unlock(&stratum_global_job_ptr_lock);
sdata->new_job = false;
sdata->last_sent_job_state = 0;
sdata->next_kick_check_tsms = current_time_millis() + 10000;
// initialize the dupe checker system
datum_stratum_dupes_init(sdata);
}
int datum_stratum_v1_get_thread_subscriber_count(T_DATUM_THREAD_DATA *my) {
int i,c=0;
T_DATUM_MINER_DATA *m;
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
c++;
}
}
return c;
}
bool stratum_job_coinbaser_ready(T_DATUM_STRATUM_THREADPOOL_DATA *sdata, T_DATUM_STRATUM_JOB *job) {
bool a = false;
// backup timeout for coinbaser on these jobs
if ((sdata->loop_tsms > job->tsms) && (sdata->loop_tsms - job->tsms) > 5000) {
// enforce a timeout of 5 seconds on waiting on a coinbaser...
sdata->full_coinbase_ready = false;
return true;
}
pthread_rwlock_rdlock(&need_coinbaser_rwlocks[job->global_index]);
if (!job->need_coinbaser) {
a = true;
}
pthread_rwlock_unlock(&need_coinbaser_rwlocks[job->global_index]);
if (a) {
sdata->full_coinbase_ready = true;
}
return a;
}
void datum_stratum_v1_socket_thread_loop(T_DATUM_THREAD_DATA *my) {
T_DATUM_STRATUM_THREADPOOL_DATA *sdata = (T_DATUM_STRATUM_THREADPOOL_DATA *)my->app_thread_data;
T_DATUM_STRATUM_JOB *job = NULL;
T_DATUM_MINER_DATA *m = NULL;
int i;
bool change_ready = true;
int cnt = 0;
uint64_t tsms,tsms2,tsms3;
// check if the stratum job has been updated
pthread_rwlock_rdlock(&stratum_global_job_ptr_lock);
if (global_latest_stratum_job_index != sdata->latest_stratum_job_index) {
change_ready = true;
if ((sdata->last_was_empty) && (global_cur_stratum_jobs[global_latest_stratum_job_index]->job_state >= JOB_STATE_FULL_PRIORITY_WAIT_COINBASER)) {
// we went from an empty to a coinbaser wait job somehow...
// we don't want to delay our full work blast, however...
if (!stratum_job_coinbaser_ready(sdata,global_cur_stratum_jobs[global_latest_stratum_job_index])) {
// yeah, it's not ready. let's just pretend we didn't see this job yet...
// ... unless it's a different block height and we're somehow _that_ far behind on processing.
// should never happen, but let's be careful.
if (sdata->last_job_height == global_cur_stratum_jobs[global_latest_stratum_job_index]->height) {
change_ready = false;
}
}
}
if (change_ready) {
sdata->cur_stratum_job = global_cur_stratum_jobs[global_latest_stratum_job_index];
sdata->latest_stratum_job_index = global_latest_stratum_job_index;
sdata->new_job = true;
if (sdata->cur_stratum_job->job_state == 2) {
// make sure we dont skip our empty work if job type 2
sdata->last_was_empty = false;
}
sdata->notify_remaining_count = 0; // this is new work
sdata->full_coinbase_ready = false;
sdata->last_job_height = sdata->cur_stratum_job->height;
}
}
pthread_rwlock_unlock(&stratum_global_job_ptr_lock);
sdata->loop_tsms = current_time_millis();
job = sdata->cur_stratum_job;
if (sdata->new_job) {
switch (job->job_state) {
case 1: {
// this is an empty work job. it should be followed up by a full priority job
sdata->full_coinbase_ready = false;
DLOG_DEBUG("Blasting empty work type 1 for thread %d",my->thread_id);
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
send_mining_notify(&my->client_data[i],true,false,true);
cnt++;
}
}
sdata->new_job = false; // we're waiting on a completely new job for the next blast wave
sdata->last_was_empty = true;
stratum_latest_empty_increment_complete(sdata->latest_stratum_job_index, cnt); // we do want to make sure everyone got an empty before a full still
sdata->last_sent_job_state = 1;
break;
}
case 2: {
sdata->full_coinbase_ready = false;
// this is an empty+ job. blast the empty work the first time around
if (!sdata->last_was_empty) {
// blast empty
DLOG_DEBUG("Blasting empty work type 2 for thread %d",my->thread_id);
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
send_mining_notify(&my->client_data[i],true,false,true);
cnt++;
}
}
sdata->last_was_empty = true;
stratum_latest_empty_increment_complete(sdata->latest_stratum_job_index, cnt);
sdata->last_sent_job_state = 2;
break;
} else {
if (stratum_latest_empty_check_ready_for_full()) {
// blast full when all threads ready or timed out
DLOG_DEBUG("Blasting full work for type 2 job thread %d",my->thread_id);
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
send_mining_notify(&my->client_data[i],false,false,false);
}
}
sdata->new_job = false;
sdata->last_was_empty = false;
sdata->last_sent_job_state = 2; // probably should be different, but not sure if needed.
}
}
break;
}
case 3: {
// This is a full work job, no coinbaser wait, and has priority blasting
// it's possible this job gets skipped straight to 4
sdata->full_coinbase_ready = false;
DLOG_DEBUG("Blasting full work for type 3 job thread %d",my->thread_id);
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
send_mining_notify(&my->client_data[i],false,false,false);
}
}
sdata->new_job = false;
sdata->last_was_empty = false;
sdata->last_sent_job_state = 3;
break;
}
case 4: {
// this is a full work job with blast priority once we get our coinbaser
// the coinbaser readiness needs to hide behind a lock specific to the job
sdata->full_coinbase_ready = false;
if (stratum_job_coinbaser_ready(sdata,job)) { // will set sdata->full_coinbase_ready = true if it's really ready. if it times out, it will not.
DLOG_DEBUG("Blasting full work for type 4 job thread %d",my->thread_id);
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
send_mining_notify(&my->client_data[i],false,false,false);
}
}
sdata->new_job = false;
sdata->last_was_empty = false;
sdata->last_sent_job_state = 4;
}
break;
}
case 5: {
sdata->full_coinbase_ready = false;
if (stratum_job_coinbaser_ready(sdata,job)) {
// this is a normal job that normally gets slowly sent out over the course of the work change time until interupted by a new block
if (sdata->last_was_empty) {
// HOWEVER...
// if the last work this thread sent out was empty work, likely due to load or whatever
// then we don't want to delay the sending of full work.
// up until this point, this wasn't a concern, but it could be if load is high and the socket side processing
// takes a long time
// blast out the work NOW
DLOG_DEBUG("Blasting full work for type 5 job thread %d",my->thread_id);
for(i=0;i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed) {
send_mining_notify(&my->client_data[i],false,false,false);
}
}
} else {
// last work was not empty, so we can safely slow things up a bit.
sdata->notify_remaining_count = datum_stratum_v1_get_thread_subscriber_count(my);
if (sdata->notify_remaining_count > 0) {
sdata->notify_last_cid = -1;
sdata->notify_start_time = sdata->loop_tsms;
sdata->notify_delay_per_slot_tsms = ((datum_config.bitcoind_work_update_seconds - 3)*1000) / sdata->notify_remaining_count;
if (!sdata->notify_delay_per_slot_tsms) {
sdata->notify_delay_per_slot_tsms = 1;
}
// loosely stagger based on thread ID as well
sdata->notify_last_time = sdata->loop_tsms - ((sdata->notify_delay_per_slot_tsms / my->app->max_threads) * my->thread_id);
DLOG_DEBUG("Pacing job update for thread %d to %d clients @ %"PRIu64" ms",my->thread_id, sdata->notify_remaining_count, sdata->notify_delay_per_slot_tsms);
}
}
sdata->new_job = false;
sdata->last_was_empty = false;
sdata->last_sent_job_state = 5; // technically might not be "sent" yet, but last processed for sure.
}
break;
}
case 0:
default: {
// Unknown job state...
break;
}
}
}
// slowly send out non-critical work changes
// this prevents bandwidth spikes from the server sending notifies to all clients at once.
// that would be quite wasteful and hard on remote connections.
if (sdata->notify_remaining_count > 0) {
// we have notifies to send
tsms = sdata->loop_tsms - sdata->notify_last_time;
if ((!tsms) || (tsms >= sdata->notify_delay_per_slot_tsms)) {
tsms = tsms / sdata->notify_delay_per_slot_tsms;
if (!tsms) tsms = 1;
for(i=(sdata->notify_last_cid+1);i<my->app->max_clients_thread;i++) {
m = my->client_data[i].app_client_data;
if (my->client_data[i].fd && m->subscribed && m->subscribe_tsms <= sdata->notify_start_time) {
send_mining_notify(&my->client_data[i],false,false,false);
sdata->notify_remaining_count--;
sdata->notify_last_cid = i;
tsms--;
if (!tsms) break;
}
}
if (i==my->app->max_clients_thread) {
sdata->notify_remaining_count = 0;
}
sdata->notify_last_time = sdata->loop_tsms;
}
}
if (sdata->loop_tsms >= sdata->next_kick_check_tsms) {
if ((datum_config.stratum_v1_idle_timeout_no_subscribe > 0) || (datum_config.stratum_v1_idle_timeout_no_share > 0) || (datum_config.stratum_v1_idle_timeout_max_last_work)) {
tsms = 1;
tsms2 = 1;
tsms3 = 1;
if (datum_config.stratum_v1_idle_timeout_no_subscribe > 0) {
tsms = sdata->loop_tsms - (datum_config.stratum_v1_idle_timeout_no_subscribe * 1000);
}
if (datum_config.stratum_v1_idle_timeout_no_share > 0) {
tsms2 = sdata->loop_tsms - (datum_config.stratum_v1_idle_timeout_no_share * 1000);
}
if (datum_config.stratum_v1_idle_timeout_max_last_work > 0) {
tsms3 = sdata->loop_tsms - (datum_config.stratum_v1_idle_timeout_max_last_work * 1000);
}
for(i=0;i<my->app->max_clients_thread;i++) {
if (my->client_data[i].fd) {
m = my->client_data[i].app_client_data;
if (m->subscribed) {
// subscribed
if (m->share_count_accepted > 0) {
// has accepted shares
if (m->stats.last_share_tsms < tsms3) {
DLOG_DEBUG("Kicking client %d/%d (%s) for being idle > %d seconds without submitting any new shares. (connected %.2f, currently %.2f, delta %.2f)",my->thread_id, i, my->client_data[i].rem_host, datum_config.stratum_v1_idle_timeout_max_last_work, (double)m->connect_tsms / (double)1000.0, (double)sdata->loop_tsms/ (double)1000.0, (double)(sdata->loop_tsms - m->connect_tsms) / (double)1000.0);
// boot them!
my->client_data[i].kill_request = true;
my->has_client_kill_request = true;
}
} else {
// no accepted shares
if (m->connect_tsms < tsms2) {
DLOG_DEBUG("Kicking client %d/%d (%s) for being idle > %d seconds without submitting any shares. (connected %.2f, currently %.2f, delta %.2f)",my->thread_id, i, my->client_data[i].rem_host, datum_config.stratum_v1_idle_timeout_no_share, (double)m->connect_tsms / (double)1000.0, (double)sdata->loop_tsms/ (double)1000.0, (double)(sdata->loop_tsms - m->connect_tsms) / (double)1000.0);
// boot them!
my->client_data[i].kill_request = true;
my->has_client_kill_request = true;
}
}
} else {
// not subscribed
if (m->connect_tsms < tsms) {
// boot them!
DLOG_DEBUG("Kicking client %d/%d (%s) for being idle > %d seconds without subscribing. (connected %.2f, currently %.2f, delta %.2f)",my->thread_id, i, my->client_data[i].rem_host, datum_config.stratum_v1_idle_timeout_no_subscribe, (double)m->connect_tsms / (double)1000.0, (double)sdata->loop_tsms/ (double)1000.0, (double)(sdata->loop_tsms - m->connect_tsms) / (double)1000.0);
my->client_data[i].kill_request = true;
my->has_client_kill_request = true;
}
}
}
}
}
sdata->next_kick_check_tsms = sdata->loop_tsms + 11150;
}
}
void send_error_to_client(T_DATUM_CLIENT_DATA *c, uint64_t id, char *e) {
// "e" must be valid JSON string
char s[1024];
snprintf(s, sizeof(s), "{\"error\":%s,\"id\":%"PRIu64",\"result\":null}\n", e, id);
datum_socket_send_string_to_client(c, s);
}
static inline void send_unknown_work_error(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[20,\"unknown-work\",null]");
}
static inline void send_rejected_high_hash_error(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[23,\"high-hash\",null]");
}
static inline void send_rejected_stale(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[21,\"stale-work\",null]");
}
static inline void send_rejected_time_too_old(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[21,\"time-too-old\",null]");
}
static inline void send_rejected_time_too_new(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[21,\"time-too-new\",null]");
}
static inline void send_rejected_stale_block(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[21,\"stale-prevblk\",null]");
}
static inline void send_rejected_hnotzero_error(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[23,\"H-not-zero\",null]");
}
static inline void send_bad_version_error(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[23,\"bad-version\",null]");
}
static inline void send_rejected_duplicate(T_DATUM_CLIENT_DATA *c, uint64_t id) {
send_error_to_client(c, id, "[22,\"duplicate\",null]");
}
uint32_t get_new_session_id(T_DATUM_CLIENT_DATA *c) {
// K.I.S.S. --- Session ID is just the thread ID and client ID, XOR with our constant.
// This will always be unique for every client connected to the server.
// We end up "limited" a little, but sanely:
// --- Max threads: 1,024
// --- Max clients per thread: 4,194,304
//
// Downside to this is it prevents stratum v1 resume, however almost nothing appears to implement this correctly anymore anyway
// TODO: Potentially implement stratum resume if a requested session ID is unique and available
uint32_t i;
i = ((uint32_t)c->cid) & (uint32_t)0x003FFFFF;
i |= ((((uint32_t)c->datum_thread->thread_id)<<22) & (uint32_t)0xFFC00000);
return i ^ 0xB10CF00D; // Feed us the blocks.
}
void reset_vardiff_stats(T_DATUM_CLIENT_DATA *c) {
T_DATUM_MINER_DATA * const m = c->app_client_data;
m->share_count_since_snap = 0;
m->share_diff_since_snap = 0;
m->share_snap_tsms = m->sdata->loop_tsms;
}
void stratum_update_vardiff(T_DATUM_CLIENT_DATA *c, bool no_quick) {
// Should be called at/around a share being accepted?
// before processing a mining notify? (for downward
T_DATUM_MINER_DATA * const m = c->app_client_data;
uint64_t delta_tsms;
uint64_t ms_per_share;
uint64_t target_ms_share;
// if we already have a diff change pending, don't do calcs again
if (m->current_diff != m->last_sent_diff) return;
// don't even bother until we have at least X shares to work with for quick diff
if ((!no_quick) && (m->share_count_since_snap < datum_config.stratum_v1_vardiff_quickdiff_count)) {
return;
}
delta_tsms = m->sdata->loop_tsms - m->share_snap_tsms;
if (!m->share_count_since_snap) {
// no shares since last snap
// is it because our diff is way too high?
if (delta_tsms > 60000) {
// 60s with no shares seems sufficient to bump diff down next round.
m->current_diff = m->current_diff >> 1;
if (m->current_diff < m->forced_high_min_diff) {
m->current_diff = m->forced_high_min_diff;
}
if (m->current_diff < datum_config.stratum_v1_vardiff_min) {
m->current_diff = datum_config.stratum_v1_vardiff_min;
}
reset_vardiff_stats(c);
}
// return either way, since with 0 shares the math below doesn't work.
return;
}
// first, let's check if we're wayyyy out of line on what we want for diff, and respond accordingly
// we need at least 1 second of data
if (delta_tsms < 1000) return;
ms_per_share = delta_tsms / m->share_count_since_snap;
if (!ms_per_share) ms_per_share = 1;
target_ms_share = (uint64_t)60000/(uint64_t)datum_config.stratum_v1_vardiff_target_shares_min;
// we want to target X shares/minute
// that would be 60000/X ms per share on average
// if we're *significantly* faster than this, we'll want to bump diff immediately
if ((!m->quickdiff_active) && (!no_quick) && (ms_per_share < (target_ms_share/(uint64_t)datum_config.stratum_v1_vardiff_quickdiff_delta))) {
// let's say if we're at 64/shares/min or higher, we'll do a quick bump
// reusing this var...
// try to set the difficulty quickly to a value that makes some sense based on how many shares we just saw
delta_tsms = roundDownToPowerOfTwo_64((target_ms_share / ms_per_share) * m->current_diff);
if (delta_tsms < (m->current_diff << 2)) {
delta_tsms = (m->current_diff << 2);
}
m->current_diff = delta_tsms;
// send a special clean=true stratum job to the client
// this will send the new diff also
send_mining_notify(c, true, true, false);
// reset the vardiff stats to start this process over again
reset_vardiff_stats(c);
// nothing else to do
return;
}
// check if we need a diff bump downward
if (ms_per_share > (target_ms_share*2)) {
// adjust diff downward a tick
m->current_diff = m->current_diff >> 1;
if (m->current_diff < m->forced_high_min_diff) {
m->current_diff = m->forced_high_min_diff;
}
if (m->current_diff < datum_config.stratum_v1_vardiff_min) {
m->current_diff = datum_config.stratum_v1_vardiff_min;
}
reset_vardiff_stats(c);
return;
}
// don't bother with looking to bump unless we have 16 shares to work with
if (m->share_count_since_snap < 16) return;
if (ms_per_share < (target_ms_share/2)) {
// adjust diff upward a tick
m->current_diff = m->current_diff << 1;
reset_vardiff_stats(c);
return;
}
// nothing to do yet
return;
}
#define STAT_CYCLE_MS 60000
void stratum_update_miner_stats_accepted(T_DATUM_CLIENT_DATA *c, uint64_t diff_accepted) {
T_DATUM_MINER_DATA * const m = c->app_client_data;
m->stats.diff_accepted[m->stats.active_index?1:0] += diff_accepted;
m->stats.last_share_tsms = m->sdata->loop_tsms;
if (m->sdata->loop_tsms >= (m->stats.last_swap_tsms+STAT_CYCLE_MS)) {
m->stats.last_swap_ms = m->sdata->loop_tsms - m->stats.last_swap_tsms;
m->stats.last_swap_tsms = m->sdata->loop_tsms;
if (m->stats.active_index) {
m->stats.active_index = 0;
m->stats.diff_accepted[0] = 0;
} else {
m->stats.active_index = 1;
m->stats.diff_accepted[1] = 0;
}
}
}
// CAUTION: modname MUST be part of username_s following a tilde
const char *datum_stratum_mod_username(const char *username_s, char * const username_buf, const size_t username_buf_sz, const uint16_t share_rnd, const char * const modname, const size_t modname_len) {
struct datum_username_mod * const umod = datum_username_mods_find(datum_config.stratum_username_mod, modname, modname_len);
if (!umod) return username_s;
struct datum_addr_range *range;
for (range = umod->ranges; ; ++range) {
if (!range->addr) return datum_config.mining_pool_address;
if (share_rnd <= range->max) break;
}
const char * const tilde = &modname[-1];
if (range->addr_len == 0) {
size_t len = tilde - username_s;
if (len >= username_buf_sz) len = username_buf_sz - 1;
memcpy(username_buf, username_s, len);
username_buf[len] = '\0';
return username_buf;
}
const char * const period = strchr(username_s, '.');
if (range->addr_len >= username_buf_sz || !period) {
return range->addr;
}
memcpy(username_buf, range->addr, range->addr_len);
size_t len = tilde - period;
if (len >= username_buf_sz) len = username_buf_sz - 1;
memcpy(&username_buf[range->addr_len], period, len);
username_buf[range->addr_len + len] = '\0';
return username_buf;
}
int client_mining_submit(T_DATUM_CLIENT_DATA *c, uint64_t id, json_t *params_obj) {
// {"params": ["username", "job", "extranonce2", "time", "nonce", "version"], "id": 1, "method": "mining.submit"}
// 0 = username
// 1 = jobid
// 2 = extranonce2
// 3 = ntime
// 4 = nonce
// 5 = version roll (OR with version)
json_t *username;
json_t *job_id;
json_t *extranonce2;
json_t *ntime;
json_t *nonce;
json_t *vroll;
T_DATUM_STRATUM_JOB *job = NULL;
const char *job_id_s;
const char *vroll_s;
const char *username_s;
char username_buf[0x100];
const char *extranonce2_s;
const char *ntime_s;
const char *nonce_s;
uint32_t vroll_uint;
uint16_t g_job_index;
uint32_t bver;
uint32_t ntime_val;
uint32_t nonce_val;
unsigned char coinbase_index = 0;
T_DATUM_STRATUM_COINBASE *cb = NULL;
unsigned char extranonce_bin[12];
unsigned char block_header[80];
unsigned char digest_temp[40]; unsigned char share_hash[40];
unsigned char full_cb_txn[MAX_COINBASE_TXN_SIZE_BYTES];
T_DATUM_MINER_DATA * const m = c->app_client_data;
int i;
bool quickdiff = false;
bool empty_work = false;
bool was_block = false;
char new_notify_blockhash[65];
// 0 = version 4 bytes
// 4 = previous block hash 32 bytes
// 36 = merkle root 32 bytes
// 68 = ntime
// 72 = nbits
// 76 = nonce
// see if this is a real job
job_id = json_array_get(params_obj, 1);
if (!job_id) {
send_unknown_work_error(c,id);
m->share_count_rejected++;
m->share_diff_rejected+=m->last_sent_diff; // guestimate here
return 0;
}
job_id_s = json_string_value(job_id);
if (!job_id_s) {
send_unknown_work_error(c,id);
m->share_count_rejected++;
m->share_diff_rejected+=m->last_sent_diff; // guestimate here
return 0;
}
if (strlen(job_id_s) != 16) {
if ((strlen(job_id_s) == 17) && (job_id_s[0] == 'Q')) {
// was a quick diff change job. discard the Q at the front
job_id_s++;