PyBitmessage-2021-04-27/src/workprover/utils.py

54 lines
1.5 KiB
Python
Raw Normal View History

2018-06-23 08:57:34 +00:00
import hashlib
import math
import os
2018-06-23 11:00:24 +00:00
import struct
import sys
import time
2018-06-23 08:57:34 +00:00
def calculateInitialHash(initialPayload):
return hashlib.sha512(initialPayload).digest()
def calculateDoubleHash(data):
return hashlib.sha512(hashlib.sha512(data).digest()).digest()
# Length including nonce
def calculateTarget(length, TTL, byteDifficulty, lengthExtension):
adjustedLength = length + lengthExtension
timeEquivalent = TTL * adjustedLength / 2 ** 16
difficulty = byteDifficulty * (adjustedLength + timeEquivalent)
2018-07-23 08:01:22 +00:00
return 2 ** 64 / difficulty, difficulty
2018-06-23 08:57:34 +00:00
def checkProof(nonce, initialHash, target):
proof = nonce + initialHash
trial, = struct.unpack(">Q", calculateDoubleHash(proof)[: 8])
return trial <= target
2018-07-29 12:47:44 +00:00
def checkWorkSufficient(payload, byteDifficulty, lengthExtension, receivedTime = None):
if receivedTime is None:
receivedTime = int(time.time())
2018-06-23 08:57:34 +00:00
expiryTime, = struct.unpack(">Q", payload[8: 16])
2018-07-29 12:47:44 +00:00
minimumTTL = max(300, expiryTime - receivedTime)
2018-06-23 08:57:34 +00:00
nonce = payload[: 8]
initialHash = calculateInitialHash(payload[8: ])
2018-07-23 08:01:22 +00:00
target, difficulty = calculateTarget(len(payload), minimumTTL, byteDifficulty, lengthExtension)
2018-06-23 08:57:34 +00:00
return checkProof(nonce, initialHash, target)
2018-07-23 08:01:22 +00:00
def estimateMaximumIterationsCount(difficulty, probability):
2018-06-23 08:57:34 +00:00
coefficient = -math.log(1 - probability)
return int(coefficient * difficulty + 255) / 256 * 256
if hasattr(sys, "winver"):
getTimePoint = time.clock
else:
def getTimePoint():
return os.times()[4]