librats 1.0.1 → 2.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (313) hide show
  1. package/README.md +137 -332
  2. package/binding.gyp +16 -3
  3. package/lib/index.d.ts +271 -696
  4. package/lib/index.js +383 -44
  5. package/native-src/3rdparty/android/ifaddrs-android.c +1 -0
  6. package/native-src/3rdparty/android/ifaddrs-android.h +1 -0
  7. package/native-src/CMakeLists.txt +396 -179
  8. package/native-src/LICENSE +1 -1
  9. package/native-src/src/librats/bindings/rats.cpp +731 -0
  10. package/native-src/src/librats/bindings/rats.h +352 -0
  11. package/native-src/src/librats/bittorrent/bencode.cpp +437 -0
  12. package/native-src/src/librats/bittorrent/bencode.h +176 -0
  13. package/native-src/src/librats/bittorrent/bitfield.cpp +97 -0
  14. package/native-src/src/librats/bittorrent/bitfield.h +76 -0
  15. package/native-src/src/librats/bittorrent/byte_io.h +58 -0
  16. package/native-src/src/librats/bittorrent/choker.cpp +25 -0
  17. package/native-src/src/librats/bittorrent/choker.h +46 -0
  18. package/native-src/src/librats/bittorrent/client.cpp +413 -0
  19. package/native-src/src/librats/bittorrent/client.h +227 -0
  20. package/native-src/src/librats/bittorrent/disk_io.cpp +209 -0
  21. package/native-src/src/librats/bittorrent/disk_io.h +150 -0
  22. package/native-src/src/librats/bittorrent/extensions.cpp +191 -0
  23. package/native-src/src/librats/bittorrent/extensions.h +94 -0
  24. package/native-src/src/librats/bittorrent/file_storage.cpp +77 -0
  25. package/native-src/src/librats/bittorrent/file_storage.h +79 -0
  26. package/native-src/src/librats/bittorrent/log.h +42 -0
  27. package/native-src/src/librats/bittorrent/magnet_uri.cpp +98 -0
  28. package/native-src/src/librats/bittorrent/magnet_uri.h +35 -0
  29. package/native-src/src/librats/bittorrent/peer_connection.cpp +502 -0
  30. package/native-src/src/librats/bittorrent/peer_connection.h +194 -0
  31. package/native-src/src/librats/bittorrent/peer_list.cpp +68 -0
  32. package/native-src/src/librats/bittorrent/peer_list.h +75 -0
  33. package/native-src/src/librats/bittorrent/piece_picker.cpp +352 -0
  34. package/native-src/src/librats/bittorrent/piece_picker.h +201 -0
  35. package/native-src/src/librats/bittorrent/reactor.cpp +97 -0
  36. package/native-src/src/librats/bittorrent/reactor.h +89 -0
  37. package/native-src/src/librats/bittorrent/resume_data.cpp +72 -0
  38. package/native-src/src/librats/bittorrent/resume_data.h +41 -0
  39. package/native-src/src/librats/bittorrent/store_buffer.cpp +48 -0
  40. package/native-src/src/librats/bittorrent/store_buffer.h +47 -0
  41. package/native-src/src/librats/bittorrent/torrent.cpp +870 -0
  42. package/native-src/src/librats/bittorrent/torrent.h +260 -0
  43. package/native-src/src/librats/bittorrent/torrent_creator.cpp +129 -0
  44. package/native-src/src/librats/bittorrent/torrent_creator.h +58 -0
  45. package/native-src/src/librats/bittorrent/torrent_info.cpp +314 -0
  46. package/native-src/src/librats/bittorrent/torrent_info.h +118 -0
  47. package/native-src/src/librats/bittorrent/tracker.cpp +374 -0
  48. package/native-src/src/librats/bittorrent/tracker.h +108 -0
  49. package/native-src/src/librats/bittorrent/types.cpp +206 -0
  50. package/native-src/src/librats/bittorrent/types.h +86 -0
  51. package/native-src/src/librats/core/address.cpp +35 -0
  52. package/native-src/src/librats/core/address.h +78 -0
  53. package/native-src/src/librats/core/bytes.h +69 -0
  54. package/native-src/src/librats/core/chained_send_buffer.cpp +172 -0
  55. package/native-src/src/librats/core/chained_send_buffer.h +183 -0
  56. package/native-src/src/librats/core/endpoint_parse.cpp +41 -0
  57. package/native-src/src/librats/core/endpoint_parse.h +31 -0
  58. package/native-src/src/librats/core/event_bus.h +70 -0
  59. package/native-src/src/librats/core/host_endpoint.h +56 -0
  60. package/native-src/src/{io_poller.cpp → librats/core/io_poller.cpp} +520 -65
  61. package/native-src/src/{io_poller.h → librats/core/io_poller.h} +12 -6
  62. package/native-src/src/librats/core/ip_address.cpp +120 -0
  63. package/native-src/src/librats/core/ip_address.h +109 -0
  64. package/native-src/src/librats/core/mpsc_queue.h +47 -0
  65. package/native-src/src/librats/core/notifier.h +74 -0
  66. package/native-src/src/librats/core/receive_buffer.cpp +219 -0
  67. package/native-src/src/librats/core/receive_buffer.h +171 -0
  68. package/native-src/src/librats/core/service_registry.h +58 -0
  69. package/native-src/src/{socket.cpp → librats/core/socket.cpp} +625 -118
  70. package/native-src/src/librats/core/socket.h +496 -0
  71. package/native-src/src/librats/core/timer_queue.h +105 -0
  72. package/native-src/src/librats/core/types.cpp +42 -0
  73. package/native-src/src/librats/core/types.h +93 -0
  74. package/native-src/src/librats/core/wakeup_pipe.h +83 -0
  75. package/native-src/src/{crypto → librats/crypto}/blake2_endian.h +21 -23
  76. package/native-src/src/{crypto → librats/crypto}/blake2b.c +34 -33
  77. package/native-src/src/{crypto → librats/crypto}/blake2b.h +7 -6
  78. package/native-src/src/{crypto → librats/crypto}/blake2s.c +55 -54
  79. package/native-src/src/{crypto → librats/crypto}/blake2s.h +13 -12
  80. package/native-src/src/{crypto → librats/crypto}/chacha.c +22 -21
  81. package/native-src/src/{crypto → librats/crypto}/chacha.h +14 -13
  82. package/native-src/src/{crypto → librats/crypto}/chachapoly.c +56 -56
  83. package/native-src/src/{crypto → librats/crypto}/chachapoly.h +24 -17
  84. package/native-src/src/{crc32.cpp → librats/crypto/crc32.cpp} +1 -1
  85. package/native-src/src/{crc32.h → librats/crypto/crc32.h} +3 -1
  86. package/native-src/src/{crypto → librats/crypto}/curve25519.c +6 -4
  87. package/native-src/src/{crypto → librats/crypto}/curve25519.h +6 -3
  88. package/native-src/src/librats/crypto/hkdf.c +266 -0
  89. package/native-src/src/{crypto → librats/crypto}/hkdf.h +19 -19
  90. package/native-src/src/{noise.cpp → librats/crypto/noise.cpp} +84 -73
  91. package/native-src/src/{noise.h → librats/crypto/noise.h} +18 -8
  92. package/native-src/src/{crypto → librats/crypto}/poly1305.c +47 -46
  93. package/native-src/src/librats/crypto/poly1305.h +37 -0
  94. package/native-src/src/{sha1.cpp → librats/crypto/sha1.cpp} +33 -1
  95. package/native-src/src/{sha1.h → librats/crypto/sha1.h} +14 -6
  96. package/native-src/src/{crypto → librats/crypto}/sha256.c +15 -14
  97. package/native-src/src/{crypto → librats/crypto}/sha256.h +8 -7
  98. package/native-src/src/{crypto → librats/crypto}/sha512.c +15 -14
  99. package/native-src/src/{crypto → librats/crypto}/sha512.h +8 -7
  100. package/native-src/src/librats/dht/announce.cpp +37 -0
  101. package/native-src/src/librats/dht/announce.h +41 -0
  102. package/native-src/src/librats/dht/bep42.cpp +109 -0
  103. package/native-src/src/librats/dht/bep42.h +48 -0
  104. package/native-src/src/librats/dht/dht.cpp +501 -0
  105. package/native-src/src/librats/dht/dht.h +119 -0
  106. package/native-src/src/librats/dht/dht_runner.cpp +103 -0
  107. package/native-src/src/librats/dht/dht_runner.h +71 -0
  108. package/native-src/src/librats/dht/dos_blocker.cpp +42 -0
  109. package/native-src/src/librats/dht/dos_blocker.h +47 -0
  110. package/native-src/src/librats/dht/find_peers.cpp +52 -0
  111. package/native-src/src/librats/dht/find_peers.h +73 -0
  112. package/native-src/src/librats/dht/id.h +167 -0
  113. package/native-src/src/{krpc.cpp → librats/dht/krpc.cpp} +32 -69
  114. package/native-src/src/{krpc.h → librats/dht/krpc.h} +19 -23
  115. package/native-src/src/librats/dht/log.h +38 -0
  116. package/native-src/src/librats/dht/node.cpp +473 -0
  117. package/native-src/src/librats/dht/node.h +164 -0
  118. package/native-src/src/librats/dht/node_entry.h +81 -0
  119. package/native-src/src/librats/dht/observer.h +72 -0
  120. package/native-src/src/librats/dht/persistence.cpp +90 -0
  121. package/native-src/src/librats/dht/persistence.h +32 -0
  122. package/native-src/src/librats/dht/routing_table.cpp +559 -0
  123. package/native-src/src/librats/dht/routing_table.h +185 -0
  124. package/native-src/src/librats/dht/rpc_manager.cpp +127 -0
  125. package/native-src/src/librats/dht/rpc_manager.h +77 -0
  126. package/native-src/src/librats/dht/storage.cpp +92 -0
  127. package/native-src/src/librats/dht/storage.h +74 -0
  128. package/native-src/src/librats/dht/transport.h +27 -0
  129. package/native-src/src/librats/dht/traversal.cpp +326 -0
  130. package/native-src/src/librats/dht/traversal.h +120 -0
  131. package/native-src/src/librats/dht/udp_transport.cpp +49 -0
  132. package/native-src/src/librats/dht/udp_transport.h +51 -0
  133. package/native-src/src/librats/mdns/log.h +22 -0
  134. package/native-src/src/{mdns.cpp → librats/mdns/mdns.cpp} +75 -40
  135. package/native-src/src/{mdns.h → librats/mdns/mdns.h} +9 -8
  136. package/native-src/src/{natpmp.cpp → librats/nat/natpmp.cpp} +12 -9
  137. package/native-src/src/{natpmp.h → librats/nat/natpmp.h} +3 -3
  138. package/native-src/src/{port_mapping.h → librats/nat/port_mapping.h} +3 -2
  139. package/native-src/src/{stun.cpp → librats/nat/stun.cpp} +4 -4
  140. package/native-src/src/{stun.h → librats/nat/stun.h} +1 -1
  141. package/native-src/src/{upnp.cpp → librats/nat/upnp.cpp} +6 -6
  142. package/native-src/src/{upnp.h → librats/nat/upnp.h} +2 -2
  143. package/native-src/src/librats/node/config.h +110 -0
  144. package/native-src/src/librats/node/dial_service.h +54 -0
  145. package/native-src/src/librats/node/dialer.cpp +264 -0
  146. package/native-src/src/librats/node/dialer.h +188 -0
  147. package/native-src/src/librats/node/host_events.h +26 -0
  148. package/native-src/src/librats/node/identify.cpp +130 -0
  149. package/native-src/src/librats/node/identify.h +71 -0
  150. package/native-src/src/librats/node/nat_status.cpp +103 -0
  151. package/native-src/src/librats/node/nat_status.h +118 -0
  152. package/native-src/src/librats/node/node.cpp +826 -0
  153. package/native-src/src/librats/node/node.h +333 -0
  154. package/native-src/src/librats/node/node_context.h +33 -0
  155. package/native-src/src/librats/node/peer_network.h +91 -0
  156. package/native-src/src/librats/peer/peer.h +49 -0
  157. package/native-src/src/librats/peer/peer_book.cpp +181 -0
  158. package/native-src/src/librats/peer/peer_book.h +88 -0
  159. package/native-src/src/librats/peer/peer_id.cpp +72 -0
  160. package/native-src/src/librats/peer/peer_id.h +62 -0
  161. package/native-src/src/librats/peer/peer_info.h +37 -0
  162. package/native-src/src/librats/peer/peer_table.cpp +137 -0
  163. package/native-src/src/librats/peer/peer_table.h +148 -0
  164. package/native-src/src/librats/security/handshaker.h +66 -0
  165. package/native-src/src/librats/security/identity.h +43 -0
  166. package/native-src/src/librats/security/noise_security.cpp +122 -0
  167. package/native-src/src/librats/security/noise_security.h +37 -0
  168. package/native-src/src/librats/security/plaintext_security.h +106 -0
  169. package/native-src/src/librats/security/session.h +37 -0
  170. package/native-src/src/{storage.cpp → librats/storage/storage.cpp} +369 -522
  171. package/native-src/src/{storage.h → librats/storage/storage.h} +135 -299
  172. package/native-src/src/librats/subsystems/bittorrent.cpp +211 -0
  173. package/native-src/src/librats/subsystems/bittorrent.h +136 -0
  174. package/native-src/src/librats/subsystems/dht_discovery.cpp +202 -0
  175. package/native-src/src/librats/subsystems/dht_discovery.h +123 -0
  176. package/native-src/src/librats/subsystems/dht_service.h +36 -0
  177. package/native-src/src/librats/subsystems/file_transfer.cpp +972 -0
  178. package/native-src/src/librats/subsystems/file_transfer.h +367 -0
  179. package/native-src/src/librats/subsystems/hole_punch.cpp +532 -0
  180. package/native-src/src/librats/subsystems/hole_punch.h +266 -0
  181. package/native-src/src/librats/subsystems/hole_punch_service.h +38 -0
  182. package/native-src/src/librats/subsystems/mdns_discovery.cpp +66 -0
  183. package/native-src/src/librats/subsystems/mdns_discovery.h +55 -0
  184. package/native-src/src/librats/subsystems/message_json.cpp +112 -0
  185. package/native-src/src/librats/subsystems/message_json.h +88 -0
  186. package/native-src/src/librats/subsystems/peer_exchange.cpp +241 -0
  187. package/native-src/src/librats/subsystems/peer_exchange.h +136 -0
  188. package/native-src/src/librats/subsystems/ping_service.cpp +98 -0
  189. package/native-src/src/librats/subsystems/ping_service.h +66 -0
  190. package/native-src/src/librats/subsystems/port_mapping_service.cpp +192 -0
  191. package/native-src/src/librats/subsystems/port_mapping_service.h +84 -0
  192. package/native-src/src/librats/subsystems/pubsub.cpp +567 -0
  193. package/native-src/src/librats/subsystems/pubsub.h +175 -0
  194. package/native-src/src/librats/subsystems/reconnection.cpp +239 -0
  195. package/native-src/src/librats/subsystems/reconnection.h +126 -0
  196. package/native-src/src/librats/transport/connection.cpp +343 -0
  197. package/native-src/src/librats/transport/connection.h +283 -0
  198. package/native-src/src/librats/transport/link.h +96 -0
  199. package/native-src/src/librats/transport/reactor.cpp +540 -0
  200. package/native-src/src/librats/transport/reactor.h +224 -0
  201. package/native-src/src/librats/transport/reactor_pool.h +81 -0
  202. package/native-src/src/librats/transport/tcp_link.cpp +49 -0
  203. package/native-src/src/librats/transport/tcp_link.h +43 -0
  204. package/native-src/src/librats/transport/udp_mux.cpp +617 -0
  205. package/native-src/src/librats/transport/udp_mux.h +363 -0
  206. package/native-src/src/librats/transport/udp_packet.cpp +121 -0
  207. package/native-src/src/librats/transport/udp_packet.h +190 -0
  208. package/native-src/src/librats/transport/udp_stream.cpp +1194 -0
  209. package/native-src/src/librats/transport/udp_stream.h +614 -0
  210. package/native-src/src/librats/util/features.h.in +51 -0
  211. package/native-src/src/{fs.cpp → librats/util/fs.cpp} +51 -3
  212. package/native-src/src/librats/util/fs.h +136 -0
  213. package/native-src/src/librats/util/json.cpp +1002 -0
  214. package/native-src/src/librats/util/json.h +444 -0
  215. package/native-src/src/{logger.cpp → librats/util/logger.cpp} +1 -1
  216. package/native-src/src/{logger.h → librats/util/logger.h} +43 -31
  217. package/native-src/src/{network_monitor.cpp → librats/util/network_monitor.cpp} +12 -4
  218. package/native-src/src/{network_monitor.h → librats/util/network_monitor.h} +2 -1
  219. package/native-src/src/{network_utils.cpp → librats/util/network_utils.cpp} +38 -23
  220. package/native-src/src/{network_utils.h → librats/util/network_utils.h} +15 -8
  221. package/native-src/src/{os.cpp → librats/util/os.cpp} +48 -18
  222. package/native-src/src/librats/util/rats_export.h +69 -0
  223. package/native-src/src/{version.cpp → librats/util/version.cpp} +2 -2
  224. package/native-src/src/{version.h.in → librats/util/version.h.in} +1 -1
  225. package/native-src/src/librats/wire/frame.cpp +76 -0
  226. package/native-src/src/librats/wire/frame.h +110 -0
  227. package/native-src/src/librats/wire/message_router.cpp +45 -0
  228. package/native-src/src/librats/wire/message_router.h +47 -0
  229. package/package.json +5 -4
  230. package/scripts/build-librats.js +1 -0
  231. package/scripts/postinstall.js +3 -3
  232. package/scripts/prepare-package.js +4 -4
  233. package/scripts/verify-installation.js +63 -105
  234. package/src/librats_node.cpp +1042 -1324
  235. package/native-src/src/bencode.cpp +0 -485
  236. package/native-src/src/bencode.h +0 -145
  237. package/native-src/src/bittorrent.cpp +0 -14
  238. package/native-src/src/bittorrent.h +0 -74
  239. package/native-src/src/bt_bitfield.cpp +0 -372
  240. package/native-src/src/bt_bitfield.h +0 -316
  241. package/native-src/src/bt_choker.cpp +0 -228
  242. package/native-src/src/bt_choker.h +0 -147
  243. package/native-src/src/bt_client.cpp +0 -1047
  244. package/native-src/src/bt_client.h +0 -445
  245. package/native-src/src/bt_create_torrent.cpp +0 -677
  246. package/native-src/src/bt_create_torrent.h +0 -473
  247. package/native-src/src/bt_extension.cpp +0 -469
  248. package/native-src/src/bt_extension.h +0 -309
  249. package/native-src/src/bt_file_storage.cpp +0 -261
  250. package/native-src/src/bt_file_storage.h +0 -298
  251. package/native-src/src/bt_handshake.cpp +0 -134
  252. package/native-src/src/bt_handshake.h +0 -157
  253. package/native-src/src/bt_messages.cpp +0 -364
  254. package/native-src/src/bt_messages.h +0 -324
  255. package/native-src/src/bt_network.cpp +0 -1007
  256. package/native-src/src/bt_network.h +0 -417
  257. package/native-src/src/bt_peer_connection.cpp +0 -742
  258. package/native-src/src/bt_peer_connection.h +0 -592
  259. package/native-src/src/bt_piece_picker.cpp +0 -786
  260. package/native-src/src/bt_piece_picker.h +0 -473
  261. package/native-src/src/bt_resume_data.cpp +0 -410
  262. package/native-src/src/bt_resume_data.h +0 -249
  263. package/native-src/src/bt_torrent.cpp +0 -2120
  264. package/native-src/src/bt_torrent.h +0 -641
  265. package/native-src/src/bt_torrent_info.cpp +0 -659
  266. package/native-src/src/bt_torrent_info.h +0 -418
  267. package/native-src/src/bt_types.h +0 -621
  268. package/native-src/src/chained_send_buffer.cpp +0 -75
  269. package/native-src/src/chained_send_buffer.h +0 -137
  270. package/native-src/src/crypto/hkdf.c +0 -266
  271. package/native-src/src/crypto/poly1305.h +0 -36
  272. package/native-src/src/dht.cpp +0 -3307
  273. package/native-src/src/dht.h +0 -709
  274. package/native-src/src/disk_io.cpp +0 -632
  275. package/native-src/src/disk_io.h +0 -315
  276. package/native-src/src/file_transfer.cpp +0 -1415
  277. package/native-src/src/file_transfer.h +0 -286
  278. package/native-src/src/fs.h +0 -108
  279. package/native-src/src/gossipsub.cpp +0 -1139
  280. package/native-src/src/gossipsub.h +0 -403
  281. package/native-src/src/ice.cpp +0 -893
  282. package/native-src/src/ice.h +0 -559
  283. package/native-src/src/json.hpp +0 -25526
  284. package/native-src/src/librats.cpp +0 -2378
  285. package/native-src/src/librats.h +0 -2324
  286. package/native-src/src/librats_bittorrent.cpp +0 -601
  287. package/native-src/src/librats_c.cpp +0 -1557
  288. package/native-src/src/librats_c.h +0 -323
  289. package/native-src/src/librats_discovery.cpp +0 -402
  290. package/native-src/src/librats_encryption.cpp +0 -275
  291. package/native-src/src/librats_file_transfer.cpp +0 -144
  292. package/native-src/src/librats_gossipsub.cpp +0 -289
  293. package/native-src/src/librats_ice.cpp +0 -213
  294. package/native-src/src/librats_log_macros.h +0 -36
  295. package/native-src/src/librats_logging.cpp +0 -173
  296. package/native-src/src/librats_mdns.cpp +0 -166
  297. package/native-src/src/librats_persistence.cpp +0 -796
  298. package/native-src/src/librats_portmap.cpp +0 -419
  299. package/native-src/src/librats_reconnection.cpp +0 -218
  300. package/native-src/src/librats_statistic.cpp +0 -105
  301. package/native-src/src/librats_storage.cpp +0 -189
  302. package/native-src/src/rats_export.h +0 -17
  303. package/native-src/src/receive_buffer.cpp +0 -82
  304. package/native-src/src/receive_buffer.h +0 -127
  305. package/native-src/src/socket.h +0 -228
  306. package/native-src/src/threadmanager.cpp +0 -105
  307. package/native-src/src/threadmanager.h +0 -53
  308. package/native-src/src/tracker.cpp +0 -1264
  309. package/native-src/src/tracker.h +0 -319
  310. package/native-src/src/turn.cpp +0 -762
  311. package/native-src/src/turn.h +0 -460
  312. package/native-src/src/wakeup_pipe.h +0 -60
  313. /package/native-src/src/{os.h → librats/util/os.h} +0 -0
@@ -1,3307 +0,0 @@
1
- #include "dht.h"
2
- #include "network_utils.h"
3
- #include "logger.h"
4
- #include "socket.h"
5
- #include "json.hpp"
6
- #include <random>
7
- #include <algorithm>
8
- #include <sstream>
9
- #include <iomanip>
10
- #include <cstring>
11
- #include <cmath>
12
- #include <fstream>
13
-
14
- #ifdef _WIN32
15
- #include <winsock2.h>
16
- #include <ws2tcpip.h>
17
- #else
18
- #include <arpa/inet.h>
19
- #include <netinet/in.h>
20
- #endif
21
-
22
- // DHT module logging macros
23
- #define LOG_DHT_DEBUG(message) LOG_DEBUG("dht", message)
24
- #define LOG_DHT_INFO(message) LOG_INFO("dht", message)
25
- #define LOG_DHT_WARN(message) LOG_WARN("dht", message)
26
- #define LOG_DHT_ERROR(message) LOG_ERROR("dht", message)
27
-
28
- namespace librats {
29
-
30
-
31
- DhtClient::DhtClient(int port, const std::string& bind_address, const std::string& data_directory,
32
- AddressFamily address_family)
33
- : port_(port), bind_address_(bind_address), data_directory_(data_directory),
34
- address_family_(address_family), socket_(INVALID_SOCKET_VALUE), running_(false) {
35
- node_id_ = generate_node_id();
36
- routing_table_.resize(NODE_ID_SIZE * 8); // 160 buckets for 160-bit node IDs
37
-
38
- if (data_directory_.empty()) {
39
- data_directory_ = ".";
40
- }
41
-
42
- LOG_DHT_INFO("DHT client created with node ID: " << node_id_to_hex(node_id_) <<
43
- " family: " << (is_ipv6() ? "IPv6" : "IPv4") <<
44
- (bind_address_.empty() ? "" : " bind address: " + bind_address_) <<
45
- " data directory: " << data_directory_);
46
- }
47
-
48
- DhtClient::~DhtClient() {
49
- stop();
50
- }
51
-
52
- bool DhtClient::start() {
53
- if (running_) {
54
- return true;
55
- }
56
-
57
- LOG_DHT_INFO("Starting DHT client on port " << port_ <<
58
- (bind_address_.empty() ? "" : " bound to " + bind_address_));
59
-
60
- // Initialize socket library (safe to call multiple times)
61
- if (!init_socket_library()) {
62
- LOG_DHT_ERROR("Failed to initialize socket library");
63
- return false;
64
- }
65
-
66
- // Each family gets its own single-family socket. IPv6 uses V6ONLY so the two
67
- // sockets can share the same port and never cross-deliver mapped addresses.
68
- socket_ = create_udp_socket(port_, bind_address_, address_family_);
69
- // Fallback to free port
70
- if (!is_valid_socket(socket_) && port_ > 0) {
71
- // Requested port is not available, try ephemeral port as fallback
72
- int original_port = port_;
73
- LOG_DHT_WARN("UDP port " << original_port << " is not available, falling back to ephemeral port");
74
- socket_ = create_udp_socket(0, bind_address_, address_family_);
75
- if (is_valid_socket(socket_)) {
76
- port_ = get_bound_port(socket_);
77
- LOG_DHT_INFO("Fell back from port " << original_port << " to ephemeral port " << port_);
78
- }
79
- }
80
- if (!is_valid_socket(socket_)) {
81
- LOG_DHT_ERROR("Failed to create " << (is_ipv6() ? "IPv6" : "IPv4") << " UDP socket on port " << port_);
82
- return false;
83
- }
84
-
85
- if (!set_socket_nonblocking(socket_)) {
86
- LOG_DHT_WARN("Failed to set socket to non-blocking mode");
87
- }
88
-
89
- running_ = true;
90
-
91
- // Load saved routing table before starting threads
92
- if (load_routing_table()) {
93
- LOG_DHT_INFO("Loaded routing table from disk (" << get_routing_table_size() << " nodes)");
94
- }
95
-
96
- // Start network and maintenance threads
97
- network_thread_ = std::thread(&DhtClient::network_loop, this);
98
- maintenance_thread_ = std::thread(&DhtClient::maintenance_loop, this);
99
-
100
- LOG_DHT_INFO("DHT client started successfully");
101
- return true;
102
- }
103
-
104
- void DhtClient::stop() {
105
- if (!running_) {
106
- return;
107
- }
108
-
109
- LOG_DHT_INFO("Stopping DHT client");
110
-
111
- // Trigger immediate shutdown of all background threads
112
- shutdown_immediate();
113
-
114
- // Wait for threads to finish
115
- if (network_thread_.joinable()) {
116
- network_thread_.join();
117
- }
118
- if (maintenance_thread_.joinable()) {
119
- maintenance_thread_.join();
120
- }
121
-
122
- // Save routing table before closing
123
- if (save_routing_table()) {
124
- LOG_DHT_INFO("Saved routing table to disk (" << get_routing_table_size() << " nodes)");
125
- }
126
-
127
- // Close socket
128
- if (is_valid_socket(socket_)) {
129
- close_socket(socket_);
130
- socket_ = INVALID_SOCKET_VALUE;
131
- }
132
-
133
- LOG_DHT_INFO("DHT client stopped");
134
- }
135
-
136
- void DhtClient::shutdown_immediate() {
137
- LOG_DHT_INFO("Triggering immediate shutdown of DHT background threads");
138
-
139
- running_.store(false);
140
-
141
- // Notify all waiting threads to wake up immediately
142
- shutdown_cv_.notify_all();
143
- }
144
-
145
- bool DhtClient::bootstrap(const std::vector<Peer>& bootstrap_nodes) {
146
- if (!running_) {
147
- LOG_DHT_ERROR("DHT client not running");
148
- return false;
149
- }
150
-
151
- LOG_DHT_INFO("Bootstrapping DHT with " << bootstrap_nodes.size() << " nodes");
152
- LOG_DHT_DEBUG("Bootstrap nodes:");
153
- for (const auto& peer : bootstrap_nodes) {
154
- LOG_DHT_DEBUG(" - " << peer.ip << ":" << peer.port);
155
- }
156
-
157
-
158
-
159
- // Send ping to bootstrap nodes
160
- LOG_DHT_DEBUG("Sending PING to all bootstrap nodes");
161
- for (const auto& peer : bootstrap_nodes) {
162
- send_krpc_ping(peer);
163
- }
164
-
165
- // Start node discovery by finding our own node
166
- LOG_DHT_DEBUG("Starting node discovery by finding our own node ID: " << node_id_to_hex(node_id_));
167
- for (const auto& peer : bootstrap_nodes) {
168
- send_krpc_find_node(peer, node_id_);
169
- }
170
-
171
- LOG_DHT_DEBUG("Bootstrap process initiated");
172
- return true;
173
- }
174
-
175
- bool DhtClient::find_peers(const InfoHash& info_hash, PeerDiscoveryCallback callback) {
176
- if (!running_) {
177
- LOG_DHT_ERROR("DHT client not running");
178
- return false;
179
- }
180
-
181
- std::string hash_key = node_id_to_hex(info_hash);
182
- LOG_DHT_INFO("Finding peers for info hash: " << hash_key);
183
-
184
- // Get initial nodes from routing table
185
- auto closest_nodes = find_closest_nodes(info_hash, K_BUCKET_SIZE);
186
-
187
- if (closest_nodes.empty()) {
188
- LOG_DHT_WARN("No nodes in routing table to query for info_hash " << hash_key);
189
- return false;
190
- }
191
-
192
- DeferredCallbacks deferred;
193
-
194
- {
195
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
196
-
197
- // Check if a search is already ongoing for this info_hash
198
- auto search_it = pending_searches_.find(hash_key);
199
- if (search_it != pending_searches_.end()) {
200
- // Search already in progress - just add the callback to the list
201
- LOG_DHT_INFO("Search already in progress for info hash " << hash_key << " - adding callback to existing search");
202
- search_it->second.callbacks.push_back(callback);
203
- return true;
204
- }
205
-
206
- // Create new search
207
- PendingSearch new_search(info_hash);
208
- new_search.callbacks.push_back(callback);
209
-
210
- // Initialize search_nodes with closest nodes from routing table (already sorted)
211
- new_search.search_nodes = std::move(closest_nodes);
212
-
213
- auto insert_result = pending_searches_.emplace(hash_key, std::move(new_search));
214
- PendingSearch& search_ref = insert_result.first->second;
215
-
216
- LOG_DHT_DEBUG("Initialized search with " << search_ref.search_nodes.size() << " nodes from routing table");
217
-
218
- // Start sending requests
219
- add_search_requests(search_ref, deferred);
220
- }
221
-
222
- // Invoke callbacks outside the lock to avoid deadlock
223
- deferred.invoke();
224
-
225
- return true;
226
- }
227
-
228
- bool DhtClient::announce_peer(const InfoHash& info_hash, uint16_t port, PeerDiscoveryCallback callback) {
229
- if (!running_) {
230
- LOG_DHT_ERROR("DHT client not running");
231
- return false;
232
- }
233
-
234
- if (port == 0) {
235
- port = port_;
236
- }
237
-
238
- std::string hash_key = node_id_to_hex(info_hash);
239
- LOG_DHT_INFO("Announcing peer for info hash: " << hash_key << " on port " << port);
240
-
241
- // BEP 5 compliant announce:
242
- // 1. Perform iterative Kademlia lookup (like find_peers)
243
- // 2. Collect tokens from responding nodes
244
- // 3. Send announce_peer to k closest nodes with their tokens
245
-
246
- // Get initial nodes from routing table
247
- auto closest_nodes = find_closest_nodes(info_hash, K_BUCKET_SIZE);
248
-
249
- if (closest_nodes.empty()) {
250
- LOG_DHT_WARN("No nodes in routing table to announce to for info_hash " << hash_key);
251
- return false;
252
- }
253
-
254
- DeferredCallbacks deferred;
255
-
256
- {
257
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
258
-
259
- // Check if a search/announce is already ongoing for this info_hash
260
- auto search_it = pending_searches_.find(hash_key);
261
- if (search_it != pending_searches_.end()) {
262
- if (search_it->second.is_announce) {
263
- LOG_DHT_INFO("Announce already in progress for info hash " << hash_key);
264
- return true;
265
- }
266
- // Regular find_peers in progress - let it complete, then user can announce again
267
- LOG_DHT_WARN("find_peers already in progress for info hash " << hash_key << " - announce will wait");
268
- return false;
269
- }
270
-
271
- // Create new search with announce flag
272
- PendingSearch new_search(info_hash);
273
- new_search.is_announce = true;
274
- new_search.announce_port = port;
275
-
276
- // Add callback if provided - peers discovered during traversal will be returned through it
277
- if (callback) {
278
- new_search.callbacks.push_back(callback);
279
- }
280
-
281
- // Initialize search_nodes with closest nodes from routing table (already sorted)
282
- new_search.search_nodes = std::move(closest_nodes);
283
-
284
- auto insert_result = pending_searches_.emplace(hash_key, std::move(new_search));
285
- PendingSearch& search_ref = insert_result.first->second;
286
-
287
- LOG_DHT_DEBUG("Initialized announce search with " << search_ref.search_nodes.size() << " nodes from routing table");
288
-
289
- // Start sending requests
290
- add_search_requests(search_ref, deferred);
291
- }
292
-
293
- // Invoke callbacks outside the lock to avoid deadlock
294
- deferred.invoke();
295
-
296
- return true;
297
- }
298
-
299
- void DhtClient::cancel_search(const InfoHash& info_hash) {
300
- std::string hash_key = node_id_to_hex(info_hash);
301
-
302
- LOG_DHT_INFO("Cancelling search/announce for info hash: " << hash_key);
303
-
304
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
305
-
306
- auto search_it = pending_searches_.find(hash_key);
307
- if (search_it == pending_searches_.end()) {
308
- LOG_DHT_DEBUG("No active search found for info hash " << hash_key);
309
- return;
310
- }
311
-
312
- // Mark as finished to prevent further queries
313
- search_it->second.is_finished = true;
314
-
315
- // Remove all associated transactions
316
- std::vector<std::string> transactions_to_remove;
317
- for (const auto& [tx_id, tx] : transaction_to_search_) {
318
- if (tx.info_hash_hex == hash_key) {
319
- transactions_to_remove.push_back(tx_id);
320
- }
321
- }
322
-
323
- for (const auto& tx_id : transactions_to_remove) {
324
- transaction_to_search_.erase(tx_id);
325
- }
326
-
327
- // Remove the search
328
- pending_searches_.erase(search_it);
329
-
330
- LOG_DHT_INFO("Cancelled search for info hash " << hash_key <<
331
- ", removed " << transactions_to_remove.size() << " pending transactions");
332
- }
333
-
334
- size_t DhtClient::get_routing_table_size() const {
335
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
336
- size_t total = 0;
337
- for (const auto& bucket : routing_table_) {
338
- total += bucket.size();
339
- }
340
- return total;
341
- }
342
-
343
- size_t DhtClient::get_pending_ping_verifications_count() const {
344
- std::lock_guard<std::mutex> lock(pending_pings_mutex_);
345
- return pending_pings_.size();
346
- }
347
-
348
- bool DhtClient::is_search_active(const InfoHash& info_hash) const {
349
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
350
- std::string hash_key = node_id_to_hex(info_hash);
351
- auto it = pending_searches_.find(hash_key);
352
- return it != pending_searches_.end() && !it->second.is_finished;
353
- }
354
-
355
- bool DhtClient::is_announce_active(const InfoHash& info_hash) const {
356
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
357
- std::string hash_key = node_id_to_hex(info_hash);
358
- auto it = pending_searches_.find(hash_key);
359
- return it != pending_searches_.end() && !it->second.is_finished && it->second.is_announce;
360
- }
361
-
362
- size_t DhtClient::get_active_searches_count() const {
363
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
364
- size_t count = 0;
365
- for (const auto& [hash, search] : pending_searches_) {
366
- if (!search.is_finished) {
367
- count++;
368
- }
369
- }
370
- return count;
371
- }
372
-
373
- size_t DhtClient::get_active_announces_count() const {
374
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
375
- size_t count = 0;
376
- for (const auto& [hash, search] : pending_searches_) {
377
- if (!search.is_finished && search.is_announce) {
378
- count++;
379
- }
380
- }
381
- return count;
382
- }
383
-
384
- std::vector<Peer> DhtClient::get_default_bootstrap_nodes() {
385
- // Hostnames are resolved to the instance's family at send time (A for IPv4, AAAA for
386
- // IPv6). dht.libtorrent.org publishes an AAAA record, giving the IPv6 network a
387
- // reliable bootstrap entry point.
388
- return {
389
- {"router.bittorrent.com", 6881},
390
- {"dht.transmissionbt.com", 6881},
391
- {"router.utorrent.com", 6881},
392
- {"dht.libtorrent.org", 25401},
393
- {"dht.aelitis.com", 6881}
394
- };
395
- }
396
-
397
- void DhtClient::network_loop() {
398
- LOG_DHT_DEBUG("Network loop started");
399
-
400
- while (running_) {
401
- Peer sender;
402
- auto data = receive_udp_data(socket_, 1500, sender, -1); // MTU size, blocking
403
-
404
- if (!data.empty()) {
405
- LOG_DHT_DEBUG("Received " << data.size() << " bytes from " << sender.ip << ":" << sender.port);
406
- handle_message(data, sender);
407
- }
408
-
409
- // Use conditional variable for responsive shutdown
410
- {
411
- std::unique_lock<std::mutex> lock(shutdown_mutex_);
412
- if (shutdown_cv_.wait_for(lock, std::chrono::milliseconds(10), [this] { return !running_.load(); })) {
413
- break;
414
- }
415
- }
416
- }
417
-
418
- LOG_DHT_DEBUG("Network loop stopped");
419
- }
420
-
421
- void DhtClient::maintenance_loop() {
422
- LOG_DHT_DEBUG("Maintenance loop started");
423
-
424
- auto last_bucket_refresh = std::chrono::steady_clock::now();
425
- auto last_ping_verification_cleanup = std::chrono::steady_clock::now();
426
- auto last_general_cleanup = std::chrono::steady_clock::now();
427
- auto last_stats_print = std::chrono::steady_clock::now();
428
- auto last_search_timeout_check = std::chrono::steady_clock::now();
429
- auto last_search_node_cleanup = std::chrono::steady_clock::now();
430
- auto last_routing_table_save = std::chrono::steady_clock::now();
431
-
432
- while (running_) {
433
- auto now = std::chrono::steady_clock::now();
434
-
435
- // Check for timed out search requests every 2 seconds (frequent check)
436
- if (now - last_search_timeout_check >= std::chrono::seconds(2)) {
437
- cleanup_timed_out_search_requests();
438
- last_search_timeout_check = now;
439
- }
440
-
441
- // Clean up finalized node_states entries in active searches every 10 seconds
442
- if (now - last_search_node_cleanup >= std::chrono::seconds(10)) {
443
- cleanup_search_node_states();
444
- last_search_node_cleanup = now;
445
- }
446
-
447
- // General cleanup operations every 1 minute (like previously)
448
- if (now - last_general_cleanup >= std::chrono::minutes(1)) {
449
- // Cleanup stale nodes every 1 minute
450
- cleanup_stale_nodes();
451
-
452
- // Cleanup stale peer tokens
453
- cleanup_stale_peer_tokens();
454
-
455
- // Cleanup stale pending searches
456
- cleanup_stale_searches();
457
-
458
- // Cleanup stale announced peers
459
- cleanup_stale_announced_peers();
460
-
461
- #ifdef RATS_SEARCH_FEATURES
462
- // Cleanup stale spider transactions (requests without responses)
463
- cleanup_stale_spider_transactions();
464
- #endif
465
-
466
- last_general_cleanup = now;
467
- }
468
-
469
- // Refresh buckets every 30 minutes
470
- if (now - last_bucket_refresh >= std::chrono::minutes(30)) {
471
- refresh_buckets();
472
- last_bucket_refresh = now;
473
- }
474
-
475
- // Frequent maintenance: ping verifications time out at ~30s, so check often
476
- if (now - last_ping_verification_cleanup >= std::chrono::seconds(30)) {
477
- cleanup_stale_ping_verifications();
478
- last_ping_verification_cleanup = now;
479
- }
480
-
481
- // Print DHT statistics every 10 seconds
482
- if (now - last_stats_print >= std::chrono::seconds(10)) {
483
- print_statistics();
484
- last_stats_print = now;
485
- }
486
-
487
- // Save routing table every 5 minutes
488
- if (now - last_routing_table_save >= std::chrono::minutes(5)) {
489
- if (save_routing_table()) {
490
- LOG_DHT_DEBUG("Periodic routing table save completed");
491
- }
492
- last_routing_table_save = now;
493
- }
494
-
495
- // Execute maintenance loop every 1 second
496
- {
497
- std::unique_lock<std::mutex> lock(shutdown_mutex_);
498
- if (shutdown_cv_.wait_for(lock, std::chrono::seconds(1), [this] { return !running_.load(); })) {
499
- break;
500
- }
501
- }
502
- }
503
-
504
- LOG_DHT_DEBUG("Maintenance loop stopped");
505
- }
506
-
507
- void DhtClient::handle_message(const std::vector<uint8_t>& data, const Peer& sender) {
508
- LOG_DHT_DEBUG("Processing message of " << data.size() << " bytes from " << sender.ip << ":" << sender.port);
509
-
510
- auto krpc_message = KrpcProtocol::decode_message(data);
511
- if (!krpc_message) {
512
- LOG_DHT_DEBUG("Failed to decode KRPC message from " << sender.ip << ":" << sender.port);
513
- return;
514
- }
515
-
516
- handle_krpc_message(*krpc_message, sender);
517
- }
518
-
519
- void DhtClient::add_node(const DhtNode& node, bool confirmed, bool no_verify) {
520
- // IPv4 and IPv6 are separate Kademlia networks (BEP 32). Reject any node whose
521
- // address family does not match this instance to keep the routing table clean.
522
- if (network_utils::is_valid_ipv6(node.peer.ip) != is_ipv6()) {
523
- LOG_DHT_DEBUG("Ignoring " << (is_ipv6() ? "non-IPv6" : "non-IPv4") << " node "
524
- << node.peer.ip << ":" << node.peer.port << " (wrong family)");
525
- return;
526
- }
527
-
528
- std::lock_guard<std::mutex> ping_lock(pending_pings_mutex_);
529
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
530
-
531
- int bucket_index = get_bucket_index(node.id);
532
- auto& bucket = routing_table_[bucket_index];
533
-
534
- LOG_DHT_DEBUG("Adding node " << node_id_to_hex(node.id) << " at " << node.peer.ip << ":" << node.peer.port
535
- << " to bucket " << bucket_index << " (confirmed=" << confirmed << ")");
536
-
537
- // Check if node already exists
538
- auto it = std::find_if(bucket.begin(), bucket.end(),
539
- [&node](const DhtNode& existing) {
540
- return existing.id == node.id;
541
- });
542
-
543
- if (it != bucket.end()) {
544
- // Update existing node - mark as successful since it contacted us
545
- LOG_DHT_DEBUG("Node " << node_id_to_hex(node.id) << " already exists in bucket " << bucket_index << ", updating");
546
- it->peer = node.peer;
547
- if (confirmed) {
548
- it->mark_success();
549
- }
550
- return;
551
- }
552
-
553
- // Bucket has space - just add
554
- if (bucket.size() < K_BUCKET_SIZE) {
555
- DhtNode new_node = node;
556
- if (confirmed) {
557
- new_node.fail_count = 0; // Node contacted us, so it's confirmed good
558
- }
559
- bucket.push_back(new_node);
560
- LOG_DHT_DEBUG("Added new node " << node_id_to_hex(node.id) << " to bucket " << bucket_index << " (size: " << bucket.size() << "/" << K_BUCKET_SIZE << ")");
561
- return;
562
- }
563
-
564
- // Bucket is full - first check for nodes with failures (stale nodes)
565
- auto worst_it = std::max_element(bucket.begin(), bucket.end(),
566
- [](const DhtNode& a, const DhtNode& b) {
567
- // Find node with highest fail_count
568
- return a.fail_count < b.fail_count;
569
- });
570
-
571
- if (worst_it != bucket.end() && worst_it->fail_count > 0) {
572
- // Found a stale node - replace it immediately
573
- LOG_DHT_DEBUG("Replacing stale node " << node_id_to_hex(worst_it->id)
574
- << " (fail_count=" << static_cast<int>(worst_it->fail_count) << ")"
575
- << " with " << node_id_to_hex(node.id));
576
- DhtNode new_node = node;
577
- if (confirmed) {
578
- new_node.fail_count = 0; // Node contacted us, so it's confirmed good
579
- }
580
- // else: keep fail_count = 0xff (unpinged) from constructor
581
- *worst_it = new_node;
582
- return;
583
- }
584
-
585
- // All nodes are good - find the "worst" good node for ping verification or replacement
586
- // Worst = highest RTT among nodes not already being pinged
587
- DhtNode* worst = nullptr;
588
- for (auto& existing : bucket) {
589
- if (nodes_being_replaced_.find(existing.id) == nodes_being_replaced_.end()) {
590
- if (!worst || existing.is_worse_than(*worst)) {
591
- worst = &existing;
592
- }
593
- }
594
- }
595
-
596
- if (!worst) {
597
- LOG_DHT_DEBUG("All nodes in bucket already have pending pings - dropping candidate " << node_id_to_hex(node.id));
598
- return;
599
- }
600
-
601
- // If no_verify is set, directly replace the worst node without ping verification
602
- if (no_verify) {
603
- LOG_DHT_DEBUG("Force adding node " << node_id_to_hex(node.id)
604
- << " - replacing worst node " << node_id_to_hex(worst->id)
605
- << " (rtt=" << worst->rtt << "ms) without ping verification");
606
- DhtNode new_node = node;
607
- if (confirmed) {
608
- new_node.fail_count = 0;
609
- }
610
- *worst = new_node;
611
- return;
612
- }
613
-
614
- // Initiate ping to worst node - if it doesn't respond, replace with candidate
615
- LOG_DHT_DEBUG("All nodes good, pinging worst node " << node_id_to_hex(worst->id)
616
- << " (rtt=" << worst->rtt << "ms) to verify");
617
- initiate_ping_verification(node, *worst, bucket_index);
618
- }
619
-
620
- std::vector<DhtNode> DhtClient::find_closest_nodes(const NodeId& target, size_t count) {
621
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
622
-
623
- auto result = find_closest_nodes_unlocked(target, count);
624
-
625
- return result;
626
- }
627
-
628
- std::vector<DhtNode> DhtClient::find_closest_nodes_unlocked(const NodeId& target, size_t count) {
629
- LOG_DHT_DEBUG("Finding closest nodes to target " << node_id_to_hex(target) << " (max " << count << " nodes)");
630
-
631
- // Find closest bucket to target
632
- int target_bucket = get_bucket_index(target);
633
-
634
- // Candidate nodes to be closest to target
635
- std::vector<DhtNode> candidates;
636
- // Reserve extra space: 3x count + buffer for 2 full buckets to avoid reallocation
637
- candidates.reserve(count * 3 + K_BUCKET_SIZE * 2);
638
-
639
- // Add nodes from ideal bucket
640
- if (target_bucket >= 0 && static_cast<size_t>(target_bucket) < routing_table_.size()) {
641
- const auto& bucket = routing_table_[target_bucket];
642
- candidates.insert(candidates.end(), bucket.begin(), bucket.end());
643
- LOG_DHT_DEBUG("Collected " << bucket.size() << " nodes from target bucket " << target_bucket);
644
- }
645
-
646
- // Add nodes from buckets above and below the ideal bucket
647
- // Collect more candidates than needed to ensure we get the actual closest ones after sorting
648
- size_t desired_candidates = count * 3; // Collect 3x more candidates for better selection
649
- int low = target_bucket - 1;
650
- int high = target_bucket + 1;
651
- const int max_bucket_index = static_cast<int>(routing_table_.size()) - 1;
652
- int buckets_checked = 1; // Already checked target_bucket
653
-
654
- while (candidates.size() < desired_candidates && (low >= 0 || high <= max_bucket_index)) {
655
- // Search left (closer buckets)
656
- if (low >= 0) {
657
- const auto& bucket = routing_table_[low];
658
- if (!bucket.empty()) {
659
- candidates.insert(candidates.end(), bucket.begin(), bucket.end());
660
- LOG_DHT_DEBUG("Collected " << bucket.size() << " nodes from bucket " << low);
661
- }
662
- low--;
663
- buckets_checked++;
664
- }
665
-
666
- // Search right (farther buckets)
667
- if (high <= max_bucket_index) {
668
- const auto& bucket = routing_table_[high];
669
- if (!bucket.empty()) {
670
- candidates.insert(candidates.end(), bucket.begin(), bucket.end());
671
- LOG_DHT_DEBUG("Collected " << bucket.size() << " nodes from bucket " << high);
672
- }
673
- high++;
674
- buckets_checked++;
675
- }
676
- }
677
-
678
- LOG_DHT_DEBUG("Bucket-aware collection: checked " << buckets_checked << " buckets, collected "
679
- << candidates.size() << " candidate nodes around target bucket " << target_bucket);
680
-
681
- if (candidates.empty()) {
682
- LOG_DHT_DEBUG("No candidates found in routing table");
683
- return candidates;
684
- }
685
-
686
- // Use partial_sort to efficiently get only the 'count' closest nodes - O(n log k) vs O(n log n)
687
- size_t sort_count = (std::min)(count, candidates.size());
688
- std::partial_sort(
689
- candidates.begin(),
690
- candidates.begin() + sort_count,
691
- candidates.end(),
692
- [&target, this](const DhtNode& a, const DhtNode& b) {
693
- return is_closer(a.id, b.id, target);
694
- }
695
- );
696
-
697
- // Return up to 'count' closest nodes
698
- if (candidates.size() > count) {
699
- candidates.resize(count);
700
- }
701
-
702
- LOG_DHT_DEBUG("Found " << candidates.size() << " closest nodes to target " << node_id_to_hex(target));
703
- for (size_t i = 0; i < candidates.size(); ++i) {
704
- LOG_DHT_DEBUG(" [" << i << "] " << node_id_to_hex(candidates[i].id) << " at " << candidates[i].peer.ip << ":" << candidates[i].peer.port);
705
- }
706
-
707
- // Debug alternative: Compare with full routing table algorithm
708
- /*
709
- candidates.clear();
710
- for (const auto& bucket : routing_table_) {
711
- candidates.insert(candidates.end(), bucket.begin(), bucket.end());
712
- }
713
- sort_count = (std::min)(count, candidates.size());
714
- std::partial_sort(
715
- candidates.begin(),
716
- candidates.begin() + sort_count,
717
- candidates.end(),
718
- [&target, this](const DhtNode& a, const DhtNode& b) {
719
- return is_closer(a.id, b.id, target);
720
- }
721
- );
722
- // Return up to 'count' closest nodes
723
- if (candidates.size() > count) {
724
- candidates.resize(count);
725
- }
726
- LOG_DHT_DEBUG("Found " << candidates.size() << " closest nodes to target " << node_id_to_hex(target));
727
- for (size_t i = 0; i < candidates.size(); ++i) {
728
- LOG_DHT_DEBUG(" +[" << i << "] " << node_id_to_hex(candidates[i].id) << " at " << candidates[i].peer.ip << ":" << candidates[i].peer.port);
729
- }
730
- */
731
- // End of debug alternative
732
-
733
- return candidates;
734
- }
735
-
736
- int DhtClient::get_bucket_index(const NodeId& id) {
737
- NodeId distance = xor_distance(node_id_, id);
738
-
739
- // Find the position of the most significant bit
740
- for (size_t i = 0; i < NODE_ID_SIZE; ++i) {
741
- if (distance[i] != 0) {
742
- for (int j = 7; j >= 0; --j) {
743
- if (distance[i] & (1 << j)) {
744
- return static_cast<int>(i * 8 + (7 - j));
745
- }
746
- }
747
- }
748
- }
749
-
750
- return NODE_ID_SIZE * 8 - 1; // All bits are 0, maximum distance
751
- }
752
-
753
-
754
-
755
- // KRPC message handling
756
- void DhtClient::handle_krpc_message(const KrpcMessage& message, const Peer& sender) {
757
- LOG_DHT_DEBUG("Handling KRPC message type " << static_cast<int>(message.type) << " from " << sender.ip << ":" << sender.port);
758
-
759
- switch (message.type) {
760
- case KrpcMessageType::Query:
761
- switch (message.query_type) {
762
- case KrpcQueryType::Ping:
763
- handle_krpc_ping(message, sender);
764
- break;
765
- case KrpcQueryType::FindNode:
766
- handle_krpc_find_node(message, sender);
767
- break;
768
- case KrpcQueryType::GetPeers:
769
- handle_krpc_get_peers(message, sender);
770
- break;
771
- case KrpcQueryType::AnnouncePeer:
772
- handle_krpc_announce_peer(message, sender);
773
- break;
774
- }
775
- break;
776
- case KrpcMessageType::Response:
777
- handle_krpc_response(message, sender);
778
- break;
779
- case KrpcMessageType::Error:
780
- handle_krpc_error(message, sender);
781
- break;
782
- }
783
- }
784
-
785
- void DhtClient::handle_krpc_ping(const KrpcMessage& message, const Peer& sender) {
786
- LOG_DHT_DEBUG("Handling KRPC PING from " << node_id_to_hex(message.sender_id) << " at " << sender.ip << ":" << sender.port);
787
-
788
- #ifdef RATS_SEARCH_FEATURES
789
- // Spider mode: check if ignoring requests
790
- if (spider_mode_.load() && spider_ignore_.load()) {
791
- return;
792
- }
793
- bool is_spider = spider_mode_.load();
794
- // Only use neighbor_id for IPs we've contacted via spider (to avoid polluting other DHT clients)
795
- bool use_neighbor_id = is_spider && is_spider_contacted_ip(sender.ip);
796
- #else
797
- bool is_spider = false;
798
- bool use_neighbor_id = false;
799
- #endif
800
-
801
- // Add sender to routing table (or spider pool in spider mode)
802
- KrpcNode krpc_node(message.sender_id, sender.ip, sender.port);
803
- DhtNode sender_node = krpc_node_to_dht_node(krpc_node);
804
-
805
- #ifdef RATS_SEARCH_FEATURES
806
- if (is_spider) {
807
- add_spider_node(sender_node);
808
- }
809
- #endif
810
- // Adding spider related node very undesirable but ok
811
- if (!use_neighbor_id)
812
- {
813
- add_node(sender_node, true, false);
814
- }
815
-
816
- // Respond with ping response
817
- // Use neighbor_id only for spider-contacted IPs, real node_id for organic DHT traffic
818
- NodeId response_id = use_neighbor_id ? neighbor_id(message.sender_id) : node_id_;
819
- auto response = KrpcProtocol::create_ping_response(message.transaction_id, response_id);
820
- send_krpc_message(response, sender);
821
- }
822
-
823
- void DhtClient::handle_krpc_find_node(const KrpcMessage& message, const Peer& sender) {
824
- LOG_DHT_DEBUG("Handling KRPC FIND_NODE from " << node_id_to_hex(message.sender_id) << " at " << sender.ip << ":" << sender.port);
825
-
826
- #ifdef RATS_SEARCH_FEATURES
827
- // Spider mode: check if ignoring requests
828
- if (spider_mode_.load() && spider_ignore_.load()) {
829
- return;
830
- }
831
- bool is_spider = spider_mode_.load();
832
- // Only use neighbor_id for IPs we've contacted via spider (to avoid polluting other DHT clients)
833
- bool use_neighbor_id = is_spider && is_spider_contacted_ip(sender.ip);
834
- #else
835
- bool is_spider = false;
836
- bool use_neighbor_id = false;
837
- #endif
838
-
839
- // Add sender to routing table (or spider pool in spider mode)
840
- KrpcNode krpc_node(message.sender_id, sender.ip, sender.port);
841
- DhtNode sender_node = krpc_node_to_dht_node(krpc_node);
842
-
843
- #ifdef RATS_SEARCH_FEATURES
844
- if (is_spider) {
845
- add_spider_node(sender_node);
846
- }
847
- #endif
848
- // Adding spider related node very undesirable but ok
849
- if (!use_neighbor_id)
850
- {
851
- add_node(sender_node, true, false);
852
- }
853
-
854
- // Find closest nodes
855
- auto closest_nodes = find_closest_nodes(message.target_id, K_BUCKET_SIZE);
856
- auto krpc_nodes = dht_nodes_to_krpc_nodes(closest_nodes);
857
-
858
- // Respond with closest nodes
859
- // Use neighbor_id only for spider-contacted IPs, real node_id for organic DHT traffic
860
- NodeId response_id = use_neighbor_id ? neighbor_id(message.target_id) : node_id_;
861
- auto response = KrpcProtocol::create_find_node_response(message.transaction_id, response_id, krpc_nodes);
862
- send_krpc_message(response, sender);
863
- }
864
-
865
- void DhtClient::handle_krpc_get_peers(const KrpcMessage& message, const Peer& sender) {
866
- LOG_DHT_DEBUG("Handling KRPC GET_PEERS from " << node_id_to_hex(message.sender_id) << " at " << sender.ip << ":" << sender.port << " for info_hash " << node_id_to_hex(message.info_hash));
867
-
868
- #ifdef RATS_SEARCH_FEATURES
869
- // Spider mode: check if ignoring requests
870
- if (spider_mode_.load() && spider_ignore_.load()) {
871
- return;
872
- }
873
- bool is_spider = spider_mode_.load();
874
- // Only use neighbor_id for IPs we've contacted via spider (to avoid polluting other DHT clients)
875
- bool use_neighbor_id = is_spider && is_spider_contacted_ip(sender.ip);
876
- #else
877
- bool is_spider = false;
878
- bool use_neighbor_id = false;
879
- #endif
880
-
881
- // Add sender to routing table (or spider pool in spider mode)
882
- KrpcNode krpc_node(message.sender_id, sender.ip, sender.port);
883
- DhtNode sender_node = krpc_node_to_dht_node(krpc_node);
884
-
885
- #ifdef RATS_SEARCH_FEATURES
886
- if (is_spider) {
887
- add_spider_node(sender_node);
888
- }
889
- #endif
890
- // Adding spider related node very undesirable but ok
891
- if (!use_neighbor_id)
892
- {
893
- add_node(sender_node, true, false);
894
- }
895
-
896
- // Generate a token for this peer
897
- std::string token = generate_token(sender);
898
-
899
- // Use neighbor_id only for spider-contacted IPs, real node_id for organic DHT traffic
900
- NodeId response_id = use_neighbor_id ? neighbor_id(message.info_hash) : node_id_;
901
-
902
- // First check if we have announced peers for this info_hash
903
- auto announced_peers = get_announced_peers(message.info_hash);
904
-
905
- KrpcMessage response;
906
- if (!announced_peers.empty()) {
907
- // Return the peers we have stored
908
- response = KrpcProtocol::create_get_peers_response(message.transaction_id, response_id, announced_peers, token);
909
- LOG_DHT_DEBUG("Responding to KRPC GET_PEERS with " << announced_peers.size() << " announced peers for info_hash " << node_id_to_hex(message.info_hash));
910
- } else {
911
- // Return closest nodes
912
- auto closest_nodes = find_closest_nodes(message.info_hash, K_BUCKET_SIZE);
913
- auto krpc_nodes = dht_nodes_to_krpc_nodes(closest_nodes);
914
- response = KrpcProtocol::create_get_peers_response_with_nodes(message.transaction_id, response_id, krpc_nodes, token);
915
- LOG_DHT_DEBUG("Responding to KRPC GET_PEERS with " << krpc_nodes.size() << " closest nodes for info_hash " << node_id_to_hex(message.info_hash));
916
- }
917
-
918
- send_krpc_message(response, sender);
919
- }
920
-
921
- void DhtClient::handle_krpc_announce_peer(const KrpcMessage& message, const Peer& sender) {
922
- LOG_DHT_DEBUG("Handling KRPC ANNOUNCE_PEER from " << node_id_to_hex(message.sender_id) << " at " << sender.ip << ":" << sender.port);
923
-
924
- #ifdef RATS_SEARCH_FEATURES
925
- bool is_spider = spider_mode_.load();
926
- // Only use neighbor_id for IPs we've contacted via spider (to avoid polluting other DHT clients)
927
- bool use_neighbor_id = is_spider && is_spider_contacted_ip(sender.ip);
928
-
929
- // Spider mode: check if ignoring requests (but still process announces for callback)
930
- // Note: We still want to collect announces even when ignoring other requests
931
-
932
- // In spider mode, skip token verification for maximum collection
933
- if (!is_spider && !verify_token(sender, message.token)) {
934
- LOG_DHT_WARN("Invalid token from " << sender.ip << ":" << sender.port << " for KRPC ANNOUNCE_PEER");
935
- auto error = KrpcProtocol::create_error(message.transaction_id, KrpcErrorCode::ProtocolError, "Invalid token");
936
- send_krpc_message(error, sender);
937
- return;
938
- }
939
- #else
940
- // Verify token
941
- if (!verify_token(sender, message.token)) {
942
- LOG_DHT_WARN("Invalid token from " << sender.ip << ":" << sender.port << " for KRPC ANNOUNCE_PEER");
943
- auto error = KrpcProtocol::create_error(message.transaction_id, KrpcErrorCode::ProtocolError, "Invalid token");
944
- send_krpc_message(error, sender);
945
- return;
946
- }
947
- bool is_spider = false;
948
- bool use_neighbor_id = false;
949
- #endif
950
-
951
- // Add sender to routing table (or spider pool in spider mode)
952
- KrpcNode krpc_node(message.sender_id, sender.ip, sender.port);
953
- DhtNode sender_node = krpc_node_to_dht_node(krpc_node);
954
-
955
- #ifdef RATS_SEARCH_FEATURES
956
- if (is_spider) {
957
- add_spider_node(sender_node);
958
- }
959
- #endif
960
- // Adding spider related node very undesirable but ok
961
- if (!use_neighbor_id)
962
- {
963
- add_node(sender_node, true, false);
964
- }
965
-
966
- // Determine the actual port (BEP 5: implied_port support)
967
- // If implied_port is set, use the UDP source port instead of the explicit port field
968
- uint16_t peer_port = message.implied_port ? sender.port : message.port;
969
-
970
- // Store the peer announcement
971
- Peer announcing_peer(sender.ip, peer_port);
972
- store_announced_peer(message.info_hash, announcing_peer);
973
-
974
- #ifdef RATS_SEARCH_FEATURES
975
- // Spider mode: invoke announce callback (ensured hash - peer definitely has it)
976
- if (is_spider) {
977
- SpiderAnnounceCallback callback;
978
- {
979
- std::lock_guard<std::mutex> lock(spider_callbacks_mutex_);
980
- callback = spider_announce_callback_;
981
- }
982
- if (callback) {
983
- LOG_DHT_DEBUG("Spider: invoking announce callback for info_hash " << node_id_to_hex(message.info_hash)
984
- << " from " << announcing_peer.ip << ":" << announcing_peer.port);
985
- callback(message.info_hash, announcing_peer);
986
- }
987
- }
988
- #endif
989
-
990
- // Respond with acknowledgment
991
- // Use neighbor_id only for spider-contacted IPs, real node_id for organic DHT traffic
992
- NodeId response_id = use_neighbor_id ? neighbor_id(message.info_hash) : node_id_;
993
- auto response = KrpcProtocol::create_announce_peer_response(message.transaction_id, response_id);
994
- send_krpc_message(response, sender);
995
- }
996
-
997
- void DhtClient::handle_krpc_response(const KrpcMessage& message, const Peer& sender) {
998
- LOG_DHT_DEBUG("Handling KRPC response from " << sender.ip << ":" << sender.port);
999
-
1000
- // BEP 42: nodes echo our external address back in the top-level "ip" field. Responses
1001
- // here are always replies to queries we sent, so the source is a node we chose to contact;
1002
- // we still require a consensus of distinct responders before regenerating our node ID.
1003
- if (!message.external_ip.empty()) {
1004
- maybe_update_external_ip(message.external_ip, sender);
1005
- }
1006
-
1007
- // Check if this is a ping verification response before normal processing
1008
- handle_ping_verification_response(message.transaction_id, message.response_id, sender);
1009
-
1010
- #ifdef RATS_SEARCH_FEATURES
1011
- // Check if this response is for a spider transaction
1012
- // This is based on how the request was sent, NOT current spider_mode_ state
1013
- // This ensures spider responses go to spider pool even if mode was toggled
1014
- bool is_spider_tx = is_spider_transaction(message.transaction_id);
1015
-
1016
- if (is_spider_tx) {
1017
- // Spider transaction response: add nodes to spider pool, NOT to routing table
1018
- // This keeps the routing table stable and clean
1019
- KrpcNode krpc_node(message.response_id, sender.ip, sender.port);
1020
- DhtNode sender_node = krpc_node_to_dht_node(krpc_node);
1021
- add_spider_node(sender_node);
1022
-
1023
- // Add discovered nodes to spider pool
1024
- std::vector<DhtNode> discovered_nodes;
1025
- discovered_nodes.reserve(message.nodes.size());
1026
- for (const auto& node : message.nodes) {
1027
- discovered_nodes.push_back(krpc_node_to_dht_node(node));
1028
- }
1029
- add_spider_nodes(discovered_nodes);
1030
-
1031
- LOG_DHT_DEBUG("Spider transaction response: added " << (1 + message.nodes.size()) << " nodes to spider pool");
1032
-
1033
- // Spider responses don't need search tracking - they're just for node discovery
1034
- // Early return to avoid polluting normal DHT operations
1035
- return;
1036
- }
1037
- #endif
1038
-
1039
- // Normal mode: add nodes to routing table
1040
- KrpcNode krpc_node(message.response_id, sender.ip, sender.port);
1041
- DhtNode sender_node = krpc_node_to_dht_node(krpc_node);
1042
- add_node(sender_node, true, false);
1043
-
1044
- // Add any nodes from the response (these are nodes we heard about, not confirmed)
1045
- for (const auto& node : message.nodes) {
1046
- DhtNode dht_node = krpc_node_to_dht_node(node);
1047
- add_node(dht_node, false, false); // Not confirmed - just heard about from another node
1048
- }
1049
-
1050
- // Check if this is a response to a pending search (get_peers with peers)
1051
- if (!message.peers.empty()) {
1052
- handle_get_peers_response_for_search(message.transaction_id, sender, message.peers);
1053
- }
1054
- // Check if this is a response to a pending search (get_peers with nodes)
1055
- else if (!message.nodes.empty()) {
1056
- handle_get_peers_response_with_nodes(message.transaction_id, sender, message.nodes);
1057
- }
1058
- else {
1059
- // Empty response (no peers, no nodes) - still need to mark as responded
1060
- // This can happen when a node has no information about the info_hash
1061
- handle_get_peers_empty_response(message.transaction_id, sender);
1062
- }
1063
-
1064
- // Save write token if present (needed for announce_peer after traversal completes)
1065
- if (!message.token.empty()) {
1066
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
1067
- auto trans_it = transaction_to_search_.find(message.transaction_id);
1068
- if (trans_it != transaction_to_search_.end()) {
1069
- auto search_it = pending_searches_.find(trans_it->second.info_hash_hex);
1070
- if (search_it != pending_searches_.end()) {
1071
- save_write_token(search_it->second, trans_it->second.queried_node_id, message.token);
1072
- }
1073
- }
1074
- }
1075
-
1076
- // Clean up finished searches AFTER all response data has been processed
1077
- // This ensures peers and nodes are fully handled before removing the search
1078
- {
1079
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
1080
- auto trans_it = transaction_to_search_.find(message.transaction_id);
1081
- if (trans_it != transaction_to_search_.end()) {
1082
- const std::string& hash_key = trans_it->second.info_hash_hex;
1083
- auto search_it = pending_searches_.find(hash_key);
1084
- if (search_it != pending_searches_.end() && search_it->second.is_finished) {
1085
- LOG_DHT_DEBUG("Cleaning up finished search for info_hash " << hash_key
1086
- << " after processing transaction " << message.transaction_id);
1087
- pending_searches_.erase(search_it);
1088
- }
1089
- // Always remove the transaction mapping after processing
1090
- transaction_to_search_.erase(trans_it);
1091
- }
1092
- }
1093
- }
1094
-
1095
- void DhtClient::handle_krpc_error(const KrpcMessage& message, const Peer& sender) {
1096
- LOG_DHT_WARN("Received KRPC error from " << sender.ip << ":" << sender.port
1097
- << " - Code: " << static_cast<int>(message.error_code)
1098
- << " Message: " << message.error_message);
1099
- }
1100
-
1101
- // KRPC sending functions
1102
- bool DhtClient::send_krpc_message(const KrpcMessage& message, const Peer& peer) {
1103
- // BEP 42: stamp the requester's external address into every response we send so the
1104
- // remote node can derive an IP-based node ID. Only copy the message when needed.
1105
- const KrpcMessage* out = &message;
1106
- KrpcMessage stamped;
1107
- if (message.type == KrpcMessageType::Response && message.external_ip.empty()) {
1108
- stamped = message;
1109
- stamped.external_ip = peer.ip;
1110
- stamped.external_port = peer.port;
1111
- out = &stamped;
1112
- }
1113
-
1114
- auto data = KrpcProtocol::encode_message(*out);
1115
- if (data.empty()) {
1116
- LOG_DHT_ERROR("Failed to encode KRPC message");
1117
- return false;
1118
- }
1119
-
1120
- LOG_DHT_DEBUG("Sending KRPC message (" << data.size() << " bytes) to " << peer.ip << ":" << peer.port);
1121
- int result = send_udp_data(socket_, data, peer.ip, peer.port, address_family_);
1122
-
1123
- if (result > 0) {
1124
- LOG_DHT_DEBUG("Successfully sent KRPC message to " << peer.ip << ":" << peer.port);
1125
- } else {
1126
- LOG_DHT_ERROR("Failed to send KRPC message to " << peer.ip << ":" << peer.port);
1127
- }
1128
-
1129
- return result > 0;
1130
- }
1131
-
1132
- void DhtClient::send_krpc_ping(const Peer& peer) {
1133
- std::string transaction_id = KrpcProtocol::generate_transaction_id();
1134
- auto message = KrpcProtocol::create_ping_query(transaction_id, node_id_);
1135
- send_krpc_message(message, peer);
1136
- }
1137
-
1138
- void DhtClient::send_krpc_find_node(const Peer& peer, const NodeId& target) {
1139
- std::string transaction_id = KrpcProtocol::generate_transaction_id();
1140
- auto message = KrpcProtocol::create_find_node_query(transaction_id, node_id_, target);
1141
- // BEP 32: ask only for nodes of our own family (separate Kademlia networks)
1142
- message.want.push_back(is_ipv6() ? "n6" : "n4");
1143
- send_krpc_message(message, peer);
1144
- }
1145
-
1146
- void DhtClient::send_krpc_get_peers(const Peer& peer, const InfoHash& info_hash) {
1147
- std::string transaction_id = KrpcProtocol::generate_transaction_id();
1148
- auto message = KrpcProtocol::create_get_peers_query(transaction_id, node_id_, info_hash);
1149
- // BEP 32: ask only for nodes of our own family (separate Kademlia networks)
1150
- message.want.push_back(is_ipv6() ? "n6" : "n4");
1151
- send_krpc_message(message, peer);
1152
- }
1153
-
1154
- void DhtClient::send_krpc_announce_peer(const Peer& peer, const InfoHash& info_hash, uint16_t port, const std::string& token, bool implied_port) {
1155
- std::string transaction_id = KrpcProtocol::generate_transaction_id();
1156
- auto message = KrpcProtocol::create_announce_peer_query(transaction_id, node_id_, info_hash, port, token, implied_port);
1157
- send_krpc_message(message, peer);
1158
- }
1159
-
1160
- // Conversion utilities
1161
- KrpcNode DhtClient::dht_node_to_krpc_node(const DhtNode& node) {
1162
- return KrpcNode(node.id, node.peer.ip, node.peer.port);
1163
- }
1164
-
1165
- DhtNode DhtClient::krpc_node_to_dht_node(const KrpcNode& node) {
1166
- Peer peer(node.ip, node.port);
1167
- return DhtNode(node.id, peer);
1168
- }
1169
-
1170
- std::vector<KrpcNode> DhtClient::dht_nodes_to_krpc_nodes(const std::vector<DhtNode>& nodes) {
1171
- std::vector<KrpcNode> krpc_nodes;
1172
- krpc_nodes.reserve(nodes.size());
1173
- for (const auto& node : nodes) {
1174
- krpc_nodes.push_back(dht_node_to_krpc_node(node));
1175
- }
1176
- return krpc_nodes;
1177
- }
1178
-
1179
- std::vector<DhtNode> DhtClient::krpc_nodes_to_dht_nodes(const std::vector<KrpcNode>& nodes) {
1180
- std::vector<DhtNode> dht_nodes;
1181
- dht_nodes.reserve(nodes.size());
1182
- for (const auto& node : nodes) {
1183
- dht_nodes.push_back(krpc_node_to_dht_node(node));
1184
- }
1185
- return dht_nodes;
1186
- }
1187
-
1188
- NodeId DhtClient::generate_node_id() {
1189
- NodeId id;
1190
- std::random_device rd;
1191
- std::mt19937 gen(rd());
1192
- std::uniform_int_distribution<> dis(0, 255);
1193
-
1194
- for (size_t i = 0; i < NODE_ID_SIZE; ++i) {
1195
- id[i] = dis(gen);
1196
- }
1197
-
1198
- return id;
1199
- }
1200
-
1201
- // ============================================================================
1202
- // BEP 42: deriving the node ID from the external IP address
1203
- // ============================================================================
1204
- namespace {
1205
-
1206
- // CRC-32C (Castagnoli) — the polynomial mandated by BEP 42. Standard parameters:
1207
- // reflected, init 0xFFFFFFFF, final XOR 0xFFFFFFFF. Bytes are processed in array order,
1208
- // matching the BEP 42 reference implementation and its published test vectors.
1209
- uint32_t crc32c(const uint8_t* data, size_t len) {
1210
- uint32_t crc = 0xFFFFFFFFu;
1211
- for (size_t i = 0; i < len; ++i) {
1212
- crc ^= data[i];
1213
- for (int k = 0; k < 8; ++k) {
1214
- crc = (crc & 1u) ? (crc >> 1) ^ 0x82F63B78u : (crc >> 1);
1215
- }
1216
- }
1217
- return crc ^ 0xFFFFFFFFu;
1218
- }
1219
-
1220
- // Mask the leading octets of an IP per BEP 42 (4 octets for IPv4, 8 for IPv6).
1221
- // Returns the number of octets written to `out`, or 0 on a parse failure.
1222
- int masked_octets(const std::string& ip, uint8_t out[8]) {
1223
- static const uint8_t v4_mask[4] = { 0x03, 0x0f, 0x3f, 0xff };
1224
- static const uint8_t v6_mask[8] = { 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff };
1225
-
1226
- if (network_utils::is_valid_ipv6(ip)) {
1227
- struct in6_addr addr6;
1228
- if (inet_pton(AF_INET6, ip.c_str(), &addr6) != 1) return 0;
1229
- for (int i = 0; i < 8; ++i) out[i] = addr6.s6_addr[i] & v6_mask[i];
1230
- return 8;
1231
- }
1232
-
1233
- struct in_addr addr;
1234
- if (inet_pton(AF_INET, ip.c_str(), &addr) != 1) return 0;
1235
- uint32_t h = ntohl(addr.s_addr);
1236
- uint8_t ipb[4] = {
1237
- static_cast<uint8_t>((h >> 24) & 0xff), static_cast<uint8_t>((h >> 16) & 0xff),
1238
- static_cast<uint8_t>((h >> 8) & 0xff), static_cast<uint8_t>(h & 0xff)
1239
- };
1240
- for (int i = 0; i < 4; ++i) out[i] = ipb[i] & v4_mask[i];
1241
- return 4;
1242
- }
1243
-
1244
- // Compute the 3 deterministic prefix bytes of a BEP 42 node ID for (ip, seed).
1245
- // Only the high 5 bits of prefix[2] are deterministic (the low 3 bits are random in a real ID).
1246
- bool bep42_prefix(const std::string& ip, uint8_t seed, uint8_t prefix[3]) {
1247
- uint8_t octets[8];
1248
- int num = masked_octets(ip, octets);
1249
- if (num == 0) return false;
1250
- octets[0] |= static_cast<uint8_t>((seed & 0x7) << 5);
1251
- uint32_t c = crc32c(octets, static_cast<size_t>(num));
1252
- prefix[0] = static_cast<uint8_t>((c >> 24) & 0xff);
1253
- prefix[1] = static_cast<uint8_t>((c >> 16) & 0xff);
1254
- prefix[2] = static_cast<uint8_t>((c >> 8) & 0xf8);
1255
- return true;
1256
- }
1257
-
1258
- } // namespace
1259
-
1260
- bool DhtClient::is_public_address(const std::string& ip) {
1261
- // Shared with automatic port forwarding; the canonical classifier lives in
1262
- // network_utils so both subsystems agree on what "publicly routable" means.
1263
- return network_utils::is_public_ip(ip);
1264
- }
1265
-
1266
- bool DhtClient::generate_node_id_from_ip(const std::string& ip, NodeId& out, std::mt19937& gen) {
1267
- uint8_t prefix[3];
1268
- std::uniform_int_distribution<int> dis(0, 255);
1269
- uint8_t seed = static_cast<uint8_t>(dis(gen));
1270
- if (!bep42_prefix(ip, seed, prefix)) return false;
1271
-
1272
- out[0] = prefix[0];
1273
- out[1] = prefix[1];
1274
- out[2] = static_cast<uint8_t>(prefix[2] | (dis(gen) & 0x7)); // low 3 bits are random
1275
- for (int i = 3; i < 19; ++i) out[i] = static_cast<uint8_t>(dis(gen));
1276
- out[19] = seed;
1277
- return true;
1278
- }
1279
-
1280
- bool DhtClient::verify_node_id_for_ip(const NodeId& id, const std::string& ip) {
1281
- // Local/private addresses cannot be verified (their IDs would be "wrong" anyway).
1282
- if (!is_public_address(ip)) return true;
1283
- uint8_t prefix[3];
1284
- if (!bep42_prefix(ip, id[19], prefix)) return true; // unparseable -> don't reject
1285
- return id[0] == prefix[0]
1286
- && id[1] == prefix[1]
1287
- && (id[2] & 0xf8) == prefix[2];
1288
- }
1289
-
1290
- void DhtClient::rebuild_routing_table_unlocked() {
1291
- // node_id_ changed; every node's bucket index is now stale. Re-bucket all of them.
1292
- std::vector<DhtNode> all;
1293
- for (auto& bucket : routing_table_) {
1294
- for (auto& node : bucket) all.push_back(std::move(node));
1295
- bucket.clear();
1296
- }
1297
- for (auto& node : all) {
1298
- int bucket_index = get_bucket_index(node.id);
1299
- if (bucket_index < 0 || bucket_index >= static_cast<int>(routing_table_.size())) continue;
1300
- auto& bucket = routing_table_[bucket_index];
1301
- if (bucket.size() < K_BUCKET_SIZE) bucket.push_back(std::move(node));
1302
- }
1303
- }
1304
-
1305
- void DhtClient::set_external_ip(const std::string& ip) {
1306
- // Only public addresses of this instance's family can derive a valid node ID.
1307
- if (!is_public_address(ip)) return;
1308
- if (network_utils::is_valid_ipv6(ip) != is_ipv6()) return;
1309
-
1310
- {
1311
- std::lock_guard<std::mutex> ext_lock(external_ip_mutex_);
1312
- if (ip == external_address_) return; // already using this address
1313
- external_address_ = ip;
1314
- }
1315
-
1316
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
1317
- // If our current ID already matches this IP, keep it (avoids needless churn).
1318
- if (verify_node_id_for_ip(node_id_, ip)) {
1319
- LOG_DHT_DEBUG("External IP " << ip << " already matches current node ID (BEP 42)");
1320
- return;
1321
- }
1322
-
1323
- std::random_device rd;
1324
- std::mt19937 gen(rd());
1325
- NodeId new_id;
1326
- if (!generate_node_id_from_ip(ip, new_id, gen)) return;
1327
-
1328
- NodeId old_id = node_id_;
1329
- node_id_ = new_id;
1330
- rebuild_routing_table_unlocked();
1331
- LOG_DHT_INFO("Regenerated DHT node ID from external IP " << ip << " (BEP 42): "
1332
- << node_id_to_hex(old_id) << " -> " << node_id_to_hex(new_id));
1333
- }
1334
-
1335
- std::string DhtClient::get_external_address() const {
1336
- std::lock_guard<std::mutex> lock(external_ip_mutex_);
1337
- return external_address_;
1338
- }
1339
-
1340
- void DhtClient::maybe_update_external_ip(const std::string& reported_ip, const Peer& responder) {
1341
- // Only consider public addresses of our own family.
1342
- if (!is_public_address(reported_ip)) return;
1343
- if (network_utils::is_valid_ipv6(reported_ip) != is_ipv6()) return;
1344
-
1345
- std::string winner;
1346
- {
1347
- std::lock_guard<std::mutex> lock(external_ip_mutex_);
1348
- if (reported_ip == external_address_) return; // already adopted
1349
-
1350
- // One vote per distinct responder so a single peer cannot force a change.
1351
- if (external_ip_voters_.size() >= MAX_EXTERNAL_IP_VOTERS) {
1352
- external_ip_voters_.clear();
1353
- external_ip_votes_.clear();
1354
- }
1355
- if (!external_ip_voters_.insert(responder.ip).second) return; // this responder already voted
1356
-
1357
- int votes = ++external_ip_votes_[reported_ip];
1358
- // A vote for an address other than our current one is genuinely interesting
1359
- // (startup ramp-up, or a possible address change), so surface it at INFO.
1360
- LOG_DHT_INFO("External IP vote from " << responder.ip << " -> " << reported_ip
1361
- << " (" << votes << "/" << EXTERNAL_IP_VOTE_THRESHOLD << ")");
1362
- if (votes >= EXTERNAL_IP_VOTE_THRESHOLD) {
1363
- winner = reported_ip;
1364
- external_ip_votes_.clear();
1365
- external_ip_voters_.clear();
1366
- }
1367
- }
1368
-
1369
- if (!winner.empty()) {
1370
- LOG_DHT_INFO("External IP consensus reached: " << winner
1371
- << " (>= " << EXTERNAL_IP_VOTE_THRESHOLD << " responders agree)");
1372
- set_external_ip(winner);
1373
- }
1374
- }
1375
-
1376
- NodeId DhtClient::xor_distance(const NodeId& a, const NodeId& b) {
1377
- NodeId result;
1378
- for (size_t i = 0; i < NODE_ID_SIZE; ++i) {
1379
- result[i] = a[i] ^ b[i];
1380
- }
1381
- return result;
1382
- }
1383
-
1384
- bool DhtClient::is_closer(const NodeId& a, const NodeId& b, const NodeId& target) {
1385
- NodeId dist_a = xor_distance(a, target);
1386
- NodeId dist_b = xor_distance(b, target);
1387
-
1388
- return std::lexicographical_compare(dist_a.begin(), dist_a.end(),
1389
- dist_b.begin(), dist_b.end());
1390
- }
1391
-
1392
- NodeId DhtClient::neighbor_id(const NodeId& target) const {
1393
- // Spider mode optimization from legacy implementation:
1394
- // Combine first 10 bytes of target with last 10 bytes of our node ID
1395
- // This makes us appear "close" to any target in the DHT keyspace,
1396
- // causing other nodes to route more queries to us
1397
- NodeId result;
1398
- std::copy(target.begin(), target.begin() + 10, result.begin());
1399
- std::copy(node_id_.begin() + 10, node_id_.end(), result.begin() + 10);
1400
- return result;
1401
- }
1402
-
1403
- std::string DhtClient::generate_token(const Peer& peer) {
1404
- // Simple token generation (in real implementation, use proper cryptographic hash)
1405
- std::string data = peer.ip + ":" + std::to_string(peer.port);
1406
- std::hash<std::string> hasher;
1407
- size_t hash = hasher(data);
1408
-
1409
- // Convert hash to hex string
1410
- std::ostringstream oss;
1411
- oss << std::hex << hash;
1412
- std::string token = oss.str();
1413
-
1414
- // Store token for this peer with timestamp
1415
- {
1416
- std::lock_guard<std::mutex> lock(peer_tokens_mutex_);
1417
- peer_tokens_[peer] = PeerToken(token);
1418
- }
1419
-
1420
- return token;
1421
- }
1422
-
1423
- bool DhtClient::verify_token(const Peer& peer, const std::string& token) {
1424
- std::lock_guard<std::mutex> lock(peer_tokens_mutex_);
1425
- auto it = peer_tokens_.find(peer);
1426
- if (it != peer_tokens_.end()) {
1427
- return it->second.token == token;
1428
- }
1429
- return false;
1430
- }
1431
-
1432
- void DhtClient::cleanup_stale_nodes() {
1433
- std::lock_guard<std::mutex> routing_lock(routing_table_mutex_);
1434
-
1435
- auto now = std::chrono::steady_clock::now();
1436
- auto stale_threshold = std::chrono::minutes(15);
1437
- constexpr uint8_t MAX_FAIL_COUNT = 3; // Remove after 3 consecutive failures
1438
-
1439
- size_t total_removed = 0;
1440
-
1441
- for (auto& bucket : routing_table_) {
1442
- auto old_size = bucket.size();
1443
-
1444
- bucket.erase(std::remove_if(bucket.begin(), bucket.end(),
1445
- [now, stale_threshold, MAX_FAIL_COUNT](const DhtNode& node) {
1446
- // Remove if too many failures
1447
- if (node.pinged() && node.fail_count >= MAX_FAIL_COUNT) {
1448
- LOG_DHT_DEBUG("Removing failed node " << node_id_to_hex(node.id)
1449
- << " (fail_count=" << static_cast<int>(node.fail_count) << ")");
1450
- return true;
1451
- }
1452
-
1453
- // Remove if never responded and too old
1454
- if (!node.pinged() && now - node.last_seen > stale_threshold) {
1455
- LOG_DHT_DEBUG("Removing unresponsive node " << node_id_to_hex(node.id)
1456
- << " (never responded, age > 15min)");
1457
- return true;
1458
- }
1459
-
1460
- return false;
1461
- }), bucket.end());
1462
-
1463
- total_removed += (old_size - bucket.size());
1464
- }
1465
-
1466
- if (total_removed > 0) {
1467
- LOG_DHT_DEBUG("Cleaned up " << total_removed << " stale/failed nodes from routing table");
1468
- }
1469
- }
1470
-
1471
- void DhtClient::cleanup_stale_peer_tokens() {
1472
- std::lock_guard<std::mutex> lock(peer_tokens_mutex_);
1473
-
1474
- auto now = std::chrono::steady_clock::now();
1475
- auto stale_threshold = std::chrono::minutes(10); // Tokens valid for 10 minutes (BEP 5 recommends tokens expire)
1476
-
1477
- size_t total_before = peer_tokens_.size();
1478
-
1479
- auto it = peer_tokens_.begin();
1480
- while (it != peer_tokens_.end()) {
1481
- if (now - it->second.created_at > stale_threshold) {
1482
- LOG_DHT_DEBUG("Removing stale token for peer " << it->first.ip << ":" << it->first.port);
1483
- it = peer_tokens_.erase(it);
1484
- } else {
1485
- ++it;
1486
- }
1487
- }
1488
-
1489
- size_t total_after = peer_tokens_.size();
1490
-
1491
- if (total_before > total_after) {
1492
- LOG_DHT_DEBUG("Cleaned up " << (total_before - total_after) << " stale peer tokens "
1493
- << "(from " << total_before << " to " << total_after << ")");
1494
- }
1495
- }
1496
-
1497
- void DhtClient::print_statistics() {
1498
- auto now = std::chrono::steady_clock::now();
1499
-
1500
- // Routing table statistics
1501
- size_t filled_buckets = 0;
1502
- size_t total_nodes = 0;
1503
- size_t max_bucket_size = 0;
1504
- size_t confirmed_nodes = 0;
1505
- size_t unpinged_nodes = 0;
1506
- size_t failed_nodes = 0;
1507
-
1508
- // Collect all nodes for best/worst analysis
1509
- std::vector<std::pair<DhtNode, int>> all_nodes; // node + bucket index
1510
-
1511
- {
1512
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
1513
- for (size_t bucket_idx = 0; bucket_idx < routing_table_.size(); ++bucket_idx) {
1514
- const auto& bucket = routing_table_[bucket_idx];
1515
- if (!bucket.empty()) {
1516
- filled_buckets++;
1517
- total_nodes += bucket.size();
1518
- max_bucket_size = (std::max)(max_bucket_size, bucket.size());
1519
-
1520
- for (const auto& node : bucket) {
1521
- all_nodes.emplace_back(node, static_cast<int>(bucket_idx));
1522
-
1523
- if (node.confirmed()) {
1524
- confirmed_nodes++;
1525
- } else if (!node.pinged()) {
1526
- unpinged_nodes++;
1527
- } else if (node.fail_count > 0) {
1528
- failed_nodes++;
1529
- }
1530
- }
1531
- }
1532
- }
1533
- }
1534
-
1535
- // Pending searches statistics
1536
- size_t pending_searches = 0;
1537
- size_t pending_announces = 0;
1538
- size_t total_search_nodes = 0;
1539
- size_t total_found_peers = 0;
1540
- size_t total_write_tokens = 0;
1541
- size_t active_transactions = 0;
1542
- {
1543
- std::lock_guard<std::mutex> search_lock(pending_searches_mutex_);
1544
- pending_searches = pending_searches_.size();
1545
- active_transactions = transaction_to_search_.size();
1546
- for (const auto& [hash, search] : pending_searches_) {
1547
- total_search_nodes += search.search_nodes.size();
1548
- total_found_peers += search.found_peers.size();
1549
- total_write_tokens += search.write_tokens.size();
1550
- if (search.is_announce) {
1551
- pending_announces++;
1552
- }
1553
- }
1554
- }
1555
-
1556
- // Announced peers statistics
1557
- size_t announced_peers_total = 0;
1558
- size_t announced_peers_infohashes = 0;
1559
- {
1560
- std::lock_guard<std::mutex> peers_lock(announced_peers_mutex_);
1561
- announced_peers_infohashes = announced_peers_.size();
1562
- for (const auto& entry : announced_peers_) {
1563
- announced_peers_total += entry.second.size();
1564
- }
1565
- }
1566
-
1567
- // Ping verification statistics
1568
- size_t pending_pings = 0;
1569
- size_t nodes_being_replaced = 0;
1570
- {
1571
- std::lock_guard<std::mutex> ping_lock(pending_pings_mutex_);
1572
- pending_pings = pending_pings_.size();
1573
- nodes_being_replaced = nodes_being_replaced_.size();
1574
- }
1575
-
1576
- // Peer tokens statistics
1577
- size_t peer_tokens_count = 0;
1578
- {
1579
- std::lock_guard<std::mutex> tokens_lock(peer_tokens_mutex_);
1580
- peer_tokens_count = peer_tokens_.size();
1581
- }
1582
-
1583
- // Spider mode statistics
1584
- #ifdef RATS_SEARCH_FEATURES
1585
- size_t spider_pool_size = 0;
1586
- size_t spider_visited_count = 0;
1587
- size_t spider_pending_transactions = 0;
1588
- size_t spider_contacted_ips_count = 0;
1589
- bool is_spider_active = spider_mode_.load();
1590
- {
1591
- std::lock_guard<std::mutex> spider_lock(spider_nodes_mutex_);
1592
- spider_pool_size = spider_nodes_.size();
1593
- spider_visited_count = spider_visited_.size();
1594
- spider_pending_transactions = spider_transactions_.size();
1595
- spider_contacted_ips_count = spider_contacted_ips_.size();
1596
- }
1597
- #endif
1598
-
1599
- // Print main statistics
1600
- LOG_DHT_INFO("=== DHT GLOBAL STATISTICS ===");
1601
- #ifdef RATS_SEARCH_FEATURES
1602
- if (is_spider_active || spider_pending_transactions > 0 || spider_contacted_ips_count > 0) {
1603
- LOG_DHT_INFO("[SPIDER MODE " << (is_spider_active ? "ACTIVE" : "INACTIVE") << "]");
1604
- LOG_DHT_INFO(" Spider pool size: " << spider_pool_size << "/" << MAX_SPIDER_NODES);
1605
- LOG_DHT_INFO(" Visited nodes: " << spider_visited_count << "/" << MAX_SPIDER_VISITED);
1606
- LOG_DHT_INFO(" Contacted IPs: " << spider_contacted_ips_count << "/" << MAX_SPIDER_CONTACTED_IPS);
1607
- LOG_DHT_INFO(" Pending transactions: " << spider_pending_transactions);
1608
- if (is_spider_active) {
1609
- LOG_DHT_INFO(" Ignore mode: " << (spider_ignore_.load() ? "ON" : "OFF"));
1610
- }
1611
- }
1612
- #endif
1613
- LOG_DHT_INFO("[ROUTING TABLE]");
1614
- LOG_DHT_INFO(" Total nodes: " << total_nodes << " (confirmed: " << confirmed_nodes
1615
- << ", unpinged: " << unpinged_nodes << ", failed: " << failed_nodes << ")");
1616
- LOG_DHT_INFO(" Filled buckets: " << filled_buckets << "/" << routing_table_.size()
1617
- << ", Max bucket size: " << max_bucket_size << "/" << K_BUCKET_SIZE);
1618
- LOG_DHT_INFO("[ACTIVE OPERATIONS]");
1619
- LOG_DHT_INFO(" Pending searches: " << pending_searches
1620
- << " (announces: " << pending_announces
1621
- << ", nodes: " << total_search_nodes
1622
- << ", peers: " << total_found_peers
1623
- << ", tokens: " << total_write_tokens << ")");
1624
- LOG_DHT_INFO(" Active transactions: " << active_transactions);
1625
- LOG_DHT_INFO(" Pending ping verifications: " << pending_pings
1626
- << " (nodes being replaced: " << nodes_being_replaced << ")");
1627
- LOG_DHT_INFO("[STORED DATA]");
1628
- LOG_DHT_INFO(" Announced peers: " << announced_peers_total
1629
- << " across " << announced_peers_infohashes << " infohashes");
1630
- LOG_DHT_INFO(" Peer tokens: " << peer_tokens_count);
1631
-
1632
- // Best/Worst nodes analysis
1633
- if (!all_nodes.empty()) {
1634
- // Sort by quality: confirmed first, then by RTT (lower is better)
1635
- std::sort(all_nodes.begin(), all_nodes.end(),
1636
- [](const std::pair<DhtNode, int>& a, const std::pair<DhtNode, int>& b) {
1637
- // Confirmed nodes are better
1638
- if (a.first.confirmed() != b.first.confirmed()) {
1639
- return a.first.confirmed();
1640
- }
1641
- // Lower fail_count is better
1642
- if (a.first.fail_count != b.first.fail_count) {
1643
- return a.first.fail_count < b.first.fail_count;
1644
- }
1645
- // Lower RTT is better (0xffff = unknown, treat as worst)
1646
- return a.first.rtt < b.first.rtt;
1647
- });
1648
-
1649
- // Calculate RTT statistics (excluding unknown)
1650
- uint32_t rtt_sum = 0;
1651
- uint16_t rtt_min = 0xffff;
1652
- uint16_t rtt_max = 0;
1653
- size_t rtt_count = 0;
1654
- for (const auto& [node, bucket_idx] : all_nodes) {
1655
- if (node.rtt != 0xffff) {
1656
- rtt_sum += node.rtt;
1657
- rtt_min = (std::min)(rtt_min, node.rtt);
1658
- rtt_max = (std::max)(rtt_max, node.rtt);
1659
- rtt_count++;
1660
- }
1661
- }
1662
-
1663
- LOG_DHT_INFO("[RTT STATISTICS]");
1664
- if (rtt_count > 0) {
1665
- LOG_DHT_INFO(" Known RTT nodes: " << rtt_count << "/" << total_nodes);
1666
- LOG_DHT_INFO(" RTT min/avg/max: " << rtt_min << "ms / "
1667
- << (rtt_sum / rtt_count) << "ms / " << rtt_max << "ms");
1668
- } else {
1669
- LOG_DHT_INFO(" No RTT data available");
1670
- }
1671
-
1672
- // Show top 5 best nodes
1673
- LOG_DHT_INFO("[TOP 5 BEST NODES]");
1674
- size_t best_count = (std::min)(size_t(5), all_nodes.size());
1675
- for (size_t i = 0; i < best_count; ++i) {
1676
- const auto& [node, bucket_idx] = all_nodes[i];
1677
- auto age_seconds = std::chrono::duration_cast<std::chrono::seconds>(now - node.last_seen).count();
1678
- std::string status = node.confirmed() ? "confirmed" :
1679
- (node.pinged() ? "pinged" : "unpinged");
1680
- std::string rtt_str = (node.rtt == 0xffff) ? "N/A" : std::to_string(node.rtt) + "ms";
1681
-
1682
- LOG_DHT_INFO(" #" << (i + 1) << " " << node.peer.ip << ":" << node.peer.port
1683
- << " | bucket:" << bucket_idx << " rtt:" << rtt_str
1684
- << " fails:" << static_cast<int>(node.fail_count)
1685
- << " " << status << " age:" << age_seconds << "s");
1686
- }
1687
-
1688
- // Show top 5 worst nodes
1689
- LOG_DHT_INFO("[TOP 5 WORST NODES]");
1690
- size_t worst_start = all_nodes.size() > 5 ? all_nodes.size() - 5 : 0;
1691
- for (size_t i = all_nodes.size(); i > worst_start; --i) {
1692
- const auto& [node, bucket_idx] = all_nodes[i - 1];
1693
- auto age_seconds = std::chrono::duration_cast<std::chrono::seconds>(now - node.last_seen).count();
1694
- std::string status = node.confirmed() ? "confirmed" :
1695
- (node.pinged() ? "pinged" : "unpinged");
1696
- std::string rtt_str = (node.rtt == 0xffff) ? "N/A" : std::to_string(node.rtt) + "ms";
1697
-
1698
- LOG_DHT_INFO(" #" << (all_nodes.size() - i + 1) << " " << node.peer.ip << ":" << node.peer.port
1699
- << " | bucket:" << bucket_idx << " rtt:" << rtt_str
1700
- << " fails:" << static_cast<int>(node.fail_count)
1701
- << " " << status << " age:" << age_seconds << "s");
1702
- }
1703
- } else {
1704
- LOG_DHT_INFO(" No nodes in routing table");
1705
- }
1706
- LOG_DHT_INFO("=== END DHT STATISTICS ===");
1707
- }
1708
-
1709
- void DhtClient::refresh_buckets() {
1710
- // Find random nodes in each bucket to refresh
1711
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
1712
-
1713
- for (size_t i = 0; i < routing_table_.size(); ++i) {
1714
- if (routing_table_[i].empty()) {
1715
- // Generate a random node ID in this bucket's range
1716
- NodeId random_id = generate_node_id();
1717
-
1718
- // Set the appropriate bits to place it in bucket i
1719
- int byte_index = static_cast<int>(i / 8);
1720
- int bit_index = static_cast<int>(i % 8);
1721
-
1722
- if (static_cast<size_t>(byte_index) < NODE_ID_SIZE) {
1723
- // Clear the target bit and higher bits
1724
- for (size_t j = static_cast<size_t>(byte_index); j < NODE_ID_SIZE; ++j) {
1725
- random_id[j] = node_id_[j];
1726
- }
1727
-
1728
- // Set the target bit
1729
- random_id[byte_index] |= (1 << (7 - bit_index));
1730
-
1731
- // Find nodes to query
1732
- auto closest_nodes = find_closest_nodes_unlocked(random_id, ALPHA);
1733
- for (const auto& node : closest_nodes) {
1734
- send_krpc_find_node(node.peer, random_id);
1735
- }
1736
- }
1737
- }
1738
- }
1739
- }
1740
-
1741
- void DhtClient::cleanup_stale_searches() {
1742
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
1743
-
1744
- auto now = std::chrono::steady_clock::now();
1745
- auto stale_threshold = std::chrono::minutes(5); // Remove searches older than 5 minutes
1746
-
1747
- // Clean up stale searches (by info_hash)
1748
- auto search_it = pending_searches_.begin();
1749
- while (search_it != pending_searches_.end()) {
1750
- if (now - search_it->second.created_at > stale_threshold) {
1751
- LOG_DHT_DEBUG("Removing stale pending search for info_hash " << search_it->first);
1752
- search_it = pending_searches_.erase(search_it);
1753
- } else {
1754
- ++search_it;
1755
- }
1756
- }
1757
-
1758
- // Clean up stale transaction mappings (remove ones that point to non-existent searches)
1759
- auto trans_it = transaction_to_search_.begin();
1760
- while (trans_it != transaction_to_search_.end()) {
1761
- if (pending_searches_.find(trans_it->second.info_hash_hex) == pending_searches_.end()) {
1762
- LOG_DHT_DEBUG("Removing stale transaction mapping " << trans_it->first << " -> " << trans_it->second.info_hash_hex);
1763
- trans_it = transaction_to_search_.erase(trans_it);
1764
- } else {
1765
- ++trans_it;
1766
- }
1767
- }
1768
- }
1769
-
1770
- void DhtClient::cleanup_search_node_states() {
1771
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
1772
- constexpr size_t MAX_NODE_STATES = 200; // Twice bigger than MAX_SEARCH_NODES
1773
-
1774
- for (auto& [hash_key, search] : pending_searches_) {
1775
- if (search.is_finished) {
1776
- continue;
1777
- }
1778
-
1779
- // Skip cleanup if node_states is within acceptable limits
1780
- if (search.node_states.size() <= MAX_NODE_STATES) {
1781
- continue;
1782
- }
1783
-
1784
- // Erase while iterating using iterator-based loop
1785
- size_t removed = 0;
1786
- auto it = search.node_states.begin();
1787
- while (it != search.node_states.end()) {
1788
- // В cleanup_search_node_states:
1789
- if ((it->second & SearchNodeFlags::ABANDONED) &&
1790
- ((it->second & (SearchNodeFlags::TIMED_OUT | SearchNodeFlags::RESPONDED)) ||
1791
- !(it->second & SearchNodeFlags::QUERIED))) { // Never queried = safe to remove immediately
1792
- it = search.node_states.erase(it);
1793
- removed++;
1794
- } else {
1795
- ++it;
1796
- }
1797
- }
1798
-
1799
- if (removed > 0) {
1800
- LOG_DHT_DEBUG("Cleaned up " << removed << " abandoned nodes for search " << hash_key
1801
- << " (remaining: " << search.node_states.size() << ")");
1802
- }
1803
- }
1804
- }
1805
-
1806
- void DhtClient::cleanup_timed_out_search_requests() {
1807
- std::vector<DeferredCallbacks> all_deferred;
1808
-
1809
- {
1810
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
1811
-
1812
- if (pending_searches_.empty()) {
1813
- return;
1814
- }
1815
-
1816
- auto now = std::chrono::steady_clock::now();
1817
- // - Short timeout (2s): Free up the slot by increasing branch_factor, but keep waiting for late response
1818
- // - Full timeout (15s): Mark node as failed and remove the transaction
1819
- auto short_timeout_threshold = std::chrono::seconds(2);
1820
- auto full_timeout_threshold = std::chrono::seconds(15);
1821
-
1822
- // Collect transactions that need short timeout or full timeout
1823
- std::vector<std::string> short_timeout_transactions;
1824
- std::vector<std::string> full_timeout_transactions;
1825
-
1826
- for (const auto& [transaction_id, trans_info] : transaction_to_search_) {
1827
- auto elapsed = now - trans_info.sent_at;
1828
-
1829
- if (elapsed > full_timeout_threshold) {
1830
- full_timeout_transactions.push_back(transaction_id);
1831
- } else if (elapsed > short_timeout_threshold) {
1832
- // Check if this node already has short timeout
1833
- auto search_it = pending_searches_.find(trans_info.info_hash_hex);
1834
- if (search_it != pending_searches_.end()) {
1835
- auto& search = search_it->second;
1836
- // Only process if not already marked with short timeout
1837
- auto state_it = search.node_states.find(trans_info.queried_node_id);
1838
- if (state_it == search.node_states.end() || !(state_it->second & SearchNodeFlags::SHORT_TIMEOUT)) {
1839
- short_timeout_transactions.push_back(transaction_id);
1840
- }
1841
- }
1842
- }
1843
- }
1844
-
1845
- // Group by search to batch process and call add_search_requests once per search
1846
- std::unordered_set<std::string> affected_searches;
1847
-
1848
- // Process short timeouts first - these nodes are slow but we still wait for a response
1849
- for (const auto& transaction_id : short_timeout_transactions) {
1850
- auto trans_it = transaction_to_search_.find(transaction_id);
1851
- if (trans_it == transaction_to_search_.end()) {
1852
- continue;
1853
- }
1854
-
1855
- const auto& trans_info = trans_it->second;
1856
- auto search_it = pending_searches_.find(trans_info.info_hash_hex);
1857
-
1858
- if (search_it != pending_searches_.end()) {
1859
- auto& search = search_it->second;
1860
-
1861
- if (!search.is_finished) {
1862
- // Check if this node was abandoned during truncation
1863
- auto state_it = search.node_states.find(trans_info.queried_node_id);
1864
- if (state_it != search.node_states.end() &&
1865
- (state_it->second & SearchNodeFlags::ABANDONED)) {
1866
- // Node was abandoned, skip short timeout processing
1867
- continue;
1868
- }
1869
-
1870
- // Mark node with short timeout (add flag, preserving existing flags)
1871
- search.node_states[trans_info.queried_node_id] |= SearchNodeFlags::SHORT_TIMEOUT;
1872
-
1873
- // Increase branch factor to allow another request (opening up a slot)
1874
- search.branch_factor++;
1875
-
1876
- LOG_DHT_DEBUG("Short timeout for node " << node_id_to_hex(trans_info.queried_node_id)
1877
- << " in search " << trans_info.info_hash_hex
1878
- << " - increased branch_factor to " << search.branch_factor
1879
- << " (still waiting for late response)");
1880
-
1881
- affected_searches.insert(trans_info.info_hash_hex);
1882
- }
1883
- }
1884
- // Note: We DON'T remove the transaction - we're still waiting for a possible late response
1885
- }
1886
-
1887
- // Process full timeouts - these nodes have completely failed
1888
- for (const auto& transaction_id : full_timeout_transactions) {
1889
- auto trans_it = transaction_to_search_.find(transaction_id);
1890
- if (trans_it == transaction_to_search_.end()) {
1891
- continue;
1892
- }
1893
-
1894
- const auto& trans_info = trans_it->second;
1895
- auto search_it = pending_searches_.find(trans_info.info_hash_hex);
1896
-
1897
- if (search_it != pending_searches_.end()) {
1898
- auto& search = search_it->second;
1899
-
1900
- if (!search.is_finished) {
1901
- // Get current flags for this node
1902
- uint8_t& flags = search.node_states[trans_info.queried_node_id];
1903
-
1904
- // Check if this node was abandoned during truncation
1905
- if (flags & SearchNodeFlags::ABANDONED) {
1906
- // Node was abandoned, invoke_count already decremented
1907
- // Mark as timed out so cleanup_search_node_states can remove it from node_states
1908
- flags |= SearchNodeFlags::TIMED_OUT;
1909
- transaction_to_search_.erase(trans_it);
1910
- continue;
1911
- }
1912
-
1913
- bool had_short_timeout = flags & SearchNodeFlags::SHORT_TIMEOUT;
1914
-
1915
- // Always decrement invoke_count on full timeout (node was still in-flight)
1916
- if (search.invoke_count > 0) {
1917
- search.invoke_count--;
1918
- }
1919
-
1920
- if (had_short_timeout) {
1921
- // Restore branch factor since node fully timed out
1922
- if (search.branch_factor > static_cast<int>(ALPHA)) {
1923
- search.branch_factor--;
1924
- }
1925
-
1926
- LOG_DHT_DEBUG("Full timeout for node " << node_id_to_hex(trans_info.queried_node_id)
1927
- << " in search " << trans_info.info_hash_hex
1928
- << " (had short timeout) - restored branch_factor to " << search.branch_factor
1929
- << ", invoke_count now: " << search.invoke_count);
1930
- } else {
1931
- LOG_DHT_DEBUG("Full timeout for node " << node_id_to_hex(trans_info.queried_node_id)
1932
- << " in search " << trans_info.info_hash_hex
1933
- << " - invoke_count now: " << search.invoke_count);
1934
- }
1935
-
1936
- // Mark the node as timed out (add flag, preserving history)
1937
- flags |= SearchNodeFlags::TIMED_OUT;
1938
-
1939
- // Mark the node as failed in routing table (BEP 5 compliance)
1940
- {
1941
- std::lock_guard<std::mutex> rt_lock(routing_table_mutex_);
1942
- int bucket_index = get_bucket_index(trans_info.queried_node_id);
1943
- auto& bucket = routing_table_[bucket_index];
1944
- auto node_it = std::find_if(bucket.begin(), bucket.end(),
1945
- [&trans_info](const DhtNode& n) { return n.id == trans_info.queried_node_id; });
1946
- if (node_it != bucket.end()) {
1947
- node_it->mark_failed();
1948
- LOG_DHT_DEBUG("Marked node " << node_id_to_hex(trans_info.queried_node_id)
1949
- << " as failed in routing table (fail_count="
1950
- << static_cast<int>(node_it->fail_count) << ")");
1951
- }
1952
- }
1953
-
1954
- affected_searches.insert(trans_info.info_hash_hex);
1955
- }
1956
- }
1957
-
1958
- // Remove the fully timed out transaction
1959
- transaction_to_search_.erase(trans_it);
1960
- }
1961
-
1962
- if (!short_timeout_transactions.empty() || !full_timeout_transactions.empty()) {
1963
- LOG_DHT_DEBUG("Timeout handling: " << short_timeout_transactions.size() << " short timeouts, "
1964
- << full_timeout_transactions.size() << " full timeouts");
1965
- }
1966
-
1967
- // Continue searches that had timeout events
1968
- for (const auto& hash_key : affected_searches) {
1969
- auto search_it = pending_searches_.find(hash_key);
1970
- if (search_it != pending_searches_.end() && !search_it->second.is_finished) {
1971
- LOG_DHT_DEBUG("Continuing search " << hash_key << " after timeout handling");
1972
- DeferredCallbacks deferred;
1973
- add_search_requests(search_it->second, deferred);
1974
- if (deferred.should_invoke) {
1975
- all_deferred.push_back(std::move(deferred));
1976
- }
1977
- }
1978
- }
1979
-
1980
- // Clean up finished searches
1981
- for (const auto& hash_key : affected_searches) {
1982
- auto search_it = pending_searches_.find(hash_key);
1983
- if (search_it != pending_searches_.end() && search_it->second.is_finished) {
1984
- LOG_DHT_DEBUG("Removing finished search " << hash_key << " after timeout handling");
1985
- pending_searches_.erase(search_it);
1986
- }
1987
- }
1988
- }
1989
-
1990
- // Invoke all deferred callbacks outside the lock to avoid deadlock
1991
- for (auto& deferred : all_deferred) {
1992
- deferred.invoke();
1993
- }
1994
- }
1995
-
1996
- void DhtClient::handle_get_peers_empty_response(const std::string& transaction_id, const Peer& responder) {
1997
- DeferredCallbacks deferred;
1998
- {
1999
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
2000
- auto trans_it = transaction_to_search_.find(transaction_id);
2001
- if (trans_it != transaction_to_search_.end()) {
2002
- const auto& trans_info = trans_it->second;
2003
- auto search_it = pending_searches_.find(trans_info.info_hash_hex);
2004
- if (search_it != pending_searches_.end()) {
2005
- auto& pending_search = search_it->second;
2006
-
2007
- // Check if this node was abandoned during truncation
2008
- auto state_it = pending_search.node_states.find(trans_info.queried_node_id);
2009
- if (state_it != pending_search.node_states.end() &&
2010
- (state_it->second & SearchNodeFlags::ABANDONED)) {
2011
- // Mark as responded so cleanup_search_node_states can remove it
2012
- state_it->second |= SearchNodeFlags::RESPONDED;
2013
- LOG_DHT_DEBUG("Ignoring empty response from abandoned node "
2014
- << node_id_to_hex(trans_info.queried_node_id));
2015
- return;
2016
- }
2017
-
2018
- uint8_t& flags = pending_search.node_states[trans_info.queried_node_id];
2019
-
2020
- if (flags & SearchNodeFlags::RESPONDED) {
2021
- LOG_DHT_DEBUG("Ignoring duplicate response from node " << node_id_to_hex(trans_info.queried_node_id));
2022
- return;
2023
- }
2024
-
2025
- // Decrement invoke count
2026
- if (pending_search.invoke_count > 0) {
2027
- pending_search.invoke_count--;
2028
- }
2029
-
2030
- // Restore branch_factor if had short timeout
2031
- if (flags & SearchNodeFlags::SHORT_TIMEOUT) {
2032
- if (pending_search.branch_factor > static_cast<int>(ALPHA)) {
2033
- pending_search.branch_factor--;
2034
- }
2035
- }
2036
-
2037
- // Mark as responded
2038
- flags |= SearchNodeFlags::RESPONDED;
2039
-
2040
- LOG_DHT_DEBUG("Empty get_peers response from " << responder.ip << ":" << responder.port
2041
- << " for info_hash " << trans_info.info_hash_hex
2042
- << " (invoke_count now: " << pending_search.invoke_count << ")");
2043
-
2044
- // Continue search
2045
- add_search_requests(pending_search, deferred);
2046
- }
2047
- }
2048
- }
2049
-
2050
- deferred.invoke();
2051
- }
2052
-
2053
- void DhtClient::handle_get_peers_response_for_search(const std::string& transaction_id, const Peer& responder, const std::vector<Peer>& peers) {
2054
- DeferredCallbacks deferred_immediate; // For new peers callbacks
2055
- DeferredCallbacks deferred_completion; // For search completion callbacks
2056
-
2057
- {
2058
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
2059
- auto trans_it = transaction_to_search_.find(transaction_id);
2060
- if (trans_it != transaction_to_search_.end()) {
2061
- const auto& trans_info = trans_it->second;
2062
- auto search_it = pending_searches_.find(trans_info.info_hash_hex);
2063
- if (search_it != pending_searches_.end()) {
2064
- auto& pending_search = search_it->second;
2065
-
2066
- // Check if this node was abandoned during truncation
2067
- auto state_it = pending_search.node_states.find(trans_info.queried_node_id);
2068
- if (state_it != pending_search.node_states.end() &&
2069
- (state_it->second & SearchNodeFlags::ABANDONED)) {
2070
- // Mark as responded so cleanup_search_node_states can remove it
2071
- state_it->second |= SearchNodeFlags::RESPONDED;
2072
- LOG_DHT_DEBUG("Ignoring response from abandoned node "
2073
- << node_id_to_hex(trans_info.queried_node_id)
2074
- << " - invoke_count already decremented during truncation");
2075
- return;
2076
- }
2077
-
2078
- // Get flags for this node and mark as responded
2079
- uint8_t& flags = pending_search.node_states[trans_info.queried_node_id];
2080
-
2081
- // Check if already responded (duplicate response)
2082
- if (flags & SearchNodeFlags::RESPONDED) {
2083
- LOG_DHT_DEBUG("Ignoring duplicate response from node "
2084
- << node_id_to_hex(trans_info.queried_node_id));
2085
- return;
2086
- }
2087
-
2088
- // Decrement invoke count since we received a response
2089
- if (pending_search.invoke_count > 0) {
2090
- pending_search.invoke_count--;
2091
- }
2092
-
2093
- // If this node had short timeout, restore the branch factor (late response arrived)
2094
- if (flags & SearchNodeFlags::SHORT_TIMEOUT) {
2095
- if (pending_search.branch_factor > static_cast<int>(ALPHA)) {
2096
- pending_search.branch_factor--;
2097
- }
2098
- LOG_DHT_DEBUG("Late response from node " << node_id_to_hex(trans_info.queried_node_id)
2099
- << " (had short timeout) - restored branch_factor to " << pending_search.branch_factor);
2100
- }
2101
-
2102
- // Mark as responded (add flag, preserving history including SHORT_TIMEOUT)
2103
- flags |= SearchNodeFlags::RESPONDED;
2104
-
2105
- LOG_DHT_DEBUG("Found pending search for KRPC transaction " << transaction_id
2106
- << " - received " << peers.size() << " peers for info_hash " << trans_info.info_hash_hex
2107
- << " from " << responder.ip << ":" << responder.port
2108
- << " (invoke_count now: " << pending_search.invoke_count << ")");
2109
-
2110
- // Accumulate peers (with deduplication) - continue search like reference implementation
2111
- if (!peers.empty()) {
2112
- // Collect only new (non-duplicate) peers for immediate callback
2113
- std::vector<Peer> new_peers;
2114
- new_peers.reserve(peers.size());
2115
-
2116
- for (const auto& peer : peers) {
2117
- // Check if peer already exists in found_peers
2118
- auto it = std::find_if(pending_search.found_peers.begin(),
2119
- pending_search.found_peers.end(),
2120
- [&peer](const Peer& p) {
2121
- return p.ip == peer.ip && p.port == peer.port;
2122
- });
2123
- if (it == pending_search.found_peers.end()) {
2124
- pending_search.found_peers.push_back(peer);
2125
- new_peers.push_back(peer);
2126
- LOG_DHT_DEBUG(" [new] found peer for hash(" << trans_info.info_hash_hex << ") = " << peer.ip << ":" << peer.port);
2127
- }
2128
- }
2129
-
2130
- // Collect immediate callbacks for new peers
2131
- if (!new_peers.empty()) {
2132
- LOG_DHT_DEBUG("Invoking " << pending_search.callbacks.size() << " callbacks with "
2133
- << new_peers.size() << " new peers for info_hash " << trans_info.info_hash_hex);
2134
- deferred_immediate.should_invoke = true;
2135
- deferred_immediate.peers = std::move(new_peers);
2136
- deferred_immediate.info_hash = pending_search.info_hash;
2137
- deferred_immediate.callbacks = pending_search.callbacks;
2138
- }
2139
-
2140
- LOG_DHT_DEBUG("Accumulated " << pending_search.found_peers.size() << " total peers for info_hash " << trans_info.info_hash_hex);
2141
- }
2142
-
2143
- // Continue search - let add_search_requests determine when to finish
2144
- add_search_requests(pending_search, deferred_completion);
2145
- }
2146
-
2147
- // DON'T remove the transaction mapping here - it will be removed at the end of handle_krpc_response
2148
- // This ensures all response data is fully processed before cleanup
2149
- }
2150
- }
2151
-
2152
- // Invoke all callbacks outside the lock to avoid deadlock
2153
- deferred_immediate.invoke();
2154
- deferred_completion.invoke();
2155
- }
2156
-
2157
-
2158
- void DhtClient::handle_get_peers_response_with_nodes(const std::string& transaction_id, const Peer& responder, const std::vector<KrpcNode>& nodes) {
2159
- // This function is called when get_peers returns nodes instead of peers
2160
- // Add the new nodes to search_nodes and continue the search
2161
-
2162
- DeferredCallbacks deferred;
2163
-
2164
- {
2165
- std::lock_guard<std::mutex> lock(pending_searches_mutex_);
2166
-
2167
- auto trans_it = transaction_to_search_.find(transaction_id);
2168
- if (trans_it != transaction_to_search_.end()) {
2169
- const auto& trans_info = trans_it->second;
2170
- auto search_it = pending_searches_.find(trans_info.info_hash_hex);
2171
- if (search_it != pending_searches_.end()) {
2172
- auto& pending_search = search_it->second;
2173
-
2174
- // Check if this node was abandoned during truncation
2175
- auto state_it = pending_search.node_states.find(trans_info.queried_node_id);
2176
- if (state_it != pending_search.node_states.end() &&
2177
- (state_it->second & SearchNodeFlags::ABANDONED)) {
2178
- // Mark as responded so cleanup_search_node_states can remove it
2179
- state_it->second |= SearchNodeFlags::RESPONDED;
2180
- LOG_DHT_DEBUG("Ignoring response from abandoned node "
2181
- << node_id_to_hex(trans_info.queried_node_id)
2182
- << " - invoke_count already decremented during truncation");
2183
- return;
2184
- }
2185
-
2186
- // Get flags for this node and mark as responded
2187
- uint8_t& flags = pending_search.node_states[trans_info.queried_node_id];
2188
-
2189
- // Check if already responded (duplicate response)
2190
- if (flags & SearchNodeFlags::RESPONDED) {
2191
- LOG_DHT_DEBUG("Ignoring duplicate response from node "
2192
- << node_id_to_hex(trans_info.queried_node_id));
2193
- return;
2194
- }
2195
-
2196
- // Decrement invoke count since we received a response
2197
- if (pending_search.invoke_count > 0) {
2198
- pending_search.invoke_count--;
2199
- }
2200
-
2201
- // If this node had short timeout, restore the branch factor (late response arrived)
2202
- if (flags & SearchNodeFlags::SHORT_TIMEOUT) {
2203
- if (pending_search.branch_factor > static_cast<int>(ALPHA)) {
2204
- pending_search.branch_factor--;
2205
- }
2206
- LOG_DHT_DEBUG("Late response from node " << node_id_to_hex(trans_info.queried_node_id)
2207
- << " (had short timeout) - restored branch_factor to " << pending_search.branch_factor);
2208
- }
2209
-
2210
- // Mark as responded (add flag, preserving history including SHORT_TIMEOUT)
2211
- flags |= SearchNodeFlags::RESPONDED;
2212
-
2213
- LOG_DHT_DEBUG("Processing get_peers response with " << nodes.size()
2214
- << " nodes for info_hash " << trans_info.info_hash_hex << " from " << responder.ip << ":" << responder.port
2215
- << " (invoke_count now: " << pending_search.invoke_count << ")");
2216
-
2217
- // Add new nodes to search_nodes (sorted by distance)
2218
- size_t nodes_added = 0;
2219
- for (const auto& node : nodes) {
2220
- DhtNode dht_node = krpc_node_to_dht_node(node);
2221
- size_t old_size = pending_search.search_nodes.size();
2222
- add_node_to_search(pending_search, dht_node);
2223
- if (pending_search.search_nodes.size() > old_size) {
2224
- nodes_added++;
2225
- }
2226
- }
2227
-
2228
- LOG_DHT_DEBUG("Added " << nodes_added << " new nodes to search_nodes (total: " << pending_search.search_nodes.size() << ")");
2229
-
2230
- // Continue search with new nodes
2231
- add_search_requests(pending_search, deferred);
2232
- }
2233
-
2234
- // DON'T remove the transaction mapping here - it will be removed at the end of handle_krpc_response
2235
- // This ensures all response data is fully processed before cleanup
2236
- }
2237
- }
2238
-
2239
- // Invoke callbacks outside the lock to avoid deadlock
2240
- deferred.invoke();
2241
- }
2242
-
2243
-
2244
- void DhtClient::add_node_to_search(PendingSearch& search, const DhtNode& node) {
2245
- // Check if node already exists in search (node is "known" if it's in node_states map)
2246
- if (search.node_states.find(node.id) != search.node_states.end()) {
2247
- LOG_DHT_DEBUG("Node " << node_id_to_hex(node.id) << " already known for search - skipping");
2248
- return;
2249
- }
2250
-
2251
- // Find insertion point to maintain sorted order (closest first)
2252
- auto insert_pos = std::lower_bound(search.search_nodes.begin(), search.search_nodes.end(), node,
2253
- [&search, this](const DhtNode& a, const DhtNode& b) {
2254
- return is_closer(a.id, b.id, search.info_hash);
2255
- });
2256
-
2257
- search.search_nodes.insert(insert_pos, node);
2258
- // Mark node as known (add to map with no flags set - will get QUERIED flag when query is sent)
2259
- search.node_states[node.id] = 0;
2260
-
2261
- // Limit search_nodes size to avoid unbounded growth
2262
- constexpr size_t MAX_SEARCH_NODES = 100;
2263
- if (search.search_nodes.size() > MAX_SEARCH_NODES) {
2264
- // Before truncating, clean up counters for in-flight queries being discarded
2265
- for (size_t i = MAX_SEARCH_NODES; i < search.search_nodes.size(); ++i) {
2266
- const auto& discarded_node = search.search_nodes[i];
2267
- auto state_it = search.node_states.find(discarded_node.id);
2268
- if (state_it != search.node_states.end()) {
2269
- uint8_t flags = state_it->second;
2270
- // If queried but not responded/failed, it's in-flight
2271
- if ((flags & SearchNodeFlags::QUERIED) &&
2272
- !(flags & (SearchNodeFlags::RESPONDED | SearchNodeFlags::TIMED_OUT))) {
2273
- // Decrement invoke_count since this request is being abandoned
2274
- if (search.invoke_count > 0) {
2275
- search.invoke_count--;
2276
- LOG_DHT_DEBUG("Decrementing invoke_count for abandoned node "
2277
- << node_id_to_hex(discarded_node.id)
2278
- << " (now: " << search.invoke_count << ")");
2279
- }
2280
- // If it had short timeout, also restore branch factor
2281
- if (flags & SearchNodeFlags::SHORT_TIMEOUT) {
2282
- if (search.branch_factor > static_cast<int>(ALPHA)) {
2283
- search.branch_factor--;
2284
- LOG_DHT_DEBUG("Decrementing branch_factor for abandoned node with short_timeout "
2285
- << node_id_to_hex(discarded_node.id)
2286
- << " (now: " << search.branch_factor << ")");
2287
- }
2288
- }
2289
- }
2290
- // Mark as ABANDONED instead of removing - prevents double invoke_count decrement
2291
- // when late response arrives (response handlers check this flag)
2292
- state_it->second |= SearchNodeFlags::ABANDONED;
2293
- }
2294
- }
2295
- search.search_nodes.resize(MAX_SEARCH_NODES);
2296
- }
2297
- }
2298
-
2299
- void DhtClient::save_write_token(PendingSearch& search, const NodeId& node_id, const std::string& token) {
2300
- // Save the write token received from a node (BEP 5 compliant)
2301
- // This token will be used later when sending announce_peer to this node
2302
-
2303
- if (token.empty()) {
2304
- return;
2305
- }
2306
-
2307
- // Only save token if we don't already have one from this node
2308
- // (first token is usually the valid one)
2309
- if (search.write_tokens.find(node_id) == search.write_tokens.end()) {
2310
- search.write_tokens[node_id] = token;
2311
- LOG_DHT_DEBUG("Saved write token from node " << node_id_to_hex(node_id)
2312
- << " for info_hash " << node_id_to_hex(search.info_hash)
2313
- << " (total tokens: " << search.write_tokens.size() << ")");
2314
- }
2315
- }
2316
-
2317
- void DhtClient::send_announce_to_closest_nodes(PendingSearch& search) {
2318
- // BEP 5: Send announce_peer to the k closest nodes that:
2319
- // 1. Responded to our get_peers query
2320
- // 2. Gave us a valid write token
2321
-
2322
- if (!search.is_announce) {
2323
- return;
2324
- }
2325
-
2326
- std::string hash_key = node_id_to_hex(search.info_hash);
2327
-
2328
- LOG_DHT_INFO("Sending announce_peer to closest nodes for info_hash " << hash_key
2329
- << " on port " << search.announce_port);
2330
-
2331
- // Collect nodes that responded and have tokens, sorted by distance (closest first)
2332
- std::vector<std::pair<DhtNode, std::string>> announce_targets;
2333
- announce_targets.reserve(K_BUCKET_SIZE);
2334
-
2335
- for (const auto& node : search.search_nodes) {
2336
- if (announce_targets.size() >= K_BUCKET_SIZE) {
2337
- break; // We have enough targets
2338
- }
2339
-
2340
- // Check if node responded successfully
2341
- auto state_it = search.node_states.find(node.id);
2342
- if (state_it == search.node_states.end()) {
2343
- continue;
2344
- }
2345
- if (!(state_it->second & SearchNodeFlags::RESPONDED)) {
2346
- continue; // Node didn't respond
2347
- }
2348
-
2349
- // Check if we have a token from this node
2350
- auto token_it = search.write_tokens.find(node.id);
2351
- if (token_it == search.write_tokens.end()) {
2352
- LOG_DHT_DEBUG("Node " << node_id_to_hex(node.id) << " responded but no token - skipping");
2353
- continue; // No token from this node
2354
- }
2355
-
2356
- announce_targets.emplace_back(node, token_it->second);
2357
- }
2358
-
2359
- if (announce_targets.empty()) {
2360
- LOG_DHT_WARN("No nodes with tokens to announce to for info_hash " << hash_key);
2361
- return;
2362
- }
2363
-
2364
- LOG_DHT_INFO("Announcing to " << announce_targets.size() << " closest nodes with tokens");
2365
-
2366
- // BEP 5: Use implied_port when the announce port is the same as the DHT port.
2367
- // This tells the receiving node to use the UDP source port from the packet,
2368
- // which is more accurate when behind NAT.
2369
- bool use_implied_port = (search.announce_port == port_);
2370
-
2371
- // Send announce_peer to each target
2372
- for (const auto& [node, token] : announce_targets) {
2373
- LOG_DHT_DEBUG("Sending announce_peer to node " << node_id_to_hex(node.id)
2374
- << " at " << node.peer.ip << ":" << node.peer.port
2375
- << " with token (distance: " << get_bucket_index(node.id) << ")"
2376
- << (use_implied_port ? " [implied_port]" : ""));
2377
-
2378
- send_krpc_announce_peer(node.peer, search.info_hash, search.announce_port, token, use_implied_port);
2379
- }
2380
-
2381
- LOG_DHT_INFO("Announce completed: sent announce_peer to " << announce_targets.size()
2382
- << " nodes for info_hash " << hash_key);
2383
- }
2384
-
2385
- bool DhtClient::add_search_requests(PendingSearch& search, DeferredCallbacks& deferred) {
2386
- // Returns true if search is done (completed or should be finished)
2387
-
2388
- if (search.is_finished) {
2389
- return true;
2390
- }
2391
-
2392
- std::string hash_key = node_id_to_hex(search.info_hash);
2393
-
2394
- LOG_DHT_DEBUG("Adding search requests for info_hash " << hash_key);
2395
-
2396
- const int k = static_cast<int>(K_BUCKET_SIZE); // Target number of results
2397
- int loop_index = -1;
2398
- int results_found = 0; // Nodes that have responded
2399
- int queries_in_flight = 0; // Requests currently in flight
2400
- int timed_out_count = 0; // Nodes that timed out
2401
- int queries_sent = 0; // Queries sent this round
2402
-
2403
- // Iterate through search_nodes (sorted by distance, closest first)
2404
- // Important: We must continue iterating to count results even when we can't send more requests
2405
- for (auto& node : search.search_nodes) {
2406
- loop_index++;
2407
-
2408
- // Stop if we have enough completed results
2409
- if (results_found >= k) {
2410
- break;
2411
- }
2412
-
2413
- // Get flags for this node (0 if not in map, meaning just "known")
2414
- auto state_it = search.node_states.find(node.id);
2415
- uint8_t flags = (state_it != search.node_states.end()) ? state_it->second : 0;
2416
-
2417
- // Usually it doesn't happen, but if it does, we skip it
2418
- if (flags & SearchNodeFlags::ABANDONED) {
2419
- continue;
2420
- }
2421
-
2422
- // Check if this node has already responded (counts toward results)
2423
- if (flags & SearchNodeFlags::RESPONDED) {
2424
- results_found++;
2425
- continue;
2426
- }
2427
-
2428
- // Skip nodes that have timed out (don't count as results or in-flight)
2429
- if (flags & SearchNodeFlags::TIMED_OUT) {
2430
- timed_out_count++;
2431
- continue;
2432
- }
2433
-
2434
- // Check if this node was already queried
2435
- if (flags & SearchNodeFlags::QUERIED) {
2436
- // Only count as in-flight if not responded yet
2437
- // (TIMED_OUT already handled above, RESPONDED handled above too)
2438
- // This case handles nodes that are QUERIED but still waiting for response
2439
- queries_in_flight++;
2440
- continue;
2441
- }
2442
-
2443
- // Check if we have capacity to send more requests
2444
- // Important: use 'continue' not 'break' to keep counting results
2445
- // Use adaptive branch_factor (increases on short timeout, restores on response/full timeout)
2446
- if (search.invoke_count >= search.branch_factor) {
2447
- continue;
2448
- }
2449
-
2450
- // Send query to this node
2451
- std::string transaction_id = KrpcProtocol::generate_transaction_id();
2452
- transaction_to_search_[transaction_id] = SearchTransaction(hash_key, node.id);
2453
- search.node_states[node.id] |= SearchNodeFlags::QUERIED;
2454
- search.invoke_count++;
2455
-
2456
- LOG_DHT_DEBUG("Querying node " << node_id_to_hex(node.id) << " at " << node.peer.ip << ":" << node.peer.port);
2457
-
2458
- auto message = KrpcProtocol::create_get_peers_query(transaction_id, node_id_, search.info_hash);
2459
- // BEP 32: request peers/nodes of our own family only
2460
- message.want.push_back(is_ipv6() ? "n6" : "n4");
2461
- send_krpc_message(message, node.peer);
2462
-
2463
- queries_sent++;
2464
- }
2465
-
2466
- LOG_DHT_DEBUG((search.is_announce ? "Announce" : "Search") << " [" << hash_key << "] progress [ms: " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - search.created_at).count() << "]:");
2467
- LOG_DHT_DEBUG(" * search_nodes: " << search.search_nodes.size());
2468
- LOG_DHT_DEBUG(" * queries_sent: " << queries_sent);
2469
- LOG_DHT_DEBUG(" * invoke_count: " << search.invoke_count);
2470
- LOG_DHT_DEBUG(" * branch_factor: " << search.branch_factor);
2471
- LOG_DHT_DEBUG(" * results_found: " << results_found);
2472
- LOG_DHT_DEBUG(" * queries_in_flight: " << queries_in_flight);
2473
- LOG_DHT_DEBUG(" * timed_out: " << timed_out_count);
2474
- LOG_DHT_DEBUG(" * peers_found: " << search.found_peers.size());
2475
- LOG_DHT_DEBUG(" * callbacks: " << search.callbacks.size());
2476
- LOG_DHT_DEBUG(" * loop_index: " << loop_index);
2477
- LOG_DHT_DEBUG(" * node_states: " << search.node_states.size());
2478
-
2479
- if ((results_found >= k && queries_in_flight == 0) || search.invoke_count == 0) {
2480
- auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
2481
- std::chrono::steady_clock::now() - search.created_at
2482
- ).count();
2483
-
2484
- // Count final stats for completion log
2485
- int queried_total = 0, responded_total = 0, timed_out_total = 0, short_timeout_total = 0, abandoned_total = 0;
2486
- for (const auto& [id, f] : search.node_states) {
2487
- if (f & SearchNodeFlags::QUERIED) queried_total++;
2488
- if (f & SearchNodeFlags::RESPONDED) responded_total++;
2489
- if (f & SearchNodeFlags::TIMED_OUT) timed_out_total++;
2490
- if (f & SearchNodeFlags::SHORT_TIMEOUT) short_timeout_total++;
2491
- if (f & SearchNodeFlags::ABANDONED) abandoned_total++;
2492
- }
2493
-
2494
- LOG_DHT_INFO("=== " << (search.is_announce ? "Announce" : "Search") << " Completed for info_hash " << hash_key << " ===");
2495
- LOG_DHT_INFO(" Duration: " << duration_ms << "ms");
2496
- LOG_DHT_INFO(" Total nodes queried: " << queried_total);
2497
- LOG_DHT_INFO(" Total nodes responded: " << responded_total);
2498
- LOG_DHT_INFO(" Total nodes timed out: " << timed_out_total);
2499
- LOG_DHT_INFO(" Nodes with short timeout: " << short_timeout_total);
2500
- LOG_DHT_INFO(" Nodes abandoned (truncation): " << abandoned_total);
2501
- LOG_DHT_INFO(" Final branch_factor: " << search.branch_factor << " (initial: " << ALPHA << ")");
2502
- if (search.is_announce) {
2503
- LOG_DHT_INFO(" Write tokens collected: " << search.write_tokens.size());
2504
- LOG_DHT_INFO(" Announce port: " << search.announce_port);
2505
- } else {
2506
- LOG_DHT_INFO(" Total peers found: " << search.found_peers.size());
2507
- LOG_DHT_INFO(" Callbacks to invoke: " << search.callbacks.size());
2508
- }
2509
-
2510
- // If this is an announce search, send announce_peer to k closest nodes with tokens
2511
- if (search.is_announce) {
2512
- send_announce_to_closest_nodes(search);
2513
- }
2514
-
2515
- // Collect callbacks for deferred invocation (avoid deadlock - don't call user callbacks while holding mutex)
2516
- deferred.should_invoke = true;
2517
- deferred.callbacks = search.callbacks;
2518
- deferred.peers = search.found_peers;
2519
- deferred.info_hash = search.info_hash;
2520
-
2521
- search.is_finished = true;
2522
- return true;
2523
- }
2524
-
2525
- return false;
2526
- }
2527
-
2528
- // Peer announcement storage management
2529
- void DhtClient::store_announced_peer(const InfoHash& info_hash, const Peer& peer) {
2530
- std::lock_guard<std::mutex> lock(announced_peers_mutex_);
2531
-
2532
- std::string hash_key = node_id_to_hex(info_hash);
2533
- auto& peers = announced_peers_[hash_key];
2534
-
2535
- // Check if peer already exists
2536
- auto it = std::find_if(peers.begin(), peers.end(),
2537
- [&peer](const AnnouncedPeer& announced) {
2538
- return announced.peer.ip == peer.ip && announced.peer.port == peer.port;
2539
- });
2540
-
2541
- if (it != peers.end()) {
2542
- // Update existing peer's timestamp
2543
- it->announced_at = std::chrono::steady_clock::now();
2544
- LOG_DHT_DEBUG("Updated existing announced peer " << peer.ip << ":" << peer.port
2545
- << " for info_hash " << hash_key);
2546
- } else {
2547
- // Add new peer
2548
- peers.emplace_back(peer);
2549
- LOG_DHT_DEBUG("Stored new announced peer " << peer.ip << ":" << peer.port
2550
- << " for info_hash " << hash_key << " (total: " << peers.size() << ")");
2551
- }
2552
- }
2553
-
2554
- std::vector<Peer> DhtClient::get_announced_peers(const InfoHash& info_hash) {
2555
- std::lock_guard<std::mutex> lock(announced_peers_mutex_);
2556
-
2557
- std::string hash_key = node_id_to_hex(info_hash);
2558
- auto it = announced_peers_.find(hash_key);
2559
-
2560
- std::vector<Peer> peers;
2561
- if (it != announced_peers_.end()) {
2562
- peers.reserve(it->second.size());
2563
- for (const auto& announced : it->second) {
2564
- peers.push_back(announced.peer);
2565
- }
2566
- LOG_DHT_DEBUG("Retrieved " << peers.size() << " announced peers for info_hash " << hash_key);
2567
- } else {
2568
- LOG_DHT_DEBUG("No announced peers found for info_hash " << hash_key);
2569
- }
2570
-
2571
- return peers;
2572
- }
2573
-
2574
- void DhtClient::cleanup_stale_announced_peers() {
2575
- std::lock_guard<std::mutex> lock(announced_peers_mutex_);
2576
-
2577
- auto now = std::chrono::steady_clock::now();
2578
- auto stale_threshold = std::chrono::minutes(30); // BEP 5 standard: 30 minutes
2579
-
2580
- size_t total_before = 0;
2581
- size_t total_after = 0;
2582
-
2583
- for (auto it = announced_peers_.begin(); it != announced_peers_.end(); ) {
2584
- auto& peers = it->second;
2585
- total_before += peers.size();
2586
-
2587
- // Remove stale peers
2588
- peers.erase(std::remove_if(peers.begin(), peers.end(),
2589
- [now, stale_threshold](const AnnouncedPeer& announced) {
2590
- return now - announced.announced_at > stale_threshold;
2591
- }), peers.end());
2592
-
2593
- total_after += peers.size();
2594
-
2595
- // Remove empty info_hash entries
2596
- if (peers.empty()) {
2597
- LOG_DHT_DEBUG("Removing empty announced peers entry for info_hash " << it->first);
2598
- it = announced_peers_.erase(it);
2599
- } else {
2600
- ++it;
2601
- }
2602
- }
2603
-
2604
- if (total_before > total_after) {
2605
- LOG_DHT_DEBUG("Cleaned up " << (total_before - total_after) << " stale announced peers "
2606
- << "(from " << total_before << " to " << total_after << ")");
2607
- }
2608
- }
2609
-
2610
- // Ping-before-replace eviction implementation
2611
- void DhtClient::initiate_ping_verification(const DhtNode& candidate_node, const DhtNode& old_node, int bucket_index) {
2612
- // NOTE: pending_pings_mutex_ is already held by caller (add_node)
2613
-
2614
- std::string ping_transaction_id = KrpcProtocol::generate_transaction_id();
2615
-
2616
- LOG_DHT_DEBUG("Initiating ping verification: pinging OLD node " << node_id_to_hex(old_node.id)
2617
- << " at " << old_node.peer.ip << ":" << old_node.peer.port
2618
- << " to check if alive. Candidate " << node_id_to_hex(candidate_node.id)
2619
- << " waiting to replace if old node fails. (transaction: " << ping_transaction_id << ")");
2620
-
2621
- // Store ping verification state and mark old node as being pinged
2622
- pending_pings_.emplace(ping_transaction_id, PingVerification(candidate_node, old_node, bucket_index));
2623
- nodes_being_replaced_.insert(old_node.id);
2624
-
2625
- // BEP 5: Send ping to the OLD node to verify it's still alive
2626
- // If old node responds -> keep it, discard candidate
2627
- // If old node times out -> replace with candidate
2628
- auto message = KrpcProtocol::create_ping_query(ping_transaction_id, node_id_);
2629
- send_krpc_message(message, old_node.peer);
2630
- }
2631
-
2632
- void DhtClient::handle_ping_verification_response(const std::string& transaction_id, const NodeId& responder_id, const Peer& responder) {
2633
- std::lock_guard<std::mutex> ping_lock(pending_pings_mutex_);
2634
-
2635
- auto it = pending_pings_.find(transaction_id);
2636
- if (it != pending_pings_.end()) {
2637
- const auto& verification = it->second;
2638
-
2639
- // Security check: Verify response comes from the IP we pinged
2640
- // Normalize IPv6-mapped IPv4 addresses (::ffff:x.x.x.x -> x.x.x.x) for comparison
2641
- auto normalize_ip = [](const std::string& ip) -> std::string {
2642
- const std::string ipv4_mapped_prefix = "::ffff:";
2643
- if (ip.compare(0, ipv4_mapped_prefix.size(), ipv4_mapped_prefix) == 0) {
2644
- return ip.substr(ipv4_mapped_prefix.size());
2645
- }
2646
- return ip;
2647
- };
2648
-
2649
- std::string responder_ip_normalized = normalize_ip(responder.ip);
2650
- std::string expected_ip_normalized = normalize_ip(verification.old_node.peer.ip);
2651
-
2652
- if (responder_ip_normalized != expected_ip_normalized) {
2653
- LOG_DHT_WARN("Ping verification response from wrong IP " << responder.ip
2654
- << " (expected " << verification.old_node.peer.ip << ") - ignoring");
2655
- return; // Don't remove from pending_pings_, let it timeout naturally
2656
- }
2657
-
2658
- // BEP 5: We pinged the OLD node to check if it's still alive
2659
- if (responder_id == verification.old_node.id) {
2660
- // Calculate RTT
2661
- auto rtt_duration = std::chrono::steady_clock::now() - verification.ping_sent_at;
2662
- uint16_t rtt_ms = static_cast<uint16_t>(
2663
- (std::min)(static_cast<int64_t>(0xfffe),
2664
- static_cast<int64_t>(std::chrono::duration_cast<std::chrono::milliseconds>(rtt_duration).count())));
2665
-
2666
- // Old node responded - it's still alive! Keep it, discard the candidate.
2667
- LOG_DHT_DEBUG("Old node " << node_id_to_hex(verification.old_node.id)
2668
- << " responded to ping (rtt=" << rtt_ms << "ms) - keeping it, discarding candidate "
2669
- << node_id_to_hex(verification.candidate_node.id));
2670
-
2671
- // Update old node in routing table
2672
- {
2673
- std::lock_guard<std::mutex> rt_lock(routing_table_mutex_);
2674
- auto& bucket = routing_table_[verification.bucket_index];
2675
- auto node_it = std::find_if(bucket.begin(), bucket.end(),
2676
- [&verification](const DhtNode& n) { return n.id == verification.old_node.id; });
2677
- if (node_it != bucket.end()) {
2678
- node_it->mark_success();
2679
- node_it->update_rtt(rtt_ms);
2680
- }
2681
- }
2682
- // Candidate is discarded (not added to routing table)
2683
- } else {
2684
- // Different node ID responded from the same IP:port!
2685
- // This means the old node is gone and this IP now belongs to a different node.
2686
- // Replace the old node with the candidate.
2687
- LOG_DHT_DEBUG("Different node " << node_id_to_hex(responder_id)
2688
- << " responded from " << responder.ip << ":" << responder.port
2689
- << " (expected old node " << node_id_to_hex(verification.old_node.id)
2690
- << ") - old node is gone, replacing with candidate "
2691
- << node_id_to_hex(verification.candidate_node.id));
2692
-
2693
- // Replace old node with candidate
2694
- DhtNode candidate = verification.candidate_node;
2695
- candidate.mark_success(); // The responder just proved it's alive
2696
- perform_replacement(candidate, verification.old_node, verification.bucket_index);
2697
- }
2698
-
2699
- // Remove tracking entries
2700
- nodes_being_replaced_.erase(verification.old_node.id);
2701
- pending_pings_.erase(it);
2702
- }
2703
- }
2704
-
2705
- void DhtClient::cleanup_stale_ping_verifications() {
2706
- std::lock_guard<std::mutex> ping_lock(pending_pings_mutex_);
2707
-
2708
- auto now = std::chrono::steady_clock::now();
2709
- auto timeout_threshold = std::chrono::seconds(30); // 30 second timeout for ping responses
2710
-
2711
- auto it = pending_pings_.begin();
2712
- while (it != pending_pings_.end()) {
2713
- if (now - it->second.ping_sent_at > timeout_threshold) {
2714
- const auto& verification = it->second;
2715
-
2716
- // BEP 5: Old node didn't respond (timeout) - it's dead, replace with candidate!
2717
- LOG_DHT_DEBUG("Old node " << node_id_to_hex(verification.old_node.id)
2718
- << " timed out after 30s - replacing with candidate " << node_id_to_hex(verification.candidate_node.id));
2719
-
2720
- // Perform the replacement with a fresh candidate
2721
- DhtNode fresh_candidate = verification.candidate_node;
2722
- perform_replacement(fresh_candidate, verification.old_node, verification.bucket_index);
2723
-
2724
- // Remove tracking entries
2725
- nodes_being_replaced_.erase(verification.old_node.id);
2726
-
2727
- it = pending_pings_.erase(it);
2728
- } else {
2729
- ++it;
2730
- }
2731
- }
2732
- }
2733
-
2734
- bool DhtClient::perform_replacement(const DhtNode& candidate_node, const DhtNode& node_to_replace, int bucket_index) {
2735
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
2736
-
2737
- auto& bucket = routing_table_[bucket_index];
2738
- auto it = std::find_if(bucket.begin(), bucket.end(),
2739
- [&node_to_replace](const DhtNode& node) {
2740
- return node.id == node_to_replace.id;
2741
- });
2742
-
2743
- if (it != bucket.end()) {
2744
- LOG_DHT_DEBUG("Replacing old node " << node_id_to_hex(node_to_replace.id)
2745
- << " with " << node_id_to_hex(candidate_node.id) << " in bucket " << bucket_index);
2746
- *it = candidate_node;
2747
- return true;
2748
- } else {
2749
- LOG_DHT_WARN("Could not find node " << node_id_to_hex(node_to_replace.id)
2750
- << " to replace in bucket " << bucket_index);
2751
- }
2752
-
2753
- return false;
2754
- }
2755
-
2756
- // Utility functions implementation
2757
- NodeId string_to_node_id(const std::string& str) {
2758
- NodeId id;
2759
- size_t copy_size = (std::min)(str.size(), NODE_ID_SIZE);
2760
- std::copy(str.begin(), str.begin() + copy_size, id.begin());
2761
- return id;
2762
- }
2763
-
2764
- std::string node_id_to_string(const NodeId& id) {
2765
- return std::string(id.begin(), id.end());
2766
- }
2767
-
2768
- NodeId hex_to_node_id(const std::string& hex) {
2769
- NodeId id;
2770
- if (hex.size() != NODE_ID_SIZE * 2) {
2771
- return id; // Return zero-filled ID on error
2772
- }
2773
-
2774
- for (size_t i = 0; i < NODE_ID_SIZE; ++i) {
2775
- std::string byte_str = hex.substr(i * 2, 2);
2776
- id[i] = static_cast<uint8_t>(std::stoul(byte_str, nullptr, 16));
2777
- }
2778
-
2779
- return id;
2780
- }
2781
-
2782
- std::string node_id_to_hex(const NodeId& id) {
2783
- std::ostringstream oss;
2784
- oss << std::hex << std::setfill('0');
2785
- for (uint8_t byte : id) {
2786
- oss << std::setw(2) << static_cast<int>(byte);
2787
- }
2788
- return oss.str();
2789
- }
2790
-
2791
- // Routing table persistence implementation
2792
- std::string DhtClient::routing_table_file_path() const {
2793
- // IPv6 instance uses a distinct filename suffix so it doesn't collide with the
2794
- // IPv4 instance bound to the same port.
2795
- const char* suffix = is_ipv6() ? "_v6" : "";
2796
- #ifdef TESTING
2797
- if (port_ == 0) {
2798
- std::ostringstream oss;
2799
- oss << "dht_routing_" << this << suffix << ".json";
2800
- return oss.str();
2801
- }
2802
- return "dht_routing_" + std::to_string(port_) + suffix + ".json";
2803
- #else
2804
- return data_directory_ + "/dht_routing_" + std::to_string(port_) + suffix + ".json";
2805
- #endif
2806
- }
2807
-
2808
- bool DhtClient::save_routing_table() {
2809
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
2810
-
2811
- try {
2812
- nlohmann::json routing_data;
2813
- routing_data["version"] = 1;
2814
- routing_data["family"] = is_ipv6() ? "ipv6" : "ipv4";
2815
- routing_data["node_id"] = node_id_to_hex(node_id_);
2816
- routing_data["saved_at"] = std::chrono::system_clock::now().time_since_epoch().count();
2817
-
2818
- nlohmann::json nodes_array = nlohmann::json::array();
2819
-
2820
- // Save only good nodes (confirmed with fail_count == 0)
2821
- size_t saved_count = 0;
2822
- for (const auto& bucket : routing_table_) {
2823
- for (const auto& node : bucket) {
2824
- // Only save confirmed good nodes
2825
- if (node.confirmed()) {
2826
- nlohmann::json node_data;
2827
- node_data["id"] = node_id_to_hex(node.id);
2828
- node_data["ip"] = node.peer.ip;
2829
- node_data["port"] = node.peer.port;
2830
-
2831
- // Save RTT if known
2832
- if (node.rtt != 0xffff) {
2833
- node_data["rtt"] = node.rtt;
2834
- }
2835
-
2836
- nodes_array.push_back(node_data);
2837
- saved_count++;
2838
- }
2839
- }
2840
- }
2841
-
2842
- routing_data["nodes"] = nodes_array;
2843
- routing_data["count"] = saved_count;
2844
-
2845
- // Determine file path
2846
- std::string file_path = routing_table_file_path();
2847
-
2848
- // Write to file
2849
- std::ofstream file(file_path);
2850
- if (!file.is_open()) {
2851
- LOG_DHT_ERROR("Failed to open routing table file for writing: " << file_path);
2852
- return false;
2853
- }
2854
-
2855
- file << routing_data.dump(2);
2856
- file.close();
2857
-
2858
- LOG_DHT_DEBUG("Saved " << saved_count << " confirmed nodes to " << file_path);
2859
- return true;
2860
-
2861
- } catch (const std::exception& e) {
2862
- LOG_DHT_ERROR("Exception while saving routing table: " << e.what());
2863
- return false;
2864
- }
2865
- }
2866
-
2867
- bool DhtClient::load_routing_table() {
2868
- std::lock_guard<std::mutex> lock(routing_table_mutex_);
2869
-
2870
- try {
2871
- // Determine file path
2872
- std::string file_path = routing_table_file_path();
2873
-
2874
- // Check if file exists
2875
- std::ifstream file(file_path);
2876
- if (!file.is_open()) {
2877
- LOG_DHT_DEBUG("No saved routing table found at " << file_path);
2878
- return false;
2879
- }
2880
-
2881
- // Parse JSON
2882
- nlohmann::json routing_data;
2883
- file >> routing_data;
2884
- file.close();
2885
-
2886
- // Validate format
2887
- if (!routing_data.contains("version") || !routing_data.contains("nodes")) {
2888
- LOG_DHT_WARN("Invalid routing table file format");
2889
- return false;
2890
- }
2891
-
2892
- int version = routing_data["version"];
2893
- if (version != 1) {
2894
- LOG_DHT_WARN("Unsupported routing table version: " << version);
2895
- return false;
2896
- }
2897
-
2898
- // Restore our own node ID so it stays stable across restarts (matches libtorrent's
2899
- // calculate_node_id). The external address is not known yet at load time, which is
2900
- // libtorrent's "external_address.is_unspecified()" case -> reuse the saved ID as long
2901
- // as it is valid (non-zero). If the external IP is later discovered and the restored
2902
- // ID is no longer valid for it (BEP 42), set_external_ip() regenerates it then.
2903
- // Restored before bucketing the loaded nodes below, since get_bucket_index() is
2904
- // computed relative to node_id_.
2905
- if (routing_data.contains("node_id")) {
2906
- try {
2907
- NodeId saved_id = hex_to_node_id(routing_data["node_id"].get<std::string>());
2908
- bool all_zeros = std::all_of(saved_id.begin(), saved_id.end(),
2909
- [](uint8_t b) { return b == 0; });
2910
- if (!all_zeros) {
2911
- node_id_ = saved_id;
2912
- LOG_DHT_INFO("Restored DHT node ID from disk: " << node_id_to_hex(node_id_));
2913
- } else {
2914
- LOG_DHT_WARN("Saved node ID is invalid (zero/malformed), keeping generated one");
2915
- }
2916
- } catch (const std::exception& e) {
2917
- LOG_DHT_WARN("Failed to restore saved node ID, keeping generated one: " << e.what());
2918
- }
2919
- }
2920
-
2921
- // Load nodes
2922
- const auto& nodes_array = routing_data["nodes"];
2923
- size_t loaded_count = 0;
2924
-
2925
- for (const auto& node_data : nodes_array) {
2926
- try {
2927
- std::string node_id_hex = node_data["id"];
2928
- std::string ip = node_data["ip"];
2929
- int port = node_data["port"];
2930
-
2931
- // Skip nodes that don't belong to this instance's family
2932
- if (network_utils::is_valid_ipv6(ip) != is_ipv6()) {
2933
- continue;
2934
- }
2935
-
2936
- NodeId node_id = hex_to_node_id(node_id_hex);
2937
- Peer peer(ip, port);
2938
- DhtNode node(node_id, peer);
2939
-
2940
- // Restore RTT if available
2941
- if (node_data.contains("rtt")) {
2942
- node.rtt = node_data["rtt"];
2943
- }
2944
-
2945
- // Mark as confirmed (fail_count = 0)
2946
- node.fail_count = 0;
2947
-
2948
- // Add to appropriate bucket
2949
- int bucket_index = get_bucket_index(node.id);
2950
- auto& bucket = routing_table_[bucket_index];
2951
-
2952
- // Check if bucket has space
2953
- if (bucket.size() < K_BUCKET_SIZE) {
2954
- bucket.push_back(node);
2955
- loaded_count++;
2956
- } else {
2957
- // Bucket full - try to replace a worse node
2958
- auto worst_it = std::max_element(bucket.begin(), bucket.end(),
2959
- [](const DhtNode& a, const DhtNode& b) {
2960
- return a.is_worse_than(b);
2961
- });
2962
-
2963
- if (worst_it != bucket.end() && worst_it->is_worse_than(node)) {
2964
- *worst_it = node;
2965
- loaded_count++;
2966
- }
2967
- }
2968
-
2969
- } catch (const std::exception& e) {
2970
- LOG_DHT_WARN("Failed to load node from routing table: " << e.what());
2971
- continue;
2972
- }
2973
- }
2974
-
2975
- LOG_DHT_INFO("Loaded " << loaded_count << " nodes from routing table file");
2976
- return loaded_count > 0;
2977
-
2978
- } catch (const std::exception& e) {
2979
- LOG_DHT_ERROR("Exception while loading routing table: " << e.what());
2980
- return false;
2981
- }
2982
- }
2983
-
2984
- void DhtClient::set_data_directory(const std::string& directory) {
2985
- data_directory_ = directory;
2986
- if (data_directory_.empty()) {
2987
- data_directory_ = ".";
2988
- }
2989
- LOG_DHT_DEBUG("Data directory set to: " << data_directory_);
2990
- }
2991
-
2992
- #ifdef RATS_SEARCH_FEATURES
2993
- // ============================================================================
2994
- // SPIDER MODE IMPLEMENTATION
2995
- // ============================================================================
2996
-
2997
- void DhtClient::set_spider_mode(bool enable) {
2998
- bool was_enabled = spider_mode_.exchange(enable);
2999
-
3000
- if (enable && !was_enabled) {
3001
- LOG_DHT_INFO("Spider mode ENABLED - aggressive node discovery active (separate node pool)");
3002
-
3003
- // Initialize spider pool with nodes from routing table
3004
- // Lock order: routing_table_mutex_ (3) -> spider_nodes_mutex_ (4)
3005
- std::lock_guard<std::mutex> rt_lock(routing_table_mutex_);
3006
- std::lock_guard<std::mutex> spider_lock(spider_nodes_mutex_);
3007
-
3008
- spider_nodes_.clear();
3009
- spider_visited_.clear();
3010
-
3011
- // Seed spider pool with current routing table nodes
3012
- for (const auto& bucket : routing_table_) {
3013
- for (const auto& node : bucket) {
3014
- if (spider_nodes_.size() < MAX_SPIDER_NODES) {
3015
- spider_nodes_.push_back(node);
3016
- }
3017
- }
3018
- }
3019
-
3020
- LOG_DHT_INFO("Spider pool initialized with " << spider_nodes_.size() << " nodes from routing table");
3021
-
3022
- } else if (!enable && was_enabled) {
3023
- LOG_DHT_INFO("Spider mode DISABLED - normal DHT operation");
3024
-
3025
- // Clear spider state
3026
- cleanup_spider_state();
3027
- }
3028
- }
3029
-
3030
- void DhtClient::add_spider_node(const DhtNode& node) {
3031
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3032
-
3033
- // Check if node already exists in pool
3034
- auto it = std::find_if(spider_nodes_.begin(), spider_nodes_.end(),
3035
- [&node](const DhtNode& existing) {
3036
- return existing.id == node.id;
3037
- });
3038
-
3039
- if (it != spider_nodes_.end()) {
3040
- // Update existing node
3041
- it->peer = node.peer;
3042
- it->last_seen = std::chrono::steady_clock::now();
3043
- return;
3044
- }
3045
-
3046
- // Add new node if pool isn't full
3047
- if (spider_nodes_.size() < MAX_SPIDER_NODES) {
3048
- spider_nodes_.push_back(node);
3049
- LOG_DHT_DEBUG("Added spider node " << node_id_to_hex(node.id) << " at "
3050
- << node.peer.ip << ":" << node.peer.port
3051
- << " (pool size: " << spider_nodes_.size() << ")");
3052
- } else {
3053
- // Replace a random node (simple eviction strategy)
3054
- static std::random_device rd;
3055
- static std::mt19937 gen(rd());
3056
- std::uniform_int_distribution<size_t> dis(0, spider_nodes_.size() - 1);
3057
- size_t replace_idx = dis(gen);
3058
- spider_nodes_[replace_idx] = node;
3059
- LOG_DHT_DEBUG("Replaced spider node at index " << replace_idx << " with "
3060
- << node_id_to_hex(node.id));
3061
- }
3062
- }
3063
-
3064
- void DhtClient::add_spider_nodes(const std::vector<DhtNode>& nodes) {
3065
- for (const auto& node : nodes) {
3066
- add_spider_node(node);
3067
- }
3068
- }
3069
-
3070
- bool DhtClient::is_spider_node_visited(const NodeId& id) const {
3071
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3072
- return spider_visited_.find(id) != spider_visited_.end();
3073
- }
3074
-
3075
- void DhtClient::mark_spider_node_visited(const NodeId& id) {
3076
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3077
-
3078
- // Clean up if too many visited nodes
3079
- if (spider_visited_.size() >= MAX_SPIDER_VISITED) {
3080
- // Clear half of the visited set (simple eviction)
3081
- auto it = spider_visited_.begin();
3082
- std::advance(it, spider_visited_.size() / 2);
3083
- spider_visited_.erase(spider_visited_.begin(), it);
3084
- LOG_DHT_DEBUG("Cleaned up spider visited set, now " << spider_visited_.size() << " entries");
3085
- }
3086
-
3087
- spider_visited_.insert(id);
3088
- }
3089
-
3090
- void DhtClient::cleanup_spider_state() {
3091
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3092
-
3093
- size_t nodes_count = spider_nodes_.size();
3094
- size_t visited_count = spider_visited_.size();
3095
- size_t transactions_count = spider_transactions_.size();
3096
- size_t contacted_ips_count = spider_contacted_ips_.size();
3097
-
3098
- spider_nodes_.clear();
3099
- spider_visited_.clear();
3100
- spider_transactions_.clear();
3101
- spider_contacted_ips_.clear();
3102
-
3103
- LOG_DHT_DEBUG("Cleaned up spider state: " << nodes_count << " nodes, "
3104
- << visited_count << " visited entries, "
3105
- << transactions_count << " pending transactions, "
3106
- << contacted_ips_count << " contacted IPs cleared");
3107
- }
3108
-
3109
- void DhtClient::cleanup_stale_spider_transactions() {
3110
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3111
-
3112
- auto now = std::chrono::steady_clock::now();
3113
- auto timeout = std::chrono::seconds(60); // 60 second timeout for spider transactions
3114
-
3115
- size_t removed = 0;
3116
- auto it = spider_transactions_.begin();
3117
- while (it != spider_transactions_.end()) {
3118
- if (now - it->second > timeout) {
3119
- it = spider_transactions_.erase(it);
3120
- removed++;
3121
- } else {
3122
- ++it;
3123
- }
3124
- }
3125
-
3126
- if (removed > 0) {
3127
- LOG_DHT_DEBUG("Cleaned up " << removed << " stale spider transactions");
3128
- }
3129
- }
3130
-
3131
- void DhtClient::mark_spider_transaction(const std::string& transaction_id) {
3132
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3133
- spider_transactions_[transaction_id] = std::chrono::steady_clock::now();
3134
- }
3135
-
3136
- bool DhtClient::is_spider_transaction(const std::string& transaction_id) {
3137
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3138
- auto it = spider_transactions_.find(transaction_id);
3139
- if (it != spider_transactions_.end()) {
3140
- spider_transactions_.erase(it); // Remove after checking - one-time use
3141
- return true;
3142
- }
3143
- return false;
3144
- }
3145
-
3146
- void DhtClient::mark_spider_contacted_ip(const std::string& ip) {
3147
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3148
-
3149
- // Limit size to avoid unbounded growth
3150
- if (spider_contacted_ips_.size() >= MAX_SPIDER_CONTACTED_IPS) {
3151
- // Clear half of the set (simple eviction)
3152
- auto it = spider_contacted_ips_.begin();
3153
- std::advance(it, spider_contacted_ips_.size() / 2);
3154
- spider_contacted_ips_.erase(spider_contacted_ips_.begin(), it);
3155
- LOG_DHT_DEBUG("Cleaned up spider contacted IPs, now " << spider_contacted_ips_.size() << " entries");
3156
- }
3157
-
3158
- spider_contacted_ips_.insert(ip);
3159
- }
3160
-
3161
- bool DhtClient::is_spider_contacted_ip(const std::string& ip) const {
3162
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3163
- return spider_contacted_ips_.count(ip) > 0;
3164
- }
3165
-
3166
- size_t DhtClient::get_spider_pool_size() const {
3167
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3168
- return spider_nodes_.size();
3169
- }
3170
-
3171
- size_t DhtClient::get_spider_visited_count() const {
3172
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3173
- return spider_visited_.size();
3174
- }
3175
-
3176
- void DhtClient::clear_spider_state() {
3177
- cleanup_spider_state();
3178
- }
3179
-
3180
- void DhtClient::set_spider_announce_callback(SpiderAnnounceCallback callback) {
3181
- std::lock_guard<std::mutex> lock(spider_callbacks_mutex_);
3182
- spider_announce_callback_ = std::move(callback);
3183
- LOG_DHT_DEBUG("Spider announce callback set");
3184
- }
3185
-
3186
- void DhtClient::set_spider_ignore(bool ignore) {
3187
- spider_ignore_.store(ignore);
3188
- LOG_DHT_DEBUG("Spider ignore mode set to " << (ignore ? "true" : "false"));
3189
- }
3190
-
3191
- void DhtClient::spider_walk() {
3192
- if (!running_) {
3193
- return;
3194
- }
3195
-
3196
- // Get a random unvisited node from the spider pool and send find_node
3197
- DhtNode target_node;
3198
- bool found = false;
3199
- size_t pool_size = 0; // Cache sizes under lock for logging
3200
- size_t visited_size = 0;
3201
-
3202
- {
3203
- std::lock_guard<std::mutex> lock(spider_nodes_mutex_);
3204
-
3205
- if (!spider_nodes_.empty()) {
3206
- // Try to find an unvisited node (up to 10 attempts)
3207
- static std::random_device rd;
3208
- static std::mt19937 gen(rd());
3209
-
3210
- for (int attempt = 0; attempt < 10 && !found; ++attempt) {
3211
- std::uniform_int_distribution<size_t> dis(0, spider_nodes_.size() - 1);
3212
- size_t idx = dis(gen);
3213
-
3214
- const auto& node = spider_nodes_[idx];
3215
- if (spider_visited_.find(node.id) == spider_visited_.end()) {
3216
- target_node = node;
3217
- spider_visited_.insert(node.id);
3218
- found = true;
3219
- }
3220
- }
3221
-
3222
- // If all sampled nodes are visited, just pick any random one
3223
- // This ensures we keep walking even when most nodes are visited
3224
- if (!found && !spider_nodes_.empty()) {
3225
- std::uniform_int_distribution<size_t> dis(0, spider_nodes_.size() - 1);
3226
- target_node = spider_nodes_[dis(gen)];
3227
- found = true;
3228
- LOG_DHT_DEBUG("Spider walk: all sampled nodes visited, reusing node");
3229
- }
3230
- }
3231
-
3232
- // Clean up visited set if it's getting too large
3233
- if (spider_visited_.size() >= MAX_SPIDER_VISITED) {
3234
- auto it = spider_visited_.begin();
3235
- std::advance(it, spider_visited_.size() / 2);
3236
- spider_visited_.erase(spider_visited_.begin(), it);
3237
- LOG_DHT_DEBUG("Spider walk: cleaned up visited set to " << spider_visited_.size() << " entries");
3238
- }
3239
-
3240
- // Cache sizes for logging outside the lock
3241
- pool_size = spider_nodes_.size();
3242
- visited_size = spider_visited_.size();
3243
- }
3244
-
3245
- if (found) {
3246
- // Spider optimization: use neighbor_id to appear close to the target node
3247
- // This makes us look like we're in the same neighborhood as the node we're querying
3248
- NodeId query_id = neighbor_id(target_node.id);
3249
-
3250
- // Generate a random target for find_node
3251
- NodeId random_target = generate_node_id();
3252
-
3253
- // Send find_node with our neighbor_id (pretending to be close to target_node)
3254
- std::string transaction_id = KrpcProtocol::generate_transaction_id();
3255
-
3256
- // Mark this transaction as spider - responses will go to spider pool
3257
- // even if spider_mode_ is disabled before response arrives
3258
- mark_spider_transaction(transaction_id);
3259
-
3260
- // Mark this IP as spider-contacted - we'll respond with neighbor_id to requests from this IP
3261
- mark_spider_contacted_ip(target_node.peer.ip);
3262
-
3263
- auto message = KrpcProtocol::create_find_node_query(transaction_id, query_id, random_target);
3264
- send_krpc_message(message, target_node.peer);
3265
-
3266
- LOG_DHT_DEBUG("Spider walk: sent find_node to " << target_node.peer.ip << ":" << target_node.peer.port
3267
- << " with neighbor_id (pool: " << pool_size << ", visited: " << visited_size << ")");
3268
- } else {
3269
- // No nodes in spider pool, seed from routing table or bootstrap
3270
- LOG_DHT_DEBUG("Spider walk: no nodes in spider pool, seeding...");
3271
-
3272
- // First try to seed from routing table
3273
- // Lock order: routing_table_mutex_ (3) -> spider_nodes_mutex_ (4)
3274
- {
3275
- std::lock_guard<std::mutex> rt_lock(routing_table_mutex_);
3276
- std::lock_guard<std::mutex> spider_lock(spider_nodes_mutex_);
3277
-
3278
- for (const auto& bucket : routing_table_) {
3279
- for (const auto& node : bucket) {
3280
- if (spider_nodes_.size() < MAX_SPIDER_NODES) {
3281
- spider_nodes_.push_back(node);
3282
- }
3283
- }
3284
- }
3285
-
3286
- // Cache size for check outside the lock
3287
- pool_size = spider_nodes_.size();
3288
- }
3289
-
3290
- // If still empty, bootstrap (rate-limited to once per 30 seconds)
3291
- if (pool_size == 0) {
3292
- auto now = std::chrono::steady_clock::now();
3293
- if (now - last_spider_bootstrap_ >= std::chrono::seconds(30)) {
3294
- last_spider_bootstrap_ = now;
3295
- LOG_DHT_DEBUG("Spider walk: routing table empty too, re-bootstrapping");
3296
- for (const auto& bootstrap : get_default_bootstrap_nodes()) {
3297
- send_krpc_find_node(bootstrap, node_id_);
3298
- }
3299
- } else {
3300
- LOG_DHT_DEBUG("Spider walk: skipping re-bootstrap (rate limited, last was < 30s ago)");
3301
- }
3302
- }
3303
- }
3304
- }
3305
- #endif // RATS_SEARCH_FEATURES
3306
-
3307
- } // namespace librats