driver-stratum.c 22 KB

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