Source: mining/mine.js

  1. /*!
  2. * mine.js - mining function for bcoin
  3. * Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
  4. * https://github.com/bcoin-org/bcoin
  5. */
  6. 'use strict';
  7. const assert = require('bsert');
  8. const hash256 = require('bcrypto/lib/hash256');
  9. /**
  10. * Hash until the nonce overflows.
  11. * @alias module:mining.mine
  12. * @param {Buffer} data
  13. * @param {Buffer} target - Big endian.
  14. * @param {Number} min
  15. * @param {Number} max
  16. * @returns {Number} Nonce or -1.
  17. */
  18. function mine(data, target, min, max) {
  19. let nonce = min;
  20. data.writeUInt32LE(nonce, 76, true);
  21. // The heart and soul of the miner: match the target.
  22. while (nonce <= max) {
  23. // Hash and test against the next target.
  24. if (rcmp(hash256.digest(data), target) <= 0)
  25. return nonce;
  26. // Increment the nonce to get a different hash.
  27. nonce += 1;
  28. // Update the raw buffer.
  29. data.writeUInt32LE(nonce, 76, true);
  30. }
  31. return -1;
  32. }
  33. /**
  34. * "Reverse" comparison so we don't have
  35. * to waste time reversing the block hash.
  36. * @ignore
  37. * @param {Buffer} a
  38. * @param {Buffer} b
  39. * @returns {Number}
  40. */
  41. function rcmp(a, b) {
  42. assert(a.length === b.length);
  43. for (let i = a.length - 1; i >= 0; i--) {
  44. if (a[i] < b[i])
  45. return -1;
  46. if (a[i] > b[i])
  47. return 1;
  48. }
  49. return 0;
  50. }
  51. /*
  52. * Expose
  53. */
  54. module.exports = mine;