o
    jh                 	   @   s  d dl mZmZ d dlmZmZmZmZmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZmZmZ d dlmZ d dlZd d	lmZ d d
lmZmZmZ d dlmZmZm Z m!Z!m"Z" d dl#m$Z$ d dl%m&Z&m'Z' d dl(m)Z) d dl*m+  m,  m-Z, d dl.m/Z/ erd dl0m1Z1 d dl2m3Z3 d dl4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z= G dd de'Z>	 G dd deZ?G dd de?e>Z@G dd deZAG dd  d e'ed  ZBG d!d" d"e'ZCG d#d$ d$e&ZDG d%d& d&eZEG d'd( d(eZFG d)d* d*eZGG d+d, d,eZHG d-d. d.eZIG d/d0 d0eZJG d1d2 d2eEeFeGeHeIeJZKG d3d4 d4eZLG d5d6 d6eZMeG d7d8 d8ZNG d9d: d:eMe=ZOG d;d< d<eZPG d=d> d>eZQG d?d@ d@eZRG dAdB dBeZSG dCdD dDeZTG dEdF dFeZUG dGdH dHeZVG dIdJ dJeZWG dKdL dLeZXG dMdN dNeZYG dOdP dPeZZG dQdR dReZ[G dSdT dTedT ee;j\ Z]G dUdV dVeZ^G dWdX dXe=Z_G dYdZ dZeZ`dS )[    )ABCabstractmethod)AsyncIterableAsyncIteratorIterableKeysViewSequence)AbstractAsyncContextManager)	dataclass)TracebackType)TYPE_CHECKINGAnyAsyncContextManagerOptional)	MultiaddrN)ConnectionType)KeyPair
PrivateKey	PublicKey)MetadataValueStreamHandlerFnTHandler	TProtocolValidatorFn)EventBus)CloserReadWriteCloser)ID)PeerInfo)TagStore)Envelope)
PeerRecord)Multiselect)Pubsub)rpc_pb2)
ServiceAPIc                   @   sB   e Zd ZU dZeed< edee fddZ	ede
fddZdS )	IRawConnectionz
    Interface for a raw connection.

    This interface provides a basic reader/writer connection abstraction.

    Attributes
    ----------
    is_initiator (bool):
        True if the local endpoint initiated
        the connection.

    is_initiatorreturnc                 C      dS )z
        Get the actual transport addresses used by this connection.

        Returns the real IP/port addresses, not peerstore addresses.
        For relayed connections, should include /p2p-circuit in the path.
        N selfr*   r*   -/Users/sumanjeet/code/py-libp2p/libp2p/abc.pyget_transport_addressesZ   s   z&IRawConnection.get_transport_addressesc                 C   r)   zD
        Get the type of connection (direct, relayed, etc.)
        Nr*   r+   r*   r*   r-   get_connection_typed      z"IRawConnection.get_connection_typeN)__name__
__module____qualname____doc__bool__annotations__r   listr   r.   r   r0   r*   r*   r*   r-   r&   J   s   
 	r&   c                   @   sX   e Zd ZdZedefddZedefddZedefddZ	ede
fd	d
ZdS )AbstractSecureConnz
    Abstract interface for secure connections.

    Represents a secured connection object, including details about the
    security involved in the connection.

    r(   c                 C   r)   )z\
        Retrieve the local peer's identifier.

        :return: The local peer ID.
        Nr*   r+   r*   r*   r-   get_local_peer}       z!AbstractSecureConn.get_local_peerc                 C   r)   )zm
        Retrieve the local peer's private key.

        :return: The private key of the local peer.
        Nr*   r+   r*   r*   r-   get_local_private_key   r;   z(AbstractSecureConn.get_local_private_keyc                 C   r)   )z^
        Retrieve the remote peer's identifier.

        :return: The remote peer ID.
        Nr*   r+   r*   r*   r-   get_remote_peer   r;   z"AbstractSecureConn.get_remote_peerc                 C   r)   )zm
        Retrieve the remote peer's public key.

        :return: The public key of the remote peer.
        Nr*   r+   r*   r*   r-   get_remote_public_key   r;   z(AbstractSecureConn.get_remote_public_keyN)r2   r3   r4   r5   r   r   r:   r   r<   r=   r   r>   r*   r*   r*   r-   r9   t   s    r9   c                   @   s   e Zd ZdZdS )ISecureConnzv
    Interface for a secure connection.

    Combines secure connection functionalities with raw I/O operations.

    N)r2   r3   r4   r5   r*   r*   r*   r-   r?      s    r?   c                   @   s   e Zd ZU dZeed< ejed< ede	deddfddZ
eedefd	d
ZedddZedddZeedefddZeedefddZedddZedddZedee fddZedefddZdS )
IMuxedConnaS  
    Interface for a multiplexed connection.

    References
    ----------
    https://github.com/libp2p/go-stream-muxer/blob/master/muxer.go

    Attributes
    ----------
    peer_id (ID):
        The identifier of the connected peer.
    event_started (trio.Event):
        An event that signals when the multiplexer has started.

    peer_idevent_startedconnr(   Nc                 C   r)   )z
        Initialize a new multiplexed connection.

        :param conn: An instance of a secure connection used for new
            multiplexed streams.
        :param peer_id: The peer ID associated with the connection.
        Nr*   r,   rC   rA   r*   r*   r-   __init__   r;   zIMuxedConn.__init__c                 C   r)   )z
        Determine if this connection is the initiator.

        :return: True if this connection initiated the connection,
            otherwise False.
        Nr*   r+   r*   r*   r-   r'      r;   zIMuxedConn.is_initiatorc                       dS )z)
        Start the multiplexer.

        Nr*   r+   r*   r*   r-   start       zIMuxedConn.startc                    rF   )z4
        Close the multiplexed connection.

        Nr*   r+   r*   r*   r-   close   rH   zIMuxedConn.closec                 C   r)   )z
        Check if the connection is fully established and ready for streams.

        :return: True if the connection is established, otherwise False.
        Nr*   r+   r*   r*   r-   is_established   r;   zIMuxedConn.is_establishedc                 C   r)   z
        Check if the connection is fully closed.

        :return: True if the connection is closed, otherwise False.
        Nr*   r+   r*   r*   r-   	is_closed   r;   zIMuxedConn.is_closedIMuxedStreamc                    rF   )zm
        Create and open a new multiplexed stream.

        :return: A new instance of IMuxedStream.
        Nr*   r+   r*   r*   r-   open_stream   rH   zIMuxedConn.open_streamc                    rF   )z
        Accept a new multiplexed stream initiated by the remote peer.

        :return: A new instance of IMuxedStream.
        Nr*   r+   r*   r*   r-   accept_stream   rH   zIMuxedConn.accept_streamc                 C   r)   )zH
        Get transport addresses by delegating to secured_conn.
        Nr*   r+   r*   r*   r-   r.     r1   z"IMuxedConn.get_transport_addressesc                 C   r)   )zD
        Get connection type by delegating to secured_conn.
        Nr*   r+   r*   r*   r-   r0     r1   zIMuxedConn.get_connection_typer(   Nr(   rM   )r2   r3   r4   r5   r   r7   trioEventr   r?   rE   propertyr6   r'   rG   rI   rJ   rL   rN   rO   r8   r   r.   r   r0   r*   r*   r*   r-   r@      sB   
 
r@   c                   @   sv   e Zd ZU dZeed< edddZededdfdd	Z	edd
dZ
dee dB dedB dedB ddfddZdS )rM   z
    Interface for a multiplexed stream.

    Represents a stream multiplexed over a single connection.

    Attributes
    ----------
    muxed_conn (IMuxedConn):
        The underlying multiplexed connection.

    
muxed_connr(   Nc                    rF   )z
        Reset the stream.

        This method closes both ends of the stream, instructing the remote
        side to hang up.
        Nr*   r+   r*   r*   r-   reset$  rH   zIMuxedStream.resetttlc                 C   r)   )z
        Set a deadline for the stream.

        :param ttl: Time-to-live for the stream in seconds.
        :raises ValueError: if ttl is invalid (e.g. negative).
        Nr*   r,   rW   r*   r*   r-   set_deadline-  r;   zIMuxedStream.set_deadlinec                    s   | S )z Enter the async context manager.r*   r+   r*   r*   r-   
__aenter__6     zIMuxedStream.__aenter__exc_typeexc_valexc_tbc                    s   |   I dH  dS )z4Exit the async context manager and close the stream.N)rI   )r,   r\   r]   r^   r*   r*   r-   	__aexit__;  s   zIMuxedStream.__aexit__rP   rQ   )r2   r3   r4   r5   r@   r7   r   rV   intrY   rZ   typeBaseExceptionr   r_   r*   r*   r*   r-   rM     s$   
 
rM   c                   @   sf   e Zd ZU dZeed< eje dB ed< e	de
dB fddZe	de
ddfd	d
Ze	dddZdS )
INetStreamz
    Interface for a network stream.

    Represents a network stream operating over a multiplexed connection.

    Attributes
    ----------
    muxed_conn (IMuxedConn):
        The multiplexed connection that this stream belongs to.

    rU   Nmetric_send_channelr(   c                 C   r)   )z
        Retrieve the protocol identifier for the stream.

        :return: The protocol ID associated with the stream.
        Nr*   r+   r*   r*   r-   get_protocolX  r;   zINetStream.get_protocolprotocol_idc                 C   r)   )z
        Set the protocol identifier for the stream.

        :param protocol_id: The protocol ID to assign to the stream.
        Nr*   r,   rf   r*   r*   r-   set_protocol`  r;   zINetStream.set_protocolc                    rF   )z`
        Reset the network stream.

        This method closes both ends of the stream.
        Nr*   r+   r*   r*   r-   rV   h  rH   zINetStream.resetrP   )r2   r3   r4   r5   r@   r7   rR   MemorySendChannelr   r   r   re   rh   rV   r*   r*   r*   r-   rc   H  s   
 rc   c                   @   s   e Zd ZU dZeed< ejed< ee	de
fddZe	defddZe	deed	f fd
dZe	dee fddZe	defddZdS )INetConna>  
    Interface for a network connection.

    Defines a network connection capable of creating and managing streams.

    Attributes
    ----------
    muxed_conn (IMuxedConn):
        The underlying multiplexed connection.
    event_started (trio.Event):
        Event signaling when the connection has started.

    rU   rB   r(   c                 C   r)   rK   r*   r+   r*   r*   r-   rL     r;   zINetConn.is_closedc                    rF   )zr
        Create a new network stream over the connection.

        :return: A new instance of INetStream.
        Nr*   r+   r*   r*   r-   
new_stream  rH   zINetConn.new_stream.c                 C   r)   )z
        Retrieve all active streams associated with this connection.

        :return: A tuple containing instances of INetStream.
        Nr*   r+   r*   r*   r-   get_streams  r;   zINetConn.get_streamsc                 C   r)   )a$  
        Retrieve the actual transport addresses used by this connection.

        Returns the real IP/port addresses, not peerstore addresses.
        For relayed connections, should include /p2p-circuit in the path.

        :return: A list of multiaddresses used by the transport.
        Nr*   r+   r*   r*   r-   r.     r;   z INetConn.get_transport_addressesc                 C   r)   r/   r*   r+   r*   r*   r-   r0     r1   zINetConn.get_connection_typeN)r2   r3   r4   r5   r@   r7   rR   rS   rT   r   r6   rL   rc   rk   tuplerl   r8   r   r.   r   r0   r*   r*   r*   r-   rj   t  s   
 

rj   c                	   @   s^   e Zd ZdZedededefddZededededdfd	d
Z	ededdfddZ
dS )IPeerMetadataz
    Interface for managing peer metadata.

    Provides methods for storing and retrieving metadata associated with peers.
    rA   keyr(   c                 C   r)   )a  
        Retrieve metadata for a specified peer.

        :param peer_id: The ID of the peer.
        :param key: The key for the metadata to retrieve.
        :return: The metadata value associated with the key.
        :raises Exception: If the peer ID is not found.
        Nr*   r,   rA   ro   r*   r*   r-   get  r;   zIPeerMetadata.getvalNc                 C   r)   )z
        Store metadata for a specified peer.

        :param peer_id: The ID of the peer.
        :param key: The key for the metadata.
        :param val: The value to store.
        :raises Exception: If the operation is unsuccessful.
        Nr*   r,   rA   ro   rr   r*   r*   r-   put  r;   zIPeerMetadata.putc                 C   r)   )z
        Remove all stored metadata for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose metadata are to be removed.

        Nr*   r,   rA   r*   r*   r-   clear_metadata  r;   zIPeerMetadata.clear_metadata)r2   r3   r4   r5   r   r   strr   rq   rt   rv   r*   r*   r*   r-   rn     s    

rn   c                	   @   s   e Zd ZdZededededdfddZeded	e	e deddfd
dZ
ededee fddZededdfddZedee fddZdS )	IAddrBookz[
    Interface for an address book.

    Provides methods for managing peer addresses.
    rA   addrrW   r(   Nc                 C   r)   )a  
        Add a single address for a given peer.

        This method calls ``add_addrs(peer_id, [addr], ttl)``.

        Parameters
        ----------
        peer_id : ID
            The peer identifier for which to add the address.
        addr : Multiaddr
            The multiaddress of the peer.
        ttl : int
            The time-to-live for the address, after which it is no longer valid.

        Nr*   r,   rA   ry   rW   r*   r*   r-   add_addr  r;   zIAddrBook.add_addraddrsc                 C   r)   )aE  
        Add multiple addresses for a given peer, all with the same TTL.

        If an address already exists with a longer TTL, no action should be taken.
        If an address exists with a shorter TTL, its TTL should be extended to match
        the provided TTL.

        Parameters
        ----------
        peer_id : ID
            The peer identifier for which to add addresses.
        addrs : Sequence[Multiaddr]
            A sequence of multiaddresses to add.
        ttl : int
            The time-to-live for the addresses, after which they become invalid.

        Nr*   r,   rA   r|   rW   r*   r*   r-   	add_addrs  r;   zIAddrBook.add_addrsc                 C   r)   )aD  
        Retrieve all known and valid addresses for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose addresses are requested.

        Returns
        -------
        list[Multiaddr]
            A list of valid multiaddresses for the given peer.

        Nr*   ru   r*   r*   r-   r|     r;   zIAddrBook.addrsc                 C   r)   )z
        Remove all stored addresses for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose addresses are to be removed.

        Nr*   ru   r*   r*   r-   clear_addrs   r;   zIAddrBook.clear_addrsc                 C   r)   )z
        Retrieve all peer identifiers that have stored addresses.

        Returns
        -------
        list[ID]
            A list of peer IDs with stored addresses.

        Nr*   r+   r*   r*   r-   peers_with_addrs,  r;   zIAddrBook.peers_with_addrs)r2   r3   r4   r5   r   r   r   r`   r{   r   r~   r8   r|   r   r   r*   r*   r*   r-   rx     s     rx   c                   @   sZ   e Zd ZdZedddedefddZedede	d fd	d
Z
ededdfddZdS )ICertifiedAddrBookzh
    Interface for a certified address book.

    Provides methods for managing signed peer records
    enveloper    rW   r(   c                 C   r)   )a!  
        Accept and store a signed PeerRecord, unless it's older than
        the one already stored.

        This function:
        - Extracts the peer ID and sequence number from the envelope
        - Rejects the record if it's older (lower seq)
        - Updates the stored peer record and replaces associated
        addresses if accepted


        Parameters
        ----------
        envelope:
            Signed envelope containing a PeerRecord.
        ttl:
            Time-to-live for the included multiaddrs (in seconds).

        Nr*   r,   r   rW   r*   r*   r-   consume_peer_recordA  r;   z&ICertifiedAddrBook.consume_peer_recordrA   c                 C   r)   a  
        Retrieve the most recent signed PeerRecord `Envelope` for a peer, if it exists
        and is still relevant.

        First, it runs cleanup via `maybe_delete_peer_record` to purge stale data.
        Then it checks whether the peer has valid, unexpired addresses before
        returning the associated envelope.


        Parameters
        ----------
        peer_id : ID
            The peer to look up.

        Nr*   ru   r*   r*   r-   get_peer_recordW  r;   z"ICertifiedAddrBook.get_peer_recordNc                 C   r)   )a  
        Delete the signed peer record for a peer if it has no know
        (non-expired) addresses.

        This is a garbage collection mechanism: if all addresses for a peer have expired
        or been cleared, there's no point holding onto its signed `Envelope`

        Parameters
        ----------
        peer_id : ID
            The peer whose record we may delete.

        Nr*   ru   r*   r*   r-   maybe_delete_peer_recordi  r;   z+ICertifiedAddrBook.maybe_delete_peer_record)r2   r3   r4   r5   r   r`   r6   r   r   r   r   r   r*   r*   r*   r-   r   :  s    r   c                   @   s   e Zd ZdZededefddZededefddZ	edededd	fd
dZ
edededd	fddZedededd	fddZedee fddZededd	fddZd	S )IKeyBookz[
    Interface for an key book.

    Provides methods for managing cryptographic keys.
    rA   r(   c                 C   r)   )z
        Returns the public key of the specified peer

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose public key is to be returned.

        Nr*   ru   r*   r*   r-   pubkey  r;   zIKeyBook.pubkeyc                 C   r)   )z
        Returns the private key of the specified peer

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose private key is to be returned.

        Nr*   ru   r*   r*   r-   privkey  r;   zIKeyBook.privkeyr   Nc                 C   r)   )z
        Adds the public key for a specified peer

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose public key is to be added
        pubkey: PublicKey
            The public key of the peer

        Nr*   r,   rA   r   r*   r*   r-   
add_pubkey  r;   zIKeyBook.add_pubkeyr   c                 C   r)   )z
        Adds the private key for a specified peer

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose private key is to be added
        privkey: PrivateKey
            The private key of the peer

        Nr*   r,   rA   r   r*   r*   r-   add_privkey  r;   zIKeyBook.add_privkeykey_pairc                 C   r)   )z
        Adds the key pair for a specified peer

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose key pair is to be added
        key_pair: KeyPair
            The key pair of the peer

        Nr*   r,   rA   r   r*   r*   r-   add_key_pair  r;   zIKeyBook.add_key_pairc                 C   r)   z/Returns all the peer IDs stored in the AddrBookNr*   r+   r*   r*   r-   peer_with_keys  r;   zIKeyBook.peer_with_keysc                 C   r)   z
        Remove all stored keydata for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The peer identifier whose keys are to be removed.

        Nr*   ru   r*   r*   r-   clear_keydata  r;   zIKeyBook.clear_keydata)r2   r3   r4   r5   r   r   r   r   r   r   r   r   r   r   r8   r   r   r*   r*   r*   r-   r   }  s     r   c                   @   sV   e Zd ZdZedededdfddZededefdd	Zededdfd
dZ	dS )IMetricszd
    Interface for metrics of peer interaction.

    Provides methods for managing the metrics.
    rA   RTTr(   Nc                 C   r)   am  
        Records a new round-trip time (RTT) latency value for the specified peer
        using Exponentially Weighted Moving Average (EWMA).

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer for which latency is being recorded.

        RTT : float
            The round-trip time latency value to record.

        Nr*   r,   rA   r   r*   r*   r-   record_latency  r;   zIMetrics.record_latencyc                 C   r)   a  
        Returns the current latency value for the specified peer using
        Exponentially Weighted Moving Average (EWMA).

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer whose latency EWMA is to be returned.

        Nr*   ru   r*   r*   r-   latency_EWMA  r;   zIMetrics.latency_EWMAc                 C   r)   z
        Clears the stored latency metrics for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer whose latency metrics are to be cleared.

        Nr*   ru   r*   r*   r-   clear_metrics  r;   zIMetrics.clear_metrics)
r2   r3   r4   r5   r   r   floatr   r   r   r*   r*   r*   r-   r     s    r   c                   @   s   e Zd ZdZededee fddZedede	e ddfdd	Z
edede	e ddfd
dZedede	e ddfddZedede	e dee fddZedede	e defddZededdfddZdS )
IProtoBookzl
    Interface for a protocol book.

    Provides methods for managing the list of supported protocols.
    rA   r(   c                 C   r)   )z
        Returns the list of protocols associated with the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer whose supported protocols are to be returned.

        Nr*   ru   r*   r*   r-   get_protocols  r;   zIProtoBook.get_protocols	protocolsNc                 C   r)   )a-  
        Adds the given protocols to the specified peer's protocol list.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to which protocols will be added.

        protocols : Sequence[str]
            A sequence of protocol strings to add.

        Nr*   r,   rA   r   r*   r*   r-   add_protocols!  r;   zIProtoBook.add_protocolsc                 C   r)   )a8  
        Replaces the existing protocols of the specified peer with the given list.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer whose protocols are to be set.

        protocols : Sequence[str]
            A sequence of protocol strings to assign.

        Nr*   r   r*   r*   r-   set_protocols0  r;   zIProtoBook.set_protocolsc                 C   r)   a3  
        Removes the specified protocols from the peer's protocol list.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer from which protocols will be removed.

        protocols : Sequence[str]
            A sequence of protocol strings to remove.

        Nr*   r   r*   r*   r-   remove_protocols?  r;   zIProtoBook.remove_protocolsc                 C   r)   am  
        Returns the list of protocols from the input sequence that the peer supports.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to check for protocol support.

        protocols : Sequence[str]
            A sequence of protocol strings to check against the peer's
            supported protocols.

        Nr*   r   r*   r*   r-   supports_protocolsN  r;   zIProtoBook.supports_protocolsc                 C   r)   a  
        Returns the first protocol from the input list that the peer supports.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to check for supported protocols.

        protocols : Sequence[str]
            A sequence of protocol strings to check.

        Returns
        -------
        str
            The first matching protocol string, or an empty string
            if none are supported.

        Nr*   r   r*   r*   r-   first_supported_protocol^  r;   z#IProtoBook.first_supported_protocolc                 C   r)   z
        Clears all protocol data associated with the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer whose protocol data will be cleared.

        Nr*   ru   r*   r*   r-   clear_protocol_datas  r;   zIProtoBook.clear_protocol_data)r2   r3   r4   r5   r   r   r8   rw   r   r   r   r   r   r   r   r   r*   r*   r*   r-   r     s      r   c                	   @   sx  e Zd ZdZedededefddZededededdfd	d
Z	ededdfddZ
ededededdfddZededee deddfddZededee fddZededdfddZedee fddZeded fddZedYddZedddedefd d!Zededed fd"d#Zededdfd$d%Zededefd&d'Zededefd(d)Zeded*eddfd+d,Zeded-eddfd.d/Z eded0e!ddfd1d2Z"edee fd3d4Z#ededdfd5d6Z$eded7e%ddfd8d9Z&edede%fd:d;Z'ededdfd<d=Z(ededee fd>d?Z)eded@ee ddfdAdBZ*eded@ee ddfdCdDZ+eded@ee ddfdEdFZ,eded@ee dee fdGdHZ-eded@ee defdIdJZ.ededdfdKdLZ/edede0fdMdNZ1edee fdOdPZ2ededefdQdRZ3ededdfdSdTZ4edZdVeddfdWdXZ5dS )[
IPeerStorez
    Interface for a peer store.

    Provides methods for managing peer information including address
    management, protocol handling, and key storage.
    rA   ro   r(   c                 C   r)   )a  
        Retrieve the value associated with a key for a specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        key : str
            The key to look up.

        Returns
        -------
        MetadataValue
            The value corresponding to the specified key.

        Raises
        ------
        PeerStoreError
            If the peer ID or value is not found.

        Nr*   rp   r*   r*   r-   rq     r;   zIPeerStore.getrr   Nc                 C   r)   )a  
        Store a key-value pair for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        key : str
            The key for the data.
        val : MetadataValue
            The value to store.

        Nr*   rs   r*   r*   r-   rt     r;   zIPeerStore.putc                 C   r)   r   r*   ru   r*   r*   r-   rv     r;   zIPeerStore.clear_metadatary   rW   c                 C   r)   )a  
        Add an address for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        addr : Multiaddr
            The multiaddress to add.
        ttl : int
            The time-to-live for the record.

        Nr*   rz   r*   r*   r-   r{     r;   zIPeerStore.add_addrr|   c                 C   r)   )a9  
        Add multiple addresses for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        addrs : Sequence[Multiaddr]
            A sequence of multiaddresses to add.
        ttl : int
            The time-to-live for the record.

        Nr*   r}   r*   r*   r-   r~     r;   zIPeerStore.add_addrsc                 C   r)   )a  
        Retrieve the addresses for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.

        Returns
        -------
        list[Multiaddr]
            A list of multiaddresses.

        Nr*   ru   r*   r*   r-   r|     r;   zIPeerStore.addrsc                 C   r)   )z
        Clear all addresses for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.

        Nr*   ru   r*   r*   r-   r     r;   zIPeerStore.clear_addrsc                 C   r)   )z
        Retrieve all peer identifiers with stored addresses.

        Returns
        -------
        list[ID]
            A list of peer IDs.

        Nr*   r+   r*   r*   r-   r      r;   zIPeerStore.peers_with_addrsr    c                 C   r)   )z-Get the local-peer-record wrapped in EnvelopeNr*   r+   r*   r*   r-   get_local_record  r;   zIPeerStore.get_local_recordr   c                 C   r)   )z-Set the local-peer-record wrapped in EnvelopeNr*   )r,   r   r*   r*   r-   set_local_record  r;   zIPeerStore.set_local_recordc                 C   r)   )a  
        Accept and store a signed PeerRecord, unless it's older
        than the one already stored.

        This function:
        - Extracts the peer ID and sequence number from the envelope
        - Rejects the record if it's older (lower seq)
        - Updates the stored peer record and replaces associated addresses if accepted


        Parameters
        ----------
        envelope:
            Signed envelope containing a PeerRecord.
        ttl:
            Time-to-live for the included multiaddrs (in seconds).

        Nr*   r   r*   r*   r-   r     r;   zIPeerStore.consume_peer_recordc                 C   r)   r   r*   ru   r*   r*   r-   r   +  r;   zIPeerStore.get_peer_recordc                 C   r)   )a  
        Delete the signed peer record for a peer if it has no
        know (non-expired) addresses.

        This is a garbage collection mechanism: if all addresses for a peer have expired
        or been cleared, there's no point holding onto its signed `Envelope`

        Parameters
        ----------
        peer_id : ID
            The peer whose record we may delete.

        Nr*   ru   r*   r*   r-   r   =  r;   z#IPeerStore.maybe_delete_peer_recordc                 C   r)   )a`  
        Retrieve the public key for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.

        Returns
        -------
        PublicKey
            The public key of the peer.

        Raises
        ------
        PeerStoreError
            If the peer ID is not found.

        Nr*   ru   r*   r*   r-   r   O  r;   zIPeerStore.pubkeyc                 C   r)   )ac  
        Retrieve the private key for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.

        Returns
        -------
        PrivateKey
            The private key of the peer.

        Raises
        ------
        PeerStoreError
            If the peer ID is not found.

        Nr*   ru   r*   r*   r-   r   e  r;   zIPeerStore.privkeyr   c                 C   r)   )aI  
        Add a public key for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        pubkey : PublicKey
            The public key to add.

        Raises
        ------
        PeerStoreError
            If the peer already has a public key set.

        Nr*   r   r*   r*   r-   r   {  r;   zIPeerStore.add_pubkeyr   c                 C   r)   )aN  
        Add a private key for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        privkey : PrivateKey
            The private key to add.

        Raises
        ------
        PeerStoreError
            If the peer already has a private key set.

        Nr*   r   r*   r*   r-   r     r;   zIPeerStore.add_privkeyr   c                 C   r)   )aP  
        Add a key pair for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        key_pair : KeyPair
            The key pair to add.

        Raises
        ------
        PeerStoreError
            If the peer already has a public or private key set.

        Nr*   r   r*   r*   r-   r     r;   zIPeerStore.add_key_pairc                 C   r)   r   r*   r+   r*   r*   r-   r     r;   zIPeerStore.peer_with_keysc                 C   r)   r   r*   ru   r*   r*   r-   r     r;   zIPeerStore.clear_keydatar   c                 C   r)   r   r*   r   r*   r*   r-   r     r;   zIPeerStore.record_latencyc                 C   r)   r   r*   ru   r*   r*   r-   r     r;   zIPeerStore.latency_EWMAc                 C   r)   r   r*   ru   r*   r*   r-   r     r;   zIPeerStore.clear_metricsc                 C   r)   )ao  
        Retrieve the protocols associated with the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.

        Returns
        -------
        list[str]
            A list of protocol identifiers.

        Raises
        ------
        PeerStoreError
            If the peer ID is not found.

        Nr*   ru   r*   r*   r-   r     r;   zIPeerStore.get_protocolsr   c                 C   r)   )z
        Add additional protocols for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        protocols : Sequence[str]
            The protocols to add.

        Nr*   r   r*   r*   r-   r     r;   zIPeerStore.add_protocolsc                 C   r)   )z
        Set the protocols for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        protocols : Sequence[str]
            The protocols to set.

        Nr*   r   r*   r*   r-   r     r;   zIPeerStore.set_protocolsc                 C   r)   r   r*   r   r*   r*   r-   r   !  r;   zIPeerStore.remove_protocolsc                 C   r)   r   r*   r   r*   r*   r-   r   0  r;   zIPeerStore.supports_protocolsc                 C   r)   r   r*   r   r*   r*   r-   r   @  r;   z#IPeerStore.first_supported_protocolc                 C   r)   r   r*   ru   r*   r*   r-   r   U  r;   zIPeerStore.clear_protocol_datac                 C   r)   )a  
        Retrieve the peer information for the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.

        Returns
        -------
        PeerInfo
            The peer information object for the given peer.

        Nr*   ru   r*   r*   r-   	peer_infob  r;   zIPeerStore.peer_infoc                 C   r)   )z
        Retrieve all peer identifiers stored in the peer store.

        Returns
        -------
        list[ID]
            A list of all peer IDs in the store.

        Nr*   r+   r*   r*   r-   peer_idss  r;   zIPeerStore.peer_idsc                 C   r)   )a  
        Return True if ``peer_id`` is known to this store.

        This MUST be O(1)-ish (in-memory map / single key lookup) and MUST
        NOT materialize the full peer list: ``peer_ids()`` on persistent
        stores reconstructs and hashes every peer, which is far too
        expensive for hot paths (e.g. per-connection checks).

        Parameters
        ----------
        peer_id : ID
            The peer ID to check.

        Returns
        -------
        bool
            True if the peer is known to the store.

        Nr*   ru   r*   r*   r-   has_peer  r;   zIPeerStore.has_peerc                 C   r)   )clear_peerdataNr*   ru   r*   r*   r-   r     r;   zIPeerStore.clear_peerdata  cleanup_intervalc                    rF   )z=Start periodic cleanup of expired peer records and addresses.Nr*   )r,   r   r*   r*   r-   start_cleanup_task  rH   zIPeerStore.start_cleanup_task)r   r    r(   N)r   )6r2   r3   r4   r5   r   r   rw   r   rq   rt   rv   r   r`   r{   r   r~   r8   r|   r   r   r   r   r   r6   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r*   r*   r*   r-   r     s      r   c                   @   sN   e Zd ZdZededdfddZedeedf fdd	Zedd
dZ	dS )	IListenerz
    Interface for a network listener.

    Provides methods for starting a listener, retrieving its addresses,
    and closing it.
    maddrr(   Nc                    rF   )an  
        Start listening on the specified multiaddress.

        The listener manages its own background tasks internally and keeps
        them alive until :meth:`close` is called.  Callers do not need to
        supply a nursery.

        Parameters
        ----------
        maddr : Multiaddr
            The multiaddress on which to listen.

        Raises
        ------
        Exception
            Transport-specific listener exception, such as
            ``OpenConnectionError`` (TCP/WebSocket) or ``QUICListenError`` (QUIC),
            if listening fails (e.g. missing/invalid port or failed start).

        Nr*   r,   r   r*   r*   r-   listen  rH   zIListener.listen.c                 C   r)   )z
        Retrieve the list of addresses on which the listener is active.

        Returns
        -------
        tuple[Multiaddr, ...]
            A tuple of multiaddresses.

        Nr*   r+   r*   r*   r-   	get_addrs  r;   zIListener.get_addrsc                    rF   )z&
        Close the listener.

        Nr*   r+   r*   r*   r-   rI        zIListener.closerP   )
r2   r3   r4   r5   r   r   r   rm   r   rI   r*   r*   r*   r-   r     s    r   c                   @   sx  e Zd ZU dZeed< eeee	 f ed< ee
ef ed< edefddZed*d	edB dee	 fd
dZedeeee	 f fddZed	ede	dB fddZed	edee	 fddZed	edefddZeded	ede	fddZedededefddZededdfddZededefddZed+d"d#Zed+d$d%Zed,d&d'Zed	eddfd(d)Z dS )-INetworka  
    Interface for the network.

    Provides methods for managing connections, streams, and listeners.

    Attributes
    ----------
    peerstore : IPeerStore
        The peer store for managing peer information.
    connections : dict[ID, list[INetConn]]
        A mapping of peer IDs to lists of network connections
        (multiple connections per peer).
    listeners : dict[str, IListener]
        A mapping of listener identifiers to listener instances.

    	peerstoreZconnections	listenersr(   c                 C   r)   )z
        Retrieve the peer identifier for this network.

        Returns
        -------
        ID
            The identifier of this peer.

        Nr*   r+   r*   r*   r-   get_peer_id  r;   zINetwork.get_peer_idNrA   c                 C   r)   )a  
        Get connections for peer (like JS getConnections, Go ConnsToPeer).

        Parameters
        ----------
        peer_id : ID | None
            The peer ID to get connections for. If None, returns all connections.

        Returns
        -------
        list[INetConn]
            List of connections to the specified peer, or all connections
            if peer_id is None.

        Nr*   ru   r*   r*   r-   get_connections  r;   zINetwork.get_connectionsc                 C   r)   )z
        Get all connections map (like JS getConnectionsMap).

        Returns
        -------
        dict[ID, list[INetConn]]
            The complete mapping of peer IDs to their connection lists.

        Nr*   r+   r*   r*   r-   get_connections_map  r;   zINetwork.get_connections_mapc                 C   r)   )a7  
        Get single connection for backward compatibility.

        Parameters
        ----------
        peer_id : ID
            The peer ID to get a connection for.

        Returns
        -------
        INetConn | None
            The first available connection, or None if no connections exist.

        Nr*   ru   r*   r*   r-   get_connection  r;   zINetwork.get_connectionc                    rF   )a  
        Create connections to the specified peer with load balancing.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to dial.

        Returns
        -------
        list[INetConn]
            List of established connections to the peer.

        Raises
        ------
        SwarmException
            If an error occurs during dialing.

        Nr*   ru   r*   r*   r-   	dial_peer)  rH   zINetwork.dial_peerc                    rF   )a  
        Create a new network stream to the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the destination peer.

        Returns
        -------
        INetStream
            The newly created network stream.

        Nr*   ru   r*   r*   r-   rk   ?  rH   zINetwork.new_streamraw_connc                    rF   )a   
        Secure and upgrade a raw outbound connection to a multiplexed network connection

        Parameters
        ----------
        raw_conn : IRawConnection
            The raw connection to upgrade.
        peer_id : ID
            The peer to which this connection is established.

        Returns
        -------
        INetConn
            The upgraded, secure, and multiplexed network connection.

        Raises
        ------
        SwarmException
            If upgrading security or multiplexing the connection fails.

        Nr*   r,   r   rA   r*   r*   r-   upgrade_outbound_raw_connP  rH   z"INetwork.upgrade_outbound_raw_connr   c                    rF   )a4  
        Secure and upgrade a raw inbound connection to a multiplexed network connection

        Parameters
        ----------
        raw_conn : IRawConnection
            The incoming raw connection to upgrade.
        maddr : Multiaddr
            The multiaddress on which the connection was received.

        Returns
        -------
        IMuxedConn
            The upgraded, secure, and multiplexed network connection.

        Raises
        ------
        SwarmException
            If upgrading security or multiplexing the connection fails.

        Nr*   r,   r   r   r*   r*   r-   upgrade_inbound_raw_connj  rH   z!INetwork.upgrade_inbound_raw_connstream_handlerc                 C   r)   )z
        Set the stream handler for incoming streams.

        Parameters
        ----------
        stream_handler : StreamHandlerFn
            The handler function to process incoming streams.

        Nr*   )r,   r   r*   r*   r-   set_stream_handler  r;   zINetwork.set_stream_handler
multiaddrsc                    rF   )aT  
        Start listening on one or more multiaddresses.

        Parameters
        ----------
        multiaddrs : Sequence[Multiaddr]
            One or more multiaddresses on which to start listening.

        Returns
        -------
        bool
            True if at least one listener started successfully, otherwise False.

        Nr*   )r,   r   r*   r*   r-   r     rH   zINetwork.listennotifeeINotifeec                 C   r)   )z
        Register a notifee instance to receive network events.

        Parameters
        ----------
        notifee : INotifee
            An object implementing the INotifee interface.

        Nr*   r,   r   r*   r*   r-   register_notifee  r;   zINetwork.register_notifeec                 C   r)   )z
        Unregister a notifee instance so it stops receiving network events.

        Parameters
        ----------
        notifee : INotifee
            The notifee previously passed to ``register_notifee``.

        Nr*   r   r*   r*   r-   remove_notifee  r;   zINetwork.remove_notifeec                    rF   )zQ
        Close the network and all associated connections and listeners.
        Nr*   r+   r*   r*   r-   rI     rH   zINetwork.closec                    rF   )z
        Close the connection to the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer whose connection should be closed.

        Nr*   ru   r*   r*   r-   
close_peer  rH   zINetwork.close_peerN)r   r   r(   NrP   )!r2   r3   r4   r5   r   r7   dictr   r8   rj   rw   r   r   r   r   r   r   r   rc   rk   r&   r   r   r@   r   r   r   r6   r   r   r   rI   r   r*   r*   r*   r-   r     sZ   
 r   c                   @   s>   e Zd ZU dZeed< eed< eed< eed< edB ed< dS )CMInfou  
    Unified snapshot of connection manager state.

    Equivalent to go-libp2p's connmgr.CMInfo snapshot returned by
    BasicConnMgr.GetInfo() — providing a single call-site for all
    watermark / live-count / grace / last-trim data needed by
    operators and metrics exporters.

    Attributes
    ----------
    low_watermark : int
        Target connection count after pruning.
    high_watermark : int
        Connection count that triggers pruning.
    connected_count : int
        Current number of live connections.
    grace_period : float
        Seconds a new connection is exempt from pruning.
    last_trim : float | None
        Unix timestamp of the most recent prune cycle, or None if
        the connection count has never exceeded the high watermark.

    Zlow_watermarkZhigh_watermarkZconnected_countZgrace_periodNZ	last_trim)r2   r3   r4   r5   r`   r7   r   r*   r*   r*   r-   r     s   
 r   c                	   @   s   e Zd ZU dZeed< edefddZede	e
ef fddZeded	e
d
eddfddZeded	e
ddfddZededefddZeded	e
ddfddZeded	e
defddZedded	e
defddZedefddZdS )INetworkServicez
    Interface for a network service with connection management capabilities.

    Extends INetwork with go-libp2p style connection manager methods.
    Zconnection_gater(   c                 C   r)   )z
        Get total number of connections (inbound + outbound).

        Returns
        -------
        int
            Total number of active connections.

        Nr*   r+   r*   r*   r-   get_total_connections  r;   z%INetworkService.get_total_connectionsc                 C   r)   )z
        Get connection metrics (go-libp2p style).

        Returns
        -------
        dict[str, int]
            Connection metrics including total, inbound, and outbound counts.

        Nr*   r+   r*   r*   r-   get_metrics  r;   zINetworkService.get_metricsrA   tagvalueNc                 C   r)   )a  
        Tag a peer with a string, associating a weight with the tag.

        Parameters
        ----------
        peer_id : ID
            The peer to tag.
        tag : str
            The tag name.
        value : int
            The weight/value associated with the tag.

        Nr*   )r,   rA   r   r   r*   r*   r-   tag_peer  r;   zINetworkService.tag_peerc                 C   r)   )z
        Remove the tagged value from the peer.

        Parameters
        ----------
        peer_id : ID
            The peer to untag.
        tag : str
            The tag name to remove.

        Nr*   r,   rA   r   r*   r*   r-   
untag_peer  r;   zINetworkService.untag_peerc                 C   r)   )a  
        Get the metadata associated with a peer.

        Parameters
        ----------
        peer_id : ID
            The peer to get info for.

        Returns
        -------
        Any
            The tag info for the peer, or None if no tags recorded.

        Nr*   ru   r*   r*   r-   get_tag_info,  r;   zINetworkService.get_tag_infoc                 C   r)   )z
        Protect a peer from having its connection(s) pruned.

        Parameters
        ----------
        peer_id : ID
            The peer to protect.
        tag : str
            Protection tag.

        Nr*   r   r*   r*   r-   protect=  r;   zINetworkService.protectc                 C   r)   )aS  
        Remove a protection that may have been placed on a peer.

        Parameters
        ----------
        peer_id : ID
            The peer to unprotect.
        tag : str
            The protection tag to remove.

        Returns
        -------
        bool
            True if the peer is still protected by other tags.

        Nr*   r   r*   r*   r-   	unprotectK  r;   zINetworkService.unprotect c                 C   r)   )a8  
        Check if a peer is protected.

        Parameters
        ----------
        peer_id : ID
            The peer to check.
        tag : str
            If provided, check if protected by this specific tag.

        Returns
        -------
        bool
            True if the peer is protected.

        Nr*   r   r*   r*   r-   is_protected^  r;   zINetworkService.is_protectedc                 C   r)   )ur  
        Return a unified snapshot of connection manager state.

        Provides a single call-site for watermarks, live connection count,
        grace period, and the timestamp of the last prune — matching
        go-libp2p's BasicConnMgr.GetInfo().

        Returns
        -------
        CMInfo
            Snapshot of current connection manager state.

        Nr*   r+   r*   r*   r-   get_conn_mgr_infoq  r;   z!INetworkService.get_conn_mgr_info)r   )r2   r3   r4   r5   r   r7   r   r`   r   r   rw   r   r   r   r   r   r   r6   r   r   r   r   r*   r*   r*   r-   r     s*   
 r   c                   @   s   e Zd ZdZedddeddfddZedddeddfd	d
ZedddeddfddZ	edddeddfddZ
edddeddfddZedddeddfddZdS )r   z
    Interface for a network service.

    Extends the INetwork interface with additional service management
    capabilities.

    networkr   streamr(   Nc                    rF   )z
        Called when a new stream is opened.

        Parameters
        ----------
        network : INetwork
            The network instance on which the stream was opened.
        stream : INetStream
            The stream that was opened.

        Nr*   r,   r   r   r*   r*   r-   opened_stream  rH   zINotifee.opened_streamc                    rF   )z
        Called when a stream is closed.

        Parameters
        ----------
        network : INetwork
            The network instance on which the stream was closed.
        stream : INetStream
            The stream that was closed.

        Nr*   r   r*   r*   r-   closed_stream  rH   zINotifee.closed_streamrC   c                    rF   )a  
        Called when a new connection is established.

        Parameters
        ----------
        network : INetwork
            The network instance where the connection was established.
        conn : INetConn
            The connection that was opened.

        Nr*   r,   r   rC   r*   r*   r-   	connected  rH   zINotifee.connectedc                    rF   )z
        Called when a connection is closed.

        Parameters
        ----------
        network : INetwork
            The network instance where the connection was closed.
        conn : INetConn
            The connection that was closed.

        Nr*   r   r*   r*   r-   disconnected  rH   zINotifee.disconnected	multiaddrc                    rF   )a#  
        Called when a listener starts on a multiaddress.

        Parameters
        ----------
        network : INetwork
            The network instance where the listener is active.
        multiaddr : Multiaddr
            The multiaddress on which the listener is listening.

        Nr*   r,   r   r   r*   r*   r-   r     rH   zINotifee.listenc                    rF   )a.  
        Called when a listener stops listening on a multiaddress.

        Parameters
        ----------
        network : INetwork
            The network instance where the listener was active.
        multiaddr : Multiaddr
            The multiaddress that is no longer being listened on.

        Nr*   r   r*   r*   r-   listen_close  rH   zINotifee.listen_close)r2   r3   r4   r5   r   rc   r   r   rj   r   r   r   r   r   r*   r*   r*   r-   r     s    r   c                	   @   s  e Zd ZdZedefddZedefddZede	fddZ
edefd	d
Zed@ddZedee fddZedee fddZedefddZeedAddZedee fddZedee fddZeejddee deded fdd Zed!ed"eddfd#d$Z ed!eddfd%d&Z!edej"e dB fd'd(Z#edBd*d+Z$edCd,e%dB ddfd-d.Z&ed/ed0ee de'fd1d2Z(ed3e)ddfd4d5Z*ed/eddfd6d7Z+edDd8d9Z,ed:e-d/ede.fd;d<Z/ed:e-d=ede0fd>d?Z1dS )EIHostz
    Interface for the host.

    Provides methods for retrieving host information, managing
    connections and streams, and running the host.

    r(   c                 C   r)   )z
        Retrieve the host's peer identifier.

        Returns
        -------
        ID
            The host's peer identifier.

        Nr*   r+   r*   r*   r-   get_id  r;   zIHost.get_idc                 C   r)   )z
        Retrieve the public key of the host.

        Returns
        -------
        PublicKey
            The public key belonging to the host.

        Nr*   r+   r*   r*   r-   get_public_key  r;   zIHost.get_public_keyc                 C   r)   )z
        Retrieve the private key of the host.

        Returns
        -------
        PrivateKey
            The private key belonging to the host.

        Nr*   r+   r*   r*   r-   get_private_key  r;   zIHost.get_private_keyc                 C   r)   )z
        Retrieve the network service instance associated with the host.

        Returns
        -------
        INetworkService
            The network instance of the host.

        Nr*   r+   r*   r*   r-   get_network  r;   zIHost.get_networkr"   c                 C   r)   )z
        Retrieve the muxer instance for the host.

        Returns
        -------
        Any
            The muxer instance of the host.

        Nr*   r+   r*   r*   r-   get_mux  r;   zIHost.get_muxc                 C   r)   )a  
        Return the addresses this host advertises to other peers.

        These may differ from the actual listen addresses when
        ``announce_addrs`` is configured. Each address includes a
        ``/p2p/{peer_id}`` suffix.

        Returns
        -------
        list[Multiaddr]
            A list of advertised multiaddresses, each with a ``/p2p/{peer_id}`` suffix.

        Nr*   r+   r*   r*   r-   r   +  r;   zIHost.get_addrsc                 C   r)   )z
        Retrieve the raw multiaddr addresses this host is listening to,
        without the /p2p/{peer_id} suffix.

        Returns
        -------
        list[Multiaddr]
            A list of raw multiaddresses.

        Nr*   r+   r*   r*   r-   get_transport_addrs;  r;   zIHost.get_transport_addrsc                 C   r)   )z4
        :return: the peerstore of the host
        Nr*   r+   r*   r*   r-   get_peerstoreH  r;   zIHost.get_peerstorer   c                 C   r)   )u  
        Return the connection manager (TagStore) for this host.

        Provides access to tag_peer, untag_peer, upsert_tag, protect,
        unprotect, and is_protected without going through the network layer
        — matching go-libp2p's h.ConnManager().

        Returns
        -------
        TagStore
            The tag store managing peer priorities and protections.

        Nr*   r+   r*   r*   r-   conn_managerN  r;   zIHost.conn_managerc                 C   r)   )z
        Retrieve the identifiers of peers currently connected to the host.

        Returns
        -------
        list[ID]
            A list of peer identifiers.

        Nr*   r+   r*   r*   r-   get_connected_peers_  r;   zIHost.get_connected_peersc                 C   r)   )zH
        :return: List of peer IDs that have active connections
        Nr*   r+   r*   r*   r-   get_live_peersk  r;   zIHost.get_live_peers)task_statuslisten_addrsr   Nc                C   r)   )aL  
        Run the host and start listening on the specified multiaddresses.

        Parameters
        ----------
        listen_addrs : Sequence[Multiaddr]
            A sequence of multiaddresses on which the host should listen.
        task_status : Any
            Task status for trio nursery compatibility (ignored).

        Nr*   )r,   r   r   r*   r*   r-   runq  r;   z	IHost.runrf   r   c                 C   r)   )a   
        Set the stream handler for the specified protocol.

        Parameters
        ----------
        protocol_id : TProtocol
            The protocol identifier used on the stream.
        stream_handler : StreamHandlerFn
            The stream handler function to be set.

        Nr*   )r,   rf   r   r*   r*   r-   r     r;   zIHost.set_stream_handlerc                 C   r)   )z
        Remove the stream handler for the specified protocol.

        Parameters
        ----------
        protocol_id : TProtocol
            The protocol identifier to remove the handler for.

        Nr*   rg   r*   r*   r-   remove_stream_handler  r;   zIHost.remove_stream_handlerc                 C   r)   )zP
        Returns the recving end of the channel, used for metric events
        Nr*   r+   r*   r*   r-   get_metrics_recv_channel  r;   zIHost.get_metrics_recv_channelr   c                 C   r)   )ai  
        Return the host's event bus (INotifee-style listener fan-out).

        Modules emit typed events on the bus whenever something happens;
        any number of listeners can register to be notified (the Prometheus
        metrics exporter being one).

        Returns
        -------
        EventBus
            The host's event bus instance.

        Nr*   r+   r*   r*   r-   get_event_bus  r;   zIHost.get_event_bus	public_ipc                    rF   )zS
        Initiate the ACME-AUTO-TLS-BROKER negotiation for TLS certificate
        Nr*   )r,   r  r*   r*   r-   initiate_autotls_procedure  rH   z IHost.initiate_autotls_procedurerA   protocol_idsc                    rF   )a  
        Create a new stream to the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to connect.
        protocol_ids : Sequence[TProtocol]
            A sequence of available protocol identifiers to use for the stream.

        Returns
        -------
        INetStream
            The newly created network stream.

        Nr*   )r,   rA   r  r*   r*   r-   rk     rH   zIHost.new_streamr   c                    rF   )a0  
        Establish a connection to the specified peer.

        This method ensures there is a connection between the host and the peer
        represented by the provided peer information. It also absorbs the addresses
        from ``peer_info`` into the host's internal peerstore. If no active connection
        exists, the host will dial the peer and block until a connection is established
        or an error occurs.

        Parameters
        ----------
        peer_info : PeerInfo
            The peer information of the peer to connect to.

        Nr*   )r,   r   r*   r*   r-   connect  rH   zIHost.connectc                    rF   )z
        Disconnect from the specified peer.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to disconnect from.

        Nr*   ru   r*   r*   r-   
disconnect  rH   zIHost.disconnectc                    rF   )zN
        Close the host and all underlying connections and services.

        Nr*   r+   r*   r*   r-   rI     rH   zIHost.closer   c                    rF   )a  
        Upgrade a raw outbound connection to a fully secure and
        multiplexed network connection for the specified peer.

        Parameters
        ----------
        raw_conn : IRawConnection
            The raw (unencrypted/unmultiplexed) connection to upgrade.
        peer_id : ID
            The ID of the peer this connection is being established to.

        Returns
        -------
        INetConn
            The upgraded and authenticated network connection
            with security and multiplexing.

        Raises
        ------
        SwarmException
            If the upgrade process (security handshake or multiplexer negotiation) fails

        Nr*   r   r*   r*   r-   upgrade_outbound_connection  rH   z!IHost.upgrade_outbound_connectionr   c                    rF   )ac  
        Upgrade a raw inbound connection to a fully secure and
        multiplexed network connection for the given multiaddress.

        Parameters
        ----------
        raw_conn : IRawConnection
            The inbound raw connection to upgrade.
        maddr : Multiaddr
            The multiaddress this connection arrived on.

        Returns
        -------
        IMuxedConn
            The upgraded and authenticated inbound muxed connection.

        Raises
        ------
        SwarmException
            If the upgrade process (security handshake or multiplexer negotiation) fails

        Nr*   r   r*   r*   r-   upgrade_inbound_connection	  rH   z IHost.upgrade_inbound_connection)r(   r"   )r(   r   )r(   r   r   rP   )2r2   r3   r4   r5   r   r   r   r   r   r   r   r   r   r   r8   r   r   r   r   r   rT   r   r   r   rR   TASK_STATUS_IGNOREDr   r   r	   r   r   r   r   r   MemoryReceiveChannelr   r   rw   r  rc   rk   r   r  r  rI   r&   rj   r  r@   r  r*   r*   r*   r-   r     s    r   c                   @   sp   e Zd ZdZedefddZedefddZede	j
fddZedefd	d
ZededefddZdS )IPeerRecorda  
    Interface for a libp2p PeerRecord object.

    A PeerRecord contains metadata about a peer such as its ID, public addresses,
    and a strictly increasing sequence number for versioning.

    PeerRecords are used in signed routing Envelopes for secure peer data propagation.
    r(   c                 C   r)   )z
        Return the domain string for this record type.

        Used in envelope validation to distinguish different record types.
        Nr*   r+   r*   r*   r-   domain;	  r;   zIPeerRecord.domainc                 C   r)   )z
        Return a binary codec prefix that identifies the PeerRecord type.

        This is prepended in signed envelopes to allow type-safe decoding.
        Nr*   r+   r*   r*   r-   codecC	  r;   zIPeerRecord.codecc                 C   r)   )z
        Convert this PeerRecord into its Protobuf representation.

        :raises ValueError: if serialization fails (e.g., invalid peer ID).
        :return: A populated protobuf `PeerRecord` message.
        Nr*   r+   r*   r*   r-   to_protobufK	  r;   zIPeerRecord.to_protobufc                 C   r)   )z
        Serialize this PeerRecord into a byte string.

        Used when signing or sealing the record in an envelope.

        :raises ValueError: if protobuf serialization fails.
        :return: Byte-encoded PeerRecord.
        Nr*   r+   r*   r*   r-   marshal_recordT	  r;   zIPeerRecord.marshal_recordotherc                 C   r)   )aY  
        Compare this PeerRecord with another for equality.

        Two PeerRecords are considered equal if:
        - They have the same `peer_id`
        - Their `seq` numbers match
        - Their address lists are identical and ordered

        :param other: Object to compare with.
        :return: True if equal, False otherwise.
        Nr*   r,   r  r*   r*   r-   equal_	  r;   zIPeerRecord.equalN)r2   r3   r4   r5   r   rw   r  bytesr  pbr!   r  r  objectr6   r  r*   r*   r*   r-   r
  1	  s    	
r
  c                   @   sX   e Zd ZedefddZededdfddZedd	d
Zede	de
fddZdS )	IEnveloper(   c                 C   r)   )z
        Serialize this Envelope into its protobuf wire format.

        Converts all envelope fields into a `pb.Envelope` protobuf message
        and returns the serialized bytes.

        :return: Serialized envelope as bytes.
        Nr*   r+   r*   r*   r-   marshal_envelopep	  r;   zIEnvelope.marshal_enveloper  Nc                 C   r)   )aM  
        Verify the envelope's signature within the given domain scope.

        This ensures that the envelope has not been tampered with
        and was signed under the correct usage context.

        :param domain: Domain string that contextualizes the signature.
        :raises ValueError: If the signature is invalid.
        Nr*   )r,   r  r*   r*   r-   validate{	  r;   zIEnvelope.validater!   c                 C   r)   )a{  
        Lazily decode and return the embedded PeerRecord.

        This method unmarshals the payload bytes into a `PeerRecord` instance,
        using the registered codec to identify the type. The decoded result
        is cached for future use.

        :return: Decoded PeerRecord object.
        :raises Exception: If decoding fails or payload type is unsupported.
        Nr*   r+   r*   r*   r-   record	  r;   zIEnvelope.recordr  c                 C   r)   )ad  
        Compare this Envelope with another for structural equality.

        Two envelopes are considered equal if:
        - They have the same public key
        - The payload type and payload bytes match
        - Their signatures are identical

        :param other: Another object to compare.
        :return: True if equal, False otherwise.
        Nr*   r  r*   r*   r-   r  	  r;   zIEnvelope.equal)r(   r!   )r2   r3   r4   r   r  r  rw   r  r  r   r6   r  r*   r*   r*   r-   r  o	  s    
r  c                   @   s$  e Zd ZdZedee fddZedee ddfddZ	edee ddfd	d
Z
edee ddfddZedee dee fddZedee defddZed@ddZedee ddfddZedee fddZed@ddZedededdfddZededefddZed@d d!Zed"eddfd#d$Zedefd%d&Zed'eddfd(d)Zedefd*d+Zed@d,d-Zed.eddfd/d0Zedefd1d2Z ed@d3d4Z!ed@d5d6Z"ede#fd7d8Z$ede#fd9d:Z%ed;e#ddfd<d=Z&ede'fd>d?Z(dS )A	IPeerDataz
    Interface for managing peer data.

    Provides methods for handling protocols, addresses, metadata, and keys
    associated with a peer.
    r(   c                 C   r)   )z
        Retrieve all protocols associated with the peer.

        Returns
        -------
        list[str]
            A list of protocols associated with the peer.

        Nr*   r+   r*   r*   r-   r   	  r;   zIPeerData.get_protocolsr   Nc                 C   r)   )z
        Add one or more protocols to the peer's data.

        Parameters
        ----------
        protocols : Sequence[str]
            A sequence of protocols to add.

        Nr*   r,   r   r*   r*   r-   r   	  r;   zIPeerData.add_protocolsc                 C   r)   )z
        Set the protocols for the peer.

        Parameters
        ----------
        protocols : Sequence[str]
            A sequence of protocols to set.

        Nr*   r  r*   r*   r-   r   	  r;   zIPeerData.set_protocolsc                 C   r)   )z
        Removes the specified protocols from this peer's list of supported protocols.

        Parameters
        ----------
        protocols : Sequence[str]
            A sequence of protocol strings to be removed.

        Nr*   r  r*   r*   r-   r   	  r;   zIPeerData.remove_protocolsc                 C   r)   )a  
        Returns the list of protocols from the input sequence that are supported
        by this peer.

        Parameters
        ----------
        protocols : Sequence[str]
            A sequence of protocol strings to check against this peer's supported
            protocols.

        Returns
        -------
        list[str]
            A list of protocol strings that are supported.

        Nr*   r  r*   r*   r-   r   	  r;   zIPeerData.supports_protocolsc                 C   r)   )ad  
        Returns the first protocol from the input list that this peer supports.

        Parameters
        ----------
        protocols : Sequence[str]
            A sequence of protocol strings to check for support.

        Returns
        -------
        str
            The first matching protocol, or an empty string if none are supported.

        Nr*   r  r*   r*   r-   r   	  r;   z"IPeerData.first_supported_protocolc                 C   r)   )zE
        Clears all protocol data associated with this peer.
        Nr*   r+   r*   r*   r-   r   
  r;   zIPeerData.clear_protocol_datar|   c                 C   r)   )z
        Add multiple multiaddresses to the peer's data.

        Parameters
        ----------
        addrs : Sequence[Multiaddr]
            A sequence of multiaddresses to add.
        ttl: inr
            Time to live for the peer record

        Nr*   )r,   r|   r*   r*   r-   r~   
  r;   zIPeerData.add_addrsc                 C   r)   )z
        Retrieve all multiaddresses associated with the peer.

        Returns
        -------
        list[Multiaddr]
            A list of multiaddresses.

        Nr*   r+   r*   r*   r-   r   
  r;   zIPeerData.get_addrsc                 C   r)   )z@
        Clear all addresses associated with the peer.

        Nr*   r+   r*   r*   r-   r   "
  r;   zIPeerData.clear_addrsro   rr   c                 C   r)   )z
        Store a metadata key-value pair for the peer.

        Parameters
        ----------
        key : str
            The metadata key.
        val : MetadataValue
            The value to associate with the key.

        Nr*   )r,   ro   rr   r*   r*   r-   put_metadata)
  r;   zIPeerData.put_metadatac                 C   r)   )aO  
        Retrieve metadata for a given key.

        Parameters
        ----------
        key : str
            The metadata key.

        Returns
        -------
        MetadataValue
            The metadata value for the given key.

        Raises
        ------
        PeerDataError
            If the key is not found.

        Nr*   )r,   ro   r*   r*   r-   get_metadata7
  r;   zIPeerData.get_metadatac                 C   r)   )zH
        Clears all metadata entries associated with this peer.
        Nr*   r+   r*   r*   r-   rv   M
  r;   zIPeerData.clear_metadatar   c                 C   r)   )z
        Add a public key to the peer's data.

        Parameters
        ----------
        pubkey : PublicKey
            The public key to add.

        Nr*   )r,   r   r*   r*   r-   r   S
  r;   zIPeerData.add_pubkeyc                 C   r)   )z
        Retrieve the public key for the peer.

        Returns
        -------
        PublicKey
            The public key of the peer.

        Raises
        ------
        PeerDataError
            If the public key is not found.

        Nr*   r+   r*   r*   r-   
get_pubkey_
  r;   zIPeerData.get_pubkeyr   c                 C   r)   )z
        Add a private key to the peer's data.

        Parameters
        ----------
        privkey : PrivateKey
            The private key to add.

        Nr*   )r,   r   r*   r*   r-   r   p
  r;   zIPeerData.add_privkeyc                 C   r)   )z
        Retrieve the private key for the peer.

        Returns
        -------
        PrivateKey
            The private key of the peer.

        Raises
        ------
        PeerDataError
            If the private key is not found.

        Nr*   r+   r*   r*   r-   get_privkey|
  r;   zIPeerData.get_privkeyc                 C   r)   )z~
        Clears all cryptographic key data associated with this peer,
        including both public and private keys.
        Nr*   r+   r*   r*   r-   r   
  r;   zIPeerData.clear_keydatanew_latencyc                 C   r)   )a!  
        Records a new latency measurement using
        Exponentially Weighted Moving Average (EWMA).

        Parameters
        ----------
        new_latency : float
            The new round-trip time (RTT) latency value to incorporate
            into the EWMA calculation.

        Nr*   )r,   r  r*   r*   r-   r   
  r;   zIPeerData.record_latencyc                 C   r)   )z
        Returns the current EWMA value of the recorded latency.

        Returns
        -------
        float
            The current latency estimate based on EWMA.

        Nr*   r+   r*   r*   r-   r   
  r;   zIPeerData.latency_EWMAc                 C   r)   )zS
        Clears all latency-related metrics and resets the internal state.
        Nr*   r+   r*   r*   r-   r   
  r;   zIPeerData.clear_metricsc                 C   r)   )z4
        Updates timestamp to current time.
        Nr*   r+   r*   r*   r-   update_last_identified
  r;   z IPeerData.update_last_identifiedc                 C   r)   )z
        Fetch the last identified timestamp

        Returns
        -------
        last_identified_timestamp
            The lastIdentified time of peer.

        Nr*   r+   r*   r*   r-   get_last_identified
  r;   zIPeerData.get_last_identifiedc                 C   r)   )z
        Get ttl value for the peer for validity check

        Returns
        -------
        int
            The ttl of the peer.

        Nr*   r+   r*   r*   r-   get_ttl
  r;   zIPeerData.get_ttlrW   c                 C   r)   )z
        Set ttl value for the peer for validity check

        Parameters
        ----------
        ttl : int
            The ttl for the peer.

        Nr*   rX   r*   r*   r-   set_ttl
  r;   zIPeerData.set_ttlc                 C   r)   )z
        Check if the peer is expired based on last_identified and ttl

        Returns
        -------
        bool
            True, if last_identified + ttl > current_time

        Nr*   r+   r*   r*   r-   
is_expired
  r;   zIPeerData.is_expiredrP   ))r2   r3   r4   r5   r   r8   rw   r   r   r   r   r   r   r   r   r   r~   r   r   r   r  r  rv   r   r   r  r   r   r  r   r   r   r   r   r   r`   r!  r"  r#  r6   r$  r*   r*   r*   r-   r  	  sl    r  c                   @   s8   e Zd ZdZededdfddZedefddZdS )	IMultiselectCommunicatorz
    Communicator helper for multiselect.

    Ensures that both the client and multistream module follow the same
    multistream protocol.
    msg_strr(   Nc                    rF   )z
        Write a message to the stream.

        Parameters
        ----------
        msg_str : str
            The message string to write.

        Nr*   )r,   r&  r*   r*   r-   write
  rH   zIMultiselectCommunicator.writec                    rF   )z
        Read a message from the stream until EOF.

        Returns
        -------
        str
            The message read from the stream.

        Nr*   r+   r*   r*   r-   read  rH   zIMultiselectCommunicator.read)r2   r3   r4   r5   r   rw   r'  r(  r*   r*   r*   r-   r%  
  s    r%  c                   @   s^   e Zd ZdZededdfddZedee dedefdd	Z	eded
edefddZ
dS )IMultiselectClientz
    Client for multiselect negotiation.

    Communicates with the receiver's multiselect module to select a protocol
    for communication.
    communicatorr(   Nc                    rF   )a  
        Ensure that the client and multiselect module are using the same
        multiselect protocol.

        Parameters
        ----------
        communicator : IMultiselectCommunicator
            The communicator used for negotiating the multiselect protocol.

        Raises
        ------
        Exception
            If there is a multiselect protocol ID mismatch.

        Nr*   r,   r*  r*   r*   r-   	handshake  rH   zIMultiselectClient.handshaker   c                    rF   )a  
        Select one protocol from a sequence by communicating with the multiselect
        module.

        For each protocol in the provided sequence, the client sends a selection
        message and expects the multiselect module to confirm the protocol. The
        first confirmed protocol is returned.

        Parameters
        ----------
        protocols : Sequence[TProtocol]
            The protocols to attempt selection.
        communicator : IMultiselectCommunicator
            The communicator used for negotiating the protocol.

        Returns
        -------
        TProtocol
            The protocol selected by the multiselect module.

        Nr*   )r,   r   r*  r*   r*   r-   select_one_of,  rH   z IMultiselectClient.select_one_ofprotocolc                    rF   )a  
        Attempt to select the given protocol.

        Parameters
        ----------
        communicator : IMultiselectCommunicator
            The communicator used to interact with the counterparty.
        protocol : TProtocol
            The protocol to select.

        Returns
        -------
        TProtocol
            The protocol if successfully selected.

        Raises
        ------
        Exception
            If protocol selection fails.

        Nr*   )r,   r*  r.  r*   r*   r-   
try_selectF  rH   zIMultiselectClient.try_select)r2   r3   r4   r5   r   r%  r,  r   r   r-  r/  r*   r*   r*   r-   r)    s(    r)  c                   @   s   e Zd ZU dZeedB edB f ed< edededdfddZ	ededdfd	d
Z
edeedB df fddZededeedB edB f fddZdS )IMultiselectMuxerz
    Multiselect module for protocol negotiation.

    Responsible for responding to a multiselect client by selecting a protocol
    and its corresponding handler for communication.
    Nhandlersr.  handlerr(   c                 C   r)   )a  
        Store a handler for the specified protocol.

        Parameters
        ----------
        protocol : TProtocol
            The protocol name.
        handler : StreamHandlerFn
            The handler function associated with the protocol.

        Nr*   )r,   r.  r2  r*   r*   r-   add_handlern  r;   zIMultiselectMuxer.add_handlerc                 C   r)   )z
        Remove the handler for the specified protocol.

        Parameters
        ----------
        protocol : TProtocol
            The protocol name to remove.

        Nr*   )r,   r.  r*   r*   r-   remove_handler|  r;   z IMultiselectMuxer.remove_handler.c                 C   r)   )z
        Retrieve the protocols for which handlers have been registered.

        Returns
        -------
        tuple[TProtocol, ...]
            A tuple of registered protocol names.

        Nr*   r+   r*   r*   r-   r     r;   zIMultiselectMuxer.get_protocolsr*  c                    rF   )a  
        Negotiate a protocol selection with a multiselect client.

        Parameters
        ----------
        communicator : IMultiselectCommunicator
            The communicator used to negotiate the protocol.

        Returns
        -------
        tuple[TProtocol, StreamHandlerFn]
            A tuple containing the selected protocol and its handler.

        Raises
        ------
        Exception
            If negotiation fails.

        Nr*   r+  r*   r*   r-   	negotiate  rH   zIMultiselectMuxer.negotiate)r2   r3   r4   r5   r   r   r   r7   r   r3  r4  rm   r   r%  r5  r*   r*   r*   r-   r0  d  s   
 r0  c                   @   sJ   e Zd ZdZeddededdfddZeded	ede	e
 fd
dZdS )IContentRoutingzm
    Interface for content routing.

    Provides methods to advertise and search for content providers.
    Tcidannouncer(   Nc                 C   r)   )a  
        Advertise that the host can provide content identified by the given CID.

        If ``announce`` is True, the content is announced; otherwise, it is only
        recorded locally.

        Parameters
        ----------
        cid : bytes
            The content identifier.
        announce : bool, optional
            Whether to announce the provided content (default is True).

        Nr*   )r,   r7  r8  r*   r*   r-   provide  r;   zIContentRouting.providecountc                 C   r)   )a  
        Search for peers that can provide the content identified by the given CID.

        Parameters
        ----------
        cid : bytes
            The content identifier.
        count : int
            The maximum number of providers to return.

        Returns
        -------
        Iterable[PeerInfo]
            An iterator of PeerInfo objects for peers that provide the content.

        Nr*   )r,   r7  r:  r*   r*   r-   find_provider_iter  r;   z"IContentRouting.find_provider_iter)T)r2   r3   r4   r5   r   r  r6   r9  r`   r   r   r;  r*   r*   r*   r-   r6    s     r6  c                   @   s*   e Zd ZdZedededB fddZdS )IPeerRoutingzZ
    Interface for peer routing.

    Provides methods to search for a specific peer.
    rA   r(   Nc                    rF   )a$  
        Search for a peer with the specified peer ID.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to search for.

        Returns
        -------
        PeerInfo
            The peer information containing relevant addresses.

        Nr*   ru   r*   r*   r-   	find_peer  rH   zIPeerRouting.find_peer)r2   r3   r4   r5   r   r   r   r=  r*   r*   r*   r-   r<    s    r<  c                   @   s@   e Zd ZdZededefddZedededefddZ	d	S )
ISecureTransporta  
    Interface for a security transport.

    Used to secure connections by performing handshakes and negotiating secure
    channels between peers.

    References
    ----------
    https://github.com/libp2p/go-conn-security/blob/master/interface.go

    rC   r(   c                    rF   )a  
        Secure an inbound connection (when we are not the initiator).

        This method secures the connection by either performing local operations
        or communicating with the opposing node.

        Parameters
        ----------
        conn : IRawConnection
            The raw connection to secure.

        Returns
        -------
        ISecureConn
            The secured connection instance.

        Nr*   )r,   rC   r*   r*   r-   secure_inbound  rH   zISecureTransport.secure_inboundrA   c                    rF   )a  
        Secure an outbound connection (when we are the initiator).

        This method secures the connection by either performing local operations
        or communicating with the opposing node.

        Parameters
        ----------
        conn : IRawConnection
            The raw connection to secure.
        peer_id : ID
            The identifier of the remote peer.

        Returns
        -------
        ISecureConn
            The secured connection instance.

        Nr*   rD   r*   r*   r-   secure_outbound  rH   z ISecureTransport.secure_outboundN)
r2   r3   r4   r5   r   r&   r?   r?  r   r@  r*   r*   r*   r-   r>    s    r>  c                   @   s   e Zd ZU dZdZeed< edede	fddZ
ededefd	d
ZededefddZededefddZedee fddZdS )
ITransportzt
    Interface for a transport.

    Provides methods for dialing peers and creating listeners on a transport.

    Fprovides_native_muxingr   r(   c                    rF   )a   
        Dial a peer on the specified multiaddress.

        Parameters
        ----------
        maddr : Multiaddr
            The multiaddress of the peer to dial.

        Returns
        -------
        IRawConnection
            The raw connection established to the peer.

        Nr*   r   r*   r*   r-   dial@  rH   zITransport.dialhandler_functionc                 C   r)   )a  
        Create a listener on the transport.

        Parameters
        ----------
        handler_function : THandler
            A function that is called when a new connection is received.
            The function should accept a connection (that implements the
            connection interface) as its argument.

        Returns
        -------
        IListener
            A listener instance.

        Nr*   )r,   rD  r*   r*   r-   create_listenerQ  r;   zITransport.create_listenerc                 C   r)   )a  
        Return True if this transport can dial the given multiaddr.

        The TransportManager calls this method before attempting a dial
        to route the connection to the correct transport.

        Parameters
        ----------
        maddr : Multiaddr
            The multiaddress to check.

        Returns
        -------
        bool
            True if this transport can dial maddr, False otherwise.

        Examples
        --------
        - TCP returns True for ``/ip4/127.0.0.1/tcp/4001``
        - WebSocket returns True for ``/ip4/127.0.0.1/tcp/8080/ws``
        - QUIC returns True for ``/ip4/127.0.0.1/udp/4001/quic-v1``

        Nr*   r   r*   r*   r-   can_diald  r;   zITransport.can_dialc                 C   r)   )u  
        Return True if this transport can listen on the given multiaddr.

        Often identical to :meth:`can_dial` but may differ — e.g. a
        relay transport can dial outbound but cannot accept inbound
        connections.

        Parameters
        ----------
        maddr : Multiaddr
            The multiaddress to check.

        Returns
        -------
        bool
            True if this transport can listen on maddr, False otherwise.

        Nr*   r   r*   r*   r-   
can_listen~  r;   zITransport.can_listenc                 C   r)   )a  
        Return the list of multiaddr protocol names this transport handles.

        Used by :class:`~libp2p.transport.manager.TransportManager` as a
        fast pre-filter: if the multiaddr contains none of the listed
        protocol names, ``can_dial`` / ``can_listen`` are not called.

        Returns
        -------
        list[str]
            Protocol name strings, e.g. ``["tcp"]``, ``["ws", "wss"]``,
            or ``["quic", "quic-v1"]``.

        Nr*   r+   r*   r*   r-   r     r;   zITransport.protocolsN)r2   r3   r4   r5   rB  r6   r7   r   r   r&   rC  r   r   rE  rF  rG  r8   rw   r   r*   r*   r*   r-   rA  3  s   
 
rA  c                   @   s2   e Zd ZdZedddZedejfddZdS )	ISubscriptionAPIz}
    Interface for a subscription in pubsub.

    Combines asynchronous context management and iteration over messages.

    r(   Nc                    rF   )z6
        Unsubscribe from the current topic.

        Nr*   r+   r*   r*   r-   unsubscribe  r   zISubscriptionAPI.unsubscribec                    rF   )z
        Retrieve the next message from the subscription.

        Returns
        -------
        rpc_pb2.Message
            The next pubsub message.

        Nr*   r+   r*   r*   r-   rq        zISubscriptionAPI.getrP   )	r2   r3   r4   r5   r   rI  r$   Messagerq   r*   r*   r*   r-   rH    s    rH  c                   @   s6  e Zd ZU dZeeee f ed< eeee f ed< eee	f ed< e
ed< edee	 fddZed%ddZedede	dB ddfddZededdfddZedejdeddfddZededejddfddZededdfddZededdfdd Zdeddfd!d"Zdededdfd#d$ZdS )&IPubsubRouterz
    Interface for a pubsub router.

    Provides methods to manage protocol support, peer attachments,
    and message handling for pubsub.

    meshZfanoutZpeer_protocoldegreer(   c                 C   r)   )z
        Retrieve the list of protocols supported by the router.

        Returns
        -------
        list[TProtocol]
            A list of supported protocol identifiers.

        Nr*   r+   r*   r*   r-   r     r;   zIPubsubRouter.get_protocolspubsubr#   Nc                 C   r)   )z
        Attach the router to a newly initialized PubSub instance.

        Parameters
        ----------
        pubsub : Pubsub
            The PubSub instance to attach to.

        Nr*   )r,   rO  r*   r*   r-   attach  r;   zIPubsubRouter.attachrA   rf   c                 C   r)   )a  
        Notify the router that a new peer has connected.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer.
        protocol_id : TProtocol
            The protocol the peer supports (e.g., floodsub, gossipsub).

        Nr*   )r,   rA   rf   r*   r*   r-   add_peer  r;   zIPubsubRouter.add_peerc                 C   r)   )z
        Notify the router that a peer has disconnected.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to remove.

        Nr*   ru   r*   r*   r-   remove_peer  r;   zIPubsubRouter.remove_peerrpcsender_peer_idc                    rF   )a  
        Process an RPC message received from a peer.

        Parameters
        ----------
        rpc : rpc_pb2.RPC
            The RPC message to process.
        sender_peer_id : ID
            The identifier of the peer that sent the message.

        Nr*   )r,   rS  rT  r*   r*   r-   
handle_rpc  rH   zIPubsubRouter.handle_rpcmsg_forwarder
pubsub_msgc                    rF   )z
        Forward a validated pubsub message.

        Parameters
        ----------
        msg_forwarder : ID
            The identifier of the message sender.
        pubsub_msg : rpc_pb2.Message
            The pubsub message to forward.

        Nr*   )r,   rV  rW  r*   r*   r-   publish  rH   zIPubsubRouter.publishtopicc                    rF   )z
        Join a topic to receive and forward messages.

        Parameters
        ----------
        topic : str
            The topic to join.

        Nr*   r,   rY  r*   r*   r-   join$  rH   zIPubsubRouter.joinc                    rF   )z
        Leave a topic, stopping message forwarding for that topic.

        Parameters
        ----------
        topic : str
            The topic to leave.

        Nr*   rZ  r*   r*   r-   leave0  rH   zIPubsubRouter.leavec                    rF   )a  
        Send messages the router queued while the peer was still connecting.

        Optional hook, invoked once the outbound stream for the peer is
        registered and again when the peer announces a new subscription.
        Routers that do not queue during connection setup keep the no-op.

        Parameters
        ----------
        peer_id : ID
            The peer whose queued messages should be sent.

        Nr*   ru   r*   r*   r-   flush_pending_messages<  rH   z$IPubsubRouter.flush_pending_messagesc                    rF   )a  
        Replay recently seen messages for a topic to a peer.

        Optional hook, invoked when a peer that is subscribed to the topic
        becomes writable. Routers without a message cache keep the no-op.

        Parameters
        ----------
        peer_id : ID
            The peer to replay messages to.
        topic : str
            The topic to replay messages for.

        Nr*   )r,   rA   rY  r*   r*   r-   send_recent_messagesK  rH   z"IPubsubRouter.send_recent_messages)rO  r#   r(   N)r2   r3   r4   r5   r   rw   setr   r7   r   r`   r   r8   r   rP  rQ  rR  r$   ZRPCrU  rK  rX  r[  r\  r]  r^  r*   r*   r*   r-   rL    s0   
 rL  c                
   @   s,  e Zd ZdZeedefddZeedee	df fddZ
eedee fdd	Zed
edededdfddZed
eddfddZed#ddZededefddZededdfddZedeee B deddfddZed$dededdfdd Ze	d$dedededdfd!d"ZdS )%IPubsubz
    Interface for the pubsub system.

    Provides properties and methods to manage topics, subscriptions, and
    message publishing.
    r(   c                 C   r)   )z
        Retrieve the identifier for this pubsub instance.

        Returns
        -------
        ID
            The pubsub identifier.

        Nr*   r+   r*   r*   r-   my_idd     zIPubsub.my_id.c                 C   r)   )z
        Retrieve the protocols used by the pubsub system.

        Returns
        -------
        tuple[TProtocol, ...]
            A tuple of protocol identifiers.

        Nr*   r+   r*   r*   r-   r   r  rb  zIPubsub.protocolsc                 C   r)   )z
        Retrieve the set of topic identifiers.

        Returns
        -------
        KeysView[str]
            A view of the topic identifiers.

        Nr*   r+   r*   r*   r-   	topic_ids  rb  zIPubsub.topic_idsrY  	validatoris_async_validatorNc                 C   r)   )aB  
        Set a validator for a specific topic.

        Parameters
        ----------
        topic : str
            The topic for which to set the validator.
        validator : ValidatorFn
            The validator function.
        is_async_validator : bool
            Whether the validator is asynchronous.

        Nr*   )r,   rY  rd  re  r*   r*   r-   set_topic_validator  s   zIPubsub.set_topic_validatorc                 C   r)   )z
        Remove the validator for a specific topic.

        Parameters
        ----------
        topic : str
            The topic whose validator should be removed.

        Nr*   rZ  r*   r*   r-   remove_topic_validator  s   zIPubsub.remove_topic_validatorc                    rF   )zO
        Wait until the pubsub system is fully initialized and ready.

        Nr*   r+   r*   r*   r-   wait_until_ready  r   zIPubsub.wait_until_readytopic_idc                    rF   )a  
        Subscribe to a topic.

        Parameters
        ----------
        topic_id : str
            The identifier of the topic to subscribe to.

        Returns
        -------
        ISubscriptionAPI
            An object representing the subscription.

        Nr*   r,   ri  r*   r*   r-   	subscribe  s   zIPubsub.subscribec                    rF   )z
        Unsubscribe from a topic.

        Parameters
        ----------
        topic_id : str
            The identifier of the topic to unsubscribe from.

        Nr*   rj  r*   r*   r-   rI    rJ  zIPubsub.unsubscribedatac                    rF   )a  
        Publish a message to a topic or multiple topics.

        Parameters
        ----------
        topic_id : str | list[str]
            The identifier of the topic (str) or topics (list[str]).
        data : bytes
            The data to publish.

        Nr*   )r,   ri  rl  r*   r*   r-   rX    s   zIPubsub.publish      @rA   timeoutc                    rF   )a  
        Wait until a pubsub stream with the given peer has been established.

        This method blocks until the given peer has been added to the pubsub
        peers map, indicating that a pubsub protocol stream exists.
        Use this instead of arbitrary trio.sleep() calls to avoid race conditions.

        The implementation uses an event-based approach with :class:`trio.Event`
        so the task consumes zero CPU while waiting.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to wait for.
        timeout : float
            Maximum time to wait in seconds. Defaults to 5.0.

        Raises
        ------
        trio.TooSlowError
            If the peer stream is not established within the timeout period.

        Example::

            await connect(host1, host2)
            await pubsub1.wait_for_peer(host2.get_id())
            # Now safe to publish or check peer_topics

        Nr*   )r,   rA   rn  r*   r*   r-   wait_for_peer  s   zIPubsub.wait_for_peerc                    rF   )a  
        Wait until a specific peer has subscribed to a topic.

        This method blocks until the given peer appears in the peer_topics map
        for the specified topic, indicating that they have sent a subscription
        message. Use this instead of arbitrary trio.sleep() calls to avoid
        race conditions.

        The implementation uses an event-based approach with :class:`trio.Event`
        so the task consumes zero CPU while waiting.

        Parameters
        ----------
        peer_id : ID
            The identifier of the peer to wait for.
        topic_id : str
            The topic to check subscription for.
        timeout : float
            Maximum time to wait in seconds. Defaults to 5.0.

        Raises
        ------
        trio.TooSlowError
            If the peer does not subscribe within the timeout period.

        Example::

            await connect(host1, host2)
            await pubsub1.wait_for_subscription(host2.get_id(), "my-topic")
            # Now safe to assert subscription state

        Nr*   )r,   rA   ri  rn  r*   r*   r-   wait_for_subscription  s   $zIPubsub.wait_for_subscriptionrP   )rm  )r2   r3   r4   r5   rT   r   r   ra  rm   r   r   r   rw   rc  r   r6   rf  rg  rh  rH  rk  rI  r8   r  rX  r   ro  rp  r*   r*   r*   r-   r`  \  sX      r`  c                
   @   s`   e Zd ZdZedddZedddZedefdd	Zed
e	de
de
dee fddZdS )IPerfzv
    Interface for the perf protocol service.

    Spec: https://github.com/libp2p/specs/blob/master/perf/perf.md
    r(   Nc                    rF   )z9Start the perf service and register the protocol handler.Nr*   r+   r*   r*   r-   rG   6  r[   zIPerf.startc                    rF   )z:Stop the perf service and unregister the protocol handler.Nr*   r+   r*   r*   r-   stop;  r[   z
IPerf.stopc                 C   r)   )z*Check if the service is currently running.Nr*   r+   r*   r*   r-   
is_started@  s   zIPerf.is_startedr   
send_bytes
recv_bytesc                 C   r)   )a  
        Measure transfer performance to a remote peer.

        Parameters
        ----------
        multiaddr : Multiaddr
            The address of the remote peer to test against.
        send_bytes : int
            Number of bytes to upload to the remote peer.
        recv_bytes : int
            Number of bytes to request the remote peer to send back.

        Yields
        ------
        PerfOutput
            Progress reports during the transfer, with a final summary at the end.

        Nr*   )r,   r   rt  ru  r*   r*   r-   measure_performanceE  s   zIPerf.measure_performancerP   )r2   r3   r4   r5   r   rG   rr  r6   rs  r   r`   r   r   rv  r*   r*   r*   r-   rq  /  s$    rq  )aabcr   r   collections.abcr   r   r   r   r   
contextlibr	   dataclassesr
   typesr   typingr   r   r   r   r   r   rR   Zlibp2p.connection_typesr   libp2p.crypto.keysr   r   r   libp2p.custom_typesr   r   r   r   r   Zlibp2p.events.busr   Zlibp2p.io.abcr   r   libp2p.peer.idr   Zlibp2p.peer.pb.peer_record_pb2Zpeerr  Zpeer_record_pb2Zlibp2p.peer.peerinfor   Zlibp2p.network.tag_storer   Zlibp2p.peer.enveloper    Zlibp2p.peer.peer_recordr!   Z!libp2p.protocol_muxer.multiselectr"   libp2p.pubsub.pubsubr#   Zlibp2p.pubsub.pbr$   Zlibp2p.tools.anyio_service.apir%   r&   r9   r?   r@   rM   rc   rj   rn   rx   r   r   r   r   r   r   r   r   r   r   r   r
  r  r  r%  r)  r0  r6  r<  r>  rA  rK  rH  rL  r`  rq  r*   r*   r*   r-   <module>   s    %*k3,A-XC]4
u    "7 u  a  M>7  J$RL,;
u   T