Dmitri Bogomolov 7a89109fc9
New logging approach in order to reduce imports from submodules
and use logging without risk of circular import. Only subpackage
that imports from debug is bitmessageqt - because it also uses
Instead of from debug import logger is now recommended to use:

import logging

logger = logging.getLogger('default')

All subclasses of StoppableThread now have a logger attribute.
All threading related stuff except for set_thread_name()
was moved from helper_threading to network.threads.

Fixed two my mistakes from previous edit of debug in a1a8d3a:

 - logger.handlers is not dict but iterable
 - sys.excepthook should be set unconditionally
2019-10-18 09:35:24 +03:00

69 lines
2.1 KiB

# pylint: disable=too-many-branches
import logging
import random # nosec
import knownnodes
import protocol
import state
from bmconfigparser import BMConfigParser
from queues import Queue, portCheckerQueue
logger = logging.getLogger('default')
def getDiscoveredPeer():
peer = random.choice(state.discoveredPeers.keys())
except (IndexError, KeyError):
raise ValueError
del state.discoveredPeers[peer]
except KeyError:
return peer
def chooseConnection(stream):
haveOnion = BMConfigParser().safeGet(
"bitmessagesettings", "socksproxytype")[0:5] == 'SOCKS'
if state.trustedPeer:
return state.trustedPeer
retval = portCheckerQueue.get(False)
return retval
except Queue.Empty:
# with a probability of 0.5, connect to a discovered peer
if random.choice((False, True)) and not haveOnion:
# discovered peers are already filtered by allowed streams
return getDiscoveredPeer()
for _ in range(50):
peer = random.choice(knownnodes.knownNodes[stream].keys())
peer_info = knownnodes.knownNodes[stream][peer]
if peer_info.get('self'):
rating = peer_info["rating"]
except TypeError:
logger.warning('Error in %s', peer)
rating = 0
if haveOnion:
# onion addresses have a higher priority when SOCKS
if'.onion') and rating > 0:
rating = 1
# TODO: need better check
elif not'bootstrap'):
encodedAddr = protocol.encodeHost(
# don't connect to local IPs when using SOCKS
if not protocol.checkIPAddress(encodedAddr, False):
if rating > 1:
rating = 1
if 0.05 / (1.0 - rating) > random.random():
return peer
except ZeroDivisionError:
return peer
raise ValueError