driver-stratum.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. #include "config.h"
  2. #include <stdbool.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <arpa/inet.h>
  6. #include <event2/buffer.h>
  7. #include <event2/bufferevent.h>
  8. #include <event2/event.h>
  9. #include <event2/listener.h>
  10. #include <jansson.h>
  11. #include "deviceapi.h"
  12. #include "driver-proxy.h"
  13. #include "miner.h"
  14. #include "util.h"
  15. #define MAX_CLIENTS 255
  16. static bool _ssm_xnonce1s[MAX_CLIENTS + 1] = { true };
  17. static uint8_t _ssm_client_octets;
  18. static uint8_t _ssm_client_xnonce2sz;
  19. static char *_ssm_notify;
  20. static int _ssm_notify_sz;
  21. static struct event *ev_notify;
  22. static notifier_t _ssm_update_notifier;
  23. struct stratumsrv_job {
  24. char *my_job_id;
  25. struct pool *pool;
  26. uint8_t work_restart_id;
  27. uint8_t n2size;
  28. struct timeval tv_prepared;
  29. struct stratum_work swork;
  30. char *nonce1;
  31. UT_hash_handle hh;
  32. };
  33. static struct stratumsrv_job *_ssm_jobs;
  34. static struct work _ssm_cur_job_work;
  35. static uint64_t _ssm_jobid;
  36. struct stratumsrv_conn {
  37. struct bufferevent *bev;
  38. uint32_t xnonce1_le;
  39. struct timeval tv_hashes_done;
  40. struct stratumsrv_conn *next;
  41. };
  42. static struct stratumsrv_conn *_ssm_connections;
  43. static
  44. void _ssm_gen_dummy_work(struct work *work, struct stratumsrv_job *ssj, const char * const extranonce2, uint32_t xnonce1)
  45. {
  46. uint8_t *p, *s;
  47. *work = (struct work){
  48. .pool = ssj->pool,
  49. .work_restart_id = ssj->work_restart_id,
  50. .tv_staged = ssj->tv_prepared,
  51. };
  52. bytes_resize(&work->nonce2, ssj->n2size);
  53. s = bytes_buf(&work->nonce2);
  54. p = &s[ssj->n2size - _ssm_client_xnonce2sz];
  55. if (extranonce2)
  56. hex2bin(p, extranonce2, _ssm_client_xnonce2sz);
  57. #ifndef __OPTIMIZE__
  58. else
  59. memset(p, '\0', _ssm_client_xnonce2sz);
  60. #endif
  61. p -= _ssm_client_octets;
  62. memcpy(p, &xnonce1, _ssm_client_octets);
  63. if (p != s)
  64. memset(s, '\xbb', p - s);
  65. gen_stratum_work2(work, &ssj->swork, ssj->nonce1);
  66. }
  67. static
  68. bool stratumsrv_update_notify_str(struct pool * const pool, bool clean)
  69. {
  70. cg_rlock(&pool->data_lock);
  71. struct stratumsrv_conn *conn;
  72. const struct stratum_work * const swork = &pool->swork;
  73. const int n2size = pool->n2size;
  74. char my_job_id[33];
  75. int i;
  76. struct stratumsrv_job *ssj;
  77. ssize_t n2pad = n2size - _ssm_client_octets - _ssm_client_xnonce2sz;
  78. if (n2pad < 0)
  79. return false;
  80. size_t coinb1in_lenx = swork->nonce2_offset * 2;
  81. size_t n2padx = n2pad * 2;
  82. size_t coinb1_lenx = coinb1in_lenx + n2padx;
  83. size_t coinb2_len = bytes_len(&swork->coinbase) - swork->nonce2_offset - n2size;
  84. size_t coinb2_lenx = coinb2_len * 2;
  85. sprintf(my_job_id, "%"PRIx64"-%"PRIx64, (uint64_t)time(NULL), _ssm_jobid++);
  86. size_t bufsz = 166 + strlen(my_job_id) + coinb1_lenx + coinb2_lenx + (swork->merkles * 67);
  87. char * const buf = malloc(bufsz);
  88. char *p = buf;
  89. char prevhash[65], coinb1[coinb1_lenx + 1], coinb2[coinb2_lenx], version[9], nbits[9], ntime[9];
  90. uint32_t ntime_n;
  91. bin2hex(prevhash, &swork->header1[4], 32);
  92. bin2hex(coinb1, bytes_buf(&swork->coinbase), swork->nonce2_offset);
  93. memset(&coinb1[coinb1in_lenx], 'B', n2padx);
  94. coinb1[coinb1_lenx] = '\0';
  95. bin2hex(coinb2, &bytes_buf(&swork->coinbase)[swork->nonce2_offset + n2size], coinb2_len);
  96. p += sprintf(p, "{\"params\":[\"%s\",\"%s\",\"%s\",\"%s\",[", my_job_id, prevhash, coinb1, coinb2);
  97. for (i = 0; i < swork->merkles; ++i)
  98. {
  99. if (i)
  100. *p++ = ',';
  101. *p++ = '"';
  102. bin2hex(p, &bytes_buf(&swork->merkle_bin)[i * 32], 32);
  103. p += 64;
  104. *p++ = '"';
  105. }
  106. bin2hex(version, swork->header1, 4);
  107. bin2hex(nbits, swork->diffbits, 4);
  108. ntime_n = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  109. bin2hex(ntime, &ntime_n, 4);
  110. p += sprintf(p, "],\"%s\",\"%s\",\"%s\",%s],\"method\":\"mining.notify\",\"id\":null}\n", version, nbits, ntime, clean ? "true" : "false");
  111. ssj = malloc(sizeof(*ssj));
  112. *ssj = (struct stratumsrv_job){
  113. .my_job_id = strdup(my_job_id),
  114. .pool = pool,
  115. .work_restart_id = pool->work_restart_id,
  116. .n2size = n2size,
  117. .nonce1 = strdup(pool->nonce1),
  118. };
  119. timer_set_now(&ssj->tv_prepared);
  120. stratum_work_cpy(&ssj->swork, swork);
  121. cg_runlock(&pool->data_lock);
  122. ssj->swork.data_lock_p = NULL;
  123. HASH_ADD_KEYPTR(hh, _ssm_jobs, ssj->my_job_id, strlen(ssj->my_job_id), ssj);
  124. _ssm_gen_dummy_work(&_ssm_cur_job_work, ssj, NULL, 0);
  125. _ssm_notify_sz = p - buf;
  126. assert(_ssm_notify_sz <= bufsz);
  127. _ssm_notify = buf;
  128. LL_FOREACH(_ssm_connections, conn)
  129. {
  130. if (unlikely(!conn->xnonce1_le))
  131. continue;
  132. bufferevent_write(conn->bev, _ssm_notify, _ssm_notify_sz);
  133. }
  134. return true;
  135. }
  136. static
  137. void _ssj_free(struct stratumsrv_job * const ssj)
  138. {
  139. free(ssj->my_job_id);
  140. stratum_work_clean(&ssj->swork);
  141. free(ssj->nonce1);
  142. free(ssj);
  143. }
  144. static
  145. void stratumsrv_job_pruner()
  146. {
  147. struct stratumsrv_job *ssj, *tmp_ssj;
  148. struct timeval tv_now;
  149. timer_set_now(&tv_now);
  150. HASH_ITER(hh, _ssm_jobs, ssj, tmp_ssj)
  151. {
  152. if (timer_elapsed(&ssj->tv_prepared, &tv_now) <= opt_expiry)
  153. break;
  154. HASH_DEL(_ssm_jobs, ssj);
  155. applog(LOG_DEBUG, "SSM: Pruning job_id %s", ssj->my_job_id);
  156. _ssj_free(ssj);
  157. }
  158. }
  159. static void stratumsrv_client_close(struct stratumsrv_conn *);
  160. static
  161. void stratumsrv_conn_close_completion_cb(struct bufferevent *bev, void *p)
  162. {
  163. struct evbuffer * const output = bufferevent_get_output(bev);
  164. if (evbuffer_get_length(output))
  165. // Still have more data to write...
  166. return;
  167. stratumsrv_client_close(p);
  168. }
  169. static void stratumsrv_event(struct bufferevent *, short, void *);
  170. static
  171. void stratumsrv_boot(struct stratumsrv_conn * const conn, const char * const msg)
  172. {
  173. struct bufferevent * const bev = conn->bev;
  174. char buf[58 + strlen(msg)];
  175. int bufsz = sprintf(buf, "{\"params\":[\"%s\"],\"method\":\"client.show_message\",\"id\":null}\n", msg);
  176. bufferevent_write(bev, buf, bufsz);
  177. bufferevent_setcb(bev, NULL, stratumsrv_conn_close_completion_cb, stratumsrv_event, conn);
  178. }
  179. static
  180. void stratumsrv_boot_all_subscribed(const char * const msg)
  181. {
  182. struct stratumsrv_conn *conn, *tmp_conn;
  183. _ssm_notify = NULL;
  184. // Boot all connections
  185. LL_FOREACH_SAFE(_ssm_connections, conn, tmp_conn)
  186. {
  187. if (!conn->xnonce1_le)
  188. continue;
  189. stratumsrv_boot(conn, msg);
  190. }
  191. }
  192. static
  193. void _stratumsrv_update_notify(evutil_socket_t fd, short what, __maybe_unused void *p)
  194. {
  195. struct pool *pool = current_pool();
  196. bool clean;
  197. if (fd == _ssm_update_notifier[0])
  198. {
  199. evtimer_del(ev_notify);
  200. notifier_read(_ssm_update_notifier);
  201. applog(LOG_DEBUG, "SSM: Update triggered by notifier");
  202. }
  203. clean = _ssm_cur_job_work.pool ? stale_work(&_ssm_cur_job_work, true) : true;
  204. if (clean)
  205. {
  206. struct stratumsrv_job *ssj, *tmp;
  207. applog(LOG_DEBUG, "SSM: Current replacing job stale, pruning all jobs");
  208. HASH_ITER(hh, _ssm_jobs, ssj, tmp)
  209. {
  210. HASH_DEL(_ssm_jobs, ssj);
  211. _ssj_free(ssj);
  212. }
  213. }
  214. else
  215. stratumsrv_job_pruner();
  216. if (!pool->stratum_notify)
  217. {
  218. applog(LOG_WARNING, "SSM: Not using a stratum server upstream!");
  219. if (clean)
  220. stratumsrv_boot_all_subscribed("Current upstream pool does not have active stratum");
  221. goto out;
  222. }
  223. if (!stratumsrv_update_notify_str(pool, clean))
  224. {
  225. applog(LOG_WARNING, "SSM: Failed to subdivide upstream stratum notify!");
  226. if (clean)
  227. stratumsrv_boot_all_subscribed("Current upstream pool does not have active stratum");
  228. }
  229. out: ;
  230. struct timeval tv_scantime = {
  231. .tv_sec = opt_scantime,
  232. };
  233. evtimer_add(ev_notify, &tv_scantime);
  234. }
  235. static struct proxy_client *_stratumsrv_find_or_create_client(const char *);
  236. static
  237. struct proxy_client *(*stratumsrv_find_or_create_client)(const char *) = _stratumsrv_find_or_create_client;
  238. static
  239. struct proxy_client *_stratumsrv_find_or_create_client(const char *user)
  240. {
  241. struct proxy_client * const client = proxy_find_or_create_client(user);
  242. struct cgpu_info *cgpu;
  243. struct thr_info *thr;
  244. if (!client)
  245. return NULL;
  246. cgpu = client->cgpu;
  247. thr = cgpu->thr[0];
  248. memcpy(thr->work_restart_notifier, _ssm_update_notifier, sizeof(thr->work_restart_notifier));
  249. stratumsrv_find_or_create_client = proxy_find_or_create_client;
  250. return client;
  251. }
  252. static
  253. void _stratumsrv_failure(struct bufferevent * const bev, const char * const idstr, const int e, const char * const emsg)
  254. {
  255. if (!idstr)
  256. return;
  257. char buf[0x100];
  258. size_t bufsz = snprintf(buf, sizeof(buf), "{\"error\":[%d,\"%s\",null],\"id\":%s,\"result\":null}\n", e, emsg, idstr);
  259. bufferevent_write(bev, buf, bufsz);
  260. }
  261. #define return_stratumsrv_failure(e, emsg) do{ \
  262. _stratumsrv_failure(bev, idstr, e, emsg); \
  263. return; \
  264. }while(0)
  265. static
  266. void _stratumsrv_success(struct bufferevent * const bev, const char * const idstr)
  267. {
  268. if (!idstr)
  269. return;
  270. size_t bufsz = 36 + strlen(idstr);
  271. char buf[bufsz];
  272. bufsz = sprintf(buf, "{\"result\":true,\"id\":%s,\"error\":null}\n", idstr);
  273. bufferevent_write(bev, buf, bufsz);
  274. }
  275. static
  276. void stratumsrv_mining_subscribe(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  277. {
  278. char buf[90 + strlen(idstr) + (_ssm_client_octets * 2 * 2) + 0x10];
  279. char xnonce1x[(_ssm_client_octets * 2) + 1];
  280. int bufsz;
  281. if (!_ssm_notify)
  282. {
  283. evtimer_del(ev_notify);
  284. _stratumsrv_update_notify(-1, 0, NULL);
  285. if (!_ssm_notify)
  286. return_stratumsrv_failure(20, "No notify set (upstream not stratum?)");
  287. }
  288. if (!*xnonce1_p)
  289. {
  290. uint32_t xnonce1;
  291. for (xnonce1 = MAX_CLIENTS; _ssm_xnonce1s[xnonce1]; --xnonce1)
  292. if (!xnonce1)
  293. return_stratumsrv_failure(20, "Maximum clients already connected");
  294. *xnonce1_p = htole32(xnonce1);
  295. }
  296. bin2hex(xnonce1x, xnonce1_p, _ssm_client_octets);
  297. bufsz = sprintf(buf, "{\"id\":%s,\"result\":[[[\"mining.set_difficulty\",\"x\"],[\"mining.notify\",\"%s\"]],\"%s\",%d],\"error\":null}\n", idstr, xnonce1x, xnonce1x, _ssm_client_xnonce2sz);
  298. bufferevent_write(bev, buf, bufsz);
  299. bufferevent_write(bev, "{\"params\":[0.9999847412109375],\"id\":null,\"method\":\"mining.set_difficulty\"}\n", 75);
  300. bufferevent_write(bev, _ssm_notify, _ssm_notify_sz);
  301. }
  302. static
  303. void stratumsrv_mining_authorize(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  304. {
  305. struct proxy_client * const client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  306. if (unlikely(!client))
  307. return_stratumsrv_failure(20, "Failed creating new cgpu");
  308. _stratumsrv_success(bev, idstr);
  309. }
  310. static
  311. void stratumsrv_mining_submit(struct bufferevent *bev, json_t *params, const char *idstr, struct stratumsrv_conn * const conn)
  312. {
  313. uint32_t * const xnonce1_p = &conn->xnonce1_le;
  314. struct work _work, *work;
  315. struct stratumsrv_job *ssj;
  316. struct proxy_client *client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  317. struct cgpu_info *cgpu;
  318. struct thr_info *thr;
  319. const char * const job_id = __json_array_string(params, 1);
  320. const char * const extranonce2 = __json_array_string(params, 2);
  321. const char * const ntime = __json_array_string(params, 3);
  322. const char * const nonce = __json_array_string(params, 4);
  323. uint32_t nonce_n;
  324. if (unlikely(!client))
  325. return_stratumsrv_failure(20, "Failed creating new cgpu");
  326. if (unlikely(!(job_id && extranonce2 && ntime && nonce)))
  327. return_stratumsrv_failure(20, "Couldn't understand parameters");
  328. if (unlikely(strlen(nonce) < 8))
  329. return_stratumsrv_failure(20, "nonce too short");
  330. if (unlikely(strlen(ntime) < 8))
  331. return_stratumsrv_failure(20, "ntime too short");
  332. if (unlikely(strlen(extranonce2) < _ssm_client_xnonce2sz * 2))
  333. return_stratumsrv_failure(20, "extranonce2 too short");
  334. cgpu = client->cgpu;
  335. thr = cgpu->thr[0];
  336. // Lookup job_id
  337. HASH_FIND_STR(_ssm_jobs, job_id, ssj);
  338. if (!ssj)
  339. return_stratumsrv_failure(21, "Job not found");
  340. // Generate dummy work
  341. work = &_work;
  342. _ssm_gen_dummy_work(work, ssj, extranonce2, *xnonce1_p);
  343. // Submit nonce
  344. hex2bin(&work->data[68], ntime, 4);
  345. hex2bin((void*)&nonce_n, nonce, 4);
  346. nonce_n = le32toh(nonce_n);
  347. if (!submit_nonce(thr, work, nonce_n))
  348. _stratumsrv_failure(bev, idstr, 23, "H-not-zero");
  349. else
  350. if (stale_work(work, true))
  351. _stratumsrv_failure(bev, idstr, 21, "stale");
  352. else
  353. _stratumsrv_success(bev, idstr);
  354. clean_work(work);
  355. {
  356. struct timeval tv_now, tv_delta;
  357. timer_set_now(&tv_now);
  358. timersub(&tv_now, &conn->tv_hashes_done, &tv_delta);
  359. conn->tv_hashes_done = tv_now;
  360. hashes_done(thr, 0x100000000, &tv_delta, NULL);
  361. }
  362. }
  363. static
  364. bool stratumsrv_process_line(struct bufferevent * const bev, const char * const ln, void * const p)
  365. {
  366. struct stratumsrv_conn *conn = p;
  367. json_error_t jerr;
  368. json_t *json, *params, *j2;
  369. const char *method;
  370. char *idstr;
  371. json = JSON_LOADS(ln, &jerr);
  372. if (!json)
  373. {
  374. applog(LOG_ERR, "SSM: JSON parse error: %s", ln);
  375. return false;
  376. }
  377. method = bfg_json_obj_string(json, "method", NULL);
  378. if (!method)
  379. {
  380. applog(LOG_ERR, "SSM: JSON missing method: %s", ln);
  381. return false;
  382. }
  383. params = json_object_get(json, "params");
  384. if (!params)
  385. {
  386. applog(LOG_ERR, "SSM: JSON missing params: %s", ln);
  387. return false;
  388. }
  389. applog(LOG_DEBUG, "SSM: RECV: %s", ln);
  390. j2 = json_object_get(json, "id");
  391. idstr = (j2 && !json_is_null(j2)) ? json_dumps_ANY(j2, 0) : NULL;
  392. if (!strcasecmp(method, "mining.submit"))
  393. stratumsrv_mining_submit(bev, params, idstr, conn);
  394. else
  395. if (!strcasecmp(method, "mining.authorize"))
  396. stratumsrv_mining_authorize(bev, params, idstr, &conn->xnonce1_le);
  397. else
  398. if (!strcasecmp(method, "mining.subscribe"))
  399. stratumsrv_mining_subscribe(bev, params, idstr, &conn->xnonce1_le);
  400. else
  401. _stratumsrv_failure(bev, idstr, -3, "Method not supported");
  402. free(idstr);
  403. return true;
  404. }
  405. static
  406. void stratumsrv_client_close(struct stratumsrv_conn * const conn)
  407. {
  408. struct bufferevent * const bev = conn->bev;
  409. bufferevent_free(bev);
  410. LL_DELETE(_ssm_connections, conn);
  411. free(conn);
  412. }
  413. static
  414. void stratumsrv_read(struct bufferevent *bev, void *p)
  415. {
  416. struct evbuffer *input = bufferevent_get_input(bev);
  417. char *ln;
  418. bool rv;
  419. while ( (ln = evbuffer_readln(input, NULL, EVBUFFER_EOL_ANY)) )
  420. {
  421. rv = stratumsrv_process_line(bev, ln, p);
  422. free(ln);
  423. if (unlikely(!rv))
  424. {
  425. stratumsrv_client_close(p);
  426. break;
  427. }
  428. }
  429. }
  430. static
  431. void stratumsrv_event(struct bufferevent *bev, short events, void *p)
  432. {
  433. if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
  434. {
  435. if (events & BEV_EVENT_ERROR)
  436. applog(LOG_ERR, "Error from bufferevent");
  437. if (events & BEV_EVENT_EOF)
  438. applog(LOG_DEBUG, "EOF from bufferevent");
  439. stratumsrv_client_close(p);
  440. }
  441. }
  442. static
  443. void stratumlistener(struct evconnlistener *listener, evutil_socket_t sock, struct sockaddr *addr, int len, void *p)
  444. {
  445. struct stratumsrv_conn *conn;
  446. struct event_base *evbase = evconnlistener_get_base(listener);
  447. struct bufferevent *bev = bufferevent_socket_new(evbase, sock, BEV_OPT_CLOSE_ON_FREE);
  448. conn = malloc(sizeof(*conn));
  449. *conn = (struct stratumsrv_conn){
  450. .bev = bev,
  451. };
  452. LL_PREPEND(_ssm_connections, conn);
  453. bufferevent_setcb(bev, stratumsrv_read, NULL, stratumsrv_event, conn);
  454. bufferevent_enable(bev, EV_READ | EV_WRITE);
  455. }
  456. void *stratumsrv_thread(__maybe_unused void *p)
  457. {
  458. pthread_detach(pthread_self());
  459. RenameThread("stratumsrv");
  460. for (uint64_t n = MAX_CLIENTS; n; n >>= 8)
  461. ++_ssm_client_octets;
  462. _ssm_client_xnonce2sz = 2;
  463. struct event_base *evbase = event_base_new();
  464. {
  465. ev_notify = evtimer_new(evbase, _stratumsrv_update_notify, NULL);
  466. _stratumsrv_update_notify(-1, 0, NULL);
  467. }
  468. {
  469. notifier_init(_ssm_update_notifier);
  470. struct event *ev_update_notifier = event_new(evbase, _ssm_update_notifier[0], EV_READ | EV_PERSIST, _stratumsrv_update_notify, NULL);
  471. event_add(ev_update_notifier, NULL);
  472. }
  473. {
  474. struct sockaddr_in sin = {
  475. .sin_family = AF_INET,
  476. .sin_addr.s_addr = INADDR_ANY,
  477. .sin_port = htons(3334),
  478. };
  479. evconnlistener_new_bind(evbase, stratumlistener, NULL, (
  480. LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE
  481. ), 0x10, (void*)&sin, sizeof(sin));
  482. }
  483. event_base_dispatch(evbase);
  484. return NULL;
  485. }