Skip to content

Instantly share code, notes, and snippets.

@StuartFarmer
Last active June 27, 2019 03:20
Show Gist options
  • Save StuartFarmer/5e6549700c9b75460df5478a2c104988 to your computer and use it in GitHub Desktop.
Save StuartFarmer/5e6549700c9b75460df5478a2c104988 to your computer and use it in GitHub Desktop.
dynamic_pow_hash.py
import hashlib
import secrets
def SHA3_512_1ST_HALF(data):
h = hashlib.sha3_512()
h.update(data)
return h.digest()[:32]
def SHA3_512_2ND_HALF(data):
h = hashlib.sha3_512()
h.update(data)
return h.digest()[32:]
def SHA3_256(data):
h = hashlib.sha3_256()
h.update(data)
return h.digest()
def SHA2_256(data):
h = hashlib.sha256()
h.update(data)
return h.digest()
def SHAKE_256_32_BYTES(data):
h = hashlib.shake_256()
h.update(data)
return h.digest(32)
def SHAKE_128_32_BYTES(data):
h = hashlib.shake_128()
h.update(data)
return h.digest(32)
def BLAKE2B_1ST_HALF(data):
h = hashlib.blake2b()
h.update(data)
return h.digest()[:32]
def BLAKE2B_2ND_HALF(data):
h = hashlib.blake2b()
h.update(data)
return h.digest()[32:]
ciphers = [
SHA3_512_1ST_HALF,
SHA3_512_2ND_HALF,
SHA3_256,
SHA2_256,
SHAKE_256_32_BYTES,
SHAKE_128_32_BYTES,
BLAKE2B_1ST_HALF,
BLAKE2B_2ND_HALF
]
def pipeline_encryptor(state, nonce, step=4):
data = nonce
for i in range(len(state) // step):
start = (i * step)
end = (i * step) + step
chunk = state[start:end]
chunk_i = int(chunk.hex(), 16)
selection = chunk_i % len(ciphers)
cipher = ciphers[selection]
data = cipher(data)
return data
DEFAULT_DIFF = '0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
def check_solution(state: bytes,
data: bytes,
nonce: bytes,
difficulty=DEFAULT_DIFF):
d_i = int(difficulty, 16)
h = hashlib.sha3_256()
h.update(data)
h.update(nonce)
d = h.digest()
work = pipeline_encryptor(state, d)
w_i = int(work.hex(), 16)
return w_i < d_i
def find_solution(state: bytes, data: bytes):
nonce = secrets.token_bytes(32)
while not check_solution(state, data, nonce):
nonce = secrets.token_bytes(32)
return nonce
state = b'a' * 32
data = b'asd'
nonce = find_solution(state, data)
print(nonce.hex())
print(check_solution(state, data, nonce))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment