lbry-sdk/lbrynet/dht/peerfinder.py

65 lines
2.3 KiB
Python
Raw Normal View History

2015-08-20 17:27:15 +02:00
import binascii
2016-11-03 20:42:45 +01:00
import logging
from twisted.internet import defer
from lbrynet import conf
2015-08-20 17:27:15 +02:00
2016-11-03 20:42:45 +01:00
log = logging.getLogger(__name__)
2018-02-15 22:49:00 +01:00
class DummyPeerFinder(object):
"""This class finds peers which have announced to the DHT that they have certain blobs"""
def find_peers_for_blob(self, blob_hash, timeout=None, filter_self=True):
2018-02-15 22:49:00 +01:00
return defer.succeed([])
class DHTPeerFinder(DummyPeerFinder):
2015-08-20 17:27:15 +02:00
"""This class finds peers which have announced to the DHT that they have certain blobs"""
#implements(IPeerFinder)
2015-08-20 17:27:15 +02:00
def __init__(self, dht_node, peer_manager):
"""
dht_node - an instance of dht.Node class
peer_manager - an instance of PeerManager class
"""
2015-08-20 17:27:15 +02:00
self.dht_node = dht_node
self.peer_manager = peer_manager
2018-07-06 02:38:52 +02:00
self.peers = {}
2015-08-20 17:27:15 +02:00
@defer.inlineCallbacks
def find_peers_for_blob(self, blob_hash, timeout=None, filter_self=True):
"""
Find peers for blob in the DHT
blob_hash (str): blob hash to look for
timeout (int): seconds to timeout after
filter_self (bool): if True, and if a peer for a blob is itself, filter it
from the result
Returns:
list of peers for the blob
"""
2018-07-06 02:38:52 +02:00
if blob_hash not in self.peers:
self.peers[blob_hash] = [(self.dht_node.externalIP, self.dht_node.peerPort)]
2015-08-20 17:27:15 +02:00
bin_hash = binascii.unhexlify(blob_hash)
2018-07-06 02:38:52 +02:00
finished_deferred = self.dht_node.iterativeFindValue(bin_hash, exclude=self.peers[blob_hash])
timeout = timeout or conf.settings['peer_search_timeout']
if timeout:
finished_deferred.addTimeout(timeout, self.dht_node.clock)
try:
peer_list = yield finished_deferred
except defer.TimeoutError:
log.debug("DHT timed out while looking peers for blob %s after %s seconds",
blob_hash, timeout)
peer_list = []
peers = set(peer_list)
results = []
for node_id, host, port in peers:
if filter_self and (host, port) == (self.dht_node.externalIP, self.dht_node.peerPort):
continue
results.append(self.peer_manager.get_peer(host, port))
2018-07-06 02:38:52 +02:00
self.peers[blob_hash].append((host, port))
defer.returnValue(results)