Used logger.isEnabledFor() to prevent unneeded calculations

This commit is contained in:
Dmitri Bogomolov 2019-08-07 18:31:08 +03:00
parent 7a89109fc9
commit d2a896697d
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13
4 changed files with 62 additions and 45 deletions

View File

@ -1,4 +1,5 @@
import hashlib import hashlib
import logging
import random import random
import shared import shared
import threading import threading
@ -24,10 +25,11 @@ import protocol
import queues import queues
import state import state
import tr import tr
from debug import logger
from fallback import RIPEMD160Hash from fallback import RIPEMD160Hash
import l10n import l10n
logger = logging.getLogger('default')
class objectProcessor(threading.Thread): class objectProcessor(threading.Thread):
""" """
@ -316,13 +318,14 @@ class objectProcessor(threading.Thread):
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey) '\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
ripe = RIPEMD160Hash(sha.digest()).digest() ripe = RIPEMD160Hash(sha.digest()).digest()
logger.debug( if logger.isEnabledFor(logging.DEBUG):
'within recpubkey, addressVersion: %s, streamNumber: %s' logger.debug(
'\nripe %s\npublicSigningKey in hex: %s' 'within recpubkey, addressVersion: %s, streamNumber: %s'
'\npublicEncryptionKey in hex: %s', '\nripe %s\npublicSigningKey in hex: %s'
addressVersion, streamNumber, hexlify(ripe), '\npublicEncryptionKey in hex: %s',
hexlify(publicSigningKey), hexlify(publicEncryptionKey) addressVersion, streamNumber, hexlify(ripe),
) hexlify(publicSigningKey), hexlify(publicEncryptionKey)
)
address = encodeAddress(addressVersion, streamNumber, ripe) address = encodeAddress(addressVersion, streamNumber, ripe)
@ -380,13 +383,14 @@ class objectProcessor(threading.Thread):
sha.update(publicSigningKey + publicEncryptionKey) sha.update(publicSigningKey + publicEncryptionKey)
ripe = RIPEMD160Hash(sha.digest()).digest() ripe = RIPEMD160Hash(sha.digest()).digest()
logger.debug( if logger.isEnabledFor(logging.DEBUG):
'within recpubkey, addressVersion: %s, streamNumber: %s' logger.debug(
'\nripe %s\npublicSigningKey in hex: %s' 'within recpubkey, addressVersion: %s, streamNumber: %s'
'\npublicEncryptionKey in hex: %s', '\nripe %s\npublicSigningKey in hex: %s'
addressVersion, streamNumber, hexlify(ripe), '\npublicEncryptionKey in hex: %s',
hexlify(publicSigningKey), hexlify(publicEncryptionKey) addressVersion, streamNumber, hexlify(ripe),
) hexlify(publicSigningKey), hexlify(publicEncryptionKey)
)
address = encodeAddress(addressVersion, streamNumber, ripe) address = encodeAddress(addressVersion, streamNumber, ripe)
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -579,17 +583,18 @@ class objectProcessor(threading.Thread):
logger.debug('ECDSA verify failed') logger.debug('ECDSA verify failed')
return return
logger.debug('ECDSA verify passed') logger.debug('ECDSA verify passed')
logger.debug( if logger.isEnabledFor(logging.DEBUG):
'As a matter of intellectual curiosity, here is the Bitcoin' logger.debug(
' address associated with the keys owned by the other person:' 'As a matter of intellectual curiosity, here is the Bitcoin'
' %s ..and here is the testnet address: %s. The other person' ' address associated with the keys owned by the other person:'
' must take their private signing key from Bitmessage and' ' %s ..and here is the testnet address: %s. The other person'
' import it into Bitcoin (or a service like Blockchain.info)' ' must take their private signing key from Bitmessage and'
' for it to be of any use. Do not use this unless you know' ' import it into Bitcoin (or a service like Blockchain.info)'
' what you are doing.', ' for it to be of any use. Do not use this unless you know'
helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), ' what you are doing.',
helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey) helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey),
) helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey)
)
# Used to detect and ignore duplicate messages in our inbox # Used to detect and ignore duplicate messages in our inbox
sigHash = hashlib.sha512( sigHash = hashlib.sha512(
hashlib.sha512(signature).digest()).digest()[32:] hashlib.sha512(signature).digest()).digest()[32:]

View File

@ -510,7 +510,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.timeOffset = self.timestamp - int(time.time()) self.timeOffset = self.timestamp - int(time.time())
logger.debug('remoteProtocolVersion: %i', self.remoteProtocolVersion) logger.debug('remoteProtocolVersion: %i', self.remoteProtocolVersion)
logger.debug('services: 0x%08X', self.services) logger.debug('services: 0x%08X', self.services)
logger.debug('time offset: %i', self.timestamp - int(time.time())) logger.debug('time offset: %i', self.timeOffset)
logger.debug('my external IP: %s', self.sockNode.host) logger.debug('my external IP: %s', self.sockNode.host)
logger.debug( logger.debug(
'remote node incoming address: %s:%i', 'remote node incoming address: %s:%i',

View File

@ -74,9 +74,10 @@ class Dandelion(): # pylint: disable=old-style-class
def removeHash(self, hashId, reason="no reason specified"): def removeHash(self, hashId, reason="no reason specified"):
"""Switch inventory vector from stem to fluff mode""" """Switch inventory vector from stem to fluff mode"""
logger.debug( if logger.isEnabledFor(logging.DEBUG):
"%s entering fluff mode due to %s.", logger.debug(
''.join('%02x' % ord(i) for i in hashId), reason) '%s entering fluff mode due to %s.',
''.join('%02x' % ord(i) for i in hashId), reason)
with self.lock: with self.lock:
try: try:
del self.hashMap[hashId] del self.hashMap[hashId]

View File

@ -39,12 +39,13 @@ else:
sslProtocolCiphers = "AECDH-AES256-SHA" sslProtocolCiphers = "AECDH-AES256-SHA"
class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instance-attributes class TLSDispatcher(AdvancedDispatcher):
"""TLS functionality for classes derived from AdvancedDispatcher""" """TLS functionality for classes derived from AdvancedDispatcher"""
# pylint: disable=too-many-arguments, super-init-not-called, unused-argument # pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-arguments,super-init-not-called,unused-argument
def __init__( def __init__(
self, address=None, sock=None, certfile=None, keyfile=None, self, address=None, sock=None, certfile=None, keyfile=None,
server_side=False, ciphers=sslProtocolCiphers server_side=False, ciphers=sslProtocolCiphers
): ):
self.want_read = self.want_write = True self.want_read = self.want_write = True
if certfile is None: if certfile is None:
@ -96,7 +97,10 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc
@staticmethod @staticmethod
def state_tls_handshake(): def state_tls_handshake():
"""Do nothing while TLS handshake is pending, as during this phase we need to react to callbacks instead""" """
Do nothing while TLS handshake is pending, as during this phase
we need to react to callbacks instead
"""
return False return False
def writable(self): def writable(self):
@ -122,10 +126,11 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc
except AttributeError: except AttributeError:
return AdvancedDispatcher.readable(self) return AdvancedDispatcher.readable(self)
def handle_read(self): # pylint: disable=inconsistent-return-statements def handle_read(self): # pylint: disable=inconsistent-return-statements
""" """
Handle reads for sockets during TLS handshake. Requires special treatment as during the handshake, buffers must Handle reads for sockets during TLS handshake. Requires special
remain empty and normal reads must be ignored treatment as during the handshake, buffers must remain empty
and normal reads must be ignored.
""" """
try: try:
# wait for write buffer flush # wait for write buffer flush
@ -147,10 +152,11 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc
self.handle_close() self.handle_close()
return return
def handle_write(self): # pylint: disable=inconsistent-return-statements def handle_write(self): # pylint: disable=inconsistent-return-statements
""" """
Handle writes for sockets during TLS handshake. Requires special treatment as during the handshake, buffers Handle writes for sockets during TLS handshake. Requires special
must remain empty and normal writes must be ignored treatment as during the handshake, buffers must remain empty
and normal writes must be ignored.
""" """
try: try:
# wait for write buffer flush # wait for write buffer flush
@ -193,18 +199,23 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc
if not (self.want_write or self.want_read): if not (self.want_write or self.want_read):
raise raise
except socket.error as err: except socket.error as err:
if err.errno in asyncore._DISCONNECTED: # pylint: disable=protected-access # pylint: disable=protected-access
if err.errno in asyncore._DISCONNECTED:
self.handle_close() self.handle_close()
else: else:
raise raise
else: else:
if sys.version_info >= (2, 7, 9): if sys.version_info >= (2, 7, 9):
self.tlsVersion = self.sslSocket.version() self.tlsVersion = self.sslSocket.version()
logger.debug("%s:%i: TLS handshake success, TLS protocol version: %s", logger.debug(
self.destination.host, self.destination.port, self.sslSocket.version()) '%s:%i: TLS handshake success, TLS protocol version: %s',
self.destination.host, self.destination.port,
self.tlsVersion)
else: else:
self.tlsVersion = "TLSv1" self.tlsVersion = "TLSv1"
logger.debug("%s:%i: TLS handshake success", self.destination.host, self.destination.port) logger.debug(
'%s:%i: TLS handshake success',
self.destination.host, self.destination.port)
# The handshake has completed, so remove this channel and... # The handshake has completed, so remove this channel and...
self.del_channel() self.del_channel()
self.set_socket(self.sslSocket) self.set_socket(self.sslSocket)