driver-stratum.c 26 KB

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