driver-stratum.c 23 KB

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