driver-stratum.c 25 KB

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