diff --git a/bittensor/chain_data.py b/bittensor/chain_data.py index ea59a4d69d..a5519d2c07 100644 --- a/bittensor/chain_data.py +++ b/bittensor/chain_data.py @@ -255,10 +255,15 @@ def from_string(cls, s: str) -> "AxonInfo": @classmethod def from_neuron_info(cls, neuron_info: dict) -> "AxonInfo": """Converts a dictionary to an axon_info object.""" + + ip, port = net.unpack_encoded_ip_port( + neuron_info["axon_info"]["ip"], neuron_info["axon_info"]["port"] + ) + return cls( version=neuron_info["axon_info"]["version"], - ip=net.int_to_ip(int(neuron_info["axon_info"]["ip"])), - port=neuron_info["axon_info"]["port"], + ip=ip, + port=port, ip_type=neuron_info["axon_info"]["ip_type"], hotkey=neuron_info["hotkey"], coldkey=neuron_info["coldkey"], diff --git a/bittensor/utils/networking.py b/bittensor/utils/networking.py index 9f1450af81..f0c6d738a1 100644 --- a/bittensor/utils/networking.py +++ b/bittensor/utils/networking.py @@ -61,6 +61,26 @@ def ip_to_int(str_val: str) -> int: return int(netaddr.IPAddress(str_val)) +def unpack_encoded_ip_port(ip_str: str, port: int) -> tuple: + r"""Unpacks an encoded IP and port if they are encoded together. + Args: + ip_str (:type:`str`, `required`): + The encoded IP address string. + port (:type:`int`, `required`): + The port number. + Returns: + tuple: A tuple containing the IP address string and port number. + Raises: + netaddr.core.AddrFormatError (Exception): + Raised when the passed IP string is not a valid IP int value. + """ + if port == 0: + port = ip_str & 0xFFFF + ip = ip_str >> 16 + return int_to_ip(ip), port + return int_to_ip(ip_str), port + + def ip_version(str_val: str) -> int: r"""Returns the ip version (IPV4 or IPV6). arg: diff --git a/tests/unit_tests/utils/test_networking.py b/tests/unit_tests/utils/test_networking.py index 2037718578..ede9db9892 100644 --- a/tests/unit_tests/utils/test_networking.py +++ b/tests/unit_tests/utils/test_networking.py @@ -25,6 +25,14 @@ def test_int_to_ip_range(): ) +def test_packed_ip_port_with_port_0(): + """Test packing and unpacking IP and port.""" + assert utils.networking.unpack_encoded_ip_port(184046647580618, 0) == ( + "167.99.179.13", + 6090, + ) + + def test_int_to_ip4_max(): """Test converting integer to maximum IPv4 address.""" assert utils.networking.int_to_ip(4294967295) == "255.255.255.255"