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.

cryptutil.js 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var crypto = require("crypto");
  2. exports.createCoinbase = createCoinbase;
  3. exports.createCbHash = createCbHash;
  4. exports.buildMerkleRoot = buildMerkleRoot;
  5. exports.doublesha = doublesha;
  6. exports.incbufBE = incbufBE;
  7. /* Create a coinbase buffer.
  8. *
  9. * Args:
  10. * cb1, cb2: Buffer, coinbase parts 1 and 2
  11. * ex1, ex2: Buffer, extranounce 1 and 2
  12. *
  13. * Returns:
  14. * Buffer, a complete coinbase
  15. */
  16. function createCoinbase(ex1, ex2, cb1, cb2) {
  17. return Buffer.concat([ cb1, ex1, ex2, cb2 ]);
  18. }
  19. /* Create a coinbase hash.
  20. *
  21. * Args:
  22. * coinbase: Buffer, the coinbase
  23. *
  24. * Returns:
  25. * Buffer, the cbHashBin
  26. */
  27. function createCbHash(coinbase) {
  28. return doublesha(coinbase);
  29. }
  30. /* Build a merkle root from a merkle branch and a coinbase hash.
  31. *
  32. * Returns:
  33. * Buffer, the merkle root
  34. *
  35. * Args:
  36. * merkleBranch: Array, hex encoded hashes
  37. * cbHash: Buffer, the coinbase hash
  38. */
  39. function buildMerkleRoot(merkleBranch, cbHash) {
  40. var root = cbHashBin
  41. for (var i in merkleBranch) {
  42. var h = Buffer.from(merkleBranch[i], "hex");
  43. root = doublesha(Buffer.concat(root, h));
  44. }
  45. return root;
  46. }
  47. /* Run sha256 twice on a buffer.
  48. *
  49. * Returns:
  50. * Buffer, the double-sha256'd buffer
  51. *
  52. * Args:
  53. * buf: Buffer, will be double-sha256'd
  54. */
  55. function doublesha(buf) {
  56. var tmp = crypto.createHash("sha256").update(buf).digest();
  57. return crypto.createHash("sha256").update(tmp).digest();
  58. }
  59. /* Increment a buffer.
  60. *
  61. * Args:
  62. * buf: Buffer, will be incremented.
  63. */
  64. function incbufBE(buf) {
  65. for (var i = buf.length - 1; i >= 0; --i) {
  66. if (buf[i]++ !== 255)
  67. break;
  68. }
  69. }