2019-03-26 13:17:08 +00:00
|
|
|
from hashlib import sha256
|
2019-03-18 18:51:52 +00:00
|
|
|
|
2019-06-11 17:23:45 +00:00
|
|
|
ZERO_BYTES32 = b'\x00' * 32
|
2019-03-18 18:51:52 +00:00
|
|
|
|
2019-06-11 19:53:38 +00:00
|
|
|
|
2019-06-11 17:23:45 +00:00
|
|
|
def _hash(x):
|
2019-06-01 00:40:29 +00:00
|
|
|
return sha256(x).digest()
|
2019-06-11 17:23:45 +00:00
|
|
|
|
2019-06-11 19:53:38 +00:00
|
|
|
|
|
|
|
# Minimal collection of (key, value) pairs, for fast hash-retrieval, to save on repetitive computation cost.
|
|
|
|
# Key = the hash input
|
|
|
|
# Value = the hash output
|
|
|
|
hash_cache = []
|
|
|
|
|
|
|
|
|
|
|
|
def add_zero_hashes_to_cache():
|
|
|
|
zerohashes = [(None, ZERO_BYTES32)]
|
|
|
|
for layer in range(1, 32):
|
|
|
|
k = zerohashes[layer - 1][1] + zerohashes[layer - 1][1]
|
|
|
|
zerohashes.append((k, _hash(k)))
|
|
|
|
hash_cache.extend(zerohashes[1:])
|
2019-06-11 17:23:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
def hash(x):
|
2019-06-11 19:53:38 +00:00
|
|
|
for (k, h) in hash_cache:
|
2019-06-11 17:23:45 +00:00
|
|
|
if x == k:
|
|
|
|
return h
|
|
|
|
return _hash(x)
|