driver-stratum.c 20 KB

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