MiNode/minode/proofofwork.py

55 lines
1.4 KiB
Python
Raw Normal View History

2022-09-23 00:54:12 +02:00
"""Doing proof of work"""
2017-07-01 17:05:39 +02:00
import base64
import hashlib
2017-07-01 16:14:31 +02:00
import logging
import multiprocessing
import struct
import threading
import time
2021-03-09 15:40:59 +01:00
from . import shared, structure
def _pow_worker(target, initial_hash, q):
nonce = 0
2021-03-08 16:06:07 +01:00
logging.debug(
'target: %s, initial_hash: %s',
target, base64.b16encode(initial_hash).decode())
trial_value = target + 1
while trial_value > target:
nonce += 1
2021-03-08 16:06:07 +01:00
trial_value = struct.unpack('>Q', hashlib.sha512(hashlib.sha512(
struct.pack('>Q', nonce) + initial_hash).digest()).digest()[:8])[0]
q.put(struct.pack('>Q', nonce))
def _worker(obj):
q = multiprocessing.Queue()
2021-03-08 16:06:07 +01:00
p = multiprocessing.Process(
target=_pow_worker, args=(obj.pow_target(), obj.pow_initial_hash(), q))
2021-03-08 16:06:07 +01:00
logging.debug('Starting POW process')
t = time.time()
p.start()
nonce = q.get()
p.join()
2021-03-08 16:06:07 +01:00
logging.debug(
'Finished doing POW, nonce: %s, time: %ss', nonce, time.time() - t)
obj = structure.Object(
obj.expires_time, obj.object_type, obj.version, obj.stream_number,
object_payload=obj.object_payload, nonce=nonce
)
2021-03-08 16:06:07 +01:00
logging.debug(
'Object vector is %s', base64.b16encode(obj.vector).decode())
2017-07-01 16:14:31 +02:00
shared.objects[obj.vector] = obj
shared.vector_advertise_queue.put(obj.vector)
def do_pow_and_publish(obj):
t = threading.Thread(target=_worker, args=(obj, ))
t.start()