Skip to content

unaiverse.networking.p2p.lib_types

The native networking library of the SDK is a shared library loaded through ctypes (see unaiverse.networking.p2p). Its functions take C strings, C integers and byte buffers and most of them return a pointer to a C string that holds JSON and that Python must free. This module holds TypeInterface, the class that converts the arguments into those C types and reads the results back. P2P owns one shared instance of it and uses it around every call. The developer never calls it.

Two methods read the replies of the library. from_go_ptr_to_json reads a JSON reply and frees it. The batch of received messages has a binary layout of its own and from_go_pop_messages reads and frees that one. A JSON reply of the library has the shape {"state": "Success" | "Error" | "Empty", "message": ...} and some replies add a "code" or a "seq" field.

logger module-attribute

logger = logging.getLogger('LIB-TYPES')

The standard logging.Logger of this module is named "LIB-TYPES" and has level WARNING. It logs a reply that cannot be read and, at level CRITICAL, a failure to free the memory of a reply.

TypeInterface

TypeInterface(libp2p_instance: GoLibP2P)
Source code in unaiverse/networking/p2p/lib_types.py
def __init__(self, libp2p_instance: GoLibP2P):
    self.libp2p: GoLibP2P = libp2p_instance  # Store the shared library object instance

Converts values between Python and the C types of the native networking library. The constructor takes the loaded library as libp2p_instance and keeps it as the attribute libp2p. The methods that free a reply call the free function of the library through that attribute.

In the SDK there is exactly one instance. P2P.setup_library builds it with TypeInterface(P2P.libp2p) and stores it as P2P._type_interface. The package unaiverse.networking.p2p also assigns the loaded library to the class attribute TypeInterface.libp2p at import time.

Most methods are stateless conversions and only the two readers of a reply free memory. The converters to_go_* serve the arguments of a call and the converters from_go_* read its results.

libp2p instance-attribute

libp2p: GoLibP2P = libp2p_instance

The loaded native library, an object of ctypes.CDLL typed as the stub class GoLibP2P. The package assigns it to the class at import time and the constructor assigns it again to the instance.

to_go_string

to_go_string(s: str) -> bytes
Source code in unaiverse/networking/p2p/lib_types.py
def to_go_string(self, s: str) -> bytes:
    """
    Converts a Python string to a UTF-8 encoded Python 'bytes' object.

    This 'bytes' object is suitable for direct use with ctypes when passing
    to a C function expecting a 'char*' (ctypes.c_char_p), as ctypes
    will automatically pass a pointer to the byte string's data.

    Args:
        s: The Python string.

    Returns:
        A Python 'bytes' object containing the UTF-8 encoded string.
    """
    if s is None:
        s = ""
    return s.encode("utf-8")

Encodes a str to UTF-8 bytes, the value ctypes passes to an argument of type c_char_p. None becomes b"".

>>> ti.to_go_string("12D3KooWAbc")
b'12D3KooWAbc'

from_go_string

from_go_string(cstr: bytes) -> str
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_string(self, cstr: bytes) -> str:
    """
    Converts a C char pointer (Go string) to a Python string.

    Args:
        cstr: The C char pointer.

    Returns:
        The decoded Python string.
    """
    if not cstr:
        return ""
    return cstr.decode("utf-8")

Decodes UTF-8 bytes to a str. An empty or None value gives "". The method does not free anything and is not used by P2P.

to_go_int

to_go_int(i: int) -> c_int
Source code in unaiverse/networking/p2p/lib_types.py
def to_go_int(self, i: int) -> ctypes.c_int:
    """
    Converts a Python integer to a Go-compatible ctypes integer.

    Args:
        i: The Python integer.

    Returns:
        A ctypes.c_int equivalent.
    """
    return ctypes.c_int(i)

Wraps a Python int in a ctypes.c_int. P2P passes the instance index and the payload lengths through it. A value outside the range of a signed 32-bit integer wraps around without an error.

from_go_int

from_go_int(val: c_int) -> int
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_int(self, val: ctypes.c_int) -> int:
    """
    Converts a ctypes.c_int from Go to a Python integer.

    Args:
        val: The ctypes.c_int value.

    Returns:
        The corresponding Python integer.
    """
    return int(val)

Returns int(val). The method works on a plain Python int. Its annotation names ctypes.c_int even though int() raises ValueError on a c_int object in the current version (read val.value instead). Nothing in the SDK calls it.

to_go_float

to_go_float(f: float) -> c_float
Source code in unaiverse/networking/p2p/lib_types.py
def to_go_float(self, f: float) -> ctypes.c_float:
    """
    Converts a Python float to a Go-compatible ctypes float.

    Args:
        f: The Python float.

    Returns:
        A ctypes.c_float equivalent.
    """
    return ctypes.c_float(f)

Wraps a Python float in a ctypes.c_float (single precision). Nothing in the SDK calls it.

from_go_float

from_go_float(val: c_float) -> float
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_float(self, val: ctypes.c_float) -> float:
    """
    Converts a ctypes.c_float from Go to a Python float.

    Args:
        val: The ctypes.c_float value.

    Returns:
        The corresponding Python float.
    """
    return float(val)

Returns float(val). As with from_go_int, it works on a plain Python number and raises ValueError on a ctypes.c_float object. Nothing in the SDK calls it.

to_go_bool

to_go_bool(b: bool) -> c_int
Source code in unaiverse/networking/p2p/lib_types.py
def to_go_bool(self, b: bool) -> ctypes.c_int:
    """
    Converts a Python boolean to a Go-compatible integer (1 if True, 0 if False).

    Args:
        b: The Python boolean.

    Returns:
        A ctypes.c_int (1 or 0).
    """
    return ctypes.c_int(1 if b else 0)

Returns ctypes.c_int(1) for a true value and ctypes.c_int(0) otherwise. Nothing in the SDK calls it.

from_go_bool

from_go_bool(val: c_int) -> bool
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_bool(self, val: ctypes.c_int) -> bool:
    """
    Converts a Go-compatible integer (ctypes.c_int) to a Python boolean.

    Args:
        val: The ctypes.c_int value.

    Returns:
        True if the value equals 1, False otherwise.
    """
    return val == 1

Returns val == 1. The comparison holds for the Python int 1. Because a ctypes.c_int object never compares equal to an int, the method returns False on such an object whatever its value. Nothing in the SDK calls it.

to_go_bytes

to_go_bytes(b: bytes) -> bytes
Source code in unaiverse/networking/p2p/lib_types.py
def to_go_bytes(self, b: bytes) -> bytes:
    """
    Converts a Python bytes object to a Go-compatible C char pointer argument.

    The bytes are passed as they are (ctypes hands Go a pointer to their buffer, which Go copies during the call
    with the length it is given): no copy into a ctypes buffer first.

    Args:
        b: The Python bytes (a bytearray or memoryview is turned into bytes).

    Returns:
        The bytes, for an argument of type c_char_p.
    """
    if b is None:
        return b""
    return b if type(b) is bytes else bytes(b)

Prepares a byte payload for an argument of type c_char_p without copying it into a ctypes buffer. A bytes object is returned as it is. A bytearray or a memoryview is turned into bytes (one copy) and None becomes b"". A payload may contain zero bytes because the library copies the buffer during the call using the length that it receives in a separate argument.

from_go_bytes

from_go_bytes(cptr: c_char_p, length: int) -> bytes
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_bytes(self, cptr: ctypes.c_char_p, length: int) -> bytes:
    """
    Converts a Go pointer representing a byte array to a Python bytes object.

    Args:
        cptr: The C pointer to the byte array.
        length: The number of bytes to read.

    Returns:
        A Python bytes object containing the read data.
    """
    if not cptr or length <= 0:
        return bytes()
    return ctypes.string_at(cptr, length)

Reads length bytes at the C pointer cptr with ctypes.string_at and returns them as bytes without freeing the memory. A null pointer or a non-positive length gives b"". Nothing in the SDK calls the method.

from_go_ptr_to_json

from_go_ptr_to_json(c_void_ptr_val: int) -> Any
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_ptr_to_json(self, c_void_ptr_val: int) -> Any:
    """
    Converts a C void* pointer (returned by Go as int) pointing to a
    null-terminated C string containing JSON into a Python object.

    It reads the string, parses it as JSON, and crucially frees the C memory
    using the provided FreeString function from the Go library.

    Args:
        c_void_ptr_val: The integer value representing the C pointer address.

    Returns:
        The parsed Python object from the JSON string.

    Raises:
        GoLibError: If the pointer is NULL, reading/decoding fails, or
                    JSON parsing fails.
        TypeError: When go_lib is not a valid ctypes library object.
    """

    if not c_void_ptr_val:  # NULL (0): nothing to read or free.
        raise Exception("Received a NULL pointer from Go function")

    try:
        # --- Cast void* to c_char_p and read the string ---
        try:
            c_char_ptr_for_read = ctypes.cast(c_void_ptr_val, ctypes.c_char_p)
            raw_bytes = ctypes.string_at(c_char_ptr_for_read)
            json_string = raw_bytes.decode('utf-8')
        except (ctypes.ArgumentError, ValueError, UnicodeDecodeError) as read_err:
            logger.error(f"Failed to read/decode string from pointer {hex(c_void_ptr_val)}: "
                         f"{read_err}", exc_info=False)
            raise Exception(f"Failed to read string from pointer "
                            f"{hex(c_void_ptr_val)}: {read_err}") from read_err

        # --- Parse JSON ---
        try:
            return json.loads(json_string)
        except json.JSONDecodeError as json_err:
            logger.error(f"Failed to decode JSON from pointer {hex(c_void_ptr_val)}: {json_err}", exc_info=False)
            raise Exception(f"Failed to decode JSON from pointer "
                            f"{hex(c_void_ptr_val)}: {json_err}") from json_err

    finally:

        # --- Free C memory allocated by Go (C.CString) ---
        # Each pointer crosses this boundary exactly once, so no double-free
        # tracking is needed; FreeString -> C.free is thread-safe for distinct
        # pointers. We never raise from here, to preserve the original error.
        try:
            self.libp2p.FreeString(c_void_ptr_val)
        except Exception as free_err:
            logger.critical(f"🚨 FAILED TO FREE C MEMORY for pointer "
                            f"{hex(c_void_ptr_val)} via FreeString: {free_err}", exc_info=True)

Reads the JSON reply of a library call and frees it. This is the reader of every call of P2P except the pop of the received messages.

Argument Type Meaning
c_void_ptr_val int The address of a NUL-terminated C string that the library allocated. ctypes returns a c_void_p result in this form.

The method reads the string, decodes it as UTF-8 and parses it with json.loads. It returns the parsed object, usually a dict with "state" and "message". Whatever happens in the reading, the finally block passes the pointer to FreeString of the library exactly once. A failure of the free is logged at level CRITICAL and is never raised. An error of the reading therefore propagates unchanged.

It raises a plain Exception (not a dedicated class) in three cases: (1) a null pointer, (2) a string that cannot be read or decoded and (3) a string that is not valid JSON. P2P wraps these into a P2PError or treats them as a failed call.

from_go_pop_messages

from_go_pop_messages(c_void_ptr_val: int) -> Any
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_pop_messages(self, c_void_ptr_val: int) -> Any:
    """
    Reads the result of PopMessages, which is either:
      * a binary message buffer (starts with the magic byte 0xB1), or
      * a JSON status string (Empty/Error), which starts with '{'.

    Returns a list of ``{"from": str, "data": bytes, "protocol": str}`` dicts for
    the binary case (``data`` is already raw bytes, no base64), or the parsed JSON
    status dict for the JSON case. Always frees the C memory, like
    ``from_go_ptr_to_json``.
    """
    if not c_void_ptr_val:
        raise Exception("Received a NULL pointer from Go PopMessages")

    try:
        first = ctypes.string_at(c_void_ptr_val, 1)
        if first and first[0] == _POP_BINARY_MAGIC:
            # Binary path. Read the fixed header (magic + totalBytes) with a
            # known length, then the whole buffer — string_at without a length
            # would stop at the first interior NUL of the binary payload.
            header = ctypes.string_at(c_void_ptr_val, 5)
            total = struct.unpack_from(">I", header, 1)[0]
            blob = ctypes.string_at(c_void_ptr_val, total)
            return self._parse_pop_binary(blob)

        # JSON path (Empty/Error): NUL-terminated, safe to read without length.
        raw_bytes = ctypes.string_at(c_void_ptr_val)
        return json.loads(raw_bytes.decode("utf-8"))

    finally:
        try:
            self.libp2p.FreeString(c_void_ptr_val)
        except Exception as free_err:
            logger.critical(f"🚨 FAILED TO FREE C MEMORY for pointer "
                            f"{hex(c_void_ptr_val)} via FreeString: {free_err}", exc_info=True)

Reads the reply of a pop of the received messages (PopMessages, PopNetworkMessages, PopStreamMessages) and frees it. P2P.pop_messages calls it at every cycle of the node.

The first byte of the reply tells which of two forms it has.

  • A JSON status ({"state": "Empty"} or {"state": "Error", "message": ...}) starts with {. The method returns the parsed dict.
  • A batch of messages starts with the byte 0xB1. The method returns a list[dict] with one dict per message.

The binary batch has the layout below. Every integer in it is a big-endian uint32.

[0xB1][total length][count]
then, count times:
[len][sender peer ID][len][protocol ID][len][data][len][files JSON]

Each returned dict has three keys.

  • "from" is the peer ID of the sender as the transport verified it.
  • "protocol" is the protocol ID: one of the Session protocols or the protocol of the chat messages.
  • "data" is a memoryview of the batch (not a copy) that the binary message format parses as it is.

A file message adds "files". This key holds the parsed JSON list of the files that the library wrote to disk, each a dict with "key", "path" and "size" (see files).

The payloads of the batch may contain zero bytes and a read that stops at the first zero byte would truncate them. The method therefore reads the binary batch with an explicit length. The method frees the pointer in a finally block as from_go_ptr_to_json does and raises a plain Exception for a null pointer.

to_go_json

to_go_json(data: Any) -> bytes
Source code in unaiverse/networking/p2p/lib_types.py
def to_go_json(self, data: Any) -> bytes:
    """
Encodes a Python object to a JSON string, returning a UTF-8 encoded
Python 'bytes' object.

This 'bytes' object is suitable for direct use with ctypes when passing
to a C function expecting a 'char*' (ctypes.c_char_p).

Args:
    data: The Python object (e.g., dict, list) to encode.

Returns:
    A Python 'bytes' object containing the JSON string, UTF-8 encoded.
"""
    json_str = json.dumps(data)
    return self.to_go_string(json_str)

Serializes a Python object with json.dumps and returns it as UTF-8 bytes. P2P passes every structured argument through it: the configuration of the library and of the node, the list of addresses of a dial and the relay servers of the browser transport. A value that JSON cannot represent raises TypeError.

>>> ti.to_go_json(["/ip4/203.0.113.7/tcp/4001/p2p/12D3KooWAbc"])
b'["/ip4/203.0.113.7/tcp/4001/p2p/12D3KooWAbc"]'

from_go_string_to_list

from_go_string_to_list(cstr: c_char_p) -> List[Any]
Source code in unaiverse/networking/p2p/lib_types.py
def from_go_string_to_list(self, cstr: ctypes.c_char_p) -> List[Any]:
    """
    Decodes a JSON-encoded list from a Go C char pointer into a Python list.

    Args:
        cstr: The Go string (C char pointer) containing a JSON list.

    Returns:
        A Python list representing the JSON data.
    """
    s = self.from_go_string(cstr)

    return json.loads(s)

Decodes bytes with from_go_string and parses them with json.loads. The method expects a JSON list but returns whatever the JSON holds. It frees nothing and nothing in the SDK calls it.