-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstratifier.c
7123 lines (6180 loc) · 199 KB
/
stratifier.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014-2016 Con Kolivas
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version. See COPYING for more details.
*/
#include "config.h"
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <dirent.h>
#include <fcntl.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include "ckpool.h"
#include "libckpool.h"
#include "bitcoin.h"
#include "sha2.h"
#include "stratifier.h"
#include "uthash.h"
#include "utlist.h"
#define MIN1 60
#define MIN5 300
#define MIN15 900
#define HOUR 3600
#define HOUR6 21600
#define DAY 86400
#define WEEK 604800
/* Consistent across all pool instances */
static const char *workpadding = "000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
static const char *scriptsig_header = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff";
static uchar scriptsig_header_bin[41];
static const double nonces = 4294967296;
/* Add unaccounted shares when they arrive, remove them with each update of
* rolling stats. */
struct pool_stats {
tv_t start_time;
ts_t last_update;
int workers;
int users;
int disconnected;
/* Absolute shares stats */
int64_t unaccounted_shares;
int64_t accounted_shares;
/* Cycle of 32 to determine which users to dump stats on */
uint8_t userstats_cycle;
/* Shares per second for 1/5/15/60 minute rolling averages */
double sps1;
double sps5;
double sps15;
double sps60;
/* Diff shares stats */
int64_t unaccounted_diff_shares;
int64_t accounted_diff_shares;
int64_t unaccounted_rejects;
int64_t accounted_rejects;
/* Diff shares per second for 1/5/15... minute rolling averages */
double dsps1;
double dsps5;
double dsps15;
double dsps60;
double dsps360;
double dsps1440;
double dsps10080;
};
typedef struct pool_stats pool_stats_t;
struct workbase {
/* Hash table data */
UT_hash_handle hh;
int64_t id;
char idstring[20];
ts_t gentime;
tv_t retired;
/* GBT/shared variables */
char target[68];
double diff;
double network_diff;
uint32_t version;
uint32_t curtime;
char prevhash[68];
char ntime[12];
uint32_t ntime32;
char bbversion[12];
char nbit[12];
uint64_t coinbasevalue;
int height;
char *flags;
int transactions;
char *txn_data;
char *txn_hashes;
int merkles;
char merklehash[16][68];
char merklebin[16][32];
json_t *merkle_array;
/* Template variables, lengths are binary lengths! */
char *coinb1; // coinbase1
uchar *coinb1bin;
int coinb1len; // length of above
char enonce1const[32]; // extranonce1 section that is constant
uchar enonce1constbin[16];
int enonce1constlen; // length of above - usually zero unless proxying
int enonce1varlen; // length of unique extranonce1 string for each worker - usually 8
int enonce2varlen; // length of space left for extranonce2 - usually 8 unless proxying
char *coinb2; // coinbase2
uchar *coinb2bin;
int coinb2len; // length of above
/* Cached header binary */
char headerbin[112];
char *logdir;
ckpool_t *ckp;
bool proxy; /* This workbase is proxied work */
};
typedef struct workbase workbase_t;
struct json_params {
json_t *method;
json_t *params;
json_t *id_val;
int64_t client_id;
};
typedef struct json_params json_params_t;
/* Stratum json messages with their associated client id */
struct smsg {
json_t *json_msg;
int64_t client_id;
};
typedef struct smsg smsg_t;
struct user_instance;
struct worker_instance;
struct stratum_instance;
typedef struct user_instance user_instance_t;
typedef struct worker_instance worker_instance_t;
typedef struct stratum_instance stratum_instance_t;
struct user_instance {
UT_hash_handle hh;
char username[128];
int id;
char *secondaryuserid;
bool btcaddress;
/* A linked list of all connected instances of this user */
stratum_instance_t *clients;
/* A linked list of all connected workers of this user */
worker_instance_t *worker_instances;
int workers;
int remote_workers;
double best_diff; /* Best share found by this user */
int64_t shares;
double dsps1; /* Diff shares per second, 1 minute rolling average */
double dsps5; /* ... 5 minute ... */
double dsps60;/* etc */
double dsps1440;
double dsps10080;
tv_t last_share;
tv_t last_decay;
tv_t last_update;
bool authorised; /* Has this username ever been authorised? */
time_t auth_time;
time_t failed_authtime; /* Last time this username failed to authorise */
int auth_backoff; /* How long to reject any auth attempts since last failure */
bool throttled; /* Have we begun rejecting auth attempts */
};
/* Combined data from workers with the same workername */
struct worker_instance {
user_instance_t *user_instance;
char *workername;
/* Number of stratum instances attached as this one worker */
int instance_count;
worker_instance_t *next;
worker_instance_t *prev;
int64_t shares;
double dsps1;
double dsps5;
double dsps60;
double dsps1440;
double dsps10080;
tv_t last_share;
tv_t last_decay;
tv_t last_update;
time_t start_time;
double best_diff; /* Best share found by this worker */
int mindiff; /* User chosen mindiff */
bool idle;
bool notified_idle;
};
typedef struct stratifier_data sdata_t;
typedef struct proxy_base proxy_t;
/* Per client stratum instance == workers */
struct stratum_instance {
UT_hash_handle hh;
int64_t id;
stratum_instance_t *next;
stratum_instance_t *prev;
/* Reference count for when this instance is used outside of the
* instance_lock */
int ref;
char enonce1[36]; /* Fit up to 16 byte binary enonce1 */
uchar enonce1bin[16];
char enonce1var[20]; /* Fit up to 8 byte binary enonce1var */
uint64_t enonce1_64;
int session_id;
int64_t diff; /* Current diff */
int64_t old_diff; /* Previous diff */
int64_t diff_change_job_id; /* Last job_id we changed diff */
double dsps1; /* Diff shares per second, 1 minute rolling average */
double dsps5; /* ... 5 minute ... */
double dsps60;/* etc */
double dsps1440;
double dsps10080;
tv_t ldc; /* Last diff change */
int ssdc; /* Shares since diff change */
tv_t first_share;
tv_t last_share;
tv_t last_decay;
time_t first_invalid; /* Time of first invalid in run of non stale rejects */
time_t upstream_invalid; /* As first_invalid but for upstream responses */
time_t start_time;
char address[INET6_ADDRSTRLEN];
bool node; /* Is this a mining node */
bool subscribed;
bool authorising; /* In progress, protected by instance_lock */
bool authorised;
bool dropped;
bool idle;
int reject; /* Indicator that this client is having a run of rejects
* or other problem and should be dropped lazily if
* this is set to 2 */
int latency; /* Latency when on a mining node */
bool reconnect; /* This client really needs to reconnect */
time_t reconnect_request; /* The time we sent a reconnect message */
user_instance_t *user_instance;
worker_instance_t *worker_instance;
char *useragent;
char *workername;
char *password;
bool messages; /* Is this a client that understands stratum messages */
int user_id;
int server; /* Which server is this instance bound to */
ckpool_t *ckp;
time_t last_txns; /* Last time this worker requested txn hashes */
time_t disconnected_time; /* Time this instance disconnected */
int64_t suggest_diff; /* Stratum client suggested diff */
double best_diff; /* Best share found by this instance */
sdata_t *sdata; /* Which sdata this client is bound to */
proxy_t *proxy; /* Proxy this is bound to in proxy mode */
int proxyid; /* Which proxy id */
int subproxyid; /* Which subproxy */
bool remote; /* Is this a trusted remote server */
};
struct share {
UT_hash_handle hh;
uchar hash[32];
int64_t workbase_id;
};
typedef struct share share_t;
struct proxy_base {
UT_hash_handle hh;
UT_hash_handle sh; /* For subproxy hashlist */
proxy_t *next; /* For retired subproxies */
proxy_t *prev;
int id;
int subid;
/* Priority has the user id encoded in the high bits if it's not a
* global proxy. */
int64_t priority;
bool global; /* Is this a global proxy */
int userid; /* Userid for non global proxies */
double diff;
char url[128];
char auth[128];
char pass[128];
char enonce1[32];
uchar enonce1bin[16];
int enonce1constlen;
int enonce1varlen;
int nonce2len;
int enonce2varlen;
bool subscribed;
bool notified;
int64_t clients; /* Incrementing client count */
int64_t max_clients; /* Maximum number of clients per subproxy */
int64_t bound_clients; /* Currently actively bound clients */
int64_t combined_clients; /* Total clients of all subproxies of a parent proxy */
int64_t headroom; /* Temporary variable when calculating how many more clients can bind */
int subproxy_count; /* Number of subproxies */
proxy_t *parent; /* Parent proxy of each subproxy */
proxy_t *subproxies; /* Hashlist of subproxies sorted by subid */
sdata_t *sdata; /* Unique stratifer data for each subproxy */
bool dead;
};
typedef struct session session_t;
struct session {
UT_hash_handle hh;
int session_id;
uint64_t enonce1_64;
int64_t client_id;
int userid;
time_t added;
char address[INET6_ADDRSTRLEN];
};
#define ID_AUTH 0
#define ID_WORKINFO 1
#define ID_AGEWORKINFO 2
#define ID_SHARES 3
#define ID_SHAREERR 4
#define ID_POOLSTATS 5
#define ID_WORKERSTATS 6
#define ID_BLOCK 7
#define ID_ADDRAUTH 8
#define ID_HEARTBEAT 9
static const char *ckdb_ids[] = {
"authorise",
"workinfo",
"ageworkinfo",
"shares",
"shareerror",
"poolstats",
"workerstats",
"block",
"addrauth",
"heartbeat"
};
static const char *ckdb_seq_names[] = {
"seqauthorise",
"seqworkinfo",
"seqageworkinfo",
"seqshares",
"seqshareerror",
"seqpoolstats",
"seqworkerstats",
"seqblock",
"seqaddrauth",
"seqheartbeat"
};
#define ID_COUNT (sizeof(ckdb_ids)/sizeof(char *))
struct stratifier_data {
ckpool_t *ckp;
char pubkeytxnbin[25];
int pubkeytxnlen;
char donkeytxnbin[25];
int donkeytxnlen;
pool_stats_t stats;
/* Protects changes to pool stats */
mutex_t stats_lock;
/* Serialises sends/receives to ckdb if possible */
mutex_t ckdb_lock;
/* Protects sequence numbers */
mutex_t ckdb_msg_lock;
/* Incrementing global sequence number */
uint64_t ckdb_seq;
/* Incrementing ckdb_ids[] sequence numbers */
uint64_t ckdb_seq_ids[ID_COUNT];
bool ckdb_offline;
bool verbose;
uint64_t enonce1_64;
/* For protecting the hashtable data */
cklock_t workbase_lock;
/* For the hashtable of all workbases */
workbase_t *workbases;
workbase_t *current_workbase;
int workbases_generated;
/* Semaphore to serialise calls to add_base */
sem_t update_sem;
/* Time we last sent out a stratum update */
time_t update_time;
int64_t workbase_id;
int64_t blockchange_id;
int session_id;
char lasthash[68];
char lastswaphash[68];
ckmsgq_t *ssends; // Stratum sends
ckmsgq_t *srecvs; // Stratum receives
ckmsgq_t *ckdbq; // ckdb
ckmsgq_t *sshareq; // Stratum share sends
ckmsgq_t *sauthq; // Stratum authorisations
ckmsgq_t *stxnq; // Transaction requests
int user_instance_id;
stratum_instance_t *stratum_instances;
stratum_instance_t *recycled_instances;
stratum_instance_t *node_instances;
int stratum_generated;
int disconnected_generated;
session_t *disconnected_sessions;
user_instance_t *user_instances;
/* Protects both stratum and user instances */
cklock_t instance_lock;
share_t *shares;
mutex_t share_lock;
int64_t shares_generated;
/* Linked list of block solves, added to during submission, removed on
* accept/reject. It is likely we only ever have one solve on here but
* you never know... */
mutex_t block_lock;
ckmsg_t *block_solves;
/* Generator message priority */
int gen_priority;
int proxy_count; /* Total proxies generated (not necessarily still alive) */
proxy_t *proxy; /* Current proxy in use */
proxy_t *proxies; /* Hashlist of all proxies */
mutex_t proxy_lock; /* Protects all proxy data */
proxy_t *subproxy; /* Which subproxy this sdata belongs to in proxy mode */
};
typedef struct json_entry json_entry_t;
struct json_entry {
json_entry_t *next;
json_entry_t *prev;
json_t *val;
};
/* Priority levels for generator messages */
#define GEN_LAX 0
#define GEN_NORMAL 1
#define GEN_PRIORITY 2
/* For storing a set of messages within another lock, allowing us to dump them
* to the log outside of lock */
static void add_msg_entry(char_entry_t **entries, char **buf)
{
char_entry_t *entry = ckalloc(sizeof(char_entry_t));
entry->buf = *buf;
*buf = NULL;
DL_APPEND(*entries, entry);
}
static void notice_msg_entries(char_entry_t **entries)
{
char_entry_t *entry, *tmpentry;
DL_FOREACH_SAFE(*entries, entry, tmpentry) {
DL_DELETE(*entries, entry);
LOGNOTICE("%s", entry->buf);
free(entry->buf);
free(entry);
}
}
static void info_msg_entries(char_entry_t **entries)
{
char_entry_t *entry, *tmpentry;
DL_FOREACH_SAFE(*entries, entry, tmpentry) {
DL_DELETE(*entries, entry);
LOGINFO("%s", entry->buf);
free(entry->buf);
free(entry);
}
}
static void generate_coinbase(const ckpool_t *ckp, workbase_t *wb)
{
uint64_t *u64, g64, d64 = 0;
sdata_t *sdata = ckp->data;
char header[228];
int len, ofs = 0;
ts_t now;
/* Set fixed length coinb1 arrays to be more than enough */
wb->coinb1 = ckzalloc(256);
wb->coinb1bin = ckzalloc(128);
/* Strings in wb should have been zero memset prior. Generate binary
* templates first, then convert to hex */
memcpy(wb->coinb1bin, scriptsig_header_bin, 41);
ofs += 41; // Fixed header length;
ofs++; // Script length is filled in at the end @wb->coinb1bin[41];
/* Put block height at start of template */
len = ser_number(wb->coinb1bin + ofs, wb->height);
ofs += len;
/* Followed by flag */
len = strlen(wb->flags) / 2;
wb->coinb1bin[ofs++] = len;
hex2bin(wb->coinb1bin + ofs, wb->flags, len);
ofs += len;
/* Followed by timestamp */
ts_realtime(&now);
len = ser_number(wb->coinb1bin + ofs, now.tv_sec);
ofs += len;
/* Followed by our unique randomiser based on the nsec timestamp */
len = ser_number(wb->coinb1bin + ofs, now.tv_nsec);
ofs += len;
wb->enonce1varlen = ckp->nonce1length;
wb->enonce2varlen = ckp->nonce2length;
wb->coinb1bin[ofs++] = wb->enonce1varlen + wb->enonce2varlen;
wb->coinb1len = ofs;
len = wb->coinb1len - 41;
len += wb->enonce1varlen;
len += wb->enonce2varlen;
wb->coinb2bin = ckzalloc(256);
memcpy(wb->coinb2bin, "\x0a\x63\x6b\x70\x6f\x6f\x6c", 7);
wb->coinb2len = 7;
if (ckp->btcsig) {
int siglen = strlen(ckp->btcsig);
LOGDEBUG("Len %d sig %s", siglen, ckp->btcsig);
if (siglen) {
wb->coinb2bin[wb->coinb2len++] = siglen;
memcpy(wb->coinb2bin + wb->coinb2len, ckp->btcsig, siglen);
wb->coinb2len += siglen;
}
}
len += wb->coinb2len;
wb->coinb1bin[41] = len - 1; /* Set the length now */
__bin2hex(wb->coinb1, wb->coinb1bin, wb->coinb1len);
LOGDEBUG("Coinb1: %s", wb->coinb1);
/* Coinbase 1 complete */
memcpy(wb->coinb2bin + wb->coinb2len, "\xff\xff\xff\xff", 4);
wb->coinb2len += 4;
// Generation value
g64 = wb->coinbasevalue;
if (ckp->donvalid) {
d64 = g64 / 200; // 0.5% donation
g64 -= d64; // To guarantee integers add up to the original coinbasevalue
wb->coinb2bin[wb->coinb2len++] = 2; // 2 transactions
} else
wb->coinb2bin[wb->coinb2len++] = 1; // 2 transactions
u64 = (uint64_t *)&wb->coinb2bin[wb->coinb2len];
*u64 = htole64(g64);
wb->coinb2len += 8;
wb->coinb2bin[wb->coinb2len++] = sdata->pubkeytxnlen;
memcpy(wb->coinb2bin + wb->coinb2len, sdata->pubkeytxnbin, sdata->pubkeytxnlen);
wb->coinb2len += sdata->pubkeytxnlen;
if (ckp->donvalid) {
u64 = (uint64_t *)&wb->coinb2bin[wb->coinb2len];
*u64 = htole64(d64);
wb->coinb2len += 8;
wb->coinb2bin[wb->coinb2len++] = sdata->donkeytxnlen;
memcpy(wb->coinb2bin + wb->coinb2len, sdata->donkeytxnbin, sdata->donkeytxnlen);
wb->coinb2len += sdata->donkeytxnlen;
}
wb->coinb2len += 4; // Blank lock
wb->coinb2 = bin2hex(wb->coinb2bin, wb->coinb2len);
LOGDEBUG("Coinb2: %s", wb->coinb2);
/* Coinbase 2 complete */
snprintf(header, 225, "%s%s%s%s%s%s%s",
wb->bbversion, wb->prevhash,
"0000000000000000000000000000000000000000000000000000000000000000",
wb->ntime, wb->nbit,
"00000000", /* nonce */
workpadding);
LOGDEBUG("Header: %s", header);
hex2bin(wb->headerbin, header, 112);
}
static void stratum_broadcast_update(sdata_t *sdata, const workbase_t *wb, bool clean);
static void clear_workbase(workbase_t *wb)
{
free(wb->flags);
free(wb->txn_data);
free(wb->txn_hashes);
free(wb->logdir);
free(wb->coinb1bin);
free(wb->coinb1);
free(wb->coinb2bin);
free(wb->coinb2);
json_decref(wb->merkle_array);
free(wb);
}
/* Remove all shares with a workbase id less than wb_id for block changes */
static void purge_share_hashtable(sdata_t *sdata, const int64_t wb_id)
{
share_t *share, *tmp;
int purged = 0;
mutex_lock(&sdata->share_lock);
HASH_ITER(hh, sdata->shares, share, tmp) {
if (share->workbase_id < wb_id) {
HASH_DEL(sdata->shares, share);
dealloc(share);
purged++;
}
}
mutex_unlock(&sdata->share_lock);
if (purged)
LOGINFO("Cleared %d shares from share hashtable", purged);
}
/* Remove all shares with a workbase id == wb_id being discarded */
static void age_share_hashtable(sdata_t *sdata, const int64_t wb_id)
{
share_t *share, *tmp;
int aged = 0;
mutex_lock(&sdata->share_lock);
HASH_ITER(hh, sdata->shares, share, tmp) {
if (share->workbase_id == wb_id) {
HASH_DEL(sdata->shares, share);
dealloc(share);
aged++;
}
}
mutex_unlock(&sdata->share_lock);
if (aged)
LOGINFO("Aged %d shares from share hashtable", aged);
}
static char *status_chars = "|/-\\";
/* Absorbs the json and generates a ckdb json message, logs it to the ckdb
* log and returns the malloced message. */
static char *ckdb_msg(ckpool_t *ckp, sdata_t *sdata, json_t *val, const int idtype)
{
char *json_msg;
char logname[512];
char *ret = NULL;
uint64_t seqall;
json_set_int(val, "seqstart", ckp->starttime);
json_set_int(val, "seqpid", ckp->startpid);
/* Set the atomically incrementing sequence numbers */
mutex_lock(&sdata->ckdb_msg_lock);
seqall = sdata->ckdb_seq++;
json_set_int(val, "seqall", seqall);
json_set_int(val, ckdb_seq_names[idtype], sdata->ckdb_seq_ids[idtype]++);
mutex_unlock(&sdata->ckdb_msg_lock);
json_msg = json_dumps(val, JSON_COMPACT);
if (unlikely(!json_msg))
goto out;
ASPRINTF(&ret, "%s.%"PRIu64".json=%s", ckdb_ids[idtype], seqall, json_msg);
free(json_msg);
out:
json_decref(val);
snprintf(logname, 511, "%s%s", ckp->logdir, ckp->ckdb_name);
rotating_log(logname, ret);
return ret;
}
static void _ckdbq_add(ckpool_t *ckp, const int idtype, json_t *val, const char *file,
const char *func, const int line)
{
static time_t time_counter;
sdata_t *sdata = ckp->data;
static int counter = 0;
char *json_msg;
time_t now_t;
char ch;
if (unlikely(!val)) {
LOGWARNING("Invalid json sent to ckdbq_add from %s %s:%d", file, func, line);
return;
}
now_t = time(NULL);
if (now_t != time_counter) {
pool_stats_t *stats = &sdata->stats;
char hashrate[16];
/* Rate limit to 1 update per second */
time_counter = now_t;
suffix_string(stats->dsps1 * nonces, hashrate, 16, 3);
ch = status_chars[(counter++) & 0x3];
fprintf(stdout, "\33[2K\r%c %sH/s %.1f SPS %d users %d workers",
ch, hashrate, stats->sps1, stats->users, stats->workers);
fflush(stdout);
}
if (CKP_STANDALONE(ckp))
return json_decref(val);
json_msg = ckdb_msg(ckp, sdata, val, idtype);
if (unlikely(!json_msg)) {
LOGWARNING("Failed to dump json from %s %s:%d", file, func, line);
return;
}
ckmsgq_add(sdata->ckdbq, json_msg);
}
#define ckdbq_add(ckp, idtype, val) _ckdbq_add(ckp, idtype, val, __FILE__, __func__, __LINE__)
static void stratum_add_send(sdata_t *sdata, json_t *val, const int64_t client_id,
const int msg_type);
static void send_node_workinfo(sdata_t *sdata, const workbase_t *wb)
{
stratum_instance_t *client;
ckmsg_t *bulk_send = NULL;
ck_rlock(&sdata->instance_lock);
if (sdata->node_instances) {
json_t *wb_val = json_object();
json_set_int(wb_val, "jobid", wb->id);
json_set_string(wb_val, "target", wb->target);
json_set_double(wb_val, "diff", wb->diff);
json_set_int(wb_val, "version", wb->version);
json_set_int(wb_val, "curtime", wb->curtime);
json_set_string(wb_val, "prevhash", wb->prevhash);
json_set_string(wb_val, "ntime", wb->ntime);
json_set_string(wb_val, "bbversion", wb->bbversion);
json_set_string(wb_val, "nbit", wb->nbit);
json_set_int(wb_val, "coinbasevalue", wb->coinbasevalue);
json_set_int(wb_val, "height", wb->height);
json_set_string(wb_val, "flags", wb->flags);
json_set_int(wb_val, "transactions", wb->transactions);
if (likely(wb->transactions))
json_set_string(wb_val, "txn_data", wb->txn_data);
/* We don't need txn_hashes */
json_set_int(wb_val, "merkles", wb->merkles);
json_object_set_new_nocheck(wb_val, "merklehash", json_deep_copy(wb->merkle_array));
json_set_string(wb_val, "coinb1", wb->coinb1);
json_set_int(wb_val, "enonce1varlen", wb->enonce1varlen);
json_set_int(wb_val, "enonce2varlen", wb->enonce2varlen);
json_set_int(wb_val, "coinb1len", wb->coinb1len);
json_set_int(wb_val, "coinb2len", wb->coinb2len);
json_set_string(wb_val, "coinb2", wb->coinb2);
DL_FOREACH(sdata->node_instances, client) {
ckmsg_t *client_msg;
smsg_t *msg;
json_t *json_msg = json_deep_copy(wb_val);
json_set_string(json_msg, "node.method", stratum_msgs[SM_WORKINFO]);
client_msg = ckalloc(sizeof(ckmsg_t));
msg = ckzalloc(sizeof(smsg_t));
msg->json_msg = json_msg;
msg->client_id = client->id;
client_msg->data = msg;
DL_APPEND(bulk_send, client_msg);
}
json_decref(wb_val);
}
ck_runlock(&sdata->instance_lock);
if (bulk_send) {
ckmsgq_t *ssends = sdata->ssends;
LOGINFO("Sending workinfo to mining nodes");
mutex_lock(ssends->lock);
DL_CONCAT(ssends->msgs, bulk_send);
pthread_cond_signal(ssends->cond);
mutex_unlock(ssends->lock);
}
}
static void send_workinfo(ckpool_t *ckp, sdata_t *sdata, const workbase_t *wb)
{
char cdfield[64];
json_t *val;
sprintf(cdfield, "%lu,%lu", wb->gentime.tv_sec, wb->gentime.tv_nsec);
JSON_CPACK(val, "{sI,ss,ss,ss,ss,ss,ss,ss,ss,sI,so,ss,ss,ss,ss}",
"workinfoid", wb->id,
"poolinstance", ckp->name,
"transactiontree", wb->txn_hashes,
"prevhash", wb->prevhash,
"coinbase1", wb->coinb1,
"coinbase2", wb->coinb2,
"version", wb->bbversion,
"ntime", wb->ntime,
"bits", wb->nbit,
"reward", wb->coinbasevalue,
"merklehash", json_deep_copy(wb->merkle_array),
"createdate", cdfield,
"createby", "code",
"createcode", __func__,
"createinet", ckp->serverurl[0]);
ckdbq_add(ckp, ID_WORKINFO, val);
send_node_workinfo(sdata, wb);
}
static void send_ageworkinfo(ckpool_t *ckp, const int64_t id)
{
char cdfield[64];
ts_t ts_now;
json_t *val;
ts_realtime(&ts_now);
sprintf(cdfield, "%lu,%lu", ts_now.tv_sec, ts_now.tv_nsec);
JSON_CPACK(val, "{sI,ss,ss,ss,ss,ss}",
"workinfoid", id,
"poolinstance", ckp->name,
"createdate", cdfield,
"createby", "code",
"createcode", __func__,
"createinet", ckp->serverurl[0]);
ckdbq_add(ckp, ID_AGEWORKINFO, val);
}
/* Add a new workbase to the table of workbases. Sdata is the global data in
* pool mode but unique to each subproxy in proxy mode */
static void add_base(ckpool_t *ckp, sdata_t *sdata, workbase_t *wb, bool *new_block)
{
workbase_t *tmp, *tmpa, *aged = NULL;
sdata_t *ckp_sdata = ckp->data;
int len, ret;
ts_realtime(&wb->gentime);
wb->network_diff = diff_from_nbits(wb->headerbin + 72);
len = strlen(ckp->logdir) + 8 + 1 + 16 + 1;
wb->logdir = ckzalloc(len);
/* In proxy mode, the wb->id is received in the notify update and
* we set workbase_id from it. In server mode the stratifier is
* setting the workbase_id */
ck_wlock(&sdata->workbase_lock);
ckp_sdata->workbases_generated++;
if (!ckp->proxy)
wb->id = sdata->workbase_id++;
else
sdata->workbase_id = wb->id;
if (strncmp(wb->prevhash, sdata->lasthash, 64)) {
char bin[32], swap[32];
*new_block = true;
memcpy(sdata->lasthash, wb->prevhash, 65);
hex2bin(bin, sdata->lasthash, 32);
swap_256(swap, bin);
__bin2hex(sdata->lastswaphash, swap, 32);
sdata->blockchange_id = wb->id;
}
if (*new_block && ckp->logshares) {
sprintf(wb->logdir, "%s%08x/", ckp->logdir, wb->height);
ret = mkdir(wb->logdir, 0750);
if (unlikely(ret && errno != EEXIST))
LOGERR("Failed to create log directory %s", wb->logdir);
}
sprintf(wb->idstring, "%016lx", wb->id);
if (ckp->logshares)
sprintf(wb->logdir, "%s%08x/%s", ckp->logdir, wb->height, wb->idstring);
/* Is this long enough to ensure we don't dereference a workbase
* immediately? Should be unless clock changes 10 minutes so we use
* ts_realtime */
HASH_ITER(hh, sdata->workbases, tmp, tmpa) {
if (HASH_COUNT(sdata->workbases) < 3)
break;
if (wb == tmp)
continue;
/* Age old workbases older than 10 minutes old */
if (tmp->gentime.tv_sec < wb->gentime.tv_sec - 600) {
HASH_DEL(sdata->workbases, tmp);
aged = tmp;
break;
}
}
HASH_ADD_I64(sdata->workbases, id, wb);
if (sdata->current_workbase)
tv_time(&sdata->current_workbase->retired);
sdata->current_workbase = wb;
ck_wunlock(&sdata->workbase_lock);
if (*new_block)
purge_share_hashtable(sdata, wb->id);
if (!ckp->passthrough)
send_workinfo(ckp, sdata, wb);
/* Send the aged work message to ckdb once we have dropped the workbase lock
* to prevent taking recursive locks */
if (aged) {
send_ageworkinfo(ckp, aged->id);
age_share_hashtable(sdata, aged->id);
clear_workbase(aged);
}
}
/* Mandatory send_recv to the generator which sets the message priority if this
* message is higher priority. Races galore on gen_priority mean this might
* read the wrong priority but occasional wrong values are harmless. */
static char *__send_recv_generator(ckpool_t *ckp, const char *msg, const int prio)
{
sdata_t *sdata = ckp->data;
char *buf = NULL;
bool set;
if (prio > sdata->gen_priority) {
sdata->gen_priority = prio;