cpu-miner.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /*
  2. * Copyright 2010 Jeff Garzik
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the Free
  6. * Software Foundation; either version 2 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. #define _GNU_SOURCE
  10. #include "cpuminer-config.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <stdbool.h>
  15. #include <unistd.h>
  16. #include <sys/time.h>
  17. #include <sys/resource.h>
  18. #include <pthread.h>
  19. #include <argp.h>
  20. #include <jansson.h>
  21. #include <curl/curl.h>
  22. #define PROGRAM_NAME "minerd"
  23. #define DEF_RPC_URL "http://127.0.0.1:8332/"
  24. #define DEF_RPC_USERPASS "rpcuser:rpcpass"
  25. #include "sha256_generic.c"
  26. enum {
  27. STAT_SLEEP_INTERVAL = 10,
  28. STAT_CTR_INTERVAL = 10000000,
  29. };
  30. static bool opt_debug;
  31. static bool opt_protocol;
  32. static bool program_running = true;
  33. static const bool opt_time = true;
  34. static int opt_n_threads = 1;
  35. static pthread_mutex_t stats_mutex = PTHREAD_MUTEX_INITIALIZER;
  36. static uint64_t hash_ctr;
  37. static char *rpc_url = DEF_RPC_URL;
  38. static char *userpass = DEF_RPC_USERPASS;
  39. static struct argp_option options[] = {
  40. { "debug", 'D', NULL, 0,
  41. "Enable debug output" },
  42. { "protocol-dump", 'P', NULL, 0,
  43. "Verbose dump of protocol-level activities" },
  44. { "threads", 't', "N", 0,
  45. "Number of miner threads (default: 1)" },
  46. { "url", 1001, "URL", 0,
  47. "URL for bitcoin JSON-RPC server "
  48. "(default: " DEF_RPC_URL ")" },
  49. { "userpass", 1002, "USER:PASS", 0,
  50. "Username:Password pair for bitcoin JSON-RPC server "
  51. "(default: " DEF_RPC_USERPASS ")" },
  52. { }
  53. };
  54. static const char doc[] =
  55. PROGRAM_NAME " - CPU miner for bitcoin";
  56. static error_t parse_opt (int key, char *arg, struct argp_state *state);
  57. static const struct argp argp = { options, parse_opt, NULL, doc };
  58. struct data_buffer {
  59. void *buf;
  60. size_t len;
  61. };
  62. struct upload_buffer {
  63. const void *buf;
  64. size_t len;
  65. };
  66. struct work {
  67. unsigned char midstate[32];
  68. unsigned char data[128];
  69. unsigned char hash[32];
  70. unsigned char hash1[64];
  71. unsigned char target[32];
  72. };
  73. static void databuf_free(struct data_buffer *db)
  74. {
  75. if (!db)
  76. return;
  77. free(db->buf);
  78. memset(db, 0, sizeof(*db));
  79. }
  80. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  81. void *user_data)
  82. {
  83. struct data_buffer *db = user_data;
  84. size_t len = size * nmemb;
  85. size_t oldlen, newlen;
  86. void *newmem;
  87. static const unsigned char zero;
  88. oldlen = db->len;
  89. newlen = oldlen + len;
  90. newmem = realloc(db->buf, newlen + 1);
  91. if (!newmem)
  92. return 0;
  93. db->buf = newmem;
  94. db->len = newlen;
  95. memcpy(db->buf + oldlen, ptr, len);
  96. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  97. return len;
  98. }
  99. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  100. void *user_data)
  101. {
  102. struct upload_buffer *ub = user_data;
  103. int len = size * nmemb;
  104. if (len > ub->len)
  105. len = ub->len;
  106. if (len) {
  107. memcpy(ptr, ub->buf, len);
  108. ub->buf += len;
  109. ub->len -= len;
  110. }
  111. return len;
  112. }
  113. static json_t *json_rpc_call(const char *url, const char *userpass,
  114. const char *rpc_req)
  115. {
  116. CURL *curl;
  117. json_t *val;
  118. int rc;
  119. struct data_buffer all_data = { };
  120. struct upload_buffer upload_data;
  121. json_error_t err = { };
  122. struct curl_slist *headers = NULL;
  123. char len_hdr[64];
  124. curl = curl_easy_init();
  125. if (!curl)
  126. return NULL;
  127. if (opt_protocol)
  128. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  129. curl_easy_setopt(curl, CURLOPT_URL, url);
  130. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  131. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  132. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  133. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  134. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  135. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  136. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  137. if (userpass) {
  138. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  139. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  140. }
  141. curl_easy_setopt(curl, CURLOPT_POST, 1);
  142. if (opt_protocol)
  143. printf("JSON protocol request:\n%s\n", rpc_req);
  144. upload_data.buf = rpc_req;
  145. upload_data.len = strlen(rpc_req);
  146. sprintf(len_hdr, "Content-Length: %lu",
  147. (unsigned long) upload_data.len);
  148. headers = curl_slist_append(headers,
  149. "Content-type: application/json");
  150. headers = curl_slist_append(headers, len_hdr);
  151. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  152. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  153. rc = curl_easy_perform(curl);
  154. if (rc)
  155. goto err_out;
  156. val = json_loads(all_data.buf, &err);
  157. if (!val) {
  158. fprintf(stderr, "JSON failed(%d): %s\n", err.line, err.text);
  159. goto err_out;
  160. }
  161. if (opt_protocol) {
  162. char *s = json_dumps(val, JSON_INDENT(3));
  163. printf("JSON protocol response:\n%s\n", s);
  164. free(s);
  165. }
  166. databuf_free(&all_data);
  167. curl_slist_free_all(headers);
  168. curl_easy_cleanup(curl);
  169. return val;
  170. err_out:
  171. databuf_free(&all_data);
  172. curl_slist_free_all(headers);
  173. curl_easy_cleanup(curl);
  174. return NULL;
  175. }
  176. static char *bin2hex(unsigned char *p, size_t len)
  177. {
  178. int i;
  179. char *s = malloc((len * 2) + 1);
  180. if (!s)
  181. return NULL;
  182. for (i = 0; i < len; i++)
  183. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  184. return s;
  185. }
  186. static bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  187. {
  188. while (*hexstr && len) {
  189. char hex_byte[3];
  190. unsigned int v;
  191. if (!hexstr[1]) {
  192. fprintf(stderr, "hex2bin str truncated\n");
  193. return false;
  194. }
  195. hex_byte[0] = hexstr[0];
  196. hex_byte[1] = hexstr[1];
  197. hex_byte[2] = 0;
  198. if (sscanf(hex_byte, "%x", &v) != 1) {
  199. fprintf(stderr, "hex2bin sscanf '%s' failed\n",
  200. hex_byte);
  201. return false;
  202. }
  203. *p = (unsigned char) v;
  204. p++;
  205. hexstr += 2;
  206. len--;
  207. }
  208. return (len == 0 && *hexstr == 0) ? true : false;
  209. }
  210. static bool jobj_binary(const json_t *obj, const char *key,
  211. void *buf, size_t buflen)
  212. {
  213. const char *hexstr;
  214. json_t *tmp;
  215. tmp = json_object_get(obj, key);
  216. if (!tmp) {
  217. fprintf(stderr, "JSON key '%s' not found\n", key);
  218. return false;
  219. }
  220. hexstr = json_string_value(tmp);
  221. if (!hexstr) {
  222. fprintf(stderr, "JSON key '%s' is not a string\n", key);
  223. return false;
  224. }
  225. if (!hex2bin(buf, hexstr, buflen))
  226. return false;
  227. return true;
  228. }
  229. static void work_free(struct work *work)
  230. {
  231. if (!work)
  232. return;
  233. free(work);
  234. }
  235. static struct work *work_decode(const json_t *val)
  236. {
  237. struct work *work;
  238. work = calloc(1, sizeof(*work));
  239. if (!work)
  240. return NULL;
  241. if (!jobj_binary(val, "midstate",
  242. work->midstate, sizeof(work->midstate))) {
  243. fprintf(stderr, "JSON inval midstate\n");
  244. goto err_out;
  245. }
  246. if (!jobj_binary(val, "data", work->data, sizeof(work->data))) {
  247. fprintf(stderr, "JSON inval data\n");
  248. goto err_out;
  249. }
  250. if (!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1))) {
  251. fprintf(stderr, "JSON inval hash1\n");
  252. goto err_out;
  253. }
  254. if (!jobj_binary(val, "target", work->target, sizeof(work->target))) {
  255. fprintf(stderr, "JSON inval target\n");
  256. goto err_out;
  257. }
  258. return work;
  259. err_out:
  260. work_free(work);
  261. return NULL;
  262. }
  263. static void inc_stats(uint64_t n_hashes)
  264. {
  265. pthread_mutex_lock(&stats_mutex);
  266. hash_ctr += n_hashes;
  267. pthread_mutex_unlock(&stats_mutex);
  268. }
  269. static void runhash(void *state, void *input, const void *init)
  270. {
  271. memcpy(state, init, 32);
  272. sha256_transform(state, input);
  273. }
  274. static const uint32_t init_state[8] = {
  275. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
  276. 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  277. };
  278. /* suspiciously similar to ScanHash* from bitcoin */
  279. static uint32_t scanhash(unsigned char *midstate, unsigned char *data,
  280. unsigned char *hash1, unsigned char *hash)
  281. {
  282. uint32_t *hash32 = (uint32_t *) hash;
  283. uint32_t *nonce = (uint32_t *)(data + 12);
  284. uint32_t n;
  285. unsigned long stat_ctr = 0;
  286. while (1) {
  287. n = *nonce;
  288. n++;
  289. *nonce = n;
  290. runhash(hash1, data, midstate);
  291. runhash(hash, hash1, init_state);
  292. if (hash32[7] == 0) {
  293. char *hexstr;
  294. hexstr = bin2hex(hash, 32);
  295. fprintf(stderr,
  296. "DBG: found zeroes in hash:\n%s\n",
  297. hexstr);
  298. free(hexstr);
  299. return n;
  300. }
  301. stat_ctr++;
  302. if (stat_ctr >= STAT_CTR_INTERVAL) {
  303. inc_stats(STAT_CTR_INTERVAL);
  304. stat_ctr = 0;
  305. }
  306. if ((n & 0xffffff) == 0) {
  307. inc_stats(stat_ctr);
  308. if (opt_debug)
  309. fprintf(stderr, "DBG: end of nonce range\n");
  310. return 0;
  311. }
  312. }
  313. }
  314. static void submit_work(struct work *work)
  315. {
  316. char *hexstr = NULL, *s = NULL;
  317. json_t *val, *res;
  318. printf("PROOF OF WORK FOUND? submitting...\n");
  319. /* build hex string */
  320. hexstr = bin2hex(work->data, sizeof(work->data));
  321. if (!hexstr)
  322. goto out;
  323. /* build JSON-RPC request */
  324. if (asprintf(&s,
  325. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  326. hexstr) < 0) {
  327. fprintf(stderr, "asprintf failed\n");
  328. goto out;
  329. }
  330. if (opt_debug)
  331. fprintf(stderr, "DBG: sending RPC call:\n%s", s);
  332. /* issue JSON-RPC request */
  333. val = json_rpc_call(rpc_url, userpass, s);
  334. if (!val) {
  335. fprintf(stderr, "submit_work json_rpc_call failed\n");
  336. goto out;
  337. }
  338. res = json_object_get(val, "result");
  339. printf("PROOF OF WORK RESULT: %s\n",
  340. json_is_true(res) ? "true (yay!!!)" : "false (booooo)");
  341. json_decref(val);
  342. out:
  343. free(s);
  344. free(hexstr);
  345. }
  346. static void *miner_thread(void *dummy)
  347. {
  348. static const char *rpc_req =
  349. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  350. while (1) {
  351. json_t *val;
  352. struct work *work;
  353. uint32_t nonce;
  354. /* obtain new work from bitcoin */
  355. val = json_rpc_call(rpc_url, userpass, rpc_req);
  356. if (!val) {
  357. fprintf(stderr, "json_rpc_call failed\n");
  358. return NULL;
  359. }
  360. /* decode result into work state struct */
  361. work = work_decode(json_object_get(val, "result"));
  362. if (!work) {
  363. fprintf(stderr, "work decode failed\n");
  364. return NULL;
  365. }
  366. json_decref(val);
  367. /* scan nonces for a proof-of-work hash */
  368. nonce = scanhash(work->midstate, work->data + 64,
  369. work->hash1, work->hash);
  370. /* if nonce found, submit work */
  371. if (nonce)
  372. submit_work(work);
  373. work_free(work);
  374. }
  375. return NULL;
  376. }
  377. static error_t parse_opt (int key, char *arg, struct argp_state *state)
  378. {
  379. int v;
  380. switch(key) {
  381. case 'D':
  382. opt_debug = true;
  383. break;
  384. case 'P':
  385. opt_protocol = true;
  386. break;
  387. case 't':
  388. v = atoi(arg);
  389. if (v < 1 || v > 9999) /* sanity check */
  390. argp_usage(state);
  391. opt_n_threads = v;
  392. break;
  393. case 1001: /* --url */
  394. if (strncmp(arg, "http://", 7) &&
  395. strncmp(arg, "https://", 8))
  396. argp_usage(state);
  397. rpc_url = arg;
  398. break;
  399. case 1002: /* --userpass */
  400. if (!strchr(arg, ':'))
  401. argp_usage(state);
  402. userpass = arg;
  403. break;
  404. case ARGP_KEY_ARG:
  405. argp_usage(state); /* too many args */
  406. break;
  407. case ARGP_KEY_END:
  408. break;
  409. default:
  410. return ARGP_ERR_UNKNOWN;
  411. }
  412. return 0;
  413. }
  414. static void calc_stats(void)
  415. {
  416. uint64_t hashes;
  417. long double hd, sd;
  418. pthread_mutex_lock(&stats_mutex);
  419. hashes = hash_ctr;
  420. hash_ctr = 0;
  421. pthread_mutex_unlock(&stats_mutex);
  422. hashes = hashes / 1000;
  423. hd = hashes;
  424. sd = STAT_SLEEP_INTERVAL;
  425. fprintf(stderr, "wildly inaccurate HashMeter: %.2Lf khash/sec\n", hd / sd);
  426. }
  427. int main (int argc, char *argv[])
  428. {
  429. error_t aprc;
  430. int i;
  431. /* parse command line */
  432. aprc = argp_parse(&argp, argc, argv, 0, NULL, NULL);
  433. if (aprc) {
  434. fprintf(stderr, "argp_parse failed: %s\n", strerror(aprc));
  435. return 1;
  436. }
  437. /* set our priority to the highest (aka "nicest, least intrusive") */
  438. if (setpriority(PRIO_PROCESS, 0, 19))
  439. perror("setpriority");
  440. /* start mining threads */
  441. for (i = 0; i < opt_n_threads; i++) {
  442. pthread_t t;
  443. if (pthread_create(&t, NULL, miner_thread, NULL)) {
  444. fprintf(stderr, "thread %d create failed\n", i);
  445. return 1;
  446. }
  447. sleep(1); /* don't pound RPC server all at once */
  448. }
  449. fprintf(stderr, "%d miner threads started.\n", opt_n_threads);
  450. /* main loop */
  451. while (program_running) {
  452. sleep(STAT_SLEEP_INTERVAL);
  453. calc_stats();
  454. }
  455. return 0;
  456. }