driver-stratum.c 27 KB

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