Skip to content

Instantly share code, notes, and snippets.

@pipermerriam
Created November 24, 2016 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pipermerriam/fc8926eea8a4128cb773261681e632f7 to your computer and use it in GitHub Desktop.
Save pipermerriam/fc8926eea8a4128cb773261681e632f7 to your computer and use it in GitHub Desktop.
import sys
import codecs
import functools
from sha3 import sha3_256
if sys.version_info.major == 2:
bytes_types = (bytes, bytearray)
text_types = (unicode,) # noqa: F821
else:
bytes_types = (bytes, bytearray)
text_types = (str,)
def is_bytes(value):
return isinstance(value, bytes_types)
def is_text(value):
return isinstance(value, text_types)
def force_bytes(value):
if is_bytes(value):
return bytes(value)
elif is_text(value):
return codecs.encode(value, "utf8")
else:
raise TypeError("Unsupported type: {0}".format(type(value)))
def identity(value):
return value
def combine(f, g):
return lambda x: f(g(x))
def compose(*functions):
return functools.reduce(combine, reversed(functions), identity)
def sha3(value):
return sha3_256(value).digest()
def _sub_hash(value, label):
return sha3(value + sha3(label))
def namehash(name):
node = b'\x00' * 32
if name:
labels = force_bytes(name).split(b'.')
print(labels)
return compose(*(
functools.partial(_sub_hash, label=label)
for label
in reversed(labels)
))(node)
return node
assert codecs.encode(namehash(''), 'hex') == b'0000000000000000000000000000000000000000000000000000000000000000'
assert codecs.encode(namehash('eth'), 'hex') == b'93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae'
assert codecs.encode(namehash('foo.eth'), 'hex') == b'de9b09fd7c5f901e23a3f19fecc54828e9c848539801e86591bd9801b019f84f'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment