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
|
2018-03-21 14:56:27 +01:00
|
|
|
import helper_random
|
2017-05-24 16:51:49 +02:00
|
|
|
|
2017-08-22 13:49:27 +02:00
|
|
|
def getDiscoveredPeer():
|
2017-08-06 21:29:54 +02:00
|
|
|
try:
|
2018-03-21 14:56:27 +01:00
|
|
|
peer = helper_random.randomchoice(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
|
2018-03-21 14:56:27 +01:00
|
|
|
if helper_random.randomchoice((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):
|
2018-03-21 14:56:27 +01:00
|
|
|
peer = helper_random.randomchoice(knownnodes.knownNodes[stream].keys())
|
2017-08-06 21:29:54 +02:00
|
|
|
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
|