util.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. * Copyright 2012 Giel van Schijndel
  5. * Copyright 2012 Gavin Andresen
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #define _GNU_SOURCE
  13. #include "config.h"
  14. #ifdef WIN32
  15. #define FD_SETSIZE 4096
  16. #endif
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <ctype.h>
  20. #include <stdarg.h>
  21. #include <string.h>
  22. #include <pthread.h>
  23. #include <jansson.h>
  24. #include <curl/curl.h>
  25. #include <time.h>
  26. #include <errno.h>
  27. #include <unistd.h>
  28. #include <sys/types.h>
  29. #ifdef HAVE_SYS_PRCTL_H
  30. # include <sys/prctl.h>
  31. #endif
  32. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  33. # include <pthread_np.h>
  34. #endif
  35. #ifndef WIN32
  36. # include <sys/socket.h>
  37. # include <netinet/in.h>
  38. # include <netinet/tcp.h>
  39. # include <netdb.h>
  40. #else
  41. # include <winsock2.h>
  42. # include <mstcpip.h>
  43. # include <ws2tcpip.h>
  44. #endif
  45. #include "miner.h"
  46. #include "elist.h"
  47. #include "compat.h"
  48. #include "util.h"
  49. bool successful_connect = false;
  50. struct timeval nettime;
  51. struct upload_buffer {
  52. const void *buf;
  53. size_t len;
  54. };
  55. struct header_info {
  56. char *lp_path;
  57. int rolltime;
  58. char *reason;
  59. char *stratum_url;
  60. bool hadrolltime;
  61. bool canroll;
  62. bool hadexpire;
  63. };
  64. struct tq_ent {
  65. void *data;
  66. struct list_head q_node;
  67. };
  68. static void databuf_free(struct data_buffer *db)
  69. {
  70. if (!db)
  71. return;
  72. free(db->buf);
  73. memset(db, 0, sizeof(*db));
  74. }
  75. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  76. void *user_data)
  77. {
  78. struct data_buffer *db = user_data;
  79. size_t len = size * nmemb;
  80. size_t oldlen, newlen;
  81. void *newmem;
  82. static const unsigned char zero = 0;
  83. if (db->idlemarker) {
  84. const unsigned char *cptr = ptr;
  85. for (size_t i = 0; i < len; ++i)
  86. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  87. *db->idlemarker = CURL_SOCKET_BAD;
  88. db->idlemarker = NULL;
  89. break;
  90. }
  91. }
  92. oldlen = db->len;
  93. newlen = oldlen + len;
  94. newmem = realloc(db->buf, newlen + 1);
  95. if (!newmem)
  96. return 0;
  97. db->buf = newmem;
  98. db->len = newlen;
  99. memcpy(db->buf + oldlen, ptr, len);
  100. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  101. return len;
  102. }
  103. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  104. void *user_data)
  105. {
  106. struct upload_buffer *ub = user_data;
  107. unsigned int len = size * nmemb;
  108. if (len > ub->len)
  109. len = ub->len;
  110. if (len) {
  111. memcpy(ptr, ub->buf, len);
  112. ub->buf += len;
  113. ub->len -= len;
  114. }
  115. return len;
  116. }
  117. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  118. {
  119. struct header_info *hi = user_data;
  120. size_t remlen, slen, ptrlen = size * nmemb;
  121. char *rem, *val = NULL, *key = NULL;
  122. void *tmp;
  123. val = calloc(1, ptrlen);
  124. key = calloc(1, ptrlen);
  125. if (!key || !val)
  126. goto out;
  127. tmp = memchr(ptr, ':', ptrlen);
  128. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  129. goto out;
  130. slen = tmp - ptr;
  131. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  132. goto out;
  133. memcpy(key, ptr, slen); /* store & nul term key */
  134. key[slen] = 0;
  135. rem = ptr + slen + 1; /* trim value's leading whitespace */
  136. remlen = ptrlen - slen - 1;
  137. while ((remlen > 0) && (isspace(*rem))) {
  138. remlen--;
  139. rem++;
  140. }
  141. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  142. val[remlen] = 0;
  143. while ((*val) && (isspace(val[strlen(val) - 1])))
  144. val[strlen(val) - 1] = 0;
  145. if (!*val) /* skip blank value */
  146. goto out;
  147. if (opt_protocol)
  148. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  149. if (!strcasecmp("X-Roll-Ntime", key)) {
  150. hi->hadrolltime = true;
  151. if (!strncasecmp("N", val, 1))
  152. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  153. else {
  154. hi->canroll = true;
  155. /* Check to see if expire= is supported and if not, set
  156. * the rolltime to the default scantime */
  157. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  158. sscanf(val + 7, "%d", &hi->rolltime);
  159. hi->hadexpire = true;
  160. } else
  161. hi->rolltime = opt_scantime;
  162. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  163. }
  164. }
  165. if (!strcasecmp("X-Long-Polling", key)) {
  166. hi->lp_path = val; /* steal memory reference */
  167. val = NULL;
  168. }
  169. if (!strcasecmp("X-Reject-Reason", key)) {
  170. hi->reason = val; /* steal memory reference */
  171. val = NULL;
  172. }
  173. if (!strcasecmp("X-Stratum", key)) {
  174. hi->stratum_url = val;
  175. val = NULL;
  176. }
  177. out:
  178. free(key);
  179. free(val);
  180. return ptrlen;
  181. }
  182. static int keep_sockalive(SOCKETTYPE fd)
  183. {
  184. const int tcp_keepidle = 60;
  185. const int tcp_keepintvl = 60;
  186. const int keepalive = 1;
  187. int ret = 0;
  188. #ifndef WIN32
  189. const int tcp_keepcnt = 5;
  190. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  191. ret = 1;
  192. # ifdef __linux
  193. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  194. ret = 1;
  195. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  196. ret = 1;
  197. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  198. ret = 1;
  199. # endif /* __linux */
  200. # ifdef __APPLE_CC__
  201. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  202. ret = 1;
  203. # endif /* __APPLE_CC__ */
  204. #else /* WIN32 */
  205. const int zero = 0;
  206. struct tcp_keepalive vals;
  207. vals.onoff = 1;
  208. vals.keepalivetime = tcp_keepidle * 1000;
  209. vals.keepaliveinterval = tcp_keepintvl * 1000;
  210. DWORD outputBytes;
  211. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
  212. ret = 1;
  213. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  214. ret = 1;
  215. /* Windows happily submits indefinitely to the send buffer blissfully
  216. * unaware nothing is getting there without gracefully failing unless
  217. * we disable the send buffer */
  218. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  219. ret = 1;
  220. #endif /* WIN32 */
  221. return ret;
  222. }
  223. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  224. curlsocktype __maybe_unused purpose)
  225. {
  226. return keep_sockalive(fd);
  227. }
  228. static void last_nettime(struct timeval *last)
  229. {
  230. rd_lock(&netacc_lock);
  231. last->tv_sec = nettime.tv_sec;
  232. last->tv_usec = nettime.tv_usec;
  233. rd_unlock(&netacc_lock);
  234. }
  235. static void set_nettime(void)
  236. {
  237. wr_lock(&netacc_lock);
  238. gettimeofday(&nettime, NULL);
  239. wr_unlock(&netacc_lock);
  240. }
  241. json_t *json_rpc_call(CURL *curl, const char *url,
  242. const char *userpass, const char *rpc_req,
  243. bool probe, bool longpoll, int *rolltime,
  244. struct pool *pool, bool share)
  245. {
  246. long timeout = longpoll ? (60 * 60) : 60;
  247. struct data_buffer all_data = {.len = 0};
  248. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  249. char len_hdr[64], user_agent_hdr[128];
  250. char curl_err_str[CURL_ERROR_SIZE];
  251. struct curl_slist *headers = NULL;
  252. struct upload_buffer upload_data;
  253. json_t *val, *err_val, *res_val;
  254. bool probing = false;
  255. json_error_t err;
  256. int rc;
  257. memset(&err, 0, sizeof(err));
  258. if (longpoll)
  259. all_data.idlemarker = &pool->lp_socket;
  260. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  261. if (probe)
  262. probing = !pool->probed;
  263. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  264. #if 0 /* Disable curl debugging since it spews to stderr */
  265. if (opt_protocol)
  266. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  267. #endif
  268. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  269. curl_easy_setopt(curl, CURLOPT_URL, url);
  270. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  271. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  272. /* Shares are staggered already and delays in submission can be costly
  273. * so do not delay them */
  274. if (!opt_delaynet || share)
  275. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  276. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  277. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  278. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  279. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  280. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  281. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  282. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  283. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  284. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  285. if (pool->rpc_proxy) {
  286. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  287. } else if (opt_socks_proxy) {
  288. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  289. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  290. }
  291. if (userpass) {
  292. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  293. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  294. }
  295. if (longpoll)
  296. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  297. curl_easy_setopt(curl, CURLOPT_POST, 1);
  298. if (opt_protocol)
  299. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  300. upload_data.buf = rpc_req;
  301. upload_data.len = strlen(rpc_req);
  302. sprintf(len_hdr, "Content-Length: %lu",
  303. (unsigned long) upload_data.len);
  304. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  305. headers = curl_slist_append(headers,
  306. "Content-type: application/json");
  307. headers = curl_slist_append(headers,
  308. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  309. if (longpoll)
  310. headers = curl_slist_append(headers,
  311. "X-Minimum-Wait: 0");
  312. if (likely(global_hashrate)) {
  313. char ghashrate[255];
  314. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  315. headers = curl_slist_append(headers, ghashrate);
  316. }
  317. headers = curl_slist_append(headers, len_hdr);
  318. headers = curl_slist_append(headers, user_agent_hdr);
  319. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  320. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  321. if (opt_delaynet) {
  322. /* Don't delay share submission, but still track the nettime */
  323. if (!share) {
  324. long long now_msecs, last_msecs;
  325. struct timeval now, last;
  326. gettimeofday(&now, NULL);
  327. last_nettime(&last);
  328. now_msecs = (long long)now.tv_sec * 1000;
  329. now_msecs += now.tv_usec / 1000;
  330. last_msecs = (long long)last.tv_sec * 1000;
  331. last_msecs += last.tv_usec / 1000;
  332. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  333. struct timespec rgtp;
  334. rgtp.tv_sec = 0;
  335. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  336. nanosleep(&rgtp, NULL);
  337. }
  338. }
  339. set_nettime();
  340. }
  341. rc = curl_easy_perform(curl);
  342. if (rc) {
  343. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  344. goto err_out;
  345. }
  346. if (!all_data.buf) {
  347. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  348. goto err_out;
  349. }
  350. if (probing) {
  351. pool->probed = true;
  352. /* If X-Long-Polling was found, activate long polling */
  353. if (hi.lp_path) {
  354. if (pool->hdr_path != NULL)
  355. free(pool->hdr_path);
  356. pool->hdr_path = hi.lp_path;
  357. } else
  358. pool->hdr_path = NULL;
  359. if (hi.stratum_url) {
  360. pool->stratum_url = hi.stratum_url;
  361. hi.stratum_url = NULL;
  362. }
  363. } else {
  364. if (hi.lp_path) {
  365. free(hi.lp_path);
  366. hi.lp_path = NULL;
  367. }
  368. if (hi.stratum_url) {
  369. free(hi.stratum_url);
  370. hi.stratum_url = NULL;
  371. }
  372. }
  373. *rolltime = hi.rolltime;
  374. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  375. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  376. pool->cgminer_pool_stats.canroll = hi.canroll;
  377. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  378. val = JSON_LOADS(all_data.buf, &err);
  379. if (!val) {
  380. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  381. if (opt_protocol)
  382. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  383. goto err_out;
  384. }
  385. if (opt_protocol) {
  386. char *s = json_dumps(val, JSON_INDENT(3));
  387. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  388. free(s);
  389. }
  390. /* JSON-RPC valid response returns a non-null 'result',
  391. * and a null 'error'.
  392. */
  393. res_val = json_object_get(val, "result");
  394. err_val = json_object_get(val, "error");
  395. if (!res_val ||(err_val && !json_is_null(err_val))) {
  396. char *s;
  397. if (err_val)
  398. s = json_dumps(err_val, JSON_INDENT(3));
  399. else
  400. s = strdup("(unknown reason)");
  401. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  402. free(s);
  403. json_decref(val);
  404. goto err_out;
  405. }
  406. if (hi.reason) {
  407. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  408. free(hi.reason);
  409. hi.reason = NULL;
  410. }
  411. successful_connect = true;
  412. databuf_free(&all_data);
  413. curl_slist_free_all(headers);
  414. curl_easy_reset(curl);
  415. return val;
  416. err_out:
  417. databuf_free(&all_data);
  418. curl_slist_free_all(headers);
  419. curl_easy_reset(curl);
  420. if (!successful_connect)
  421. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  422. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  423. return NULL;
  424. }
  425. bool our_curl_supports_proxy_uris()
  426. {
  427. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  428. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  429. }
  430. /* Returns a malloced array string of a binary value of arbitrary length. The
  431. * array is rounded up to a 4 byte size to appease architectures that need
  432. * aligned array sizes */
  433. char *bin2hex(const unsigned char *p, size_t len)
  434. {
  435. unsigned int i;
  436. ssize_t slen;
  437. char *s;
  438. slen = len * 2 + 1;
  439. if (slen % 4)
  440. slen += 4 - (slen % 4);
  441. s = calloc(slen, 1);
  442. if (unlikely(!s))
  443. quit(1, "Failed to calloc in bin2hex");
  444. for (i = 0; i < len; i++)
  445. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  446. return s;
  447. }
  448. /* Does the reverse of bin2hex but does not allocate any ram */
  449. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  450. {
  451. bool ret = false;
  452. while (*hexstr && len) {
  453. char hex_byte[4];
  454. unsigned int v;
  455. if (unlikely(!hexstr[1])) {
  456. applog(LOG_ERR, "hex2bin str truncated");
  457. return ret;
  458. }
  459. memset(hex_byte, 0, 4);
  460. hex_byte[0] = hexstr[0];
  461. hex_byte[1] = hexstr[1];
  462. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  463. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  464. return ret;
  465. }
  466. *p = (unsigned char) v;
  467. p++;
  468. hexstr += 2;
  469. len--;
  470. }
  471. if (likely(len == 0 && *hexstr == 0))
  472. ret = true;
  473. return ret;
  474. }
  475. bool fulltest(const unsigned char *hash, const unsigned char *target)
  476. {
  477. unsigned char hash_swap[32], target_swap[32];
  478. uint32_t *hash32 = (uint32_t *) hash_swap;
  479. uint32_t *target32 = (uint32_t *) target_swap;
  480. char *hash_str, *target_str;
  481. bool rc = true;
  482. int i;
  483. swap256(hash_swap, hash);
  484. swap256(target_swap, target);
  485. for (i = 0; i < 32/4; i++) {
  486. uint32_t h32tmp = htobe32(hash32[i]);
  487. uint32_t t32tmp = htole32(target32[i]);
  488. target32[i] = swab32(target32[i]); /* for printing */
  489. if (h32tmp > t32tmp) {
  490. rc = false;
  491. break;
  492. }
  493. if (h32tmp < t32tmp) {
  494. rc = true;
  495. break;
  496. }
  497. }
  498. if (opt_debug) {
  499. hash_str = bin2hex(hash_swap, 32);
  500. target_str = bin2hex(target_swap, 32);
  501. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  502. hash_str,
  503. target_str,
  504. rc ? "YES (hash < target)" :
  505. "no (false positive; hash > target)");
  506. free(hash_str);
  507. free(target_str);
  508. }
  509. return rc;
  510. }
  511. struct thread_q *tq_new(void)
  512. {
  513. struct thread_q *tq;
  514. tq = calloc(1, sizeof(*tq));
  515. if (!tq)
  516. return NULL;
  517. INIT_LIST_HEAD(&tq->q);
  518. pthread_mutex_init(&tq->mutex, NULL);
  519. pthread_cond_init(&tq->cond, NULL);
  520. return tq;
  521. }
  522. void tq_free(struct thread_q *tq)
  523. {
  524. struct tq_ent *ent, *iter;
  525. if (!tq)
  526. return;
  527. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  528. list_del(&ent->q_node);
  529. free(ent);
  530. }
  531. pthread_cond_destroy(&tq->cond);
  532. pthread_mutex_destroy(&tq->mutex);
  533. memset(tq, 0, sizeof(*tq)); /* poison */
  534. free(tq);
  535. }
  536. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  537. {
  538. mutex_lock(&tq->mutex);
  539. tq->frozen = frozen;
  540. pthread_cond_signal(&tq->cond);
  541. mutex_unlock(&tq->mutex);
  542. }
  543. void tq_freeze(struct thread_q *tq)
  544. {
  545. tq_freezethaw(tq, true);
  546. }
  547. void tq_thaw(struct thread_q *tq)
  548. {
  549. tq_freezethaw(tq, false);
  550. }
  551. bool tq_push(struct thread_q *tq, void *data)
  552. {
  553. struct tq_ent *ent;
  554. bool rc = true;
  555. ent = calloc(1, sizeof(*ent));
  556. if (!ent)
  557. return false;
  558. ent->data = data;
  559. INIT_LIST_HEAD(&ent->q_node);
  560. mutex_lock(&tq->mutex);
  561. if (!tq->frozen) {
  562. list_add_tail(&ent->q_node, &tq->q);
  563. } else {
  564. free(ent);
  565. rc = false;
  566. }
  567. pthread_cond_signal(&tq->cond);
  568. mutex_unlock(&tq->mutex);
  569. return rc;
  570. }
  571. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  572. {
  573. struct tq_ent *ent;
  574. void *rval = NULL;
  575. int rc;
  576. mutex_lock(&tq->mutex);
  577. if (!list_empty(&tq->q))
  578. goto pop;
  579. if (abstime)
  580. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  581. else
  582. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  583. if (rc)
  584. goto out;
  585. if (list_empty(&tq->q))
  586. goto out;
  587. pop:
  588. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  589. rval = ent->data;
  590. list_del(&ent->q_node);
  591. free(ent);
  592. out:
  593. mutex_unlock(&tq->mutex);
  594. return rval;
  595. }
  596. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  597. {
  598. return pthread_create(&thr->pth, attr, start, arg);
  599. }
  600. void thr_info_freeze(struct thr_info *thr)
  601. {
  602. struct tq_ent *ent, *iter;
  603. struct thread_q *tq;
  604. if (!thr)
  605. return;
  606. tq = thr->q;
  607. if (!tq)
  608. return;
  609. mutex_lock(&tq->mutex);
  610. tq->frozen = true;
  611. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  612. list_del(&ent->q_node);
  613. free(ent);
  614. }
  615. mutex_unlock(&tq->mutex);
  616. }
  617. void thr_info_cancel(struct thr_info *thr)
  618. {
  619. if (!thr)
  620. return;
  621. if (PTH(thr) != 0L) {
  622. pthread_cancel(thr->pth);
  623. PTH(thr) = 0L;
  624. }
  625. }
  626. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  627. * on SMP machines */
  628. void nmsleep(unsigned int msecs)
  629. {
  630. struct timespec twait, tleft;
  631. int ret;
  632. ldiv_t d;
  633. d = ldiv(msecs, 1000);
  634. tleft.tv_sec = d.quot;
  635. tleft.tv_nsec = d.rem * 1000000;
  636. do {
  637. twait.tv_sec = tleft.tv_sec;
  638. twait.tv_nsec = tleft.tv_nsec;
  639. ret = nanosleep(&twait, &tleft);
  640. } while (ret == -1 && errno == EINTR);
  641. }
  642. /* Returns the microseconds difference between end and start times as a double */
  643. double us_tdiff(struct timeval *end, struct timeval *start)
  644. {
  645. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  646. }
  647. void rename_thr(const char* name) {
  648. #if defined(PR_SET_NAME)
  649. // Only the first 15 characters are used (16 - NUL terminator)
  650. prctl(PR_SET_NAME, name, 0, 0, 0);
  651. #elif defined(__APPLE__)
  652. pthread_setname_np(name);
  653. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  654. pthread_set_name_np(pthread_self(), name);
  655. #else
  656. // Prevent warnings for unused parameters...
  657. (void)name;
  658. #endif
  659. }
  660. /* Returns the seconds difference between end and start times as a double */
  661. double tdiff(struct timeval *end, struct timeval *start)
  662. {
  663. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  664. }
  665. bool extract_sockaddr(struct pool *pool, char *url)
  666. {
  667. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  668. char url_address[256], port[6];
  669. int url_len, port_len = 0;
  670. url_begin = strstr(url, "//");
  671. if (!url_begin)
  672. url_begin = url;
  673. else
  674. url_begin += 2;
  675. /* Look for numeric ipv6 entries */
  676. ipv6_begin = strstr(url_begin, "[");
  677. ipv6_end = strstr(url_begin, "]");
  678. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  679. url_end = strstr(ipv6_end, ":");
  680. else
  681. url_end = strstr(url_begin, ":");
  682. if (url_end) {
  683. url_len = url_end - url_begin;
  684. port_len = strlen(url_begin) - url_len - 1;
  685. if (port_len < 1)
  686. return false;
  687. port_start = url_end + 1;
  688. } else
  689. url_len = strlen(url_begin);
  690. if (url_len < 1)
  691. return false;
  692. sprintf(url_address, "%.*s", url_len, url_begin);
  693. if (port_len)
  694. snprintf(port, 6, "%.*s", port_len, port_start);
  695. else
  696. strcpy(port, "80");
  697. free(pool->stratum_port);
  698. pool->stratum_port = strdup(port);
  699. free(pool->sockaddr_url);
  700. pool->sockaddr_url = strdup(url_address);
  701. return true;
  702. }
  703. /* Send a single command across a socket, appending \n to it. This should all
  704. * be done under stratum lock except when first establishing the socket */
  705. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  706. {
  707. SOCKETTYPE sock = pool->sock;
  708. ssize_t ssent = 0;
  709. if (opt_protocol)
  710. applog(LOG_DEBUG, "SEND: %s", s);
  711. strcat(s, "\n");
  712. len++;
  713. while (len > 0 ) {
  714. struct timeval timeout = {0, 0};
  715. size_t sent = 0;
  716. CURLcode rc;
  717. fd_set wd;
  718. FD_ZERO(&wd);
  719. FD_SET(sock, &wd);
  720. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  721. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  722. return false;
  723. }
  724. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  725. if (rc != CURLE_OK) {
  726. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  727. return false;
  728. }
  729. ssent += sent;
  730. len -= ssent;
  731. }
  732. return true;
  733. }
  734. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  735. {
  736. bool ret = false;
  737. mutex_lock(&pool->stratum_lock);
  738. if (pool->stratum_active)
  739. ret = __stratum_send(pool, s, len);
  740. else
  741. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  742. mutex_unlock(&pool->stratum_lock);
  743. return ret;
  744. }
  745. static void clear_sock(struct pool *pool)
  746. {
  747. size_t n = 0;
  748. char buf[RECVSIZE];
  749. mutex_lock(&pool->stratum_lock);
  750. while (CURLE_OK == curl_easy_recv(pool->stratum_curl, buf, RECVSIZE, &n))
  751. {}
  752. mutex_unlock(&pool->stratum_lock);
  753. }
  754. /* Check to see if Santa's been good to you */
  755. static bool sock_full(struct pool *pool, bool wait)
  756. {
  757. SOCKETTYPE sock = pool->sock;
  758. struct timeval timeout;
  759. fd_set rd;
  760. if (pool->readbuf.buf && memchr(pool->readbuf.buf, '\n', pool->readbuf.len))
  761. return true;
  762. FD_ZERO(&rd);
  763. FD_SET(sock, &rd);
  764. timeout.tv_usec = 0;
  765. if (wait)
  766. timeout.tv_sec = 60;
  767. else
  768. timeout.tv_sec = 0;
  769. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  770. return true;
  771. return false;
  772. }
  773. /* Peeks at a socket to find the first end of line and then reads just that
  774. * from the socket and returns that as a malloced char */
  775. char *recv_line(struct pool *pool)
  776. {
  777. ssize_t len;
  778. char *tok, *sret = NULL;
  779. size_t n = 0;
  780. while (!(pool->readbuf.buf && memchr(pool->readbuf.buf, '\n', pool->readbuf.len))) {
  781. char s[RBUFSIZE];
  782. CURLcode rc;
  783. if (!sock_full(pool, true)) {
  784. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  785. goto out;
  786. }
  787. memset(s, 0, RBUFSIZE);
  788. mutex_lock(&pool->stratum_lock);
  789. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  790. mutex_unlock(&pool->stratum_lock);
  791. if (rc != CURLE_OK) {
  792. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %d", rc);
  793. goto out;
  794. }
  795. len = all_data_cb(s, n, 1, &pool->readbuf);
  796. if (n != (size_t)len) {
  797. applog(LOG_DEBUG, "Error appending readbuf in recv_line");
  798. goto out;
  799. }
  800. }
  801. // Assuming the bulk of the data will be in the line, steal the buffer and return it
  802. tok = memchr(pool->readbuf.buf, '\n', pool->readbuf.len);
  803. *tok = '\0';
  804. len = tok - (char*)pool->readbuf.buf;
  805. pool->readbuf.len -= len + 1;
  806. tok = memcpy(malloc(pool->readbuf.len), tok + 1, pool->readbuf.len);
  807. sret = realloc(pool->readbuf.buf, len + 1);
  808. pool->readbuf.buf = tok;
  809. out:
  810. if (!sret)
  811. clear_sock(pool);
  812. else if (opt_protocol)
  813. applog(LOG_DEBUG, "RECVD: %s", sret);
  814. return sret;
  815. }
  816. /* Extracts a string value from a json array with error checking. To be used
  817. * when the value of the string returned is only examined and not to be stored.
  818. * See json_array_string below */
  819. static char *__json_array_string(json_t *val, unsigned int entry)
  820. {
  821. json_t *arr_entry;
  822. if (json_is_null(val))
  823. return NULL;
  824. if (!json_is_array(val))
  825. return NULL;
  826. if (entry > json_array_size(val))
  827. return NULL;
  828. arr_entry = json_array_get(val, entry);
  829. if (!json_is_string(arr_entry))
  830. return NULL;
  831. return (char *)json_string_value(arr_entry);
  832. }
  833. /* Creates a freshly malloced dup of __json_array_string */
  834. static char *json_array_string(json_t *val, unsigned int entry)
  835. {
  836. char *buf = __json_array_string(val, entry);
  837. if (buf)
  838. return strdup(buf);
  839. return NULL;
  840. }
  841. static bool parse_notify(struct pool *pool, json_t *val)
  842. {
  843. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  844. int merkles, i;
  845. json_t *arr;
  846. bool clean;
  847. arr = json_array_get(val, 4);
  848. if (!arr || !json_is_array(arr))
  849. return false;
  850. merkles = json_array_size(arr);
  851. job_id = json_array_string(val, 0);
  852. prev_hash = json_array_string(val, 1);
  853. coinbase1 = json_array_string(val, 2);
  854. coinbase2 = json_array_string(val, 3);
  855. bbversion = json_array_string(val, 5);
  856. nbit = json_array_string(val, 6);
  857. ntime = json_array_string(val, 7);
  858. clean = json_is_true(json_array_get(val, 8));
  859. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  860. /* Annoying but we must not leak memory */
  861. if (job_id)
  862. free(job_id);
  863. if (prev_hash)
  864. free(prev_hash);
  865. if (coinbase1)
  866. free(coinbase1);
  867. if (coinbase2)
  868. free(coinbase2);
  869. if (bbversion)
  870. free(bbversion);
  871. if (nbit)
  872. free(nbit);
  873. if (ntime)
  874. free(ntime);
  875. return false;
  876. }
  877. mutex_lock(&pool->pool_lock);
  878. free(pool->swork.job_id);
  879. free(pool->swork.prev_hash);
  880. free(pool->swork.coinbase1);
  881. free(pool->swork.coinbase2);
  882. free(pool->swork.bbversion);
  883. free(pool->swork.nbit);
  884. free(pool->swork.ntime);
  885. pool->swork.job_id = job_id;
  886. pool->swork.prev_hash = prev_hash;
  887. pool->swork.coinbase1 = coinbase1;
  888. pool->swork.coinbase2 = coinbase2;
  889. pool->swork.bbversion = bbversion;
  890. pool->swork.nbit = nbit;
  891. pool->swork.ntime = ntime;
  892. pool->submit_old = !clean;
  893. pool->swork.clean = true;
  894. for (i = 0; i < pool->swork.merkles; i++)
  895. free(pool->swork.merkle[i]);
  896. if (merkles) {
  897. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  898. for (i = 0; i < merkles; i++)
  899. pool->swork.merkle[i] = json_array_string(arr, i);
  900. }
  901. pool->swork.merkles = merkles;
  902. if (clean)
  903. pool->nonce2 = 0;
  904. mutex_unlock(&pool->pool_lock);
  905. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  906. pool->pool_no, job_id);
  907. if (opt_protocol) {
  908. applog(LOG_DEBUG, "job_id: %s", job_id);
  909. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  910. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  911. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  912. for (i = 0; i < merkles; i++)
  913. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  914. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  915. applog(LOG_DEBUG, "nbit: %s", nbit);
  916. applog(LOG_DEBUG, "ntime: %s", ntime);
  917. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  918. }
  919. /* A notify message is the closest stratum gets to a getwork */
  920. pool->getwork_requested++;
  921. total_getworks++;
  922. {
  923. // Request transaction data to discourage pools from doing anything shady
  924. char s[1024];
  925. int sLen;
  926. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  927. pool->swork.job_id,
  928. pool->swork.job_id);
  929. stratum_send(pool, s, sLen);
  930. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  931. pool->swork.transparency_time = time(NULL);
  932. }
  933. return true;
  934. }
  935. static bool parse_diff(struct pool *pool, json_t *val)
  936. {
  937. double diff;
  938. diff = json_number_value(json_array_get(val, 0));
  939. if (diff == 0)
  940. return false;
  941. mutex_lock(&pool->pool_lock);
  942. pool->swork.diff = diff;
  943. mutex_unlock(&pool->pool_lock);
  944. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
  945. return true;
  946. }
  947. static bool parse_reconnect(struct pool *pool, json_t *val)
  948. {
  949. char *url, *port, address[256];
  950. memset(address, 0, 255);
  951. url = (char *)json_string_value(json_array_get(val, 0));
  952. if (!url)
  953. url = pool->sockaddr_url;
  954. port = (char *)json_string_value(json_array_get(val, 1));
  955. if (!port)
  956. port = pool->stratum_port;
  957. sprintf(address, "%s:%s", url, port);
  958. if (!extract_sockaddr(pool, address))
  959. return false;
  960. pool->stratum_url = pool->sockaddr_url;
  961. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  962. if (!initiate_stratum(pool) || !auth_stratum(pool))
  963. return false;
  964. return true;
  965. }
  966. static bool send_version(struct pool *pool, json_t *val)
  967. {
  968. char s[RBUFSIZE];
  969. int id = json_integer_value(json_object_get(val, "id"));
  970. if (!id)
  971. return false;
  972. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  973. if (!stratum_send(pool, s, strlen(s)))
  974. return false;
  975. return true;
  976. }
  977. bool parse_method(struct pool *pool, char *s)
  978. {
  979. json_t *val = NULL, *method, *err_val, *params;
  980. json_error_t err;
  981. bool ret = false;
  982. char *buf;
  983. if (!s)
  984. goto out;
  985. val = JSON_LOADS(s, &err);
  986. if (!val) {
  987. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  988. goto out;
  989. }
  990. method = json_object_get(val, "method");
  991. if (!method)
  992. goto out;
  993. err_val = json_object_get(val, "error");
  994. params = json_object_get(val, "params");
  995. if (err_val && !json_is_null(err_val)) {
  996. char *ss;
  997. if (err_val)
  998. ss = json_dumps(err_val, JSON_INDENT(3));
  999. else
  1000. ss = strdup("(unknown reason)");
  1001. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1002. free(ss);
  1003. goto out;
  1004. }
  1005. buf = (char *)json_string_value(method);
  1006. if (!buf)
  1007. goto out;
  1008. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  1009. ret = true;
  1010. goto out;
  1011. }
  1012. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1013. ret = true;
  1014. goto out;
  1015. }
  1016. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1017. ret = true;
  1018. goto out;
  1019. }
  1020. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1021. ret = true;
  1022. goto out;
  1023. }
  1024. out:
  1025. if (val)
  1026. json_decref(val);
  1027. return ret;
  1028. }
  1029. extern bool parse_stratum_response(struct pool *, char *s);
  1030. bool auth_stratum(struct pool *pool)
  1031. {
  1032. json_t *val = NULL, *res_val, *err_val;
  1033. char s[RBUFSIZE], *sret = NULL;
  1034. json_error_t err;
  1035. bool ret = false;
  1036. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1037. pool->rpc_user, pool->rpc_pass);
  1038. if (!stratum_send(pool, s, strlen(s)))
  1039. goto out;
  1040. /* Parse all data in the queue and anything left should be auth */
  1041. while (42) {
  1042. sret = recv_line(pool);
  1043. if (!sret)
  1044. goto out;
  1045. if (parse_method(pool, sret))
  1046. free(sret);
  1047. else
  1048. break;
  1049. }
  1050. val = JSON_LOADS(sret, &err);
  1051. free(sret);
  1052. res_val = json_object_get(val, "result");
  1053. err_val = json_object_get(val, "error");
  1054. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1055. char *ss;
  1056. if (err_val)
  1057. ss = json_dumps(err_val, JSON_INDENT(3));
  1058. else
  1059. ss = strdup("(unknown reason)");
  1060. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1061. free(ss);
  1062. goto out;
  1063. }
  1064. ret = true;
  1065. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1066. pool->stratum_auth = true;
  1067. out:
  1068. if (val)
  1069. json_decref(val);
  1070. return ret;
  1071. }
  1072. bool initiate_stratum(struct pool *pool)
  1073. {
  1074. json_t *val = NULL, *res_val, *err_val;
  1075. char curl_err_str[CURL_ERROR_SIZE];
  1076. char s[RBUFSIZE], *sret = NULL;
  1077. CURL *curl = NULL;
  1078. json_error_t err;
  1079. bool ret = false;
  1080. mutex_lock(&pool->stratum_lock);
  1081. pool->swork.transparency_time = (time_t)-1;
  1082. pool->stratum_active = false;
  1083. pool->stratum_auth = false;
  1084. if (!pool->stratum_curl) {
  1085. pool->stratum_curl = curl_easy_init();
  1086. if (unlikely(!pool->stratum_curl))
  1087. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1088. }
  1089. pool->readbuf.len = 0;
  1090. mutex_unlock(&pool->stratum_lock);
  1091. curl = pool->stratum_curl;
  1092. /* Create a http url for use with curl */
  1093. memset(s, 0, RBUFSIZE);
  1094. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1095. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1096. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1097. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1098. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1099. curl_easy_setopt(curl, CURLOPT_URL, s);
  1100. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1101. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1102. if (pool->rpc_proxy) {
  1103. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1104. } else if (opt_socks_proxy) {
  1105. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1106. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1107. }
  1108. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1109. pool->sock = INVSOCK;
  1110. if (curl_easy_perform(curl)) {
  1111. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1112. goto out;
  1113. }
  1114. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1115. keep_sockalive(pool->sock);
  1116. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1117. if (!__stratum_send(pool, s, strlen(s))) {
  1118. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1119. goto out;
  1120. }
  1121. if (!sock_full(pool, true)) {
  1122. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1123. goto out;
  1124. }
  1125. sret = recv_line(pool);
  1126. if (!sret)
  1127. goto out;
  1128. val = JSON_LOADS(sret, &err);
  1129. free(sret);
  1130. if (!val) {
  1131. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1132. goto out;
  1133. }
  1134. res_val = json_object_get(val, "result");
  1135. err_val = json_object_get(val, "error");
  1136. if (!res_val || json_is_null(res_val) ||
  1137. (err_val && !json_is_null(err_val))) {
  1138. char *ss;
  1139. if (err_val)
  1140. ss = json_dumps(err_val, JSON_INDENT(3));
  1141. else
  1142. ss = strdup("(unknown reason)");
  1143. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1144. free(ss);
  1145. goto out;
  1146. }
  1147. free(pool->nonce1);
  1148. pool->nonce1 = json_array_string(res_val, 1);
  1149. if (!pool->nonce1) {
  1150. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1151. goto out;
  1152. }
  1153. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1154. if (!pool->n2size) {
  1155. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1156. goto out;
  1157. }
  1158. ret = true;
  1159. out:
  1160. if (val)
  1161. json_decref(val);
  1162. if (ret) {
  1163. if (!pool->stratum_url)
  1164. pool->stratum_url = pool->sockaddr_url;
  1165. pool->stratum_active = true;
  1166. pool->swork.diff = 1;
  1167. if (opt_protocol) {
  1168. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1169. pool->pool_no, pool->nonce1, pool->n2size);
  1170. }
  1171. } else
  1172. {
  1173. applog(LOG_DEBUG, "Initiate stratum failed");
  1174. if (pool->sock != INVSOCK) {
  1175. shutdown(pool->sock, SHUT_RDWR);
  1176. pool->sock = INVSOCK;
  1177. }
  1178. }
  1179. return ret;
  1180. }