Onionr/onionr/onionrproofs/__init__.py

252 lines
8.3 KiB
Python
Raw Normal View History

2018-02-22 22:55:42 +00:00
'''
Onionr - Private P2P Communication
2018-02-22 22:55:42 +00:00
Proof of work module
'''
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
import multiprocessing, time, math, threading, binascii, sys, json
import nacl.encoding, nacl.hash, nacl.utils
import config, logger
from onionrblocks import onionrblockapi, storagecounter
from onionrutils import bytesconverter
2019-07-20 00:01:16 +00:00
from onionrcrypto import hashers
2019-06-16 06:06:32 +00:00
config.reload()
2019-08-13 19:51:46 +00:00
2019-07-19 19:49:56 +00:00
def getDifficultyModifier():
'''returns the difficulty modifier for block storage based
2018-12-24 06:12:46 +00:00
on a variety of factors, currently only disk use.
'''
percentUse = storagecounter.StorageCounter().get_percent()
2019-08-13 20:10:58 +00:00
difficultyIncrease = math.floor(4 * percentUse) # difficulty increase is a step function
2018-12-24 06:12:46 +00:00
2019-08-13 19:51:46 +00:00
return difficultyIncrease
2018-12-24 06:12:46 +00:00
def getDifficultyForNewBlock(data):
2018-12-24 06:12:46 +00:00
'''
Get difficulty for block. Accepts size in integer, Block instance, or str/bytes full block contents
'''
if isinstance(data, onionrblockapi.Block):
dataSizeInBytes = len(bytesconverter.str_to_bytes(data.getRaw()))
2018-12-24 06:12:46 +00:00
else:
dataSizeInBytes = len(bytesconverter.str_to_bytes(data))
minDifficulty = config.get('general.minimum_send_pow', 4)
totalDifficulty = max(minDifficulty, math.floor(dataSizeInBytes / 1000000.0)) + getDifficultyModifier()
2018-12-24 06:12:46 +00:00
return totalDifficulty
2019-02-17 05:20:47 +00:00
2018-12-24 06:12:46 +00:00
return retData
2018-11-11 02:10:58 +00:00
def getHashDifficulty(h: str):
2018-11-11 02:10:58 +00:00
'''
Return the amount of leading zeroes in a hex hash string (hexHash)
2018-11-11 02:10:58 +00:00
'''
return len(h) - len(h.lstrip('0'))
2018-11-11 02:10:58 +00:00
2019-08-13 20:18:43 +00:00
def hashMeetsDifficulty(hexHash):
2018-11-11 02:10:58 +00:00
'''
Return bool for a hash string to see if it meets pow difficulty defined in config
'''
2019-08-13 20:18:43 +00:00
hashDifficulty = getHashDifficulty(hexHash)
2018-12-09 17:29:39 +00:00
try:
expected = int(config.get('general.minimum_block_pow'))
except TypeError:
raise ValueError('Missing general.minimum_block_pow config')
2019-08-13 20:18:43 +00:00
return hashDifficulty >= expected
2018-04-23 03:49:53 +00:00
class DataPOW:
2019-08-14 00:12:45 +00:00
def __init__(self, data, minDifficulty = 0, threadCount = 1):
self.data = data
self.threadCount = threadCount
2019-08-14 00:12:45 +00:00
self.difficulty = max(minDifficulty, getDifficultyForNewBlock(data))
2018-12-24 06:12:46 +00:00
self.rounds = 0
2019-07-22 05:24:42 +00:00
self.hashing = False
2019-08-14 00:12:45 +00:00
self.foundHash = False
try:
self.data = self.data.encode()
except AttributeError:
pass
self.data = nacl.hash.blake2b(self.data)
logger.info('Computing POW (difficulty: %s)...' % self.difficulty)
self.mainHash = '0' * 70
self.puzzle = self.mainHash[0:min(self.difficulty, len(self.mainHash))]
for i in range(max(1, threadCount)):
2019-07-24 18:10:37 +00:00
t = threading.Thread(name = 'thread%s' % i, target = self.pow, args = (True,))
t.start()
2019-07-19 19:49:56 +00:00
def pow(self, reporting = False):
startTime = math.floor(time.time())
self.hashing = True
self.reporting = reporting
iFound = False # if current thread is the one that found the answer
while self.hashing:
rand = nacl.utils.random()
token = nacl.hash.blake2b(rand + self.data).decode()
2018-12-24 06:12:46 +00:00
self.rounds += 1
#print(token)
if self.puzzle == token[0:self.difficulty]:
self.hashing = False
iFound = True
break
if iFound:
endTime = math.floor(time.time())
if self.reporting:
logger.debug('Found token after %s seconds: %s' % (endTime - startTime, token), timestamp=True)
2018-12-24 06:12:46 +00:00
logger.debug('Round count: %s' % (self.rounds,))
self.result = (token, rand)
def shutdown(self):
self.hashing = False
self.puzzle = ''
def changeDifficulty(self, newDiff):
self.difficulty = newDiff
def getResult(self):
'''
Returns the result then sets to false, useful to automatically clear the result
'''
try:
retVal = self.result
except AttributeError:
retVal = False
self.result = False
return retVal
def waitForResult(self):
'''
Returns the result only when it has been found, False if not running and not found
'''
result = False
try:
while True:
result = self.getResult()
if not self.hashing:
break
else:
2019-02-10 18:43:45 +00:00
time.sleep(1)
except KeyboardInterrupt:
self.shutdown()
logger.warn('Got keyboard interrupt while waiting for POW result, stopping')
return result
2018-02-22 22:55:42 +00:00
class POW:
2019-08-14 00:12:45 +00:00
def __init__(self, metadata, data, threadCount = 1, minDifficulty=0):
2018-02-22 22:55:42 +00:00
self.foundHash = False
2018-05-05 20:07:32 +00:00
self.difficulty = 0
self.data = data
2018-07-08 07:51:23 +00:00
self.metadata = metadata
self.threadCount = threadCount
2019-07-22 05:24:42 +00:00
self.hashing = False
2018-05-05 20:07:32 +00:00
json_metadata = json.dumps(metadata).encode()
2018-05-05 20:07:32 +00:00
try:
self.data = self.data.encode()
except AttributeError:
pass
2019-08-14 00:12:45 +00:00
if minDifficulty > 0:
self.difficulty = minDifficulty
2018-12-24 06:12:46 +00:00
else:
# Calculate difficulty. Dumb for now, may use good algorithm in the future.
2019-07-19 19:49:56 +00:00
self.difficulty = getDifficultyForNewBlock(bytes(json_metadata + b'\n' + self.data))
2018-12-24 06:12:46 +00:00
2019-07-19 19:49:56 +00:00
logger.info('Computing POW (difficulty: %s)...' % (self.difficulty,))
2018-02-22 22:55:42 +00:00
2018-07-08 07:51:23 +00:00
self.mainHash = '0' * 64
self.puzzle = self.mainHash[0:min(self.difficulty, len(self.mainHash))]
2018-12-24 06:12:46 +00:00
for i in range(max(1, threadCount)):
2019-07-24 18:10:37 +00:00
t = threading.Thread(name = 'thread%s' % i, target = self.pow, args = (True,))
t.start()
2018-02-22 22:55:42 +00:00
2019-07-19 19:49:56 +00:00
def pow(self, reporting = False):
2018-06-20 20:56:28 +00:00
startTime = math.floor(time.time())
self.hashing = True
self.reporting = reporting
iFound = False # if current thread is the one that found the answer
nonce = int(binascii.hexlify(nacl.utils.random(64)), 16)
2018-06-20 20:56:28 +00:00
while self.hashing:
2018-07-08 07:51:23 +00:00
#token = nacl.hash.blake2b(rand + self.data).decode()
2019-04-04 21:56:18 +00:00
self.metadata['pow'] = nonce
2018-07-08 07:51:23 +00:00
payload = json.dumps(self.metadata).encode() + b'\n' + self.data
2019-07-20 00:01:16 +00:00
token = hashers.sha3_hash(payload)
try:
# on some versions, token is bytes
token = token.decode()
except AttributeError:
pass
2018-06-20 20:56:28 +00:00
if self.puzzle == token[0:self.difficulty]:
self.hashing = False
iFound = True
2018-07-08 07:51:23 +00:00
self.result = payload
2018-06-20 20:56:28 +00:00
break
2019-02-17 05:20:47 +00:00
nonce += 1
2018-06-20 20:56:28 +00:00
if iFound:
endTime = math.floor(time.time())
if self.reporting:
logger.debug('Found token after %s seconds: %s' % (endTime - startTime, token), timestamp=True)
2018-02-22 22:55:42 +00:00
def shutdown(self):
self.hashing = False
2018-02-26 02:30:43 +00:00
self.puzzle = ''
2018-04-19 01:47:35 +00:00
2018-02-26 02:30:43 +00:00
def changeDifficulty(self, newDiff):
self.difficulty = newDiff
def getResult(self):
2018-04-23 03:49:53 +00:00
'''
Returns the result then sets to false, useful to automatically clear the result
'''
2018-02-26 02:30:43 +00:00
try:
retVal = self.result
except AttributeError:
retVal = False
2018-02-26 02:30:43 +00:00
self.result = False
2018-04-19 01:47:35 +00:00
return retVal
2018-06-20 20:56:28 +00:00
def waitForResult(self):
'''
Returns the result only when it has been found, False if not running and not found
'''
result = False
try:
while True:
result = self.getResult()
if not self.hashing:
break
else:
2019-02-10 18:43:45 +00:00
time.sleep(1)
2018-06-20 20:56:28 +00:00
except KeyboardInterrupt:
self.shutdown()
logger.warn('Got keyboard interrupt while waiting for POW result, stopping')
return result