如何在Bittorrent DHT中找到具有精确info_hash的节点?

时间:2017-08-28 18:51:05

标签: p2p bittorrent dht

在bittorrent的DHT协议文档中,给出了get_peers方法用于查找给定info_hash的节点。如果响应包含“values”键,则查询的节点返回了包含精确info_hash的节点的信息。 。如果节点返回“nodes”键,则返回最接近结果的K个节点。我们是否应该在返回的节点(最近的)上递归调用get_peers,以便到达精确节点(具有相同的info_hash)?

1 个答案:

答案 0 :(得分:0)

  

我们是否应该在返回的节点(最近)上递归调用get_peers以便到达直到具有相同info_hash的确切节点?

是,不是。如果您是LISP类型的,则可以使用递归函数。就是说,while循环将完成这项工作。这是一些实现FIND_VALUE算法并带有一些注释的python代码:

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])

此代码基于qadom's peer.py