proofow/proofow.py

33 lines
773 B
Python
Raw Normal View History

2017-12-01 19:25:57 +00:00
from os import urandom
from itertools import count
from hashlib import sha256
2017-12-01 20:40:45 +00:00
class pow_base:
2017-12-01 22:57:52 +00:00
@property
def base(self):
return self._base
2017-12-01 19:45:52 +00:00
def __init__(self, difficulty, base=None):
2017-12-01 20:40:45 +00:00
self._base = urandom(self._bits//8) if not base else base
self._target = 2 ** (self._bits - difficulty)
2017-12-01 19:25:57 +00:00
def work(self):
for nonce in count():
if self.verify(nonce):
return nonce
def verify(self, nonce):
2017-12-01 20:40:45 +00:00
hexresult = self._hexdigest(self._base + str(nonce).encode())
2017-12-01 19:25:57 +00:00
return int(hexresult, 16) < self._target
2017-12-01 20:40:45 +00:00
class pow_hashlib_base(pow_base):
def _hexdigest(self, data):
return self._hasher(data).hexdigest()
class pow256(pow_hashlib_base):
_bits = 256
_hasher = sha256