util.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  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. if (err_val)
  401. s = json_dumps(err_val, JSON_INDENT(3));
  402. else
  403. s = strdup("(unknown reason)");
  404. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  405. free(s);
  406. goto err_out;
  407. }
  408. if (hi.reason) {
  409. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  410. free(hi.reason);
  411. hi.reason = NULL;
  412. }
  413. successful_connect = true;
  414. databuf_free(&all_data);
  415. curl_slist_free_all(headers);
  416. curl_easy_reset(curl);
  417. return val;
  418. err_out:
  419. databuf_free(&all_data);
  420. curl_slist_free_all(headers);
  421. curl_easy_reset(curl);
  422. if (!successful_connect)
  423. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  424. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  425. return NULL;
  426. }
  427. bool our_curl_supports_proxy_uris()
  428. {
  429. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  430. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  431. }
  432. /* Returns a malloced array string of a binary value of arbitrary length. The
  433. * array is rounded up to a 4 byte size to appease architectures that need
  434. * aligned array sizes */
  435. char *bin2hex(const unsigned char *p, size_t len)
  436. {
  437. unsigned int i;
  438. ssize_t slen;
  439. char *s;
  440. slen = len * 2 + 1;
  441. if (slen % 4)
  442. slen += 4 - (slen % 4);
  443. s = calloc(slen, 1);
  444. if (unlikely(!s))
  445. quit(1, "Failed to calloc in bin2hex");
  446. for (i = 0; i < len; i++)
  447. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  448. return s;
  449. }
  450. /* Does the reverse of bin2hex but does not allocate any ram */
  451. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  452. {
  453. bool ret = false;
  454. while (*hexstr && len) {
  455. char hex_byte[4];
  456. unsigned int v;
  457. if (unlikely(!hexstr[1])) {
  458. applog(LOG_ERR, "hex2bin str truncated");
  459. return ret;
  460. }
  461. memset(hex_byte, 0, 4);
  462. hex_byte[0] = hexstr[0];
  463. hex_byte[1] = hexstr[1];
  464. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  465. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  466. return ret;
  467. }
  468. *p = (unsigned char) v;
  469. p++;
  470. hexstr += 2;
  471. len--;
  472. }
  473. if (likely(len == 0 && *hexstr == 0))
  474. ret = true;
  475. return ret;
  476. }
  477. bool fulltest(const unsigned char *hash, const unsigned char *target)
  478. {
  479. unsigned char hash_swap[32], target_swap[32];
  480. uint32_t *hash32 = (uint32_t *) hash_swap;
  481. uint32_t *target32 = (uint32_t *) target_swap;
  482. char *hash_str, *target_str;
  483. bool rc = true;
  484. int i;
  485. swap256(hash_swap, hash);
  486. swap256(target_swap, target);
  487. for (i = 0; i < 32/4; i++) {
  488. uint32_t h32tmp = swab32(hash32[i]);
  489. uint32_t t32tmp = target32[i];
  490. target32[i] = swab32(target32[i]); /* for printing */
  491. if (h32tmp > t32tmp) {
  492. rc = false;
  493. break;
  494. }
  495. if (h32tmp < t32tmp) {
  496. rc = true;
  497. break;
  498. }
  499. }
  500. if (opt_debug) {
  501. hash_str = bin2hex(hash_swap, 32);
  502. target_str = bin2hex(target_swap, 32);
  503. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  504. hash_str,
  505. target_str,
  506. rc ? "YES (hash < target)" :
  507. "no (false positive; hash > target)");
  508. free(hash_str);
  509. free(target_str);
  510. }
  511. return rc;
  512. }
  513. struct thread_q *tq_new(void)
  514. {
  515. struct thread_q *tq;
  516. tq = calloc(1, sizeof(*tq));
  517. if (!tq)
  518. return NULL;
  519. INIT_LIST_HEAD(&tq->q);
  520. pthread_mutex_init(&tq->mutex, NULL);
  521. pthread_cond_init(&tq->cond, NULL);
  522. return tq;
  523. }
  524. void tq_free(struct thread_q *tq)
  525. {
  526. struct tq_ent *ent, *iter;
  527. if (!tq)
  528. return;
  529. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  530. list_del(&ent->q_node);
  531. free(ent);
  532. }
  533. pthread_cond_destroy(&tq->cond);
  534. pthread_mutex_destroy(&tq->mutex);
  535. memset(tq, 0, sizeof(*tq)); /* poison */
  536. free(tq);
  537. }
  538. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  539. {
  540. mutex_lock(&tq->mutex);
  541. tq->frozen = frozen;
  542. pthread_cond_signal(&tq->cond);
  543. mutex_unlock(&tq->mutex);
  544. }
  545. void tq_freeze(struct thread_q *tq)
  546. {
  547. tq_freezethaw(tq, true);
  548. }
  549. void tq_thaw(struct thread_q *tq)
  550. {
  551. tq_freezethaw(tq, false);
  552. }
  553. bool tq_push(struct thread_q *tq, void *data)
  554. {
  555. struct tq_ent *ent;
  556. bool rc = true;
  557. ent = calloc(1, sizeof(*ent));
  558. if (!ent)
  559. return false;
  560. ent->data = data;
  561. INIT_LIST_HEAD(&ent->q_node);
  562. mutex_lock(&tq->mutex);
  563. if (!tq->frozen) {
  564. list_add_tail(&ent->q_node, &tq->q);
  565. } else {
  566. free(ent);
  567. rc = false;
  568. }
  569. pthread_cond_signal(&tq->cond);
  570. mutex_unlock(&tq->mutex);
  571. return rc;
  572. }
  573. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  574. {
  575. struct tq_ent *ent;
  576. void *rval = NULL;
  577. int rc;
  578. mutex_lock(&tq->mutex);
  579. if (!list_empty(&tq->q))
  580. goto pop;
  581. if (abstime)
  582. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  583. else
  584. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  585. if (rc)
  586. goto out;
  587. if (list_empty(&tq->q))
  588. goto out;
  589. pop:
  590. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  591. rval = ent->data;
  592. list_del(&ent->q_node);
  593. free(ent);
  594. out:
  595. mutex_unlock(&tq->mutex);
  596. return rval;
  597. }
  598. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  599. {
  600. return pthread_create(&thr->pth, attr, start, arg);
  601. }
  602. void thr_info_freeze(struct thr_info *thr)
  603. {
  604. struct tq_ent *ent, *iter;
  605. struct thread_q *tq;
  606. if (!thr)
  607. return;
  608. tq = thr->q;
  609. if (!tq)
  610. return;
  611. mutex_lock(&tq->mutex);
  612. tq->frozen = true;
  613. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  614. list_del(&ent->q_node);
  615. free(ent);
  616. }
  617. mutex_unlock(&tq->mutex);
  618. }
  619. void thr_info_cancel(struct thr_info *thr)
  620. {
  621. if (!thr)
  622. return;
  623. if (PTH(thr) != 0L) {
  624. pthread_cancel(thr->pth);
  625. PTH(thr) = 0L;
  626. }
  627. }
  628. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  629. * on SMP machines */
  630. void nmsleep(unsigned int msecs)
  631. {
  632. struct timespec twait, tleft;
  633. int ret;
  634. ldiv_t d;
  635. d = ldiv(msecs, 1000);
  636. tleft.tv_sec = d.quot;
  637. tleft.tv_nsec = d.rem * 1000000;
  638. do {
  639. twait.tv_sec = tleft.tv_sec;
  640. twait.tv_nsec = tleft.tv_nsec;
  641. ret = nanosleep(&twait, &tleft);
  642. } while (ret == -1 && errno == EINTR);
  643. }
  644. /* Returns the microseconds difference between end and start times as a double */
  645. double us_tdiff(struct timeval *end, struct timeval *start)
  646. {
  647. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  648. }
  649. void rename_thr(const char* name) {
  650. #if defined(PR_SET_NAME)
  651. // Only the first 15 characters are used (16 - NUL terminator)
  652. prctl(PR_SET_NAME, name, 0, 0, 0);
  653. #elif defined(__APPLE__)
  654. pthread_setname_np(name);
  655. #elif defined(__FreeBSD__) || defined(__OpenBSD__)
  656. pthread_set_name_np(pthread_self(), name);
  657. #else
  658. // Prevent warnings for unused parameters...
  659. (void)name;
  660. #endif
  661. }
  662. /* Returns the seconds difference between end and start times as a double */
  663. double tdiff(struct timeval *end, struct timeval *start)
  664. {
  665. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  666. }
  667. bool extract_sockaddr(struct pool *pool, char *url)
  668. {
  669. char *url_begin, *url_end, *port_start = NULL;
  670. char url_address[256], port[6];
  671. struct addrinfo hints, *res;
  672. int url_len, port_len = 0;
  673. pool->sockaddr_url = url;
  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. pool->stratum_port = strdup(port);
  696. memset(&hints, 0, sizeof(struct addrinfo));
  697. hints.ai_family = AF_UNSPEC;
  698. hints.ai_socktype = SOCK_STREAM;
  699. hints.ai_protocol = IPPROTO_TCP;
  700. if (getaddrinfo(url_address, port, &hints, &res)) {
  701. applog(LOG_DEBUG, "Failed to extract sock addr");
  702. return false;
  703. }
  704. pool->server = (struct sockaddr_in *)res->ai_addr;
  705. pool->sockaddr_url = strdup(url_address);
  706. return true;
  707. }
  708. /* Send a single command across a socket, appending \n to it. This should all
  709. * be done under stratum lock except when first establishing the socket */
  710. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  711. {
  712. SOCKETTYPE sock = pool->sock;
  713. ssize_t ssent = 0;
  714. if (opt_protocol)
  715. applog(LOG_DEBUG, "SEND: %s", s);
  716. strcat(s, "\n");
  717. len++;
  718. while (len > 0 ) {
  719. struct timeval timeout = {0, 0};
  720. size_t sent = 0;
  721. CURLcode rc;
  722. fd_set wd;
  723. FD_ZERO(&wd);
  724. FD_SET(sock, &wd);
  725. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  726. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  727. return false;
  728. }
  729. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  730. if (rc != CURLE_OK) {
  731. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  732. return false;
  733. }
  734. ssent += sent;
  735. len -= ssent;
  736. }
  737. return true;
  738. }
  739. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  740. {
  741. bool ret = false;
  742. mutex_lock(&pool->stratum_lock);
  743. if (pool->stratum_active)
  744. ret = __stratum_send(pool, s, len);
  745. else
  746. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  747. mutex_unlock(&pool->stratum_lock);
  748. return ret;
  749. }
  750. static void clear_sock(struct pool *pool)
  751. {
  752. size_t n = 0;
  753. mutex_lock(&pool->stratum_lock);
  754. /* Ignore return code of curl_easy_recv since we're just clearing
  755. * anything in the socket if it's still alive */
  756. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  757. mutex_unlock(&pool->stratum_lock);
  758. strcpy(pool->sockbuf, "");
  759. }
  760. /* Check to see if Santa's been good to you */
  761. static bool sock_full(struct pool *pool, bool wait)
  762. {
  763. SOCKETTYPE sock = pool->sock;
  764. struct timeval timeout;
  765. fd_set rd;
  766. if (strlen(pool->sockbuf))
  767. return true;
  768. FD_ZERO(&rd);
  769. FD_SET(sock, &rd);
  770. timeout.tv_usec = 0;
  771. if (wait)
  772. timeout.tv_sec = 60;
  773. else
  774. timeout.tv_sec = 0;
  775. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  776. return true;
  777. return false;
  778. }
  779. /* Peeks at a socket to find the first end of line and then reads just that
  780. * from the socket and returns that as a malloced char */
  781. char *recv_line(struct pool *pool)
  782. {
  783. ssize_t len, buflen;
  784. char *tok, *sret = NULL;
  785. size_t n = 0;
  786. if (!strstr(pool->sockbuf, "\n")) {
  787. char s[RBUFSIZE];
  788. size_t sspace;
  789. CURLcode rc;
  790. if (!sock_full(pool, true)) {
  791. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  792. goto out;
  793. }
  794. memset(s, 0, RBUFSIZE);
  795. mutex_lock(&pool->stratum_lock);
  796. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  797. mutex_unlock(&pool->stratum_lock);
  798. if (rc != CURLE_OK) {
  799. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  800. goto out;
  801. }
  802. /* Prevent buffer overflows, but if 8k is still not enough,
  803. * likely we have had some comms issues and the data is all
  804. * useless anyway */
  805. sspace = RECVSIZE - strlen(pool->sockbuf);
  806. strncat(pool->sockbuf, s, sspace);
  807. }
  808. buflen = strlen(pool->sockbuf);
  809. tok = strtok(pool->sockbuf, "\n");
  810. if (!tok) {
  811. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  812. goto out;
  813. }
  814. sret = strdup(tok);
  815. len = strlen(sret);
  816. /* Copy what's left in the buffer after the \n, including the
  817. * terminating \0 */
  818. if (buflen > len + 1)
  819. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  820. else
  821. strcpy(pool->sockbuf, "");
  822. out:
  823. if (!sret)
  824. clear_sock(pool);
  825. else if (opt_protocol)
  826. applog(LOG_DEBUG, "RECVD: %s", sret);
  827. return sret;
  828. }
  829. /* Extracts a string value from a json array with error checking. To be used
  830. * when the value of the string returned is only examined and not to be stored.
  831. * See json_array_string below */
  832. static char *__json_array_string(json_t *val, unsigned int entry)
  833. {
  834. json_t *arr_entry;
  835. if (json_is_null(val))
  836. return NULL;
  837. if (!json_is_array(val))
  838. return NULL;
  839. if (entry > json_array_size(val))
  840. return NULL;
  841. arr_entry = json_array_get(val, entry);
  842. if (!json_is_string(arr_entry))
  843. return NULL;
  844. return (char *)json_string_value(arr_entry);
  845. }
  846. /* Creates a freshly malloced dup of __json_array_string */
  847. static char *json_array_string(json_t *val, unsigned int entry)
  848. {
  849. char *buf = __json_array_string(val, entry);
  850. if (buf)
  851. return strdup(buf);
  852. return NULL;
  853. }
  854. static bool parse_notify(struct pool *pool, json_t *val)
  855. {
  856. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  857. int merkles, i;
  858. json_t *arr;
  859. bool clean;
  860. arr = json_array_get(val, 4);
  861. if (!arr || !json_is_array(arr))
  862. return false;
  863. merkles = json_array_size(arr);
  864. job_id = json_array_string(val, 0);
  865. prev_hash = json_array_string(val, 1);
  866. coinbase1 = json_array_string(val, 2);
  867. coinbase2 = json_array_string(val, 3);
  868. bbversion = json_array_string(val, 5);
  869. nbit = json_array_string(val, 6);
  870. ntime = json_array_string(val, 7);
  871. clean = json_is_true(json_array_get(val, 8));
  872. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  873. /* Annoying but we must not leak memory */
  874. if (job_id)
  875. free(job_id);
  876. if (prev_hash)
  877. free(prev_hash);
  878. if (coinbase1)
  879. free(coinbase1);
  880. if (coinbase2)
  881. free(coinbase2);
  882. if (bbversion)
  883. free(bbversion);
  884. if (nbit)
  885. free(nbit);
  886. if (ntime)
  887. free(ntime);
  888. return false;
  889. }
  890. mutex_lock(&pool->pool_lock);
  891. pool->swork.job_id = job_id;
  892. pool->swork.prev_hash = prev_hash;
  893. pool->swork.coinbase1 = coinbase1;
  894. pool->swork.coinbase2 = coinbase2;
  895. pool->swork.bbversion = bbversion;
  896. pool->swork.nbit = nbit;
  897. pool->swork.ntime = ntime;
  898. pool->swork.clean = clean;
  899. for (i = 0; i < pool->swork.merkles; i++)
  900. free(pool->swork.merkle[i]);
  901. if (merkles) {
  902. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  903. for (i = 0; i < merkles; i++)
  904. pool->swork.merkle[i] = json_array_string(arr, i);
  905. }
  906. pool->swork.merkles = merkles;
  907. if (clean)
  908. pool->nonce2 = 0;
  909. mutex_unlock(&pool->pool_lock);
  910. if (opt_protocol) {
  911. applog(LOG_DEBUG, "job_id: %s", job_id);
  912. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  913. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  914. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  915. for (i = 0; i < merkles; i++)
  916. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  917. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  918. applog(LOG_DEBUG, "nbit: %s", nbit);
  919. applog(LOG_DEBUG, "ntime: %s", ntime);
  920. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  921. }
  922. /* A notify message is the closest stratum gets to a getwork */
  923. pool->getwork_requested++;
  924. total_getworks++;
  925. return true;
  926. }
  927. static bool parse_diff(struct pool *pool, json_t *val)
  928. {
  929. int diff;
  930. diff = json_integer_value(json_array_get(val, 0));
  931. if (diff < 1)
  932. return false;
  933. mutex_lock(&pool->pool_lock);
  934. pool->swork.diff = diff;
  935. mutex_unlock(&pool->pool_lock);
  936. applog(LOG_DEBUG, "Pool %d difficulty set to %d", pool->pool_no, diff);
  937. return true;
  938. }
  939. static bool parse_reconnect(struct pool *pool, json_t *val)
  940. {
  941. char *url, *port, address[256];
  942. memset(address, 0, 255);
  943. url = (char *)json_string_value(json_array_get(val, 0));
  944. if (!url)
  945. url = pool->sockaddr_url;
  946. port = (char *)json_string_value(json_array_get(val, 1));
  947. if (!port)
  948. port = pool->stratum_port;
  949. sprintf(address, "%s:%s", url, port);
  950. if (!extract_sockaddr(pool, address))
  951. return false;
  952. pool->stratum_url = pool->sockaddr_url;
  953. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  954. if (!initiate_stratum(pool) || !auth_stratum(pool))
  955. return false;
  956. return true;
  957. }
  958. static bool send_version(struct pool *pool, json_t *val)
  959. {
  960. char s[RBUFSIZE];
  961. int id = json_integer_value(json_object_get(val, "id"));
  962. if (!id)
  963. return false;
  964. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  965. if (!stratum_send(pool, s, strlen(s)))
  966. return false;
  967. return true;
  968. }
  969. bool parse_method(struct pool *pool, char *s)
  970. {
  971. json_t *val = NULL, *method, *err_val, *params;
  972. json_error_t err;
  973. bool ret = false;
  974. char *buf;
  975. if (!s)
  976. goto out;
  977. val = JSON_LOADS(s, &err);
  978. if (!val) {
  979. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  980. goto out;
  981. }
  982. method = json_object_get(val, "method");
  983. if (!method)
  984. goto out;
  985. err_val = json_object_get(val, "error");
  986. params = json_object_get(val, "params");
  987. if (err_val && !json_is_null(err_val)) {
  988. char *ss;
  989. if (err_val)
  990. ss = json_dumps(err_val, JSON_INDENT(3));
  991. else
  992. ss = strdup("(unknown reason)");
  993. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  994. free(ss);
  995. goto out;
  996. }
  997. buf = (char *)json_string_value(method);
  998. if (!buf)
  999. goto out;
  1000. if (!strncasecmp(buf, "mining.notify", 13) && parse_notify(pool, params)) {
  1001. ret = true;
  1002. goto out;
  1003. }
  1004. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1005. ret = true;
  1006. goto out;
  1007. }
  1008. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1009. ret = true;
  1010. goto out;
  1011. }
  1012. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1013. ret = true;
  1014. goto out;
  1015. }
  1016. out:
  1017. if (val)
  1018. json_decref(val);
  1019. return ret;
  1020. }
  1021. bool auth_stratum(struct pool *pool)
  1022. {
  1023. json_t *val = NULL, *res_val, *err_val;
  1024. char s[RBUFSIZE], *sret = NULL;
  1025. json_error_t err;
  1026. bool ret = false;
  1027. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1028. swork_id++, pool->rpc_user, pool->rpc_pass);
  1029. /* Parse all data prior sending auth request */
  1030. while (sock_full(pool, false)) {
  1031. sret = recv_line(pool);
  1032. if (!parse_method(pool, sret)) {
  1033. clear_sock(pool);
  1034. applog(LOG_INFO, "Failed to parse stratum buffer");
  1035. free(sret);
  1036. return ret;
  1037. }
  1038. free(sret);
  1039. }
  1040. if (!stratum_send(pool, s, strlen(s)))
  1041. goto out;
  1042. sret = recv_line(pool);
  1043. if (!sret)
  1044. goto out;
  1045. val = JSON_LOADS(sret, &err);
  1046. free(sret);
  1047. res_val = json_object_get(val, "result");
  1048. err_val = json_object_get(val, "error");
  1049. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1050. char *ss;
  1051. if (err_val)
  1052. ss = json_dumps(err_val, JSON_INDENT(3));
  1053. else
  1054. ss = strdup("(unknown reason)");
  1055. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1056. free(ss);
  1057. goto out;
  1058. }
  1059. ret = true;
  1060. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1061. out:
  1062. if (val)
  1063. json_decref(val);
  1064. return ret;
  1065. }
  1066. bool initiate_stratum(struct pool *pool)
  1067. {
  1068. json_t *val = NULL, *res_val, *err_val;
  1069. char curl_err_str[CURL_ERROR_SIZE];
  1070. char s[RBUFSIZE], *sret = NULL;
  1071. CURL *curl = NULL;
  1072. json_error_t err;
  1073. bool ret = false;
  1074. mutex_lock(&pool->stratum_lock);
  1075. pool->stratum_active = false;
  1076. if (!pool->stratum_curl) {
  1077. pool->stratum_curl = curl_easy_init();
  1078. if (unlikely(!pool->stratum_curl))
  1079. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1080. }
  1081. mutex_unlock(&pool->stratum_lock);
  1082. curl = pool->stratum_curl;
  1083. /* Create a http url for use with curl */
  1084. memset(s, 0, RBUFSIZE);
  1085. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1086. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1087. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1088. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1089. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1090. curl_easy_setopt(curl, CURLOPT_URL, s);
  1091. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1092. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1093. if (pool->rpc_proxy) {
  1094. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1095. } else if (opt_socks_proxy) {
  1096. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1097. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1098. }
  1099. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1100. if (curl_easy_perform(curl)) {
  1101. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1102. goto out;
  1103. }
  1104. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1105. keep_sockalive(pool->sock);
  1106. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1107. if (!__stratum_send(pool, s, strlen(s))) {
  1108. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1109. goto out;
  1110. }
  1111. if (!sock_full(pool, true)) {
  1112. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1113. goto out;
  1114. }
  1115. sret = recv_line(pool);
  1116. if (!sret)
  1117. goto out;
  1118. val = JSON_LOADS(sret, &err);
  1119. free(sret);
  1120. if (!val) {
  1121. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1122. goto out;
  1123. }
  1124. res_val = json_object_get(val, "result");
  1125. err_val = json_object_get(val, "error");
  1126. if (!res_val || json_is_null(res_val) ||
  1127. (err_val && !json_is_null(err_val))) {
  1128. char *ss;
  1129. if (err_val)
  1130. ss = json_dumps(err_val, JSON_INDENT(3));
  1131. else
  1132. ss = strdup("(unknown reason)");
  1133. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1134. free(ss);
  1135. goto out;
  1136. }
  1137. pool->nonce1 = json_array_string(res_val, 1);
  1138. if (!pool->nonce1) {
  1139. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1140. goto out;
  1141. }
  1142. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1143. if (!pool->n2size) {
  1144. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1145. goto out;
  1146. }
  1147. ret = true;
  1148. out:
  1149. if (val)
  1150. json_decref(val);
  1151. if (ret) {
  1152. if (!pool->stratum_url)
  1153. pool->stratum_url = pool->sockaddr_url;
  1154. pool->stratum_active = true;
  1155. pool->swork.diff = 1;
  1156. if (opt_protocol) {
  1157. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1158. pool->pool_no, pool->nonce1, pool->n2size);
  1159. }
  1160. } else
  1161. applog(LOG_DEBUG, "Initiate stratum failed");
  1162. return ret;
  1163. }