Hide bmpow output and relog it

using contextmanager found in https://stackoverflow.com/questions/5081657.
Fixes: #1571
This commit is contained in:
Dmitri Bogomolov 2021-03-17 16:47:46 +02:00
parent 7ce0180eed
commit 174dffb360
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13

View File

@ -7,6 +7,7 @@ import ctypes
import hashlib import hashlib
import os import os
import sys import sys
import tempfile
import time import time
from struct import pack, unpack from struct import pack, unpack
from subprocess import call from subprocess import call
@ -23,6 +24,42 @@ bitmsglib = 'bitmsghash.so'
bmpow = None bmpow = None
class LogOutput(object): # pylint: disable=too-few-public-methods
"""
A context manager that block stdout for its scope
and appends it's content to log before exit. Usage::
with LogOutput():
os.system('ls -l')
https://stackoverflow.com/questions/5081657
"""
def __init__(self, prefix='PoW'):
self.prefix = prefix
sys.stdout.flush()
self._stdout = sys.stdout
self._stdout_fno = os.dup(sys.stdout.fileno())
self._dst, self._filepath = tempfile.mkstemp()
def __enter__(self):
stdout = os.dup(1)
os.dup2(self._dst, 1)
os.close(self._dst)
sys.stdout = os.fdopen(stdout, 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._stdout
sys.stdout.flush()
os.dup2(self._stdout_fno, 1)
with open(self._filepath) as out:
for line in out:
logger.info('%s: %s', self.prefix, line)
os.remove(self._filepath)
def _set_idle(): def _set_idle():
if 'linux' in sys.platform: if 'linux' in sys.platform:
os.nice(20) os.nice(20)
@ -109,12 +146,14 @@ def _doFastPoW(target, initialHash):
def _doCPoW(target, initialHash): def _doCPoW(target, initialHash):
h = initialHash with LogOutput():
m = target h = initialHash
out_h = ctypes.pointer(ctypes.create_string_buffer(h, 64)) m = target
out_m = ctypes.c_ulonglong(m) out_h = ctypes.pointer(ctypes.create_string_buffer(h, 64))
logger.debug("C PoW start") out_m = ctypes.c_ulonglong(m)
nonce = bmpow(out_h, out_m) logger.debug("C PoW start")
nonce = bmpow(out_h, out_m)
trialValue, = unpack('>Q', hashlib.sha512(hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8]) trialValue, = unpack('>Q', hashlib.sha512(hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8])
if state.shutdown != 0: if state.shutdown != 0:
raise StopIteration("Interrupted") raise StopIteration("Interrupted")