util.c 33 KB

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