"""
Copyright 2025 Biglup Labs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import annotations
from typing import Union
from .._ffi import ffi, lib
from ..errors import CardanoError
from ..cbor.cbor_reader import CborReader
from ..cbor.cbor_writer import CborWriter
[docs]
class IPv4:
"""
Represents an IPv4 address used in Cardano stake pool relay configuration.
IPv4 addresses are 4 bytes (32 bits) and are used to identify single-host
address relays in stake pool registration certificates.
"""
IP_SIZE = 4 # IPv4 addresses are 4 bytes
[docs]
def __init__(self, ptr) -> None:
"""
Initializes an IPv4 address from a C pointer.
Args:
ptr: A C pointer to the cardano_ipv4_t object.
Raises:
CardanoError: If the pointer is NULL.
"""
if ptr == ffi.NULL:
raise CardanoError("IPv4: invalid handle")
self._ptr = ptr
def __del__(self) -> None:
"""
Cleans up the IPv4 object by releasing the underlying C resources.
"""
if getattr(self, "_ptr", ffi.NULL) not in (None, ffi.NULL):
ptr_ptr = ffi.new("cardano_ipv4_t**", self._ptr)
lib.cardano_ipv4_unref(ptr_ptr)
self._ptr = ffi.NULL
[docs]
def __enter__(self) -> IPv4:
"""
Enables context manager support for the IPv4 object.
Returns:
The IPv4 instance.
"""
return self
[docs]
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""
Exits the context manager.
Args:
exc_type: The exception type (if any).
exc_val: The exception value (if any).
exc_tb: The exception traceback (if any).
"""
[docs]
def __repr__(self) -> str:
"""
Returns a detailed string representation of the IPv4 address.
Returns:
A string representation in the format "IPv4(address)".
"""
return f"IPv4({self.to_string()})"
[docs]
def __str__(self) -> str:
"""
Returns the IPv4 address in dotted-decimal notation.
Returns:
A string representation of the IPv4 address.
"""
return self.to_string()
[docs]
def __eq__(self, other: object) -> bool:
"""
Compares two IPv4 addresses for equality.
Args:
other: The object to compare with.
Returns:
True if the addresses are equal, False otherwise.
"""
if not isinstance(other, IPv4):
return False
return self.to_bytes() == other.to_bytes()
[docs]
def __hash__(self) -> int:
"""
Returns a hash value for the IPv4 address.
Returns:
The hash value based on the IPv4 bytes.
"""
return hash(self.to_bytes())
[docs]
@classmethod
def from_bytes(cls, data: Union[bytes, bytearray]) -> IPv4:
"""
Creates an IPv4 address from raw bytes.
Args:
data: The raw IPv4 bytes (must be exactly 4 bytes).
Returns:
A new IPv4 address.
Raises:
CardanoError: If the bytes are invalid.
Example:
>>> ipv4 = IPv4.from_bytes(bytes([192, 168, 1, 1]))
>>> str(ipv4)
'192.168.1.1'
"""
if len(data) != cls.IP_SIZE:
raise CardanoError(f"IPv4 requires exactly {cls.IP_SIZE} bytes, got {len(data)}")
out = ffi.new("cardano_ipv4_t**")
c_data = ffi.from_buffer("byte_t[]", data)
err = lib.cardano_ipv4_new(c_data, len(data), out)
if err != 0:
raise CardanoError(f"Failed to create IPv4 from bytes (error code: {err})")
return cls(out[0])
[docs]
@classmethod
def from_string(cls, ip_string: str) -> IPv4:
"""
Creates an IPv4 address from a dotted-decimal string.
Args:
ip_string: The IPv4 address in dotted-decimal notation (e.g., "192.168.1.1").
Returns:
A new IPv4 address.
Raises:
CardanoError: If the string is not a valid IPv4 address.
Example:
>>> ipv4 = IPv4.from_string("192.168.1.1")
>>> ipv4.to_bytes()
b'\\xc0\\xa8\\x01\\x01'
"""
out = ffi.new("cardano_ipv4_t**")
ip_bytes = ip_string.encode("utf-8")
err = lib.cardano_ipv4_from_string(ip_bytes, len(ip_bytes), out)
if err != 0:
raise CardanoError(f"Failed to create IPv4 from string (error code: {err})")
return cls(out[0])
[docs]
@classmethod
def from_cbor(cls, reader: CborReader) -> IPv4:
"""
Deserializes an IPv4 address from CBOR data.
Args:
reader: A CborReader positioned at the IPv4 data.
Returns:
A new IPv4 address deserialized from the CBOR data.
Raises:
CardanoError: If deserialization fails.
"""
out = ffi.new("cardano_ipv4_t**")
err = lib.cardano_ipv4_from_cbor(reader._ptr, out)
if err != 0:
raise CardanoError(f"Failed to deserialize IPv4 from CBOR (error code: {err})")
return cls(out[0])
[docs]
def to_bytes(self) -> bytes:
"""
Returns the raw IPv4 bytes.
Returns:
The IPv4 address as a 4-byte bytes object.
Example:
>>> ipv4 = IPv4.from_string("192.168.1.1")
>>> ipv4.to_bytes()
b'\\xc0\\xa8\\x01\\x01'
"""
size = lib.cardano_ipv4_get_bytes_size(self._ptr)
if size == 0:
return b""
data_ptr = lib.cardano_ipv4_get_bytes(self._ptr)
if data_ptr == ffi.NULL:
return b""
return bytes(ffi.buffer(data_ptr, size))
[docs]
def to_string(self) -> str:
"""
Returns the IPv4 address in dotted-decimal notation.
Returns:
The IPv4 address as a string (e.g., "192.168.1.1").
Example:
>>> ipv4 = IPv4.from_bytes(bytes([192, 168, 1, 1]))
>>> ipv4.to_string()
'192.168.1.1'
"""
str_ptr = lib.cardano_ipv4_get_string(self._ptr)
if str_ptr == ffi.NULL:
return ""
return ffi.string(str_ptr).decode("utf-8")
[docs]
def to_cbor(self, writer: CborWriter) -> None:
"""
Serializes the IPv4 address to CBOR format.
Args:
writer: A CborWriter to write the serialized data to.
Raises:
CardanoError: If serialization fails.
"""
err = lib.cardano_ipv4_to_cbor(self._ptr, writer._ptr)
if err != 0:
raise CardanoError(f"Failed to serialize IPv4 to CBOR (error code: {err})")