message.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { keccak256 } from "../crypto/index.js";
  2. import { MessagePrefix } from "../constants/index.js";
  3. import { recoverAddress } from "../transaction/index.js";
  4. import { concat, toUtf8Bytes } from "../utils/index.js";
  5. /**
  6. * Computes the [[link-eip-191]] personal-sign message digest to sign.
  7. *
  8. * This prefixes the message with [[MessagePrefix]] and the decimal length
  9. * of %%message%% and computes the [[keccak256]] digest.
  10. *
  11. * If %%message%% is a string, it is converted to its UTF-8 bytes
  12. * first. To compute the digest of a [[DataHexString]], it must be converted
  13. * to [bytes](getBytes).
  14. *
  15. * @example:
  16. * hashMessage("Hello World")
  17. * //_result:
  18. *
  19. * // Hashes the SIX (6) string characters, i.e.
  20. * // [ "0", "x", "4", "2", "4", "3" ]
  21. * hashMessage("0x4243")
  22. * //_result:
  23. *
  24. * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...
  25. * hashMessage(getBytes("0x4243"))
  26. * //_result:
  27. *
  28. * // ...which is equal to using data
  29. * hashMessage(new Uint8Array([ 0x42, 0x43 ]))
  30. * //_result:
  31. *
  32. */
  33. export function hashMessage(message) {
  34. if (typeof (message) === "string") {
  35. message = toUtf8Bytes(message);
  36. }
  37. return keccak256(concat([
  38. toUtf8Bytes(MessagePrefix),
  39. toUtf8Bytes(String(message.length)),
  40. message
  41. ]));
  42. }
  43. /**
  44. * Return the address of the private key that produced
  45. * the signature %%sig%% during signing for %%message%%.
  46. */
  47. export function verifyMessage(message, sig) {
  48. const digest = hashMessage(message);
  49. return recoverAddress(digest, sig);
  50. }
  51. //# sourceMappingURL=message.js.map