forked from VeriBlock/nodecore-pow-cuda-miner
-
Notifications
You must be signed in to change notification settings - Fork 5
/
UCPClient.h
1209 lines (1036 loc) · 38.6 KB
/
UCPClient.h
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
// VeriBlock PoW GPU Miner
// Copyright 2017-2018 VeriBlock, Inc.
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#pragma comment(lib, "Ws2_32.lib")
#ifdef _WIN32
#define _WINSOCKAPI_
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <Windows.h>
#elif __linux__
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#define boolean bool
#define byte uint8_t
#define SOCKET_ERROR -1
#define SOCKADDR_IN sockaddr_in
#define SOCKADDR sockaddr
#define SOCKET int
#endif
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
#include "Constants.h"
#include "Log.h"
#undef min
#undef max
#include "picojson.h"
#define SCK_VERSION2 0x0202
#define UPDATE_FREQUENCY_MS 500.0
#define MESSAGE_BUFFER_SIZE 16 * 1024
#define BLOCK_HASH_SIZE_BYTES 24
#define BLOCK_NUM_SIZE_BYTES 4
#define VERSION_SIZE_BYTES 2
#define PREVIOUS_BLOCK_HASH_SIZE_BYTES 12
#define SECOND_PREVIOUS_BLOCK_HASH_SIZE_BYTES 9
#define THIRD_PREVIOUS_BLOCK_HASH_SIZE_BYTES 9
#define TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES 16
#define MAX_PACKET_DATA 1460
#define VERIBLOCK_BLOCK_HEADER_SIZE 64
// Offset for reading Capability BITFLAG
#define MINING_AUTH_OFFSET 0
#define MINING_SUBSCRIBE_OFFSET 1
#define MINING_SUBMIT_OFFSET 2
#define MINING_UNSUBSCRIBE_OFFSET 3
#define MINING_RESET_ACK_OFFSET 4
#define MINING_MEMPOOL_UPDATE_ACK_OFFSET 5
#define ERROR_INITIAL_SETUP_FAILED -1
using namespace std;
class UCPClient {
string storedHost;
short storedPort;
string storedUsername;
string storedPassword;
int validShares = 0;
int invalidShares = 0;
int sentShares = 0;
int lastAcknowledgement = 0;
boolean successfulConnect = false;
boolean workAvailable = false;
boolean reconnecting = false;
boolean wasDown = false;
unsigned long long lastDowntime = 0;
byte headerToHash[VERIBLOCK_BLOCK_HEADER_SIZE];
unsigned int jobId = 0xFFFFFFFF;
int64_t startExtraNonce = 0xFFFFFFFFFFFFFFFF;
unsigned int encodedDifficulty;
int blockHeight = -1;
string previousBlockHash = "...";
string secondPreviousBlockHash = "...";
string thirdPreviousBlockHash = "...";
string merkleRoot = "...";
char outputBuffer[2048];
byte miningTarget[BLOCK_HASH_SIZE_BYTES];
thread runThread;
SOCKET ucpServerSocket;
private:
enum ServerCommand {
Capabilities,
MiningAuthFailure,
MiningAuthSuccess,
MiningSubscribeFailure,
MiningSubscribeSuccess,
MiningSubmitFailure,
MiningSubmitSuccess,
MiningJob,
MiningMempoolUpdate,
Unsupported,
Invalid
};
void promptExit(int exitCode) {
cout << "Exiting in 10 seconds..." << endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
exit(exitCode);
}
double submitOffset = 2500000;
string getMiningSubmitString(unsigned int jobId, unsigned int timestamp,
unsigned int nonce) {
picojson::object top;
picojson::object requestIdObj;
picojson::object jobIdObj;
picojson::object nTimeObj;
picojson::object nonceObj;
picojson::object extraNonceObj;
top["command"] = picojson::value("MINING_SUBMIT");
requestIdObj["type"] = picojson::value("REQUEST_ID");
requestIdObj["data"] = picojson::value(submitOffset++);
jobIdObj["type"] = picojson::value("JOB_ID");
jobIdObj["data"] = picojson::value((double)jobId);
nTimeObj["type"] = picojson::value("TIMESTAMP");
nTimeObj["data"] = picojson::value((double)timestamp);
nonceObj["type"] = picojson::value("NONCE");
nonceObj["data"] = picojson::value((double)nonce);
extraNonceObj["type"] = picojson::value("EXTRA_NONCE");
extraNonceObj["data"] = picojson::value(startExtraNonce);
top["request_id"] = picojson::value(requestIdObj);
top["job_id"] = picojson::value(jobIdObj);
top["nTime"] = picojson::value(nTimeObj);
top["nonce"] = picojson::value(nonceObj);
top["extra_nonce"] = picojson::value(extraNonceObj);
return picojson::value(top).serialize();
}
string getMiningAuthString(string username, string password) {
picojson::object top;
picojson::object requestIdObj;
picojson::object usernameObj;
picojson::object passwordObj;
top["command"] = picojson::value("MINING_AUTH");
requestIdObj["type"] = picojson::value("REQUEST_ID");
requestIdObj["data"] = picojson::value(1.0);
usernameObj["type"] = picojson::value("USERNAME");
usernameObj["data"] = picojson::value(username);
passwordObj["type"] = picojson::value("PASSWORD");
passwordObj["data"] = picojson::value(password);
top["request_id"] = picojson::value(requestIdObj);
top["username"] = picojson::value(usernameObj);
top["password"] = picojson::value(passwordObj);
return picojson::value(top).serialize();
}
string getMiningSubscribeString() {
picojson::object top;
picojson::object requestIdObj;
picojson::object updateFrequencyMS;
top["command"] = picojson::value("MINING_SUBSCRIBE");
requestIdObj["type"] = picojson::value("REQUEST_ID");
requestIdObj["data"] = picojson::value(2.0);
updateFrequencyMS["type"] = picojson::value("FREQUENCY_MS");
updateFrequencyMS["data"] = picojson::value(UPDATE_FREQUENCY_MS);
top["request_id"] = picojson::value(requestIdObj);
top["update_frequency_ms"] = picojson::value(updateFrequencyMS);
return picojson::value(top).serialize();
}
ServerCommand getCommandType(string line) {
picojson::value jsonMaster;
string err = picojson::parse(jsonMaster, line);
if (!err.empty()) {
snprintf(
outputBuffer, sizeof(outputBuffer),
"An error has been encountered while reading a command! Command: %s",
line.c_str());
cout << outputBuffer << endl;
Log::error(outputBuffer);
return Invalid;
}
if (!jsonMaster.is<picojson::object>()) {
snprintf(outputBuffer, 2048, "Top-level line %s is not a JSON object!",
line.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return Invalid;
}
const picojson::value::object& jsonMasterObj =
jsonMaster.get<picojson::object>();
picojson::value::object::const_iterator jsonCommandIterator =
jsonMasterObj.find("command");
if (jsonCommandIterator != jsonMasterObj.end()) {
picojson::value commandValue = jsonCommandIterator->second;
string command = commandValue.to_str();
if (command.compare("CAPABILITIES") == 0) {
return Capabilities;
} else if (command.compare("MINING_AUTH_FAILURE") == 0) {
return MiningAuthFailure;
} else if (command.compare("MINING_AUTH_SUCCESS") == 0) {
return MiningAuthSuccess;
} else if (command.compare("MINING_SUBSCRIBE_FAILURE") == 0) {
return MiningSubscribeFailure;
} else if (command.compare("MINING_SUBSCRIBE_SUCCESS") == 0) {
return MiningSubscribeSuccess;
} else if (command.compare("MINING_SUBMIT_FAILURE") == 0) {
return MiningSubmitFailure;
} else if (command.compare("MINING_SUBMIT_SUCCESS") == 0) {
return MiningSubmitSuccess;
} else if (command.compare("MINING_JOB") == 0) {
return MiningJob;
} else if (command.compare("MINING_MEMPOOL_UPDATE") == 0) {
return MiningMempoolUpdate;
} else {
return Unsupported;
}
} else {
return Invalid;
}
}
bool setupLoginAndSubscribe(string username, string password) {
char message[MESSAGE_BUFFER_SIZE];
long success = recv(ucpServerSocket, message, sizeof(message),
#ifdef _WIN32
NULL
#else
0
#endif
);
if (success == SOCKET_ERROR) {
#ifdef _WIN32
if (!reconnecting) {
snprintf(outputBuffer, sizeof(outputBuffer),
"Reading from socket during setup resulted in an error %d",
WSAGetLastError());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
closesocket(ucpServerSocket);
WSACleanup();
}
#else
if (!reconnecting) {
snprintf(outputBuffer, sizeof(outputBuffer),
"Reading from socket during setup resulted in an error %d",
success);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
close(ucpServerSocket);
}
#endif
return false;
}
if (getCommandType(message) != Capabilities) {
snprintf(outputBuffer, sizeof(outputBuffer),
"Server did not send its capabilities at the beginning of the "
"setup process! Instead, it sent the command: %s",
message);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
picojson::value capabilitiesCommand;
string err = picojson::parse(capabilitiesCommand, message);
if (!err.empty()) {
snprintf(outputBuffer, sizeof(outputBuffer),
"An error has occurred while attempting to read the server "
"capabilities: %s",
err.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
if (!capabilitiesCommand.is<picojson::object>()) {
snprintf(outputBuffer, sizeof(outputBuffer),
"Provided JSON (%s) does not contain a top-level JSON-object!",
message);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
const picojson::value::object& capabilitiesCommandObj =
capabilitiesCommand.get<picojson::object>();
picojson::value::object::const_iterator capabilitiesIter =
capabilitiesCommandObj.find("capabilities");
if (capabilitiesIter != capabilitiesCommandObj.end()) {
picojson::value capabilitiesSection = capabilitiesIter->second;
const picojson::value::object& capabilitiesObject =
capabilitiesSection.get<picojson::object>();
picojson::value::object::const_iterator capabilitiesInternalIter =
capabilitiesObject.find("data");
if (capabilitiesInternalIter != capabilitiesObject.end()) {
picojson::value bitflagValue = capabilitiesInternalIter->second;
string bitflag = bitflagValue.to_str();
char MINING_AUTH = bitflag[bitflag.length() - 1 - MINING_AUTH_OFFSET];
char MINING_SUBSCRIBE =
bitflag[bitflag.length() - 1 - MINING_SUBSCRIBE_OFFSET];
char MINING_SUBMIT =
bitflag[bitflag.length() - 1 - MINING_SUBMIT_OFFSET];
char MINING_UNSUBSCRIBE =
bitflag[bitflag.length() - 1 - MINING_UNSUBSCRIBE_OFFSET];
char MINING_RESET_ACK =
bitflag[bitflag.length() - 1 - MINING_RESET_ACK_OFFSET];
char MINING_MEMPOOL_UPDATE_ACK =
bitflag[bitflag.length() - 1 - MINING_MEMPOOL_UPDATE_ACK_OFFSET];
boolean capabilitiesCorrect = true;
if (MINING_AUTH != '1') {
capabilitiesCorrect = false;
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server does not support MINING_AUTH according "
"to its bitflag (%s)",
bitflag.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
if (MINING_SUBSCRIBE != '1') {
capabilitiesCorrect = false;
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server does not support MINING_SUBSCRIBE "
"according to its bitflag (%s)",
bitflag.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
if (MINING_SUBMIT != '1') {
capabilitiesCorrect = false;
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server does not support MINING_SUBMIT "
"according to its bitflag (%s)",
bitflag.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
if (MINING_UNSUBSCRIBE != '1') {
capabilitiesCorrect = false;
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server does not support MINING_UNSUBSCRIBE "
"according to its bitflag (%s)",
bitflag.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
if (MINING_RESET_ACK != '1') {
capabilitiesCorrect = false;
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server does not support MINING_RESET_ACK "
"according to its bitflag (%s)",
bitflag.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
if (MINING_MEMPOOL_UPDATE_ACK != '1') {
capabilitiesCorrect = false;
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server does not support "
"MINING_MEMPOOL_UPDATE_ACK according to its bitflag (%s)",
bitflag.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
if (capabilitiesCorrect) {
snprintf(outputBuffer, sizeof(outputBuffer),
"The specified server supports all necessary commands "
"(bitflag: %s)",
bitflag.c_str());
cout << outputBuffer << endl;
Log::info(outputBuffer);
} else {
return false;
}
} else {
snprintf(outputBuffer, sizeof(outputBuffer),
"The server did not send a valid capabilities command!");
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
}
string authenticate = getMiningAuthString(username, password) + "\n";
success = send(ucpServerSocket, authenticate.c_str(),
(int)strlen(authenticate.c_str()), 0);
if (success == SOCKET_ERROR) {
#ifdef _WIN32
snprintf(outputBuffer, sizeof(outputBuffer),
"Sending authentication string failed with error %d",
WSAGetLastError());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
closesocket(ucpServerSocket);
WSACleanup();
#else
snprintf(outputBuffer, sizeof(outputBuffer),
"Sending authentication string failed with error %d", errno);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
close(ucpServerSocket);
#endif
return false;
}
success = recv(ucpServerSocket, message, sizeof(message),
#ifdef _WIN32
NULL
#else
0
#endif
);
if (success == SOCKET_ERROR) {
#ifdef _WIN32
snprintf(
outputBuffer, sizeof(outputBuffer),
"Reading from socket during authentication resulted in an error %d",
WSAGetLastError());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
// closesocket(ucpServerSocket);
// WSACleanup(); // TODO: delete these?
#else
snprintf(
outputBuffer, sizeof(outputBuffer),
"Reading from socket during authentication resulted in an error %d",
errno);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
close(ucpServerSocket);
#endif
return false;
}
if (getCommandType(message) == MiningAuthSuccess) {
snprintf(outputBuffer, sizeof(outputBuffer), "Successfully authenticated to server!");
cout << outputBuffer << endl;
Log::info(outputBuffer);
} else {
picojson::value authenticationResponseCommand;
string err = picojson::parse(authenticationResponseCommand, message);
if (!err.empty()) {
snprintf(outputBuffer, sizeof(outputBuffer),
"An error has occurred while attempting to read the server "
"authentication response: %s",
err.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
if (!authenticationResponseCommand.is<picojson::object>()) {
snprintf(
outputBuffer, sizeof(outputBuffer),
"Provided JSON (%s) does not contain a top-level JSON-object!",
err.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
const picojson::value::object& authenticationResponseCommandObj =
authenticationResponseCommand.get<picojson::object>();
picojson::value::object::const_iterator authenticationResponseIter =
authenticationResponseCommandObj.find("reason");
if (authenticationResponseIter !=
authenticationResponseCommandObj.end()) {
picojson::value reasonValue = authenticationResponseIter->second;
string reason = reasonValue.to_str();
snprintf(outputBuffer, sizeof(outputBuffer),
"Unable to authenticate to the server: %s",
reason.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
} else {
snprintf(outputBuffer, sizeof(outputBuffer),
"The server did not send a valid mining authentication "
"response command!");
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
}
string subscribe = getMiningSubscribeString() + "\n";
success = send(ucpServerSocket, subscribe.c_str(),
(int)strlen(subscribe.c_str()), 0);
if (success == SOCKET_ERROR) {
#ifdef _WIN32
snprintf(outputBuffer, sizeof(outputBuffer),
"Sending subscription string failed with error %d",
WSAGetLastError());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
closesocket(ucpServerSocket);
WSACleanup();
#else
snprintf(outputBuffer, sizeof(outputBuffer),
"Sending subscription string failed with error %d",
errno);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
close(ucpServerSocket);
#endif
return false;
}
success = recv(ucpServerSocket, message, sizeof(message),
#ifdef _WIN32
NULL
#else
0
#endif
);
if (success == SOCKET_ERROR) {
#ifdef _WIN32
snprintf(outputBuffer, sizeof(outputBuffer),
"Reading from socket during subscription resulted in an error %d",
WSAGetLastError());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
closesocket(ucpServerSocket);
WSACleanup();
#else
snprintf(outputBuffer, sizeof(outputBuffer),
"Reading from socket during subscription resulted in an error %d",
errno);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
close(ucpServerSocket);
#endif
return false;
}
if (getCommandType(message) == MiningSubscribeSuccess) {
snprintf(outputBuffer, sizeof(outputBuffer), "Successfully subscribed to server!");
cout << outputBuffer << endl;
Log::info(outputBuffer);
} else {
picojson::value subscriptionResponseCommand;
string err = picojson::parse(subscriptionResponseCommand, message);
if (!err.empty()) {
snprintf(outputBuffer, sizeof(outputBuffer),
"Reading from socket during subscription resulted in an error %s",
err.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
if (!subscriptionResponseCommand.is<picojson::object>()) {
snprintf(outputBuffer, sizeof(outputBuffer),
"Provided JSON (%s) does not contain a top-level JSON-object!",
message);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
const picojson::value::object& subscriptionResponseCommandObj =
subscriptionResponseCommand.get<picojson::object>();
picojson::value::object::const_iterator subscriptionResponseIter =
subscriptionResponseCommandObj.find("reason");
if (subscriptionResponseIter != subscriptionResponseCommandObj.end()) {
picojson::value reasonValue = subscriptionResponseIter->second;
string reason = reasonValue.to_str();
snprintf(outputBuffer, sizeof(outputBuffer), "Unable to subscribe to server: %s",
reason.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
} else {
snprintf(
outputBuffer, sizeof(outputBuffer),
"The server did not send a valid mining subscription response "
"command!");
cerr << outputBuffer << endl;
Log::error(outputBuffer);
return false;
}
}
return true;
}
picojson::value extractDataValueFromJSONById(string JSON, string id) {
JSON.erase(remove(JSON.begin(), JSON.end(), '\n'), JSON.end());
picojson::value command;
string err = picojson::parse(command, JSON);
if (!err.empty()) {
snprintf(outputBuffer,
sizeof outputBuffer,
"An error has occurred while attempting to read the server "
"response: %s",
err.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
throw invalid_argument("Provided JSON (" + JSON + ") is not valid!");
}
if (!command.is<picojson::object>()) {
snprintf(outputBuffer, sizeof outputBuffer,
"Provided JSON (%s) does not contain a top-level JSON-object!",
JSON.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
throw invalid_argument("Provided JSON (" + JSON +
") does not contain an object on its top level!");
}
const picojson::value::object& commandObj = command.get<picojson::object>();
picojson::value::object::const_iterator jobIdIter = commandObj.find(id);
if (jobIdIter != commandObj.end()) {
picojson::value jobIdSection = jobIdIter->second;
const picojson::value::object& jobIdSectionObject =
jobIdSection.get<picojson::object>();
picojson::value::object::const_iterator jobIdInternalIter =
jobIdSectionObject.find("data");
if (jobIdInternalIter != jobIdSectionObject.end()) {
picojson::value jobIdValue = jobIdInternalIter->second;
return jobIdValue;
} else {
snprintf(outputBuffer, sizeof outputBuffer,
"The JSON blob (%s) does not contain an id %s!",
JSON.c_str(), id.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
throw invalid_argument("The JSON blob (" + JSON +
") does not contain an id " + id + "!");
}
} else {
snprintf(outputBuffer, sizeof outputBuffer,
"The JSON blob (%s) does not contain an id %s!",
JSON.c_str(), id.c_str());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
throw invalid_argument("The JSON blob (" + JSON +
") does not contain an id " + id + "!");
}
}
int getDataIntFromJSONById(string JSON, string id) {
picojson::value value = extractDataValueFromJSONById(JSON, id);
return (unsigned int)value.get<double>();
}
string getDataStringFromJSONById(string JSON, string id) {
picojson::value value = extractDataValueFromJSONById(JSON, id);
return value.get<string>();
}
string validLowerCaseHex = "0123456789abcdef";
bool isLowerCaseHexCharacter(char toTest) {
return validLowerCaseHex.find(toTest) != string::npos;
}
int getValueFromLowerCaseHex(char toRoute) {
if (!isLowerCaseHexCharacter(toRoute)) {
throw invalid_argument("The provided character " + string(1, toRoute) +
" is not valid!");
}
// Process upper- and lower-case hex with ASCII offsets
if (toRoute >= 48 && toRoute <= 57) {
return toRoute - 48;
} else if (toRoute >= 97 && toRoute <= 102) {
return toRoute - 87;
} else {
throw invalid_argument(
"The provided character " + string(1, toRoute) +
" is invalid and was not rejected in preliminary hex checks!");
}
}
byte extractByteFromHex(string hex, int byteIndex) {
if (hex.length() % 2 != 0) {
throw invalid_argument("Provided hex " + hex + " is not valid!");
}
char hi = tolower(hex.at(byteIndex + 0));
char lo = tolower(hex.at(byteIndex + 1));
if (!isLowerCaseHexCharacter(hi)) {
throw invalid_argument("Hex character " + string(1, hi) +
" is not valid!");
}
if (!isLowerCaseHexCharacter(lo)) {
throw invalid_argument("Hex character " + string(1, lo) +
" is not valid!");
}
int hiVal = getValueFromLowerCaseHex(hi) * 16;
int loVal = getValueFromLowerCaseHex(lo) * 1;
if (hiVal + loVal > 255) {
throw invalid_argument("The provided hex (" + hex + ") at index " +
to_string(byteIndex) + " is not a valid byte!");
}
return (byte)(hiVal + loVal);
}
void fillNull(char* toFill, int length) {
for (int i = 0; i < length; i++) {
toFill[i] = '\0';
}
}
void cyclicRun() {
char message[MESSAGE_BUFFER_SIZE];
char extraMessage[MESSAGE_BUFFER_SIZE];
for (;;) {
// cout << "Cyclic run, our socket is " << ucpServerSocket << "..." << endl;
fillNull(message, MESSAGE_BUFFER_SIZE);
fillNull(extraMessage, MESSAGE_BUFFER_SIZE);
long success = recv(ucpServerSocket, message, sizeof(message),
#ifdef _WIN32
NULL
#else
0
#endif
);
int cursor = success;
boolean check1 = message[cursor - 1] == '\n';
if ((!check1)) {
Log::info(
"Message from server was chopped into multiple packets, reading "
"additional packets...");
}
int check1Count = 0;
while ((!check1)) {
long result=0;
try {
result = recv(ucpServerSocket, message + cursor, sizeof(message)-cursor,
#ifdef _WIN32
NULL
#else
0
#endif
);
} catch (char *e) {
cout << "Exception..." << endl;
// ex
}
if (++check1Count > 5) {
break;
}
cursor += result;
if ((message != nullptr) && (message[0] == '\0')) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
} else {
check1 = message[cursor - 1] == '\n';
}
}
Log::info("Processing command:");
Log::info(message);
if (success == SOCKET_ERROR) {
#ifdef _WIN32
if (!reconnecting) {
snprintf(
outputBuffer, sizeof outputBuffer,
"Reading from socket during normal operations resulted in an "
"error %d, this could be the result of incorrect credentials or an interrupted pool connection.",
WSAGetLastError());
cerr << outputBuffer << endl;
Log::error(outputBuffer);
closesocket(ucpServerSocket);
WSACleanup();
reconnecting = true;
bool success = reconnect();
while (!success) {
cout << "Attempting to reconnect to server..." << endl;
success = reconnect();
}
reconnecting = false;
lastDowntime = time(0);
}
#else
if (!reconnecting) {
snprintf(outputBuffer, sizeof outputBuffer,
"Reading from socket during normal operations resulted in an "
"error %d, this could be the result of incorrect credentials or an interrupted pool connection.",
errno);
cerr << outputBuffer << endl;
Log::error(outputBuffer);
}
#endif
continue;
}
#ifdef _WIN32
// Nothing
#else
if (strlen(message) == 0) {
snprintf(outputBuffer, sizeof outputBuffer, "\033[1;31mServer sent a 0-length message (or reading from socket failed), attempting to reconnect...\033[0m");
cerr << outputBuffer << endl;
Log::error(outputBuffer);
close(ucpServerSocket);
reconnecting = true;
bool success = reconnect();
while (!success) {
snprintf(outputBuffer, sizeof outputBuffer, "\033[1;33mAttempting to reconnect to server...\033[0m");
cerr << outputBuffer << endl;
Log::error(outputBuffer);
success = reconnect();
}
reconnecting = false;
lastDowntime = time(0);
}
#endif
ServerCommand commandType = getCommandType(message);
if (commandType == MiningJob) {
unsigned int blockVersion;
byte previousBlockHashBytes[PREVIOUS_BLOCK_HASH_SIZE_BYTES];
byte
secondPreviousBlockHashBytes[SECOND_PREVIOUS_BLOCK_HASH_SIZE_BYTES];
byte thirdPreviousBlockHashBytes[THIRD_PREVIOUS_BLOCK_HASH_SIZE_BYTES];
byte topLevelMerkleRootBytes[TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES];
unsigned int timestamp;
jobId = getDataIntFromJSONById(message, "job_id");
blockVersion = getDataIntFromJSONById(message, "block_version");
previousBlockHash =
getDataStringFromJSONById(message, "previous_block_hash");
for (int i = BLOCK_HASH_SIZE_BYTES - PREVIOUS_BLOCK_HASH_SIZE_BYTES;
i < BLOCK_HASH_SIZE_BYTES; i++) {
previousBlockHashBytes[i - (BLOCK_HASH_SIZE_BYTES -
PREVIOUS_BLOCK_HASH_SIZE_BYTES)] =
extractByteFromHex(previousBlockHash, i * 2);
}
secondPreviousBlockHash =
getDataStringFromJSONById(message, "second_previous_block_hash");
for (int i =
BLOCK_HASH_SIZE_BYTES - SECOND_PREVIOUS_BLOCK_HASH_SIZE_BYTES;
i < BLOCK_HASH_SIZE_BYTES; i++) {
secondPreviousBlockHashBytes
[i - (BLOCK_HASH_SIZE_BYTES -
SECOND_PREVIOUS_BLOCK_HASH_SIZE_BYTES)] =
extractByteFromHex(secondPreviousBlockHash, i * 2);
}
thirdPreviousBlockHash =
getDataStringFromJSONById(message, "third_previous_block_hash");
for (int i =
BLOCK_HASH_SIZE_BYTES - THIRD_PREVIOUS_BLOCK_HASH_SIZE_BYTES;
i < BLOCK_HASH_SIZE_BYTES; i++) {
thirdPreviousBlockHashBytes[i -
(BLOCK_HASH_SIZE_BYTES -
THIRD_PREVIOUS_BLOCK_HASH_SIZE_BYTES)] =
extractByteFromHex(thirdPreviousBlockHash, i * 2);
}
merkleRoot = getDataStringFromJSONById(message, "merkle_root");
for (int i = 0; i < TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES; i++) {
topLevelMerkleRootBytes[i] = extractByteFromHex(merkleRoot, i * 2);
}
blockHeight = getDataIntFromJSONById(message, "block_index");
timestamp = getDataIntFromJSONById(message, "timestamp");
encodedDifficulty = getDataIntFromJSONById(message, "difficulty");
string miningTargetHex =
getDataStringFromJSONById(message, "mining_target");
for (int i = 0; i < BLOCK_HASH_SIZE_BYTES; i++) {
miningTarget[i] = extractByteFromHex(miningTargetHex, i * 2);
}
picojson::value value =
extractDataValueFromJSONById(message, "extra_nonce_start");
int64_t test = value.get<int64_t>();
startExtraNonce = test;
for (int i = 0; i < 4; i++) {
headerToHash[i] = (blockHeight >> ((3 - i) * 8));
}
for (int i = 0; i < 2; i++) {
headerToHash[i + 4] = (blockVersion >> ((1 - i) * 8));
}
memcpy(headerToHash + 6, previousBlockHashBytes,
PREVIOUS_BLOCK_HASH_SIZE_BYTES);
memcpy(headerToHash + 18, secondPreviousBlockHashBytes,
SECOND_PREVIOUS_BLOCK_HASH_SIZE_BYTES);
memcpy(headerToHash + 27, thirdPreviousBlockHashBytes,
THIRD_PREVIOUS_BLOCK_HASH_SIZE_BYTES);
memcpy(headerToHash + 36, topLevelMerkleRootBytes,
TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES);
for (int i = 0; i < 4; i++) {
headerToHash[52 + i] = (timestamp >> ((3 - i) * 8));
}
for (int i = 0; i < 4; i++) {
headerToHash[56 + i] = (encodedDifficulty >> ((3 - i) * 8));
}
workAvailable = true;
} else if (commandType == MiningMempoolUpdate) {
byte topLevelMerkleRoot[TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES];
string topLevelMerkleRootHex =
getDataStringFromJSONById(message, "new_merkle_root");
for (int i = 0; i < TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES; i++) {
topLevelMerkleRoot[i] =
extractByteFromHex(topLevelMerkleRootHex, i * 2);
}
memcpy(headerToHash + 36, topLevelMerkleRoot,
TOP_LEVEL_MERKLE_ROOT_SIZE_BYTES);
jobId = getDataIntFromJSONById(message, "job_id");
} else if (commandType == MiningSubmitSuccess) {
Log::info("Successfully mined a share!");
validShares++;
lastAcknowledgement = sentShares;
} else if (commandType == MiningSubmitFailure) {
invalidShares++;
string failureReason = getDataStringFromJSONById(message, "reason");
snprintf(outputBuffer, sizeof outputBuffer,
"Submitting a share failed for the following reason: %s",