How to find nodes with exact info_hash in Bittorrent DHT?

1k views Asked by At

In the documentation of DHT protocol for bittorrent,it is given that get_peers method is used for finding nodes with given info_hash.It says that if response contains "values" key,the queried node has returned the information about nodes containing exact info_hash.If node returns "nodes" key,it has returned K nodes closest to the result.Should we recursively call get_peers on returned nodes(closest) in order to reach till exact nodes(with same info_hash)?

1

There are 1 answers

0
amirouche On

Should we recursively call get_peers on returned nodes(closest) in order to reach till exact nodes(with same info_hash)?

Yes and no. You could use a recursive function if you are the LISP kind. That said, a while loop will do the job. Here is some python code that implement the FIND_VALUE algorithm with some comments:

async def _get(self, key):
    """Fetch the value associated with KEY from the network"""
    uid = key
    queried = set()
    while True:
        # retrieve the k nearest peers and remove already queried peers
        peers = nearest(k, self.peers)
        # no more peer to query, the key is not found in the dht
        if not peers:
            raise KeyError(uid)
        # query selected peers
        responses = dict()
        for address in peers:
            response = self._protocol.rpc(address, "value", uid)
            responses[address] = response
        # check responses: look for the value or add peers more near KEY
        for (address, response) in responses.items():
            queried.add(address)
            if isinstance(response, Exception):
                continue
            elif response[0] == b"VALUE":
                # value is found, return it
                value = response[1]
                if hash(value) == unpack(uid):
                    # at last!
                    return value
                else:
                    log.warning(
                        "[%r] bad value returned from %r", self._uid, address
                    )
                    await self.blacklist(address)
                    continue
            elif response[0] == b"PEERS":
                # value not found but we got peers that are more near KEY
                await self._welcome_peers(response[1])

This code is based on qadom's peer.py