driver-stratum.c 26 KB

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