From 7719de533828a7bf225a7013c64071a6deb778da Mon Sep 17 00:00:00 2001 From: Lee Miller Date: Thu, 24 Aug 2023 00:23:54 +0300 Subject: [PATCH] Define a static method network_group() in NetAddrNoPrefix and use it in manager. --- minode/manager.py | 17 +++++++++-------- minode/structure.py | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/minode/manager.py b/minode/manager.py index 93a3f30..a03f9d6 100644 --- a/minode/manager.py +++ b/minode/manager.py @@ -77,7 +77,7 @@ class Manager(threading.Thread): with shared.connections_lock: shared.connections.remove(c) else: - hosts.add(c.host) + hosts.add(structure.NetAddrNoPrefix.network_group(c.host)) if not c.server: outgoing_connections += 1 @@ -121,15 +121,16 @@ class Manager(threading.Thread): else: to_connect.update(shared.i2p_node_pool) - for addr in to_connect: - if addr[0] in hosts: + for host, port in to_connect: + group = structure.NetAddrNoPrefix.network_group(host) + if group in hosts: continue - if addr[1] == 'i2p' and shared.i2p_enabled: - if shared.i2p_session_nick and addr[0] != shared.i2p_dest_pub: + if port == 'i2p' and shared.i2p_enabled: + if shared.i2p_session_nick and host != shared.i2p_dest_pub: try: d = I2PDialer( shared, - addr[0], shared.i2p_session_nick, + host, shared.i2p_session_nick, shared.i2p_sam_host, shared.i2p_sam_port) d.start() hosts.add(d.destination) @@ -141,9 +142,9 @@ class Manager(threading.Thread): else: continue else: - c = Connection(addr[0], addr[1]) + c = Connection(host, port) c.start() - hosts.add(c.host) + hosts.add(group) with shared.connections_lock: shared.connections.add(c) shared.hosts = hosts diff --git a/minode/structure.py b/minode/structure.py index 53785b8..405da1a 100644 --- a/minode/structure.py +++ b/minode/structure.py @@ -173,6 +173,21 @@ class NetAddrNoPrefix(): b += struct.pack('>H', int(self.port)) return b + @staticmethod + def network_group(host): + """A simplified network group identifier from pybitmessage protocol""" + try: + host = socket.inet_pton(socket.AF_INET, host) + return host[:2] + except socket.error: + try: + host = socket.inet_pton(socket.AF_INET6, host) + return host[:12] + except OSError: + return host + except TypeError: + return host + @classmethod def from_bytes(cls, b): services, host, port = struct.unpack('>Q16sH', b)