2019-05-14 18:25:46 -04:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
import { Bytes, concat, hexlify } from "@ethersproject/bytes";
|
2019-07-27 18:44:53 -03:00
|
|
|
import { nameprep, toUtf8Bytes } from "@ethersproject/strings";
|
2019-05-14 18:25:46 -04:00
|
|
|
import { keccak256 } from "@ethersproject/keccak256";
|
|
|
|
|
2019-08-01 18:04:06 -04:00
|
|
|
import { Logger } from "@ethersproject/logger";
|
|
|
|
import { version } from "./_version";
|
|
|
|
const logger = new Logger(version);
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
///////////////////////////////
|
|
|
|
|
|
|
|
const Zeros = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
|
|
|
const Partition = new RegExp("^((.*)\\.)?([^.]+)$");
|
2019-07-27 18:44:53 -03:00
|
|
|
|
|
|
|
export function isValidName(name: string): boolean {
|
|
|
|
try {
|
2019-11-01 23:33:51 +09:00
|
|
|
const comps = name.split(".");
|
2019-07-27 18:44:53 -03:00
|
|
|
for (let i = 0; i < comps.length; i++) {
|
|
|
|
if (nameprep(comps[i]).length === 0) {
|
|
|
|
throw new Error("empty")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
} catch (error) { }
|
|
|
|
return false;
|
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
export function namehash(name: string): string {
|
|
|
|
if (typeof(name) !== "string") {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.throwArgumentError("invalid address - " + String(name), "name", name);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let result: string | Uint8Array = Zeros;
|
|
|
|
while (name.length) {
|
2019-11-01 23:33:51 +09:00
|
|
|
const partition = name.match(Partition);
|
|
|
|
const label = toUtf8Bytes(nameprep(partition[3]));
|
2019-05-14 18:25:46 -04:00
|
|
|
result = keccak256(concat([result, keccak256(label)]));
|
|
|
|
|
|
|
|
name = partition[2] || "";
|
|
|
|
}
|
|
|
|
|
|
|
|
return hexlify(result);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export function id(text: string): string {
|
|
|
|
return keccak256(toUtf8Bytes(text));
|
|
|
|
}
|
|
|
|
|
|
|
|
export const messagePrefix = "\x19Ethereum Signed Message:\n";
|
|
|
|
|
|
|
|
export function hashMessage(message: Bytes | string): string {
|
|
|
|
if (typeof(message) === "string") { message = toUtf8Bytes(message); }
|
|
|
|
return keccak256(concat([
|
|
|
|
toUtf8Bytes(messagePrefix),
|
|
|
|
toUtf8Bytes(String(message.length)),
|
|
|
|
message
|
|
|
|
]));
|
|
|
|
}
|