driver-stratum.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /*
  2. * Copyright 2013 Luke Dashjr
  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 3 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. #include "config.h"
  10. #ifndef WIN32
  11. #include <arpa/inet.h>
  12. #else
  13. #include <winsock2.h>
  14. #endif
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <string.h>
  18. #include <event2/buffer.h>
  19. #include <event2/bufferevent.h>
  20. #include <event2/event.h>
  21. #include <event2/listener.h>
  22. #include <jansson.h>
  23. #include "deviceapi.h"
  24. #include "driver-proxy.h"
  25. #include "miner.h"
  26. #include "util.h"
  27. #include "work2d.h"
  28. #define _ssm_client_octets work2d_xnonce1sz
  29. #define _ssm_client_xnonce2sz work2d_xnonce2sz
  30. static char *_ssm_notify;
  31. static int _ssm_notify_sz;
  32. static struct stratumsrv_job *_ssm_last_ssj;
  33. static struct event *ev_notify;
  34. static notifier_t _ssm_update_notifier;
  35. struct stratumsrv_job {
  36. char *my_job_id;
  37. struct timeval tv_prepared;
  38. struct stratum_work swork;
  39. float job_pdiff[WORK2D_MAX_DIVISIONS+1];
  40. UT_hash_handle hh;
  41. };
  42. static struct stratumsrv_job *_ssm_jobs;
  43. static struct work _ssm_cur_job_work;
  44. static uint64_t _ssm_jobid;
  45. static struct event_base *_smm_evbase;
  46. static bool _smm_running;
  47. static struct evconnlistener *_smm_listener;
  48. struct stratumsrv_conn {
  49. struct bufferevent *bev;
  50. uint32_t xnonce1_le;
  51. struct timeval tv_hashes_done;
  52. bool hashes_done_ext;
  53. float current_share_pdiff;
  54. float desired_share_pdiff;
  55. bool have_authorised_user;
  56. struct stratumsrv_conn *next;
  57. };
  58. static struct stratumsrv_conn *_ssm_connections;
  59. static
  60. void stratumsrv_send_set_difficulty(struct stratumsrv_conn * const conn, const float share_pdiff)
  61. {
  62. struct bufferevent * const bev = conn->bev;
  63. char buf[0x100];
  64. const double bdiff = pdiff_to_bdiff(share_pdiff);
  65. conn->current_share_pdiff = share_pdiff;
  66. const int prec = double_find_precision(bdiff, 10.);
  67. const size_t bufsz = snprintf(buf, sizeof(buf), "{\"params\":[%.*f],\"id\":null,\"method\":\"mining.set_difficulty\"}\n", prec, bdiff);
  68. bufferevent_write(bev, buf, bufsz);
  69. }
  70. #define _ssm_gen_dummy_work work2d_gen_dummy_work
  71. static
  72. bool stratumsrv_update_notify_str(struct pool * const pool, bool clean)
  73. {
  74. cg_rlock(&pool->data_lock);
  75. struct stratumsrv_conn *conn;
  76. const struct stratum_work * const swork = &pool->swork;
  77. const int n2size = pool->swork.n2size;
  78. char my_job_id[33];
  79. int i;
  80. struct stratumsrv_job *ssj;
  81. ssize_t n2pad = work2d_pad_xnonce_size(swork);
  82. if (n2pad < 0)
  83. return false;
  84. size_t coinb1in_lenx = swork->nonce2_offset * 2;
  85. size_t n2padx = n2pad * 2;
  86. size_t coinb1_lenx = coinb1in_lenx + n2padx;
  87. size_t coinb2_len = bytes_len(&swork->coinbase) - swork->nonce2_offset - n2size;
  88. size_t coinb2_lenx = coinb2_len * 2;
  89. sprintf(my_job_id, "%"PRIx64"-%"PRIx64, (uint64_t)time(NULL), _ssm_jobid++);
  90. size_t bufsz = 166 + strlen(my_job_id) + coinb1_lenx + coinb2_lenx + (swork->merkles * 67);
  91. char * const buf = malloc(bufsz);
  92. char *p = buf;
  93. char prevhash[65], coinb1[coinb1_lenx + 1], coinb2[coinb2_lenx], version[9], nbits[9], ntime[9];
  94. uint32_t ntime_n;
  95. bin2hex(prevhash, &swork->header1[4], 32);
  96. bin2hex(coinb1, bytes_buf(&swork->coinbase), swork->nonce2_offset);
  97. work2d_pad_xnonce(&coinb1[coinb1in_lenx], swork, true);
  98. coinb1[coinb1_lenx] = '\0';
  99. bin2hex(coinb2, &bytes_buf(&swork->coinbase)[swork->nonce2_offset + n2size], coinb2_len);
  100. p += sprintf(p, "{\"params\":[\"%s\",\"%s\",\"%s\",\"%s\",[", my_job_id, prevhash, coinb1, coinb2);
  101. for (i = 0; i < swork->merkles; ++i)
  102. {
  103. if (i)
  104. *p++ = ',';
  105. *p++ = '"';
  106. bin2hex(p, &bytes_buf(&swork->merkle_bin)[i * 32], 32);
  107. p += 64;
  108. *p++ = '"';
  109. }
  110. bin2hex(version, swork->header1, 4);
  111. bin2hex(nbits, swork->diffbits, 4);
  112. ntime_n = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  113. bin2hex(ntime, &ntime_n, 4);
  114. p += sprintf(p, "],\"%s\",\"%s\",\"%s\",%s],\"method\":\"mining.notify\",\"id\":null}\n", version, nbits, ntime, clean ? "true" : "false");
  115. ssj = malloc(sizeof(*ssj));
  116. *ssj = (struct stratumsrv_job){
  117. .my_job_id = strdup(my_job_id),
  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. if (likely(_ssm_cur_job_work.pool))
  125. clean_work(&_ssm_cur_job_work);
  126. _ssm_gen_dummy_work(&_ssm_cur_job_work, &ssj->swork, &ssj->tv_prepared, NULL, 0);
  127. _ssm_notify_sz = p - buf;
  128. assert(_ssm_notify_sz <= bufsz);
  129. free(_ssm_notify);
  130. _ssm_notify = buf;
  131. _ssm_last_ssj = ssj;
  132. float pdiff = target_diff(ssj->swork.target);
  133. LL_FOREACH(_ssm_connections, conn)
  134. {
  135. if (unlikely(!conn->xnonce1_le))
  136. continue;
  137. float conn_pdiff = conn->desired_share_pdiff;
  138. if (pdiff < conn_pdiff)
  139. conn_pdiff = pdiff;
  140. ssj->job_pdiff[conn->xnonce1_le] = conn_pdiff;
  141. if (conn_pdiff != conn->current_share_pdiff)
  142. stratumsrv_send_set_difficulty(conn, conn_pdiff);
  143. bufferevent_write(conn->bev, _ssm_notify, _ssm_notify_sz);
  144. }
  145. return true;
  146. }
  147. static
  148. void _ssj_free(struct stratumsrv_job * const ssj)
  149. {
  150. free(ssj->my_job_id);
  151. stratum_work_clean(&ssj->swork);
  152. free(ssj);
  153. }
  154. static
  155. void stratumsrv_job_pruner()
  156. {
  157. struct stratumsrv_job *ssj, *tmp_ssj;
  158. struct timeval tv_now;
  159. timer_set_now(&tv_now);
  160. HASH_ITER(hh, _ssm_jobs, ssj, tmp_ssj)
  161. {
  162. if (timer_elapsed(&ssj->tv_prepared, &tv_now) <= opt_expiry)
  163. break;
  164. HASH_DEL(_ssm_jobs, ssj);
  165. applog(LOG_DEBUG, "SSM: Pruning job_id %s", ssj->my_job_id);
  166. _ssj_free(ssj);
  167. }
  168. }
  169. static void stratumsrv_client_close(struct stratumsrv_conn *);
  170. static
  171. void stratumsrv_conn_close_completion_cb(struct bufferevent *bev, void *p)
  172. {
  173. struct evbuffer * const output = bufferevent_get_output(bev);
  174. if (evbuffer_get_length(output))
  175. // Still have more data to write...
  176. return;
  177. stratumsrv_client_close(p);
  178. }
  179. static void stratumsrv_event(struct bufferevent *, short, void *);
  180. static
  181. void stratumsrv_boot(struct stratumsrv_conn * const conn, const char * const msg)
  182. {
  183. struct bufferevent * const bev = conn->bev;
  184. char buf[58 + strlen(msg)];
  185. int bufsz = sprintf(buf, "{\"params\":[\"%s\"],\"method\":\"client.show_message\",\"id\":null}\n", msg);
  186. bufferevent_write(bev, buf, bufsz);
  187. bufferevent_setcb(bev, NULL, stratumsrv_conn_close_completion_cb, stratumsrv_event, conn);
  188. }
  189. static
  190. void stratumsrv_boot_all_subscribed(const char * const msg)
  191. {
  192. struct stratumsrv_conn *conn, *tmp_conn;
  193. free(_ssm_notify);
  194. _ssm_notify = NULL;
  195. _ssm_last_ssj = NULL;
  196. // Boot all connections
  197. LL_FOREACH_SAFE(_ssm_connections, conn, tmp_conn)
  198. {
  199. if (!conn->xnonce1_le)
  200. continue;
  201. stratumsrv_boot(conn, msg);
  202. }
  203. }
  204. static
  205. void _stratumsrv_update_notify(evutil_socket_t fd, short what, __maybe_unused void *p)
  206. {
  207. struct pool *pool = current_pool();
  208. bool clean;
  209. if (fd == _ssm_update_notifier[0])
  210. {
  211. evtimer_del(ev_notify);
  212. notifier_read(_ssm_update_notifier);
  213. applog(LOG_DEBUG, "SSM: Update triggered by notifier");
  214. }
  215. clean = _ssm_cur_job_work.pool ? stale_work(&_ssm_cur_job_work, true) : true;
  216. if (clean)
  217. {
  218. struct stratumsrv_job *ssj, *tmp;
  219. applog(LOG_DEBUG, "SSM: Current replacing job stale, pruning all jobs");
  220. HASH_ITER(hh, _ssm_jobs, ssj, tmp)
  221. {
  222. HASH_DEL(_ssm_jobs, ssj);
  223. _ssj_free(ssj);
  224. }
  225. }
  226. else
  227. stratumsrv_job_pruner();
  228. if (!pool_has_usable_swork(pool))
  229. {
  230. applog(LOG_WARNING, "SSM: No usable 2D work upstream!");
  231. if (clean)
  232. stratumsrv_boot_all_subscribed("Current upstream pool does not have usable 2D work");
  233. goto out;
  234. }
  235. if (!stratumsrv_update_notify_str(pool, clean))
  236. {
  237. applog(LOG_WARNING, "SSM: Failed to subdivide upstream stratum notify!");
  238. if (clean)
  239. stratumsrv_boot_all_subscribed("Current upstream pool does not have active stratum");
  240. }
  241. out: ;
  242. struct timeval tv_scantime = {
  243. .tv_sec = opt_scantime,
  244. };
  245. evtimer_add(ev_notify, &tv_scantime);
  246. }
  247. static struct proxy_client *_stratumsrv_find_or_create_client(const char *);
  248. static
  249. struct proxy_client *(*stratumsrv_find_or_create_client)(const char *) = _stratumsrv_find_or_create_client;
  250. static
  251. struct proxy_client *_stratumsrv_find_or_create_client(const char *user)
  252. {
  253. struct proxy_client * const client = proxy_find_or_create_client(user);
  254. struct cgpu_info *cgpu;
  255. struct thr_info *thr;
  256. if (!client)
  257. return NULL;
  258. cgpu = client->cgpu;
  259. thr = cgpu->thr[0];
  260. memcpy(thr->work_restart_notifier, _ssm_update_notifier, sizeof(thr->work_restart_notifier));
  261. stratumsrv_find_or_create_client = proxy_find_or_create_client;
  262. return client;
  263. }
  264. static
  265. void _stratumsrv_failure(struct bufferevent * const bev, const char * const idstr, const int e, const char * const emsg)
  266. {
  267. if (!idstr)
  268. return;
  269. char buf[0x100];
  270. size_t bufsz = snprintf(buf, sizeof(buf), "{\"error\":[%d,\"%s\",null],\"id\":%s,\"result\":null}\n", e, emsg, idstr);
  271. bufferevent_write(bev, buf, bufsz);
  272. }
  273. #define return_stratumsrv_failure(e, emsg) do{ \
  274. _stratumsrv_failure(bev, idstr, e, emsg); \
  275. return; \
  276. }while(0)
  277. static
  278. void _stratumsrv_success(struct bufferevent * const bev, const char * const idstr)
  279. {
  280. if (!idstr)
  281. return;
  282. size_t bufsz = 36 + strlen(idstr);
  283. char buf[bufsz];
  284. bufsz = sprintf(buf, "{\"result\":true,\"id\":%s,\"error\":null}\n", idstr);
  285. bufferevent_write(bev, buf, bufsz);
  286. }
  287. static
  288. void stratumsrv_mining_subscribe(struct bufferevent * const bev, json_t * const params, const char * const idstr, struct stratumsrv_conn * const conn)
  289. {
  290. uint32_t * const xnonce1_p = &conn->xnonce1_le;
  291. char buf[90 + strlen(idstr) + (_ssm_client_octets * 2 * 2) + 0x10];
  292. char xnonce1x[(_ssm_client_octets * 2) + 1];
  293. int bufsz;
  294. if (!_ssm_notify)
  295. {
  296. evtimer_del(ev_notify);
  297. _stratumsrv_update_notify(-1, 0, NULL);
  298. if (!_ssm_notify)
  299. return_stratumsrv_failure(20, "No notify set (upstream not stratum?)");
  300. }
  301. if (!*xnonce1_p)
  302. {
  303. if (!reserve_work2d_(xnonce1_p))
  304. return_stratumsrv_failure(20, "Maximum clients already connected");
  305. }
  306. bin2hex(xnonce1x, xnonce1_p, _ssm_client_octets);
  307. bufsz = sprintf(buf, "{\"id\":%s,\"result\":[[[\"mining.set_difficulty\",\"x\"],[\"mining.notify\",\"%s\"]],\"%s\",%d],\"error\":null}\n", idstr, xnonce1x, xnonce1x, _ssm_client_xnonce2sz);
  308. bufferevent_write(bev, buf, bufsz);
  309. float pdiff = target_diff(_ssm_last_ssj->swork.target);
  310. if (pdiff > conn->desired_share_pdiff)
  311. pdiff = conn->desired_share_pdiff;
  312. _ssm_last_ssj->job_pdiff[*xnonce1_p] = pdiff;
  313. stratumsrv_send_set_difficulty(conn, pdiff);
  314. bufferevent_write(bev, _ssm_notify, _ssm_notify_sz);
  315. }
  316. static
  317. void stratumsrv_mining_authorize(struct bufferevent * const bev, json_t * const params, const char * const idstr, struct stratumsrv_conn * const conn)
  318. {
  319. struct proxy_client * const client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  320. if (unlikely(!client))
  321. return_stratumsrv_failure(20, "Failed creating new cgpu");
  322. if ((!conn->have_authorised_user) || client->desired_share_pdiff < conn->desired_share_pdiff)
  323. conn->desired_share_pdiff = client->desired_share_pdiff;
  324. conn->have_authorised_user = true;
  325. _stratumsrv_success(bev, idstr);
  326. }
  327. static
  328. void stratumsrv_mining_submit(struct bufferevent *bev, json_t *params, const char *idstr, struct stratumsrv_conn * const conn)
  329. {
  330. uint32_t * const xnonce1_p = &conn->xnonce1_le;
  331. struct stratumsrv_job *ssj;
  332. struct proxy_client *client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  333. struct cgpu_info *cgpu;
  334. struct thr_info *thr;
  335. const char * const job_id = __json_array_string(params, 1);
  336. const char * const extranonce2 = __json_array_string(params, 2);
  337. const char * const ntime = __json_array_string(params, 3);
  338. const char * const nonce = __json_array_string(params, 4);
  339. uint8_t xnonce2[work2d_xnonce2sz];
  340. uint32_t ntime_n, nonce_n;
  341. bool is_stale;
  342. if (unlikely(!client))
  343. return_stratumsrv_failure(20, "Failed creating new cgpu");
  344. if (unlikely(!(job_id && extranonce2 && ntime && nonce)))
  345. return_stratumsrv_failure(20, "Couldn't understand parameters");
  346. if (unlikely(strlen(nonce) < 8))
  347. return_stratumsrv_failure(20, "nonce too short");
  348. if (unlikely(strlen(ntime) < 8))
  349. return_stratumsrv_failure(20, "ntime too short");
  350. if (unlikely(strlen(extranonce2) < _ssm_client_xnonce2sz * 2))
  351. return_stratumsrv_failure(20, "extranonce2 too short");
  352. cgpu = client->cgpu;
  353. thr = cgpu->thr[0];
  354. // Lookup job_id
  355. HASH_FIND_STR(_ssm_jobs, job_id, ssj);
  356. if (!ssj)
  357. return_stratumsrv_failure(21, "Job not found");
  358. float nonce_diff = ssj->job_pdiff[*xnonce1_p];
  359. if (unlikely(nonce_diff <= 0))
  360. {
  361. applog(LOG_WARNING, "Unknown share difficulty for SSM job %s", ssj->my_job_id);
  362. nonce_diff = conn->current_share_pdiff;
  363. }
  364. hex2bin(xnonce2, extranonce2, work2d_xnonce2sz);
  365. // Submit nonce
  366. hex2bin((void*)&ntime_n, ntime, 4);
  367. ntime_n = be32toh(ntime_n);
  368. hex2bin((void*)&nonce_n, nonce, 4);
  369. nonce_n = le32toh(nonce_n);
  370. if (!work2d_submit_nonce(thr, &ssj->swork, &ssj->tv_prepared, xnonce2, *xnonce1_p, nonce_n, ntime_n, &is_stale, nonce_diff))
  371. _stratumsrv_failure(bev, idstr, 23, "H-not-zero");
  372. else
  373. if (is_stale)
  374. _stratumsrv_failure(bev, idstr, 21, "stale");
  375. else
  376. _stratumsrv_success(bev, idstr);
  377. if (!conn->hashes_done_ext)
  378. {
  379. struct timeval tv_now, tv_delta;
  380. timer_set_now(&tv_now);
  381. timersub(&tv_now, &conn->tv_hashes_done, &tv_delta);
  382. conn->tv_hashes_done = tv_now;
  383. const uint64_t hashes = (float)0x100000000 * nonce_diff;
  384. hashes_done(thr, hashes, &tv_delta, NULL);
  385. }
  386. }
  387. static
  388. void stratumsrv_mining_hashes_done(struct bufferevent * const bev, json_t * const params, const char * const idstr, struct stratumsrv_conn * const conn)
  389. {
  390. double f;
  391. struct timeval tv_delta;
  392. struct cgpu_info *cgpu;
  393. struct thr_info *thr;
  394. struct proxy_client * const client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  395. json_t *jduration = json_array_get(params, 1);
  396. json_t *jhashcount = json_array_get(params, 2);
  397. if (!(json_is_number(jduration) && json_is_number(jhashcount)))
  398. return_stratumsrv_failure(20, "mining.hashes_done(String username, Number duration-in-seconds, Number hashcount)");
  399. cgpu = client->cgpu;
  400. thr = cgpu->thr[0];
  401. f = json_number_value(jduration);
  402. tv_delta.tv_sec = f;
  403. tv_delta.tv_usec = (f - tv_delta.tv_sec) * 1e6;
  404. f = json_number_value(jhashcount);
  405. hashes_done(thr, f, &tv_delta, NULL);
  406. conn->hashes_done_ext = true;
  407. }
  408. static
  409. bool stratumsrv_process_line(struct bufferevent * const bev, const char * const ln, void * const p)
  410. {
  411. struct stratumsrv_conn *conn = p;
  412. json_error_t jerr;
  413. json_t *json, *params, *j2;
  414. const char *method;
  415. char *idstr;
  416. json = JSON_LOADS(ln, &jerr);
  417. if (!json)
  418. {
  419. if (strncmp(ln, "GET ", 4) && strncmp(ln, "POST ", 5) && ln[0] != '\x16' /* TLS handshake */)
  420. applog(LOG_ERR, "SSM: JSON parse error: %s", ln);
  421. return false;
  422. }
  423. method = bfg_json_obj_string(json, "method", NULL);
  424. if (!method)
  425. {
  426. applog(LOG_ERR, "SSM: JSON missing method: %s", ln);
  427. errout:
  428. json_decref(json);
  429. return false;
  430. }
  431. params = json_object_get(json, "params");
  432. if (!params)
  433. {
  434. applog(LOG_ERR, "SSM: JSON missing params: %s", ln);
  435. goto errout;
  436. }
  437. applog(LOG_DEBUG, "SSM: RECV: %s", ln);
  438. j2 = json_object_get(json, "id");
  439. idstr = (j2 && !json_is_null(j2)) ? json_dumps_ANY(j2, 0) : NULL;
  440. if (!strcasecmp(method, "mining.submit"))
  441. stratumsrv_mining_submit(bev, params, idstr, conn);
  442. else
  443. if (!strcasecmp(method, "mining.hashes_done"))
  444. stratumsrv_mining_hashes_done(bev, params, idstr, conn);
  445. else
  446. if (!strcasecmp(method, "mining.authorize"))
  447. stratumsrv_mining_authorize(bev, params, idstr, conn);
  448. else
  449. if (!strcasecmp(method, "mining.subscribe"))
  450. stratumsrv_mining_subscribe(bev, params, idstr, conn);
  451. else
  452. _stratumsrv_failure(bev, idstr, -3, "Method not supported");
  453. free(idstr);
  454. json_decref(json);
  455. return true;
  456. }
  457. static
  458. void stratumsrv_client_close(struct stratumsrv_conn * const conn)
  459. {
  460. struct bufferevent * const bev = conn->bev;
  461. bufferevent_free(bev);
  462. LL_DELETE(_ssm_connections, conn);
  463. release_work2d_(conn->xnonce1_le);
  464. free(conn);
  465. }
  466. static
  467. void stratumsrv_read(struct bufferevent *bev, void *p)
  468. {
  469. struct evbuffer *input = bufferevent_get_input(bev);
  470. char *ln;
  471. bool rv;
  472. while ( (ln = evbuffer_readln(input, NULL, EVBUFFER_EOL_ANY)) )
  473. {
  474. rv = stratumsrv_process_line(bev, ln, p);
  475. free(ln);
  476. if (unlikely(!rv))
  477. {
  478. stratumsrv_client_close(p);
  479. break;
  480. }
  481. }
  482. }
  483. static
  484. void stratumsrv_event(struct bufferevent *bev, short events, void *p)
  485. {
  486. if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
  487. {
  488. if (events & BEV_EVENT_ERROR)
  489. applog(LOG_ERR, "Error from bufferevent");
  490. if (events & BEV_EVENT_EOF)
  491. applog(LOG_DEBUG, "EOF from bufferevent");
  492. stratumsrv_client_close(p);
  493. }
  494. }
  495. static
  496. const char *stratumsrv_init_diff(struct cgpu_info * const proc, const char * const optname, const char * const newvalue, char * const replybuf, enum bfg_set_device_replytype * const success)
  497. {
  498. struct stratumsrv_conn * const conn = proc->device_data;
  499. const double nv = atof(newvalue);
  500. if (nv <= 0)
  501. return "Invalid difficulty";
  502. conn->desired_share_pdiff = nv;
  503. return NULL;
  504. }
  505. static const struct bfg_set_device_definition stratumsrv_set_device_funcs_newconnect[] = {
  506. {"diff", stratumsrv_init_diff, NULL},
  507. {NULL},
  508. };
  509. static
  510. void stratumlistener(struct evconnlistener *listener, evutil_socket_t sock, struct sockaddr *addr, int len, void *p)
  511. {
  512. struct stratumsrv_conn *conn;
  513. struct event_base *evbase = evconnlistener_get_base(listener);
  514. struct bufferevent *bev = bufferevent_socket_new(evbase, sock, BEV_OPT_CLOSE_ON_FREE);
  515. conn = malloc(sizeof(*conn));
  516. *conn = (struct stratumsrv_conn){
  517. .bev = bev,
  518. .desired_share_pdiff = opt_scrypt ? (1./0x10000) : 1.,
  519. };
  520. drv_set_defaults(&proxy_drv, stratumsrv_set_device_funcs_newconnect, conn, NULL, NULL, 1);
  521. LL_PREPEND(_ssm_connections, conn);
  522. bufferevent_setcb(bev, stratumsrv_read, NULL, stratumsrv_event, conn);
  523. bufferevent_enable(bev, EV_READ | EV_WRITE);
  524. }
  525. void stratumsrv_start();
  526. void stratumsrv_change_port()
  527. {
  528. struct event_base * const evbase = _smm_evbase;
  529. if (_smm_listener)
  530. evconnlistener_free(_smm_listener);
  531. if (!_smm_running)
  532. {
  533. stratumsrv_start();
  534. return;
  535. }
  536. struct sockaddr_in sin = {
  537. .sin_family = AF_INET,
  538. .sin_addr.s_addr = INADDR_ANY,
  539. .sin_port = htons(stratumsrv_port),
  540. };
  541. _smm_listener = evconnlistener_new_bind(evbase, stratumlistener, NULL, (
  542. LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE
  543. ), 0x10, (void*)&sin, sizeof(sin));
  544. // NOTE: libevent doesn't seem to implement LEV_OPT_CLOSE_ON_EXEC for Windows, so we must do this ourselves
  545. set_cloexec_socket(evconnlistener_get_fd(_smm_listener), true);
  546. }
  547. static
  548. void *stratumsrv_thread(__maybe_unused void *p)
  549. {
  550. pthread_detach(pthread_self());
  551. RenameThread("stratumsrv");
  552. work2d_init();
  553. struct event_base *evbase = event_base_new();
  554. _smm_evbase = evbase;
  555. {
  556. ev_notify = evtimer_new(evbase, _stratumsrv_update_notify, NULL);
  557. _stratumsrv_update_notify(-1, 0, NULL);
  558. }
  559. {
  560. notifier_init(_ssm_update_notifier);
  561. struct event *ev_update_notifier = event_new(evbase, _ssm_update_notifier[0], EV_READ | EV_PERSIST, _stratumsrv_update_notify, NULL);
  562. event_add(ev_update_notifier, NULL);
  563. }
  564. stratumsrv_change_port();
  565. event_base_dispatch(evbase);
  566. return NULL;
  567. }
  568. void stratumsrv_start()
  569. {
  570. _smm_running = true;
  571. pthread_t pth;
  572. if (unlikely(pthread_create(&pth, NULL, stratumsrv_thread, NULL)))
  573. quit(1, "stratumsrv thread create failed");
  574. }