PyBitmessage-2021-04-27/src/network/connectionchooser.py

67 lines
2.1 KiB
Python
Raw Normal View History

# pylint: disable=too-many-branches
2019-07-29 14:54:19 +02:00
import random # nosec
import knownnodes
import protocol
import state
2019-07-29 14:54:19 +02:00
from bmconfigparser import BMConfigParser
from debug import logger
from queues import Queue, portCheckerQueue
2017-08-22 13:49:27 +02:00
def getDiscoveredPeer():
try:
2019-07-29 14:54:19 +02:00
peer = random.choice(state.discoveredPeers.keys())
except (IndexError, KeyError):
raise ValueError
try:
del state.discoveredPeers[peer]
except KeyError:
pass
return peer
2019-07-29 14:54:19 +02:00
def chooseConnection(stream):
2019-07-29 14:54:19 +02:00
haveOnion = BMConfigParser().safeGet(
"bitmessagesettings", "socksproxytype")[0:5] == 'SOCKS'
if state.trustedPeer:
return state.trustedPeer
2017-06-24 12:13:35 +02:00
try:
retval = portCheckerQueue.get(False)
portCheckerQueue.task_done()
return retval
2017-06-24 12:13:35 +02:00
except Queue.Empty:
pass
2017-08-22 13:49:27 +02:00
# with a probability of 0.5, connect to a discovered peer
2019-07-29 14:54:19 +02:00
if random.choice((False, True)) and not haveOnion:
2017-08-22 13:49:27 +02:00
# discovered peers are already filtered by allowed streams
return getDiscoveredPeer()
for _ in range(50):
2019-07-29 14:54:19 +02:00
peer = random.choice(knownnodes.knownNodes[stream].keys())
try:
peer_info = knownnodes.knownNodes[stream][peer]
if peer_info.get('self'):
continue
rating = peer_info["rating"]
except TypeError:
2019-07-29 14:54:19 +02:00
logger.warning('Error in %s', peer)
rating = 0
if haveOnion:
# onion addresses have a higher priority when SOCKS
if peer.host.endswith('.onion') and rating > 0:
rating = 1
2019-07-12 17:19:06 +02:00
# TODO: need better check
elif not peer.host.startswith('bootstrap'):
encodedAddr = protocol.encodeHost(peer.host)
# don't connect to local IPs when using SOCKS
if not protocol.checkIPAddress(encodedAddr, False):
continue
if rating > 1:
rating = 1
try:
2019-07-29 14:54:19 +02:00
if 0.05 / (1.0 - rating) > random.random():
return peer
except ZeroDivisionError:
return peer
raise ValueError