2 * Copyright 2010 Jeff Garzik
3 * Copyright 2012 Luke Dashjr
4 * Copyright 2012-2014 pooler
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the Free
8 * Software Foundation; either version 2 of the License, or (at your option)
9 * any later version. See COPYING for more details.
13 #include <cpuminer-config.h>
26 #include <curl/curl.h>
32 #include "compat/winansi.h"
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <netinet/tcp.h>
40 /* dirname() linux/mingw, else in compat.h */
47 extern pthread_mutex_t stats_lock;
54 struct upload_buffer {
68 struct list_head q_node;
76 pthread_mutex_t mutex;
80 void applog(int prio, const char *fmt, ...)
92 /* custom colors to syslog prio */
93 if (prio > LOG_DEBUG) {
95 case LOG_BLUE: prio = LOG_NOTICE; break;
100 len = vsnprintf(NULL, 0, fmt, ap2) + 1;
103 if (vsnprintf(buf, len, fmt, ap) >= 0)
104 syslog(prio, "%s", buf);
110 const char* color = "";
114 time_t now = time(NULL);
116 localtime_r(&now, &tm);
119 case LOG_ERR: color = CL_RED; break;
120 case LOG_WARNING: color = CL_YLW; break;
121 case LOG_NOTICE: color = CL_WHT; break;
122 case LOG_INFO: color = ""; break;
123 case LOG_DEBUG: color = CL_GRY; break;
133 len = 64 + (int) strlen(fmt) + 2;
134 f = (char*) malloc(len);
135 sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]%s %s%s\n",
144 use_colors ? CL_N : ""
146 pthread_mutex_lock(&applog_lock);
147 vfprintf(stdout, f, ap); /* atomic write to stdout */
150 pthread_mutex_unlock(&applog_lock);
155 /* Get default config.json path (will be system specific) */
156 void get_defconfig_path(char *out, size_t bufsize, char *argv0)
158 char *cmd = strdup(argv0);
159 char *dir = dirname(cmd);
160 const char *sep = strstr(dir, "\\") ? "\\" : "/";
161 struct stat info = { 0 };
163 snprintf(out, bufsize, "%s\\cpuminer\\cpuminer-conf.json", getenv("APPDATA"));
165 snprintf(out, bufsize, "%s\\.cpuminer\\cpuminer-conf.json", getenv("HOME"));
167 if (dir && stat(out, &info) != 0) {
168 snprintf(out, bufsize, "%s%scpuminer-conf.json", dir, sep);
170 if (stat(out, &info) != 0) {
174 out[bufsize - 1] = '\0';
179 void format_hashrate(double hashrate, char *output)
183 if (hashrate < 10000) {
186 else if (hashrate < 1e7) {
190 else if (hashrate < 1e10) {
194 else if (hashrate < 1e13) {
205 prefix ? "%.2f %cH/s" : "%.2f H/s%c",
210 /* Modify the representation of integer numbers which would cause an overflow
211 * so that they are treated as floating-point numbers.
212 * This is a hack to overcome the limitations of some versions of Jansson. */
213 static char *hack_json_numbers(const char *in)
219 out = (char*) calloc(2 * strlen(in) + 1, 1);
223 in_str = in_int = false;
224 for (i = 0; in[i]; i++) {
228 } else if (c == '\\') {
232 } else if (!in_str && !in_int && isdigit(c)) {
235 } else if (in_int && !isdigit(c)) {
236 if (c != '.' && c != 'e' && c != 'E' && c != '+' && c != '-') {
238 if (off - intoff > 4) {
240 #if JSON_INTEGER_IS_LONG_LONG
242 strtoll(out + intoff, &end, 10);
243 if (!*end && errno == ERANGE) {
247 l = strtol(out + intoff, &end, 10);
248 if (!*end && (errno == ERANGE || l > INT_MAX)) {
261 static void databuf_free(struct data_buffer *db)
268 memset(db, 0, sizeof(*db));
271 static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
274 struct data_buffer *db = (struct data_buffer *) user_data;
275 size_t len = size * nmemb;
276 size_t oldlen, newlen;
278 static const unsigned char zero = 0;
281 newlen = oldlen + len;
283 newmem = realloc(db->buf, newlen + 1);
289 memcpy((uchar*) db->buf + oldlen, ptr, len);
290 memcpy((uchar*) db->buf + newlen, &zero, 1); /* null terminate */
295 static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
298 struct upload_buffer *ub = (struct upload_buffer *) user_data;
299 size_t len = size * nmemb;
301 if (len > ub->len - ub->pos)
302 len = ub->len - ub->pos;
305 memcpy(ptr, ((uchar*)ub->buf) + ub->pos, len);
312 #if LIBCURL_VERSION_NUM >= 0x071200
313 static int seek_data_cb(void *user_data, curl_off_t offset, int origin)
315 struct upload_buffer *ub = (struct upload_buffer *) user_data;
319 ub->pos = (size_t) offset;
322 ub->pos += (size_t) offset;
325 ub->pos = ub->len + (size_t) offset;
328 return 1; /* CURL_SEEKFUNC_FAIL */
331 return 0; /* CURL_SEEKFUNC_OK */
335 static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
337 struct header_info *hi = (struct header_info *) user_data;
338 size_t remlen, slen, ptrlen = size * nmemb;
339 char *rem, *val = NULL, *key = NULL;
342 val = (char*) calloc(1, ptrlen);
343 key = (char*) calloc(1, ptrlen);
347 tmp = memchr(ptr, ':', ptrlen);
348 if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
350 slen = (char*)tmp - (char*)ptr;
351 if ((slen + 1) == ptrlen) /* skip key w/ no value */
353 memcpy(key, ptr, slen); /* store & nul term key */
356 rem = (char*)ptr + slen + 1; /* trim value's leading whitespace */
357 remlen = ptrlen - slen - 1;
358 while ((remlen > 0) && (isspace(*rem))) {
363 memcpy(val, rem, remlen); /* store value, trim trailing ws */
365 while ((*val) && (isspace(val[strlen(val) - 1]))) {
366 val[strlen(val) - 1] = 0;
369 if (!strcasecmp("X-Long-Polling", key)) {
370 hi->lp_path = val; /* steal memory reference */
374 if (!strcasecmp("X-Reject-Reason", key)) {
375 hi->reason = val; /* steal memory reference */
379 if (!strcasecmp("X-Stratum", key)) {
380 hi->stratum_url = val; /* steal memory reference */
390 #if LIBCURL_VERSION_NUM >= 0x070f06
391 static int sockopt_keepalive_cb(void *userdata, curl_socket_t fd,
392 curlsocktype purpose)
397 int tcp_keepintvl = 50;
398 int tcp_keepidle = 50;
401 if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive,
405 if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT,
406 &tcp_keepcnt, sizeof(tcp_keepcnt))))
408 if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE,
409 &tcp_keepidle, sizeof(tcp_keepidle))))
411 if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL,
412 &tcp_keepintvl, sizeof(tcp_keepintvl))))
416 if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE,
417 &tcp_keepintvl, sizeof(tcp_keepintvl))))
419 #endif /* __APPLE_CC__ */
421 struct tcp_keepalive vals;
423 vals.keepalivetime = tcp_keepidle * 1000;
424 vals.keepaliveinterval = tcp_keepintvl * 1000;
426 if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals),
427 NULL, 0, &outputBytes, NULL, NULL)))
435 json_t *json_rpc_call(CURL *curl, const char *url,
436 const char *userpass, const char *rpc_req,
437 int *curl_err, int flags)
439 json_t *val, *err_val, *res_val;
442 struct data_buffer all_data = {0};
443 struct upload_buffer upload_data;
446 struct curl_slist *headers = NULL;
448 char curl_err_str[CURL_ERROR_SIZE] = { 0 };
449 long timeout = (flags & JSON_RPC_LONGPOLL) ? opt_timeout : 30;
450 struct header_info hi = {0};
452 /* it is assumed that 'curl' is freshly [re]initialized at this pt */
455 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
456 curl_easy_setopt(curl, CURLOPT_URL, url);
458 curl_easy_setopt(curl, CURLOPT_CAINFO, opt_cert);
459 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
460 curl_easy_setopt(curl, CURLOPT_ENCODING, "");
461 curl_easy_setopt(curl, CURLOPT_FAILONERROR, 0);
462 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
463 curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
464 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
465 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
466 curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
467 curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
468 #if LIBCURL_VERSION_NUM >= 0x071200
469 curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, &seek_data_cb);
470 curl_easy_setopt(curl, CURLOPT_SEEKDATA, &upload_data);
472 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
474 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
475 curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
476 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
477 curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
479 curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
480 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
483 curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
484 curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
486 #if LIBCURL_VERSION_NUM >= 0x070f06
487 if (flags & JSON_RPC_LONGPOLL)
488 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb);
490 curl_easy_setopt(curl, CURLOPT_POST, 1);
493 applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);
495 upload_data.buf = rpc_req;
496 upload_data.len = strlen(rpc_req);
498 sprintf(len_hdr, "Content-Length: %lu",
499 (unsigned long) upload_data.len);
501 headers = curl_slist_append(headers, "Content-Type: application/json");
502 headers = curl_slist_append(headers, len_hdr);
503 headers = curl_slist_append(headers, "User-Agent: " USER_AGENT);
504 headers = curl_slist_append(headers, "X-Mining-Extensions: longpoll reject-reason");
505 //headers = curl_slist_append(headers, "Accept:"); /* disable Accept hdr*/
506 //headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
508 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
510 rc = curl_easy_perform(curl);
511 if (curl_err != NULL)
514 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_rc);
515 if (!((flags & JSON_RPC_LONGPOLL) && rc == CURLE_OPERATION_TIMEDOUT) &&
516 !((flags & JSON_RPC_QUIET_404) && http_rc == 404))
517 applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
518 if (curl_err && (flags & JSON_RPC_QUIET_404) && http_rc == 404)
519 *curl_err = CURLE_OK;
523 /* If X-Stratum was found, activate Stratum */
524 if (want_stratum && hi.stratum_url &&
525 !strncasecmp(hi.stratum_url, "stratum+tcp://", 14)) {
527 tq_push(thr_info[stratum_thr_id].q, hi.stratum_url);
528 hi.stratum_url = NULL;
531 /* If X-Long-Polling was found, activate long polling */
532 if (!have_longpoll && want_longpoll && hi.lp_path && !have_gbt &&
533 allow_getwork && !have_stratum) {
534 have_longpoll = true;
535 tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
540 applog(LOG_ERR, "Empty data received in json_rpc_call.");
544 json_buf = hack_json_numbers((char*) all_data.buf);
545 errno = 0; /* needed for Jansson < 2.1 */
546 val = JSON_LOADS(json_buf, &err);
549 applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
554 char *s = json_dumps(val, JSON_INDENT(3));
555 applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
559 /* JSON-RPC valid response returns a 'result' and a null 'error'. */
560 res_val = json_object_get(val, "result");
561 err_val = json_object_get(val, "error");
563 if (!res_val || (err_val && !json_is_null(err_val)
564 && !(flags & JSON_RPC_IGNOREERR))) {
569 s = json_dumps(err_val, 0);
570 json_t *msg = json_object_get(err_val, "message");
571 json_t *err_code = json_object_get(err_val, "code");
572 if (curl_err && json_integer_value(err_code))
573 *curl_err = (int)json_integer_value(err_code);
575 if (msg && json_is_string(msg)) {
577 s = strdup(json_string_value(msg));
578 if (have_longpoll && s && !strcmp(s, "method not getwork")) {
579 json_decref(err_val);
584 json_decref(err_val);
587 s = strdup("(unknown reason)");
589 if (!curl_err || opt_debug)
590 applog(LOG_ERR, "JSON-RPC call failed: %s", s);
598 json_object_set_new(val, "reject-reason", json_string(hi.reason));
600 databuf_free(&all_data);
601 curl_slist_free_all(headers);
602 curl_easy_reset(curl);
608 free(hi.stratum_url);
609 databuf_free(&all_data);
610 curl_slist_free_all(headers);
611 curl_easy_reset(curl);
615 /* used to load a remote config */
616 json_t* json_load_url(char* cfg_url, json_error_t *err)
618 char err_str[CURL_ERROR_SIZE] = { 0 };
619 struct data_buffer all_data = { 0 };
620 int rc = 0; json_t *cfg = NULL;
621 CURL *curl = curl_easy_init();
622 if (unlikely(!curl)) {
623 applog(LOG_ERR, "Remote config init failed!");
626 curl_easy_setopt(curl, CURLOPT_URL, cfg_url);
627 curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
628 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15);
629 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, err_str);
630 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
631 curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
632 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
633 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
635 curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
636 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
637 } else if (getenv("http_proxy")) {
638 if (getenv("all_proxy"))
639 curl_easy_setopt(curl, CURLOPT_PROXY, getenv("all_proxy"));
640 else if (getenv("ALL_PROXY"))
641 curl_easy_setopt(curl, CURLOPT_PROXY, getenv("ALL_PROXY"));
643 curl_easy_setopt(curl, CURLOPT_PROXY, "");
645 rc = curl_easy_perform(curl);
647 applog(LOG_ERR, "Remote config read failed: %s", err_str);
650 if (!all_data.buf || !all_data.len) {
651 applog(LOG_ERR, "Empty data received for config");
655 cfg = JSON_LOADS((char*)all_data.buf, err);
657 curl_easy_cleanup(curl);
661 void bin2hex(char *s, const unsigned char *p, size_t len)
663 for (size_t i = 0; i < len; i++)
664 sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
667 char *abin2hex(const unsigned char *p, size_t len)
669 char *s = (char*) malloc((len * 2) + 1);
676 bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
683 while (*hexstr && len) {
685 applog(LOG_ERR, "hex2bin str truncated");
688 hex_byte[0] = hexstr[0];
689 hex_byte[1] = hexstr[1];
690 *p = (unsigned char) strtol(hex_byte, &ep, 16);
692 applog(LOG_ERR, "hex2bin failed on '%s'", hex_byte);
700 return(!len) ? true : false;
701 /* return (len == 0 && *hexstr == 0) ? true : false; */
704 int varint_encode(unsigned char *p, uint64_t n)
714 p[2] = (uchar) (n >> 8);
717 if (n <= 0xffffffff) {
719 for (i = 1; i < 5; i++) {
726 for (i = 1; i < 9; i++) {
733 static const char b58digits[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
735 static bool b58dec(unsigned char *bin, size_t binsz, const char *b58)
741 size_t outisz = (binsz + 3) / 4;
743 uint32_t remmask = 0xffffffff << (8 * rem);
744 size_t b58sz = strlen(b58);
747 outi = (uint32_t *) calloc(outisz, sizeof(*outi));
749 for (i = 0; i < b58sz; ++i) {
750 for (c = 0; b58digits[c] != b58[i]; c++)
753 for (j = outisz; j--; ) {
754 t = (uint64_t)outi[j] * 58 + c;
756 outi[j] = t & 0xffffffff;
758 if (c || outi[0] & remmask)
765 *(bin++) = (outi[0] >> 16) & 0xff;
767 *(bin++) = (outi[0] >> 8) & 0xff;
769 *(bin++) = outi[0] & 0xff;
774 for (; j < outisz; ++j) {
775 be32enc((uint32_t *)bin, outi[j]);
776 bin += sizeof(uint32_t);
785 static int b58check(unsigned char *bin, size_t binsz, const char *b58)
787 unsigned char buf[32];
790 sha256d(buf, bin, (int) (binsz - 4));
791 if (memcmp(&bin[binsz - 4], buf, 4))
794 /* Check number of zeros is correct AFTER verifying checksum
795 * (to avoid possibility of accessing the string beyond the end) */
796 for (i = 0; bin[i] == '\0' && b58[i] == '1'; ++i);
797 if (bin[i] == '\0' || b58[i] == '1')
803 bool jobj_binary(const json_t *obj, const char *key, void *buf, size_t buflen)
808 tmp = json_object_get(obj, key);
809 if (unlikely(!tmp)) {
810 applog(LOG_ERR, "JSON key '%s' not found", key);
813 hexstr = json_string_value(tmp);
814 if (unlikely(!hexstr)) {
815 applog(LOG_ERR, "JSON key '%s' is not a string", key);
818 if (!hex2bin((uchar*) buf, hexstr, buflen))
824 size_t address_to_script(unsigned char *out, size_t outsz, const char *addr)
826 unsigned char addrbin[25];
830 if (!b58dec(addrbin, sizeof(addrbin), addr))
832 addrver = b58check(addrbin, sizeof(addrbin), addr);
836 case 5: /* Bitcoin script hash */
837 case 196: /* Testnet script hash */
838 if (outsz < (rv = 23))
840 out[ 0] = 0xa9; /* OP_HASH160 */
841 out[ 1] = 0x14; /* push 20 bytes */
842 memcpy(&out[2], &addrbin[1], 20);
843 out[22] = 0x87; /* OP_EQUAL */
846 if (outsz < (rv = 25))
848 out[ 0] = 0x76; /* OP_DUP */
849 out[ 1] = 0xa9; /* OP_HASH160 */
850 out[ 2] = 0x14; /* push 20 bytes */
851 memcpy(&out[3], &addrbin[1], 20);
852 out[23] = 0x88; /* OP_EQUALVERIFY */
853 out[24] = 0xac; /* OP_CHECKSIG */
858 /* Subtract the `struct timeval' values X and Y,
859 storing the result in RESULT.
860 Return 1 if the difference is negative, otherwise 0. */
861 int timeval_subtract(struct timeval *result, struct timeval *x,
864 /* Perform the carry for the later subtraction by updating Y. */
865 if (x->tv_usec < y->tv_usec) {
866 int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
867 y->tv_usec -= 1000000 * nsec;
870 if (x->tv_usec - y->tv_usec > 1000000) {
871 int nsec = (x->tv_usec - y->tv_usec) / 1000000;
872 y->tv_usec += 1000000 * nsec;
876 /* Compute the time remaining to wait.
877 * `tv_usec' is certainly positive. */
878 result->tv_sec = x->tv_sec - y->tv_sec;
879 result->tv_usec = x->tv_usec - y->tv_usec;
881 /* Return 1 if result is negative. */
882 return x->tv_sec < y->tv_sec;
885 bool fulltest(const uint32_t *hash, const uint32_t *target)
890 for (i = 7; i >= 0; i--) {
891 if (hash[i] > target[i]) {
895 if (hash[i] < target[i]) {
902 uint32_t hash_be[8], target_be[8];
903 char hash_str[65], target_str[65];
905 for (i = 0; i < 8; i++) {
906 be32enc(hash_be + i, hash[7 - i]);
907 be32enc(target_be + i, target[7 - i]);
909 bin2hex(hash_str, (unsigned char *)hash_be, 32);
910 bin2hex(target_str, (unsigned char *)target_be, 32);
912 applog(LOG_DEBUG, "DEBUG: %s\nHash: %s\nTarget: %s",
913 rc ? "hash <= target"
914 : "hash > target (false positive)",
922 void diff_to_target(uint32_t *target, double diff)
927 for (k = 6; k > 0 && diff > 1.0; k--)
928 diff /= 4294967296.0;
929 m = (uint64_t)(4294901760.0 / diff);
930 if (m == 0 && k == 6)
931 memset(target, 0xff, 32);
933 memset(target, 0, 32);
934 target[k] = (uint32_t)m;
935 target[k + 1] = (uint32_t)(m >> 32);
939 // Only used by stratum pools
940 void work_set_target(struct work* work, double diff)
942 diff_to_target(work->target, diff);
943 work->targetdiff = diff;
946 // Only used by longpoll pools
947 double target_to_diff(uint32_t* target)
949 uchar* tgt = (uchar*) target;
951 (uint64_t)tgt[29] << 56 |
952 (uint64_t)tgt[28] << 48 |
953 (uint64_t)tgt[27] << 40 |
954 (uint64_t)tgt[26] << 32 |
955 (uint64_t)tgt[25] << 24 |
956 (uint64_t)tgt[24] << 16 |
957 (uint64_t)tgt[23] << 8 |
958 (uint64_t)tgt[22] << 0;
963 return (double)0x0000ffff00000000/m;
967 #define socket_blocks() (WSAGetLastError() == WSAEWOULDBLOCK)
969 #define socket_blocks() (errno == EAGAIN || errno == EWOULDBLOCK)
972 static bool send_line(curl_socket_t sock, char *s)
977 len = (int) strlen(s);
981 struct timeval timeout = {0, 0};
987 if (select((int) (sock + 1), NULL, &wd, NULL, &timeout) < 1)
989 n = send(sock, s + sent, len, 0);
991 if (!socket_blocks())
1002 bool stratum_send_line(struct stratum_ctx *sctx, char *s)
1007 applog(LOG_DEBUG, "> %s", s);
1009 pthread_mutex_lock(&sctx->sock_lock);
1010 ret = send_line(sctx->sock, s);
1011 pthread_mutex_unlock(&sctx->sock_lock);
1016 static bool socket_full(curl_socket_t sock, int timeout)
1023 tv.tv_sec = timeout;
1025 if (select((int)(sock + 1), &rd, NULL, NULL, &tv) > 0)
1030 bool stratum_socket_full(struct stratum_ctx *sctx, int timeout)
1032 return strlen(sctx->sockbuf) || socket_full(sctx->sock, timeout);
1035 #define RBUFSIZE 2048
1036 #define RECVSIZE (RBUFSIZE - 4)
1038 static void stratum_buffer_append(struct stratum_ctx *sctx, const char *s)
1042 old = strlen(sctx->sockbuf);
1043 n = old + strlen(s) + 1;
1044 if (n >= sctx->sockbuf_size) {
1045 sctx->sockbuf_size = n + (RBUFSIZE - (n % RBUFSIZE));
1046 sctx->sockbuf = (char*) realloc(sctx->sockbuf, sctx->sockbuf_size);
1048 strcpy(sctx->sockbuf + old, s);
1051 char *stratum_recv_line(struct stratum_ctx *sctx)
1053 ssize_t len, buflen;
1054 char *tok, *sret = NULL;
1056 if (!strstr(sctx->sockbuf, "\n")) {
1061 if (!socket_full(sctx->sock, 60)) {
1062 applog(LOG_ERR, "stratum_recv_line timed out");
1069 memset(s, 0, RBUFSIZE);
1070 n = recv(sctx->sock, s, RECVSIZE, 0);
1076 if (!socket_blocks() || !socket_full(sctx->sock, 1)) {
1081 stratum_buffer_append(sctx, s);
1082 } while (time(NULL) - rstart < 60 && !strstr(sctx->sockbuf, "\n"));
1085 applog(LOG_ERR, "stratum_recv_line failed");
1090 buflen = (ssize_t) strlen(sctx->sockbuf);
1091 tok = strtok(sctx->sockbuf, "\n");
1093 applog(LOG_ERR, "stratum_recv_line failed to parse a newline-terminated string");
1097 len = (ssize_t) strlen(sret);
1099 if (buflen > len + 1)
1100 memmove(sctx->sockbuf, sctx->sockbuf + len + 1, buflen - len + 1);
1102 sctx->sockbuf[0] = '\0';
1105 if (sret && opt_protocol)
1106 applog(LOG_DEBUG, "< %s", sret);
1110 #if LIBCURL_VERSION_NUM >= 0x071101
1111 static curl_socket_t opensocket_grab_cb(void *clientp, curlsocktype purpose,
1112 struct curl_sockaddr *addr)
1114 curl_socket_t *sock = (curl_socket_t*) clientp;
1115 *sock = socket(addr->family, addr->socktype, addr->protocol);
1120 bool stratum_connect(struct stratum_ctx *sctx, const char *url)
1125 pthread_mutex_lock(&sctx->sock_lock);
1127 curl_easy_cleanup(sctx->curl);
1128 sctx->curl = curl_easy_init();
1130 applog(LOG_ERR, "CURL initialization failed");
1131 pthread_mutex_unlock(&sctx->sock_lock);
1135 if (!sctx->sockbuf) {
1136 sctx->sockbuf = (char*) calloc(RBUFSIZE, 1);
1137 sctx->sockbuf_size = RBUFSIZE;
1139 sctx->sockbuf[0] = '\0';
1140 pthread_mutex_unlock(&sctx->sock_lock);
1142 if (url != sctx->url) {
1144 sctx->url = strdup(url);
1146 free(sctx->curl_url);
1147 sctx->curl_url = (char*) malloc(strlen(url));
1148 sprintf(sctx->curl_url, "http%s", strstr(url, "://"));
1151 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
1152 curl_easy_setopt(curl, CURLOPT_URL, sctx->curl_url);
1153 curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
1154 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
1155 curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, sctx->curl_err_str);
1156 curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
1157 curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
1159 curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
1160 curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
1162 curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
1163 #if LIBCURL_VERSION_NUM >= 0x070f06
1164 curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb);
1166 #if LIBCURL_VERSION_NUM >= 0x071101
1167 curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, opensocket_grab_cb);
1168 curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, &sctx->sock);
1170 curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
1172 rc = curl_easy_perform(curl);
1174 applog(LOG_ERR, "Stratum connection failed: %s", sctx->curl_err_str);
1175 curl_easy_cleanup(curl);
1180 #if LIBCURL_VERSION_NUM < 0x071101
1181 /* CURLINFO_LASTSOCKET is broken on Win64; only use it as a last resort */
1182 curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sctx->sock);
1188 void stratum_disconnect(struct stratum_ctx *sctx)
1190 pthread_mutex_lock(&sctx->sock_lock);
1192 curl_easy_cleanup(sctx->curl);
1194 sctx->sockbuf[0] = '\0';
1196 pthread_mutex_unlock(&sctx->sock_lock);
1199 static const char *get_stratum_session_id(json_t *val)
1204 arr_val = json_array_get(val, 0);
1205 if (!arr_val || !json_is_array(arr_val))
1207 n = (int) json_array_size(arr_val);
1208 for (i = 0; i < n; i++) {
1210 json_t *arr = json_array_get(arr_val, i);
1212 if (!arr || !json_is_array(arr))
1214 notify = json_string_value(json_array_get(arr, 0));
1217 if (!strcasecmp(notify, "mining.notify"))
1218 return json_string_value(json_array_get(arr, 1));
1223 static bool stratum_parse_extranonce(struct stratum_ctx *sctx, json_t *params, int pndx)
1225 const char* xnonce1;
1228 xnonce1 = json_string_value(json_array_get(params, pndx));
1230 applog(LOG_ERR, "Failed to get extranonce1");
1233 xn2_size = (int) json_integer_value(json_array_get(params, pndx+1));
1235 applog(LOG_ERR, "Failed to get extranonce2_size");
1238 if (xn2_size < 2 || xn2_size > 16) {
1239 applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
1243 pthread_mutex_lock(&sctx->work_lock);
1245 free(sctx->xnonce1);
1246 sctx->xnonce1_size = strlen(xnonce1) / 2;
1247 sctx->xnonce1 = (uchar*) calloc(1, sctx->xnonce1_size);
1248 if (unlikely(!sctx->xnonce1)) {
1249 applog(LOG_ERR, "Failed to alloc xnonce1");
1250 pthread_mutex_unlock(&sctx->work_lock);
1253 hex2bin(sctx->xnonce1, xnonce1, sctx->xnonce1_size);
1254 sctx->xnonce2_size = xn2_size;
1255 pthread_mutex_unlock(&sctx->work_lock);
1257 if (pndx == 0 && opt_debug) /* pool dynamic change */
1258 applog(LOG_DEBUG, "Stratum set nonce %s with extranonce2 size=%d",
1266 bool stratum_subscribe(struct stratum_ctx *sctx)
1268 char *s, *sret = NULL;
1270 json_t *val = NULL, *res_val, *err_val;
1272 bool ret = false, retry = false;
1278 s = (char*) malloc(128 + (sctx->session_id ? strlen(sctx->session_id) : 0));
1280 sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}");
1281 else if (sctx->session_id)
1282 sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": [\"" USER_AGENT "\", \"%s\"]}", sctx->session_id);
1284 sprintf(s, "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": [\"" USER_AGENT "\"]}");
1286 if (!stratum_send_line(sctx, s)) {
1287 applog(LOG_ERR, "stratum_subscribe send failed");
1291 if (!socket_full(sctx->sock, 30)) {
1292 applog(LOG_ERR, "stratum_subscribe timed out");
1296 sret = stratum_recv_line(sctx);
1300 val = JSON_LOADS(sret, &err);
1303 applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
1307 res_val = json_object_get(val, "result");
1308 err_val = json_object_get(val, "error");
1310 if (!res_val || json_is_null(res_val) ||
1311 (err_val && !json_is_null(err_val))) {
1312 if (opt_debug || retry) {
1315 s = json_dumps(err_val, JSON_INDENT(3));
1317 s = strdup("(unknown reason)");
1318 applog(LOG_ERR, "JSON-RPC call failed: %s", s);
1323 sid = get_stratum_session_id(res_val);
1324 if (opt_debug && sid)
1325 applog(LOG_DEBUG, "Stratum session id: %s", sid);
1327 pthread_mutex_lock(&sctx->work_lock);
1328 if (sctx->session_id)
1329 free(sctx->session_id);
1330 sctx->session_id = sid ? strdup(sid) : NULL;
1331 sctx->next_diff = 1.0;
1332 pthread_mutex_unlock(&sctx->work_lock);
1334 // sid is param 1, extranonce params are 2 and 3
1335 if (!stratum_parse_extranonce(sctx, res_val, 1)) {
1347 if (sret && !retry) {
1356 extern bool opt_extranonce;
1358 bool stratum_authorize(struct stratum_ctx *sctx, const char *user, const char *pass)
1360 json_t *val = NULL, *res_val, *err_val;
1366 s = (char*) malloc(300 + strlen(user) + strlen(pass));
1367 sprintf(s, "{\"method\": \"login\", \"params\": {"
1368 "\"login\": \"%s\", \"pass\": \"%s\", \"agent\": \"%s\"}, \"id\": 1}",
1369 user, pass, USER_AGENT);
1371 s = (char*) malloc(80 + strlen(user) + strlen(pass));
1372 sprintf(s, "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
1376 if (!stratum_send_line(sctx, s))
1380 sret = stratum_recv_line(sctx);
1383 if (!stratum_handle_method(sctx, sret))
1388 val = JSON_LOADS(sret, &err);
1391 applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
1395 res_val = json_object_get(val, "result");
1396 err_val = json_object_get(val, "error");
1398 if (!res_val || json_is_false(res_val) ||
1399 (err_val && !json_is_null(err_val))) {
1400 applog(LOG_ERR, "Stratum authentication failed");
1405 rpc2_login_decode(val);
1406 json_t *job_val = json_object_get(res_val, "job");
1407 pthread_mutex_lock(&sctx->work_lock);
1408 if(job_val) rpc2_job_decode(job_val, &sctx->work);
1409 pthread_mutex_unlock(&sctx->work_lock);
1414 if (!opt_extranonce)
1417 // subscribe to extranonce (optional)
1418 sprintf(s, "{\"id\": 3, \"method\": \"mining.extranonce.subscribe\", \"params\": []}");
1420 if (!stratum_send_line(sctx, s))
1423 if (!socket_full(sctx->sock, 3)) {
1425 applog(LOG_DEBUG, "stratum extranonce subscribe timed out");
1429 sret = stratum_recv_line(sctx);
1431 json_t *extra = JSON_LOADS(sret, &err);
1433 applog(LOG_WARNING, "JSON decode failed(%d): %s", err.line, err.text);
1435 if (json_integer_value(json_object_get(extra, "id")) != 3) {
1436 // we receive a standard method if extranonce is ignored
1437 if (!stratum_handle_method(sctx, sret))
1438 applog(LOG_WARNING, "Stratum answer id is not correct!");
1453 // -------------------- RPC 2.0 (XMR/AEON) -------------------------
1455 extern pthread_mutex_t rpc2_login_lock;
1456 extern pthread_mutex_t rpc2_job_lock;
1458 bool rpc2_login_decode(const json_t *val)
1463 json_t *res = json_object_get(val, "result");
1465 applog(LOG_ERR, "JSON invalid result");
1470 tmp = json_object_get(res, "id");
1472 applog(LOG_ERR, "JSON inval id");
1475 id = json_string_value(tmp);
1477 applog(LOG_ERR, "JSON id is not a string");
1481 memcpy(&rpc2_id, id, 64);
1484 applog(LOG_DEBUG, "Auth id: %s", id);
1486 tmp = json_object_get(res, "status");
1488 applog(LOG_ERR, "JSON inval status");
1491 s = json_string_value(tmp);
1493 applog(LOG_ERR, "JSON status is not a string");
1496 if(strcmp(s, "OK")) {
1497 applog(LOG_ERR, "JSON returned status \"%s\"", s);
1504 applog(LOG_WARNING,"%s: fail", __func__);
1508 json_t* json_rpc2_call_recur(CURL *curl, const char *url, const char *userpass,
1509 json_t *rpc_req, int *curl_err, int flags, int recur)
1513 applog(LOG_DEBUG, "Failed to call rpc command after %i tries", recur);
1516 if(!strcmp(rpc2_id, "")) {
1518 applog(LOG_DEBUG, "Tried to call rpc2 command before authentication");
1521 json_t *params = json_object_get(rpc_req, "params");
1523 json_t *auth_id = json_object_get(params, "id");
1525 json_string_set(auth_id, rpc2_id);
1528 json_t *res = json_rpc_call(curl, url, userpass, json_dumps(rpc_req, 0),
1529 curl_err, flags | JSON_RPC_IGNOREERR);
1531 json_t *error = json_object_get(res, "error");
1532 if(!error) goto end;
1534 if(json_is_string(error))
1537 message = json_object_get(error, "message");
1538 if(!message || !json_is_string(message)) goto end;
1539 const char *mes = json_string_value(message);
1540 if(!strcmp(mes, "Unauthenticated")) {
1541 pthread_mutex_lock(&rpc2_login_lock);
1544 pthread_mutex_unlock(&rpc2_login_lock);
1545 return json_rpc2_call_recur(curl, url, userpass, rpc_req,
1546 curl_err, flags, recur + 1);
1547 } else if(!strcmp(mes, "Low difficulty share") || !strcmp(mes, "Block expired") || !strcmp(mes, "Invalid job id") || !strcmp(mes, "Duplicate share")) {
1548 json_t *result = json_object_get(res, "result");
1552 json_object_set(result, "reject-reason", json_string(mes));
1554 applog(LOG_ERR, "json_rpc2.0 error: %s", mes);
1561 json_t *json_rpc2_call(CURL *curl, const char *url, const char *userpass, const char *rpc_req, int *curl_err, int flags)
1563 json_t* req_json = JSON_LOADS(rpc_req, NULL);
1564 json_t* res = json_rpc2_call_recur(curl, url, userpass, req_json, curl_err, flags, 0);
1565 json_decref(req_json);
1569 bool rpc2_job_decode(const json_t *job, struct work *work)
1572 applog(LOG_ERR, "Tried to decode job without JSON-RPC 2.0");
1576 tmp = json_object_get(job, "job_id");
1578 applog(LOG_ERR, "JSON invalid job id");
1581 const char *job_id = json_string_value(tmp);
1582 tmp = json_object_get(job, "blob");
1584 applog(LOG_ERR, "JSON invalid blob");
1587 const char *hexblob = json_string_value(tmp);
1588 size_t blobLen = strlen(hexblob);
1589 if (blobLen % 2 != 0 || ((blobLen / 2) < 40 && blobLen != 0) || (blobLen / 2) > 128) {
1590 applog(LOG_ERR, "JSON invalid blob length");
1594 uint32_t target = 0;
1595 pthread_mutex_lock(&rpc2_job_lock);
1596 uchar *blob = (uchar*) malloc(blobLen / 2);
1597 if (!hex2bin(blob, hexblob, blobLen / 2)) {
1598 applog(LOG_ERR, "JSON invalid blob");
1599 pthread_mutex_unlock(&rpc2_job_lock);
1602 rpc2_bloblen = blobLen / 2;
1603 if (rpc2_blob) free(rpc2_blob);
1604 rpc2_blob = (char*) malloc(rpc2_bloblen);
1606 applog(LOG_ERR, "RPC2 OOM!");
1609 memcpy(rpc2_blob, blob, blobLen / 2);
1612 jobj_binary(job, "target", &target, 4);
1613 if(rpc2_target != target) {
1614 double hashrate = 0.0;
1615 pthread_mutex_lock(&stats_lock);
1616 for (int i = 0; i < opt_n_threads; i++)
1617 hashrate += thr_hashrates[i];
1618 pthread_mutex_unlock(&stats_lock);
1619 double difficulty = (((double) 0xffffffff) / target);
1621 // xmr pool diff can change a lot...
1622 applog(LOG_WARNING, "Stratum difficulty set to %g", difficulty);
1624 stratum_diff = difficulty;
1625 rpc2_target = target;
1628 if (rpc2_job_id) free(rpc2_job_id);
1629 rpc2_job_id = strdup(job_id);
1630 pthread_mutex_unlock(&rpc2_job_lock);
1634 applog(LOG_WARNING, "Work requested before it was received");
1637 memcpy(work->data, rpc2_blob, rpc2_bloblen);
1638 memset(work->target, 0xff, sizeof(work->target));
1639 work->target[7] = rpc2_target;
1640 if (work->job_id) free(work->job_id);
1641 work->job_id = strdup(rpc2_job_id);
1646 applog(LOG_WARNING, "%s", __func__);
1651 * Extract bloc height L H... here len=3, height=0x1333e8
1652 * "...0000000000ffffffff2703e83313062f503253482f043d61105408"
1654 static uint32_t getblocheight(struct stratum_ctx *sctx)
1656 uint32_t height = 0;
1657 uint8_t hlen = 0, *p, *m;
1660 p = (uint8_t*) sctx->job.coinbase + 32;
1662 while (*p != 0xff && p < m) p++;
1663 while (*p == 0xff && p < m) p++;
1664 if (*(p-1) == 0xff && *(p-2) == 0xff) {
1666 p++; height = le16dec(p);
1670 height += 0x10000UL * le16dec(p);
1673 height += 0x10000UL * (*p);
1680 static bool stratum_notify(struct stratum_ctx *sctx, json_t *params)
1682 const char *job_id, *prevhash, *coinb1, *coinb2, *version, *nbits, *ntime;
1683 size_t coinb1_size, coinb2_size;
1684 bool clean, ret = false;
1685 int merkle_count, i;
1689 job_id = json_string_value(json_array_get(params, 0));
1690 prevhash = json_string_value(json_array_get(params, 1));
1691 coinb1 = json_string_value(json_array_get(params, 2));
1692 coinb2 = json_string_value(json_array_get(params, 3));
1693 merkle_arr = json_array_get(params, 4);
1694 if (!merkle_arr || !json_is_array(merkle_arr))
1696 merkle_count = (int) json_array_size(merkle_arr);
1697 version = json_string_value(json_array_get(params, 5));
1698 nbits = json_string_value(json_array_get(params, 6));
1699 ntime = json_string_value(json_array_get(params, 7));
1700 clean = json_is_true(json_array_get(params, 8));
1702 if (!job_id || !prevhash || !coinb1 || !coinb2 || !version || !nbits || !ntime ||
1703 strlen(prevhash) != 64 || strlen(version) != 8 ||
1704 strlen(nbits) != 8 || strlen(ntime) != 8) {
1705 applog(LOG_ERR, "Stratum notify: invalid parameters");
1708 merkle = (uchar**) malloc(merkle_count * sizeof(char *));
1709 for (i = 0; i < merkle_count; i++) {
1710 const char *s = json_string_value(json_array_get(merkle_arr, i));
1711 if (!s || strlen(s) != 64) {
1715 applog(LOG_ERR, "Stratum notify: invalid Merkle branch");
1718 merkle[i] = (uchar*) malloc(32);
1719 hex2bin(merkle[i], s, 32);
1722 pthread_mutex_lock(&sctx->work_lock);
1724 coinb1_size = strlen(coinb1) / 2;
1725 coinb2_size = strlen(coinb2) / 2;
1726 sctx->job.coinbase_size = coinb1_size + sctx->xnonce1_size +
1727 sctx->xnonce2_size + coinb2_size;
1728 sctx->job.coinbase = (uchar*) realloc(sctx->job.coinbase, sctx->job.coinbase_size);
1729 sctx->job.xnonce2 = sctx->job.coinbase + coinb1_size + sctx->xnonce1_size;
1730 hex2bin(sctx->job.coinbase, coinb1, coinb1_size);
1731 memcpy(sctx->job.coinbase + coinb1_size, sctx->xnonce1, sctx->xnonce1_size);
1732 if (!sctx->job.job_id || strcmp(sctx->job.job_id, job_id))
1733 memset(sctx->job.xnonce2, 0, sctx->xnonce2_size);
1734 hex2bin(sctx->job.xnonce2 + sctx->xnonce2_size, coinb2, coinb2_size);
1736 free(sctx->job.job_id);
1737 sctx->job.job_id = strdup(job_id);
1738 hex2bin(sctx->job.prevhash, prevhash, 32);
1740 sctx->bloc_height = getblocheight(sctx);
1742 for (i = 0; i < sctx->job.merkle_count; i++)
1743 free(sctx->job.merkle[i]);
1744 free(sctx->job.merkle);
1745 sctx->job.merkle = merkle;
1746 sctx->job.merkle_count = merkle_count;
1748 hex2bin(sctx->job.version, version, 4);
1749 hex2bin(sctx->job.nbits, nbits, 4);
1750 hex2bin(sctx->job.ntime, ntime, 4);
1751 sctx->job.clean = clean;
1753 sctx->job.diff = sctx->next_diff;
1755 pthread_mutex_unlock(&sctx->work_lock);
1763 static bool stratum_set_difficulty(struct stratum_ctx *sctx, json_t *params)
1767 diff = json_number_value(json_array_get(params, 0));
1771 pthread_mutex_lock(&sctx->work_lock);
1772 sctx->next_diff = diff;
1773 pthread_mutex_unlock(&sctx->work_lock);
1778 static bool stratum_reconnect(struct stratum_ctx *sctx, json_t *params)
1785 host = json_string_value(json_array_get(params, 0));
1786 port_val = json_array_get(params, 1);
1787 if (json_is_string(port_val))
1788 port = atoi(json_string_value(port_val));
1790 port = (int) json_integer_value(port_val);
1794 url = (char*) malloc(32 + strlen(host));
1795 sprintf(url, "stratum+tcp://%s:%d", host, port);
1797 if (!opt_redirect) {
1798 applog(LOG_INFO, "Ignoring request to reconnect to %s", url);
1803 applog(LOG_NOTICE, "Server requested reconnection to %s", url);
1807 stratum_disconnect(sctx);
1812 static bool json_object_set_error(json_t *result, int code, const char *msg)
1814 json_t *val = json_object();
1815 json_object_set_new(val, "code", json_integer(code));
1816 json_object_set_new(val, "message", json_string(msg));
1817 return json_object_set_new(result, "error", val) != -1;
1820 /* allow to report algo perf to the pool for algo stats */
1821 static bool stratum_benchdata(json_t *result, json_t *params, int thr_id)
1823 char algo[64] = { 0 };
1824 char cpuname[80] = { 0 };
1825 char vendorid[32] = { 0 };
1826 char compiler[32] = { 0 };
1827 char arch[16] = { 0 };
1833 if (!opt_stratum_stats) return false;
1835 get_currentalgo(algo, sizeof(algo));
1837 #if defined(WIN32) && (defined(_M_X64) || defined(__x86_64__))
1838 strcpy(os, "win64");
1840 strcpy(os, is_windows() ? "win32" : "linux");
1844 sprintf(compiler, "VC++ %d\n", _MSC_VER / 100);
1845 #elif defined(__clang__)
1846 sprintf(compiler, "clang %s\n", __clang_version__);
1847 #elif defined(__GNUC__)
1848 sprintf(compiler, "GCC %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
1852 strcat(compiler, " AVX2");
1853 #elif defined(__AVX__)
1854 strcat(compiler, " AVX");
1855 #elif defined(__FMA4__)
1856 strcat(compiler, " FMA4");
1857 #elif defined(__FMA3__)
1858 strcat(compiler, " FMA3");
1859 #elif defined(__SSE4_2__)
1860 strcat(compiler, " SSE4.2");
1861 #elif defined(__SSE4_1__)
1862 strcat(compiler, " SSE4");
1863 #elif defined(__SSE3__)
1864 strcat(compiler, " SSE3");
1865 #elif defined(__SSE2__)
1866 strcat(compiler, " SSE2");
1867 #elif defined(__SSE__)
1868 strcat(compiler, " SSE");
1871 cpu_bestfeature(arch, 16);
1872 if (has_aes_ni()) strcat(arch, " NI");
1874 cpu_getmodelid(vendorid, 32);
1875 cpu_getname(cpuname, 80);
1876 p = strstr(cpuname, " @ ");
1879 char freq[32] = { 0 };
1881 snprintf(freq, 32, "%s", p);
1882 cpufreq = atof(freq);
1883 p = strstr(freq, "GHz"); if (p) cpufreq *= 1000;
1884 applog(LOG_NOTICE, "sharing CPU stats with freq %s", freq);
1887 compiler[31] = '\0';
1889 val = json_object();
1890 json_object_set_new(val, "algo", json_string(algo));
1891 json_object_set_new(val, "type", json_string("cpu"));
1892 json_object_set_new(val, "device", json_string(cpuname));
1893 json_object_set_new(val, "vendorid", json_string(vendorid));
1894 json_object_set_new(val, "arch", json_string(arch));
1895 json_object_set_new(val, "freq", json_integer((uint64_t)cpufreq));
1896 json_object_set_new(val, "memf", json_integer(0));
1897 json_object_set_new(val, "power", json_integer(0));
1898 json_object_set_new(val, "khashes", json_real((double)global_hashrate / 1000.0));
1899 json_object_set_new(val, "intensity", json_real(opt_priority));
1900 json_object_set_new(val, "throughput", json_integer(opt_n_threads));
1901 json_object_set_new(val, "client", json_string(PACKAGE_NAME "/" PACKAGE_VERSION));
1902 json_object_set_new(val, "os", json_string(os));
1903 json_object_set_new(val, "driver", json_string(compiler));
1905 json_object_set_new(result, "result", val);
1910 static bool stratum_get_stats(struct stratum_ctx *sctx, json_t *id, json_t *params)
1916 if (!id || json_is_null(id))
1919 val = json_object();
1920 json_object_set(val, "id", id);
1922 ret = stratum_benchdata(val, params, 0);
1925 json_object_set_error(val, 1, "disabled"); //EPERM
1927 json_object_set_new(val, "error", json_null());
1930 s = json_dumps(val, 0);
1931 ret = stratum_send_line(sctx, s);
1938 static bool stratum_unknown_method(struct stratum_ctx *sctx, json_t *id)
1944 if (!id || json_is_null(id))
1947 val = json_object();
1948 json_object_set(val, "id", id);
1949 json_object_set_new(val, "result", json_false());
1950 json_object_set_error(val, 38, "unknown method"); // ENOSYS
1952 s = json_dumps(val, 0);
1953 ret = stratum_send_line(sctx, s);
1960 static bool stratum_pong(struct stratum_ctx *sctx, json_t *id)
1965 if (!id || json_is_null(id))
1968 sprintf(buf, "{\"id\":%d,\"result\":\"pong\",\"error\":null}",
1969 (int) json_integer_value(id));
1970 ret = stratum_send_line(sctx, buf);
1975 static bool stratum_get_algo(struct stratum_ctx *sctx, json_t *id, json_t *params)
1977 char algo[64] = { 0 };
1982 if (!id || json_is_null(id))
1985 get_currentalgo(algo, sizeof(algo));
1987 val = json_object();
1988 json_object_set(val, "id", id);
1989 json_object_set_new(val, "error", json_null());
1990 json_object_set_new(val, "result", json_string(algo));
1992 s = json_dumps(val, 0);
1993 ret = stratum_send_line(sctx, s);
2000 static bool stratum_get_version(struct stratum_ctx *sctx, json_t *id)
2006 if (!id || json_is_null(id))
2009 val = json_object();
2010 json_object_set(val, "id", id);
2011 json_object_set_new(val, "error", json_null());
2012 json_object_set_new(val, "result", json_string(USER_AGENT));
2013 s = json_dumps(val, 0);
2014 ret = stratum_send_line(sctx, s);
2021 static bool stratum_show_message(struct stratum_ctx *sctx, json_t *id, json_t *params)
2027 val = json_array_get(params, 0);
2029 applog(LOG_NOTICE, "MESSAGE FROM SERVER: %s", json_string_value(val));
2031 if (!id || json_is_null(id))
2034 val = json_object();
2035 json_object_set(val, "id", id);
2036 json_object_set_new(val, "error", json_null());
2037 json_object_set_new(val, "result", json_true());
2038 s = json_dumps(val, 0);
2039 ret = stratum_send_line(sctx, s);
2046 bool stratum_handle_method(struct stratum_ctx *sctx, const char *s)
2048 json_t *val, *id, *params;
2053 val = JSON_LOADS(s, &err);
2055 applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
2059 method = json_string_value(json_object_get(val, "method"));
2063 params = json_object_get(val, "params");
2066 if (!strcasecmp(method, "job")) {
2067 ret = rpc2_stratum_job(sctx, params);
2072 id = json_object_get(val, "id");
2074 if (!strcasecmp(method, "mining.notify")) {
2075 ret = stratum_notify(sctx, params);
2078 if (!strcasecmp(method, "mining.ping")) { // cgminer 4.7.1+
2079 if (opt_debug) applog(LOG_DEBUG, "Pool ping");
2080 ret = stratum_pong(sctx, id);
2083 if (!strcasecmp(method, "mining.set_difficulty")) {
2084 ret = stratum_set_difficulty(sctx, params);
2087 if (!strcasecmp(method, "mining.set_extranonce")) {
2088 ret = stratum_parse_extranonce(sctx, params, 0);
2091 if (!strcasecmp(method, "client.reconnect")) {
2092 ret = stratum_reconnect(sctx, params);
2095 if (!strcasecmp(method, "client.get_algo")) {
2096 // will prevent wrong algo parameters on a pool, will be used as test on rejects
2097 if (!opt_quiet) applog(LOG_NOTICE, "Pool asked your algo parameter");
2098 ret = stratum_get_algo(sctx, id, params);
2101 if (!strcasecmp(method, "client.get_stats")) {
2102 // optional to fill device benchmarks
2103 ret = stratum_get_stats(sctx, id, params);
2106 if (!strcasecmp(method, "client.get_version")) {
2107 ret = stratum_get_version(sctx, id);
2110 if (!strcasecmp(method, "client.show_message")) {
2111 ret = stratum_show_message(sctx, id, params);
2116 // don't fail = disconnect stratum on unknown (and optional?) methods
2117 if (opt_debug) applog(LOG_WARNING, "unknown stratum method %s!", method);
2118 ret = stratum_unknown_method(sctx, id);
2128 struct thread_q *tq_new(void)
2130 struct thread_q *tq;
2132 tq = (struct thread_q*) calloc(1, sizeof(*tq));
2136 INIT_LIST_HEAD(&tq->q);
2137 pthread_mutex_init(&tq->mutex, NULL);
2138 pthread_cond_init(&tq->cond, NULL);
2143 void tq_free(struct thread_q *tq)
2145 struct tq_ent *ent, *iter;
2150 list_for_each_entry_safe(ent, iter, &tq->q, q_node, struct tq_ent) {
2151 list_del(&ent->q_node);
2155 pthread_cond_destroy(&tq->cond);
2156 pthread_mutex_destroy(&tq->mutex);
2158 memset(tq, 0, sizeof(*tq)); /* poison */
2162 static void tq_freezethaw(struct thread_q *tq, bool frozen)
2164 pthread_mutex_lock(&tq->mutex);
2166 tq->frozen = frozen;
2168 pthread_cond_signal(&tq->cond);
2169 pthread_mutex_unlock(&tq->mutex);
2172 void tq_freeze(struct thread_q *tq)
2174 tq_freezethaw(tq, true);
2177 void tq_thaw(struct thread_q *tq)
2179 tq_freezethaw(tq, false);
2182 bool tq_push(struct thread_q *tq, void *data)
2187 ent = (struct tq_ent*) calloc(1, sizeof(*ent));
2192 INIT_LIST_HEAD(&ent->q_node);
2194 pthread_mutex_lock(&tq->mutex);
2197 list_add_tail(&ent->q_node, &tq->q);
2203 pthread_cond_signal(&tq->cond);
2204 pthread_mutex_unlock(&tq->mutex);
2209 void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
2215 pthread_mutex_lock(&tq->mutex);
2217 if (!list_empty(&tq->q))
2221 rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
2223 rc = pthread_cond_wait(&tq->cond, &tq->mutex);
2226 if (list_empty(&tq->q))
2230 ent = list_entry(tq->q.next, struct tq_ent, q_node);
2233 list_del(&ent->q_node);
2237 pthread_mutex_unlock(&tq->mutex);
2241 /* sprintf can be used in applog */
2242 static char* format_hash(char* buf, uint8_t *hash)
2245 for (int i=0; i < 32; i += 4) {
2246 len += sprintf(buf+len, "%02x%02x%02x%02x ",
2247 hash[i], hash[i+1], hash[i+2], hash[i+3]);
2252 void applog_compare_hash(void *hash, void *hash_ref)
2256 uchar* hash1 = (uchar*)hash;
2257 uchar* hash2 = (uchar*)hash_ref;
2258 for (int i=0; i < 32; i += 4) {
2259 const char *color = memcmp(hash1+i, hash2+i, 4) ? CL_WHT : CL_GRY;
2260 len += sprintf(s+len, "%s%02x%02x%02x%02x " CL_GRY, color,
2261 hash1[i], hash1[i+1], hash1[i+2], hash1[i+3]);
2264 applog(LOG_DEBUG, "%s", s);
2267 void applog_hash(void *hash)
2269 char s[128] = {'\0'};
2270 applog(LOG_DEBUG, "%s", format_hash(s, (uchar*) hash));
2273 void applog_hex(void *data, int len)
2275 char* hex = abin2hex((uchar*)data, len);
2276 applog(LOG_DEBUG, "%s", hex);
2280 void applog_hash64(void *hash)
2282 char s[128] = {'\0'};
2283 char t[128] = {'\0'};
2284 applog(LOG_DEBUG, "%s %s", format_hash(s, (uchar*)hash), format_hash(t, &((uchar*)hash)[32]));
2288 #define printpfx(n,h) \
2289 printf("%s%11s%s: %s\n", CL_CYN, n, CL_N, format_hash(s, (uint8_t*) h))
2291 void print_hash_tests(void)
2293 uchar *scratchbuf = NULL;
2294 char hash[128], s[80];
2295 char buf[192] = { 0 };
2297 scratchbuf = (uchar*) calloc(128, 1024);
2299 printf(CL_WHT "CPU HASH ON EMPTY BUFFER RESULTS:" CL_N "\n\n");
2301 //buf[0] = 1; buf[64] = 2; // for endian tests
2303 axiomhash(&hash[0], &buf[0]);
2304 printpfx("axiom", hash);
2306 bastionhash(&hash[0], &buf[0]);
2307 printpfx("bastion", hash);
2309 blakehash(&hash[0], &buf[0]);
2310 printpfx("blake", hash);
2312 blakecoinhash(&hash[0], &buf[0]);
2313 printpfx("blakecoin", hash);
2315 blake2s_hash(&hash[0], &buf[0]);
2316 printpfx("blake2s", hash);
2318 bmwhash(&hash[0], &buf[0]);
2319 printpfx("bmw", hash);
2321 c11hash(&hash[0], &buf[0]);
2322 printpfx("c11", hash);
2324 cryptolight_hash(&hash[0], &buf[0], 76);
2325 printpfx("cryptolight", hash);
2327 cryptonight_hash(&hash[0], &buf[0], 76);
2328 printpfx("cryptonight", hash);
2330 decred_hash(&hash[0], &buf[0]);
2331 printpfx("decred", hash);
2333 droplp_hash(&hash[0], &buf[0]);
2334 printpfx("drop", hash);
2336 freshhash(&hash[0], &buf[0], 80);
2337 printpfx("fresh", hash);
2339 groestlhash(&hash[0], &buf[0]);
2340 printpfx("groestl", hash);
2342 heavyhash((uint8_t*) &hash[0], (uint8_t*) &buf[0], 32);
2343 printpfx("heavy", hash);
2345 keccakhash(&hash[0], &buf[0]);
2346 printpfx("keccak", hash);
2348 luffahash(&hash[0], &buf[0]);
2349 printpfx("luffa", hash);
2351 lyra2_hash(&hash[0], &buf[0]);
2352 printpfx("lyra2", hash);
2354 lyra2rev2_hash(&hash[0], &buf[0]);
2355 printpfx("lyra2v2", hash);
2357 myriadhash(&hash[0], &buf[0]);
2358 printpfx("myr-gr", hash);
2360 neoscrypt((uchar*) &hash[0], (uchar*)&buf[0], 80000620);
2361 printpfx("neoscrypt", hash);
2363 nist5hash(&hash[0], &buf[0]);
2364 printpfx("nist5", hash);
2366 pentablakehash(&hash[0], &buf[0]);
2367 printpfx("pentablake", hash);
2369 pluck_hash((uint32_t*)&hash[0], (uint32_t*)&buf[0], scratchbuf, 128);
2370 memset(&buf[0], 0, sizeof(buf));
2371 printpfx("pluck", hash);
2373 init_quarkhash_contexts();
2374 quarkhash(&hash[0], &buf[0]);
2375 printpfx("quark", hash);
2377 qubithash(&hash[0], &buf[0]);
2378 printpfx("qubit", hash);
2380 scrypthash(&hash[0], &buf[0], 1024);
2381 printpfx("scrypt", hash);
2383 scrypthash(&hash[0], &buf[0], 2048);
2384 printpfx("scrypt:2048", hash);
2386 scryptjanehash(&hash[0], &buf[0], 9);
2387 printpfx("scrypt-jane", hash);
2389 inkhash(&hash[0], &buf[0]);
2390 printpfx("shavite3", hash);
2392 sha256d((uint8_t*) &hash[0], (uint8_t*)&buf[0], 64);
2393 printpfx("sha256d", hash);
2395 sibhash(&hash[0], &buf[0]);
2396 printpfx("sib", hash);
2398 skeinhash(&hash[0], &buf[0]);
2399 printpfx("skein", hash);
2401 skein2hash(&hash[0], &buf[0]);
2402 printpfx("skein2", hash);
2404 s3hash(&hash[0], &buf[0]);
2405 printpfx("s3", hash);
2407 x11hash(&hash[0], &buf[0]);
2408 printpfx("x11", hash);
2410 x13hash(&hash[0], &buf[0]);
2411 printpfx("x13", hash);
2413 x14hash(&hash[0], &buf[0]);
2414 printpfx("x14", hash);
2416 x15hash(&hash[0], &buf[0]);
2417 printpfx("x15", hash);
2419 yescrypthash(&hash[0], &buf[0]);
2420 printpfx("yescrypt", hash);
2422 //zr5hash(&hash[0], &buf[0]);
2423 zr5hash_pok(&hash[0], (uint32_t*) &buf[0]);
2424 memset(buf, 0, sizeof(buf));
2425 printpfx("zr5", hash);