1 /*
2  * Copyright 2010 Jeff Garzik
3  * Copyright 2012-2017 pooler
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version.  See COPYING for more details.
9  */
10 
11 #include "cpuminer-config.h"
12 #define _GNU_SOURCE
13 
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <stdbool.h>
18 #include <inttypes.h>
19 #include <unistd.h>
20 #include <sys/time.h>
21 #include <time.h>
22 #ifdef WIN32
23 #include <windows.h>
24 #else
25 #include <errno.h>
26 #include <signal.h>
27 #include <sys/resource.h>
28 #if HAVE_SYS_SYSCTL_H
29 #include <sys/types.h>
30 #if HAVE_SYS_PARAM_H
31 #include <sys/param.h>
32 #endif
33 #include <sys/sysctl.h>
34 #endif
35 #endif
36 #include <jansson.h>
37 #include <curl/curl.h>
38 #include "compat.h"
39 #include "miner.h"
40 
41 #define PROGRAM_NAME		"minerd"
42 #define LP_SCANTIME		60
43 
44 #ifdef __linux /* Linux specific policy and affinity management */
45 #include <sched.h>
drop_policy(void)46 static inline void drop_policy(void)
47 {
48 	struct sched_param param;
49 	param.sched_priority = 0;
50 
51 #ifdef SCHED_IDLE
52 	if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
53 #endif
54 #ifdef SCHED_BATCH
55 		sched_setscheduler(0, SCHED_BATCH, &param);
56 #endif
57 }
58 
affine_to_cpu(int id,int cpu)59 static inline void affine_to_cpu(int id, int cpu)
60 {
61 	cpu_set_t set;
62 
63 	CPU_ZERO(&set);
64 	CPU_SET(cpu, &set);
65 	sched_setaffinity(0, sizeof(set), &set);
66 }
67 #elif defined(__FreeBSD__) /* FreeBSD specific policy and affinity management */
68 #include <sys/cpuset.h>
drop_policy(void)69 static inline void drop_policy(void)
70 {
71 }
72 
affine_to_cpu(int id,int cpu)73 static inline void affine_to_cpu(int id, int cpu)
74 {
75 	cpuset_t set;
76 	CPU_ZERO(&set);
77 	CPU_SET(cpu, &set);
78 	cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset_t), &set);
79 }
80 #else
drop_policy(void)81 static inline void drop_policy(void)
82 {
83 }
84 
affine_to_cpu(int id,int cpu)85 static inline void affine_to_cpu(int id, int cpu)
86 {
87 }
88 #endif
89 
90 enum workio_commands {
91 	WC_GET_WORK,
92 	WC_SUBMIT_WORK,
93 };
94 
95 struct workio_cmd {
96 	enum workio_commands	cmd;
97 	struct thr_info		*thr;
98 	union {
99 		struct work	*work;
100 	} u;
101 };
102 
103 enum algos {
104 	ALGO_SCRYPT,		/* scrypt(1024,1,1) */
105 	ALGO_SHA256D,		/* SHA-256d */
106 };
107 
108 static const char *algo_names[] = {
109 	[ALGO_SCRYPT]		= "scrypt",
110 	[ALGO_SHA256D]		= "sha256d",
111 };
112 
113 bool opt_debug = false;
114 bool opt_protocol = false;
115 static bool opt_benchmark = false;
116 bool opt_redirect = true;
117 bool want_longpoll = true;
118 bool have_longpoll = false;
119 bool have_gbt = true;
120 bool allow_getwork = true;
121 bool want_stratum = true;
122 bool have_stratum = false;
123 bool use_syslog = false;
124 static bool opt_background = false;
125 static bool opt_quiet = false;
126 static int opt_retries = -1;
127 static int opt_fail_pause = 30;
128 int opt_timeout = 0;
129 static int opt_scantime = 5;
130 static enum algos opt_algo = ALGO_SCRYPT;
131 static int opt_scrypt_n = 1024;
132 static int opt_n_threads;
133 static int num_processors;
134 static char *rpc_url;
135 static char *rpc_userpass;
136 static char *rpc_user, *rpc_pass;
137 static int pk_script_size;
138 static unsigned char pk_script[25];
139 static char coinbase_sig[101] = "";
140 char *opt_cert;
141 char *opt_proxy;
142 long opt_proxy_type;
143 struct thr_info *thr_info;
144 static int work_thr_id;
145 int longpoll_thr_id = -1;
146 int stratum_thr_id = -1;
147 struct work_restart *work_restart = NULL;
148 static struct stratum_ctx stratum;
149 
150 pthread_mutex_t applog_lock;
151 static pthread_mutex_t stats_lock;
152 
153 static unsigned long accepted_count = 0L;
154 static unsigned long rejected_count = 0L;
155 static double *thr_hashrates;
156 
157 #ifdef HAVE_GETOPT_LONG
158 #include <getopt.h>
159 #else
160 struct option {
161 	const char *name;
162 	int has_arg;
163 	int *flag;
164 	int val;
165 };
166 #endif
167 
168 static char const usage[] = "\
169 Usage: " PROGRAM_NAME " [OPTIONS]\n\
170 Options:\n\
171   -a, --algo=ALGO       specify the algorithm to use\n\
172                           scrypt    scrypt(1024, 1, 1) (default)\n\
173                           scrypt:N  scrypt(N, 1, 1)\n\
174                           sha256d   SHA-256d\n\
175   -o, --url=URL         URL of mining server\n\
176   -O, --userpass=U:P    username:password pair for mining server\n\
177   -u, --user=USERNAME   username for mining server\n\
178   -p, --pass=PASSWORD   password for mining server\n\
179       --cert=FILE       certificate for mining server using SSL\n\
180   -x, --proxy=[PROTOCOL://]HOST[:PORT]  connect through a proxy\n\
181   -t, --threads=N       number of miner threads (default: number of processors)\n\
182   -r, --retries=N       number of times to retry if a network call fails\n\
183                           (default: retry indefinitely)\n\
184   -R, --retry-pause=N   time to pause between retries, in seconds (default: 30)\n\
185   -T, --timeout=N       timeout for long polling, in seconds (default: none)\n\
186   -s, --scantime=N      upper bound on time spent scanning current work when\n\
187                           long polling is unavailable, in seconds (default: 5)\n\
188       --coinbase-addr=ADDR  payout address for solo mining\n\
189       --coinbase-sig=TEXT  data to insert in the coinbase when possible\n\
190       --no-longpoll     disable long polling support\n\
191       --no-getwork      disable getwork support\n\
192       --no-gbt          disable getblocktemplate support\n\
193       --no-stratum      disable X-Stratum support\n\
194       --no-redirect     ignore requests to change the URL of the mining server\n\
195   -q, --quiet           disable per-thread hashmeter output\n\
196   -D, --debug           enable debug output\n\
197   -P, --protocol-dump   verbose dump of protocol-level activities\n"
198 #ifdef HAVE_SYSLOG_H
199 "\
200   -S, --syslog          use system log for output messages\n"
201 #endif
202 #ifndef WIN32
203 "\
204   -B, --background      run the miner in the background\n"
205 #endif
206 "\
207       --benchmark       run in offline benchmark mode\n\
208   -c, --config=FILE     load a JSON-format configuration file\n\
209   -V, --version         display version information and exit\n\
210   -h, --help            display this help text and exit\n\
211 ";
212 
213 static char const short_options[] =
214 #ifndef WIN32
215 	"B"
216 #endif
217 #ifdef HAVE_SYSLOG_H
218 	"S"
219 #endif
220 	"a:c:Dhp:Px:qr:R:s:t:T:o:u:O:V";
221 
222 static struct option const options[] = {
223 	{ "algo", 1, NULL, 'a' },
224 #ifndef WIN32
225 	{ "background", 0, NULL, 'B' },
226 #endif
227 	{ "benchmark", 0, NULL, 1005 },
228 	{ "cert", 1, NULL, 1001 },
229 	{ "coinbase-addr", 1, NULL, 1013 },
230 	{ "coinbase-sig", 1, NULL, 1015 },
231 	{ "config", 1, NULL, 'c' },
232 	{ "debug", 0, NULL, 'D' },
233 	{ "help", 0, NULL, 'h' },
234 	{ "no-gbt", 0, NULL, 1011 },
235 	{ "no-getwork", 0, NULL, 1010 },
236 	{ "no-longpoll", 0, NULL, 1003 },
237 	{ "no-redirect", 0, NULL, 1009 },
238 	{ "no-stratum", 0, NULL, 1007 },
239 	{ "pass", 1, NULL, 'p' },
240 	{ "protocol-dump", 0, NULL, 'P' },
241 	{ "proxy", 1, NULL, 'x' },
242 	{ "quiet", 0, NULL, 'q' },
243 	{ "retries", 1, NULL, 'r' },
244 	{ "retry-pause", 1, NULL, 'R' },
245 	{ "scantime", 1, NULL, 's' },
246 #ifdef HAVE_SYSLOG_H
247 	{ "syslog", 0, NULL, 'S' },
248 #endif
249 	{ "threads", 1, NULL, 't' },
250 	{ "timeout", 1, NULL, 'T' },
251 	{ "url", 1, NULL, 'o' },
252 	{ "user", 1, NULL, 'u' },
253 	{ "userpass", 1, NULL, 'O' },
254 	{ "version", 0, NULL, 'V' },
255 	{ 0, 0, 0, 0 }
256 };
257 
258 struct work {
259 	uint32_t data[32];
260 	uint32_t target[8];
261 
262 	int height;
263 	char *txs;
264 	char *workid;
265 
266 	char *job_id;
267 	size_t xnonce2_len;
268 	unsigned char *xnonce2;
269 };
270 
271 static struct work g_work;
272 static time_t g_work_time;
273 static pthread_mutex_t g_work_lock;
274 static bool submit_old = false;
275 static char *lp_id;
276 
work_free(struct work * w)277 static inline void work_free(struct work *w)
278 {
279 	free(w->txs);
280 	free(w->workid);
281 	free(w->job_id);
282 	free(w->xnonce2);
283 }
284 
work_copy(struct work * dest,const struct work * src)285 static inline void work_copy(struct work *dest, const struct work *src)
286 {
287 	memcpy(dest, src, sizeof(struct work));
288 	if (src->txs)
289 		dest->txs = strdup(src->txs);
290 	if (src->workid)
291 		dest->workid = strdup(src->workid);
292 	if (src->job_id)
293 		dest->job_id = strdup(src->job_id);
294 	if (src->xnonce2) {
295 		dest->xnonce2 = malloc(src->xnonce2_len);
296 		memcpy(dest->xnonce2, src->xnonce2, src->xnonce2_len);
297 	}
298 }
299 
jobj_binary(const json_t * obj,const char * key,void * buf,size_t buflen)300 static bool jobj_binary(const json_t *obj, const char *key,
301 			void *buf, size_t buflen)
302 {
303 	const char *hexstr;
304 	json_t *tmp;
305 
306 	tmp = json_object_get(obj, key);
307 	if (unlikely(!tmp)) {
308 		applog(LOG_ERR, "JSON key '%s' not found", key);
309 		return false;
310 	}
311 	hexstr = json_string_value(tmp);
312 	if (unlikely(!hexstr)) {
313 		applog(LOG_ERR, "JSON key '%s' is not a string", key);
314 		return false;
315 	}
316 	if (!hex2bin(buf, hexstr, buflen))
317 		return false;
318 
319 	return true;
320 }
321 
work_decode(const json_t * val,struct work * work)322 static bool work_decode(const json_t *val, struct work *work)
323 {
324 	int i;
325 
326 	if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
327 		applog(LOG_ERR, "JSON invalid data");
328 		goto err_out;
329 	}
330 	if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
331 		applog(LOG_ERR, "JSON invalid target");
332 		goto err_out;
333 	}
334 
335 	for (i = 0; i < ARRAY_SIZE(work->data); i++)
336 		work->data[i] = le32dec(work->data + i);
337 	for (i = 0; i < ARRAY_SIZE(work->target); i++)
338 		work->target[i] = le32dec(work->target + i);
339 
340 	return true;
341 
342 err_out:
343 	return false;
344 }
345 
gbt_work_decode(const json_t * val,struct work * work)346 static bool gbt_work_decode(const json_t *val, struct work *work)
347 {
348 	int i, n;
349 	uint32_t version, curtime, bits;
350 	uint32_t prevhash[8];
351 	uint32_t target[8];
352 	int cbtx_size;
353 	unsigned char *cbtx = NULL;
354 	int tx_count, tx_size;
355 	unsigned char txc_vi[9];
356 	unsigned char (*merkle_tree)[32] = NULL;
357 	bool coinbase_append = false;
358 	bool submit_coinbase = false;
359 	bool segwit = false;
360 	json_t *tmp, *txa;
361 	bool rc = false;
362 
363 	tmp = json_object_get(val, "rules");
364 	if (tmp && json_is_array(tmp)) {
365 		n = json_array_size(tmp);
366 		for (i = 0; i < n; i++) {
367 			const char *s = json_string_value(json_array_get(tmp, i));
368 			if (!s)
369 				continue;
370 			if (!strcmp(s, "segwit") || !strcmp(s, "!segwit"))
371 				segwit = true;
372 		}
373 	}
374 
375 	tmp = json_object_get(val, "mutable");
376 	if (tmp && json_is_array(tmp)) {
377 		n = json_array_size(tmp);
378 		for (i = 0; i < n; i++) {
379 			const char *s = json_string_value(json_array_get(tmp, i));
380 			if (!s)
381 				continue;
382 			if (!strcmp(s, "coinbase/append"))
383 				coinbase_append = true;
384 			else if (!strcmp(s, "submit/coinbase"))
385 				submit_coinbase = true;
386 		}
387 	}
388 
389 	tmp = json_object_get(val, "height");
390 	if (!tmp || !json_is_integer(tmp)) {
391 		applog(LOG_ERR, "JSON invalid height");
392 		goto out;
393 	}
394 	work->height = json_integer_value(tmp);
395 
396 	tmp = json_object_get(val, "version");
397 	if (!tmp || !json_is_integer(tmp)) {
398 		applog(LOG_ERR, "JSON invalid version");
399 		goto out;
400 	}
401 	version = json_integer_value(tmp);
402 
403 	if (unlikely(!jobj_binary(val, "previousblockhash", prevhash, sizeof(prevhash)))) {
404 		applog(LOG_ERR, "JSON invalid previousblockhash");
405 		goto out;
406 	}
407 
408 	tmp = json_object_get(val, "curtime");
409 	if (!tmp || !json_is_integer(tmp)) {
410 		applog(LOG_ERR, "JSON invalid curtime");
411 		goto out;
412 	}
413 	curtime = json_integer_value(tmp);
414 
415 	if (unlikely(!jobj_binary(val, "bits", &bits, sizeof(bits)))) {
416 		applog(LOG_ERR, "JSON invalid bits");
417 		goto out;
418 	}
419 
420 	/* find count and size of transactions */
421 	txa = json_object_get(val, "transactions");
422 	if (!txa || !json_is_array(txa)) {
423 		applog(LOG_ERR, "JSON invalid transactions");
424 		goto out;
425 	}
426 	tx_count = json_array_size(txa);
427 	tx_size = 0;
428 	for (i = 0; i < tx_count; i++) {
429 		const json_t *tx = json_array_get(txa, i);
430 		const char *tx_hex = json_string_value(json_object_get(tx, "data"));
431 		if (!tx_hex) {
432 			applog(LOG_ERR, "JSON invalid transactions");
433 			goto out;
434 		}
435 		tx_size += strlen(tx_hex) / 2;
436 	}
437 
438 	/* build coinbase transaction */
439 	tmp = json_object_get(val, "coinbasetxn");
440 	if (tmp) {
441 		const char *cbtx_hex = json_string_value(json_object_get(tmp, "data"));
442 		cbtx_size = cbtx_hex ? strlen(cbtx_hex) / 2 : 0;
443 		cbtx = malloc(cbtx_size + 100);
444 		if (cbtx_size < 60 || !hex2bin(cbtx, cbtx_hex, cbtx_size)) {
445 			applog(LOG_ERR, "JSON invalid coinbasetxn");
446 			goto out;
447 		}
448 	} else {
449 		int64_t cbvalue;
450 		if (!pk_script_size) {
451 			if (allow_getwork) {
452 				applog(LOG_INFO, "No payout address provided, switching to getwork");
453 				have_gbt = false;
454 			} else
455 				applog(LOG_ERR, "No payout address provided");
456 			goto out;
457 		}
458 		tmp = json_object_get(val, "coinbasevalue");
459 		if (!tmp || !json_is_number(tmp)) {
460 			applog(LOG_ERR, "JSON invalid coinbasevalue");
461 			goto out;
462 		}
463 		cbvalue = json_is_integer(tmp) ? json_integer_value(tmp) : json_number_value(tmp);
464 		cbtx = malloc(256);
465 		le32enc((uint32_t *)cbtx, 1); /* version */
466 		cbtx[4] = 1; /* in-counter */
467 		memset(cbtx+5, 0x00, 32); /* prev txout hash */
468 		le32enc((uint32_t *)(cbtx+37), 0xffffffff); /* prev txout index */
469 		cbtx_size = 43;
470 		/* BIP 34: height in coinbase */
471 		for (n = work->height; n; n >>= 8) {
472 			cbtx[cbtx_size++] = n & 0xff;
473 			if (n < 0x100 && n >= 0x80)
474 				cbtx[cbtx_size++] = 0;
475 		}
476 		cbtx[42] = cbtx_size - 43;
477 		cbtx[41] = cbtx_size - 42; /* scriptsig length */
478 		le32enc((uint32_t *)(cbtx+cbtx_size), 0xffffffff); /* sequence */
479 		cbtx_size += 4;
480 		cbtx[cbtx_size++] = segwit ? 2 : 1; /* out-counter */
481 		le32enc((uint32_t *)(cbtx+cbtx_size), (uint32_t)cbvalue); /* value */
482 		le32enc((uint32_t *)(cbtx+cbtx_size+4), cbvalue >> 32);
483 		cbtx_size += 8;
484 		cbtx[cbtx_size++] = pk_script_size; /* txout-script length */
485 		memcpy(cbtx+cbtx_size, pk_script, pk_script_size);
486 		cbtx_size += pk_script_size;
487 		if (segwit) {
488 			unsigned char (*wtree)[32] = calloc(tx_count + 2, 32);
489 			memset(cbtx+cbtx_size, 0, 8); /* value */
490 			cbtx_size += 8;
491 			cbtx[cbtx_size++] = 38; /* txout-script length */
492 			cbtx[cbtx_size++] = 0x6a; /* txout-script */
493 			cbtx[cbtx_size++] = 0x24;
494 			cbtx[cbtx_size++] = 0xaa;
495 			cbtx[cbtx_size++] = 0x21;
496 			cbtx[cbtx_size++] = 0xa9;
497 			cbtx[cbtx_size++] = 0xed;
498 			for (i = 0; i < tx_count; i++) {
499 				const json_t *tx = json_array_get(txa, i);
500 				const json_t *hash = json_object_get(tx, "hash");
501 				if (!hash || !hex2bin(wtree[1+i], json_string_value(hash), 32)) {
502 					applog(LOG_ERR, "JSON invalid transaction hash");
503 					free(wtree);
504 					goto out;
505 				}
506 				memrev(wtree[1+i], 32);
507 			}
508 			n = tx_count + 1;
509 			while (n > 1) {
510 				if (n % 2)
511 					memcpy(wtree[n], wtree[n-1], 32);
512 				n = (n + 1) / 2;
513 				for (i = 0; i < n; i++)
514 					sha256d(wtree[i], wtree[2*i], 64);
515 			}
516 			memset(wtree[1], 0, 32);  /* witness reserved value = 0 */
517 			sha256d(cbtx+cbtx_size, wtree[0], 64);
518 			cbtx_size += 32;
519 			free(wtree);
520 		}
521 		le32enc((uint32_t *)(cbtx+cbtx_size), 0); /* lock time */
522 		cbtx_size += 4;
523 		coinbase_append = true;
524 	}
525 	if (coinbase_append) {
526 		unsigned char xsig[100];
527 		int xsig_len = 0;
528 		if (*coinbase_sig) {
529 			n = strlen(coinbase_sig);
530 			if (cbtx[41] + xsig_len + n <= 100) {
531 				memcpy(xsig+xsig_len, coinbase_sig, n);
532 				xsig_len += n;
533 			} else {
534 				applog(LOG_WARNING, "Signature does not fit in coinbase, skipping");
535 			}
536 		}
537 		tmp = json_object_get(val, "coinbaseaux");
538 		if (tmp && json_is_object(tmp)) {
539 			void *iter = json_object_iter(tmp);
540 			while (iter) {
541 				unsigned char buf[100];
542 				const char *s = json_string_value(json_object_iter_value(iter));
543 				n = s ? strlen(s) / 2 : 0;
544 				if (!s || n > 100 || !hex2bin(buf, s, n)) {
545 					applog(LOG_ERR, "JSON invalid coinbaseaux");
546 					break;
547 				}
548 				if (cbtx[41] + xsig_len + n <= 100) {
549 					memcpy(xsig+xsig_len, buf, n);
550 					xsig_len += n;
551 				}
552 				iter = json_object_iter_next(tmp, iter);
553 			}
554 		}
555 		if (xsig_len) {
556 			unsigned char *ssig_end = cbtx + 42 + cbtx[41];
557 			int push_len = cbtx[41] + xsig_len < 76 ? 1 :
558 			               cbtx[41] + 2 + xsig_len > 100 ? 0 : 2;
559 			n = xsig_len + push_len;
560 			memmove(ssig_end + n, ssig_end, cbtx_size - 42 - cbtx[41]);
561 			cbtx[41] += n;
562 			if (push_len == 2)
563 				*(ssig_end++) = 0x4c; /* OP_PUSHDATA1 */
564 			if (push_len)
565 				*(ssig_end++) = xsig_len;
566 			memcpy(ssig_end, xsig, xsig_len);
567 			cbtx_size += n;
568 		}
569 	}
570 
571 	n = varint_encode(txc_vi, 1 + tx_count);
572 	work->txs = malloc(2 * (n + cbtx_size + tx_size) + 1);
573 	bin2hex(work->txs, txc_vi, n);
574 	bin2hex(work->txs + 2*n, cbtx, cbtx_size);
575 
576 	/* generate merkle root */
577 	merkle_tree = malloc(32 * ((1 + tx_count + 1) & ~1));
578 	sha256d(merkle_tree[0], cbtx, cbtx_size);
579 	for (i = 0; i < tx_count; i++) {
580 		tmp = json_array_get(txa, i);
581 		const char *tx_hex = json_string_value(json_object_get(tmp, "data"));
582 		const int tx_size = tx_hex ? strlen(tx_hex) / 2 : 0;
583 		if (segwit) {
584 			const char *txid = json_string_value(json_object_get(tmp, "txid"));
585 			if (!txid || !hex2bin(merkle_tree[1 + i], txid, 32)) {
586 				applog(LOG_ERR, "JSON invalid transaction txid");
587 				goto out;
588 			}
589 			memrev(merkle_tree[1 + i], 32);
590 		} else {
591 			unsigned char *tx = malloc(tx_size);
592 			if (!tx_hex || !hex2bin(tx, tx_hex, tx_size)) {
593 				applog(LOG_ERR, "JSON invalid transactions");
594 				free(tx);
595 				goto out;
596 			}
597 			sha256d(merkle_tree[1 + i], tx, tx_size);
598 			free(tx);
599 		}
600 		if (!submit_coinbase)
601 			strcat(work->txs, tx_hex);
602 	}
603 	n = 1 + tx_count;
604 	while (n > 1) {
605 		if (n % 2) {
606 			memcpy(merkle_tree[n], merkle_tree[n-1], 32);
607 			++n;
608 		}
609 		n /= 2;
610 		for (i = 0; i < n; i++)
611 			sha256d(merkle_tree[i], merkle_tree[2*i], 64);
612 	}
613 
614 	/* assemble block header */
615 	work->data[0] = swab32(version);
616 	for (i = 0; i < 8; i++)
617 		work->data[8 - i] = le32dec(prevhash + i);
618 	for (i = 0; i < 8; i++)
619 		work->data[9 + i] = be32dec((uint32_t *)merkle_tree[0] + i);
620 	work->data[17] = swab32(curtime);
621 	work->data[18] = le32dec(&bits);
622 	memset(work->data + 19, 0x00, 52);
623 	work->data[20] = 0x80000000;
624 	work->data[31] = 0x00000280;
625 
626 	if (unlikely(!jobj_binary(val, "target", target, sizeof(target)))) {
627 		applog(LOG_ERR, "JSON invalid target");
628 		goto out;
629 	}
630 	for (i = 0; i < ARRAY_SIZE(work->target); i++)
631 		work->target[7 - i] = be32dec(target + i);
632 
633 	tmp = json_object_get(val, "workid");
634 	if (tmp) {
635 		if (!json_is_string(tmp)) {
636 			applog(LOG_ERR, "JSON invalid workid");
637 			goto out;
638 		}
639 		work->workid = strdup(json_string_value(tmp));
640 	}
641 
642 	/* Long polling */
643 	tmp = json_object_get(val, "longpollid");
644 	if (want_longpoll && json_is_string(tmp)) {
645 		free(lp_id);
646 		lp_id = strdup(json_string_value(tmp));
647 		if (!have_longpoll) {
648 			char *lp_uri;
649 			tmp = json_object_get(val, "longpolluri");
650 			lp_uri = strdup(json_is_string(tmp) ? json_string_value(tmp) : rpc_url);
651 			have_longpoll = true;
652 			tq_push(thr_info[longpoll_thr_id].q, lp_uri);
653 		}
654 	}
655 
656 	rc = true;
657 
658 out:
659 	free(cbtx);
660 	free(merkle_tree);
661 	return rc;
662 }
663 
share_result(int result,const char * reason)664 static void share_result(int result, const char *reason)
665 {
666 	char s[345];
667 	double hashrate;
668 	int i;
669 
670 	hashrate = 0.;
671 	pthread_mutex_lock(&stats_lock);
672 	for (i = 0; i < opt_n_threads; i++)
673 		hashrate += thr_hashrates[i];
674 	result ? accepted_count++ : rejected_count++;
675 	pthread_mutex_unlock(&stats_lock);
676 
677 	sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", 1e-3 * hashrate);
678 	applog(LOG_INFO, "accepted: %lu/%lu (%.2f%%), %s khash/s %s",
679 		   accepted_count,
680 		   accepted_count + rejected_count,
681 		   100. * accepted_count / (accepted_count + rejected_count),
682 		   s,
683 		   result ? "(yay!!!)" : "(booooo)");
684 
685 	if (opt_debug && reason)
686 		applog(LOG_DEBUG, "DEBUG: reject reason: %s", reason);
687 }
688 
submit_upstream_work(CURL * curl,struct work * work)689 static bool submit_upstream_work(CURL *curl, struct work *work)
690 {
691 	json_t *val, *res, *reason;
692 	char data_str[2 * sizeof(work->data) + 1];
693 	char s[345];
694 	int i;
695 	bool rc = false;
696 
697 	/* pass if the previous hash is not the current previous hash */
698 	if (!submit_old && memcmp(work->data + 1, g_work.data + 1, 32)) {
699 		if (opt_debug)
700 			applog(LOG_DEBUG, "DEBUG: stale work detected, discarding");
701 		return true;
702 	}
703 
704 	if (have_stratum) {
705 		uint32_t ntime, nonce;
706 		char ntimestr[9], noncestr[9], *xnonce2str, *req;
707 
708 		le32enc(&ntime, work->data[17]);
709 		le32enc(&nonce, work->data[19]);
710 		bin2hex(ntimestr, (const unsigned char *)(&ntime), 4);
711 		bin2hex(noncestr, (const unsigned char *)(&nonce), 4);
712 		xnonce2str = abin2hex(work->xnonce2, work->xnonce2_len);
713 		req = malloc(256 + strlen(rpc_user) + strlen(work->job_id) + 2 * work->xnonce2_len);
714 		sprintf(req,
715 			"{\"method\": \"mining.submit\", \"params\": [\"%s\", \"%s\", \"%s\", \"%s\", \"%s\"], \"id\":4}",
716 			rpc_user, work->job_id, xnonce2str, ntimestr, noncestr);
717 		free(xnonce2str);
718 
719 		rc = stratum_send_line(&stratum, req);
720 		free(req);
721 		if (unlikely(!rc)) {
722 			applog(LOG_ERR, "submit_upstream_work stratum_send_line failed");
723 			goto out;
724 		}
725 	} else if (work->txs) {
726 		char *req;
727 
728 		for (i = 0; i < ARRAY_SIZE(work->data); i++)
729 			be32enc(work->data + i, work->data[i]);
730 		bin2hex(data_str, (unsigned char *)work->data, 80);
731 		if (work->workid) {
732 			char *params;
733 			val = json_object();
734 			json_object_set_new(val, "workid", json_string(work->workid));
735 			params = json_dumps(val, 0);
736 			json_decref(val);
737 			req = malloc(128 + 2*80 + strlen(work->txs) + strlen(params));
738 			sprintf(req,
739 				"{\"method\": \"submitblock\", \"params\": [\"%s%s\", %s], \"id\":1}\r\n",
740 				data_str, work->txs, params);
741 			free(params);
742 		} else {
743 			req = malloc(128 + 2*80 + strlen(work->txs));
744 			sprintf(req,
745 				"{\"method\": \"submitblock\", \"params\": [\"%s%s\"], \"id\":1}\r\n",
746 				data_str, work->txs);
747 		}
748 		val = json_rpc_call(curl, rpc_url, rpc_userpass, req, NULL, 0);
749 		free(req);
750 		if (unlikely(!val)) {
751 			applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
752 			goto out;
753 		}
754 
755 		res = json_object_get(val, "result");
756 		if (json_is_object(res)) {
757 			char *res_str;
758 			bool sumres = false;
759 			void *iter = json_object_iter(res);
760 			while (iter) {
761 				if (json_is_null(json_object_iter_value(iter))) {
762 					sumres = true;
763 					break;
764 				}
765 				iter = json_object_iter_next(res, iter);
766 			}
767 			res_str = json_dumps(res, 0);
768 			share_result(sumres, res_str);
769 			free(res_str);
770 		} else
771 			share_result(json_is_null(res), json_string_value(res));
772 
773 		json_decref(val);
774 	} else {
775 		/* build hex string */
776 		for (i = 0; i < ARRAY_SIZE(work->data); i++)
777 			le32enc(work->data + i, work->data[i]);
778 		bin2hex(data_str, (unsigned char *)work->data, sizeof(work->data));
779 
780 		/* build JSON-RPC request */
781 		sprintf(s,
782 			"{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
783 			data_str);
784 
785 		/* issue JSON-RPC request */
786 		val = json_rpc_call(curl, rpc_url, rpc_userpass, s, NULL, 0);
787 		if (unlikely(!val)) {
788 			applog(LOG_ERR, "submit_upstream_work json_rpc_call failed");
789 			goto out;
790 		}
791 
792 		res = json_object_get(val, "result");
793 		reason = json_object_get(val, "reject-reason");
794 		share_result(json_is_true(res), reason ? json_string_value(reason) : NULL);
795 
796 		json_decref(val);
797 	}
798 
799 	rc = true;
800 
801 out:
802 	return rc;
803 }
804 
805 static const char *getwork_req =
806 	"{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
807 
808 #define GBT_CAPABILITIES "[\"coinbasetxn\", \"coinbasevalue\", \"longpoll\", \"workid\"]"
809 #define GBT_RULES "[\"segwit\"]"
810 
811 static const char *gbt_req =
812 	"{\"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": "
813 	GBT_CAPABILITIES ", \"rules\": " GBT_RULES "}], \"id\":0}\r\n";
814 static const char *gbt_lp_req =
815 	"{\"method\": \"getblocktemplate\", \"params\": [{\"capabilities\": "
816 	GBT_CAPABILITIES ", \"rules\": " GBT_RULES ", \"longpollid\": \"%s\"}], \"id\":0}\r\n";
817 
get_upstream_work(CURL * curl,struct work * work)818 static bool get_upstream_work(CURL *curl, struct work *work)
819 {
820 	json_t *val;
821 	int err;
822 	bool rc;
823 	struct timeval tv_start, tv_end, diff;
824 
825 start:
826 	gettimeofday(&tv_start, NULL);
827 	val = json_rpc_call(curl, rpc_url, rpc_userpass,
828 			    have_gbt ? gbt_req : getwork_req,
829 			    &err, have_gbt ? JSON_RPC_QUIET_404 : 0);
830 	gettimeofday(&tv_end, NULL);
831 
832 	if (have_stratum) {
833 		if (val)
834 			json_decref(val);
835 		return true;
836 	}
837 
838 	if (!have_gbt && !allow_getwork) {
839 		applog(LOG_ERR, "No usable protocol");
840 		if (val)
841 			json_decref(val);
842 		return false;
843 	}
844 
845 	if (have_gbt && allow_getwork && !val && err == CURLE_OK) {
846 		applog(LOG_INFO, "getblocktemplate failed, falling back to getwork");
847 		have_gbt = false;
848 		goto start;
849 	}
850 
851 	if (!val)
852 		return false;
853 
854 	if (have_gbt) {
855 		rc = gbt_work_decode(json_object_get(val, "result"), work);
856 		if (!have_gbt) {
857 			json_decref(val);
858 			goto start;
859 		}
860 	} else
861 		rc = work_decode(json_object_get(val, "result"), work);
862 
863 	if (opt_debug && rc) {
864 		timeval_subtract(&diff, &tv_end, &tv_start);
865 		applog(LOG_DEBUG, "DEBUG: got new work in %d ms",
866 		       diff.tv_sec * 1000 + diff.tv_usec / 1000);
867 	}
868 
869 	json_decref(val);
870 
871 	return rc;
872 }
873 
workio_cmd_free(struct workio_cmd * wc)874 static void workio_cmd_free(struct workio_cmd *wc)
875 {
876 	if (!wc)
877 		return;
878 
879 	switch (wc->cmd) {
880 	case WC_SUBMIT_WORK:
881 		work_free(wc->u.work);
882 		free(wc->u.work);
883 		break;
884 	default: /* do nothing */
885 		break;
886 	}
887 
888 	memset(wc, 0, sizeof(*wc));	/* poison */
889 	free(wc);
890 }
891 
workio_get_work(struct workio_cmd * wc,CURL * curl)892 static bool workio_get_work(struct workio_cmd *wc, CURL *curl)
893 {
894 	struct work *ret_work;
895 	int failures = 0;
896 
897 	ret_work = calloc(1, sizeof(*ret_work));
898 	if (!ret_work)
899 		return false;
900 
901 	/* obtain new work from bitcoin via JSON-RPC */
902 	while (!get_upstream_work(curl, ret_work)) {
903 		if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
904 			applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
905 			free(ret_work);
906 			return false;
907 		}
908 
909 		/* pause, then restart work-request loop */
910 		applog(LOG_ERR, "json_rpc_call failed, retry after %d seconds",
911 			opt_fail_pause);
912 		sleep(opt_fail_pause);
913 	}
914 
915 	/* send work to requesting thread */
916 	if (!tq_push(wc->thr->q, ret_work))
917 		free(ret_work);
918 
919 	return true;
920 }
921 
workio_submit_work(struct workio_cmd * wc,CURL * curl)922 static bool workio_submit_work(struct workio_cmd *wc, CURL *curl)
923 {
924 	int failures = 0;
925 
926 	/* submit solution to bitcoin via JSON-RPC */
927 	while (!submit_upstream_work(curl, wc->u.work)) {
928 		if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
929 			applog(LOG_ERR, "...terminating workio thread");
930 			return false;
931 		}
932 
933 		/* pause, then restart work-request loop */
934 		applog(LOG_ERR, "...retry after %d seconds",
935 			opt_fail_pause);
936 		sleep(opt_fail_pause);
937 	}
938 
939 	return true;
940 }
941 
workio_thread(void * userdata)942 static void *workio_thread(void *userdata)
943 {
944 	struct thr_info *mythr = userdata;
945 	CURL *curl;
946 	bool ok = true;
947 
948 	curl = curl_easy_init();
949 	if (unlikely(!curl)) {
950 		applog(LOG_ERR, "CURL initialization failed");
951 		return NULL;
952 	}
953 
954 	while (ok) {
955 		struct workio_cmd *wc;
956 
957 		/* wait for workio_cmd sent to us, on our queue */
958 		wc = tq_pop(mythr->q, NULL);
959 		if (!wc) {
960 			ok = false;
961 			break;
962 		}
963 
964 		/* process workio_cmd */
965 		switch (wc->cmd) {
966 		case WC_GET_WORK:
967 			ok = workio_get_work(wc, curl);
968 			break;
969 		case WC_SUBMIT_WORK:
970 			ok = workio_submit_work(wc, curl);
971 			break;
972 
973 		default:		/* should never happen */
974 			ok = false;
975 			break;
976 		}
977 
978 		workio_cmd_free(wc);
979 	}
980 
981 	tq_freeze(mythr->q);
982 	curl_easy_cleanup(curl);
983 
984 	return NULL;
985 }
986 
get_work(struct thr_info * thr,struct work * work)987 static bool get_work(struct thr_info *thr, struct work *work)
988 {
989 	struct workio_cmd *wc;
990 	struct work *work_heap;
991 
992 	if (opt_benchmark) {
993 		memset(work->data, 0x55, 76);
994 		work->data[17] = swab32(time(NULL));
995 		memset(work->data + 19, 0x00, 52);
996 		work->data[20] = 0x80000000;
997 		work->data[31] = 0x00000280;
998 		memset(work->target, 0x00, sizeof(work->target));
999 		return true;
1000 	}
1001 
1002 	/* fill out work request message */
1003 	wc = calloc(1, sizeof(*wc));
1004 	if (!wc)
1005 		return false;
1006 
1007 	wc->cmd = WC_GET_WORK;
1008 	wc->thr = thr;
1009 
1010 	/* send work request to workio thread */
1011 	if (!tq_push(thr_info[work_thr_id].q, wc)) {
1012 		workio_cmd_free(wc);
1013 		return false;
1014 	}
1015 
1016 	/* wait for response, a unit of work */
1017 	work_heap = tq_pop(thr->q, NULL);
1018 	if (!work_heap)
1019 		return false;
1020 
1021 	/* copy returned work into storage provided by caller */
1022 	memcpy(work, work_heap, sizeof(*work));
1023 	free(work_heap);
1024 
1025 	return true;
1026 }
1027 
submit_work(struct thr_info * thr,const struct work * work_in)1028 static bool submit_work(struct thr_info *thr, const struct work *work_in)
1029 {
1030 	struct workio_cmd *wc;
1031 
1032 	/* fill out work request message */
1033 	wc = calloc(1, sizeof(*wc));
1034 	if (!wc)
1035 		return false;
1036 
1037 	wc->u.work = malloc(sizeof(*work_in));
1038 	if (!wc->u.work)
1039 		goto err_out;
1040 
1041 	wc->cmd = WC_SUBMIT_WORK;
1042 	wc->thr = thr;
1043 	work_copy(wc->u.work, work_in);
1044 
1045 	/* send solution to workio thread */
1046 	if (!tq_push(thr_info[work_thr_id].q, wc))
1047 		goto err_out;
1048 
1049 	return true;
1050 
1051 err_out:
1052 	workio_cmd_free(wc);
1053 	return false;
1054 }
1055 
stratum_gen_work(struct stratum_ctx * sctx,struct work * work)1056 static void stratum_gen_work(struct stratum_ctx *sctx, struct work *work)
1057 {
1058 	unsigned char merkle_root[64];
1059 	int i;
1060 
1061 	pthread_mutex_lock(&sctx->work_lock);
1062 
1063 	free(work->job_id);
1064 	work->job_id = strdup(sctx->job.job_id);
1065 	work->xnonce2_len = sctx->xnonce2_size;
1066 	work->xnonce2 = realloc(work->xnonce2, sctx->xnonce2_size);
1067 	memcpy(work->xnonce2, sctx->job.xnonce2, sctx->xnonce2_size);
1068 
1069 	/* Generate merkle root */
1070 	sha256d(merkle_root, sctx->job.coinbase, sctx->job.coinbase_size);
1071 	for (i = 0; i < sctx->job.merkle_count; i++) {
1072 		memcpy(merkle_root + 32, sctx->job.merkle[i], 32);
1073 		sha256d(merkle_root, merkle_root, 64);
1074 	}
1075 
1076 	/* Increment extranonce2 */
1077 	for (i = 0; i < sctx->xnonce2_size && !++sctx->job.xnonce2[i]; i++);
1078 
1079 	/* Assemble block header */
1080 	memset(work->data, 0, 128);
1081 	work->data[0] = le32dec(sctx->job.version);
1082 	for (i = 0; i < 8; i++)
1083 		work->data[1 + i] = le32dec((uint32_t *)sctx->job.prevhash + i);
1084 	for (i = 0; i < 8; i++)
1085 		work->data[9 + i] = be32dec((uint32_t *)merkle_root + i);
1086 	work->data[17] = le32dec(sctx->job.ntime);
1087 	work->data[18] = le32dec(sctx->job.nbits);
1088 	work->data[20] = 0x80000000;
1089 	work->data[31] = 0x00000280;
1090 
1091 	pthread_mutex_unlock(&sctx->work_lock);
1092 
1093 	if (opt_debug) {
1094 		char *xnonce2str = abin2hex(work->xnonce2, work->xnonce2_len);
1095 		applog(LOG_DEBUG, "DEBUG: job_id='%s' extranonce2=%s ntime=%08x",
1096 		       work->job_id, xnonce2str, swab32(work->data[17]));
1097 		free(xnonce2str);
1098 	}
1099 
1100 	if (opt_algo == ALGO_SCRYPT)
1101 		diff_to_target(work->target, sctx->job.diff / 65536.0);
1102 	else
1103 		diff_to_target(work->target, sctx->job.diff);
1104 }
1105 
miner_thread(void * userdata)1106 static void *miner_thread(void *userdata)
1107 {
1108 	struct thr_info *mythr = userdata;
1109 	int thr_id = mythr->id;
1110 	struct work work = {{0}};
1111 	uint32_t max_nonce;
1112 	uint32_t end_nonce = 0xffffffffU / opt_n_threads * (thr_id + 1) - 0x20;
1113 	unsigned char *scratchbuf = NULL;
1114 	char s[16];
1115 	int i;
1116 
1117 	/* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
1118 	 * and if that fails, then SCHED_BATCH. No need for this to be an
1119 	 * error if it fails */
1120 	if (!opt_benchmark) {
1121 		setpriority(PRIO_PROCESS, 0, 19);
1122 		drop_policy();
1123 	}
1124 
1125 	/* Cpu affinity only makes sense if the number of threads is a multiple
1126 	 * of the number of CPUs */
1127 	if (num_processors > 1 && opt_n_threads % num_processors == 0) {
1128 		if (!opt_quiet)
1129 			applog(LOG_INFO, "Binding thread %d to cpu %d",
1130 			       thr_id, thr_id % num_processors);
1131 		affine_to_cpu(thr_id, thr_id % num_processors);
1132 	}
1133 
1134 	if (opt_algo == ALGO_SCRYPT) {
1135 		scratchbuf = scrypt_buffer_alloc(opt_scrypt_n);
1136 		if (!scratchbuf) {
1137 			applog(LOG_ERR, "scrypt buffer allocation failed");
1138 			pthread_mutex_lock(&applog_lock);
1139 			exit(1);
1140 		}
1141 	}
1142 
1143 	while (1) {
1144 		unsigned long hashes_done;
1145 		struct timeval tv_start, tv_end, diff;
1146 		int64_t max64;
1147 		int rc;
1148 
1149 		if (have_stratum) {
1150 			while (time(NULL) >= g_work_time + 120)
1151 				sleep(1);
1152 			pthread_mutex_lock(&g_work_lock);
1153 			if (work.data[19] >= end_nonce && !memcmp(work.data, g_work.data, 76))
1154 				stratum_gen_work(&stratum, &g_work);
1155 		} else {
1156 			int min_scantime = have_longpoll ? LP_SCANTIME : opt_scantime;
1157 			/* obtain new work from internal workio thread */
1158 			pthread_mutex_lock(&g_work_lock);
1159 			if (!have_stratum &&
1160 			    (time(NULL) - g_work_time >= min_scantime ||
1161 			     work.data[19] >= end_nonce)) {
1162 				work_free(&g_work);
1163 				if (unlikely(!get_work(mythr, &g_work))) {
1164 					applog(LOG_ERR, "work retrieval failed, exiting "
1165 						"mining thread %d", mythr->id);
1166 					pthread_mutex_unlock(&g_work_lock);
1167 					goto out;
1168 				}
1169 				g_work_time = have_stratum ? 0 : time(NULL);
1170 			}
1171 			if (have_stratum) {
1172 				pthread_mutex_unlock(&g_work_lock);
1173 				continue;
1174 			}
1175 		}
1176 		if (memcmp(work.data, g_work.data, 76)) {
1177 			work_free(&work);
1178 			work_copy(&work, &g_work);
1179 			work.data[19] = 0xffffffffU / opt_n_threads * thr_id;
1180 		} else
1181 			work.data[19]++;
1182 		pthread_mutex_unlock(&g_work_lock);
1183 		work_restart[thr_id].restart = 0;
1184 
1185 		/* adjust max_nonce to meet target scan time */
1186 		if (have_stratum)
1187 			max64 = LP_SCANTIME;
1188 		else
1189 			max64 = g_work_time + (have_longpoll ? LP_SCANTIME : opt_scantime)
1190 			      - time(NULL);
1191 		max64 *= thr_hashrates[thr_id];
1192 		if (max64 <= 0) {
1193 			switch (opt_algo) {
1194 			case ALGO_SCRYPT:
1195 				max64 = opt_scrypt_n < 16 ? 0x3ffff : 0x3fffff / opt_scrypt_n;
1196 				break;
1197 			case ALGO_SHA256D:
1198 				max64 = 0x1fffff;
1199 				break;
1200 			}
1201 		}
1202 		if (work.data[19] + max64 > end_nonce)
1203 			max_nonce = end_nonce;
1204 		else
1205 			max_nonce = work.data[19] + max64;
1206 
1207 		hashes_done = 0;
1208 		gettimeofday(&tv_start, NULL);
1209 
1210 		/* scan nonces for a proof-of-work hash */
1211 		switch (opt_algo) {
1212 		case ALGO_SCRYPT:
1213 			rc = scanhash_scrypt(thr_id, work.data, scratchbuf, work.target,
1214 			                     max_nonce, &hashes_done, opt_scrypt_n);
1215 			break;
1216 
1217 		case ALGO_SHA256D:
1218 			rc = scanhash_sha256d(thr_id, work.data, work.target,
1219 			                      max_nonce, &hashes_done);
1220 			break;
1221 
1222 		default:
1223 			/* should never happen */
1224 			goto out;
1225 		}
1226 
1227 		/* record scanhash elapsed time */
1228 		gettimeofday(&tv_end, NULL);
1229 		timeval_subtract(&diff, &tv_end, &tv_start);
1230 		if (diff.tv_usec || diff.tv_sec) {
1231 			pthread_mutex_lock(&stats_lock);
1232 			thr_hashrates[thr_id] =
1233 				hashes_done / (diff.tv_sec + 1e-6 * diff.tv_usec);
1234 			pthread_mutex_unlock(&stats_lock);
1235 		}
1236 		if (!opt_quiet) {
1237 			sprintf(s, thr_hashrates[thr_id] >= 1e6 ? "%.0f" : "%.2f",
1238 				1e-3 * thr_hashrates[thr_id]);
1239 			applog(LOG_INFO, "thread %d: %lu hashes, %s khash/s",
1240 				thr_id, hashes_done, s);
1241 		}
1242 		if (opt_benchmark && thr_id == opt_n_threads - 1) {
1243 			double hashrate = 0.;
1244 			for (i = 0; i < opt_n_threads && thr_hashrates[i]; i++)
1245 				hashrate += thr_hashrates[i];
1246 			if (i == opt_n_threads) {
1247 				sprintf(s, hashrate >= 1e6 ? "%.0f" : "%.2f", 1e-3 * hashrate);
1248 				applog(LOG_INFO, "Total: %s khash/s", s);
1249 			}
1250 		}
1251 
1252 		/* if nonce found, submit work */
1253 		if (rc && !opt_benchmark && !submit_work(mythr, &work))
1254 			break;
1255 	}
1256 
1257 out:
1258 	tq_freeze(mythr->q);
1259 
1260 	return NULL;
1261 }
1262 
restart_threads(void)1263 static void restart_threads(void)
1264 {
1265 	int i;
1266 
1267 	for (i = 0; i < opt_n_threads; i++)
1268 		work_restart[i].restart = 1;
1269 }
1270 
longpoll_thread(void * userdata)1271 static void *longpoll_thread(void *userdata)
1272 {
1273 	struct thr_info *mythr = userdata;
1274 	CURL *curl = NULL;
1275 	char *copy_start, *hdr_path = NULL, *lp_url = NULL;
1276 	bool need_slash = false;
1277 
1278 	curl = curl_easy_init();
1279 	if (unlikely(!curl)) {
1280 		applog(LOG_ERR, "CURL initialization failed");
1281 		goto out;
1282 	}
1283 
1284 start:
1285 	hdr_path = tq_pop(mythr->q, NULL);
1286 	if (!hdr_path)
1287 		goto out;
1288 
1289 	/* full URL */
1290 	if (strstr(hdr_path, "://")) {
1291 		lp_url = hdr_path;
1292 		hdr_path = NULL;
1293 	}
1294 
1295 	/* absolute path, on current server */
1296 	else {
1297 		copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
1298 		if (rpc_url[strlen(rpc_url) - 1] != '/')
1299 			need_slash = true;
1300 
1301 		lp_url = malloc(strlen(rpc_url) + strlen(copy_start) + 2);
1302 		if (!lp_url)
1303 			goto out;
1304 
1305 		sprintf(lp_url, "%s%s%s", rpc_url, need_slash ? "/" : "", copy_start);
1306 	}
1307 
1308 	applog(LOG_INFO, "Long-polling activated for %s", lp_url);
1309 
1310 	while (1) {
1311 		json_t *val, *res, *soval;
1312 		char *req = NULL;
1313 		int err;
1314 
1315 		if (have_gbt) {
1316 			req = malloc(strlen(gbt_lp_req) + strlen(lp_id) + 1);
1317 			sprintf(req, gbt_lp_req, lp_id);
1318 		}
1319 		val = json_rpc_call(curl, lp_url, rpc_userpass,
1320 				    req ? req : getwork_req, &err,
1321 				    JSON_RPC_LONGPOLL);
1322 		free(req);
1323 		if (have_stratum) {
1324 			if (val)
1325 				json_decref(val);
1326 			goto out;
1327 		}
1328 		if (likely(val)) {
1329 			bool rc;
1330 			applog(LOG_INFO, "LONGPOLL pushed new work");
1331 			res = json_object_get(val, "result");
1332 			soval = json_object_get(res, "submitold");
1333 			submit_old = soval ? json_is_true(soval) : false;
1334 			pthread_mutex_lock(&g_work_lock);
1335 			work_free(&g_work);
1336 			if (have_gbt)
1337 				rc = gbt_work_decode(res, &g_work);
1338 			else
1339 				rc = work_decode(res, &g_work);
1340 			if (rc) {
1341 				time(&g_work_time);
1342 				restart_threads();
1343 			}
1344 			pthread_mutex_unlock(&g_work_lock);
1345 			json_decref(val);
1346 		} else {
1347 			pthread_mutex_lock(&g_work_lock);
1348 			g_work_time -= LP_SCANTIME;
1349 			pthread_mutex_unlock(&g_work_lock);
1350 			if (err == CURLE_OPERATION_TIMEDOUT) {
1351 				restart_threads();
1352 			} else {
1353 				have_longpoll = false;
1354 				restart_threads();
1355 				free(hdr_path);
1356 				free(lp_url);
1357 				lp_url = NULL;
1358 				sleep(opt_fail_pause);
1359 				goto start;
1360 			}
1361 		}
1362 	}
1363 
1364 out:
1365 	free(hdr_path);
1366 	free(lp_url);
1367 	tq_freeze(mythr->q);
1368 	if (curl)
1369 		curl_easy_cleanup(curl);
1370 
1371 	return NULL;
1372 }
1373 
stratum_handle_response(char * buf)1374 static bool stratum_handle_response(char *buf)
1375 {
1376 	json_t *val, *err_val, *res_val, *id_val;
1377 	json_error_t err;
1378 	bool ret = false;
1379 
1380 	val = JSON_LOADS(buf, &err);
1381 	if (!val) {
1382 		applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
1383 		goto out;
1384 	}
1385 
1386 	res_val = json_object_get(val, "result");
1387 	err_val = json_object_get(val, "error");
1388 	id_val = json_object_get(val, "id");
1389 
1390 	if (!id_val || json_is_null(id_val) || !res_val)
1391 		goto out;
1392 
1393 	share_result(json_is_true(res_val),
1394 		err_val ? json_string_value(json_array_get(err_val, 1)) : NULL);
1395 
1396 	ret = true;
1397 out:
1398 	if (val)
1399 		json_decref(val);
1400 
1401 	return ret;
1402 }
1403 
stratum_thread(void * userdata)1404 static void *stratum_thread(void *userdata)
1405 {
1406 	struct thr_info *mythr = userdata;
1407 	char *s;
1408 
1409 	stratum.url = tq_pop(mythr->q, NULL);
1410 	if (!stratum.url)
1411 		goto out;
1412 	applog(LOG_INFO, "Starting Stratum on %s", stratum.url);
1413 
1414 	while (1) {
1415 		int failures = 0;
1416 
1417 		while (!stratum.curl) {
1418 			pthread_mutex_lock(&g_work_lock);
1419 			g_work_time = 0;
1420 			pthread_mutex_unlock(&g_work_lock);
1421 			restart_threads();
1422 
1423 			if (!stratum_connect(&stratum, stratum.url) ||
1424 			    !stratum_subscribe(&stratum) ||
1425 			    !stratum_authorize(&stratum, rpc_user, rpc_pass)) {
1426 				stratum_disconnect(&stratum);
1427 				if (opt_retries >= 0 && ++failures > opt_retries) {
1428 					applog(LOG_ERR, "...terminating workio thread");
1429 					tq_push(thr_info[work_thr_id].q, NULL);
1430 					goto out;
1431 				}
1432 				applog(LOG_ERR, "...retry after %d seconds", opt_fail_pause);
1433 				sleep(opt_fail_pause);
1434 			}
1435 		}
1436 
1437 		if (stratum.job.job_id &&
1438 		    (!g_work_time || strcmp(stratum.job.job_id, g_work.job_id))) {
1439 			pthread_mutex_lock(&g_work_lock);
1440 			stratum_gen_work(&stratum, &g_work);
1441 			time(&g_work_time);
1442 			pthread_mutex_unlock(&g_work_lock);
1443 			if (stratum.job.clean) {
1444 				applog(LOG_INFO, "Stratum requested work restart");
1445 				restart_threads();
1446 			}
1447 		}
1448 
1449 		if (!stratum_socket_full(&stratum, 120)) {
1450 			applog(LOG_ERR, "Stratum connection timed out");
1451 			s = NULL;
1452 		} else
1453 			s = stratum_recv_line(&stratum);
1454 		if (!s) {
1455 			stratum_disconnect(&stratum);
1456 			applog(LOG_ERR, "Stratum connection interrupted");
1457 			continue;
1458 		}
1459 		if (!stratum_handle_method(&stratum, s))
1460 			stratum_handle_response(s);
1461 		free(s);
1462 	}
1463 
1464 out:
1465 	return NULL;
1466 }
1467 
show_version_and_exit(void)1468 static void show_version_and_exit(void)
1469 {
1470 	printf(PACKAGE_STRING "\n built on " __DATE__ "\n features:"
1471 #if defined(USE_ASM) && defined(__i386__)
1472 		" i386"
1473 #endif
1474 #if defined(USE_ASM) && defined(__x86_64__)
1475 		" x86_64"
1476 		" PHE"
1477 #endif
1478 #if defined(USE_ASM) && (defined(__i386__) || defined(__x86_64__))
1479 		" SSE2"
1480 #endif
1481 #if defined(__x86_64__) && defined(USE_AVX)
1482 		" AVX"
1483 #endif
1484 #if defined(__x86_64__) && defined(USE_AVX2)
1485 		" AVX2"
1486 #endif
1487 #if defined(__x86_64__) && defined(USE_XOP)
1488 		" XOP"
1489 #endif
1490 #if defined(USE_ASM) && defined(__arm__) && defined(__APCS_32__)
1491 		" ARM"
1492 #if defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) || \
1493 	defined(__ARM_ARCH_5TEJ__) || defined(__ARM_ARCH_6__) || \
1494 	defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || \
1495 	defined(__ARM_ARCH_6M__) || defined(__ARM_ARCH_6T2__) || \
1496 	defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || \
1497 	defined(__ARM_ARCH_7__) || \
1498 	defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || \
1499 	defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)
1500 		" ARMv5E"
1501 #endif
1502 #if defined(__ARM_NEON__)
1503 		" NEON"
1504 #endif
1505 #endif
1506 #if defined(USE_ASM) && (defined(__powerpc__) || defined(__ppc__) || defined(__PPC__))
1507 		" PowerPC"
1508 #if defined(__ALTIVEC__)
1509 		" AltiVec"
1510 #endif
1511 #endif
1512 		"\n");
1513 
1514 	printf("%s\n", curl_version());
1515 #ifdef JANSSON_VERSION
1516 	printf("libjansson %s\n", JANSSON_VERSION);
1517 #endif
1518 	exit(0);
1519 }
1520 
show_usage_and_exit(int status)1521 static void show_usage_and_exit(int status)
1522 {
1523 	if (status)
1524 		fprintf(stderr, "Try `" PROGRAM_NAME " --help' for more information.\n");
1525 	else
1526 		printf(usage);
1527 	exit(status);
1528 }
1529 
strhide(char * s)1530 static void strhide(char *s)
1531 {
1532 	if (*s) *s++ = 'x';
1533 	while (*s) *s++ = '\0';
1534 }
1535 
1536 static void parse_config(json_t *config, char *pname, char *ref);
1537 
parse_arg(int key,char * arg,char * pname)1538 static void parse_arg(int key, char *arg, char *pname)
1539 {
1540 	char *p;
1541 	int v, i;
1542 
1543 	switch(key) {
1544 	case 'a':
1545 		for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
1546 			v = strlen(algo_names[i]);
1547 			if (!strncmp(arg, algo_names[i], v)) {
1548 				if (arg[v] == '\0') {
1549 					opt_algo = i;
1550 					break;
1551 				}
1552 				if (arg[v] == ':' && i == ALGO_SCRYPT) {
1553 					char *ep;
1554 					v = strtol(arg+v+1, &ep, 10);
1555 					if (*ep || v & (v-1) || v < 2)
1556 						continue;
1557 					opt_algo = i;
1558 					opt_scrypt_n = v;
1559 					break;
1560 				}
1561 			}
1562 		}
1563 		if (i == ARRAY_SIZE(algo_names)) {
1564 			fprintf(stderr, "%s: unknown algorithm -- '%s'\n",
1565 				pname, arg);
1566 			show_usage_and_exit(1);
1567 		}
1568 		break;
1569 	case 'B':
1570 		opt_background = true;
1571 		break;
1572 	case 'c': {
1573 		json_error_t err;
1574 		json_t *config = JSON_LOAD_FILE(arg, &err);
1575 		if (!json_is_object(config)) {
1576 			if (err.line < 0)
1577 				fprintf(stderr, "%s: %s\n", pname, err.text);
1578 			else
1579 				fprintf(stderr, "%s: %s:%d: %s\n",
1580 					pname, arg, err.line, err.text);
1581 			exit(1);
1582 		}
1583 		parse_config(config, pname, arg);
1584 		json_decref(config);
1585 		break;
1586 	}
1587 	case 'q':
1588 		opt_quiet = true;
1589 		break;
1590 	case 'D':
1591 		opt_debug = true;
1592 		break;
1593 	case 'p':
1594 		free(rpc_pass);
1595 		rpc_pass = strdup(arg);
1596 		strhide(arg);
1597 		break;
1598 	case 'P':
1599 		opt_protocol = true;
1600 		break;
1601 	case 'r':
1602 		v = atoi(arg);
1603 		if (v < -1 || v > 9999)	/* sanity check */
1604 			show_usage_and_exit(1);
1605 		opt_retries = v;
1606 		break;
1607 	case 'R':
1608 		v = atoi(arg);
1609 		if (v < 1 || v > 9999)	/* sanity check */
1610 			show_usage_and_exit(1);
1611 		opt_fail_pause = v;
1612 		break;
1613 	case 's':
1614 		v = atoi(arg);
1615 		if (v < 1 || v > 9999)	/* sanity check */
1616 			show_usage_and_exit(1);
1617 		opt_scantime = v;
1618 		break;
1619 	case 'T':
1620 		v = atoi(arg);
1621 		if (v < 1 || v > 99999)	/* sanity check */
1622 			show_usage_and_exit(1);
1623 		opt_timeout = v;
1624 		break;
1625 	case 't':
1626 		v = atoi(arg);
1627 		if (v < 1 || v > 9999)	/* sanity check */
1628 			show_usage_and_exit(1);
1629 		opt_n_threads = v;
1630 		break;
1631 	case 'u':
1632 		free(rpc_user);
1633 		rpc_user = strdup(arg);
1634 		break;
1635 	case 'o': {			/* --url */
1636 		char *ap, *hp;
1637 		ap = strstr(arg, "://");
1638 		ap = ap ? ap + 3 : arg;
1639 		hp = strrchr(arg, '@');
1640 		if (hp) {
1641 			*hp = '\0';
1642 			p = strchr(ap, ':');
1643 			if (p) {
1644 				free(rpc_userpass);
1645 				rpc_userpass = strdup(ap);
1646 				free(rpc_user);
1647 				rpc_user = calloc(p - ap + 1, 1);
1648 				strncpy(rpc_user, ap, p - ap);
1649 				free(rpc_pass);
1650 				rpc_pass = strdup(++p);
1651 				if (*p) *p++ = 'x';
1652 				v = strlen(hp + 1) + 1;
1653 				memmove(p + 1, hp + 1, v);
1654 				memset(p + v, 0, hp - p);
1655 				hp = p;
1656 			} else {
1657 				free(rpc_user);
1658 				rpc_user = strdup(ap);
1659 			}
1660 			*hp++ = '@';
1661 		} else
1662 			hp = ap;
1663 		if (ap != arg) {
1664 			if (strncasecmp(arg, "http://", 7) &&
1665 			    strncasecmp(arg, "https://", 8) &&
1666 			    strncasecmp(arg, "stratum+tcp://", 14) &&
1667 			    strncasecmp(arg, "stratum+tcps://", 15)) {
1668 				fprintf(stderr, "%s: unknown protocol -- '%s'\n",
1669 					pname, arg);
1670 				show_usage_and_exit(1);
1671 			}
1672 			free(rpc_url);
1673 			rpc_url = strdup(arg);
1674 			strcpy(rpc_url + (ap - arg), hp);
1675 		} else {
1676 			if (*hp == '\0' || *hp == '/') {
1677 				fprintf(stderr, "%s: invalid URL -- '%s'\n",
1678 					pname, arg);
1679 				show_usage_and_exit(1);
1680 			}
1681 			free(rpc_url);
1682 			rpc_url = malloc(strlen(hp) + 8);
1683 			sprintf(rpc_url, "http://%s", hp);
1684 		}
1685 		have_stratum = !opt_benchmark && !strncasecmp(rpc_url, "stratum", 7);
1686 		break;
1687 	}
1688 	case 'O':			/* --userpass */
1689 		p = strchr(arg, ':');
1690 		if (!p) {
1691 			fprintf(stderr, "%s: invalid username:password pair -- '%s'\n",
1692 				pname, arg);
1693 			show_usage_and_exit(1);
1694 		}
1695 		free(rpc_userpass);
1696 		rpc_userpass = strdup(arg);
1697 		free(rpc_user);
1698 		rpc_user = calloc(p - arg + 1, 1);
1699 		strncpy(rpc_user, arg, p - arg);
1700 		free(rpc_pass);
1701 		rpc_pass = strdup(++p);
1702 		strhide(p);
1703 		break;
1704 	case 'x':			/* --proxy */
1705 		if (!strncasecmp(arg, "socks4://", 9))
1706 			opt_proxy_type = CURLPROXY_SOCKS4;
1707 		else if (!strncasecmp(arg, "socks5://", 9))
1708 			opt_proxy_type = CURLPROXY_SOCKS5;
1709 #if LIBCURL_VERSION_NUM >= 0x071200
1710 		else if (!strncasecmp(arg, "socks4a://", 10))
1711 			opt_proxy_type = CURLPROXY_SOCKS4A;
1712 		else if (!strncasecmp(arg, "socks5h://", 10))
1713 			opt_proxy_type = CURLPROXY_SOCKS5_HOSTNAME;
1714 #endif
1715 		else
1716 			opt_proxy_type = CURLPROXY_HTTP;
1717 		free(opt_proxy);
1718 		opt_proxy = strdup(arg);
1719 		break;
1720 	case 1001:
1721 		free(opt_cert);
1722 		opt_cert = strdup(arg);
1723 		break;
1724 	case 1005:
1725 		opt_benchmark = true;
1726 		want_longpoll = false;
1727 		want_stratum = false;
1728 		have_stratum = false;
1729 		break;
1730 	case 1003:
1731 		want_longpoll = false;
1732 		break;
1733 	case 1007:
1734 		want_stratum = false;
1735 		break;
1736 	case 1009:
1737 		opt_redirect = false;
1738 		break;
1739 	case 1010:
1740 		allow_getwork = false;
1741 		break;
1742 	case 1011:
1743 		have_gbt = false;
1744 		break;
1745 	case 1013:			/* --coinbase-addr */
1746 		pk_script_size = address_to_script(pk_script, sizeof(pk_script), arg);
1747 		if (!pk_script_size) {
1748 			fprintf(stderr, "%s: invalid address -- '%s'\n",
1749 				pname, arg);
1750 			show_usage_and_exit(1);
1751 		}
1752 		break;
1753 	case 1015:			/* --coinbase-sig */
1754 		if (strlen(arg) + 1 > sizeof(coinbase_sig)) {
1755 			fprintf(stderr, "%s: coinbase signature too long\n", pname);
1756 			show_usage_and_exit(1);
1757 		}
1758 		strcpy(coinbase_sig, arg);
1759 		break;
1760 	case 'S':
1761 		use_syslog = true;
1762 		break;
1763 	case 'V':
1764 		show_version_and_exit();
1765 	case 'h':
1766 		show_usage_and_exit(0);
1767 	default:
1768 		show_usage_and_exit(1);
1769 	}
1770 }
1771 
parse_config(json_t * config,char * pname,char * ref)1772 static void parse_config(json_t *config, char *pname, char *ref)
1773 {
1774 	int i;
1775 	char *s;
1776 	json_t *val;
1777 
1778 	for (i = 0; i < ARRAY_SIZE(options); i++) {
1779 		if (!options[i].name)
1780 			break;
1781 
1782 		val = json_object_get(config, options[i].name);
1783 		if (!val)
1784 			continue;
1785 
1786 		if (options[i].has_arg && json_is_string(val)) {
1787 			if (!strcmp(options[i].name, "config")) {
1788 				fprintf(stderr, "%s: %s: option '%s' not allowed here\n",
1789 					pname, ref, options[i].name);
1790 				exit(1);
1791 			}
1792 			s = strdup(json_string_value(val));
1793 			if (!s)
1794 				break;
1795 			parse_arg(options[i].val, s, pname);
1796 			free(s);
1797 		} else if (!options[i].has_arg && json_is_true(val)) {
1798 			parse_arg(options[i].val, "", pname);
1799 		} else {
1800 			fprintf(stderr, "%s: invalid argument for option '%s'\n",
1801 				pname, options[i].name);
1802 			exit(1);
1803 		}
1804 	}
1805 }
1806 
parse_cmdline(int argc,char * argv[])1807 static void parse_cmdline(int argc, char *argv[])
1808 {
1809 	int key;
1810 
1811 	while (1) {
1812 #if HAVE_GETOPT_LONG
1813 		key = getopt_long(argc, argv, short_options, options, NULL);
1814 #else
1815 		key = getopt(argc, argv, short_options);
1816 #endif
1817 		if (key < 0)
1818 			break;
1819 
1820 		parse_arg(key, optarg, argv[0]);
1821 	}
1822 	if (optind < argc) {
1823 		fprintf(stderr, "%s: unsupported non-option argument -- '%s'\n",
1824 			argv[0], argv[optind]);
1825 		show_usage_and_exit(1);
1826 	}
1827 }
1828 
1829 #ifndef WIN32
signal_handler(int sig)1830 static void signal_handler(int sig)
1831 {
1832 	switch (sig) {
1833 	case SIGHUP:
1834 		applog(LOG_INFO, "SIGHUP received");
1835 		break;
1836 	case SIGINT:
1837 		applog(LOG_INFO, "SIGINT received, exiting");
1838 		exit(0);
1839 		break;
1840 	case SIGTERM:
1841 		applog(LOG_INFO, "SIGTERM received, exiting");
1842 		exit(0);
1843 		break;
1844 	}
1845 }
1846 #endif
1847 
main(int argc,char * argv[])1848 int main(int argc, char *argv[])
1849 {
1850 	struct thr_info *thr;
1851 	long flags;
1852 	int i;
1853 
1854 	rpc_user = strdup("");
1855 	rpc_pass = strdup("");
1856 
1857 	/* parse command line */
1858 	parse_cmdline(argc, argv);
1859 
1860 	if (!opt_benchmark && !rpc_url) {
1861 		fprintf(stderr, "%s: no URL supplied\n", argv[0]);
1862 		show_usage_and_exit(1);
1863 	}
1864 
1865 	if (!rpc_userpass) {
1866 		rpc_userpass = malloc(strlen(rpc_user) + strlen(rpc_pass) + 2);
1867 		if (!rpc_userpass)
1868 			return 1;
1869 		sprintf(rpc_userpass, "%s:%s", rpc_user, rpc_pass);
1870 	}
1871 
1872 	pthread_mutex_init(&applog_lock, NULL);
1873 	pthread_mutex_init(&stats_lock, NULL);
1874 	pthread_mutex_init(&g_work_lock, NULL);
1875 	pthread_mutex_init(&stratum.sock_lock, NULL);
1876 	pthread_mutex_init(&stratum.work_lock, NULL);
1877 
1878 	flags = opt_benchmark || (strncasecmp(rpc_url, "https://", 8) &&
1879 	                          strncasecmp(rpc_url, "stratum+tcps://", 15))
1880 	      ? (CURL_GLOBAL_ALL & ~CURL_GLOBAL_SSL)
1881 	      : CURL_GLOBAL_ALL;
1882 	if (curl_global_init(flags)) {
1883 		applog(LOG_ERR, "CURL initialization failed");
1884 		return 1;
1885 	}
1886 
1887 #ifndef WIN32
1888 	if (opt_background) {
1889 		i = fork();
1890 		if (i < 0) exit(1);
1891 		if (i > 0) exit(0);
1892 		i = setsid();
1893 		if (i < 0)
1894 			applog(LOG_ERR, "setsid() failed (errno = %d)", errno);
1895 		i = chdir("/");
1896 		if (i < 0)
1897 			applog(LOG_ERR, "chdir() failed (errno = %d)", errno);
1898 		signal(SIGHUP, signal_handler);
1899 		signal(SIGINT, signal_handler);
1900 		signal(SIGTERM, signal_handler);
1901 	}
1902 #endif
1903 
1904 #if defined(WIN32)
1905 	SYSTEM_INFO sysinfo;
1906 	GetSystemInfo(&sysinfo);
1907 	num_processors = sysinfo.dwNumberOfProcessors;
1908 #elif defined(_SC_NPROCESSORS_CONF)
1909 	num_processors = sysconf(_SC_NPROCESSORS_CONF);
1910 #elif defined(CTL_HW) && defined(HW_NCPU)
1911 	int req[] = { CTL_HW, HW_NCPU };
1912 	size_t len = sizeof(num_processors);
1913 	sysctl(req, 2, &num_processors, &len, NULL, 0);
1914 #else
1915 	num_processors = 1;
1916 #endif
1917 	if (num_processors < 1)
1918 		num_processors = 1;
1919 	if (!opt_n_threads)
1920 		opt_n_threads = num_processors;
1921 
1922 #ifdef HAVE_SYSLOG_H
1923 	if (use_syslog)
1924 		openlog("cpuminer", LOG_PID, LOG_USER);
1925 #endif
1926 
1927 	work_restart = calloc(opt_n_threads, sizeof(*work_restart));
1928 	if (!work_restart)
1929 		return 1;
1930 
1931 	thr_info = calloc(opt_n_threads + 3, sizeof(*thr));
1932 	if (!thr_info)
1933 		return 1;
1934 
1935 	thr_hashrates = (double *) calloc(opt_n_threads, sizeof(double));
1936 	if (!thr_hashrates)
1937 		return 1;
1938 
1939 	/* init workio thread info */
1940 	work_thr_id = opt_n_threads;
1941 	thr = &thr_info[work_thr_id];
1942 	thr->id = work_thr_id;
1943 	thr->q = tq_new();
1944 	if (!thr->q)
1945 		return 1;
1946 
1947 	/* start work I/O thread */
1948 	if (pthread_create(&thr->pth, NULL, workio_thread, thr)) {
1949 		applog(LOG_ERR, "workio thread create failed");
1950 		return 1;
1951 	}
1952 
1953 	if (want_longpoll && !have_stratum) {
1954 		/* init longpoll thread info */
1955 		longpoll_thr_id = opt_n_threads + 1;
1956 		thr = &thr_info[longpoll_thr_id];
1957 		thr->id = longpoll_thr_id;
1958 		thr->q = tq_new();
1959 		if (!thr->q)
1960 			return 1;
1961 
1962 		/* start longpoll thread */
1963 		if (unlikely(pthread_create(&thr->pth, NULL, longpoll_thread, thr))) {
1964 			applog(LOG_ERR, "longpoll thread create failed");
1965 			return 1;
1966 		}
1967 	}
1968 	if (want_stratum) {
1969 		/* init stratum thread info */
1970 		stratum_thr_id = opt_n_threads + 2;
1971 		thr = &thr_info[stratum_thr_id];
1972 		thr->id = stratum_thr_id;
1973 		thr->q = tq_new();
1974 		if (!thr->q)
1975 			return 1;
1976 
1977 		/* start stratum thread */
1978 		if (unlikely(pthread_create(&thr->pth, NULL, stratum_thread, thr))) {
1979 			applog(LOG_ERR, "stratum thread create failed");
1980 			return 1;
1981 		}
1982 
1983 		if (have_stratum)
1984 			tq_push(thr_info[stratum_thr_id].q, strdup(rpc_url));
1985 	}
1986 
1987 	/* start mining threads */
1988 	for (i = 0; i < opt_n_threads; i++) {
1989 		thr = &thr_info[i];
1990 
1991 		thr->id = i;
1992 		thr->q = tq_new();
1993 		if (!thr->q)
1994 			return 1;
1995 
1996 		if (unlikely(pthread_create(&thr->pth, NULL, miner_thread, thr))) {
1997 			applog(LOG_ERR, "thread %d create failed", i);
1998 			return 1;
1999 		}
2000 	}
2001 
2002 	applog(LOG_INFO, "%d miner threads started, "
2003 		"using '%s' algorithm.",
2004 		opt_n_threads,
2005 		algo_names[opt_algo]);
2006 
2007 	/* main loop - simply wait for workio thread to exit */
2008 	pthread_join(thr_info[work_thr_id].pth, NULL);
2009 
2010 	applog(LOG_INFO, "workio thread dead, exiting.");
2011 
2012 	return 0;
2013 }
2014