An old btc miner project.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stratum-client.js 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. var RPCConn = require("./rpcconn");
  2. class StratumClient {
  3. constructor(ip, port, miner) {
  4. this.name = ip+":"+port;
  5. this.nounceReady = false;
  6. this.difficultyReady = false;
  7. this.miner = miner;
  8. this.rpc = new RPCConn(ip, port);
  9. }
  10. log(...msgs) {
  11. process.stdout.write(this.name+": ");
  12. console.log.apply(console, msgs);
  13. }
  14. async startWork() {
  15. if (!this.work)
  16. return;
  17. this.log("Starting work", this.work.id);
  18. var res;
  19. try {
  20. res = await this.miner.startWork(this.work);
  21. } catch (err) {
  22. console.trace(err);
  23. return;
  24. }
  25. this.log("Work done,", res.toString("hex"));
  26. }
  27. async connect() {
  28. await this.rpc.wait();
  29. await this.miner.wait();
  30. this.rpc.on("mining.notify", async params => {
  31. var work = {
  32. id: params[0], prevHash: params[1],
  33. coinb1: params[2], coinb2: params[3],
  34. merkleBranch: params[4], version: params[5],
  35. nBits: params[6], nTime: params[7], cleanJobs: params[8],
  36. };
  37. this.log("Got work", work.id);
  38. this.work = work;
  39. if (this.difficultyReady && this.nounceReady)
  40. this.startWork();
  41. });
  42. this.rpc.on("mining.set_difficulty", params => {
  43. this.log("Got difficulty", params[0]);
  44. this.miner.setDifficulty(params[0]);
  45. if (this.difficultyReady)
  46. return;
  47. this.difficultyReady = true;
  48. if (this.nounceReady)
  49. this.startWork();
  50. });
  51. var sub = await this.rpc.call("mining.subscribe");
  52. this.log("Got nounce", sub[1]);
  53. this.miner.setNounce(sub[1], sub[2]);
  54. this.nounceReady = true;
  55. if (this.difficultyReady)
  56. this.startWork();
  57. }
  58. async auth(user, pass) {
  59. var success = await this.rpc.call("mining.authorize", user, pass);
  60. if (!success)
  61. throw new Error("Incorrect username/password.");
  62. this.log("Authenticated "+user+".");
  63. }
  64. writePayload() {
  65. var rdlen = 95 - 63;
  66. var rdata = Buffer.alloc(rdlen);
  67. for (var i = 0; i < rdlen; ++i)
  68. rdata[i] = this._block[94 - i];
  69. var rmlen = 64;
  70. var rmid = Buffer.alloc(rmlen);
  71. for (var i = 0; i < rmlen; ++i)
  72. rmid[i] = this._midstate[rmlen - i - 1];
  73. var payload = Buffer.concat([rmid, rdata]);
  74. this.log("Writing '"+payload.toString("hex")+"'");
  75. this._port.write(payload);
  76. }
  77. }
  78. module.exports = StratumClient;