driver-stratum.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 _stratumsrv_update_notify(evutil_socket_t fd, short what, __maybe_unused void *p)
  134. {
  135. struct pool *pool = current_pool();
  136. bool clean;
  137. if (fd == _ssm_update_notifier[0])
  138. {
  139. evtimer_del(ev_notify);
  140. notifier_read(_ssm_update_notifier);
  141. applog(LOG_DEBUG, "SSM: Update triggered by notifier");
  142. }
  143. if (!pool->stratum_notify)
  144. {
  145. applog(LOG_WARNING, "SSM: Not using a stratum server upstream!");
  146. // FIXME
  147. return;
  148. }
  149. clean = _ssm_cur_job_work.pool ? stale_work(&_ssm_cur_job_work, true) : true;
  150. if (clean)
  151. {
  152. struct stratumsrv_job *ssj, *tmp;
  153. applog(LOG_DEBUG, "SSM: Current replacing job stale, pruning all jobs");
  154. HASH_ITER(hh, _ssm_jobs, ssj, tmp)
  155. {
  156. HASH_DEL(_ssm_jobs, ssj);
  157. //FIXME: stratum_work_clean(ssj);
  158. free(ssj);
  159. }
  160. }
  161. stratumsrv_update_notify_str(pool, clean);
  162. struct timeval tv_scantime = {
  163. .tv_sec = opt_scantime,
  164. };
  165. evtimer_add(ev_notify, &tv_scantime);
  166. }
  167. static struct proxy_client *_stratumsrv_find_or_create_client(const char *);
  168. static
  169. struct proxy_client *(*stratumsrv_find_or_create_client)(const char *) = _stratumsrv_find_or_create_client;
  170. static
  171. struct proxy_client *_stratumsrv_find_or_create_client(const char *user)
  172. {
  173. struct proxy_client * const client = proxy_find_or_create_client(user);
  174. struct cgpu_info *cgpu;
  175. struct thr_info *thr;
  176. if (!client)
  177. return NULL;
  178. cgpu = client->cgpu;
  179. thr = cgpu->thr[0];
  180. memcpy(thr->work_restart_notifier, _ssm_update_notifier, sizeof(thr->work_restart_notifier));
  181. stratumsrv_find_or_create_client = proxy_find_or_create_client;
  182. return client;
  183. }
  184. static
  185. void stratumsrv_mining_subscribe(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  186. {
  187. char buf[90 + strlen(idstr) + (_ssm_client_octets * 2 * 2) + 0x10];
  188. char xnonce1x[(_ssm_client_octets * 2) + 1];
  189. int bufsz;
  190. if (!*xnonce1_p)
  191. {
  192. uint32_t xnonce1;
  193. for (xnonce1 = MAX_CLIENTS; _ssm_xnonce1s[xnonce1]; --xnonce1)
  194. if (!xnonce1)
  195. ; // TODO: Error
  196. *xnonce1_p = htole32(xnonce1);
  197. }
  198. bin2hex(xnonce1x, xnonce1_p, _ssm_client_octets);
  199. bufsz = sprintf(buf, "{\"id\":%s,\"result\":[[[\"mining.set_difficulty\",\"x\"],[\"mining.notify\",\"%s\"]],\"%s\",%d],\"error\":null}\n", idstr, xnonce1x, xnonce1x, _ssm_client_xnonce2sz);
  200. bufferevent_write(bev, buf, bufsz);
  201. bufferevent_write(bev, "{\"params\":[0.9999847412109375],\"id\":null,\"method\":\"mining.set_difficulty\"}\n", 75);
  202. bufferevent_write(bev, _ssm_notify, _ssm_notify_sz);
  203. }
  204. static
  205. void _stratumsrv_failure(struct bufferevent * const bev, const char * const idstr, const int e, const char * const emsg)
  206. {
  207. if (!idstr)
  208. return;
  209. char buf[0x100];
  210. size_t bufsz = snprintf(buf, sizeof(buf), "{\"error\":[%d,\"%s\",null],\"id\":%s,\"result\":null}\n", e, emsg, idstr);
  211. bufferevent_write(bev, buf, bufsz);
  212. }
  213. #define return_stratumsrv_failure(e, emsg) do{ \
  214. _stratumsrv_failure(bev, idstr, e, emsg); \
  215. return; \
  216. }while(0)
  217. static
  218. void _stratumsrv_success(struct bufferevent * const bev, const char * const idstr)
  219. {
  220. if (!idstr)
  221. return;
  222. size_t bufsz = 36 + strlen(idstr);
  223. char buf[bufsz];
  224. bufsz = sprintf(buf, "{\"result\":true,\"id\":%s,\"error\":null}\n", idstr);
  225. bufferevent_write(bev, buf, bufsz);
  226. }
  227. static
  228. void stratumsrv_mining_authorize(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  229. {
  230. struct proxy_client * const client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  231. if (unlikely(!client))
  232. return_stratumsrv_failure(20, "Failed creating new cgpu");
  233. _stratumsrv_success(bev, idstr);
  234. }
  235. static
  236. void stratumsrv_mining_submit(struct bufferevent *bev, json_t *params, const char *idstr, uint32_t *xnonce1_p)
  237. {
  238. struct work _work, *work;
  239. struct stratumsrv_job *ssj;
  240. struct proxy_client *client = stratumsrv_find_or_create_client(__json_array_string(params, 0));
  241. struct cgpu_info *cgpu;
  242. struct thr_info *thr;
  243. const char * const job_id = __json_array_string(params, 1);
  244. const char * const extranonce2 = __json_array_string(params, 2);
  245. const char * const ntime = __json_array_string(params, 3);
  246. const char * const nonce = __json_array_string(params, 4);
  247. uint32_t nonce_n;
  248. if (unlikely(!client))
  249. return_stratumsrv_failure(20, "Failed creating new cgpu");
  250. if (unlikely(!(job_id && extranonce2 && ntime && nonce)))
  251. return_stratumsrv_failure(20, "Couldn't understand parameters");
  252. if (unlikely(strlen(nonce) < 8))
  253. return_stratumsrv_failure(20, "nonce too short");
  254. if (unlikely(strlen(ntime) < 8))
  255. return_stratumsrv_failure(20, "ntime too short");
  256. if (unlikely(strlen(extranonce2) < _ssm_client_xnonce2sz * 2))
  257. return_stratumsrv_failure(20, "extranonce2 too short");
  258. cgpu = client->cgpu;
  259. thr = cgpu->thr[0];
  260. // Lookup job_id
  261. HASH_FIND_STR(_ssm_jobs, job_id, ssj);
  262. if (!ssj)
  263. return_stratumsrv_failure(21, "Job not found");
  264. // Generate dummy work
  265. work = &_work;
  266. _ssm_gen_dummy_work(work, ssj, extranonce2, *xnonce1_p);
  267. // Submit nonce
  268. hex2bin(&work->data[68], ntime, 4);
  269. hex2bin((void*)&nonce_n, nonce, 4);
  270. nonce_n = le32toh(nonce_n);
  271. if (!submit_nonce(thr, work, nonce_n))
  272. _stratumsrv_failure(bev, idstr, 23, "H-not-zero");
  273. else
  274. if (stale_work(work, true))
  275. _stratumsrv_failure(bev, idstr, 21, "stale");
  276. else
  277. _stratumsrv_success(bev, idstr);
  278. clean_work(work);
  279. }
  280. static
  281. bool stratumsrv_process_line(struct bufferevent * const bev, const char * const ln, void * const p)
  282. {
  283. struct stratumsrv_conn *conn = p;
  284. json_error_t jerr;
  285. json_t *json, *params, *j2;
  286. const char *method;
  287. char *idstr;
  288. json = JSON_LOADS(ln, &jerr);
  289. if (!json)
  290. {
  291. applog(LOG_ERR, "SSM: JSON parse error: %s", ln);
  292. return false;
  293. }
  294. method = bfg_json_obj_string(json, "method", NULL);
  295. if (!method)
  296. {
  297. applog(LOG_ERR, "SSM: JSON missing method: %s", ln);
  298. return false;
  299. }
  300. params = json_object_get(json, "params");
  301. if (!params)
  302. {
  303. applog(LOG_ERR, "SSM: JSON missing params: %s", ln);
  304. return false;
  305. }
  306. applog(LOG_DEBUG, "SSM: RECV: %s", ln);
  307. j2 = json_object_get(json, "id");
  308. idstr = (j2 && !json_is_null(j2)) ? json_dumps_ANY(j2, 0) : NULL;
  309. if (!strcasecmp(method, "mining.submit"))
  310. stratumsrv_mining_submit(bev, params, idstr, &conn->xnonce1_le);
  311. else
  312. if (!strcasecmp(method, "mining.authorize"))
  313. stratumsrv_mining_authorize(bev, params, idstr, &conn->xnonce1_le);
  314. else
  315. if (!strcasecmp(method, "mining.subscribe"))
  316. stratumsrv_mining_subscribe(bev, params, idstr, &conn->xnonce1_le);
  317. else
  318. _stratumsrv_failure(bev, idstr, -3, "Method not supported");
  319. free(idstr);
  320. return true;
  321. }
  322. static
  323. void stratumsrv_client_close(struct stratumsrv_conn * const conn)
  324. {
  325. struct bufferevent * const bev = conn->bev;
  326. bufferevent_free(bev);
  327. LL_DELETE(_ssm_connections, conn);
  328. free(conn);
  329. }
  330. static
  331. void stratumsrv_read(struct bufferevent *bev, void *p)
  332. {
  333. struct evbuffer *input = bufferevent_get_input(bev);
  334. char *ln;
  335. bool rv;
  336. while ( (ln = evbuffer_readln(input, NULL, EVBUFFER_EOL_ANY)) )
  337. {
  338. rv = stratumsrv_process_line(bev, ln, p);
  339. free(ln);
  340. if (unlikely(!rv))
  341. {
  342. stratumsrv_client_close(p);
  343. break;
  344. }
  345. }
  346. }
  347. static
  348. void stratumsrv_event(struct bufferevent *bev, short events, void *p)
  349. {
  350. if (events & (BEV_EVENT_EOF | BEV_EVENT_ERROR))
  351. {
  352. if (events & BEV_EVENT_ERROR)
  353. applog(LOG_ERR, "Error from bufferevent");
  354. if (events & BEV_EVENT_EOF)
  355. applog(LOG_DEBUG, "EOF from bufferevent");
  356. stratumsrv_client_close(p);
  357. }
  358. }
  359. static
  360. void stratumlistener(struct evconnlistener *listener, evutil_socket_t sock, struct sockaddr *addr, int len, void *p)
  361. {
  362. struct stratumsrv_conn *conn;
  363. struct event_base *evbase = evconnlistener_get_base(listener);
  364. struct bufferevent *bev = bufferevent_socket_new(evbase, sock, BEV_OPT_CLOSE_ON_FREE);
  365. conn = malloc(sizeof(*conn));
  366. *conn = (struct stratumsrv_conn){
  367. .bev = bev,
  368. };
  369. LL_PREPEND(_ssm_connections, conn);
  370. bufferevent_setcb(bev, stratumsrv_read, NULL, stratumsrv_event, conn);
  371. bufferevent_enable(bev, EV_READ | EV_WRITE);
  372. }
  373. void *stratumsrv_thread(__maybe_unused void *p)
  374. {
  375. pthread_detach(pthread_self());
  376. RenameThread("stratumsrv");
  377. for (uint64_t n = MAX_CLIENTS; n; n >>= 8)
  378. ++_ssm_client_octets;
  379. _ssm_client_xnonce2sz = 2;
  380. struct event_base *evbase = event_base_new();
  381. {
  382. ev_notify = evtimer_new(evbase, _stratumsrv_update_notify, NULL);
  383. _stratumsrv_update_notify(-1, 0, NULL);
  384. }
  385. {
  386. notifier_init(_ssm_update_notifier);
  387. struct event *ev_update_notifier = event_new(evbase, _ssm_update_notifier[0], EV_READ | EV_PERSIST, _stratumsrv_update_notify, NULL);
  388. event_add(ev_update_notifier, NULL);
  389. }
  390. {
  391. struct sockaddr_in sin = {
  392. .sin_family = AF_INET,
  393. .sin_addr.s_addr = INADDR_ANY,
  394. .sin_port = htons(3334),
  395. };
  396. evconnlistener_new_bind(evbase, stratumlistener, NULL, (
  397. LEV_OPT_CLOSE_ON_FREE | LEV_OPT_CLOSE_ON_EXEC | LEV_OPT_REUSEABLE
  398. ), 0x10, (void*)&sin, sizeof(sin));
  399. }
  400. event_base_dispatch(evbase);
  401. return NULL;
  402. }