Reference client for Bitmessage: a P2P encrypted decentralised communication protocol:
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 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