sygcpp.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /**
  2. * Thanks PurpleI2P Project for support to writing that code.
  3. *
  4. * IRC: irc.ilita.i2p port 6667 || 303:60d4:3d32:a2b9::3 port 16667
  5. * general channels: #ru and #howtoygg
  6. *
  7. * git: notabug.org/Vort/SimpleYggGen-CPP
  8. *
  9. * developers: acetone, lialh4, orignal, R4SAS, Vort
  10. * developers team, 2020 (c) GPLv3
  11. *
  12. */
  13. #include <x86intrin.h>
  14. #include <string.h> // memcmp
  15. #include <sodium.h> // библиотека libsodium
  16. #include <iostream> // вывод на экран
  17. #include <string>
  18. #include <sstream>
  19. #include <fstream> // файловые потоки
  20. #include <iomanip> // форматированный вывод строк
  21. #include <bitset> // побитовое чтение
  22. #include <vector>
  23. #include <thread> // многопоточность
  24. #include <mutex>
  25. #include <chrono> // для вычисления скорости
  26. #include <ctime>
  27. #ifdef _WIN32 // преобразование в IPv6
  28. #include <ws2tcpip.h>
  29. #else
  30. #include <arpa/inet.h>
  31. #endif
  32. #include "x25519.h"
  33. #include "sha512.h"
  34. #define BLOCKSIZE 10000
  35. //#define SELF_CHECK
  36. ////////////////////////////////////////////////// Заставка
  37. void intro()
  38. {
  39. std::cout <<
  40. std::endl <<
  41. " +----------------------------------------------------------------------------+" << std::endl <<
  42. " | SimpleYggGen C++ |" << std::endl <<
  43. " | libsodium inside: x25519 -> sha512 |" << std::endl <<
  44. " | notabug.org/Vort/SimpleYggGen-CPP |" << std::endl <<
  45. " | |" << std::endl <<
  46. " | developers: acetone, lialh4, orignal, R4SAS, Vort |" << std::endl <<
  47. " | GPLv3 (c) 2020 |" << std::endl <<
  48. " +----------------------------------------------------------------------------+" << std::endl <<
  49. std::endl;
  50. }
  51. ////////////////////////////////////////////////// Суть вопроса
  52. std::mutex mtx;
  53. int conf_proc = 0;
  54. int conf_mode = 0;
  55. int conf_log = 0;
  56. int conf_high = 0;
  57. std::string conf_search;
  58. std::string log_file;
  59. std::time_t sygstartedin = std::time(NULL); // для вывода времени работы
  60. int countsize = 0; // определяет периодичность вывода счетчика
  61. uint64_t block_count = 0; // количество вычисленных блоков
  62. uint64_t totalcountfortune = 0; // счетчик нахождений
  63. std::chrono::steady_clock::duration blocks_duration(0);
  64. int config()
  65. {
  66. std::ifstream conffile ("sygcpp.conf");
  67. if(!conffile) // проверка наличия конфига
  68. {
  69. std::cout << " Configuration file not found..." << std::endl;
  70. conffile.close();
  71. std::ofstream newconf ("sygcpp.conf"); // создание конфига
  72. if(!newconf)
  73. {
  74. std::cerr << " Config (sygcpp.conf) creation failed :(" << std::endl;
  75. return -1;
  76. }
  77. newconf << "1 0 1 9 ::\n"
  78. << "| | | | ^Pattern for search by name.\n"
  79. << "| | | ^Start position for high addresses search.\n"
  80. << "| | ^Logging mode (0 - console output only, 1 - log to file).\n"
  81. << "| ^Mining mode (0 - by name, 1 - high address).\n"
  82. << "^Count of thread (mining streams).\n\n"
  83. << "Parameters are separated by spaces.";
  84. newconf.close();
  85. std::ifstream conffile ("sygcpp.conf");
  86. if(conffile)
  87. std::cout << " Config successfully created :)" << std::endl;
  88. config();
  89. return 0;
  90. } else {
  91. conffile >> conf_proc >> conf_mode >> conf_log >> conf_high >> conf_search;
  92. conffile.close();
  93. if(conf_mode > 1 || conf_mode < 0 || conf_log > 1 || conf_log < 0 || conf_high < 0) // проверка полученных значений
  94. {
  95. std::cerr << " Invalid config found! Check it:\n";
  96. if(conf_mode > 1 || conf_mode < 0)
  97. std::cerr << " - field #2 - mining mode: 0 or 1 only\n";
  98. if(conf_log > 1 || conf_log < 0)
  99. std::cerr << " - field #3 - logging mode: 0 or 1 only\n";
  100. if(conf_high < 0)
  101. std::cerr << " - field #4 - start position for high address search (default 9)\n";
  102. std::cerr << " Remove or correct sygcpp.conf and run SYG again."<< std::endl;
  103. return -2;
  104. }
  105. unsigned int processor_count = std::thread::hardware_concurrency(); // кол-во процессоров
  106. if (conf_proc > (int)processor_count)
  107. conf_proc = (int)processor_count;
  108. countsize = 800 << __bsrq(conf_proc);
  109. }
  110. // вывод конфигурации на экран
  111. std::cout << " Threads: " << conf_proc << ", ";
  112. if(conf_mode)
  113. std::cout << "search high addresses (" << conf_high << "), ";
  114. else
  115. std::cout << "search by name (" << conf_search << "), ";
  116. if(conf_log)
  117. std::cout << "logging to text file." << std::endl;
  118. else
  119. std::cout << "console log only." << std::endl;
  120. std::cout << std::endl;
  121. return 0;
  122. }
  123. void testoutput()
  124. {
  125. if(conf_log) // проверка включено ли логирование
  126. {
  127. if(conf_mode)
  128. log_file = "syg-high.txt";
  129. else
  130. log_file = "syg-byname.txt";
  131. std::ifstream test(log_file);
  132. if(!test) // проверка наличия выходного файла
  133. {
  134. test.close();
  135. std::ofstream output(log_file);
  136. output << "**************************************************************************\n"
  137. << "Change EncryptionPublicKey and EncryptionPrivateKey to your yggdrasil.conf\n"
  138. << "Windows: C:\\ProgramData\\Yggdrasil\\yggdrasil.conf\n"
  139. << "Debian: /etc/yggdrasil.conf\n\n"
  140. << "Visit HowTo.Ygg wiki for more information (russian language page):\n"
  141. << "http://[300:529f:150c:eafe::6]/doku.php?id=yggdrasil:simpleygggen_cpp\n"
  142. << "**************************************************************************\n";
  143. output.close();
  144. } else test.close();
  145. }
  146. }
  147. int getOnes(const unsigned char HashValue[crypto_hash_sha512_BYTES])
  148. {
  149. int lOnes = 0; // кол-во лидирующих единиц
  150. for (int i = 0; i < 32; ++i) // всего 32 байта, т.к. лидирующих единиц больше быть не может (32*8 = 256 бит, а ff = 255)
  151. {
  152. std::bitset<8> bits(HashValue[i]);
  153. for (int i = 7; i >= 0; --i)
  154. {
  155. if (bits[i] == 1) // обращение к i-тому элементу битсета
  156. ++lOnes;
  157. else
  158. return lOnes;
  159. }
  160. }
  161. return -1; // это никогда не случится
  162. }
  163. std::string getAddress(unsigned char HashValue[crypto_hash_sha512_BYTES])
  164. {
  165. // функция "портит" массив хэша, т.к. копирование массива не происходит
  166. int lErase = getOnes(HashValue) + 1; // лидирующие единицы и первый ноль
  167. bool changeit = false;
  168. int bigbyte = 0;
  169. for(int j = 0; j < lErase; ++j) // побитовое смещение
  170. {
  171. for(int i = 63; i >= 0; --i)
  172. {
  173. if(bigbyte == i+1) // предыдущий байт требует переноса
  174. changeit = true;
  175. if(HashValue[i] & 0x80)
  176. bigbyte = i;
  177. HashValue[i] <<= 1;
  178. if(changeit)
  179. {
  180. HashValue[i] |= 0x01;
  181. changeit = false;
  182. }
  183. }
  184. }
  185. uint8_t ipAddr[16];
  186. ipAddr[0] = 0x02;
  187. ipAddr[1] = lErase - 1;
  188. for (int i = 0; i < 14; ++i)
  189. ipAddr[i + 2] = HashValue[i];
  190. char ipStrBuf[46];
  191. inet_ntop(AF_INET6, ipAddr, ipStrBuf, 46);
  192. return std::string(ipStrBuf);
  193. }
  194. void logStatistics()
  195. {
  196. if (++block_count % countsize == 0)
  197. {
  198. auto timedays = (std::time(NULL) - sygstartedin) / 86400;
  199. auto timehours = ((std::time(NULL) - sygstartedin) - (timedays * 86400)) / 3600;
  200. auto timeminutes = ((std::time(NULL) - sygstartedin) - (timedays * 86400) - (timehours * 3600)) / 60;
  201. auto timeseconds = (std::time(NULL) - sygstartedin) - (timedays * 86400) - (timehours * 3600) - (timeminutes * 60);
  202. std::chrono::duration<double, std::milli> df = blocks_duration;
  203. blocks_duration = std::chrono::steady_clock::duration::zero();
  204. int khs = conf_proc * countsize * BLOCKSIZE / df.count();
  205. std::cout <<
  206. " kH/s: [" << std::setw(7) << std::setfill('_') << khs <<
  207. "] Total: [" << std::setw(19) << block_count * BLOCKSIZE <<
  208. "] Found: [" << std::setw(3) << totalcountfortune <<
  209. "] Uptime: " << timedays << ":" << std::setw(2) << std::setfill('0') <<
  210. timehours << ":" << std::setw(2) << timeminutes << ":" << std::setw(2) << timeseconds << std::endl;
  211. }
  212. }
  213. std::string hexArrayToString(const uint8_t* bytes, int length)
  214. {
  215. std::stringstream ss;
  216. for (int i = 0; i < length; i++)
  217. ss << std::setw(2) << std::setfill('0') << std::hex << (int)bytes[i];
  218. return ss.str();
  219. }
  220. std::string keyToString(const key25519 key)
  221. {
  222. return hexArrayToString(key, KEYSIZE);
  223. }
  224. std::string hashToString(const uint8_t hash[crypto_hash_sha512_BYTES])
  225. {
  226. return hexArrayToString(hash, crypto_hash_sha512_BYTES);
  227. }
  228. void logKeys(std::string address, const key25519 publicKey, const key25519 privateKey)
  229. {
  230. std::cout << std::endl;
  231. std::cout << " Address: " << address << std::endl;
  232. std::cout << " PublicKey: " << keyToString(publicKey) << std::endl;
  233. std::cout << " PrivateKey: " << keyToString(privateKey) << std::endl;
  234. std::cout << std::endl;
  235. if (conf_log) // запись в файл
  236. {
  237. std::ofstream output(log_file, std::ios::app);
  238. output << std::endl;
  239. output << "Address: " << address << std::endl;
  240. output << "EncryptionPublicKey: " << keyToString(publicKey) << std::endl;
  241. output << "EncryptionPrivateKey: " << keyToString(privateKey) << std::endl;
  242. output.close();
  243. }
  244. }
  245. void process_fortune_key(const keys_block& block, int index)
  246. {
  247. if (index == -1)
  248. return;
  249. key25519 public_key;
  250. key25519 private_key;
  251. block.get_public_key(public_key, index);
  252. block.get_private_key(private_key, index);
  253. uint8_t sha512_hash[crypto_hash_sha512_BYTES];
  254. crypto_hash_sha512(sha512_hash, public_key);
  255. std::string address = getAddress(sha512_hash);
  256. logKeys(address, public_key, private_key);
  257. ++totalcountfortune;
  258. }
  259. template <int T>
  260. void miner_thread()
  261. {
  262. key25519 public_key;
  263. keys_block block(BLOCKSIZE);
  264. uint8_t random_bytes[KEYSIZE];
  265. uint8_t sha512_hash[crypto_hash_sha512_BYTES];
  266. for (;;)
  267. {
  268. auto start_time = std::chrono::steady_clock::now();
  269. int fortune_key_index = -1;
  270. randombytes(random_bytes, KEYSIZE);
  271. block.calculate_public_keys(random_bytes);
  272. for (int i = 0; i < BLOCKSIZE; i++)
  273. {
  274. block.get_public_key(public_key, i);
  275. crypto_hash_sha512(sha512_hash, public_key);
  276. if (T == 1) // high mining
  277. {
  278. int newones = getOnes(sha512_hash);
  279. if (newones > conf_high)
  280. {
  281. conf_high = newones;
  282. fortune_key_index = i;
  283. }
  284. }
  285. else // name mining
  286. {
  287. if (getAddress(sha512_hash).find(
  288. conf_search.c_str()) != std::string::npos)
  289. {
  290. fortune_key_index = i;
  291. break; // можно использовать только один ключ из блока
  292. }
  293. }
  294. }
  295. auto stop_time = std::chrono::steady_clock::now();
  296. mtx.lock();
  297. blocks_duration += stop_time - start_time;
  298. process_fortune_key(block, fortune_key_index);
  299. logStatistics();
  300. mtx.unlock();
  301. }
  302. }
  303. #ifdef SELF_CHECK
  304. void selfCheck()
  305. {
  306. std::cout << "Self-check started." << std::endl;
  307. for (int i = 0; i < 16; i++)
  308. {
  309. int block_size = 1 << i;
  310. keys_block block(block_size);
  311. uint8_t random_bytes[KEYSIZE];
  312. randombytes(random_bytes, KEYSIZE);
  313. block.calculate_public_keys(random_bytes);
  314. key25519 public_key1;
  315. key25519 public_key2;
  316. key25519 private_key;
  317. uint8_t sha512_hash1[crypto_hash_sha512_BYTES];
  318. uint8_t sha512_hash2[crypto_hash_sha512_BYTES];
  319. for (int j = 0; j < block_size; j++)
  320. {
  321. block.get_public_key(public_key1, j);
  322. block.get_private_key(private_key, j);
  323. crypto_scalarmult_curve25519_base(public_key2, private_key);
  324. crypto_hash_sha512(sha512_hash1, public_key2);
  325. crypto_hash_sha512(sha512_hash2, public_key2, KEYSIZE);
  326. if (memcmp(public_key1, public_key2, KEYSIZE) != 0 ||
  327. memcmp(sha512_hash1, sha512_hash2, crypto_hash_sha512_BYTES))
  328. {
  329. std::cout << "!!! Self-check failed !!!" << std::endl;
  330. std::cout << " PrivateKey: " << keyToString(private_key) << std::endl;
  331. std::cout << " PublicKey1: " << keyToString(public_key1) << std::endl;
  332. std::cout << " PublicKey2: " << keyToString(public_key2) << std::endl;
  333. std::cout << " SHA512Hash1: " << hashToString(sha512_hash1) << std::endl;
  334. std::cout << " SHA512Hash2: " << hashToString(sha512_hash2) << std::endl;
  335. std::cout << "!!! Self-check failed !!!" << std::endl;
  336. return;
  337. }
  338. else
  339. {
  340. //std::cout << " Self-check ok" << std::endl;
  341. //std::cout << " PrivateKey: " << keyToString(private_key) << std::endl;
  342. }
  343. }
  344. }
  345. std::cout << "Self-check finished." << std::endl;
  346. }
  347. #endif
  348. // ------------------------------------------------------
  349. int main()
  350. {
  351. intro();
  352. #ifdef SELF_CHECK
  353. selfCheck();
  354. return 0;
  355. #endif
  356. int configcheck = config();
  357. if(configcheck < 0) // функция получения конфигурации
  358. {
  359. std::cerr << " Error code: " << configcheck << std::endl << std::endl;
  360. system("PAUSE");
  361. return configcheck;
  362. }
  363. testoutput();
  364. std::thread* lastThread;
  365. for (int i = 0; i < conf_proc; i++)
  366. lastThread = new std::thread(conf_mode ? miner_thread<1> : miner_thread<0>);
  367. lastThread->join();
  368. std::cerr << "SYG has stopped working unexpectedly! Please, report about this." << std::endl;
  369. system("PAUSE");
  370. return -420;
  371. }