2017-05-04 03:24:07 +03:00
|
|
|
'use strict';
|
|
|
|
|
2018-12-11 01:02:02 +03:00
|
|
|
import * as errors from '../errors';
|
|
|
|
|
2018-07-16 10:27:49 +03:00
|
|
|
import { concat, hexlify } from './bytes';
|
2018-06-13 22:39:39 +03:00
|
|
|
import { toUtf8Bytes } from './utf8';
|
|
|
|
import { keccak256 } from './keccak256';
|
2017-05-04 03:24:07 +03:00
|
|
|
|
2018-07-31 01:59:52 +03:00
|
|
|
///////////////////////////////
|
|
|
|
// Imported Types
|
|
|
|
|
|
|
|
import { Arrayish } from './bytes';
|
|
|
|
|
|
|
|
///////////////////////////////
|
2018-07-16 10:27:49 +03:00
|
|
|
|
2018-12-11 01:02:02 +03: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("^((.*)\\.)?([^.]+)$");
|
|
|
|
const UseSTD3ASCIIRules = new RegExp("^[a-z0-9.-]*$");
|
2017-05-04 03:24:07 +03:00
|
|
|
|
2018-06-13 22:39:39 +03:00
|
|
|
export function namehash(name: string): string {
|
2018-12-11 01:02:02 +03:00
|
|
|
if (typeof(name) !== 'string') {
|
|
|
|
errors.throwError('invalid address - ' + String(name), errors.INVALID_ARGUMENT, {
|
|
|
|
argument: 'name',
|
|
|
|
value: name
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-05-04 03:24:07 +03:00
|
|
|
name = name.toLowerCase();
|
|
|
|
|
|
|
|
// Supporting the full UTF-8 space requires additional (and large)
|
|
|
|
// libraries, so for now we simply do not support them.
|
|
|
|
// It should be fairly easy in the future to support systems with
|
|
|
|
// String.normalize, but that is future work.
|
|
|
|
if (!name.match(UseSTD3ASCIIRules)) {
|
2018-12-11 01:02:02 +03:00
|
|
|
errors.throwError('contains invalid UseSTD3ASCIIRules characters', errors.INVALID_ARGUMENT, {
|
|
|
|
argument: 'name',
|
|
|
|
value: name
|
|
|
|
});
|
2017-05-04 03:24:07 +03:00
|
|
|
}
|
|
|
|
|
2018-12-11 01:02:02 +03:00
|
|
|
let result: string | Uint8Array = Zeros;
|
2018-06-13 22:39:39 +03:00
|
|
|
while (name.length) {
|
2018-12-11 01:02:02 +03:00
|
|
|
let partition = name.match(Partition);
|
|
|
|
let label = toUtf8Bytes(partition[3]);
|
2018-06-13 22:39:39 +03:00
|
|
|
result = keccak256(concat([result, keccak256(label)]));
|
2017-05-04 03:24:07 +03:00
|
|
|
|
|
|
|
name = partition[2] || '';
|
|
|
|
}
|
|
|
|
|
2018-06-13 22:39:39 +03:00
|
|
|
return hexlify(result);
|
2017-05-04 03:24:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2018-06-18 12:42:41 +03:00
|
|
|
export function id(text: string): string {
|
|
|
|
return keccak256(toUtf8Bytes(text));
|
|
|
|
}
|
|
|
|
|
|
|
|
export function hashMessage(message: Arrayish | string): string {
|
2018-12-11 01:02:02 +03:00
|
|
|
return keccak256(concat([
|
2018-06-18 12:42:41 +03:00
|
|
|
toUtf8Bytes('\x19Ethereum Signed Message:\n'),
|
|
|
|
toUtf8Bytes(String(message.length)),
|
|
|
|
((typeof(message) === 'string') ? toUtf8Bytes(message): message)
|
2018-12-11 01:02:02 +03:00
|
|
|
]));
|
2018-06-18 12:42:41 +03:00
|
|
|
}
|
|
|
|
|