sign.js 936 B

12345678910111213141516171819202122232425262728
  1. const utils = require('ethereumjs-util');
  2. /**
  3. * Hash and add same prefix to the hash that ganache use.
  4. * @param {string} message the plaintext/ascii/original message
  5. * @return {string} the hash of the message, prefixed, and then hashed again
  6. */
  7. function hashMessage (message) {
  8. const messageHex = Buffer.from(utils.sha3(message).toString('hex'), 'hex');
  9. const prefix = utils.toBuffer('\u0019Ethereum Signed Message:\n' + messageHex.length.toString());
  10. return utils.bufferToHex(utils.sha3(Buffer.concat([prefix, messageHex])));
  11. }
  12. // signs message using web3 (auto-applies prefix)
  13. function signMessage (signer, message = '', options = {}) {
  14. return web3.eth.sign(signer, web3.sha3(message, options));
  15. }
  16. // signs hex string using web3 (auto-applies prefix)
  17. function signHex (signer, message = '') {
  18. return signMessage(signer, message, { encoding: 'hex' });
  19. }
  20. module.exports = {
  21. hashMessage,
  22. signMessage,
  23. signHex,
  24. };