namehash.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { concat, hexlify } from "@ethersproject/bytes";
  2. import { nameprep, toUtf8Bytes } from "@ethersproject/strings";
  3. import { keccak256 } from "@ethersproject/keccak256";
  4. import { Logger } from "@ethersproject/logger";
  5. import { version } from "./_version";
  6. const logger = new Logger(version);
  7. const Zeros = new Uint8Array(32);
  8. Zeros.fill(0);
  9. const Partition = new RegExp("^((.*)\\.)?([^.]+)$");
  10. export function isValidName(name) {
  11. try {
  12. const comps = name.split(".");
  13. for (let i = 0; i < comps.length; i++) {
  14. if (nameprep(comps[i]).length === 0) {
  15. throw new Error("empty");
  16. }
  17. }
  18. return true;
  19. }
  20. catch (error) { }
  21. return false;
  22. }
  23. export function namehash(name) {
  24. /* istanbul ignore if */
  25. if (typeof (name) !== "string") {
  26. logger.throwArgumentError("invalid ENS name; not a string", "name", name);
  27. }
  28. let current = name;
  29. let result = Zeros;
  30. while (current.length) {
  31. const partition = current.match(Partition);
  32. if (partition == null || partition[2] === "") {
  33. logger.throwArgumentError("invalid ENS address; missing component", "name", name);
  34. }
  35. const label = toUtf8Bytes(nameprep(partition[3]));
  36. result = keccak256(concat([result, keccak256(label)]));
  37. current = partition[2] || "";
  38. }
  39. return hexlify(result);
  40. }
  41. export function dnsEncode(name) {
  42. return hexlify(concat(name.split(".").map((comp) => {
  43. // We jam in an _ prefix to fill in with the length later
  44. // Note: Nameprep throws if the component is over 63 bytes
  45. const bytes = toUtf8Bytes("_" + nameprep(comp));
  46. bytes[0] = bytes.length - 1;
  47. return bytes;
  48. }))) + "00";
  49. }
  50. //# sourceMappingURL=namehash.js.map