driver-stratum.c 21 KB

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