2

我知道在 SO 的某个地方之前有一个关于这个的问题,但我找不到了。NodeId和InfoHash的关系。下图大致正确吗?

在此处输入图像描述

背景 (无需阅读)

我正在尝试用 Java 实现我自己的 DHT/bittorrent 应用程序。我知道已经有一些我永远不会更好的优秀实现。但这纯粹是一种享乐主义的追求。肯尼迪说了什么?“我们选择这样做不是因为它很容易......”

我已经克服了简单的部分,即编写低级套接字处理和远程过程调用语法等。现在我进入了困难的部分,我必须负责任地行事并为 DHT 上的传入请求提供服务。(维护 KBucket 等)

4

1 回答 1

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 项目 peer.py的摘录。

于 2019-05-30T13:30:25.963 回答