util.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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. url_begin = strstr(url, "//");
  674. if (!url_begin)
  675. url_begin = url;
  676. else
  677. url_begin += 2;
  678. url_end = strstr(url_begin, ":");
  679. if (url_end) {
  680. url_len = url_end - url_begin;
  681. port_len = strlen(url_begin) - url_len - 1;
  682. if (port_len < 1)
  683. return false;
  684. port_start = url_end + 1;
  685. } else
  686. url_len = strlen(url_begin);
  687. if (url_len < 1)
  688. return false;
  689. sprintf(url_address, "%.*s", url_len, url_begin);
  690. if (port_len)
  691. snprintf(port, 6, "%.*s", port_len, port_start);
  692. else
  693. strcpy(port, "80");
  694. free(pool->stratum_port);
  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. free(pool->sockaddr_url);
  706. pool->sockaddr_url = strdup(url_address);
  707. return true;
  708. }
  709. /* Send a single command across a socket, appending \n to it. This should all
  710. * be done under stratum lock except when first establishing the socket */
  711. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  712. {
  713. SOCKETTYPE sock = pool->sock;
  714. ssize_t ssent = 0;
  715. if (opt_protocol)
  716. applog(LOG_DEBUG, "SEND: %s", s);
  717. strcat(s, "\n");
  718. len++;
  719. while (len > 0 ) {
  720. struct timeval timeout = {0, 0};
  721. size_t sent = 0;
  722. CURLcode rc;
  723. fd_set wd;
  724. FD_ZERO(&wd);
  725. FD_SET(sock, &wd);
  726. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  727. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  728. return false;
  729. }
  730. rc = curl_easy_send(pool->stratum_curl, s + ssent, len, &sent);
  731. if (rc != CURLE_OK) {
  732. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  733. return false;
  734. }
  735. ssent += sent;
  736. len -= ssent;
  737. }
  738. return true;
  739. }
  740. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  741. {
  742. bool ret = false;
  743. mutex_lock(&pool->stratum_lock);
  744. if (pool->stratum_active)
  745. ret = __stratum_send(pool, s, len);
  746. else
  747. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  748. mutex_unlock(&pool->stratum_lock);
  749. return ret;
  750. }
  751. static void clear_sock(struct pool *pool)
  752. {
  753. size_t n = 0;
  754. mutex_lock(&pool->stratum_lock);
  755. /* Ignore return code of curl_easy_recv since we're just clearing
  756. * anything in the socket if it's still alive */
  757. curl_easy_recv(pool->stratum_curl, pool->sockbuf, RECVSIZE, &n);
  758. mutex_unlock(&pool->stratum_lock);
  759. strcpy(pool->sockbuf, "");
  760. }
  761. /* Check to see if Santa's been good to you */
  762. static bool sock_full(struct pool *pool, bool wait)
  763. {
  764. SOCKETTYPE sock = pool->sock;
  765. struct timeval timeout;
  766. fd_set rd;
  767. if (strlen(pool->sockbuf))
  768. return true;
  769. FD_ZERO(&rd);
  770. FD_SET(sock, &rd);
  771. timeout.tv_usec = 0;
  772. if (wait)
  773. timeout.tv_sec = 60;
  774. else
  775. timeout.tv_sec = 0;
  776. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  777. return true;
  778. return false;
  779. }
  780. /* Peeks at a socket to find the first end of line and then reads just that
  781. * from the socket and returns that as a malloced char */
  782. char *recv_line(struct pool *pool)
  783. {
  784. ssize_t len, buflen;
  785. char *tok, *sret = NULL;
  786. size_t n = 0;
  787. if (!strstr(pool->sockbuf, "\n")) {
  788. char s[RBUFSIZE];
  789. size_t sspace;
  790. CURLcode rc;
  791. if (!sock_full(pool, true)) {
  792. applog(LOG_DEBUG, "Timed out waiting for data on sock_full");
  793. goto out;
  794. }
  795. memset(s, 0, RBUFSIZE);
  796. mutex_lock(&pool->stratum_lock);
  797. rc = curl_easy_recv(pool->stratum_curl, s, RECVSIZE, &n);
  798. mutex_unlock(&pool->stratum_lock);
  799. if (rc != CURLE_OK) {
  800. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  801. goto out;
  802. }
  803. /* Prevent buffer overflows, but if 8k is still not enough,
  804. * likely we have had some comms issues and the data is all
  805. * useless anyway */
  806. sspace = RECVSIZE - strlen(pool->sockbuf);
  807. strncat(pool->sockbuf, s, sspace);
  808. }
  809. buflen = strlen(pool->sockbuf);
  810. tok = strtok(pool->sockbuf, "\n");
  811. if (!tok) {
  812. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  813. goto out;
  814. }
  815. sret = strdup(tok);
  816. len = strlen(sret);
  817. /* Copy what's left in the buffer after the \n, including the
  818. * terminating \0 */
  819. if (buflen > len + 1)
  820. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  821. else
  822. strcpy(pool->sockbuf, "");
  823. out:
  824. if (!sret)
  825. clear_sock(pool);
  826. else if (opt_protocol)
  827. applog(LOG_DEBUG, "RECVD: %s", sret);
  828. return sret;
  829. }
  830. /* Extracts a string value from a json array with error checking. To be used
  831. * when the value of the string returned is only examined and not to be stored.
  832. * See json_array_string below */
  833. static char *__json_array_string(json_t *val, unsigned int entry)
  834. {
  835. json_t *arr_entry;
  836. if (json_is_null(val))
  837. return NULL;
  838. if (!json_is_array(val))
  839. return NULL;
  840. if (entry > json_array_size(val))
  841. return NULL;
  842. arr_entry = json_array_get(val, entry);
  843. if (!json_is_string(arr_entry))
  844. return NULL;
  845. return (char *)json_string_value(arr_entry);
  846. }
  847. /* Creates a freshly malloced dup of __json_array_string */
  848. static char *json_array_string(json_t *val, unsigned int entry)
  849. {
  850. char *buf = __json_array_string(val, entry);
  851. if (buf)
  852. return strdup(buf);
  853. return NULL;
  854. }
  855. static bool parse_notify(struct pool *pool, json_t *val)
  856. {
  857. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  858. int merkles, i;
  859. json_t *arr;
  860. bool clean;
  861. arr = json_array_get(val, 4);
  862. if (!arr || !json_is_array(arr))
  863. return false;
  864. merkles = json_array_size(arr);
  865. job_id = json_array_string(val, 0);
  866. prev_hash = json_array_string(val, 1);
  867. coinbase1 = json_array_string(val, 2);
  868. coinbase2 = json_array_string(val, 3);
  869. bbversion = json_array_string(val, 5);
  870. nbit = json_array_string(val, 6);
  871. ntime = json_array_string(val, 7);
  872. clean = json_is_true(json_array_get(val, 8));
  873. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  874. /* Annoying but we must not leak memory */
  875. if (job_id)
  876. free(job_id);
  877. if (prev_hash)
  878. free(prev_hash);
  879. if (coinbase1)
  880. free(coinbase1);
  881. if (coinbase2)
  882. free(coinbase2);
  883. if (bbversion)
  884. free(bbversion);
  885. if (nbit)
  886. free(nbit);
  887. if (ntime)
  888. free(ntime);
  889. return false;
  890. }
  891. mutex_lock(&pool->pool_lock);
  892. free(pool->swork.job_id);
  893. free(pool->swork.prev_hash);
  894. free(pool->swork.coinbase1);
  895. free(pool->swork.coinbase2);
  896. free(pool->swork.bbversion);
  897. free(pool->swork.nbit);
  898. free(pool->swork.ntime);
  899. pool->swork.job_id = job_id;
  900. pool->swork.prev_hash = prev_hash;
  901. pool->swork.coinbase1 = coinbase1;
  902. pool->swork.coinbase2 = coinbase2;
  903. pool->swork.bbversion = bbversion;
  904. pool->swork.nbit = nbit;
  905. pool->swork.ntime = ntime;
  906. pool->swork.clean = clean;
  907. for (i = 0; i < pool->swork.merkles; i++)
  908. free(pool->swork.merkle[i]);
  909. if (merkles) {
  910. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  911. for (i = 0; i < merkles; i++)
  912. pool->swork.merkle[i] = json_array_string(arr, i);
  913. }
  914. pool->swork.merkles = merkles;
  915. if (clean)
  916. pool->nonce2 = 0;
  917. mutex_unlock(&pool->pool_lock);
  918. if (opt_protocol) {
  919. applog(LOG_DEBUG, "job_id: %s", job_id);
  920. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  921. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  922. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  923. for (i = 0; i < merkles; i++)
  924. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  925. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  926. applog(LOG_DEBUG, "nbit: %s", nbit);
  927. applog(LOG_DEBUG, "ntime: %s", ntime);
  928. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  929. }
  930. /* A notify message is the closest stratum gets to a getwork */
  931. pool->getwork_requested++;
  932. total_getworks++;
  933. return true;
  934. }
  935. static bool parse_diff(struct pool *pool, json_t *val)
  936. {
  937. int diff;
  938. diff = json_integer_value(json_array_get(val, 0));
  939. if (diff < 1)
  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 %d", 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. bool auth_stratum(struct pool *pool)
  1030. {
  1031. json_t *val = NULL, *res_val, *err_val;
  1032. char s[RBUFSIZE], *sret = NULL;
  1033. json_error_t err;
  1034. bool ret = false;
  1035. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1036. swork_id++, pool->rpc_user, pool->rpc_pass);
  1037. /* Parse all data prior sending auth request */
  1038. while (sock_full(pool, false)) {
  1039. sret = recv_line(pool);
  1040. if (!parse_method(pool, sret)) {
  1041. clear_sock(pool);
  1042. applog(LOG_INFO, "Failed to parse stratum buffer");
  1043. free(sret);
  1044. return ret;
  1045. }
  1046. free(sret);
  1047. }
  1048. if (!stratum_send(pool, s, strlen(s)))
  1049. goto out;
  1050. sret = recv_line(pool);
  1051. if (!sret)
  1052. goto out;
  1053. val = JSON_LOADS(sret, &err);
  1054. free(sret);
  1055. res_val = json_object_get(val, "result");
  1056. err_val = json_object_get(val, "error");
  1057. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1058. char *ss;
  1059. if (err_val)
  1060. ss = json_dumps(err_val, JSON_INDENT(3));
  1061. else
  1062. ss = strdup("(unknown reason)");
  1063. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1064. free(ss);
  1065. goto out;
  1066. }
  1067. ret = true;
  1068. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1069. out:
  1070. if (val)
  1071. json_decref(val);
  1072. return ret;
  1073. }
  1074. bool initiate_stratum(struct pool *pool)
  1075. {
  1076. json_t *val = NULL, *res_val, *err_val;
  1077. char curl_err_str[CURL_ERROR_SIZE];
  1078. char s[RBUFSIZE], *sret = NULL;
  1079. CURL *curl = NULL;
  1080. json_error_t err;
  1081. bool ret = false;
  1082. mutex_lock(&pool->stratum_lock);
  1083. pool->stratum_active = 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. mutex_unlock(&pool->stratum_lock);
  1090. curl = pool->stratum_curl;
  1091. /* Create a http url for use with curl */
  1092. memset(s, 0, RBUFSIZE);
  1093. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1094. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1095. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1096. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1097. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1098. curl_easy_setopt(curl, CURLOPT_URL, s);
  1099. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1100. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1101. if (pool->rpc_proxy) {
  1102. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1103. } else if (opt_socks_proxy) {
  1104. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1105. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1106. }
  1107. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1108. if (curl_easy_perform(curl)) {
  1109. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1110. goto out;
  1111. }
  1112. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1113. keep_sockalive(pool->sock);
  1114. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1115. if (!__stratum_send(pool, s, strlen(s))) {
  1116. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1117. goto out;
  1118. }
  1119. if (!sock_full(pool, true)) {
  1120. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1121. goto out;
  1122. }
  1123. sret = recv_line(pool);
  1124. if (!sret)
  1125. goto out;
  1126. val = JSON_LOADS(sret, &err);
  1127. free(sret);
  1128. if (!val) {
  1129. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1130. goto out;
  1131. }
  1132. res_val = json_object_get(val, "result");
  1133. err_val = json_object_get(val, "error");
  1134. if (!res_val || json_is_null(res_val) ||
  1135. (err_val && !json_is_null(err_val))) {
  1136. char *ss;
  1137. if (err_val)
  1138. ss = json_dumps(err_val, JSON_INDENT(3));
  1139. else
  1140. ss = strdup("(unknown reason)");
  1141. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1142. free(ss);
  1143. goto out;
  1144. }
  1145. pool->nonce1 = json_array_string(res_val, 1);
  1146. if (!pool->nonce1) {
  1147. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1148. goto out;
  1149. }
  1150. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1151. if (!pool->n2size) {
  1152. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1153. goto out;
  1154. }
  1155. ret = true;
  1156. out:
  1157. if (val)
  1158. json_decref(val);
  1159. if (ret) {
  1160. if (!pool->stratum_url)
  1161. pool->stratum_url = pool->sockaddr_url;
  1162. pool->stratum_active = true;
  1163. pool->swork.diff = 1;
  1164. if (opt_protocol) {
  1165. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1166. pool->pool_no, pool->nonce1, pool->n2size);
  1167. }
  1168. } else
  1169. applog(LOG_DEBUG, "Initiate stratum failed");
  1170. return ret;
  1171. }