2017-05-25 14:59:18 +02:00
|
|
|
from queues import Queue
|
2017-05-24 16:51:49 +02:00
|
|
|
import random
|
|
|
|
|
|
|
|
from bmconfigparser import BMConfigParser
|
|
|
|
import knownnodes
|
2017-10-19 09:16:29 +02:00
|
|
|
import protocol
|
2017-08-06 21:29:54 +02:00
|
|
|
from queues import portCheckerQueue
|
2017-05-24 16:51:49 +02:00
|
|
|
import state
|
|
|
|
|
2017-08-22 13:49:27 +02:00
|
|
|
def getDiscoveredPeer():
|
2017-08-06 21:29:54 +02:00
|
|
|
try:
|
2017-08-09 17:34:47 +02:00
|
|
|
peer = random.choice(state.discoveredPeers.keys())
|
2017-08-06 21:29:54 +02:00
|
|
|
except (IndexError, KeyError):
|
|
|
|
raise ValueError
|
2017-08-09 17:34:47 +02:00
|
|
|
try:
|
|
|
|
del state.discoveredPeers[peer]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
return peer
|
2017-08-06 21:29:54 +02:00
|
|
|
|
2017-05-24 16:51:49 +02:00
|
|
|
def chooseConnection(stream):
|
2017-07-05 09:17:01 +02:00
|
|
|
haveOnion = BMConfigParser().safeGet("bitmessagesettings", "socksproxytype")[0:5] == 'SOCKS'
|
2017-05-24 16:51:49 +02:00
|
|
|
if state.trustedPeer:
|
|
|
|
return state.trustedPeer
|
2017-06-24 12:13:35 +02:00
|
|
|
try:
|
|
|
|
retval = portCheckerQueue.get(False)
|
|
|
|
portCheckerQueue.task_done()
|
2017-08-06 21:29:54 +02:00
|
|
|
return retval
|
2017-06-24 12:13:35 +02:00
|
|
|
except Queue.Empty:
|
2017-08-06 21:29:54 +02:00
|
|
|
pass
|
2017-08-22 13:49:27 +02:00
|
|
|
# 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):
|
2017-08-06 21:29:54 +02:00
|
|
|
peer = random.choice(knownnodes.knownNodes[stream].keys())
|
|
|
|
try:
|
|
|
|
rating = knownnodes.knownNodes[stream][peer]["rating"]
|
|
|
|
except TypeError:
|
|
|
|
print "Error in %s" % (peer)
|
|
|
|
rating = 0
|
2017-10-19 09:16:29 +02:00
|
|
|
if haveOnion:
|
|
|
|
# onion addresses have a higher priority when SOCKS
|
|
|
|
if peer.host.endswith('.onion') and rating > 0:
|
|
|
|
rating = 1
|
|
|
|
else:
|
|
|
|
encodedAddr = protocol.encodeHost(peer.host)
|
|
|
|
# don't connect to local IPs when using SOCKS
|
|
|
|
if not protocol.checkIPAddress(encodedAddr, False):
|
|
|
|
continue
|
2017-08-06 21:29:54 +02:00
|
|
|
if rating > 1:
|
|
|
|
rating = 1
|
2017-05-25 14:59:18 +02:00
|
|
|
try:
|
2017-08-06 21:29:54 +02:00
|
|
|
if 0.05/(1.0-rating) > random.random():
|
|
|
|
return peer
|
|
|
|
except ZeroDivisionError:
|
|
|
|
return peer
|
|
|
|
raise ValueError
|