driver-stratum.c 12 KB

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