This repository has been archived by the owner on Sep 27, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.cpp
executable file
·2559 lines (2344 loc) · 96.9 KB
/
main.cpp
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
#define _FILE_OFFSET_BITS 64 // needs to be defined first
#include <atomic> // needed for atomic
#include <ctime> // needed for time_t
#include <fcntl.h> // needed fot fcntl
#include <fstream> // needed for ifstream
#include <iostream>
#include <limits.h>
#include <mutex> // needed for mutex
#include <string>
#include <signal.h> // needed for SignalHandler
#include <thread> // needed for thread
#include <unistd.h> // needed for readlink and lseek64
#include <sys/socket.h>
#ifdef __linux__
#include <sys/statfs.h> // needed for statfs // not working on macos
#include <sys/stat.h>
#endif
#include <sys/mman.h> // needed for mmap and munmap
#include <sys/types.h> // needed for lseek64
#include <errno.h> //For errno - the error number
#include <netdb.h> //hostent
#include <arpa/inet.h>
#include <experimental/filesystem>
#ifdef __APPLE__
#include <libproc.h> // mac: needed for proc_pidpath
#endif
#include "json.hpp"
// use c library
extern "C"
{
#include "picohttpparser.h"
#include "sph_shabal.h"
};
#include "consoleColor.h"
#ifndef INVALID_SOCKET
const int INVALID_SOCKET = -1;
const int SOCKET_ERROR = -1;
const int INVALID_HANDLE_VALUE = -1;
#endif
#ifndef lseek64
#define lseek64(handle,offset,whence) lseek(handle,offset,whence)
#endif
/*#ifdef __AVX2__
char const *const version = "v1.170820_AVX2";
#elif __AVX__
char const *const version = "v1.170820_AVX";
#else*/
char const *const version = "v1.170820";
//#endif
// needed for lseek64
#ifndef _LARGEFILE64_SOURCE
#define _LARGEFILE64_SOURCE
#endif
enum class MinerMode
{
unknown = 0,
solo,
pool
};
std::string MinerModeToStr(MinerMode mode)
{
switch (mode)
{
case MinerMode::solo:
return "solo";
case MinerMode::pool:
return "pool";
default:
return "unknown";
}
}
uint64_t GetFileSize(std::string path)
{
struct stat stat_buf;
if (stat(path.c_str(), &stat_buf) != 0) // |TODO maybe use stat64 for very large files
{
// error happens, just quits here
console::SetColor(console::color::FG_RED);
std::cout << "[GetFileSize] Error could not run stat: " << std::strerror(errno) << std::endl;
console::SetColor(console::color::RESET);
return 0;
}
return stat_buf.st_size;
}
bool GetAvailableSpace(const char* path, uint32_t &spc, uint32_t §or_size, uint32_t &free_blocks, uint32_t &total_blocks)
{
struct statfs statfs_buf;
if (statfs(path, &statfs_buf) != 0)
{
// error happens, just quits here
console::SetColor(console::color::FG_RED);
std::cout << "[GetAvailableSpace] Error could not run statfs: " << std::strerror(errno) << std::endl;
console::SetColor(console::color::RESET);
return false;
}
// \TODO find equivalent for sectors per cluster (spc)
sector_size = statfs_buf.f_bsize;
free_blocks = statfs_buf.f_bfree;
total_blocks = statfs_buf.f_blocks;
// the available size is f_bsize * f_bavail
return true;
}
// required options
MinerMode mode; //!< The mode of the miner
std::string server_address; //!< The ip-address or hostname of the server
std::string server_ip; //!< The resolved ip-address of the server
std::string server_port; //!< The port of the server
std::string updater_address;
std::string updater_ip;
std::string updater_port;
std::string info_address;
std::string info_port;
std::vector<std::string> plot_paths; //!< Vector of paths to plotfiles
uint64_t total_plotfile_size = 0;
uint64_t cache_size;
size_t update_interval;
size_t send_interval;
uint64_t target_deadline;
// optional options
bool use_debug = false;
bool use_hdd_wakeup = false;
bool enable_proxy = false;
bool show_winner = false;
uint16_t proxy_port = 0;
std::string passphrase;
// info
uint8_t network_quality = 100;
// data
uint64_t block_height = 0;
uint64_t base_target = 0;
std::string signature;
std::string signature_str;
std::string old_signature;
uint64_t target_deadline_info;
uint32_t scoop; //!< \TODO or uint16_t??
uint64_t deadline;
uint64_t my_target_deadline = std::numeric_limits<uint64_t>::max(); // 4294967295;
std::chrono::system_clock::time_point cur_time;
// \TODO remove u_long
std::map <u_long, uint64_t> satellite_size;
// structs
struct Plotfile
{
std::string path;
std::string name;
uint64_t size;// = 0;
uint64_t key;
uint64_t start_nonce;
uint64_t nonces;
uint64_t stagger;
};
struct WorkerProgress
{
size_t number;
uint64_t reads_bytes;
bool is_alive;
};
struct Share
{
std::string file_name;
uint64_t account_id;// = 0;
uint64_t best;// = 0;
uint64_t nonce;// = 0;
};
struct Session
{
#ifdef __WIN32
SOCKET Socket;
#elif defined(__linux__) || defined(__APPLE__)
int socket;
#endif
uint64_t deadline;
Share body;
};
struct Best
{
uint64_t account_id;// = 0;
uint64_t best;// = 0;
uint64_t nonce;// = 0;
uint64_t deadline;// = 0;
uint64_t target_deadline;// = 0;
};
// best related stuff
std::vector<Best> bests;
// share related stuff
std::vector<Share> shares;
// session related stuff
std::vector<Session> sessions;
// thread related stuff
volatile std::atomic<bool> stop_all_threads;
std::thread updater_thread;
volatile std::atomic<bool> stop_local_threads;
std::vector<std::thread> worker_threads;
std::vector<WorkerProgress> worker_progress;
//std::mutex shutdown_all_mutex;
// mutexes
std::mutex bests_mutex;
std::mutex sessions_mutex;
std::mutex shares_mutex;
std::mutex signature_mutex;
std::string GetExePath()
{
std::string path = "";
#ifdef __APPLE__
pid_t pid = getpid();
char result[PROC_PIDPATHINFO_MAXSIZE];
ssize_t count = proc_pidpath (pid, result, sizeof(result));
#elif __linux__
char result[ PATH_MAX ];
ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
#endif
path = std::string(result, (count > 0) ? count : 0);
path = path.substr(0, path.find_last_of("/\\"));
return path;
}
const std::string HostnameToIP(const std::string hostname)
{
int sockfd;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *h;
int rv;
std::string ip;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
hints.ai_socktype = SOCK_STREAM;
if ( (rv = getaddrinfo( hostname.c_str() , "http" , &hints , &servinfo)) != 0)
{
console::SetColor(console::color::FG_RED);
std::cout << "[HostnameToIP] Error: getaddrinfo: " << gai_strerror(rv) << std::endl;
console::SetColor(console::color::RESET);
return "";
}
// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
h = (struct sockaddr_in *) p->ai_addr;
ip = std::string(inet_ntoa( h->sin_addr ));
if(ip.compare("0.0.0.0") != 0)
{
return ip;
}
}
freeaddrinfo(servinfo); // all done with this structure
return std::string(ip);
}
bool LoadConfig(std::string file)
{
std::ifstream config_file(file.c_str());
bool ret = false;
if (config_file.is_open())
{
nlohmann::json config;
config_file >> config;
config_file.close();
if(config.is_object())
{
uint8_t errors = 0;
// check mode
if(config["Mode"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Mode\" of the miner!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["Mode"].is_string())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Mode\" as string!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
if(config["Mode"] == "solo")
{
mode = MinerMode::solo;
}
else if(config["Mode"] == "pool")
{
mode = MinerMode::pool;
}
else
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error the specified \"Mode\" "<< config["Mode"] <<" is invalid!\n";
console::SetColor(console::color::RESET);
++errors;
}
}
// check server ip
if(config["Server"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Server\" hostname or ip-address!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["Server"].is_string())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Server\" hostname or ip-address as string!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
server_address = config["Server"];
}
// check server port
if(config["Port"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Port\" of the server!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["Port"].is_number())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Port\" of the server as a number!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
uint16_t port = config["Port"];
server_port = std::to_string(port);
}
// check Plotfile paths
if(config["Paths"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Paths\" to your plotfiles!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["Paths"].is_array())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"Paths\" as an array/list!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
for (auto& path : config["Paths"])
{
plot_paths.push_back(path);
}
}
// check cache size \TODO Is it optional?
if(config["CacheSize"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"CacheSize\"!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["CacheSize"].is_number())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"CacheSize\" as a number!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
cache_size = config["CacheSize"];
}
// check use hdd wakeup
if(!config["UseHDDWakeUp"].empty())
{
if(!config["UseHDDWakeUp"].is_boolean())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify \"UseHDDWakeUp\" as a boolean!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
use_hdd_wakeup = config["UseHDDWakeUp"];
}
}
// check send interval
if(config["SendInterval"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"SendInterval\"!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["SendInterval"].is_number())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"SendInterval\" as a number!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
send_interval = config["SendInterval"];
}
// check update interval
if(config["UpdateInterval"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"UpdateInterval\"!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["UpdateInterval"].is_number())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"UpdateInterval\" as a number!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
update_interval = config["UpdateInterval"];
}
// check debug
if(!config["Debug"].empty())
{
if(!config["Debug"].is_boolean())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify \"Debug\" as a boolean!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
use_debug = config["Debug"];
}
}
// check updater address
if(config["UpdaterAddr"].empty())
{
updater_address = server_address;
}
else if(!config["UpdaterAddr"].is_string())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"UpdaterAddr\" as a string!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
updater_address = config["UpdaterAddr"];
}
// check updater port
if(config["UpdaterPort"].empty())
{
updater_port = server_port;
}
else if(!config["UpdaterPort"].is_string())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"UpdaterPort\" as a string!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
updater_port = config["UpdaterPort"];
}
// check info address
if(config["InfoAddr"].empty())
{
info_address = updater_address;
}
else if(!config["InfoAddr"].is_string())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"InfoAddr\" as a string!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
info_address = config["InfoAddr"];
}
// check info port
if(config["InfoPort"].empty())
{
info_port = updater_port;
}
else if(!config["InfoPort"].is_string())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"InfoPort\" as a string!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
info_port = config["InfoPort"];
}
// check enable proxy
if(!config["EnableProxy"].empty())
{
if(!config["EnableProxy"].is_boolean())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify \"EnableProxy\" as a boolean!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
enable_proxy = config["EnableProxy"];
}
}
// check proxy port
if(!config["ProxyPort"].empty())
{
if(!config["ProxyPort"].is_number())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"ProxyPort\" as a number!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
if(!enable_proxy)
{
console::SetColor(console::color::FG_YELLOW);
std::cout << "[loadConfig] Warning \"ProxyPort\" specified, but \"EnableProxy\" disabled.\n";
console::SetColor(console::color::RESET);
}
proxy_port = config["ProxyPort"];
}
}
else if(enable_proxy)
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error no \"ProxyPort\" specified, but \"EnableProxy\" enabled!\n";
console::SetColor(console::color::RESET);
++errors;
}
if (!config["ShowWinner"].empty())
{
if(config["ShowWinner"].is_boolean())
{
show_winner = config["ShowWinner"];
}
else
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify \"ShowWinner\" as a boolean!\n";
console::SetColor(console::color::RESET);
++errors;
}
}
// check target deadline
if(config["TargetDeadline"].empty())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"TargetDeadline\"!\n";
console::SetColor(console::color::RESET);
++errors;
}
else if(!config["TargetDeadline"].is_number())
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error you need to specify the \"TargetDeadline\" as a number!\n";
console::SetColor(console::color::RESET);
++errors;
}
else
{
target_deadline = config["TargetDeadline"];
}
//! \TODO Add UseBoost!
// check if errors occured
if(!errors)
{
ret = true;
}
}
}
else
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error could not open config file \"" << file << "\"!\n";
console::SetColor(console::color::RESET);
}
return ret;
}
bool ReadPassphrase(std::string file)
{
std::ifstream passphrase_file(file.c_str());
bool ret = false;
if (passphrase_file.is_open())
{
std::getline(passphrase_file, passphrase);
passphrase_file.close();
std::transform(passphrase.begin(), passphrase.end(), passphrase.begin(), [](char ch) {
return ch == ' ' ? '+' : ch;
});
while(passphrase.back() == '+')
{
passphrase.pop_back();
}
ret = true;
}
else
{
console::SetColor(console::color::FG_RED);
std::cout << "[loadConfig] Error could not open passphrase file \"" << file << "\"!\n";
console::SetColor(console::color::RESET);
}
return ret;
}
void SplitStringIntoVector(std::string str, char delimiter, std::vector<std::string> &v)
{
size_t pos;
while ((pos = str.find(delimiter)) != std::string::npos)
{
v.push_back(str.substr(0, pos));
str.erase(0, pos + 1);
}
if(str.size()) // don't forget last part after last delimiter
{
v.push_back(str);
}
}
size_t GetPlotfiles(const std::string path, std::vector<Plotfile> &files)
{
size_t count = 0;
const std::experimental::filesystem::directory_iterator end{};
std::experimental::filesystem::directory_iterator fs_iter{};
try
{
fs_iter = std::experimental::filesystem::directory_iterator{path};
}
catch(std::experimental::filesystem::filesystem_error& e)
{
console::SetColor(console::color::FG_YELLOW);
std::cout << "[GetPlotfiles] Warning could not open directory. Reason: " << e.what() << std::endl;
console::SetColor(console::color::RESET);
return 0;
}
while(fs_iter != end)
{
if( std::experimental::filesystem::is_regular_file(*fs_iter) || std::experimental::filesystem::is_other(*fs_iter) )
{
std::string filename = fs_iter->path().filename().string();
std::vector<std::string> split_filename;
SplitStringIntoVector(filename, '_', split_filename);
if(split_filename.size() == 4)
{
try
{
std::string tmp_file_path = fs_iter->path().string();
tmp_file_path = tmp_file_path.substr(0, tmp_file_path.find_last_of("/\\")+1);
files.push_back(Plotfile{
tmp_file_path,
filename,
// Filesize in bits
//std::experimental::filesystem::file_size(fs_iter->path()), // this does not work for is_other files
GetFileSize(fs_iter->path().string()),
std::stoull(split_filename[0]),
std::stoull(split_filename[1]),
std::stoull(split_filename[2]),
std::stoull(split_filename[3])
});
}
catch(std::invalid_argument& e)
{
console::SetColor(console::color::FG_YELLOW);
std::cout << "[GetPlotfiles] Warning could not convert string to int. Reason: " << e.what() << std::endl;
console::SetColor(console::color::RESET);
}
catch(std::out_of_range& e)
{
console::SetColor(console::color::FG_YELLOW);
std::cout << "[GetPlotfiles] Warning converted string out of the range. Reason: " << e.what() << std::endl;
console::SetColor(console::color::RESET);
}
++count;
}
else
{
//std::cout << "[GetPlotfiles] Warning could not parse filename \"" << filename << "\"\n";
}
}
++fs_iter;
}
return count;
}
void ShutdownAllThreads()
{
stop_all_threads = true;
stop_local_threads = true;
for (std::vector<std::thread>::iterator it = worker_threads.begin() ; it != worker_threads.end(); ++it)
{
if(it->joinable())
{
it->join();
}
}
if(updater_thread.joinable())
{
updater_thread.join();
}
}
int EndMinerWithError()
{
ShutdownAllThreads();
std::cout << "Press enter to continue ...";
std::cin.get();
return 1;
}
// Helper routines taken from http://stackoverflow.com/questions/1557400/hex-to-char-array-in-c
int xdigit( char const digit )
{
int val;
if( '0' <= digit && digit <= '9' )
{
val = digit -'0';
}
else if( 'a' <= digit && digit <= 'f' )
{
val = digit -'a'+10;
}
else if( 'A' <= digit && digit <= 'F' )
{
val = digit -'A'+10;
}
else
{
val = -1;
}
return val;
}
bool HexStr2Str(std::string &out, const std::string in)
{
if( !in.size() )
{
return false; // missing input string
}
size_t inlen = in.size();
if( (inlen % 2) != 0 )
{
inlen--; // hex string must even sized
}
for ( char c : in)
{
if( xdigit(c) < 0 )
{
return false; // bad character in hex string
}
}
out = "";
for(size_t i=0; i<inlen; i+=2)
{
uint8_t both = xdigit(in[i])*16 + xdigit(in[i+1]);
out.push_back(both);
}
out.push_back('\0');
return true;
}
void PollLocal(void)
{
const size_t buffer_size = 1000; // |TODO remove this buffer
char buffer[buffer_size] = {};
int cmd_result = 0;
struct addrinfo hints, *servinfo, *p;
//SOCKET UpdaterSocket = INVALID_SOCKET;
int sockfd;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // also works with ipv6
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(updater_address.c_str(), updater_port.c_str(), &hints, &servinfo) != 0)
{
if (network_quality > 0)
{
network_quality--;
}
// \TODO Show error of errno
//Log("\n*! GMI: getaddrinfo failed with error: "); Log_u(WSAGetLastError());
}
else
{
sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if (sockfd == -1)
{
if (network_quality > 0)
{
network_quality--;
}
// \TODO Show error of errno
//Log("\n*! GMI: socket function failed with error: "); Log_u(WSAGetLastError());
}
else
{
const unsigned timeout = 1000;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
//Log("\n*Connecting to server: "); Log(updateraddr); Log(":"); Log(updaterport);
cmd_result = connect(sockfd, servinfo->ai_addr, (int)servinfo->ai_addrlen);
if (cmd_result == -1)
{
if (network_quality > 0)
{
network_quality--;
}
// \TODO Show error of errno
//Log("\n*! GMI: connect function failed with error: "); Log_u(WSAGetLastError());
}
else
{
int bytes = snprintf(buffer, buffer_size, "POST /burst?requestType=getMiningInfo HTTP/1.0\r\nHost: %s:%s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", server_address.c_str(), server_port.c_str());
cmd_result = send(sockfd, buffer, bytes, 0);
if (cmd_result == -1)
{
if (network_quality > 0)
{
network_quality--;
}
// \TODO Show error of errno
//Log("\n*! GMI: send request failed: "); Log_u(WSAGetLastError());
}
else
{
memset(buffer, 0, buffer_size);
size_t pos = 0;
ssize_t res = 0;
do
{
res = recv(sockfd, &buffer[pos], (int)(buffer_size - pos - 1), 0);
if (res > 0)
{
pos += res;
}
} while (res > 0);
if (res == -1)
{
if (network_quality)
{
network_quality--;
}
// \TODO Show error of errno
//Log("\n*! GMI: get mining info failed:: "); Log_u(WSAGetLastError());
}
else
{
if (network_quality < 100)
{
network_quality++;
}
// \TODO Show in log
//Log("\n* GMI: Received: "); Log_server(buffer);
// locate HTTP header
char *find = strstr(buffer, "\r\n\r\n");
if (find == nullptr)
{
// \TODO Show in log
//Log("\n*! GMI: error message from pool");
}
else
{
//rapidjson::Document gmi;
nlohmann::json gmi;
try
{
gmi = nlohmann::json::parse(find+4);
}
catch(std::invalid_argument e)
{
console::SetColor(console::color::FG_YELLOW);
std::cout << "[PollLocal] Could not parse answer: " << e.what() << std::endl;
console::SetColor(console::color::RESET);
}
//std::cout << std::setw(4) << gmi << std::endl;
if (gmi.is_object())
{
if (!gmi["baseTarget"].empty())
{
if (gmi["baseTarget"].is_string())
{
std::string tmp = gmi["baseTarget"];
base_target = std::stoull(tmp);
}
else
{
if (gmi["baseTarget"].is_number())
{
base_target = gmi["baseTarget"];
}
}
}
if (!gmi["height"].empty())
{
if (gmi["height"].is_string())
{
std::string tmp = gmi["height"];
block_height = std::stoull(tmp);
}
else