cpu-miner.c 11 KB

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