Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: IP is packed with port #1962

Merged
merged 6 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions bittensor/chain_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,10 +283,13 @@ def from_neuron_info(cls, neuron_info: dict) -> "AxonInfo":
Returns:
instance (AxonInfo): An instance of AxonInfo created from the dictionary.
"""
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"],
Expand Down
22 changes: 22 additions & 0 deletions bittensor/utils/networking.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,28 @@ def int_to_ip(int_val: int) -> str:
return str(netaddr.IPAddress(int_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 ip_str < (1 << 128) + (1 << 16) and 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_to_int(str_val: str) -> int:
r"""Maps an ip-string to a unique integer.
arg:
Expand Down
8 changes: 8 additions & 0 deletions tests/unit_tests/utils/test_networking.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ def test_int_to_ip_range():
)


def test_packed_ip_port():
"""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"
Expand Down
Loading