driver-stratum.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. #include "config.h"
  2. #include <stdbool.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <arpa/inet.h>
  6. #include <event2/buffer.h>
  7. #include <event2/bufferevent.h>
  8. #include <event2/event.h>
  9. #include <event2/listener.h>
  10. #include <jansson.h>
  11. #include "deviceapi.h"
  12. #include "driver-proxy.h"
  13. #include "miner.h"
  14. #include "util.h"
  15. #define MAX_CLIENTS 255
  16. static bool _ssm_xnonce1s[MAX_CLIENTS + 1] = { true };
  17. static uint8_t _ssm_client_octets;
  18. static uint8_t _ssm_client_xnonce2sz;
  19. static char *_ssm_notify;
  20. static int _ssm_notify_sz;
  21. static struct event *ev_notify;
  22. static notifier_t _ssm_update_notifier;
  23. struct stratumsrv_job {
  24. char *my_job_id;
  25. struct pool *pool;
  26. uint8_t work_restart_id;
  27. uint8_t n2size;
  28. struct timeval tv_prepared;
  29. struct stratum_work swork;
  30. char *nonce1;
  31. UT_hash_handle hh;
  32. };
  33. static struct stratumsrv_job *_ssm_jobs;
  34. static struct work _ssm_cur_job_work;
  35. static uint64_t _ssm_jobid;
  36. struct stratumsrv_conn {
  37. struct bufferevent *bev;
  38. uint32_t xnonce1_le;
  39. struct stratumsrv_conn *next;
  40. };
  41. static struct stratumsrv_conn *_ssm_connections;
  42. static
  43. void _ssm_gen_dummy_work(struct work *work, struct stratumsrv_job *ssj, const char * const extranonce2, uint32_t xnonce1)
  44. {
  45. uint8_t *p, *s;
  46. *work = (struct work){
  47. .pool = ssj->pool,
  48. .work_restart_id = ssj->work_restart_id,
  49. .tv_staged = ssj->tv_prepared,
  50. };
  51. bytes_resize(&work->nonce2, ssj->n2size);
  52. s = bytes_buf(&work->nonce2);
  53. p = &s[ssj->n2size - _ssm_client_xnonce2sz];
  54. if (extranonce2)
  55. hex2bin(p, extranonce2, _ssm_client_xnonce2sz);
  56. #ifndef __OPTIMIZE__
  57. else
  58. memset(p, '\0', _ssm_client_xnonce2sz);
  59. #endif
  60. p -= _ssm_client_octets;
  61. memcpy(p, &xnonce1, _ssm_client_octets);
  62. if (p != s)
  63. memset(s, '\xbb', p - s);
  64. gen_stratum_work2(work, &ssj->swork, ssj->nonce1);
  65. }
  66. static
  67. void stratumsrv_update_notify_str(struct pool * const pool, bool clean)
  68. {
  69. struct stratumsrv_conn *conn;
  70. const struct stratum_work * const swork = &pool->swork;
  71. const int n2size = pool->n2size;
  72. char my_job_id[17];
  73. int i;
  74. struct stratumsrv_job *ssj;
  75. ssize_t n2pad = n2size - _ssm_client_octets - _ssm_client_xnonce2sz;
  76. if (n2pad < 0)
  77. {}// FIXME
  78. size_t coinb1in_lenx = swork->nonce2_offset * 2;
  79. size_t n2padx = n2pad * 2;
  80. size_t coinb1_lenx = coinb1in_lenx + n2padx;
  81. size_t coinb2_len = bytes_len(&swork->coinbase) - swork->nonce2_offset - n2size;
  82. size_t coinb2_lenx = coinb2_len * 2;
  83. sprintf(my_job_id, "%"PRIx64, _ssm_jobid++);
  84. size_t bufsz = 166 + strlen(my_job_id) + coinb1_lenx + coinb2_lenx + (swork->merkles * 67);
  85. char * const buf = malloc(bufsz);
  86. char *p = buf;
  87. char prevhash[65], coinb1[coinb1_lenx + 1], coinb2[coinb2_lenx], version[9], nbits[9], ntime[9];
  88. uint32_t ntime_n;
  89. bin2hex(prevhash, &swork->header1[4], 32);
  90. bin2hex(coinb1, bytes_buf(&swork->coinbase), swork->nonce2_offset);
  91. memset(&coinb1[coinb1in_lenx], 'B', n2padx);
  92. coinb1[coinb1_lenx] = '\0';
  93. bin2hex(coinb2, &bytes_buf(&swork->coinbase)[swork->nonce2_offset + n2size], coinb2_len);
  94. p += sprintf(p, "{\"params\":[\"%s\",\"%s\",\"%s\",\"%s\",[", my_job_id, prevhash, coinb1, coinb2);
  95. for (i = 0; i < swork->merkles; ++i)
  96. {
  97. if (i)
  98. *p++ = ',';
  99. *p++ = '"';
  100. bin2hex(p, &bytes_buf(&swork->merkle_bin)[i * 32], 32);
  101. p += 64;
  102. *p++ = '"';
  103. }
  104. bin2hex(version, swork->header1, 4);
  105. bin2hex(nbits, swork->diffbits, 4);
  106. ntime_n = htobe32(swork->ntime + timer_elapsed(&swork->tv_received, NULL));
  107. bin2hex(ntime, &ntime_n, 4);
  108. p += sprintf(p, "],\"%s\",\"%s\",\"%s\",%s],\"method\":\"mining.notify\",\"id\":null}\n", version, nbits, ntime, clean ? "true" : "false");
  109. ssj = malloc(sizeof(*ssj));
  110. *ssj = (struct stratumsrv_job){
  111. .my_job_id = strdup(my_job_id),
  112. .pool = pool,
  113. .work_restart_id = pool->work_restart_id,
  114. .n2size = n2size,
  115. .nonce1 = strdup(pool->nonce1),
  116. };
  117. timer_set_now(&ssj->tv_prepared);
  118. stratum_work_cpy(&ssj->swork, swork);
  119. ssj->swork.data_lock_p = NULL;
  120. HASH_ADD_KEYPTR(hh, _ssm_jobs, ssj->my_job_id, strlen(ssj->my_job_id), ssj);
  121. _ssm_gen_dummy_work(&_ssm_cur_job_work, ssj, NULL, 0);
  122. _ssm_notify_sz = p - buf;
  123. assert(_ssm_notify_sz <= bufsz);
  124. _ssm_notify = buf;
  125. LL_FOREACH(_ssm_connections, conn)
  126. {
  127. if (unlikely(!conn->xnonce1_le))
  128. continue;
  129. bufferevent_write(conn->bev, _ssm_notify, _ssm_notify_sz);
  130. }
  131. }
  132. static
  133. void _ssj_free(struct stratumsrv_job * const ssj)
  134. {
  135. free(ssj->my_job_id);
  136. stratum_work_clean(&ssj->swork);
  137. free(ssj->nonce1);
  138. free(ssj);
  139. }
  140. static
  141. void _stratumsrv_update_notify(evutil_socket_t fd, short what, __maybe_unused void *p)
  142. {
  143. struct pool *pool = current_pool();
  144. bool clean;
  145. if (fd == _ssm_update_notifier[0])
  146. {
  147. evtimer_del(ev_notify);
  148. notifier_read(_ssm_update_notifier);
  149. applog(LOG_DEBUG, "SSM: Update triggered by notifier");
  150. }
  151. if (!pool->stratum_notify)
  152. {
  153. applog(LOG_WARNING, "SSM: Not using a stratum server upstream!");
  154. // FIXME
  155. return;
  156. }
  157. clean = _ssm_cur_job_work.pool ? stale_work(&_ssm_cur_job_work, true) : true;
  158. if (clean)
  159. {
  160. struct stratumsrv_job *ssj, *tmp;
  161. applog(LOG_DEBUG, "SSM: Current replacing job stale, pruning all jobs");
  162. HASH_ITER(hh, _ssm_jobs, ssj, tmp)
  163. {
  164. HASH_DEL(_ssm_jobs, ssj);
  165. _ssj_free(ssj);
  166. }
  167. }
  168. stratumsrv_update_notify_str(pool, clean);
  169. struct timeval tv_scantime = {
  170. .tv_sec = opt_scantime,
  171. };
  172. evtimer_add(ev_notify, &tv_scantime);
  173. }
  174. static struct proxy_client *_stratumsrv_find_or_create_client(const char *);
  175. static
  176. struct proxy_client *(*stratumsrv_find_or_create_client)(const char *) = _stratumsrv_find_or_create_client;
  177. static
  178. struct proxy_client *_stratumsrv_find_or_create_client(const char *user)
  179. {
  180. struct proxy_client * const client = proxy_find_or_create_client(user);
  181. struct cgpu_info *cgpu;
  182. struct thr_info *thr;
  183. if (!client)
  184. return NULL;
  185. cgpu = client->cgpu;
  186. thr = cgpu->thr[0];
  187. memcpy(thr->work_restart_notifier, _ssm_update_notifier, sizeof(thr->work_restart_notifier));
  188. stratumsrv_find_or_create_client = proxy_find_or_create_client;
  189. return client;
  190. }
  191. static
  192. void stratumsrv_mining_subscribe(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  193. {
  194. char buf[90 + strlen(idstr) + (_ssm_client_octets * 2 * 2) + 0x10];
  195. char xnonce1x[(_ssm_client_octets * 2) + 1];
  196. int bufsz;
  197. if (!*xnonce1_p)
  198. {
  199. uint32_t xnonce1;
  200. for (xnonce1 = MAX_CLIENTS; _ssm_xnonce1s[xnonce1]; --xnonce1)
  201. if (!xnonce1)
  202. ; // TODO: Error
  203. *xnonce1_p = htole32(xnonce1);
  204. }
  205. bin2hex(xnonce1x, xnonce1_p, _ssm_client_octets);
  206. bufsz = sprintf(buf, "{\"id\":%s,\"result\":[[[\"mining.set_difficulty\",\"x\"],[\"mining.notify\",\"%s\"]],\"%s\",%d],\"error\":null}\n", idstr, xnonce1x, xnonce1x, _ssm_client_xnonce2sz);
  207. bufferevent_write(bev, buf, bufsz);
  208. bufferevent_write(bev, "{\"params\":[0.9999847412109375],\"id\":null,\"method\":\"mining.set_difficulty\"}\n", 75);
  209. bufferevent_write(bev, _ssm_notify, _ssm_notify_sz);
  210. }
  211. static
  212. void _stratumsrv_failure(struct bufferevent * const bev, const char * const idstr, const int e, const char * const emsg)
  213. {
  214. if (!idstr)
  215. return;
  216. char buf[0x100];
  217. size_t bufsz = snprintf(buf, sizeof(buf), "{\"error\":[%d,\"%s\",null],\"id\":%s,\"result\":null}\n", e, emsg, idstr);
  218. bufferevent_write(bev, buf, bufsz);
  219. }
  220. #define return_stratumsrv_failure(e, emsg) do{ \
  221. _stratumsrv_failure(bev, idstr, e, emsg); \
  222. return; \
  223. }while(0)
  224. static
  225. void _stratumsrv_success(struct bufferevent * const bev, const char * const idstr)
  226. {
  227. if (!idstr)
  228. return;
  229. size_t bufsz = 36 + strlen(idstr);
  230. char buf[bufsz];
  231. bufsz = sprintf(buf, "{\"result\":true,\"id\":%s,\"error\":null}\n", idstr);
  232. bufferevent_write(bev, buf, bufsz);
  233. }
  234. static
  235. void stratumsrv_mining_authorize(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  236. {
  237. struct proxy_client * const client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  238. if (unlikely(!client))
  239. return_stratumsrv_failure(20, "Failed creating new cgpu");
  240. _stratumsrv_success(bev, idstr);
  241. }
  242. static
  243. void stratumsrv_mining_submit(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  244. {
  245. struct work _work, *work;
  246. struct stratumsrv_job *ssj;
  247. struct proxy_client *client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  248. struct cgpu_info *cgpu;
  249. struct thr_info *thr;
  250. const char * const job_id = __json_array_string(params, 1);
  251. const char * const extranonce2 = __json_array_string(params, 2);
  252. const char * const ntime = __json_array_string(params, 3);
  253. const char * const nonce = __json_array_string(params, 4);
  254. uint32_t nonce_n;
  255. if (unlikely(!client))
  256. return_stratumsrv_failure(20, "Failed creating new cgpu");
  257. if (unlikely(!(job_id && extranonce2 && ntime && nonce)))
  258. return_stratumsrv_failure(20, "Couldn't understand parameters");
  259. if (unlikely(strlen(nonce) < 8))
  260. return_stratumsrv_failure(20, "nonce too short");
  261. if (unlikely(strlen(ntime) < 8))
  262. return_stratumsrv_failure(20, "ntime too short");
  263. if (unlikely(strlen(extranonce2) < _ssm_client_xnonce2sz * 2))
  264. return_stratumsrv_failure(20, "extranonce2 too short");
  265. cgpu = client->cgpu;
  266. thr = cgpu->thr[0];
  267. // Lookup job_id
  268. HASH_FIND_STR(_ssm_jobs, job_id, ssj);
  269. if (!ssj)
  270. return_stratumsrv_failure(21, "Job not found");
  271. // Generate dummy work
  272. work = &_work;
  273. _ssm_gen_dummy_work(work, ssj, extranonce2, *xnonce1_p);
  274. // Submit nonce
  275. hex2bin(&work->data[68], ntime, 4);
  276. hex2bin((void*)&nonce_n, nonce, 4);
  277. nonce_n = le32toh(nonce_n);
  278. if (!submit_nonce(thr, work, nonce_n))
  279. _stratumsrv_failure(bev, idstr, 23, "H-not-zero");
  280. else
  281. if (stale_work(work, true))
  282. _stratumsrv_failure(bev, idstr, 21, "stale");
  283. else
  284. _stratumsrv_success(bev, idstr);
  285. clean_work(work);
  286. }
  287. static
  288. bool stratumsrv_process_line(struct bufferevent * const bev, const char * const ln, void * const p)
  289. {
  290. struct stratumsrv_conn *conn = p;
  291. json_error_t jerr;
  292. json_t *json, *params, *j2;
  293. const char *method;
  294. char *idstr;
  295. json = JSON_LOADS(ln, &jerr);
  296. if (!json)
  297. {
  298. applog(LOG_ERR, "SSM: JSON parse error: %s", ln);
  299. return false;
  300. }
  301. method = bfg_json_obj_string(json, "method", NULL);
  302. if (!method)
  303. {
  304. applog(LOG_ERR, "SSM: JSON missing method: %s", ln);
  305. return false;
  306. }
  307. params = json_object_get(json, "params");
  308. if (!params)
  309. {
  310. applog(LOG_ERR, "SSM: JSON missing params: %s", ln);
  311. return false;
  312. }
  313. applog(LOG_DEBUG, "SSM: RECV: %s", ln);
  314. j2 = json_object_get(json, "id");
  315. idstr = (j2 && !json_is_null(j2)) ? json_dumps_ANY(j2, 0) : NULL;
  316. if (!strcasecmp(method, "mining.submit"))
  317. stratumsrv_mining_submit(bev, params, idstr, &conn->xnonce1_le);
  318. else
  319. if (!strcasecmp(method, "mining.authorize"))
  320. stratumsrv_mining_authorize(bev, params, idstr, &conn->xnonce1_le);
  321. else
  322. if (!strcasecmp(method, "mining.subscribe"))
  323. stratumsrv_mining_subscribe(bev, params, idstr, &conn->xnonce1_le);
  324. else
  325. _stratumsrv_failure(bev, idstr, -3, "Method not supported");
  326. free(idstr);
  327. return true;
  328. }
  329. static
  330. void stratumsrv_client_close(struct stratumsrv_conn * const conn)
  331. {
  332. struct bufferevent * const bev = conn->bev;
  333. bufferevent_free(bev);
  334. LL_DELETE(_ssm_connections, conn);
  335. free(conn);
  336. }
  337. static
  338. void stratumsrv_read(struct bufferevent *bev, void *p)
  339. {
  340. struct evbuffer *input = bufferevent_get_input(bev);
  341. char *ln;
  342. bool rv;
  343. while ( (ln = evbuffer_readln(input, NULL, EVBUFFER_EOL_ANY)) )
  344. {
  345. rv = stratumsrv_process_line(bev, ln, p);
  346. free(ln);
  347. if (unlikely(!rv))
  348. {
  349. stratumsrv_client_close(p);
  350. break;
  351. }
  352. }
  353. }
  354. static
  355. void stratumsrv_event(struct bufferevent *bev, short events, void *p)
  356. {
  357. if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
  358. {
  359. if (events & BEV_EVENT_ERROR)
  360. applog(LOG_ERR, "Error from bufferevent");
  361. if (events & BEV_EVENT_EOF)
  362. applog(LOG_DEBUG, "EOF from bufferevent");
  363. stratumsrv_client_close(p);
  364. }
  365. }
  366. static
  367. void stratumlistener(struct evconnlistener *listener, evutil_socket_t sock, struct sockaddr *addr, int len, void *p)
  368. {
  369. struct stratumsrv_conn *conn;
  370. struct event_base *evbase = evconnlistener_get_base(listener);
  371. struct bufferevent *bev = bufferevent_socket_new(evbase, sock, BEV_OPT_CLOSE_ON_FREE);
  372. conn = malloc(sizeof(*conn));
  373. *conn = (struct stratumsrv_conn){
  374. .bev = bev,
  375. };
  376. LL_PREPEND(_ssm_connections, conn);
  377. bufferevent_setcb(bev, stratumsrv_read, NULL, stratumsrv_event, conn);
  378. bufferevent_enable(bev, EV_READ | EV_WRITE);
  379. }
  380. void *stratumsrv_thread(__maybe_unused void *p)
  381. {
  382. pthread_detach(pthread_self());
  383. RenameThread("stratumsrv");
  384. for (uint64_t n = MAX_CLIENTS; n; n >>= 8)
  385. ++_ssm_client_octets;
  386. _ssm_client_xnonce2sz = 2;
  387. struct event_base *evbase = event_base_new();
  388. {
  389. ev_notify = evtimer_new(evbase, _stratumsrv_update_notify, NULL);
  390. _stratumsrv_update_notify(-1, 0, NULL);
  391. }
  392. {
  393. notifier_init(_ssm_update_notifier);
  394. struct event *ev_update_notifier = event_new(evbase, _ssm_update_notifier[0], EV_READ | EV_PERSIST, _stratumsrv_update_notify, NULL);
  395. event_add(ev_update_notifier, NULL);
  396. }
  397. {
  398. struct sockaddr_in sin = {
  399. .sin_family = AF_INET,
  400. .sin_addr.s_addr = INADDR_ANY,
  401. .sin_port = htons(3334),
  402. };
  403. evconnlistener_new_bind(evbase, stratumlistener, NULL, (
  404. LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE
  405. ), 0x10, (void*)&sin, sizeof(sin));
  406. }
  407. event_base_dispatch(evbase);
  408. return NULL;
  409. }