在 BitTorrent 中的 DHT 协议文档中,指出了使用 get_peers 方法来查找包含所需 info_hash 的节点。如果响应包含“values”键,则查询的节点已经返回关于包含完全相同 info_hash 的节点的信息。如果节点返回“nodes”键,则返回了 K 个最接近结果的节点。我们需要递归调用返回的节点(最接近的节点)的 get_peers 方法,以达到查找具有相同 info_hash 的节点的目的吗?
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