driver-stratum.c 14 KB

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