run_dht.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import time
  2. from argparse import ArgumentParser
  3. from hivemind.dht import DHT, DHTNode
  4. from hivemind.utils.logging import get_logger, use_hivemind_log_handler
  5. from hivemind.utils.networking import log_visible_maddrs
  6. use_hivemind_log_handler("in_root_logger")
  7. logger = get_logger(__name__)
  8. async def report_status(dht: DHT, node: DHTNode):
  9. logger.info(
  10. f"{len(node.protocol.routing_table.uid_to_peer_id) + 1} DHT nodes (including this one) "
  11. f"are in the local routing table "
  12. )
  13. logger.debug(f"Routing table contents: {node.protocol.routing_table}")
  14. logger.info(f"Local storage contains {len(node.protocol.storage)} keys")
  15. logger.debug(f"Local storage contents: {node.protocol.storage}")
  16. def main():
  17. parser = ArgumentParser()
  18. parser.add_argument(
  19. "--initial_peers",
  20. nargs="*",
  21. help="Multiaddrs of the peers that will welcome you into the existing DHT. "
  22. "Example: /ip4/203.0.113.1/tcp/31337/p2p/XXXX /ip4/203.0.113.2/tcp/7777/p2p/YYYY",
  23. )
  24. parser.add_argument(
  25. "--host_maddrs",
  26. nargs="*",
  27. default=["/ip4/0.0.0.0/tcp/0"],
  28. help="Multiaddrs to listen for external connections from other DHT instances. "
  29. "Defaults to all IPv4 interfaces and the TCP protocol: /ip4/0.0.0.0/tcp/0",
  30. )
  31. parser.add_argument(
  32. "--announce_maddrs",
  33. nargs="*",
  34. help="Visible multiaddrs the host announces for external connections from other DHT instances",
  35. )
  36. parser.add_argument(
  37. "--use_ipfs",
  38. action="store_true",
  39. help='Use IPFS to find initial_peers. If enabled, you only need to provide the "/p2p/XXXX" '
  40. "part of the multiaddrs for the initial_peers "
  41. "(no need to specify a particular IPv4/IPv6 host and port)",
  42. )
  43. parser.add_argument(
  44. "--identity_path",
  45. help="Path to a private key file. If defined, makes the peer ID deterministic. "
  46. "If the file does not exist, writes a new private key to this file.",
  47. )
  48. parser.add_argument(
  49. "--refresh_period", type=int, default=30, help="Period (in seconds) for fetching the keys from DHT"
  50. )
  51. args = parser.parse_args()
  52. dht = DHT(
  53. start=True,
  54. initial_peers=args.initial_peers,
  55. host_maddrs=args.host_maddrs,
  56. announce_maddrs=args.announce_maddrs,
  57. use_ipfs=args.use_ipfs,
  58. identity_path=args.identity_path,
  59. )
  60. log_visible_maddrs(dht.get_visible_maddrs(), only_p2p=args.use_ipfs)
  61. while True:
  62. dht.run_coroutine(report_status, return_future=False)
  63. time.sleep(args.refresh_period)
  64. if __name__ == "__main__":
  65. main()