driver-stratum.c 21 KB

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