2022-09-23 00:54:12 +02:00
|
|
|
"""Doing proof of work"""
|
2017-07-01 17:05:39 +02:00
|
|
|
import base64
|
2017-07-01 15:05:06 +02:00
|
|
|
import hashlib
|
2017-07-01 16:14:31 +02:00
|
|
|
import logging
|
2017-07-01 15:05:06 +02:00
|
|
|
import multiprocessing
|
|
|
|
import struct
|
|
|
|
import threading
|
|
|
|
import time
|
|
|
|
|
2021-03-09 15:40:59 +01:00
|
|
|
from . import shared, structure
|
2017-07-01 15:05:06 +02:00
|
|
|
|
|
|
|
|
|
|
|
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())
|
2017-07-01 15:05:06 +02:00
|
|
|
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]
|
2017-07-01 15:05:06 +02:00
|
|
|
|
|
|
|
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))
|
2017-07-01 15:05:06 +02:00
|
|
|
|
2021-03-08 16:06:07 +01:00
|
|
|
logging.debug('Starting POW process')
|
2017-07-01 15:05:06 +02:00
|
|
|
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(
|
|
|
|
nonce, obj.expires_time, obj.object_type, obj.version,
|
|
|
|
obj.stream_number, obj.object_payload)
|
|
|
|
logging.debug(
|
|
|
|
'Object vector is %s', base64.b16encode(obj.vector).decode())
|
2017-07-01 16:14:31 +02:00
|
|
|
|
2017-07-01 15:05:06 +02:00
|
|
|
with shared.objects_lock:
|
|
|
|
shared.objects[obj.vector] = obj
|
|
|
|
shared.vector_advertise_queue.put(obj.vector)
|
|
|
|
|
|
|
|
|
|
|
|
def do_pow_and_publish(obj):
|
2024-10-24 20:24:54 +02:00
|
|
|
"""
|
|
|
|
Start a worker thread, doing PoW for the given object
|
|
|
|
and putting a new object and its vector into appropriate places in `shared`
|
|
|
|
to advertize to the network.
|
|
|
|
"""
|
2017-07-01 15:05:06 +02:00
|
|
|
t = threading.Thread(target=_worker, args=(obj, ))
|
|
|
|
t.start()
|