33 lines
1.0 KiB
Python
33 lines
1.0 KiB
Python
import itertools
|
|
import hashlib
|
|
import hmac
|
|
|
|
|
|
class NonceFinder:
|
|
def __init__(self, data, difficulty, key):
|
|
self.data = data
|
|
self.difficulty = difficulty
|
|
self.key = key
|
|
|
|
@staticmethod
|
|
def to_long(x):
|
|
return sum(ord(b) << (8 * i) for i, b in enumerate(x))
|
|
|
|
def verify_pow(self, nonce):
|
|
self.data[0]['nonce'] = nonce
|
|
# Использование HMAC с SHA-256
|
|
combined_data = str(self.data).encode()
|
|
hmac_result = hmac.new(self.key.encode(), combined_data, hashlib.sha256).hexdigest()
|
|
return self.to_long(list(hmac_result)) % (1 << self.difficulty) == 0
|
|
|
|
def create_pow(self):
|
|
for nonce in itertools.count(0):
|
|
if self.verify_pow(nonce):
|
|
combined_data = str(self.data).encode()
|
|
hmac_result = hmac.new(
|
|
self.key.encode(),
|
|
combined_data,
|
|
hashlib.sha256
|
|
).hexdigest()
|
|
return nonce, hmac_result
|