DHT InfoHash查找序列。 PeerID与InfoHash

时间:2018-10-04 12:31:24

标签: bittorrent dht kademlia

我知道在SO上的某个地方对此有一个先前的问题,但是我再也找不到它。 NodeId和InfoHash之间的关系。 下图大致正确吗?

enter image description here

背景 (无需阅读)

我正在尝试用Java实现自己的DHT / bittorrent应用程序。 我知道已经有一些出色的实现,我将永远做不到。但这纯粹是享乐主义的追求。 肯尼迪怎么说? “我们选择这样做不是因为它很容易。”

我已经征服了简单的部分,那就是编写底层套接字处理和远程过程调用语法等。 现在我要讲的是困难的部分,我必须负责任地行事并在DHT上处理传入的请求。 (维护KBuckets等)

1 个答案:

答案 0 :(得分:0)

是的,该图是正确的。这里是一些您描​​述的实现FIND_VALUE算法的python代码:

async def _get(self, key):
    """Fetch the value associated with KEY from the network"""
    uid = pack(key)
    queried = set()
    while True:
        # retrieve the k nearest peers and remove already queried peers
        peers = await self.peers((None, None), uid)
        peers = [address for address in peers if address not in queried]
        # no more peer to query, the key is not found in the dht
        if not peers:
            raise KeyError(unpack(uid))
        # query selected peers
        queries = dict()
        for address in peers:
            query = self._protocol.rpc(address, "value", uid)
            queries[address] = query
        responses = await gather(queries, return_exceptions=True)
        for (address, response) in responses.items():
            queried.add(address)
            if isinstance(response, Exception):
                continue
            elif response[0] == b"VALUE":
                value = response[1]
                if hash(value) == unpack(uid):
                    # store it
                    @h.transactional
                    def add(tr, key, value):
                        tr.add("QADOM:MAPPING", key, "value", value)

                    await self._run(add, self._hoply, key, value)
                    # 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":
                await self._welcome_peers(response[1])
            else:
                await self.blacklist(address)
                log.warning(
                    "[%r] unknown response %r from %r",
                    self._uid,
                    response[0],
                    address,

这是从qadom project peer.py中摘录的。