Each node of UNaIVERSE is present on two networks, the public network and the world network (see Networking). On each network the node is one host of the native networking library. A host owns a peer identity, listens on its ports, opens connections, carries streams and publishes on topics. The class P2P wraps one such host. A node builds two of them (p2p_public and p2p_world) and hands each to a SessionManager that owns it from then on.
P2P is the lowest Python layer of the network. Above it, Session and SessionManager run the handshake with each peer and check that the peer is still alive. NodeConn sits above them and runs the pools, the send path and the world membership. The developer never creates or calls a P2P because Node builds both instances at start-up and closes them at shutdown. This page helps to read the logs and to debug a connection. It also lists the limits of the send queues that Custom controls.
The class has three groups of methods.
Raw calls, synchronous and blocking: connect_to, disconnect_from, send_message_to_peer, broadcast_message, send_file_message_to_peer, send_on_protocol, reserve_on_relay, pop_messages and the getters. Each one calls one function of the library, reads its JSON reply through TypeInterface and raises P2PError on an error.
The surface used by the layers above, mostly async: connect, disconnect, send, broadcast, send_session, reserve, get_messages, sign_with_host_key and verify_peer_signature. These methods move the blocking calls to a worker thread with asyncio.to_thread, encode and decode the messages and turn errors into return values where the caller expects them. Session runs unchanged on a Python node and in the browser because the browser transport implements the same surface in JavaScript.
The send queues: drop_send_queue, cancel_send, pop_send_events and set_peer_capabilities.
A send never waits for the network when the send queues are on. The library keeps one queue per peer and one writer per queue. send_message_to_peer only appends to the queue and returns the sequence number of the message. The outcome of the message (written, retried, refused or dropped) arrives later as an event that pop_send_events returns. The limits come from Custom and are listed under setup_library.
The standard logging.Logger of the module is named "P2P". setup_library lowers it to CRITICAL when logging is off and raises it to INFO when logging is on. The SDK logger of the node does not see these records. With Custom.LIBP2PLOG on, the node also routes the output of the native library to the p2p channel of its own logger.
The exception of every failure of the native library: a call that returned an error, a null reply, a reply that could not be parsed or a host that could not be created. The raw calls raise it. The methods used by the layers above catch it and return None, False or an empty list where the caller expects a value. A P2PError raised by a raw call keeps the original error as its __cause__.
A subclass of P2PError raised by send_file_message_to_peer when the library refuses a file message because the peer does not accept file messages. Nothing has been queued at that point. send catches it and sends the message again with the files inside it.
def__init__(self,message:str,peer_id:str)->None:"""Initializes the error. Args: message: The text of the refusal, as Go gives it (it names the cap that was hit). peer_id: The peer whose queue is full. """super().__init__(message)self.peer_id=peer_id
A subclass of P2PError raised when the send queue of a peer is full and the message was not queued. A full queue is the expected result when a sender produces messages faster than its peer consumes them. It is not a fault and the messages already queued are untouched. The queue accepts new messages again once it has drained to Custom.SEND_QUEUE_LOW_WATER (0.5) of its limits.
The constructor takes message (the text of the library, which names the limit that was hit) and peer_id.
Always True. NodeConn recognizes a full queue by this attribute (getattr(e, "queue_full", False)) and not by the class. Code that runs both on a Python node and in the browser must not import the class because the browser runtime replaces this module with a stub that has a bare P2PError and no P2PQueueFull.
def__init__(self,identity_dir:str,port:int=0,ips:list[str]=None,enable_relay_client:bool=True,enable_relay_service:bool=False,use_broad_limits:bool=False,is_isolated:bool=False,knows_is_public:bool=False,enable_tls:bool=False,domain_name:str|None=None,tls_cert_path:str|None=None,tls_key_path:str|None=None,probe_peers:list[str]|None=None,webrtc_enabled:bool=True,flood_sub:bool=False,ice_stun_servers:list[str]|None=None,ice_turn_servers:list[dict[str,Any]]|None=None,log_sub:str="pub",)->None:""" Initializes and starts a new libp2p node. Args: identity_dir: Directory path to load/store the node's private key and certificates. port: The (first) TCP port to listen on (0 for random). ips: A list of specific IP addresses to listen on. Defaults to ["0.0.0.0"]. enable_relay_client: Enable listening to relayed connections for this node. enable_relay_service: Enable relay service capabilities for this node. knows_is_public: If you already know that the node is public this forces its public reachability. Otherwise, it tries every possible attempt to make the node publicly reachable (UPnP, HolePunching, AutoNAT dial-backs from the probe peers...). enable_tls: Whether to enable AutoTLS certificate management (requires internet access). probe_peers: Multiaddrs (with peer IDs) dialed at boot as AutoNAT dial-back servers, so the node can discover its own reachability. None uses the built-in infrastructure relays; an empty list disables probing entirely (no reachability verdict unless knows_is_public). domain_name: Optional domain name for TLS certificate (required if enable_tls is True). tls_cert_path: Optional path to a custom TLS certificate file (PEM format). tls_key_path: Optional path to a custom TLS private key file (PEM format). webrtc_enabled: Enable the /unaiverse/webrtc-signal/1.0.0 protocol for Go-to-browser NAT traversal via WebRTC DataChannels. Defaults to True. flood_sub: Enable flood sub. Defaults to False. ice_stun_servers: List of STUN server URIs (e.g. ["stun:stun.example.com:3478"]). Defaults to Google public STUN when None. ice_turn_servers: List of TURN server dicts, each with keys "urls", "username", "credential". Optional; leave None if no TURN servers are needed. Raises: P2PError: If the node creation fails in the Go library. AttributeError: If P2P.libp2p has not been set before instantiation. """# --- CRITICAL: Check if library is initialized ---ifnotP2P._library_initialized:raiseP2PError("P2P library not set up. Call P2P.setup_library() before creating an instance.")# Assign instance IDassigned_instance_id=-1withP2P._instance_lock:for_instance_id,iinenumerate(self._instance_ids):ifnoti:self._instance_ids[_instance_id]=Trueassigned_instance_id=_instance_idbreakifassigned_instance_id==-1:raiseP2PError(f"Cannot create new P2P instance: Maximum number of instances "f"({P2P._MAX_INSTANCES}).")self._instance:int=assigned_instance_idlogger.info(f"🚀 Attempting to initialize P2P Node with auto-assigned Instance ID: {self._instance}")os.makedirs(identity_dir,exist_ok=True)self._enable_relay_client=enable_relay_clientorenable_relay_serviceself._peer_id:str|None=Noneself.log_sub=log_subself._peer_caps:dict[str,int]={}# Peer ID -> the CAP_* bits of its Session (set_peer_capabilities)# Who sent a file (a callable: peer ID -> (handle, node name), or None when unknown), set by the node that# owns this instance: a received file goes to Downloads/<handle>/<node name>/self.file_owner_of=None# TLS Validation Logichas_custom_tls_args=(tls_cert_pathisnotNone)or(tls_key_pathisnotNone)or(domain_nameisnotNone)ifhas_custom_tls_args:ifdomain_nameisNoneortls_cert_pathisNoneortls_key_pathisNone:raiseValueError("Custom TLS requires 'domain_name', 'tls_cert_path' and 'tls_key_path'.")use_auto_tls=enable_tlsandnothas_custom_tls_argsself._enable_tls=use_auto_tlsorhas_custom_tls_args# --- Build Configuration JSON ---node_config={"identity_dir":identity_dir,"predefined_port":port,"listen_ips":ips,"relay":{"enable_client":self._enable_relay_client,"enable_service":enable_relay_service,"with_broad_limits":use_broad_limits,},"tls":{"auto_tls":use_auto_tls,"domain":domain_nameifdomain_nameelse"","cert_path":tls_cert_pathiftls_cert_pathelse"","key_path":tls_key_pathiftls_key_pathelse"",},"network":{"isolated":is_isolated,"force_public":knows_is_public,"flood_sub":flood_sub,},"reachability":{"probe_peers":probe_peers,},"webrtc":{"enabled":webrtc_enabled,"ice_config":{"stun_servers":ice_stun_servers,"turn_servers":ice_turn_servers,}ifwebrtc_enabledelseNone,},}logger.info(f"🐍 Creating Node (Instance ID: {self._instance})...")try:# Call the Go functionresult_ptr=P2P.libp2p.CreateNode(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_json(node_config),)result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:err_msg="Received null result from Go CreateNode."logger.error(f"[Instance {self._instance}] {err_msg}")raiseP2PError(f"[Instance {self._instance}] {err_msg}")ifresult.get('state')=="Error":err_msg=result.get('message','Unknown Go error on CreateNode')logger.error(f"[Instance {self._instance}] Go error: {err_msg}")raiseP2PError(f"[Instance {self._instance}] Failed to create node: {err_msg}")message_data=result.get('message')initial_addresses=message_data.get("addresses",[])self._is_public=message_data.get("isPublic",False)# Check the returned dataifnotisinstance(initial_addresses,list):err_msg="Received invalid addresses list from Go CreateNode."logger.error(f"[Instance {self._instance}] {err_msg}")raiseP2PError(f"[Instance {self._instance}] {err_msg}")elifnotinitial_addresses:err_msg="Received empty addresses list from Go CreateNode."logger.error(f"[Instance {self._instance}] {err_msg}")raiseP2PError(f"[Instance {self._instance}] {err_msg}")self._peer_id=initial_addresses[0].split("/")[-1]ifP2P.supports_file_stream:p2p_files.clear_incoming(self._peer_id)# What a previous run of this identity left half receivedlogger.info(f"✅ [Instance {self._instance}] Node created with ID: {self._peer_id}")logger.info(f"👂 [Instance {self._instance}] Listening on: {initial_addresses}")logger.info(f"🌐 [Instance {self._instance}] Publicly reachable: {self._is_public}")logger.info(f"🎉 [Instance {self._instance}] Node initialized successfully.")exceptExceptionase:logger.error(f"❌ [Instance {self._instance}] Node creation failed: {e}")# Reclaim the instance ID using the _instance_ids listifself._instance!=-1:# Check if an ID was actually assignedwithP2P._instance_lock:P2P._instance_ids[self._instance]=Falselogger.info(f"[Instance {self._instance}] "f"Reclaimed instance ID {self._instance} due to creation failure.")raise# Re-raise the exception that caused the failurelogger.info("🎉 Node created successfully.")
One host of the native networking library on one network.
P2P.setup_library() must have run once in the process before any instance is created. The constructor then creates the host, waits until it listens and records its peer ID. Each process has at most max_instances slots (32 by default). An instance takes the first free slot and releases it in close.
Argument
Type
Default
Meaning
identity_dir
str
required
Folder of the private key of the host (created when missing). The same folder gives the same peer ID at every start.
port
int
0
First port to listen on. The host uses four consecutive ports (one per transport). 0 picks free ports at random.
ips
list[str] \| None
None
Addresses to listen on. None means every interface.
enable_relay_client
bool
True
Lets the host reserve a slot on a relay and be reached through it. It is forced on when enable_relay_service is on.
enable_relay_service
bool
False
Makes the host a relay for other nodes. The node turns it on for the world network of a world and for the public network of a node with NODE_IS_PUBLIC_RELAY.
use_broad_limits
bool
False
Gives the relay service larger resource limits. The node uses it on the world network.
is_isolated
bool
False
Accepts connections only from friendly peers and turns off the reachability probes. The node takes it from NODE_IS_ISOLATED.
knows_is_public
bool
False
Declares the host publicly reachable. Without it the host tries to become reachable (port mapping, hole punching, probes by other peers) and reports its verdict in is_public.
enable_tls
bool
False
Asks for an automatic certificate for the secure listener (needs internet access). Ignored when a custom certificate is given.
domain_name
str \| None
None
Domain of a custom certificate.
tls_cert_path
str \| None
None
Path of a custom certificate (PEM).
tls_key_path
str \| None
None
Path of the private key of a custom certificate (PEM).
probe_peers
list[str] \| None
None
Addresses of peers asked at boot to dial back and tell the host whether it is reachable. None uses the relays of the UNaIVERSE infrastructure and [] disables the probes.
webrtc_enabled
bool
True
Accepts connections from browsers through the browser transport.
flood_sub
bool
False
Uses flooding for the topics instead of the default router. The node turns it on for the world network.
ice_stun_servers
list[str] \| None
None
Servers that the browser transport uses to discover its public address. None uses a public default.
ice_turn_servers
list[dict] \| None
None
Relay servers of the browser transport, each with "urls", "username" and "credential".
log_sub
str
"pub"
Label of the instance in the logs ("pub" or "prv" in the node).
A custom certificate needs all three of domain_name, tls_cert_path and tls_key_path. Giving only some of them raises ValueError. The constructor raises P2PError in three cases: (1) setup_library has not run, (2) no slot is free and (3) the library cannot create the host. In the last case the slot is released before the error propagates. When the library supports file messages, the constructor also deletes what a previous run of the same identity left in its incoming folder (see files.clear_incoming).
The node creates its two hosts in two parallel threads because creating a host blocks until it listens.
The loaded native library (class attribute). The package unaiverse.networking.p2p assigns it at import time. setup_library raises P2PError when it is missing.
True when the library can pop the stream messages apart from the rest (class attribute, decided in setup_library). A node with a network task and a tick task then lets the network task take everything but the streams and lets each tick take one message per stream channel. A library that cannot split the pops answers a pop of kind "network" with every message as "all" does and a pop of kind "streams" with nothing.
True when the send queues are on, the library can be told the capabilities of a peer and Custom.CHUNK_SIZE is positive (class attribute). A message larger than one chunk (5 MB) can then travel as a sequence of chunks on one stream up to Custom.MAX_MESSAGE_SIZE (1 GB). The Session announces it to the peer with the bit CAP_CHUNKED_FRAMES.
True when supports_file_stream holds and Custom.ACCEPT_FILES is on (class attribute). The Session announces it to the peer with the bit CAP_FILE_STREAM. A node that does not accept file messages still streams its own files to the peers that accept them.
True when chunks are supported and the library can stop one queued message (class attribute). The Session announces it with the bit CAP_STOP_SENDING and honors a STOP_SENDING of the peer through cancel_send.
A callable peer_id -> (handle, node name) or None that gives the name of the folder of a received file. It starts as None. The node replaces it on both instances with a function that reads the profile of the sender in the hosted agent or world and returns None when the sender is unknown. A file of an unknown sender goes to Downloads/unknown/<peer ID>/.
@classmethoddefsetup_library(cls,max_instances:int|None=None,max_channels:int|None=None,max_queue_per_channel:int|None=None,max_message_size:int|None=None,enable_logging:bool=False,unai_logger:Any=None)->None:""" Initializes the underlying Go library. Must be called once. This is called automatically. Initializes the underlying Go library. Must be called once. This is called automatically. Args: enable_logging: Enable Go-level log output. When True and ``unai_logger`` is supplied, all Go stdout/stderr lines are captured and routed to the ``P2P`` channel of the provided logger instead of being printed raw to the terminal. unai_logger: An instance of ``unaiverse.utils.logger.Logger``. When provided (and ``enable_logging=True``), Go output is intercepted at the OS file-descriptor level and emitted via ``logger.p2p()``. Ignored when ``enable_logging=False``. """withcls._initialize_lock:ifcls._library_initialized:logger.warning("P2P library is already initialized. Skipping setup.")returnifnothasattr(cls,'libp2p')orcls.libp2pisNone:raiseP2PError("Library not loaded before setup. Check package __init__.py")# Configure Python logging based on the flagifnotenable_logging:logger.setLevel(logging.CRITICAL)_log_config={}else:logger.setLevel(logging.INFO)_log_config={'net/identify':'info','unailib':'info',# The AutoTLS certificate manager: the wait for the verdict, the registration# and the certificate, or why none was asked'p2p-forge/client':'info','nat':'info','basichost':'info','p2p-circuit':'info','relay':'info','p2p-holepunch':'info','tcp-tpt':'info','quic-transport':'info','quicreuse':'info','webtransport':'info','connmgr':'info','dht':'info',# AutoRelay reports its candidates and reservation attempts at debug only'autorelay':'debug','autonat':'info','autonatv2':'info',# 'rcmgr': 'info','swarm2':'info','yamux':'info',}# --- Start OS-level fd capture BEFORE InitializeLibrary, so we# catch every line the Go runtime emits from the very start ---ifenable_loggingandunai_loggerisnotNoneand_CAPTURE_AVAILABLE:def_make_cb(src_label:str):def_cb(line:str):unai_logger.p2p(line,src=src_label)return_cbcls._cap_stdout=FdCapture(1,_make_cb("stdout"))cls._cap_stderr=FdCapture(2,_make_cb("stderr"))cls._cap_stdout.start()cls._cap_stderr.start()logger.info("🐍 Go stdout/stderr redirected to P2P log channel.")logger.info("🐍 Setting up and initializing P2P library core with user settings...")cls._type_interface=TypeInterface(cls.libp2p)# Use provided arguments or fall back to class defaults_max_instances=max_instancesifmax_instancesisnotNoneelsecls._MAX_INSTANCES_max_channels=max_channelsifmax_channelsisnotNoneelsecls._MAX_NUM_CAHNNELS_max_queue=max_queue_per_channelifmax_queue_per_channelisnotNoneelsecls._MAX_QUEUE_PER_CHANNEL_max_msg_size=max_message_sizeifmax_message_sizeisnotNoneelsecls._MAX_MESSAGE_SIZE# Validate the message-size cap: it is passed to Go as a C int and there# reinterpreted as uint32. A non-positive or >2^31-1 value would wrap to a# negative C int and then to a huge uint32, silently lifting the cap.ifnot(0<_max_msg_size<=2**31-1):raiseValueError(f"max_message_size must be a positive int <= 2^31-1, got {_max_msg_size}.")# Update class attributes if they were overriddencls._MAX_INSTANCES=_max_instancescls._instance_ids=[False,]*_max_instances# Resize the tracking list# Call the Go function to set up its internal statelogger.info("🐍 Initializing Go library core...")cls.libp2p.InitializeLibrary(cls._type_interface.to_go_int(_max_instances),cls._type_interface.to_go_int(_max_channels),cls._type_interface.to_go_int(_max_queue),cls._type_interface.to_go_int(_max_msg_size),cls._type_interface.to_go_json(_log_config))# The per-peer send queues of the direct messages, with the limits of Custom (Go has no defaults of its# own); a library older than them has no such export and keeps sending synchronouslycls._send_queues_enabled=Falseifhasattr(cls.libp2p,'ConfigureSendQueues'):send_queue_config={'max_bytes_per_peer':int(Custom.SEND_QUEUE_MAX_BYTES_PER_PEER),'max_msgs_per_peer':int(Custom.SEND_QUEUE_MAX_MSGS_PER_PEER),'max_bytes_total':int(Custom.SEND_QUEUE_MAX_BYTES_TOTAL),'low_water':float(Custom.SEND_QUEUE_LOW_WATER),'max_wait_age_ms':int(Custom.SEND_MAX_WAIT_AGE*1000),'max_dial_attempts':int(Custom.SEND_MAX_DIAL_ATTEMPTS),'retry_backoff_ms':[int(b*1000)forbinCustom.SEND_RETRY_BACKOFF],'write_base_timeout_ms':int(Custom.SEND_WRITE_BASE_TIMEOUT*1000),'write_min_bytes_per_sec':int(Custom.SEND_WRITE_MIN_BYTES_PER_SEC),'max_events':int(Custom.SEND_MAX_EVENTS),'chunk_size':int(Custom.CHUNK_SIZE),'max_message_size':int(Custom.MAX_MESSAGE_SIZE),'reassembly_max_bytes_per_peer':int(Custom.REASSEMBLY_MAX_BYTES_PER_PEER),'reassembly_max_bytes_total':int(Custom.REASSEMBLY_MAX_BYTES_TOTAL),'reassembly_timeout_ms':int(Custom.REASSEMBLY_TIMEOUT*1000),'file_incoming_dir':p2p_files.incoming_dir(),'accept_files':bool(Custom.ACCEPT_FILES),'max_file_size':int(Custom.MAX_FILE_SIZE),}result=cls._type_interface.from_go_ptr_to_json(cls.libp2p.ConfigureSendQueues(cls._type_interface.to_go_json(send_queue_config)))ifresultisnotNoneandresult.get('state')=="Success":cls._send_queues_enabled=Truecls.supports_chunked_frames=(hasattr(cls.libp2p,'SetPeerCapabilities')andint(Custom.CHUNK_SIZE)>0)cls.supports_file_stream=(cls.supports_chunked_framesandhasattr(cls.libp2p,'SendFileMessageToPeer'))cls.accepts_file_stream=cls.supports_file_streamandbool(Custom.ACCEPT_FILES)cls.supports_stop_sending=cls.supports_chunked_framesandhasattr(cls.libp2p,'CancelSend')logger.info(f"✅ Send queues configured: {send_queue_config}")else:logger.error(f"❌ Send queues not configured, sends stay synchronous: {result}")cls.supports_split_pop=hasattr(cls.libp2p,'PopNetworkMessages')cls._library_initialized=Truelogger.info("✅ Go library initialized successfully.")
Initializes the native library once per process (classmethod). The node calls it in its constructor with enable_logging=Custom.LIBP2PLOG and its own logger. A second call only logs a warning and returns. All the nodes of one process therefore share the first configuration.
Argument
Type
Default
Meaning
max_instances
int \| None
None (32)
Number of host slots in the process.
max_channels
int \| None
None (100)
Number of receive channels per host.
max_queue_per_channel
int \| None
None (50)
Number of received messages kept per channel until they are popped.
max_message_size
int \| None
None
Largest message carried as a single frame. None takes Custom.LEGACY_MAX_MESSAGE_SIZE (50 MB). A value outside (0, 2**31 - 1] raises ValueError.
enable_logging
bool
False
Turns on the logs of the library and of this module.
unai_logger
Logger \| None
None
The SDK logger. With enable_logging=True the standard output and standard error of the process are captured at the file-descriptor level and every line goes to unai_logger.p2p().
When the library has send queues, the method also configures them from Custom. The table lists the values in the current version.
Custom constant
Value
Effect
SEND_QUEUE_MAX_MSGS_PER_PEER
64
Messages in the queue of one peer.
SEND_QUEUE_MAX_BYTES_PER_PEER
1 GB + 64 MB
Bytes in the queue of one peer.
SEND_QUEUE_MAX_BYTES_TOTAL
4 GB
Bytes in all the queues of the process.
SEND_QUEUE_LOW_WATER
0.5
Fraction of the limits a refusing queue must drain to before it accepts again.
SEND_MAX_WAIT_AGE
60 s
Time the oldest message may wait without progress before the queue is dropped.
SEND_MAX_DIAL_ATTEMPTS
3
Failed writes in a row before the queue is dropped.
SEND_RETRY_BACKOFF
1, 2, 4 s
Wait before each retry (the last value repeats).
SEND_WRITE_BASE_TIMEOUT
10 s
Base deadline of one write.
SEND_WRITE_MIN_BYTES_PER_SEC
1 MB/s
Slowest rate a write waits for. The deadline grows with the size of the frame at this rate.
SEND_MAX_EVENTS
1024
Send events kept until they are popped (the oldest are lost first).
CHUNK_SIZE
5 MB
Bytes of message carried by one chunk.
MAX_MESSAGE_SIZE
1 GB
Largest message in memory, sent or received (0 means no limit).
REASSEMBLY_MAX_BYTES_PER_PEER
1 GB
Bytes under reassembly from one peer.
REASSEMBLY_MAX_BYTES_TOTAL
4 GB
Bytes under reassembly from all the peers.
REASSEMBLY_TIMEOUT
120 s
Wait for the next chunk of a message before it is dropped.
ACCEPT_FILES
True
Accepts file messages.
MAX_FILE_SIZE
0
Largest file sent or received (0 means no limit).
The incoming folder of the files comes from files.incoming_dir(). The capability flags (supports_chunked_frames, supports_file_stream, accepts_file_stream, supports_stop_sending) become True only when the library accepts this configuration. With an older library they stay False. Sends are then synchronous and every message travels as one frame of at most 50 MB.
defconnect_to(self,multiaddrs:list[str])->dict[str,Any]:""" Establishes a connection with a remote peer. Args: multiaddrs: The list of multiaddress strings of the peer to try to connect to. Returns: A dictionary containing the connected peer's AddrInfo (ID and Addrs). Raises: P2PError: If the connection fails. ValueError: If the multiaddr is invalid. """ifnotmultiaddrsornotisinstance(multiaddrs,list):logger.error("Invalid multiaddr provided.")raiseValueError("Invalid multiaddr provided.")dest_peer_id=multiaddrs[0].split('/')[-1]logger.info(f"📞 Attempting to connect to: {dest_peer_id}...")try:result_ptr=P2P.libp2p.ConnectTo(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_json(multiaddrs))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to connect to peer, received null result.")raiseP2PError("Failed to connect to peer, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to connect to peer '{dest_peer_id}': {result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to connect to peer '{dest_peer_id}': "f"{result.get('message','Unknown Go error')}")peer_info=result.get('message',{})logger.info(f"✅ Connection initiated to peer: {peer_info.get('ID',dest_peer_id)}")# Use ID if availablereturnpeer_infoexceptExceptionase:logger.error(f"❌ Connection to {dest_peer_id} failed: {e}")raiseP2PError(f"Connection to {dest_peer_id} failed")frome
Dials a peer and blocks until a connection is open or the dial fails (raw call). connect runs it in a worker thread.
Argument
Type
Meaning
multiaddrs
list[str]
The addresses of the peer. Each one ends with /p2p/<peer ID>. The library dials all of them in parallel within one timeout and keeps the first connection that opens.
Returns the address info of the peer as a dict with "ID" (its peer ID) and "Addrs" (the list with the address that connected). Raises ValueError for an empty argument or one that is not a list and P2PError when the dial fails.
defdisconnect_from(self,peer_id:str)->None:""" Closes connections to a specific peer and removes tracking. Args: peer_id: The Peer ID string of the peer to disconnect from. Raises: P2PError: If disconnecting fails. ValueError: If the peer_id is invalid. """ifnotpeer_idornotisinstance(peer_id,str):logger.error("Invalid Peer ID provided.")raiseValueError("Invalid Peer ID provided.")# Basic peer ID format check (Qm... or 12D3...)ifnot(peer_id.startswith("Qm")orpeer_id.startswith("12D3")):logger.warning(f"⚠️ Warning: Peer ID '{peer_id}' does not look like a standard v0 or v1 ID.")logger.info(f"🔌 Attempting to disconnect from peer: {peer_id}...")try:result_ptr=P2P.libp2p.DisconnectFrom(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(peer_id))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to disconnect from peer, received null result.")raiseP2PError("Failed to disconnect from peer, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to disconnect from peer '{peer_id}': {result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to disconnect from peer '{peer_id}': "f"{result.get('message','Unknown Go error')}")logger.info(f"✅ Successfully disconnected from {peer_id}")exceptExceptionase:logger.error(f"❌ Disconnection from {peer_id} failed: {e}")raiseP2PError(f"Disconnection from {peer_id} failed")frome
Closes every connection to a peer (raw call). The close is abortive because the library first resets every open stream. A frame that was written just before the call and not yet delivered is lost. Raises ValueError for an empty peer_id and P2PError when the call fails. A peer ID that does not start with Qm or 12D3 only logs a warning.
defsend_message_to_peer(self,channel:str,msg_bytes:bytes)->int|None:""" Sends a direct message to a specific peer. With the send queues on, the message is only queued (the call returns at once, whatever the state of the peer) and a writer of the peer writes it, in order. Args: channel: The string identifying the channel for the communication. msg_bytes: The message to send (bytes). Returns: The sequence number of the message in the queue of its peer, or None when the send queues are off (the message was then written before returning). Raises: P2PQueueFull: If the send queue of the peer is full (the message is not queued). P2PError: If message sending fails (based on return code). ValueError: If inputs are invalid. TypeError: If data is not bytes. """ifnotchannelornotisinstance(channel,str):logger.error("Invalid channel provided.")raiseValueError("Invalid channel provided.")if"::dm:"notinchannel:# Guard the split below: without "::dm:" it would raise a raw IndexError.logger.error(f"Invalid direct-message channel format: '{channel}'.")raiseValueError(f"Invalid direct-message channel format: '{channel}'.")# Serialize the entire message object to bytes using Protobuf.payload_len=len(msg_bytes)peer_id=channel.split("::dm:")[1].split('-')[0]# Extract Peer ID from channel format# Call the Go functiontry:result_ptr=P2P.libp2p.SendMessageToPeer(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(channel),P2P._type_interface.to_go_bytes(msg_bytes),# Pass bytes directlyP2P._type_interface.to_go_int(payload_len),)result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error(f"Failed to send direct message to {peer_id}, received null result.")raiseP2PError(f"Failed to send direct message to {peer_id}, received null result.")ifresult.get('state')=="Error":ifresult.get('code')=="queue_full":raiseP2PQueueFull(result.get('message','Send queue full'),peer_id)logger.error(f"Failed to send direct message to '{peer_id}': "f"{result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to send direct message to '{peer_id}': "f"{result.get('message','Unknown Go error')}")seq=result.get('seq')logger.info(f"✅ Successfully {'queued'ifseqisnotNoneelse'sent'} direct message to "f"...{peer_id[-5:]}.")returnseqexceptP2PQueueFull:raiseexceptExceptionase:logger.error(f"❌ Sending direct message to {peer_id} failed: {e}")raiseP2PError(f"Sending direct message to {peer_id} failed")frome
Sends the bytes of a direct chat message (raw call). send runs it in a worker thread after encoding the Msg.
Argument
Type
Meaning
channel
str
A direct channel <own peer ID>::dm:<peer ID>-<content type>[~<trail>]. The peer is read from the part between ::dm: and the first -.
msg_bytes
bytes
The encoded message.
With the send queues on, the message is appended to the queue of the peer and the method returns its sequence number (int) at once whatever the state of the peer. Each peer has its own sequence numbers that grow by one per message and the events of pop_send_events refer to them. With the queues off, the method writes the message before it returns and returns None.
It raises ValueError for a channel that is empty or has no ::dm:, P2PQueueFull when the queue of the peer is full and P2PError for any other refusal. A message larger than the limit of the peer is refused with P2PError and is never sent.
defbroadcast_message(self,channel:str,msg_bytes:bytes)->None:""" Broadcasts a message using PubSub to the node's own topic. Peers subscribed to this node's Peer ID topic will receive it. Args: channel: The Channel for this topic (e.g., owner_peer_id::ps:topic_name). msg_bytes: The message to send (bytes). Raises: P2PError: If broadcasting fails. ValueError: If inputs are invalid. TypeError: If data is not bytes. """ifnotchannelornotisinstance(channel,str):raiseValueError("Invalid channel provided.")if"::ps:"notinchannel:logger.error(f"Invalid pubsub channel format: '{channel}'.")raiseValueError(f"Invalid pubsub channel format: '{channel}'.")# Serialize the entire message object to bytes using Protobuf.payload_len=len(msg_bytes)# Call SendMessageToPeer with an empty peer_id string for broadcasttry:result_ptr=P2P.libp2p.SendMessageToPeer(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(channel),P2P._type_interface.to_go_bytes(msg_bytes),P2P._type_interface.to_go_int(payload_len),)result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error(f"Failed to broadcast message on channel {channel}, received null result.")raiseP2PError(f"Failed to broadcast message on channel {channel}, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to broadcast message on channel '{channel}': "f"{result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to broadcast message on channel '{channel}': "f"{result.get('message','Unknown Go error')}")exceptExceptionase:logger.error(f"❌ Broadcasting to {channel} failed: {e}")raiseP2PError(f"Broadcasting to {channel} failed")fromelogger.info(f"✅ Successfully broadcasted message on channel {channel}.")
Publishes the bytes of a message on a topic of this host (raw call). broadcast runs it in a worker thread.
Argument
Type
Meaning
channel
str
A topic channel <own peer ID>::ps:<topic>, for example the rendezvous channel <world peer ID>::ps:rv.
msg_bytes
bytes
The encoded message.
Every peer subscribed to the topic receives the message. A broadcast message is one frame and obeys the single-frame limit (50 MB). Raises ValueError for a channel without ::ps: and P2PError when the library refuses the message.
asyncdefsend(self,channel:str,msg:Msg)->int|None:"""Encodes and sends a direct chat Msg to a peer (async). The wire codec (Msg.to_bytes) and the thread offload both live here, at the transport tier (the rewrite boundary toward OP2P.js): the Coordinator hands over a Msg object and awaits, it never serializes nor offloads. Outbound mirror of send_session. With the send queues on, the Go call only queues, and the thread is still worth it for the protobuf + PNG + gzip encoding. Args: channel: The direct-message channel. msg: The message object. Returns: The sequence number of the message in the queue of its peer, or None when the send queues are off. Raises: P2PQueueFull: If the send queue of the peer is full. P2PError: If the send fails. """# The FILE samples with a path go next to the message, read from disk while they are sent, to a peer that takes# file messages; to any other peer their files are read into the messagestreamed=p2p_files.streamed_files(msg.content_type,msg.content)ifP2P.supports_file_streamelse[]ifstreamedandself._peer_caps.get(self._peer_of_channel(channel),0)&CAP_FILE_STREAM:keys={f["key"]forfinstreamed}try:returnawaitasyncio.to_thread(lambda:self.send_file_message_to_peer(channel,msg.to_bytes(streamed_keys=keys),streamed))exceptP2PNoFileStream:pass# The lambda function moves the protobuf+PNG+gzip work (the expensive part) off the event loopreturnawaitasyncio.to_thread(lambda:self.send_message_to_peer(channel,msg_bytes=msg.to_bytes()))
Encodes a Msg and sends it to the peer of a direct channel (async). SessionManager.send calls it on behalf of NodeConn.send.
Argument
Type
Meaning
channel
str
The direct channel.
msg
Msg
The message.
The method first looks for FILE samples that point to a file on disk (see files.streamed_files). The message travels as a file message when such samples exist, the library supports file messages and the Session of the peer announced CAP_FILE_STREAM. The samples then travel without their content and the library streams the files from disk after the message. In every other case, including a P2PNoFileStream raised by the library, the files are read into the message and it travels as a normal message. Encoding (the binary message format, PNG, gzip) and the call of the library run in a worker thread so that the event loop keeps running.
Returns the sequence number of the message in the queue of the peer (None when the queues are off) and raises P2PQueueFull and P2PError as send_message_to_peer does. A file that cannot be read raises OSError while the message is encoded.
defsend_file_message_to_peer(self,channel:str,msg_bytes:bytes,files:list[dict])->int|None:"""Queues a file message for a peer: the message, whose FILE samples have no content, and their files, which Go reads from disk while it sends them (Phase 6.5). Args: channel: The direct-message channel. msg_bytes: The message. files: The files, [{"key": sample name, "path": file}]. Returns: The sequence number of the message in the queue of its peer. Raises: P2PNoFileStream: If the peer does not take file messages (nothing queued). P2PQueueFull: If the send queue of the peer is full. P2PError: If the message is refused for another reason (a limit, a missing file). """importjsonpeer_id=self._peer_of_channel(channel)result=P2P._type_interface.from_go_ptr_to_json(P2P.libp2p.SendFileMessageToPeer(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(channel),P2P._type_interface.to_go_bytes(msg_bytes),P2P._type_interface.to_go_int(len(msg_bytes)),P2P._type_interface.to_go_string(json.dumps(files))))ifresultisNone:raiseP2PError(f"Failed to send a file message to {peer_id}, received null result.")ifresult.get('state')=="Error":ifresult.get('code')=="no_file_stream":raiseP2PNoFileStream(result.get('message','No file messages'))ifresult.get('code')=="queue_full":raiseP2PQueueFull(result.get('message','Send queue full'),peer_id)logger.error(f"Failed to send a file message to '{peer_id}': {result.get('message')}")raiseP2PError(f"Failed to send a file message to '{peer_id}': {result.get('message')}")logger.info(f"✅ Queued a file message ({len(files)} files) to ...{peer_id[-5:]}.")returnresult.get('seq')
Queues a file message for a peer (raw call). The message holds the FILE samples without their content. The library reads each file from disk while it sends it as chunks after the message. send calls this method in a worker thread.
Argument
Type
Meaning
channel
str
The direct channel.
msg_bytes
bytes
The message encoded with streamed_keys.
files
list[dict]
The files, each {"key": sample name, "path": file} (a "name" key is accepted).
Returns the sequence number of the message in the queue of the peer. Raises P2PNoFileStream when the peer does not accept file messages, P2PQueueFull when its queue is full and P2PError for any other refusal (a file that is missing, a file above MAX_FILE_SIZE or a limit of the peer). In each of these cases nothing is queued.
asyncdefbroadcast(self,channel:str,msg:Msg)->None:"""Encode and broadcast a chat Msg over pubsub. Like send, the codec and the thread offload live here; the Coordinator hands over a Msg object and awaits (async)."""awaitasyncio.to_thread(self.broadcast_message,channel,msg.to_bytes())
Encodes a Msg and publishes it on a topic in a worker thread (async). SessionManager.broadcast calls it on behalf of NodeConn.publish. Raises P2PError as broadcast_message does.
defpop_messages(self,kind:str="all")->list[bytes]:""" Retrieves and removes the first message from the queue of each chat/pubsub channel for this node instance, and every queued frame of the Session protocols (their queues are shared by all the peers, so they are drained in full at every call, oldest frame first). With kind "network" it takes instead every queued message of every channel that is not a stream channel (Session frames included), with kind "streams" the oldest message of every stream channel (stream_sample direct messages, PubSub topics): the network pass and the tick of a node with two tasks. A library without the split pops serves "network" as "all" and "streams" with nothing. Args: kind: "all" (default), "network" or "streams". Returns: A list of byte arrays (messages). Returns an empty list if no messages were available. Raises: P2PError: If popping messages failed internally in Go, or if data conversion fails for any message. """logger.debug(f"[Instance {self._instance}] Popping message(s)...")try:go_instance_c=P2P._type_interface.to_go_int(self._instance)ifkind=="all"ornotP2P.supports_split_pop:ifkind=="streams":return[]result_ptr=P2P.libp2p.PopMessages(go_instance_c)elifkind=="network":result_ptr=P2P.libp2p.PopNetworkMessages(go_instance_c)else:result_ptr=P2P.libp2p.PopStreamMessages(go_instance_c)# Binary message buffer (success) or JSON status dict (Empty/Error);# from_go_pop_messages decodes either and frees result_ptr. On the binary# path each message's "data" is already raw bytes (no base64).raw_result=P2P._type_interface.from_go_pop_messages(result_ptr)ifraw_resultisNone:# This indicates an issue with the C call or JSON conversion in TypeInterfacelogger.error(f"[Instance {self._instance}] PopMessages: "f"Received null/invalid result from TypeInterface.")raiseP2PError(f"[Instance {self._instance}] PopMessages: Failed to get valid JSON response.")# Check for Go-side error or empty states firstifisinstance(raw_result,dict):state=raw_result.get('state')ifstate=="Empty":logger.debug(f"[Instance {self._instance}] PopMessages: Queue is empty.")return[]# No messages availableifstate=="Error":error_message=raw_result.get('message','Unknown Go error during PopMessages')logger.error(f"[Instance {self._instance}] PopMessages: {error_message}")raiseP2PError(f"[Instance {self._instance}] PopMessages: {error_message}")# If it's a dict but not a known state, it's unexpectedlogger.warning(f"[Instance {self._instance}] PopMessages: Unexpected dictionary format: {raw_result}")raiseP2PError(f"[Instance {self._instance}] PopMessages: Unexpected dictionary response format.")# Expecting a list of messages if not an error/empty dictifnotisinstance(raw_result,list):# This also covers the case where n=0 and Go returns "[]" which json.loads makes a list# If it's not a list at this point, it's an unexpected format.logger.error(f"[Instance {self._instance}] PopMessages: Unexpected response format, expected a list or "f"specific state dictionary. Got: {type(raw_result)}")raiseP2PError(f"[Instance {self._instance}] PopMessages: Unexpected response format.")returnraw_resultexceptP2PError:# Re-raise P2PError directlyraiseexceptExceptionase:# Catch potential JSON parsing errors from TypeInterface or other unexpected errorslogger.error(f"[Instance {self._instance}] ❌ Error during pop_message: {e}")raiseP2PError(f"[Instance {self._instance}] Unexpected error during pop_message: {e}")frome
Takes the received messages out of the queues of the library (raw call). get_messages calls it at every cycle of the node.
Argument
Type
Default
Meaning
kind
str
"all"
"all" takes the oldest message of every chat or topic channel and every queued Session frame. "network" takes every queued message of every channel that is not a stream channel (Session frames included). "streams" takes the oldest message of every stream channel (stream samples and topics).
The Session protocols share one queue for all the peers and every call drains it completely in arrival order. Returns a list[dict], each with "from" (the peer ID that the transport verified), "protocol", "data" (a memoryview of the reply) and for a file message "files". An empty queue returns []. Raises P2PError when the library reports an error or the reply cannot be read.
defdrop_send_queue(self,peer_id:str)->int:"""Empties the send queue of a peer at once (Go records a queue_dropped event, reason "explicit"). For the purge of a peer: what is still queued for it is no longer wanted, and its writer must not dial it again. A no-op when the send queues are off. Args: peer_id: The peer. Returns: How many queued messages were dropped. """ifnotP2P._send_queues_enabled:return0try:result=P2P._type_interface.from_go_ptr_to_json(P2P.libp2p.DropSendQueue(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(peer_id)))exceptExceptionase:logger.error(f"[Instance {self._instance}] DropSendQueue({peer_id}) failed: {e}")return0ifresultisNoneorresult.get('state')!="Success":logger.error(f"[Instance {self._instance}] DropSendQueue({peer_id}) failed: {result}")return0returnint(result.get('message')or0)
Empties the send queue of a peer at once and returns how many messages it held (int). The library records a queue_dropped event with reason "explicit". SessionManager.drop_send_queue calls it when the node purges a peer or when a Session ends. At that point the queued messages are no longer wanted and the writer of the queue must not dial the peer again. It returns 0 when the queues are off or the call fails (the failure is logged).
defcancel_send(self,peer_id:str,seq:int)->bool:"""Stops one message of the send queue of a peer, because the peer (its receiver) asked so (STOP_SENDING). A message still waiting leaves the queue at once; the one being written stops before its next chunk. Go then records a queue_dropped event of that seq, reason "receiver_stopped". A no-op when the send queues are off. Args: peer_id: The peer (the receiver). seq: The sequence number of the message in its queue. Returns: True when the message was in the queue (and is now stopped). """ifnotP2P._send_queues_enabledornotP2P.supports_stop_sending:returnFalsetry:result=P2P._type_interface.from_go_ptr_to_json(P2P.libp2p.CancelSend(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(peer_id),int(seq)))exceptExceptionase:logger.error(f"[Instance {self._instance}] CancelSend({peer_id}, {seq}) failed: {e}")returnFalseifresultisNoneorresult.get('state')!="Success":logger.error(f"[Instance {self._instance}] CancelSend({peer_id}, {seq}) failed: {result}")returnFalsereturnbool(result.get('message'))
Stops one message in the send queue of a peer after that peer asked for it with STOP_SENDING. Session calls it when such a request arrives on an established Session.
Argument
Type
Meaning
peer_id
str
The peer that receives the message and asked to stop it.
seq
int
The sequence number of the message in the queue of that peer.
A message that still waits leaves the queue at once. The message being written stops before its next chunk. The library then records a queue_dropped event for that sequence number with reason "receiver_stopped". Returns True when the message was in the queue. It returns False in three cases: (1) the message was not in the queue, (2) the library does not support the send queues or the cancellation of a message and (3) the call failed.
defpop_send_events(self)->list[dict]:"""Pops the events of the send queues recorded since the last call, oldest first. Each event is a dict with "type" (written, write_failed, recovered, refused, queue_dropped, events_lost), "peer_id" (absent for events_lost), "time" (unix seconds) and the fields of its type: "seq", "from_seq", "to_seq", "count", "bytes", "attempt", "reason", "error". Consecutive written (or refused) events of a peer are merged into one. An empty list when the send queues are off. Returns: The list of the events. """ifnotP2P._send_queues_enabled:return[]try:result=P2P._type_interface.from_go_ptr_to_json(P2P.libp2p.PopSendEvents(P2P._type_interface.to_go_int(self._instance)))exceptExceptionase:logger.error(f"[Instance {self._instance}] PopSendEvents failed: {e}")return[]ifresultisNoneorresult.get('state')!="Success":ifresultisNoneorresult.get('state')!="Empty":logger.error(f"[Instance {self._instance}] PopSendEvents failed: {result}")return[]returnlist(result.get('message')or[])
Returns the events of the send queues recorded since the last call as a list[dict] in the order they happened. SessionManager.pop_send_events calls it at every cycle and the node hands the events to Agent.on_send_event and Agent.on_transfer_progress (see Agents).
Every event has "type", "time" (Unix seconds) and, except for events_lost, "peer_id". The other fields depend on the type.
Type
Meaning
Fields
written
Messages up to seq were written to their stream. This is no proof that the peer processed them.
seq
write_failed
A write failed and the message stays for a retry.
seq, attempt, error
recovered
A write succeeded after failures.
count
refused
The full queue refused messages.
count
queue_dropped
Queued messages were dropped. reason is max_attempts, max_age, explicit or receiver_stopped.
from_seq, to_seq, count, reason, error
events_lost
Events were lost because they were popped too rarely.
count
progress
Bytes of message seq written so far (only for a message larger than one chunk).
seq, bytes, total, kind ("chunked" or "file"), files
receive_progress
Bytes of message seq of the peer received so far.
seq, bytes, total, kind, files
receive_dropped
A message of the peer was dropped while it arrived. reason is timeout, hash_mismatch or too_large.
seq, bytes, total, reason
Consecutive written (or refused) events of one peer are merged into one. A field with a zero or empty value is absent. The method returns [] when the queues are off or the call fails.
defset_peer_capabilities(self,peer_id:str,capabilities:int,max_message_size:int|None,max_file_size:int|None=None)->None:"""Tells Go what a peer can receive: the capability bits of its HELLO / HELLO_ACK, and the largest message and file its profile accepts. A message larger than a chunk then goes to it as chunk frames if it has CAP_CHUNKED_FRAMES, a message with path-backed files as a file message if it has CAP_FILE_STREAM, and one above its maximum is refused instead of sent (it would be reset). Args: peer_id: The peer. capabilities: Its CAP_* bits. max_message_size: The largest message it accepts (0: no limit; None: unknown, legacy). max_file_size: The largest file it accepts (0 or None: no limit). """self._peer_caps[peer_id]=int(capabilities)ifnothasattr(P2P.libp2p,'SetPeerCapabilities'):returntry:P2P._type_interface.from_go_ptr_to_json(P2P.libp2p.SetPeerCapabilities(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(peer_id),int(capabilities),-1ifmax_message_sizeisNoneelseint(max_message_size),int(max_file_sizeor0)))exceptExceptionase:logger.error(f"[Instance {self._instance}] SetPeerCapabilities({peer_id}) failed: {e}")
Tells the library what a peer can receive. SessionManager.set_peer_capabilities calls it after every ESTABLISHED or RESUMED Session with the values of the handshake and of the profile of the peer.
Argument
Type
Default
Meaning
peer_id
str
required
The peer.
capabilities
int
required
The CAP_* bits of its HELLO or HELLO_ACK (see sess_msg).
max_message_size
int \| None
required
The largest message the peer accepts according to its profile. 0 means no limit and None means unknown (an older peer, treated with the single-frame limit).
max_file_size
int \| None
None
The largest file the peer accepts. 0 and None mean no limit.
From then on, a message larger than one chunk goes to the peer as chunks only when it has CAP_CHUNKED_FRAMES and a message with files on disk goes as a file message only when it has CAP_FILE_STREAM. A message above the maximum of the peer is refused when it is sent instead of being reset by the peer. The instance also stores the bits because send reads them. A failure of the call is logged and not raised. The method only stores the bits when the library lacks this function.
defsubscribe_to_topic(self,channel:str)->None:""" Subscribes to a PubSub topic to receive messages. Args: channel: The Channel for this topic (e.g., owner_peer_id::ps:topic_name). Raises: P2PError: If subscribing fails. ValueError: If topic_name is invalid. """ifnotchannelornotisinstance(channel,str):logger.error("Invalid topic name provided.")raiseValueError("Invalid topic name provided.")logger.info(f"<sub> Subscribing to topic: {channel}...")try:result_ptr=P2P.libp2p.SubscribeToTopic(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(channel))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to subscribe to topic, received null result.")raiseP2PError("Failed to subscribe to topic, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to subscribe to topic '{channel}': {result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to subscribe to topic '{channel}': {result.get('message','Unknown Go error')}")logger.info(f"✅ Successfully subscribed to {channel}")exceptExceptionase:logger.error(f"❌ Subscription to {channel} failed: {e}")raiseP2PError(f"Subscription to {channel} failed")frome
Subscribes the host to a topic (raw call). channel is <owner peer ID>::ps:<topic>. Received messages of the topic come out of pop_messages. Raises ValueError for an empty channel and P2PError when the call fails. SessionManager.subscribe_to_topic calls it for NodeConn.subscribe.
defunsubscribe_from_topic(self,channel:str)->None:""" Unsubscribes from a PubSub topic. Args: channel: The Channel for this topic (e.g., owner_peer_id::ps:topic_name). Raises: P2PError: If unsubscribing fails. ValueError: If topic_name is invalid. """ifnotchannelornotisinstance(channel,str):logger.error("Invalid topic name provided.")raiseValueError("Invalid topic name provided.")logger.info(f"</sub> Unsubscribing from topic: {channel}...")try:result_ptr=P2P.libp2p.UnsubscribeFromTopic(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(channel))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to unsubscribe from topic, received null result.")raiseP2PError("Failed to unsubscribe from topic, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to unsubscribe from topic '{channel}': "f"{result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to unsubscribe from topic '{channel}': "f"{result.get('message','Unknown Go error')}")logger.info(f"✅ Successfully unsubscribed from {channel}")exceptExceptionase:logger.error(f"❌ Unsubscription from {channel} failed: {e}")raiseP2PError(f"Unsubscription from {channel} failed")frome
Leaves a topic (raw call). Same argument and errors as subscribe_to_topic.
defsend_on_protocol(self,peer_id:str,protocol_id:str,payload:bytes)->bool:""" Open a fresh outbound stream on `protocol_id` to `peer_id`, write a single length-prefixed protobuf payload, and close the stream. Returns True on send success, False on transport failure. The response (if any) is delivered asynchronously as a pop_messages entry whose `protocol` field equals `protocol_id`. """ifnotpeer_idornotisinstance(peer_id,str):raiseValueError("send_on_protocol: peer_id must be a non-empty string")ifnotprotocol_idornotisinstance(protocol_id,str):raiseValueError("send_on_protocol: protocol_id must be a non-empty string")ifnotisinstance(payload,(bytes,bytearray)):raiseTypeError("send_on_protocol: payload must be bytes")try:result_ptr=P2P.libp2p.SendOnProtocol(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(peer_id),P2P._type_interface.to_go_string(protocol_id),P2P._type_interface.to_go_bytes(bytes(payload)),P2P._type_interface.to_go_int(len(payload)),)result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNoneorresult.get('state')=='Error':logger.warning(f"send_on_protocol(...{peer_id[-5:]}, {protocol_id}) failed: "f"{result.get('message')ifresultelse'null result'}")returnFalsereturnTrueexceptExceptionase:logger.error(f"send_on_protocol(...{peer_id[-5:]}, {protocol_id}) exception: {e}")returnFalse
Opens a new outbound stream to a peer on a protocol, writes one length-prefixed payload and closes the stream (raw call). send_session runs it in a worker thread for every Session message.
Argument
Type
Meaning
peer_id
str
The peer. The library dials it when no connection is open.
protocol_id
str
The protocol, one of the Session protocols such as /unaiverse/session/hello/1.0.0.
payload
bytes \| bytearray
The encoded message.
Returns True when the local side accepted the payload and False on any failure of the transport (logged). An answer of the peer, if any, arrives later through pop_messages with "protocol" equal to protocol_id. Raises ValueError for an empty peer_id or protocol_id and TypeError for a payload that is not bytes.
asyncdefconnect(self,addresses:list[str])->tuple[str|None,bool]:"""Establish a connection to a peer: one ConnectTo with every non-loopback address. The libp2p swarm dials them in parallel under a single Go-side budget (its dialer already ranks transports; the first success wins), so there is no second sequential pass and the worst case is one dial timeout. Returns (peer_id, through_relay) (async)."""force:str|None=None# force: str | None = '/tcp'ifforceisnotNone:_addresses=[aforainaddressesifforceina]addresses.clear()forain_addresses:addresses.append(a)addresses=[aforainaddressesif"127.0.0.1"notina]iflen(addresses)==0:logger.error("Connection failed! (not even tried, no usable addresses)")returnNone,Falselogger.info(f"Connecting to {addresses}")try:# Off the event loop: the dial can block up to its timeout, and other# sessions must keep ticking meanwhile (e.g. during a re-dial).winning_addr_info_dict=awaitasyncio.to_thread(self.connect_to,addresses)peer_id=winning_addr_info_dict.get('ID')addrs=winning_addr_info_dict.get('Addrs')assertaddrsisnotNoneandisinstance(addrs,(tuple,list))connected_addr_str=addrs[0]through_relay='/p2p-circuit/'inconnected_addr_strlogger.info(f"Connected to peer {peer_id} via {connected_addr_str} "f"(through relay: {through_relay})")returnpeer_id,through_relayexceptP2PError:logger.error("Connection failed!")returnNone,False
Dials a peer in a worker thread and reports the outcome without raising (async). Session calls it for every dial of a handshake and of a reconnection.
Argument
Type
Meaning
addresses
list[str]
The addresses of the peer. Addresses that contain 127.0.0.1 are removed first.
Returns the tuple (peer_id, through_relay). The first item is the peer ID that answered and the second tells whether the connection goes through a relay (its address contains /p2p-circuit/). A failed dial and a list left empty by the filter both return (None, False). The call lasts at most one dial timeout of the library because the whole list goes to a single connect_to.
asyncdefdisconnect(self,peer_id:str)->bool:"""Abortively tear down the connection to `peer_id`. Go resets every open stream before closing the connection, so any frame written but not yet delivered (e.g. a GOAWAY queued microseconds earlier) is DESTROYED, not flushed: callers that just sent a farewell must not disconnect in the same stack — schedule the teardown after the Session reaches a terminal state. Returns True on success, False on a transport-level failure. The canonical transport-disconnect primitive the SessionManager delegates to; best-effort, any error (including a malformed peer_id) means 'gone' rather than propagating into the caller. The blocking Go round-trip (WebRTC teardown + stream resets + ClosePeer) runs off the event loop, same as `send` (async)."""try:awaitasyncio.to_thread(self.disconnect_from,peer_id)except(P2PError,ValueError):returnFalsereturnTrue
Closes every connection to a peer in a worker thread (async). SessionManager calls it in three cases: (1) the deferred cut of a Session that ended, (2) a coercive cut of the world perimeter and (3) a teardown with no farewell.
The close is abortive. A GOAWAY or a GOAWAY_ACK written a moment earlier is destroyed with its stream. A caller that has just sent a farewell must therefore wait for the Session to end before it disconnects. SessionManager enforces that order by waiting 2 s (the linger) before the cut (see session_manager). Returns True on success and False on any failure (a malformed peer ID included) and never raises.
asyncdefsend_session(self,peer_id:str,protocol_id:str,sess_msg:SessMsg)->bool:"""Serialize `sess_msg` via its own `to_bytes()` and open a fresh outbound stream on `protocol_id` to `peer_id`, writing one length-prefixed payload and closing the stream. Returns True when the payload was ACCEPTED by the local muxer (written + half-closed) — NOT when it was delivered: delivery needs the connection to stay alive for the transport to flush/retransmit, and an abortive disconnect (or process exit) right after a True return destroys the frame. End-to-end confirmation is the Session protocol's own ACKs (async). The Session FSM passes a `SessMsg` value object (not bytes), so this method stays protobuf-free: it just calls `.to_bytes()` on whatever it receives. The Go call runs off the event loop, same as `send`. """try:payload=sess_msg.to_bytes()exceptExceptionase:logger.error(f"send_session(...{peer_id[-5:]}, {protocol_id}) encode failed: {e}")returnFalsetry:returnawaitasyncio.to_thread(self.send_on_protocol,peer_id,protocol_id,payload)exceptExceptionase:logger.error(f"send_session(...{peer_id[-5:]}, {protocol_id}) failed: {e}")returnFalse
Encodes a SessMsg and sends it on a Session protocol in a worker thread (async). Session calls it for every message of the handshake, of the keep-alive and of the close. SessionManager calls it for the replies that belong to no Session.
Argument
Type
Meaning
peer_id
str
The peer.
protocol_id
str
The Session protocol.
sess_msg
SessMsg
The message. The method calls sess_msg.to_bytes().
Returns True when the local side accepted the payload. This does not prove delivery because an abortive disconnect or the end of the process right after the call destroys the frame. The Session messages carry their own acknowledgments (HELLO_ACK, PONG, RESUME_ACK, GOAWAY_ACK) for that reason. Returns False when the message cannot be encoded or sent and never raises.
defget_messages(self,kind:str="all")->tuple:"""Pop this instance's inbound batch (all, the network part or the streams: see pop_messages) and split it. The whole wire codec lives here, in the transport tier (this is the rewrite boundary toward OP2P.js): Session-protocol frames are decoded into SessionInbound(peer_id, protocol_id, SessMsg) via SessMsg.from_bytes, chat frames into Msg objects via Msg.from_bytes. Chat frames are also sender-verified here (the sender claimed inside the payload must match the cryptographically verified network sender); spoofed or undecodable frames are dropped. The Node-bound chat path downstream only gates membership and verifies the JWT piggyback, it never touches the codec. Inbound mirror of send_session / send. Returns (chat_messages, session_inbounds): chat_messages a list of decoded, sender-verified Msg; session_inbounds a list of SessionInbound. """chat_messages=[]session_inbounds=[]formsg_dictin(self.pop_messages()ifkind=="all"elseself.pop_messages(kind)):protocol_id=msg_dict.get("protocol")or""ifprotocol_idinSESSION_PROTOCOL_IDS:try:# The pop reply gives views of its buffer: protobuf parses them as they are, the Session codec# needs bytes (its frames are small)sess_msg=SessMsg.from_bytes(bytes(msg_dict.get("data")orb""),protocol_id)exceptExceptionase:logger.error(f"get_messages: failed to decode session message on "f"{protocol_id} from {msg_dict.get('from')}: {e}")continuesession_inbounds.append(SessionInbound(peer_id=msg_dict.get("from"),protocol_id=protocol_id,sess_msg=sess_msg))else:# Chat path (Node-bound). The binary transport delivers "data" already as# raw bytes (Go structure: {"from":"Qm...", "data":<bytes>, "protocol":"..."}).verified_sender_id=msg_dict.get("from")received_files=msg_dict.get("files")or[]try:msg_obj=Msg.from_bytes(msg_dict.get("data"))exceptExceptionase:logger.error(f"get_messages: failed to decode chat message from "f"{verified_sender_id}: {e}")p2p_files.remove_quietly([f["path"]forfinreceived_files])continue# --- CRITICAL SECURITY CHECK ---# Verify that the sender claimed inside the message payload matches the# cryptographically verified sender from the network layer.ifmsg_obj.sender!=verified_sender_id:logger.error(f"SENDER MISMATCH! Network sender '{verified_sender_id}' "f"does not match payload sender '{msg_obj.sender}'. "f"Discarding message.")p2p_files.remove_quietly([f["path"]forfinreceived_files])continueifreceived_filesandnotself._place_received_files(msg_obj,verified_sender_id,received_files):continuemsg_obj.wire_size=len(msg_dict.get("data")orb"")# For the bounds of what waits for a tickchat_messages.append(msg_obj)returnchat_messages,session_inbounds
Pops the received messages, decodes them and splits them into two lists. SessionManager.get_messages calls it at every cycle of the node.
Argument
Type
Default
Meaning
kind
str
"all"
Passed to pop_messages.
Returns (chat_messages, session_inbounds).
A frame on a Session protocol is decoded with SessMsg.from_bytes into a SessionInbound(peer_id, protocol_id, sess_msg). A frame that cannot be decoded is logged and skipped.
Any other frame is decoded with Msg.from_bytes. The method drops it when it cannot be decoded or when the sender written inside it differs from the peer ID that the transport verified. A message that passes gets the attribute wire_size (its length in bytes). A file message also has its files moved to the downloads folder (see files.place_received_file) and attached to its samples. When a file cannot be placed the method drops the message. The files of a dropped message are deleted.
The chat messages still carry the token of the sender in piggyback. NodeConn.get_messages checks it afterwards. Raises P2PError when the pop fails.
asyncdefsign_with_host_key(self,data:bytes)->bytes|None:"""Async wrapper over the host-key signer (see sync impl) (async)."""returnself._sign_with_host_key_sync(data)
Signs data (bytes) with the private key of the host and returns the raw signature (async). It returns None when the signing fails. Session signs nonce || session_id with it during the handshake (sig_a, sig_b). The call runs on the event loop because it does not block on the network. Raises TypeError when data is not bytes.
asyncdefverify_peer_signature(self,peer_id:str,data:bytes,signature:bytes)->bool:"""Async wrapper over the peer-signature verifier (see sync impl) (async)."""returnself._verify_peer_signature_sync(peer_id,data,signature)
Checks that signature over data was made by the key of peer_id (async). The public key is derived from the peer ID itself. This works for Ed25519 identities (the default of the SDK) and fails for RSA identities. Returns True for a valid signature and False otherwise or on any error. Raises TypeError when data or signature is not bytes. Session calls it on the signatures of the handshake.
defreserve_on_relay(self,relay_peer_id:str)->str:""" Attempts to reserve a slot on a specified relay node. Args: relay_peer_id: The peerID of the relay node Returns: The UTC expiration timestamp of the reservation as an ISO 8601 string. Raises: P2PError: If the reservation fails. ValueError: If the relay_multiaddr is invalid. """ifnotrelay_peer_idornotisinstance(relay_peer_id,str):logger.error("Invalid relay multiaddr provided.")raiseValueError("Invalid relay multiaddr provided.")logger.info(f"🅿️ Attempting to reserve slot on relay: {relay_peer_id}...")try:result_ptr=P2P.libp2p.ReserveOnRelay(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(relay_peer_id))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to reserve on relay, received null result.")raiseP2PError("Failed to reserve on relay, received null result.")ifresult.get('state')=="Error":go_error=result.get('message','Unknown Go error')logger.error(f"Failed to reserve on relay '{relay_peer_id}': {go_error}")raiseP2PError(f"Failed to reserve on relay '{relay_peer_id}': {go_error}")expiration_utc=result.get('message',{})ifnotisinstance(expiration_utc,str):raiseP2PError(f"Expected expiration timestamp string, but got {type(expiration_utc)}")logger.info(f"✅ Reservation successful. Expires at: {expiration_utc}")returnexpiration_utcexceptExceptionase:logger.error(f"❌ Reservation on {relay_peer_id} failed: {e}")print(e)raiseP2PError(f"Reservation on {relay_peer_id} failed")frome
Reserves a slot on a relay (raw call). The host can then be reached through a relayed address of that relay (see Networking). Takes the peer ID of the relay and returns the expiry of the reservation as an ISO 8601 string in UTC. Raises ValueError for an empty peer ID and P2PError when the relay refuses or the reply is not a string. A failure is also printed on standard output.
asyncdefreserve(self,relay_peer_id:str)->str:"""Reserve a relay slot, offloading the blocking Go call to a thread. The async boundary lives here, at the transport tier (like send / broadcast / send_session), so the Coordinator just awaits and never offloads. Returns the expiry timestamp; raises P2PError on failure (the Coordinator catches it) (async)."""returnawaitasyncio.to_thread(self.reserve_on_relay,relay_peer_id)
Runs reserve_on_relay in a worker thread (async). SessionManager.reserve calls it on behalf of NodeConn.reserve and the caller catches the P2PError.
The current addresses of the host as a list[str]. Each address ends with /p2p/<peer ID>. Every access asks the library for the list. The library updates it as the host learns new addresses. An error gives [] and a warning.
Whether the host is publicly reachable (bool). Every access calls get_reachability. A host created with knows_is_public=True is always public. Any other host reports the latest verdict of the probes.
Whether the secure listener of the host has a custom or automatic certificate (bool). A browser can reach a world through its relay only on a secure address (see Networking).
defget_node_addresses(self,peer_id:str="")->list[str]:""" Gets the known multiaddresses for the local node or a specific peer. Args: peer_id: The Peer ID string of the target peer. If empty, gets addresses for the local node. Returns: A list of multiaddress strings (including the /p2p/PeerID suffix). Raises: P2PError: If fetching addresses fails. """target="local node"ifnotpeer_idelsef"peer {peer_id}"logger.info(f"ℹ️ Fetching addresses for {target}...")try:result_ptr=P2P.libp2p.GetNodeAddresses(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_string(peer_id))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to get node addresses, received null result.")raiseP2PError("Failed to get node addresses, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to get addresses for '{target}': {result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to get addresses for '{target}': {result.get('message','Unknown Go error')}")addr_list=result.get('message',[])logger.info(f"✅ Found addresses for {target}: {addr_list}")returnaddr_listexceptExceptionase:logger.error(f"❌ Failed to get addresses for {target}: {e}")raiseP2PError(f"Failed to get addresses for {target}")frome
Returns the addresses that the library knows for the host (peer_id="", the default) or for another peer. Each address ends with /p2p/<peer ID>. Raises P2PError when the call fails.
defget_reachability(self)->bool:"""Reads the current AutoNAT reachability from the Go engine (O(1), event-cached) and updates the cached ``_is_public``. Returns the last known value on FFI error rather than raising, since callers treat reachability as best-effort telemetry."""try:result_ptr=P2P.libp2p.GetReachability(P2P._type_interface.to_go_int(self._instance))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNoneorresult.get('state')=="Error":msg=result.get('message','null result')ifresultisnotNoneelse'null result'logger.warning(f"Failed to read reachability: {msg}. Using last known value.")returnbool(self._is_public)self._is_public=bool(result.get('message',False))returnself._is_publicexceptExceptionase:logger.warning(f"Failed to read reachability: {e}. Using last known value.")returnbool(self._is_public)
Reads the current reachability verdict from the library, stores it and returns it (bool). On an error it logs a warning and returns the last stored value.
defget_webrtc_connections(self)->list[dict[str,Any]]:""" Returns the list of peers that currently have an active WebRTC DataChannel connection with this node. Each entry is a dict with keys ``peer_id`` (str) and ``state`` (str, ``"open"`` or ``"other"``). Raises: P2PError: If the Go call fails. """try:result_ptr=P2P.libp2p.GetWebRTCConnections(P2P._type_interface.to_go_int(self._instance),)result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:raiseP2PError("Null result from GetWebRTCConnections.")ifresult.get('state')=="Error":raiseP2PError(f"GetWebRTCConnections failed: "f"{result.get('message','Unknown Go error')}")returnresult.get('message',[])exceptExceptionase:logger.error(f"❌ GetWebRTCConnections failed: {e}")raiseP2PError("GetWebRTCConnections failed")frome
Returns the peers connected to the host through the browser transport. Each entry is a dict with "peer_id" and "state" ("open" or "other"). Raises P2PError when the call fails. Nothing in the SDK calls it.
defset_turn_credentials(self,ice_turn_servers:list[dict[str,Any]])->None:"""Updates the TURN servers of the ICE configuration (future WebRTC connections). Args: ice_turn_servers: The TURN server descriptions. """self.set_ice_config(ice_turn_servers=ice_turn_servers)
Replaces the relay servers of the browser transport with ice_turn_servers (a list of dicts with "urls", "username" and "credential"). It is equivalent to set_ice_config(ice_turn_servers=...). The node calls it through NodeConn.set_turn_credentials on both instances when it receives fresh credentials.
defset_ice_config(self,ice_stun_servers:list[str]|None=None,ice_turn_servers:list[dict[str,Any]]|None=None)->None:"""Update STUN/TURN servers used for *future* WebRTC connections. Existing PeerConnections keep their captured ICE config; each newly constructed PC reads the updated values. Safe to call from any thread. Pass ``None`` for a field to leave it unchanged on the Go side; pass ``[]`` to explicitly clear it. Typical usage rotates only TURN creds while leaving STUN alone. Args: ice_stun_servers: STUN URIs, or ``None`` to keep existing STUN list. ice_turn_servers: TURN dicts (urls/username/credential), or ``None`` to keep existing TURN list. """cfg:dict[str,Any]={}ifice_stun_serversisnotNone:cfg["stun_servers"]=ice_stun_serversifice_turn_serversisnotNone:cfg["turn_servers"]=ice_turn_serversifnotcfg:return# nothing to update — no round-tripresult_ptr=P2P.libp2p.UpdateICEConfig(P2P._type_interface.to_go_int(self._instance),P2P._type_interface.to_go_json(cfg),)result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNoneorresult.get('state')=="Error":msg:str=result.get('message','unknown error')ifresultelse'null result'raiseP2PError(f"[Instance {self._instance}] set_ice_config failed: {msg}")
Updates the address-discovery servers and the relay servers of the browser transport. The new values apply to the connections opened afterwards. Open connections keep the configuration they started with.
Argument
Type
Default
Meaning
ice_stun_servers
list[str] \| None
None
Server URIs. None leaves the list unchanged and [] empties it.
ice_turn_servers
list[dict] \| None
None
Relay servers. None leaves the list unchanged and [] empties it.
With both arguments None the method returns without calling the library. Raises P2PError when the library refuses the update. It can be called from any thread.
defget_connected_peers_info(self)->list[dict[str,Any]]|None:""" Gets information about currently connected peers from the Go library. Returns: On success, a (possibly empty) list of dictionaries, each representing a connected peer with keys like 'addr_info' (containing 'ID', 'Addrs'), 'connected_at', 'direction', and 'misc'. A real empty list means "zero peers". ``None`` on an FFI-LEVEL failure — a Go panic reported as ``state == "Error"``, a NULL/unparseable result pointer, or a marshalling exception — so such a transient is not read as "zero peers": the reconcile skips the diff on None (leaving the pools intact) instead of tearing every peer down. Note this does NOT cover a Go "instance not ready", which Go reports as a successful empty list (read here as a genuine zero-peers), not as an error. """# Logger.info("ℹ️ Fetching connected peers info...") # Can be noisytry:# GetConnectedPeers takes no arguments in Goresult_ptr=P2P.libp2p.GetConnectedPeers(P2P._type_interface.to_go_int(self._instance))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to get connected peers, received null result.")returnNoneifresult.get('state')=="Error":logger.error(f"Failed to get connected peers: {result.get('message','Unknown Go error')}")returnNone# A successful call returns the real list (empty means genuinely zero peers).returnresult.get('message',[])exceptExceptionase:# Avoid crashing the polling thread, just log the errorlogger.error(f"❌ Error fetching connected peers info: {e}")# None (not []) so the caller distinguishes "FFI errored" from "zero peers".returnNone
Returns the peers connected to the host as a list of dicts. SessionManager.connected_peers_info calls it at every update of the pools.
Each dict has "id" (the peer ID), "addrs" (its addresses), "connected_at", "direction" ("inbound" or "outbound"), "misc" (an integer for the role bits, filled by NodeConn) and "relayed". An empty list means that no peer is connected. A failure of the call returns None instead. The caller then skips the update and keeps its pools as they are instead of reading the failure as zero peers. A host that is not ready yet reports an empty list.
defget_topic_peers(self)->list[str]:""" Gets the peer IDs subscribed to any of this instance's topics (the de-duplicated union of topic.ListPeers()). Each is a peer we are DIRECTLY connected to that announced a subscription: the pubsub router intersects its connected-peer set with the topic subscribers, so a peer we are not connected to never appears. These are exactly the peers that receive this instance's broadcasts; the world perimeter uses them to cut the pubsub-only peers that open no stream and so never surface in get_connected_peers_info. A relay does not subscribe, so it never appears here. Returns: A list of peer-id strings, empty on error so that a transient FFI failure never triggers a spurious perimeter cut. """try:result_ptr=P2P.libp2p.GetTopicPeers(P2P._type_interface.to_go_int(self._instance))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to get topic peers, received null result.")raiseP2PError("Failed to get topic peers, received null result.")ifresult.get('state')=="Error":logger.error(f"Failed to get topic peers: {result.get('message','Unknown Go error')}")raiseP2PError(f"Failed to get topic peers: {result.get('message','Unknown Go error')}")returnresult.get('message',[])exceptExceptionase:# Avoid crashing the polling loop; empty means "cut nobody" (fail-safe).logger.error(f"❌ Error fetching topic peers: {e}")return[]
Returns the peer IDs subscribed to any topic of the host (list[str], without duplicates). Only directly connected peers appear and a relay never does. These are the peers that receive the broadcasts of the host. The world perimeter uses them to find peers that only listen to topics and never open a stream. An error returns [] so that a failure never causes a cut.
defget_rendezvous_peers_info(self)->dict[str,Any]|None:""" Gets the full rendezvous state from the Go library, including peers and metadata. Returns: - A dictionary representing the RendezvousState (containing 'peers', 'update_count', 'last_updated') if an update has been received. - None if no rendezvous topic is active or no updates have arrived yet. Raises: P2PError: If fetching the state fails in Go. """try:result_ptr=P2P.libp2p.GetRendezvousPeers(P2P._type_interface.to_go_int(self._instance))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Failed to get rendezvous peers, received null result.")raiseP2PError("Failed to get rendezvous peers, received null result.")state=result.get('state')ifstate=="Empty":logger.debug(f"[Instance {self._instance}] GetRendezvousPeers: No rendezvous messages received yet.")returnNone# Return None for the "empty" stateelifstate=="Error":error_msg=result.get('message','Unknown Go error')logger.error(f"Failed to get rendezvous peers: {error_msg}")raiseP2PError(f"Failed to get rendezvous peers: {error_msg}")elifstate=="Success":# The message payload is the full RendezvousState objectrendezvous_state=result.get('message',{})returnrendezvous_stateelse:logger.error(f"[Instance {self._instance}] GetRendezvousPeers: Received invalid state '{state}'.")raiseP2PError(f"[Instance {self._instance}] GetRendezvousPeers: Received invalid state.")exceptExceptionase:# Avoid crashing the polling thread, just log the errorlogger.error(f"❌ Error fetching rendezvous peers info: {e}")# Return None (not []) on error: the rest of this method uses None for# "no data yet", and callers branch on `is None`.returnNone
Returns the latest roster that the host read on the rendezvous topic of its world (or None when there is none). SessionManager.rendezvous_peers calls it for NodeConn.set_world_agents_and_world_masters_lists_from_rendezvous.
The roster is a dict with "peers" (a list of peer dicts with the keys of get_connected_peers_info) and "update_count" (an int that grows with every publication of the world). The method returns None when no roster has arrived yet and when the call fails. Only the world network joins a rendezvous topic.
defclose(self,close_all:bool=False)->None|str:""" Shuts down this instance's libp2p host via the Go CloseNode, freeing its slot (there are no Python-side background threads to stop). Closing the host abortively tears every remaining connection, so callers must drain their farewells first (see NodeConn.drain_teardown). Blocking FFI: the shutdown path calls it after the main loop has ended. Args: close_all: If True, closes ALL instances in the process (Go slot -1), not just this one. Default is False. """logger.info("🛑 Closing node...")try:ifclose_all:result_ptr=P2P.libp2p.CloseNode(P2P._type_interface.to_go_int(-1))else:result_ptr=P2P.libp2p.CloseNode(P2P._type_interface.to_go_int(self._instance))result=P2P._type_interface.from_go_ptr_to_json(result_ptr)ifresultisNone:logger.error("Node closure failed: received null result.")raiseP2PError("Node closure failed: received null result.")ifresult.get('state')=="Error":logger.error(f"Node closure failed: {result.get('message','Unknown Go error')}")raiseP2PError(f"Node closure failed: {result.get('message','Unknown Go error')}")close_msg=(f"Node closed successfully "f"({'all instances'ifclose_allelsef'instance {str(self._instance)}'}).")logger.info(f"✅ {close_msg}")exceptExceptionase:logger.error(f"❌ Error closing node: {e}")raiseP2PError(f"Error closing node: {e}")fromefinally:# 4. Clear internal stateself._peer_id=NonewithP2P._instance_lock:ifclose_all:# Also apply the lock here and use the corrected logicP2P._instance_ids=[False]*P2P._MAX_INSTANCESlogger.info("🐍 All instance slots have been marked as free.")else:ifself._instance!=-1:# Ensure instance was setP2P._instance_ids[self._instance]=Falselogger.info(f"🐍 Instance slot {self._instance} has been marked as free.")logger.info("🐍 Python P2P object state cleared.")returnclose_msg
Shuts the host down and frees its slot. Closing the host resets every open connection. NodeConn.close_transports therefore calls it at shutdown only after the farewells of the Sessions have completed (see NodeConn.drain_teardown).
Argument
Type
Default
Meaning
close_all
bool
False
Closes every host of the process and frees every slot.
Returns a confirmation string. Raises P2PError when the library fails to close. The peer ID becomes None and the slot is freed in both cases.